Files
kilocode/.github/docs-sync/edit.mjs
Igor Šćekić 94de3e0eea refactor(docs-sync): declare the headless agent scope in the committed policy (#16405)
* refactor(docs-sync): declare the headless agent scope in the committed policy

Each headless pass now states its tool and path scope in configuration the CLI
enforces. agent-permissions.json holds two modes; agent-policy.mjs turns a mode
into KILO_CONFIG_CONTENT and lib.mjs applies it to every spawned run.

The gateway credentials now sit on the four steps that call the CLI, and the
checkout keeps no git credential: the fetch and push steps authenticate from
their own environment.

* fix(docs-sync): narrow the agent scope and keep attachment delivery

- `read` is allowed in both modes, because the CLI reads a `-f` attachment
  through the read tool.
- `docs-write` names every permission it needs, with a catch-all deny first.
- Edits cover the docs pages and navigation directories.
- The allowlist drops `sed`, `uniq` and `diff`, which each have a form that
  writes a file or runs a command.
- The rebuild step's comment describes the rebuild only.

* test(docs-sync): guard the command allowlist

The policy test records the allowlist the docs passes rely on, so a later edit
that changes it has to update this expectation too.

* fix(docs-sync): restrict docs edits to markdown and pin the mode tests

- The pages allow names the `.md` extension, so the Next.js app modules and API
  routes beside the docs stay out of reach.
- The mode tests compare against literal expectations instead of the map they
  read, so a new allow fails the test.
- The triage comment matches the mode it describes.

* test(docs-sync): cover sort in the allowlist guard

sort can write a file with -o and run a program with --compress-program, so the
guard that keeps such commands out of the allowlist names it too.

* test(docs-sync): drop an assertion the exact list already covers

The edit-scope test pins the exact allow list, so a second shape check could not
fail; the label and a comment now state what the list enforces.

* docs(docs-sync): describe the repair step's scope accurately

The comment on the repair step now names the paths and commands the mode
declares, so it matches agent-permissions.json.

* fix(docs-sync): require a valid agent policy before each run

Every mode is now checked as it becomes KILO_CONFIG_CONTENT: the first rule
must be the catch-all deny, and each rule and pattern must state a known
action. A mode that does not meet that requirement stops the run, so every
run carries the scope its mode declares.

The repair step builds the policy into a variable and checks it before
`kilo run`, so the pass starts only when its policy is present.

* test(docs-sync): pin the docs typecheck grant in the policy guard

* fix(docs-sync): let the mode own the emitted permission map

Each mode now supplies `permission` outright, so a run always evaluates the
rule map the mode declares, with the catch-all deny first. Provider and model
settings from the calling environment still pass through.

* fix(docs-sync): give each agent run its own step environment

- agent-policy.env() passes each pass the gateway credentials and its inputs,
  and leaves the variables a step sets for its own gh and git calls on the step.
- The edit pass prints through the same line filter as the repair step, and the
  re-verify step carries the same 10-minute build ceiling.
- The no-base config check passes an explicit empty base, so it no longer
  depends on the environment it runs in.

* fix(docs-sync): filter the agent environment by credential name

- The child environment of a kilo run keeps the caller's provider and model
  settings and drops credential-shaped names, instead of naming a fixed list.
- The gateway credentials stay, and the policy test pins a credential-shaped
  key from a step that does not exist yet.

* docs(docs-sync): state the name rule at the scope the filter applies

* fix(docs-sync): complete the read-only bash scope of the docs agent

The docs-write permission map now denies every form of an allowed inspection
command that leaves the read-only scope. A guard check pins each such deny entry
after the allow rule it qualifies, because permission evaluation takes the last
matching rule.

* fix(docs-sync): refuse an ask in a mode's rule map

A headless pass cannot answer a permission prompt, so a mode that leaves one
open fails at that tool call instead of before the model starts. Restrict the
accepted actions to allow and deny, name them in both validation messages, and
pin the rejection at a whole rule and at one pattern.

* test(docs-sync): wrap the new assertion to the file's width
2026-11-22 04:29:06 +01:00

210 lines
8.5 KiB
JavaScript

// kilocode_change - new file
/**
* Runs the LLM edit pass over docs-sync-out/worthy.json in batches.
*
* Batching bounds each `kilo run` context (a replay window can yield dozens
* of docs-worthy PRs with large diffs). Each batch gets its own CLI session
* and writes its own summary file; results are merged into
* docs-sync-out/edit-summary.json. A batch that fails or is deferred by the
* wall-clock budget is recorded as action "pending" so the watermark holds
* back and the next run re-collects those PRs.
*
* Env: EDIT_MODEL (provider/model), DOCS_SYNC_VARIANT (reasoning effort, default max),
* KILO_API_KEY + KILO_ORG_ID (set by workflow; read natively by the kilo provider).
* Budgets: EDIT_BUDGET_MINUTES (default 50), EDIT_BATCH_TIMEOUT_MINUTES (default 15).
* Test hook: DOCS_SYNC_BACKOFF_MS replaces every retry wait when set.
*/
import fs from "node:fs"
import path from "node:path"
import { fileURLToPath } from "node:url"
import { MODE } from "./agent-policy.mjs"
import { backoffMsForAttempt, deadline, remainingMs, REASONING_VARIANT, runKilo, sleepSync } from "./lib.mjs"
import { readLearningsBlock } from "./learn.mjs"
const BATCH_SIZE = 5
const ATTEMPTS = 3
const OUT_DIR = "docs-sync-out"
export const SUMMARY_FILE = ".docs-sync-summary.json"
const HERE = path.dirname(fileURLToPath(import.meta.url))
const basePrompt = fs.readFileSync(path.join(HERE, "edit-prompt.md"), "utf8") + readLearningsBlock("edit")
const model = process.env.EDIT_MODEL
if (!model) throw new Error("EDIT_MODEL is required")
const EDIT_BUDGET_MINUTES = Number(process.env.EDIT_BUDGET_MINUTES) || 50
const EDIT_BATCH_TIMEOUT_MINUTES = Number(process.env.EDIT_BATCH_TIMEOUT_MINUTES) || 15
const BATCH_TIMEOUT_MS = EDIT_BATCH_TIMEOUT_MINUTES * 60 * 1000
const worthy = JSON.parse(fs.readFileSync(`${OUT_DIR}/worthy.json`, "utf8"))
const triage = JSON.parse(fs.readFileSync(`${OUT_DIR}/triage.json`, "utf8"))
const priority = new Map(triage.map((e) => [e.url, e]))
const ordered = [...worthy].sort((a, b) => {
const rank = { high: 0, medium: 1, low: 2 }
return (rank[priority.get(a.url)?.priority] ?? 1) - (rank[priority.get(b.url)?.priority] ?? 1)
})
/** @type {Map<string, string>} url → pending cause for failed/deferred batches */
const pendingCauses = new Map()
function formatCause(result) {
const bits = []
if (result.timedOut) bits.push("timed out")
if (result.exitCode !== null && result.exitCode !== undefined) bits.push(`exit ${result.exitCode}`)
if (result.stderrTail) bits.push(result.stderrTail.replaceAll("\n", " ").slice(0, 200))
return bits.join("; ") || "no diagnostic"
}
function editBatch(batch, index, budgetDeadline) {
const batchFile = `${OUT_DIR}/edit-batch-${index}.json`
const triageFile = `${OUT_DIR}/edit-batch-triage-${index}.json`
const summaryFile = `${OUT_DIR}/edit-summary-${index}.json`
fs.writeFileSync(batchFile, JSON.stringify(batch, null, 2))
fs.writeFileSync(triageFile, JSON.stringify(batch.map((d) => priority.get(d.url)).filter(Boolean), null, 2))
const prompt = `${basePrompt}
Batch specifics for this run: the PRs to handle are in the attached ${batchFile} (full details) and ${triageFile} (triage verdicts). Handle ONLY the PRs in these batch files. When finished, write your per-PR results in the summary JSON format described above to the file \`${summaryFile}\` (path relative to the repository root).`
let lastCause = "edit pass failed"
for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {
const left = remainingMs(budgetDeadline)
if (left < BATCH_TIMEOUT_MS) {
lastCause = `edit budget exhausted before batch ${index} attempt ${attempt} (${Math.ceil(left / 1000)}s left, need ${EDIT_BATCH_TIMEOUT_MINUTES}m)`
console.warn(
`batch ${index}: stopping retries — remaining budget cannot fit another ${EDIT_BATCH_TIMEOUT_MINUTES}m attempt`,
)
break
}
// The run's tool and path scope comes from agent-permissions.json (mode
// docs-write), passed as KILO_CONFIG_CONTENT: writes under packages/kilo-docs,
// read-only inspection and the docs build and tests, everything else denied.
const result = runKilo({
mode: MODE.docsWrite,
args: [
"run",
prompt,
"-m",
model,
"--variant",
REASONING_VARIANT,
"--dir",
process.cwd(),
"-f",
batchFile,
"-f",
triageFile,
],
timeoutMs: Math.min(BATCH_TIMEOUT_MS, left),
streamStdout: true,
label: `edit batch ${index} attempt ${attempt}`,
})
if (fs.existsSync(summaryFile)) return true
// Tolerate the agent dropping the docs-sync-out/ prefix.
const alt = path.basename(summaryFile)
if (fs.existsSync(alt)) {
fs.renameSync(alt, summaryFile)
return true
}
// Exit 0 is not success: missing summary is a failure logged WITH the
// captured stderrTail and exit code on every attempt.
const cause = formatCause(result)
lastCause = `edit batch ${index}: ${cause}`
console.warn(
`batch ${index} attempt ${attempt}: summary file ${summaryFile} not produced` +
` (exit ${result.exitCode}${result.timedOut ? ", timed out" : ""})` +
(result.stderrTail ? `\nstderr tail:\n${result.stderrTail}` : "\nstderr tail: (empty)"),
)
if (attempt < ATTEMPTS) {
const wait = backoffMsForAttempt(attempt)
// Skip the wait when the remaining budget cannot fit another attempt.
const afterWait = remainingMs(budgetDeadline) - wait
if (wait > 0 && afterWait >= BATCH_TIMEOUT_MS) {
console.warn(`batch ${index}: backing off ${wait / 1000}s before attempt ${attempt + 1}`)
sleepSync(wait)
} else if (wait > 0) {
console.warn(`batch ${index}: skipping backoff — remaining budget cannot fit attempt ${attempt + 1} after wait`)
}
}
}
console.warn(`::warning::edit batch ${index} failed after up to ${ATTEMPTS} attempts; ${batch.length} PRs pending`)
for (const d of batch) pendingCauses.set(d.url, lastCause)
return false
}
const batches = []
for (let i = 0; i < ordered.length; i += BATCH_SIZE) {
batches.push(ordered.slice(i, i + BATCH_SIZE))
}
console.log(`editing docs for ${ordered.length} PRs in ${batches.length} batches of up to ${BATCH_SIZE}`)
const budgetDeadline = deadline(EDIT_BUDGET_MINUTES)
let deferredFrom = -1
for (let i = 0; i < batches.length; i++) {
const left = remainingMs(budgetDeadline)
if (left < BATCH_TIMEOUT_MS) {
deferredFrom = i
const deferredPrs = batches.slice(i).reduce((n, b) => n + b.length, 0)
console.warn(
`stopping edit pass before batch ${i}: remaining budget (${Math.ceil(left / 1000)}s) cannot fit a ${EDIT_BATCH_TIMEOUT_MINUTES}m batch; deferring ${deferredPrs} PRs`,
)
const cause = `edit budget exhausted before batch ${i} (${Math.ceil(left / 1000)}s left)`
for (let j = i; j < batches.length; j++) {
for (const d of batches[j]) pendingCauses.set(d.url, cause)
}
break
}
editBatch(batches[i], i, budgetDeadline)
}
if (deferredFrom >= 0) {
console.warn(
`edit pass deferred ${batches.slice(deferredFrom).reduce((n, b) => n + b.length, 0)} PRs due to wall-clock budget`,
)
}
// Merge batch summaries. Coverage: every worthy PR gets an entry so the PR
// body accounts for it; failed/deferred batches show up as pending (not skipped).
const merged = []
const seen = new Set()
for (let i = 0; i < batches.length; i++) {
const file = `${OUT_DIR}/edit-summary-${i}.json`
let entries = []
try {
entries = JSON.parse(fs.readFileSync(file, "utf8"))
} catch {
continue
}
for (const e of entries) {
const url = String(e?.url ?? "")
if (!url.startsWith("http") || seen.has(url)) continue
seen.add(url)
merged.push({
pr: Number(e.pr) || 0,
url,
action: String(e.action ?? "skipped"),
reason: String(e.reason ?? ""),
})
}
}
for (const d of ordered) {
if (seen.has(d.url)) continue
const cause = pendingCauses.get(d.url) || "edit pass failed or timed out for this PR"
merged.push({ pr: d.number, url: d.url, action: "pending", reason: cause })
}
// upsert-pr.mjs consumes the merged summary from the repo root; the file is
// removed there before committing so it never lands in the docs PR.
fs.writeFileSync(SUMMARY_FILE, JSON.stringify(merged, null, 2))
const changed = merged.filter((e) => e.action !== "skipped" && e.action !== "pending").length
const skipped = merged.filter((e) => e.action === "skipped").length
const pending = merged.filter((e) => e.action === "pending").length
console.log(`edit pass complete: ${changed} changed, ${skipped} skipped, ${pending} pending`)