Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(repair): a per-item invalid_params / source_changed refusal no longer stops the whole run
garrytancd2bd9d7e49b
diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex 85eca2f9e2..c3285aa038 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/commands/repair.ts` — `gbrain repair [<kind>] [--apply] [--source <id>] [--limit <n>] [--no-embed] [--json]` and `gbrain repair --all`. Kinds `timeline` (#5567 materialize), `visibility` (#5525 tighten-only backfill) `safe-chunks` (#5050/#5247 projection-only re-seal of pages of every kind below the safe-chunk fence; `--no-embed` defers embedding to `embed --stale`), `contextual-mode` (#5621 projection-only stamp of the import-time contextual retrieval mode on pages that have none; honors `--no-embed`) `connector-checkpoints` (#5686 brain-wide cleanup of connector checkpoint rows no source can load), `take-supersession` (#5886 relinks takes supersession chains from journal, stored-pointer or forced fence-structure evidence; ambiguous pages are reported with the manual edit, never rewritten; `src/core/repair/take-supersession.ts`), `orphan-bindings` (#5732 brain-wide cleanup of persistence source bindings whose source or incarnation is gone) and `embedding-effects` (#5629/#5734 settlement of stale queued and failed embedding effects: reconciled, superseded, retry_queued or blocked, reported per item in `outcomes` / `outcome_items`) and `google-file-modes` (clears group/other bits on gbrain's own files under Google source dirs outside `~/.gbrain`; filesystem only); no kind previews every kind. Dry run unless `--apply` (no prompt; `--yes` refused). `gbrain repair fences [--only <path>]... [--skip <path>]... [--slug <slug>]... [--diff] [--no-llm] [--max-usd <n>] [--apply [--expect <hash>]]` repairs malformed facts and takes fences (#6188, `src/core/repair/fences.ts`). `parseRepairArgs` is strict: any unknown option or a second positional refuses `invalid_params` before anything runs; flags a kind does not take name the kinds that do (`--only`/`--skip`/`--diff`: frontmatter, fences; `--slug`: fences; `--yes`: frontmatter); `--expect` is accepted for explicit-only and preview-bound kinds, `--include-ambiguous` for explicit-only kinds; `--max-usd <n>` and `--no-llm` only for `spends: 'llm'` kinds (a non-negative USD amount that only lowers the kind's cap), and on any other kind `--max-usd` names the capped route `gbrain doctor --remediate --yes --include-repairs --max-usd <n> --expect <plan_hash>` (hash from `doctor --remediation-plan --json`), as `--max-cost` always does. Help lines come from `REPAIR_REGISTRY`; `--json` adds `paid` per kind and `paid_kinds`. An apply with a report hook prints `repaired N; still waiting: <reason>=<count>` (never a repair count it did not make) and a partial scan; a stop prints its `fix` command and the consent it asks for. Output carries the resolved scope, affected count, a capped `source:slug` sample, residual counts, request-ID / receipt-byte / re-embedding cost (plus, for a `spends: 'llm'` kind, the paid-model estimate or spend and what is left under today's cap) and capacity, and the apply command; `--json` has the same fields. The dry run lists the kinds that may queue paid embeddings and, when a result carries `cost.llm_usd`, `Kinds that may call a paid model` with the summed estimate and the cap left. Host-only: thin clients refuse via `THIN_CLIENT_REFUSED_COMMANDS`. Logic lives in `src/core/repair/`.+- `src/commands/repair.ts` — `gbrain repair [<kind>] [--apply] [--source <id>] [--limit <n>] [--no-embed] [--json]` and `gbrain repair --all`. Kinds `timeline` (#5567 materialize), `visibility` (#5525 tighten-only backfill) `safe-chunks` (#5050/#5247 projection-only re-seal of pages of every kind below the safe-chunk fence; `--no-embed` defers embedding to `embed --stale`), `contextual-mode` (#5621 projection-only stamp of the import-time contextual retrieval mode on pages that have none; honors `--no-embed`) `connector-checkpoints` (#5686 brain-wide cleanup of connector checkpoint rows no source can load), `take-supersession` (#5886 relinks takes supersession chains from journal, stored-pointer or forced fence-structure evidence; ambiguous pages are reported with the manual edit, never rewritten; `src/core/repair/take-supersession.ts`), `orphan-bindings` (#5732 brain-wide cleanup of persistence source bindings whose source or incarnation is gone) and `embedding-effects` (#5629/#5734 settlement of stale queued and failed embedding effects: reconciled, superseded, retry_queued or blocked, reported per item in `outcomes` / `outcome_items`) and `google-file-modes` (clears group/other bits on gbrain's own files under Google source dirs outside `~/.gbrain`; filesystem only); no kind previews every kind. Dry run unless `--apply` (no prompt; `--yes` refused). `gbrain repair fences [--only <path>]... [--skip <path>]... [--slug <slug>]... [--diff] [--no-llm] [--max-usd <n>] [--apply [--expect <hash>]]` repairs malformed facts and takes fences (#6188, `src/core/repair/fences.ts`). `parseRepairArgs` is strict: any unknown option or a second positional refuses `invalid_params` before anything runs; flags a kind does not take name the kinds that do (`--only`/`--skip`/`--diff`: frontmatter, fences; `--slug`: fences; `--yes`: frontmatter); `--expect` is accepted for explicit-only and preview-bound kinds, `--include-ambiguous` for explicit-only kinds; `--max-usd <n>` and `--no-llm` only for `spends: 'llm'` kinds (a non-negative USD amount that only lowers the kind's cap), and on any other kind `--max-usd` names the capped route `gbrain doctor --remediate --yes --include-repairs --max-usd <n> --expect <plan_hash>` (hash from `doctor --remediation-plan --json`), as `--max-cost` always does. Help lines come from `REPAIR_REGISTRY`; `--json` adds `paid` per kind and `paid_kinds`. An apply with a report hook prints `repaired N; still waiting: <reason>=<count>` (never a repair count it did not make) and a partial scan; a stop prints its `fix` command and the consent it asks for. Output carries the resolved scope, affected count, a capped `source:slug` sample, residual counts, request-ID / receipt-byte / re-embedding cost (plus, for a `spends: 'llm'` kind, the paid-model estimate or spend and what is left under today's cap) and capacity, and the apply command; `--json` has the same fields. The dry run lists the kinds that may queue paid embeddings and, when a result carries `cost.llm_usd`, `Kinds that may call a paid model` with the summed estimate and the cap left. Host-only: thin clients refuse via `THIN_CLIENT_REFUSED_COMMANDS`. Logic lives in `src/core/repair/`. An item whose apply refuses `invalid_params` or `source_changed` (`REPAIR_ITEM_FAILURE_CODES` in `src/core/repair/core.ts`) is a per-item verdict: `runRepair` records it in `result.failed[]` (`item`, `source_id`, `slug`, `reason`, redacted `message`, `retry: 'next_full_scan'`) plus a `failed` outcome, writes no cursor for it and continues; a later success moves the cursor past it, so a resumed run skips it and the next full scan retries it (the `revision_conflict` rule). The command prints `failed N`, each `FAILED <item> (<reason>)` line and the full-scan command, and `repairExitVerdict` exits 1 on any failure or stop. Consumers never read failures as an all-clear: `runRepairSteps` (`RepairStepResult.failed`, status `failed`), the content lane (`ContentLaneResult.failed[]`, exit 1), and the `fence_repair` / `content_repair` phases (`warn`). Test: `test/repair-apply-continue-6459.test.ts`.- `src/commands/repair-content.ts` — `gbrain repair content [--source <id>] [--only <path>]... [--skip <path>]... [--no-llm] [--max-usd <n>] [--diff] [--apply [--expect <h1>[,<h2>]]] [--json]` (#6377): the content-repair lane as one command. `content` is parsed by `repair.ts`'s strict flag grammar like a kind (`CONTENT_LANE`; `--only`/`--skip`/`--diff`, `--no-llm`, `--max-usd` and `--expect` are accepted for it, `--slug`, `--yes`, `--include-ambiguous` and `--all` refuse) and dispatched before the kind check; it is a lane, not a `RepairKind`: no registry entry, no cursor of its own, listed under "Lanes:" in `REPAIR_HELP`. `runRepairContentCommand` resolves the scope, runs `runContentLane` and prints each kind's result through `renderRepairResult` plus a lane line (spend, allowance left, each kind's hash, every stop, the apply command); `--json` prints `{ lane, scope, mode, kinds, results[] (with `paid`), preview_hashes, cost, stopped, paid_kinds, apply_command }`. A kind's stop sets exit verdict 1; a wrong `--expect` count is `invalid_params` with the preview as its fix. Test: `test/repair-content.test.ts`.- `src/commands/reindex.ts` — `gbrain reindex --markdown [--type PAGE_TYPE] [--limit N] [--workers N] [--dry-run] [--json] [--no-embed] [--yes] [--max-usd USD] [--repo PATH]`. W4.5: re-embedding is paid, so `runReindex(engine, args, { authorized?, interactive? })` calls `requireReindexConsent` (`src/core/reindex-consent.ts`) after the dry-run return and before the managed dispatch for every caller unless `--no-embed` or `authorized` (the upgrade path's TTY yes, the job handler's stored spend record); `src/cli/commands/reindex.ts` renders the exit-3 consent refusal and `cost_cap_exceeded`. The approved finite cap runs the inline pass (and the managed dispatch) under a `BudgetTracker` via `withBudgetTracker`; once it is exhausted (an import swallows the refused embedding) the loop stops at the next page and `reportBudgetStop` exits 1 with `budget_exhausted` in `--json`. `countPending` is exported for `jobs submit reindex` and the mode-switch prompt. The writer pool is sized once from the run's page target (pending, capped by `--limit`) through `resolveWorkersWithClamp`, so Postgres runs over 100 pages default to `DEFAULT_PARALLEL_WORKERS` while PGLite stays at one; `--workers` overrides and the used count is reported as `workers` in the result and JSON (pinned by `test/e2e/reindex-auto-workers-5181.test.ts`). Walks markdown pages with stale `chunker_version` (plus unstamped contextual-retrieval mode when embedding is enabled; `--no-embed` still stamps the mode of every page it re-chunks) in 100-row id-keyset batches; a failed row cannot starve later batches in the same invocation. `--type` adds a bound-parameter `pages.type = $N` scope for focused backfills such as atom pages and is rejected by reindex modes that do not consume it. Current-version chunkless healing deliberately remains owned by the native, bounded `embed --stale` path. Rows with non-null `source_path` re-import via `importFromFile`; rows without fall back to `importFromContent`. Both paths pass `forceRechunk: true` to bypass `importFromContent`'s `content_hash` short-circuit — without it the chunker version bump never reaches pages whose source content hasn't changed, AND the stripFactsFence privacy strip never applies to chunks stored without it. Wired into `src/commands/upgrade.ts:runPostUpgrade` after `apply-migrations`. The DB-only fallback (no source file on disk) does NOT pass body-only `compiled_truth` to `importFromContent` (that path re-parses with EMPTY frontmatter and OVERWRITES the page's real frontmatter/title/timeline); it `getPage`+`getTags`, reconstructs FULL markdown via `serializeMarkdown(frontmatter, compiled_truth, timeline, {type, title, tags})`, and re-imports THAT so re-chunking a DB-only page preserves everything while bumping `chunker_version`. Pinned by `test/reindex-preserve-tags.test.ts` and `test/reindex.test.ts`. #5377: on a managed brain (`managedPersistenceEnabled`) the `--markdown` sweep delegates to the projection repairs through `runRepair` (`safe-chunks`, then `contextual-mode` unless `--no-embed`), so it never takes the legacy writer and changes no page revision, journal request or canonical file; `--type` is refused there with the repair commands, and pages the repairs cannot rebuild are reported as `unsupported_pages`. The doctor, upgrade and post-upgrade hints that name `gbrain reindex --markdown` therefore work on both brain modes (C-NEW-5).diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 487466c031..c2c8c5bd55 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -86,7 +86,13 @@ Each item is re-checked against the page's current state just before it iswritten, and the write is bound to the revision it just read, so an edit madeafter planning is kept and repaired too. An item that no longer needs therepair, or whose page changes during the write, is counted as `skipped` and-left for the next run. No kind deletes data except `stale-atoms`, which+left for the next run. An item the write refuses for its own reasons (its slug+is one the grammar no longer accepts, `invalid_params`; its file and database+copy disagree and neither is overwritten, `source_changed`) is listed in+`failed[]` with its reason and left exactly as it was, and the run goes on to+the next item. A failed item is not retried by a resumed run (a later success+moves the cursor past it); it is retried by the next full scan, which is the+printed `apply_command` once the run has completed. No kind deletes data except `stale-atoms`, whichsoft-deletes the atoms it retires, and `managed-sync-orphans`, which deletesonly sync bookkeeping rows nothing current can resume ([Managed syncorphans](#managed-sync-orphans)). Retired atoms stay recoverable through the@@ -107,11 +113,14 @@ gives each a fresh row number); it never deletes or rewrites a page.| `--only <path>`, `--skip <path>` | `frontmatter` only: select source-relative files (repeatable). The hash covers the selection, so pass the same flags to the apply. || `--diff` | `frontmatter` only: print every per-file diff instead of one sample per class (`--json` always carries all of them). || `--yes` | `frontmatter --apply` only: the user agreed to the previewed file changes (destructive consent). Without it a terminal asks, and a run without a terminal exits 3 with the consent payload. |-| `--json` | Print `{ scope, mode, results[], paid_kinds }`, one result per kind with `paid`, `affected`, `sample`, `residuals`, `cost`, `capacity`, `resumed_from`, `applied`, `skipped`, `complete`, `stopped` and `apply_command`, plus `explicit_kinds[]` when the run skipped explicit-only kinds. |+| `--json` | Print `{ scope, mode, results[], paid_kinds }`, one result per kind with `paid`, `affected`, `sample`, `residuals`, `cost`, `capacity`, `resumed_from`, `applied`, `skipped`, `failed[]` (`item`, `source_id`, `slug`, `reason`, `message`, `retry: "next_full_scan"`), `complete`, `stopped` and `apply_command`, plus `explicit_kinds[]` when the run skipped explicit-only kinds. |The command exits 1 when a run stops early (capacity, a pending write, or a-held writer). A `--limit` batch that leaves work behind exits 0, so scripts-should also check `results[].complete`.+held writer) and when any item failed (`failed[]` is not empty; `complete`+still means every pending item was attempted). A `--limit` batch that leaves+work behind exits 0, so scripts should also check `results[].complete`.+`gbrain doctor --remediate` reports a repair step with failed items as+`failed`, never `completed`.## What each kind fixesdiff --git a/src/commands/repair-content.ts b/src/commands/repair-content.tsindex a363edde52..102cf20ac0 100644--- a/src/commands/repair-content.ts+++ b/src/commands/repair-content.ts@@ -39,7 +39,7 @@ export async function runRepairContentCommand(engine: BrainEngine, args: RepairCconst paidKinds = lane.kinds.filter(kind => repairMaySpend(repairSpec(kind), args.noEmbed));if (args.json) {console.log(JSON.stringify({ lane: 'content', scope, mode: lane.mode, kinds: lane.kinds, results: lane.results.map(result => ({ ...result, paid: paidKinds.includes(result.kind) })),- preview_hashes: lane.preview_hashes, cost: lane.cost, stopped: lane.stopped, paid_kinds: paidKinds, apply_command: lane.apply_command }, null, 2));+ preview_hashes: lane.preview_hashes, cost: lane.cost, stopped: lane.stopped, failed: lane.failed, paid_kinds: paidKinds, apply_command: lane.apply_command }, null, 2));} else {console.log(`Scope: brain ${scope.brain_id}; sources ${scope.source_ids.join(', ') || '(none)'}; lane content (${lane.kinds.join(', ')})`);for (const result of lane.results) console.log(renderRepairResult(result, { diff: args.diff }));@@ -47,7 +47,8 @@ export async function runRepairContentCommand(engine: BrainEngine, args: RepairCconsole.log(`Lane: paid model ${lane.mode === 'apply' ? `$${lane.cost.llm_usd.toFixed(4)} spent` : `~$${lane.cost.llm_usd.toFixed(4)}`}`+ `${lane.cost.llm_allowance_remaining_usd === null ? '' : ` ($${lane.cost.llm_allowance_remaining_usd.toFixed(4)} left of this run's --max-usd)`}; preview hashes: ${hashes}`);for (const stop of lane.stopped) console.log(` ${stop.kind} STOPPED (${stop.reason}): ${stop.message}`);+ if (lane.failed.length) console.log(` ${lane.failed.length} item(s) refused and left unchanged (${lane.failed.map(f => `${f.kind} ${f.item}`).join(', ')}); the next full scan retries them.`);if (lane.mode === 'dry_run') console.log(` apply: ${lane.apply_command}`);}- if (lane.stopped.length) setCliExitVerdict(1);+ if (lane.stopped.length || lane.failed.length) setCliExitVerdict(1);}diff --git a/src/commands/repair.ts b/src/commands/repair.tsindex f67491e52b..eb2616abe7 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -218,7 +218,11 @@ export function renderRepairResult(result: RepairResult, opts: { diff: boolean }+ `${typeof llmLeft === 'number' ? ` ($${llmLeft.toFixed(4)} left under today's cap)` : ''}`}`);for (const c of result.capacity) lines.push(` capacity ${c.scope} ${c.resource}: ${c.used} of ${c.limit} (stops at ${c.stop_at})`);if (result.resumed_from) lines.push(` resuming after item ${result.resumed_from.phase}:${result.resumed_from.id}`);- if (result.mode === 'apply') lines.push(` applied ${result.applied}, skipped ${result.skipped}${result.complete ? ', complete' : ''}`);+ if (result.mode === 'apply') lines.push(` applied ${result.applied}, skipped ${result.skipped}, failed ${result.failed.length}${result.complete ? ', complete' : ''}`);+ for (const failed of result.mode === 'apply' ? result.failed : []) lines.push(` FAILED ${failed.item} (${failed.reason}): ${failed.message}`);+ if (result.mode === 'apply' && result.failed.length) {+ lines.push(` ${result.failed.length} item(s) left unchanged; a resumed run skips past them, the next full scan retries them: ${result.apply_command}`);+ }if (result.mode === 'apply' && result.repaired !== undefined) {const left = Object.entries(result.remaining ?? {}).map(([k, v]) => `${k}=${v}`).join(', ');lines.push(` repaired ${result.repaired}; ${left ? `still waiting: ${left}` : 'nothing left in this selection'}`);@@ -302,5 +306,10 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro}if (explicitKindsNotRun.length) console.log(`Explicit-only kinds (not run without their name; preview each): ${explicitKindsNotRun.map(n => n.preview_command).join('; ')}`);}- if (results.some(r => r.stopped)) setCliExitVerdict(1);+ if (repairExitVerdict(results) !== 0) setCliExitVerdict(1);+}++/** Exit 1 when any kind stopped early or refused an item; 0 only when every pending item was attempted and applied or skipped. */+export function repairExitVerdict(results: ReadonlyArray<Pick<RepairResult, 'stopped' | 'failed'>>): 0 | 1 {+ return results.some(r => r.stopped || r.failed.length > 0) ? 1 : 0;}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex c034a7549f..081bffb525 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -439,6 +439,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.169.0', text: '`recall` takes an optional `question` and returns saved facts ranked by relevance to it (facts below the match threshold are left out); calls without it still return the newest facts, every response now says `facts_order`, and a call that passes only `query` carries a `recall_hint` notice. `gbrain recall --question` passes the question instead of reading its value as an entity name. In `query`, the facts of an entity the question names come only from that entity page\'s own source, and the temporal fact reserve (`search.temporal_fact_reserve`, off by default) scores with the same question scorer: whole-word matches, and a long fact\'s word matches count for less.' },// Fix wave 15 (GBRA-79), doctor / repair / migrations group.{ since: '0.60.176.0', text: '`gbrain doctor --only harness_wiring` on a Postgres, `database_url` or `remote_mcp` brain now probes an HTTP registration\'s `/health` without any credential instead of reporting `http_serve_missing` unseen: a healthy gbrain answer is `wired_running` with `mcp_access: unverified` (a listener is proven, this registration\'s token and tool access are not; confirm tools in a new session), a refused local `http:` port keeps `http_serve_missing` with the `serve --http` fix, and anything else (`https:` refused, DNS or TLS errors, a timeout, a redirect, a 503 or a non-gbrain answer) is `http_serve_unreachable` / `http_serve_unhealthy` with no fix. Registered URLs are printed without userinfo, query or fragment in every doctor message and JSON (#6453).' },+ { since: '0.60.176.0', text: '`gbrain repair <kind> --apply` no longer stops the whole run when one item is refused with `invalid_params` (a slug the grammar no longer accepts) or `source_changed` (file and database copies disagree): the item is listed in `failed[]` with its reason and left exactly as it was, the remaining items are repaired, and the command exits 1. A failed item is not retried by a resumed run; the next full scan (the printed apply command once the run has completed) retries it. `gbrain doctor --remediate` reports a repair step with failed items as `failed`, never `completed`, and the content lane and maintenance phases warn on them.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cycle/content-repair.ts b/src/core/cycle/content-repair.tsindex 7d25cefcc0..09763359a0 100644--- a/src/core/cycle/content-repair.ts+++ b/src/core/cycle/content-repair.ts@@ -95,9 +95,9 @@ export async function runContentRepairPhase(engine: BrainEngine | null, opts: Coconst byKind = Object.fromEntries(lane.results.map(result => {const held = heldByReason(result);const v = result.verification as { oldest_hold_at?: string | null } | undefined;- return [result.kind, { mode: result.mode, candidates: result.affected, repaired: result.repaired ?? result.applied, outcomes: result.outcomes ?? {}, held_by_reason: held,+ return [result.kind, { mode: result.mode, candidates: result.affected, repaired: result.repaired ?? result.applied, failed: result.failed.length, outcomes: result.outcomes ?? {}, held_by_reason: held,llm_usd: result.cost.llm_usd ?? null, complete: result.complete, stopped_reason: result.stopped?.reason ?? null, oldest_hold_at: v?.oldest_hold_at ?? null }];- })) as Record<string, { mode: string; candidates: number; repaired: number; outcomes: Record<string, number>; held_by_reason: Record<string, number>; llm_usd: number | null; complete: boolean;+ })) as Record<string, { mode: string; candidates: number; repaired: number; failed: number; outcomes: Record<string, number>; held_by_reason: Record<string, number>; llm_usd: number | null; complete: boolean;stopped_reason: string | null; oldest_hold_at: string | null }>;const kindsRun = Object.values(byKind);const candidates = kindsRun.reduce((sum, k) => sum + k.candidates, 0);@@ -110,6 +110,7 @@ export async function runContentRepairPhase(engine: BrainEngine | null, opts: Coconst oldestHoldAgeHours = oldest ? Math.max(0, Math.round((now() - Date.parse(oldest)) / 3_600_000)) : null;const hardStop = lane.stopped.find(stop => stop.reason !== 'time_budget');const timeStop = lane.stopped.find(stop => stop.reason === 'time_budget');+ const failed = lane.failed.length;const usd = `$${lane.cost.llm_usd.toFixed(4)}`;const parts = [lane.mode === 'dry_run' ? `dry run: ${candidates} content candidate(s) planned across ${lane.kinds.join(', ')}, nothing written`@@ -121,16 +122,17 @@ export async function runContentRepairPhase(engine: BrainEngine | null, opts: Coconst notes = [timeStop ? `Stopped at the phase time budget (${Math.round(timeBudgetMs / 1000)} s) in ${timeStop.kind}; the next maintenance run resumes.` : '',hardStop ? `Stopped (${hardStop.kind}: ${hardStop.reason}): ${hardStop.message}` : '',+ failed ? `${failed} item(s) refused and left unchanged (first: ${lane.failed[0]!.kind} ${lane.failed[0]!.item}, ${lane.failed[0]!.reason}); the next full scan retries them.` : '',needsHuman ? `${needsHuman} wait for a person: gbrain sync status --source <id> --json names each with its paragraph.` : '',].filter(Boolean);const fix = hardStop ? hardStop.fix ?? previewFix('A lane kind stopped; the preview shows each kind\'s plan on the brain host.'): needsHuman ? previewFix('Some holds wait for a person; the preview names each with its exact next step.') : undefined;return {...base,- status: hardStop ? 'warn' : 'ok',+ status: hardStop || failed ? 'warn' : 'ok',summary: [`${parts}.`, ...notes].join(' '),details: {- mode: lane.mode, kinds: lane.kinds, candidates, repaired, held_by_reason: heldTotals, by_kind: byKind,+ mode: lane.mode, kinds: lane.kinds, candidates, repaired, failed, held_by_reason: heldTotals, by_kind: byKind,llm_usd: lane.cost.llm_usd, oldest_hold_at: oldest, oldest_hold_age_hours: oldestHoldAgeHours,complete: lane.results.every(result => result.complete), time_budget_ms: timeBudgetMs, stopped_reason: hardStop?.reason ?? timeStop?.reason ?? null,...(lane.stopped.length ? { stopped: lane.stopped } : {}), ...(fix ? { fix } : {}),diff --git a/src/core/cycle/fence-repair.ts b/src/core/cycle/fence-repair.tsindex 30fa3fec72..4f5b469b86 100644--- a/src/core/cycle/fence-repair.ts+++ b/src/core/cycle/fence-repair.ts@@ -88,6 +88,7 @@ export async function runFenceRepairPhase(engine: BrainEngine | null, opts: Fencconst llmUsdPerRepair = v?.llm_usd_per_repair ?? null;const scanPartial = v?.partial ?? result.scan?.partial ?? false;const stopped = result.stopped;+ const failed = result.failed.length;const held = Object.values(heldByReason).reduce((sum, n) => sum + n, 0);const manual = Object.entries(heldByReason).filter(([reason]) => FENCE_REASONS[reason as FenceReason]?.manualOnly).reduce((sum, [, n]) => sum + n, 0);const llmDisabled = heldByReason.llm_disabled ?? 0;@@ -104,6 +105,7 @@ export async function runFenceRepairPhase(engine: BrainEngine | null, opts: Fencconst notes = [stopped?.reason === 'time_budget' ? `Stopped at the phase time budget (${Math.round(timeBudgetMs / 1000)} s); the next maintenance run resumes.` : '',stopped && stopped.reason !== 'time_budget' ? `Stopped (${stopped.reason}): ${stopped.message}` : '',+ failed ? `${failed} item(s) refused and left unchanged (first: ${result.failed[0]!.item}, ${result.failed[0]!.reason}); the next full scan retries them.` : '',scanPartial ? 'The fence census scan is still partial; the next run continues it.' : '',llmEnabled ? '' : `Model (Tier 3) repair is off (${FENCE_REPAIR_LLM_KEY} false)${llmDisabled ? `: ${llmDisabled} fence(s) wait for it; ask the user before `+ `turning it on (\`gbrain config set ${FENCE_REPAIR_LLM_KEY} true\`, paid) or edit them by hand` : ''}.`,@@ -112,10 +114,10 @@ export async function runFenceRepairPhase(engine: BrainEngine | null, opts: Fencconst fix = stopped && stopped.reason !== 'time_budget' ? stopped.fix : manual ? previewFix('Some fences need a manual edit; the preview names each exact fix.') : undefined;return {...base,- status: stopped && stopped.reason !== 'time_budget' ? 'warn' : 'ok',+ status: (stopped && stopped.reason !== 'time_budget') || failed ? 'warn' : 'ok',summary: [`${parts}.`, ...notes].join(' '),details: {- mode: result.mode, candidates, repaired, repaired_by_tier: repairedByTier, held_by_reason: heldByReason,+ mode: result.mode, candidates, repaired, failed, repaired_by_tier: repairedByTier, held_by_reason: heldByReason,llm_enabled: llmEnabled, llm_usd: llmUsd, llm_cap_remaining_usd: result.cost.llm_cap_remaining_usd ?? null,llm_repairs: v?.llm_repairs ?? 0, llm_usd_per_repair: llmUsdPerRepair, oldest_hold_at: oldestHoldAt, oldest_hold_age_hours: oldestHoldAgeHours,scan_partial: scanPartial, complete: result.complete, time_budget_ms: timeBudgetMs, stopped_reason: stopped?.reason ?? null,diff --git a/src/core/remediation/repairs.ts b/src/core/remediation/repairs.tsindex 1c0aa6d1a2..89b344c73a 100644--- a/src/core/remediation/repairs.ts+++ b/src/core/remediation/repairs.ts@@ -57,6 +57,8 @@ export interface RepairStepResult {status: RepairStepStatus;applied: number;skipped: number;+ /** Items refused per item and left unchanged (`failed[]` of the run); any makes the step `failed`, never `completed`. */+ failed: number;message?: string;}@@ -168,7 +170,7 @@ export async function runRepairSteps(engine: BrainEngine, steps: RepairPlanStep[const runner = await repairRunner(engine, { apply: true, noEmbed: opts.noEmbed, registry: opts.registry });const results: RepairStepResult[] = [];for (const step of steps) {- const base = { id: step.id, kind: step.kind, applied: 0, skipped: 0 };+ const base = { id: step.id, kind: step.kind, applied: 0, skipped: 0, failed: 0 };let result: RepairStepResult;const remaining = opts.remainingUsd();if (step.paid && remaining !== undefined && (step.est_usd_cost === null || step.est_usd_cost > remaining)) {@@ -185,9 +187,12 @@ export async function runRepairSteps(engine: BrainEngine, steps: RepairPlanStep[const applied = llm ? await runner.run(step.kind, scope, { maxLlmUsd: opts.remainingUsd() }): step.paid && step.embeds === 'inline' && opts.stepBudget ? await opts.stepBudget(() => runner.run(step.kind, scope)) : await runner.run(step.kind, scope);if (llm) opts.charge?.(Math.max(0, (applied.cost.llm_usd ?? 0) - ((opts.spentUsd?.() ?? 0) - spentBefore)));- result = { ...base, applied: applied.applied, skipped: applied.skipped,- status: applied.stopped?.reason === 'budget_exhausted' ? 'budget_exhausted' : applied.stopped ? 'stopped' : applied.complete ? 'completed' : 'stopped',- ...(applied.stopped ? { message: applied.stopped.message } : {}) };+ const failed = applied.failed.length;+ const failedMessage = failed ? `${failed} item(s) refused and left unchanged (first: ${applied.failed[0]!.item}, ${applied.failed[0]!.reason}); `+ + `the next full scan retries them: ${applied.apply_command}` : undefined;+ result = { ...base, applied: applied.applied, skipped: applied.skipped, failed,+ status: applied.stopped?.reason === 'budget_exhausted' ? 'budget_exhausted' : applied.stopped ? 'stopped' : failed ? 'failed' : applied.complete ? 'completed' : 'stopped',+ ...(applied.stopped ? { message: failedMessage ? `${applied.stopped.message} ${failedMessage}` : applied.stopped.message } : failedMessage ? { message: failedMessage } : {}) };// A callee (for example the stale-embedding pass) may swallow BudgetExhausted; the tracker still knows.if (step.paid && step.embeds === 'inline' && opts.exhausted?.()) result = { ...result, status: 'budget_exhausted',message: 'The --max-usd budget ran out during the step; re-sealed pages keep their text, and the rest of their embeddings resume with the printed resume command or gbrain embed --stale.' };diff --git a/src/core/remediation/run.ts b/src/core/remediation/run.tsindex 776ad4c146..38fabe4e2a 100644--- a/src/core/remediation/run.ts+++ b/src/core/remediation/run.ts@@ -365,7 +365,7 @@ export async function runRemediation(}if (trackerExhausted) status = 'budget_exhausted';else if (status === 'completed' && pendingEmbedSources.length) status = 'stopped';- repairResults.push({ id: 'repair:safe-chunks:embeddings', kind: 'safe-chunks', status, applied: embedded, skipped: 0,+ repairResults.push({ id: 'repair:safe-chunks:embeddings', kind: 'safe-chunks', status, applied: embedded, skipped: 0, failed: 0,...(status === 'budget_exhausted' || status === 'budget_refused' ? { message: 'The --max-usd budget does not cover the embeddings of re-sealed pages; resume with a higher cap to continue.' }: status === 'stopped' ? { message: `Some re-sealed pages still lack embeddings (${pendingEmbedSources.join(', ')}); check the embedding provider, then run gbrain embed --stale.` } : {}) });}diff --git a/src/core/repair/content-lane.ts b/src/core/repair/content-lane.tsindex f439fe2cb8..723ef84f15 100644--- a/src/core/repair/content-lane.ts+++ b/src/core/repair/content-lane.ts@@ -39,7 +39,7 @@ import { readFix } from '../ops/op-fix.ts';import { shellQuote } from '../agent-output.ts';import { fenceHoldStatus, type FenceAutoRepair } from '../fence-repair/hold-fix.ts';import type { GitHoldRecord } from '../persistence/sync-holds.ts';-import type { RepairKind, RepairResult, RepairScope } from './core.ts';+import type { RepairFailedItem, RepairKind, RepairResult, RepairScope } from './core.ts';import { repairRunner, type RepairKindSpec } from './registry.ts';/** The lane, in run order: fences first (a merged or closed fence can change what a slug conflict's page looks like), then slug conflicts. */@@ -122,6 +122,8 @@ export interface ContentLaneResult {cost: { llm_usd: number; llm_allowance_remaining_usd: number | null };/** Every kind that stopped, with its reason (`time_budget` ends the lane; the rest let the next kind run). */stopped: Array<{ kind: RepairKind } & NonNullable<RepairResult['stopped']>>;+ /** Every item a kind refused per item and left unchanged (the kinds' `failed[]`, with the kind); the next full scan retries them. */+ failed: Array<{ kind: RepairKind } & RepairFailedItem>;/** The command that applies exactly these plans (dry run), or reruns the lane (apply). */apply_command: string;}@@ -153,6 +155,7 @@ export async function runContentLane(engine: BrainEngine, scope: RepairScope, opconst runner = await repairRunner(engine, { apply: opts.apply, noEmbed: opts.noEmbed, ...(opts.logger ? { logger: opts.logger } : {}), ...(opts.registry ? { registry: opts.registry } : {}) });const hashes: ContentLaneResult['preview_hashes'] = {};const stopped: ContentLaneResult['stopped'] = [];+ const failed: ContentLaneResult['failed'] = [];const results: RepairResult[] = [];let spent = 0;const allowance = () => opts.maxLlmUsd === undefined ? undefined : Math.max(0, opts.maxLlmUsd - spent);@@ -164,10 +167,11 @@ export async function runContentLane(engine: BrainEngine, scope: RepairScope, opspent += result.cost.llm_usd ?? 0;results.push(result);if (result.stopped) stopped.push({ kind, ...result.stopped });+ for (const item of result.failed) failed.push({ kind, ...item });if (result.stopped?.reason === 'time_budget') break;}const expect = kinds.map(kind => hashes[kind] ?? null);- return { mode: opts.apply ? 'apply' : 'dry_run', scope, kinds, results, preview_hashes: hashes, cost: { llm_usd: spent, llm_allowance_remaining_usd: allowance() ?? null }, stopped,+ return { mode: opts.apply ? 'apply' : 'dry_run', scope, kinds, results, preview_hashes: hashes, cost: { llm_usd: spent, llm_allowance_remaining_usd: allowance() ?? null }, stopped, failed,apply_command: shellQuote(contentLaneArgv({ source: opts.sourceFlag, only: opts.only, skip: opts.skip, noLlm: opts.noLlm, maxLlmUsd: opts.maxLlmUsd, apply: true,expect: expect.every((hash): hash is string => hash !== null) ? expect : undefined })) };}diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 4926fe9c9e..9211804e6e 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -11,6 +11,13 @@* a stable order and the cursor after the last committed item is stored in* `op_checkpoints` under a fingerprint of (kind, brain, sources): a rerun with* the same scope resumes after it, and a finished scan clears it.+ *+ * An item whose apply refuses `invalid_params` or `source_changed` is a+ * per-item verdict, not a run failure: it is recorded in `failed[]`, left as+ * it was, and the loop continues without a cursor write for it. A later+ * success writes a higher cursor, so a resumed run does not retry it; the next+ * full scan (a run with no stored cursor, which every completed run leaves+ * behind) does, the same way a `revision_conflict` item is retried.*/import { randomUUID } from 'node:crypto';import type { BrainEngine } from '../engine.ts';@@ -23,6 +30,7 @@ import { getWriteRequest } from '../persistence/journal.ts';import { initializeLocalPersistence, requestPrincipalForContext } from '../persistence/page-mutations.ts';import { lookupEmbeddingPrice, estimateCostFromChars } from '../embedding-pricing.ts';import { shellQuote, type Action } from '../agent-output.ts';+import { redactConnectionInfo } from '../audit/redact-connection-info.ts';import type { RepairKindSpec } from './registry.ts';export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans'] as const;@@ -114,6 +122,12 @@ export interface RepairHandler {export interface RepairItemOutcome { applied: boolean; outcome: string; reason?: string; detail?: Record<string, unknown>; llm_usd?: number;stop?: { reason: string; message: string; fix?: Action } }+/** Refusal codes that are one item's verdict: the item is recorded in `failed[]` and the run goes on. */+export const REPAIR_ITEM_FAILURE_CODES: ReadonlySet<string> = new Set(['invalid_params', 'source_changed']);++/** An item whose apply refused with a per-item code; its page, file and rows are exactly as before. The next full scan retries it. */+export interface RepairFailedItem { item: string; source_id: string; slug: string; reason: string; message: string; retry: 'next_full_scan' }+export interface RepairResult {kind: RepairKind;mode: 'dry_run' | 'apply';@@ -131,6 +145,8 @@ export interface RepairResult {resumed_from: RepairCursor | null;applied: number;skipped: number;+ /** Items refused per item (`REPAIR_ITEM_FAILURE_CODES`) and left unchanged; `complete` still means every pending item was attempted. */+ failed: RepairFailedItem[];complete: boolean;stopped?: { reason: string; message: string; fix?: Action };apply_command: string;@@ -274,7 +290,7 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, s: pending.some(item => item.llm_usd !== undefined) ? pending.reduce((sum, item) => sum + (item.llm_usd ?? 0), 0) : plan.llm.usd,llm_cap_remaining_usd: llmLeft(0) } : {}) },capacity: counters.map(({ scope: key, resource, used, limit, stop_at }) => ({ scope: key, resource, used, limit, stop_at })),- resumed_from: resumed, applied: 0, skipped: 0, complete: false, ...(plan.warnings?.length ? { warnings: plan.warnings } : {}),+ resumed_from: resumed, applied: 0, skipped: 0, failed: [], complete: false, ...(plan.warnings?.length ? { warnings: plan.warnings } : {}),apply_command: `gbrain repair ${handler.kind}${opts.sourceFlag ? ` --source ${opts.sourceFlag}` : ''}${(opts.applyArgs ?? []).map(arg => ` ${arg}`).join('')}`+ `${[...(opts.only ?? []).flatMap(path => ['--only', path]), ...(opts.skip ?? []).flatMap(path => ['--skip', path]),...(opts.slugs ?? []).flatMap(slug => ['--slug', slug])].map(arg => ` ${shellQuote([arg])}`).join('')}`@@ -344,6 +360,17 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, s} catch (error) {// A page edited since planning is left for the next full scan.if (error instanceof OperationError && error.code === 'revision_conflict') { result.skipped++; continue; }+ // A per-item refusal: recorded, nothing written, no cursor for it; the next full scan retries it (PR #6459).+ if (error instanceof OperationError && REPAIR_ITEM_FAILURE_CODES.has(error.code)) {+ const message = redactConnectionInfo(error.message);+ const failedItem = `${item.source_id}:${item.slug}`;+ result.failed.push({ item: failedItem, source_id: item.source_id, slug: item.slug, reason: error.code, message, retry: 'next_full_scan' });+ result.outcomes = { ...result.outcomes, failed: (result.outcomes?.failed ?? 0) + 1 };+ if ((result.outcome_items ??= []).length < (handler.outcomeItemsLimit ?? SAMPLE * 2)) {+ result.outcome_items.push({ item: failedItem, outcome: 'failed', reason: error.code, detail: { message } });+ }+ continue;+ }if (error instanceof OperationError && error.code === 'write_pending') {result.stopped = { reason: 'write_pending', message: `The repair of ${item.source_id}:${item.slug} was accepted and is still pending publication. `+ `Rerun \`${result.apply_command}\` to resume; the same request is replayed.` };diff --git a/src/core/repair/fences.ts b/src/core/repair/fences.tsindex e98d9809db..d437064a28 100644--- a/src/core/repair/fences.ts+++ b/src/core/repair/fences.ts@@ -562,7 +562,7 @@ async function reportFences(ctx: OperationContext, scope: RepairScope, result: Rif (outcome.outcome === 'repaired') { const tier = outcome.detail?.tier as RepairTier | undefined; if (tier) repairedByTier[tier]++; }else if (outcome.reason && outcome.reason !== 'already_clean') remaining[outcome.reason] = (remaining[outcome.reason] ?? 0) + 1;}- const unattempted = result.affected - result.applied - result.skipped;+ const unattempted = result.affected - result.applied - result.skipped - result.failed.length;if (unattempted > 0 && result.stopped) remaining[result.stopped.reason] = (remaining[result.stopped.reason] ?? 0) + unattempted;// An --expect apply replays the approved set only; re-check the selection for what the preview listed as held.if (opts.expect) for (const [reason, count] of Object.entries(await heldInScope(ctx.engine, scope, opts, result))) remaining[reason] = (remaining[reason] ?? 0) + count;diff --git a/src/core/repair/slug-conflicts.ts b/src/core/repair/slug-conflicts.tsindex 09577ca9db..c360a999ff 100644--- a/src/core/repair/slug-conflicts.ts+++ b/src/core/repair/slug-conflicts.ts@@ -634,7 +634,7 @@ async function reportConflicts(ctx: OperationContext, scope: RepairScope, resultif (outcome.outcome === 'repaired') { const tier = outcome.detail?.tier as Tier | undefined; if (tier) repairedByTier[tier]++; if (tier === 'llm') judgments++; }else if (outcome.reason && !skips.has(outcome.reason)) { remaining[outcome.reason] = (remaining[outcome.reason] ?? 0) + 1; if (outcome.detail?.tier === 'llm') judgments++; }}- const unattempted = result.affected - result.applied - result.skipped;+ const unattempted = result.affected - result.applied - result.skipped - result.failed.length;if (unattempted > 0 && result.stopped) remaining[result.stopped.reason] = (remaining[result.stopped.reason] ?? 0) + unattempted;} else if (result.affected) remaining.pending_repair = result.affected;const [oldest] = await ctx.engine.executeRaw<{ held_at: string | null }>(`SELECT min(completed_keys->0->>'held_at') AS held_at FROM op_checkpointsdiff --git a/test/repair-apply-continue-6459.test.ts b/test/repair-apply-continue-6459.test.tsnew file mode 100644index 0000000000..f9618fd682--- /dev/null+++ b/test/repair-apply-continue-6459.test.ts@@ -0,0 +1,194 @@+/**+ * `gbrain repair <kind> --apply` and a per-item refusal (PR #6459): an item+ * whose apply raises `invalid_params` (a page whose slug the grammar no longer+ * accepts) or `source_changed` (file/database drift, neither copy overwritten)+ * used to abort the whole run, and because the cursor is written only after a+ * successful item, every rerun stopped at the same item.+ *+ * Now the item is recorded in `failed[]` (and as a `failed` outcome), left+ * exactly as it was, and the loop continues. The retry story is the one+ * `revision_conflict` already has: no cursor is written for the failed item,+ * but a later success writes a higher cursor, so a resumed run does NOT retry+ * it; the next full scan (a run that starts with no stored cursor, which every+ * completed run leaves behind) does. The human output and the JSON say so,+ * `gbrain repair` exits 1, and no `RepairResult` consumer (`doctor+ * --remediate`, the content lane, the cycle phases) reads a run with failures+ * as an all-clear.+ *+ * PGLite, stub handler (projection kind: no admission, no page writes); the+ * stub keeps its own per-item store so "bytes untouched" is asserted directly.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { afterCursor, resolveRepairScope, runRepair, type RepairCursor, type RepairHandler, type RepairItem, type RepairKind, type RepairResult } from '../src/core/repair/core.ts';+import type { RepairKindSpec } from '../src/core/repair/registry.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { renderRepairResult, repairExitVerdict } from '../src/commands/repair.ts';+import { runRepairSteps, type RepairPlanStep } from '../src/core/remediation/repairs.ts';+import { runContentLane } from '../src/core/repair/content-lane.ts';++let engine: PGLiteEngine;+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => { await resetPgliteState(engine); });++const ctx = () => ({ engine, sourceId: 'default', remote: false as const, config: { engine: 'pglite', embedding_disabled: true }, dryRun: false,+ logger: { info() {}, warn() {}, error() {} } }) as never;++type Failure = { code: 'invalid_params' | 'source_changed'; message: string };++interface Stub {+ spec: RepairKindSpec;+ handler: RepairHandler;+ /** What each item holds; a repaired item is rewritten, a failed one must keep its original bytes. */+ store: Map<number, string>;+ attempts: number[];+ failures: Map<number, Failure>;+}++function stubKind(kind: RepairKind, count: number, failures: Record<number, Failure>): Stub {+ const store = new Map(Array.from({ length: count }, (_, id) => [id, `original bytes of item ${id}`]));+ const stub: Stub = { store, attempts: [], failures: new Map(Object.entries(failures).map(([k, v]) => [Number(k), v])), spec: undefined as never, handler: undefined as never };+ const item = (id: number): RepairItem => ({ cursor: { phase: 0, id }, source_id: 'default', slug: `notes/item-${id}`, chars: 10, action: 'repair' });+ stub.handler = {+ kind, publication: 'projection', embeds: false,+ async plan(_engine, _scope, after: RepairCursor | null) {+ const items = [...store.entries()].filter(([, body]) => body.startsWith('original')).map(([id]) => item(id)).filter(i => afterCursor(i.cursor, after));+ return { items, residuals: {} };+ },+ async apply(_ctx, it) {+ stub.attempts.push(it.cursor.id);+ const failure = stub.failures.get(it.cursor.id);+ if (failure) throw new OperationError(failure.code, failure.message, 'fix the page and rerun the repair');+ store.set(it.cursor.id, `repaired item ${it.cursor.id}`);+ return { applied: true, outcome: 'repaired' };+ },+ };+ stub.spec = { kind, handler: stub.handler, summary: 'stub', embeds: 'none', checks: [], consent: 'safe' } as unknown as RepairKindSpec;+ return stub;+}++const FAILURES: Record<number, Failure> = {+ 1: { code: 'invalid_params', message: "Slug 'notes/item-1' is not a valid slug any more: postgres://user:[email protected]/brain" },+ 3: { code: 'source_changed', message: 'file_database_drift: notes/item-3.md differs from the database copy; neither was overwritten' },+};++const cursorRows = () => engine.executeRaw<{ completed_keys: unknown }>("SELECT completed_keys FROM op_checkpoints WHERE op='repair'");++describe('repair --apply continues past a per-item invalid_params / source_changed refusal (PR #6459)', () => {+ test('items after a failed one are applied, failed[] names each with its reason, bytes stay untouched, and the next full scan retries them', async () => {+ const stub = stubKind('timeline', 5, FAILURES);+ const scope = await resolveRepairScope(engine);+ const result = await runRepair(ctx(), stub.handler, scope, { apply: true, spec: stub.spec });+ expect(stub.attempts).toEqual([0, 1, 2, 3, 4]);+ expect(result).toMatchObject({ applied: 3, skipped: 0, complete: true });+ expect(result.stopped).toBeUndefined();+ expect(result.failed).toEqual([+ { item: 'default:notes/item-1', source_id: 'default', slug: 'notes/item-1', reason: 'invalid_params', message: expect.stringContaining('not a valid slug'), retry: 'next_full_scan' },+ { item: 'default:notes/item-3', source_id: 'default', slug: 'notes/item-3', reason: 'source_changed', message: expect.stringContaining('file_database_drift'), retry: 'next_full_scan' },+ ]);+ expect(JSON.stringify(result)).not.toContain('secret');+ expect(result.outcomes).toEqual({ repaired: 3, failed: 2 });+ expect(result.outcome_items?.filter(o => o.outcome === 'failed').map(o => [o.item, o.reason])).toEqual([['default:notes/item-1', 'invalid_params'], ['default:notes/item-3', 'source_changed']]);+ expect(stub.store.get(1)).toBe('original bytes of item 1');+ expect(stub.store.get(3)).toBe('original bytes of item 3');+ expect([0, 2, 4].map(id => stub.store.get(id))).toEqual(['repaired item 0', 'repaired item 2', 'repaired item 4']);+ // A completed run clears its cursor: the next apply is a full scan and retries exactly the failed items.+ expect(await cursorRows()).toEqual([]);+ stub.failures.clear();+ stub.attempts.length = 0;+ const rerun = await runRepair(ctx(), stub.handler, scope, { apply: true, spec: stub.spec });+ expect(stub.attempts).toEqual([1, 3]);+ expect(rerun).toMatchObject({ applied: 2, failed: [], complete: true });+ expect(stub.store.get(1)).toBe('repaired item 1');+ });++ test('failure → later success → interruption → resume: the resumed run does not retry the failed item; the next full scan does', async () => {+ const stub = stubKind('timeline', 5, { 1: FAILURES[1]! });+ const scope = await resolveRepairScope(engine);+ let clock = 1_000;+ const now = () => clock;+ // Items 0 (ok), 1 (fails), 2 (ok) run; the deadline then stops the run before item 3.+ const originalApply = stub.handler.apply.bind(stub.handler);+ stub.handler.apply = async (c, it, o) => { const out = await originalApply(c, it, o); if (it.cursor.id === 2) clock = 10_000; return out; };+ const first = await runRepair(ctx(), stub.handler, scope, { apply: true, spec: stub.spec, deadline: 5_000, now });+ expect(stub.attempts).toEqual([0, 1, 2]);+ expect(first).toMatchObject({ applied: 2, complete: false, stopped: { reason: 'time_budget' } });+ expect(first.failed.map(f => f.slug)).toEqual(['notes/item-1']);+ expect(stub.store.get(1)).toBe('original bytes of item 1');+ // The stored cursor is after item 2 (the later success), past the failed item.+ const [row] = await cursorRows();+ expect((row!.completed_keys as Array<{ cursor: RepairCursor }>)[0]!.cursor).toEqual({ phase: 0, id: 2 });+ expect(String(first.stopped!.message)).toContain('resume');+ // Resume: items 3 and 4 only; item 1 is not retried and still reported as left for the full scan.+ stub.attempts.length = 0;+ clock = 1_000;+ const resumed = await runRepair(ctx(), stub.handler, scope, { apply: true, spec: stub.spec, deadline: 50_000, now });+ expect(stub.attempts).toEqual([3, 4]);+ expect(resumed).toMatchObject({ applied: 2, failed: [], complete: true, resumed_from: { phase: 0, id: 2 } });+ expect(stub.store.get(1)).toBe('original bytes of item 1');+ expect(await cursorRows()).toEqual([]);+ // Full scan: the failed item comes back as pending and is retried.+ stub.attempts.length = 0;+ stub.failures.clear();+ const full = await runRepair(ctx(), stub.handler, scope, { apply: true, spec: stub.spec });+ expect(stub.attempts).toEqual([1]);+ expect(full).toMatchObject({ applied: 1, complete: true, resumed_from: null });+ expect(stub.store.get(1)).toBe('repaired item 1');+ });++ test('other refusals still stop the run as before (write_pending stops; an unexpected error rethrows)', async () => {+ const stub = stubKind('timeline', 3, {});+ stub.handler.apply = async (_c, it) => {+ stub.attempts.push(it.cursor.id);+ if (it.cursor.id === 1) throw new OperationError('write_pending', 'accepted, pending publication', 'rerun');+ return { applied: true, outcome: 'repaired' };+ };+ const scope = await resolveRepairScope(engine);+ const pending = await runRepair(ctx(), stub.handler, scope, { apply: true, spec: stub.spec });+ expect(stub.attempts).toEqual([0, 1]);+ expect(pending).toMatchObject({ applied: 1, failed: [], stopped: { reason: 'write_pending' }, complete: false });+ await resetPgliteState(engine);+ const boom = stubKind('timeline', 3, {});+ boom.handler.apply = async (_c, it) => { if (it.cursor.id === 0) throw new Error('disk on fire'); return { applied: true, outcome: 'repaired' }; };+ await expect(runRepair(ctx(), boom.handler, await resolveRepairScope(engine), { apply: true, spec: boom.spec })).rejects.toThrow('disk on fire');+ });++ test('the human output counts the failures, names the slug and the full-scan command; the command exits 1', async () => {+ const stub = stubKind('timeline', 5, FAILURES);+ const result = await runRepair(ctx(), stub.handler, await resolveRepairScope(engine), { apply: true, spec: stub.spec });+ const text = renderRepairResult(result);+ expect(text).toContain('applied 3, skipped 0, failed 2, complete');+ expect(text).toContain('FAILED default:notes/item-1 (invalid_params)');+ expect(text).toContain('FAILED default:notes/item-3 (source_changed)');+ expect(text).toMatch(/left unchanged.*next full scan.*gbrain repair timeline --apply/);+ expect(text).not.toContain('secret');+ expect(repairExitVerdict([result])).toBe(1);+ expect(repairExitVerdict([{ ...result, failed: [] }])).toBe(0);+ expect(repairExitVerdict([{ ...result, failed: [], stopped: { reason: 'capacity', message: 'x' } }])).toBe(1);+ });++ test('doctor --remediate reports a step with failures as failed, never completed', async () => {+ const stub = stubKind('timeline', 5, FAILURES);+ const step: RepairPlanStep = { step: 1, id: 'repair:timeline', kind: 'timeline', affected: 5, command: 'gbrain repair timeline --apply', requires_user_agreement: true, protected: true,+ paid: false, embeds: 'none', est_usd_cost: 0, lifetime_ids: 0, checks: [], rationale: 'stub' };+ const [stepResult] = await runRepairSteps(engine, [step], { remote: false, remainingUsd: () => undefined, registry: [stub.spec] });+ expect(stepResult).toMatchObject({ kind: 'timeline', status: 'failed', applied: 3, skipped: 0, failed: 2 });+ expect(String(stepResult!.message)).toContain('notes/item-1');+ expect(String(stepResult!.message)).toContain('next full scan');+ const clean = stubKind('timeline', 2, {});+ const [ok] = await runRepairSteps(engine, [step], { remote: false, remainingUsd: () => undefined, registry: [clean.spec] });+ expect(ok).toMatchObject({ status: 'completed', applied: 2, failed: 0 });+ });++ test('the content lane carries each kind\'s failures and names them in its stopped-or-failed summary', async () => {+ const stub = stubKind('fences', 5, FAILURES);+ const lane = await runContentLane(engine, await resolveRepairScope(engine), { apply: true, kinds: ['fences'], registry: [stub.spec] });+ const [result] = lane.results as RepairResult[];+ expect(result!.failed.map(f => f.slug)).toEqual(['notes/item-1', 'notes/item-3']);+ expect(lane.failed).toEqual([{ kind: 'fences', item: 'default:notes/item-1', source_id: 'default', slug: 'notes/item-1', reason: 'invalid_params', message: expect.any(String), retry: 'next_full_scan' },+ { kind: 'fences', item: 'default:notes/item-3', source_id: 'default', slug: 'notes/item-3', reason: 'source_changed', message: expect.any(String), retry: 'next_full_scan' }]);+ expect(lane.stopped).toEqual([]);+ });+});diff --git a/test/repair-command.test.ts b/test/repair-command.test.tsindex 073eaf7d51..b4aea612f9 100644--- a/test/repair-command.test.ts+++ b/test/repair-command.test.ts@@ -180,18 +180,24 @@ describe('gbrain repair timeline', () => {});}, 120_000);- test('a terminal failure does not block the retry once its cause is fixed', async () => {+ // PR #6459: a per-item refusal (source_changed) is recorded in failed[] and the run goes on; the file is untouched and the next full scan retries it.+ test('a per-item refusal is recorded, leaves the file untouched, and does not block the retry once its cause is fixed', async () => {await brain(async (engine, [source]) => {await pageWithHistory(engine, source, 'notes/a');const [{ local_path }] = await engine.executeRaw<{ local_path: string }>('SELECT local_path FROM sources WHERE id=$1', [source]);const file = join(local_path, 'notes/a.md');const original = readFileSync(file, 'utf8');- writeFileSync(file, `${original}\nAn uncoordinated local edit.\n`);+ const edited = `${original}\nAn uncoordinated local edit.\n`;+ writeFileSync(file, edited);const scope = await resolveRepairScope(engine);- await expect(runRepair(ctxFor(engine, source), timelineRepair, scope, { apply: true })).rejects.toBeDefined();+ const refused = await runRepair(ctxFor(engine, source), timelineRepair, scope, { apply: true });+ expect(refused).toMatchObject({ applied: 0, skipped: 0, complete: true, failed: [{ item: `${source}:notes/a`, slug: 'notes/a', reason: 'source_changed', retry: 'next_full_scan' }] });+ expect(refused.stopped).toBeUndefined();+ expect(readFileSync(file, 'utf8')).toBe(edited);+ expect(await markedPages(engine, source)).toEqual([]);writeFileSync(file, original);const retried = await runRepair(ctxFor(engine, source), timelineRepair, scope, { apply: true });- expect(retried).toMatchObject({ applied: 1, complete: true });+ expect(retried).toMatchObject({ applied: 1, failed: [], complete: true });expect(await markedPages(engine, source)).toEqual(['notes/a']);});}, 120_000);