Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(repair): slug-conflict repair agrees with managed sync (#6696 C8)

garrytanb05f71f418a3
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index 82e7386f43..a0270e6d38 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -16,7 +16,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/repair/orphan-children.ts` — `gbrain repair orphan-children` (#5216, #4738), explicit-only, brain-wide, projection publication. `PAGE_CHILD_FK_TARGETS` + `orphanPredicate` (a correlated, table-qualified `NOT EXISTS`, so Postgres plans an anti-join instead of a per-row subplan once page ids outgrow work_mem; `test/e2e/repair-orphan-children-plan-postgres.test.ts`) are the single target list (doctor `child_table_orphans` in `doctor/checks/core-health.ts` imports them and names this repair instead of printing SQL). One item per (table, column); apply deletes orphans or clears the two ON DELETE SET NULL references in one rechecking statement. `probeTornPages` reads every page body in 500-row batches, row by row inside a failing batch, and the plan reports torn rows as the `torn_pages` residual plus a warning naming id/source/slug; they are never changed. The `storage_corrupt` reason in `pg-access-classify.ts` points XX000 storage errors here (`repair-orphan-children-5216.test.ts`, `pg-access-storage-corrupt-5216.test.ts`).
- `src/core/repair/fences.ts` — `gbrain repair fences` (#6188), preview-bound, `spends: 'llm'`, not explicit-only (no destructive consent). Candidates: the fence census (`listFenceCandidates` after a bounded `runFenceCensus`, `GBRAIN_FENCE_REPAIR_SCAN_MS`, default 10 s) filtered by `--only`/`--skip <path>` and `--slug <slug>`, plus files or pages the selection names that the census has not judged. Per candidate (`fence-repair/repair-io.ts` reads the current bytes): a host that may not write the source is skipped with the owner condition as its reason (`host_mismatch`, `transfer_in_progress`, `clone_in_progress`, `incarnation_changed`, `local_path_missing`, `coordination_path_missing`; `owner_unavailable` is the fallback; the skip's detail carries `why`, the read-only fix and `retryable`), a candidate a write in flight or an unfinished sync's frozen manifest still names is `sync_in_progress` (#6278: checked at plan, at apply and again at the write's admission in `file-repair.ts`; the rest of the source repairs while the sync runs, and a held path is not busy); `analyzeFences` (`repair-tiers.ts`) decides `proposal` (Tier 1 or Tier 2, validated, a fixed point, the exact diff), `llm` (only Tier 3 residuals: `fences.repair.llm`/`--no-llm` → `llm_disabled`, a page whose tags its file lacks → `canonical_overlay` before any spend, no measured model with a key and `models.fence_repair` unset → `no_measured_model`, an unpriced model under a user cap → `no_pricing`, under the default caps a warn-and-run notice naming `gbrain pricing set`, 0 caps or an estimate over `fences.repair.max_usd_per_page` → `budget_exhausted`, an attempt memo already rejected for these bytes → its stored verdict at $0) or `manual` with the exact location-only edit. The model is `resolveFenceRepairModel` (`fence-repair/model.ts`: `models.fence_repair`, else the first measured model with a key, else none). The preview saves the approved set (`previewHash` over sources, selection and each item's location, bytes hash, revision, tier and after-hash) and prints `apply_command` with `--expect`; `--apply --expect` replays it (`changed_since_preview` for moved bytes or revision), a bare `--apply` applies the current plan starting after the last candidate the previous bare run touched (`fence-repair-rotation`). Apply refuses a remote caller (`trusted_cli_required`) and runs Tier 3 through `runTier3` (ledger reservation, attempt claim, a corrective re-ask only after gate (a) or (e)); a daily-ledger refusal stops the run (`budget_exhausted`, D15: spent and cap, reset time, pages waiting, `gbrain config set fences.repair.max_usd_per_day <usd>` with consent `paid`). Outcomes `repaired` / `held` (FenceReason, also written to the hold with `recordFenceHoldRepair`) / `skipped`; `report` adds `repaired`, `remaining` by reason (an `--expect` apply re-checks the selection for what stays held) and `verification` (`FenceRepairVerification`: repaired per tier, held per reason, oldest hold, USD per Tier 3 repair). Tests: `test/repair-fences.test.ts` (PGLite and Postgres), `test/fence-repair-llm.test.ts`.
- `src/core/repair/content-lane.ts` — the content-repair lane (#6377). `CONTENT_REPAIR_KINDS` is the ordered list of repair kinds that clear managed-sync content holds (today `fences`; the GBRA-72 integration appends `slug-conflicts`), read by `gbrain repair content` (`src/commands/repair-content.ts`), the `content_repair` cycle phase and `gbrain sync unblock --apply`, so a new kind plugs in with one entry. `CONTENT_REPAIR_HOLD_KINDS` maps a hold code to the kind that clears it (`invalid_fence` → `fences`; `frontmatter_slug_conflict` → `null` until Lane B's kind lands, which keeps the surfaces' refusal text). `runContentLane(engine, scope, { apply, kinds?, only, skip, expect?, noLlm, maxLlmUsd, deadline, registry? })` has no rule logic: it runs each kind through `repairRunner` in order, passing the run's paid allowance minus what earlier kinds spent (read from each result's `cost.llm_usd`; the daily ledger is `FENCE_REPAIR_LEDGER` for every kind) and one absolute deadline (a `time_budget` stop ends the pass; any other stop lets the next kind run), and returns per-kind results, each kind's own `preview_hash` (no combined hash: `--expect` is one hash per kind in lane order, `parseContentLaneExpect` refuses a wrong count with `invalid_params` before any kind runs), the lane's spend and remaining allowance, and `apply_command` (`contentLaneArgv`). A preview plans every kind before any mutation; `--apply --expect` binds each kind to its approved set; a bare apply runs each kind's own plan-and-apply (`changed_since_read` binding, held reasons recorded on the holds). `contentHoldDisposition(record, auto)` reads a hold's stored repair state (`fenceHoldStatus` for a fence hold; `meta.content_repair.action` for a slug-conflict hold, read loosely) and says whether an unattended surface may run the kind (`repair`), must list it (`listed`: `needs_human` for a manual reason or a recommended merge, `paid`, `owner`) or has no kind for it (`unsupported`). Output is counts, codes, hashes and paths only. Tests: `test/cycle-content-repair.test.ts` (stub kinds), `test/repair-content.test.ts` (the real `fences` kind through the CLI).
-- `src/core/repair/slug-conflicts.ts` — `gbrain repair slug-conflicts` (#6377, Lane B), the lane kind that clears `frontmatter_slug_conflict` holds: preview-bound, `spends: 'llm'`, `checks: []` (doctor keeps `git_held_files` on `frontmatter`), not explicit-only. Candidates are the source's slug-conflict holds (plus `--only <path>`); identity is resolved, not textual: the frontmatter slug is normalized the way the screen does and resolved through `slug_aliases` to a page id in the same source (a slug resolving to the held file's own page is exempt; a held file with no page yet is a normal candidate). Deterministic tier (`remove_slug`, confidence high): the named slug resolves to no page and names no other file, or to a page of a different type sharing no title token; the one-line edit publishes through the frontmatter repair's coordinated path (`prepareRepairPublication` / `submitManagedFileRepair`: bytes bound to the sha256 the preview read, import, hold clear and Git effect in one write). Everything else goes to the model tier (`src/core/content-repair/judgment.ts`): `remove_slug` applies the same way, `merge_into <canonical>` and `needs_human` are recorded on the hold as codes and slugs only (`recordContentHoldRepair`, `meta.content_repair`) and rendered by `sync status` as `needs_human` paragraphs; nothing merges pages. Caps and ledger are the fence repair's (`FENCE_REPAIR_LEDGER`, `fences.repair.max_usd_per_page` / `_per_day`, `fences.repair.llm`, `--no-llm`, `--max-usd`); the receipt is a `content_repair` receipt (action, tier, confidence, model, cost, before/after sha256) carried by the write and the commit trailer `gbrain-repair: <hold_code> <tier> <confidence>`. Tests: `test/repair-slug-conflicts.test.ts`.
+- `src/core/repair/slug-conflicts.ts` — `gbrain repair slug-conflicts` (#6377, Lane B), the lane kind that clears `frontmatter_slug_conflict` holds: preview-bound, `spends: 'llm'`, `checks: []` (doctor keeps `git_held_files` on `frontmatter`), not explicit-only. Candidates are the source's slug-conflict holds (plus `--only <path>`); identity is resolved, not textual: the frontmatter slug is normalized the way the screen does and resolved through `slug_aliases` to a page id in the same source (a slug resolving to the held file's own page is exempt; a held file with no page yet is a normal candidate). Deterministic tier (`remove_slug`, confidence high): the named slug resolves to no page and names no other file, or to a page of a different type sharing no title token; the one-line edit publishes through the frontmatter repair's coordinated path (`prepareRepairPublication` / `submitManagedFileRepair`: bytes bound to the sha256 the preview read, import, hold clear and Git effect in one write). Every verdict uses managed sync's own screen (`sync-screen.ts` `loadSyncScreenRun` + `frozenImportScreenInput` + `screenFrozenContent`, on the file's bytes and on the edited bytes): a held file the screen now admits as it is (its line is clean, or names the file's own page as written) is planned as `import` and published unchanged through `submitManagedFileRepair` with an `import` receipt and `holdObservedAt` (the hold observation the plan read; a newer hold is kept and the hold records a `changed_since_read` retry); a file sync would hold whatever the lane writes (the page it is filed as carries another slug than its path, or the line reaches the own page only through an alias) is held `slug_page_mismatch` with both slugs (`named` on the hold). Everything else goes to the model tier (`src/core/content-repair/judgment.ts`): `remove_slug` applies the same way, `merge_into <canonical>` and `needs_human` are recorded on the hold as codes and slugs only (`recordContentHoldRepair`, `meta.content_repair`) and rendered by `sync status` as `needs_human` paragraphs; nothing merges pages. Caps and ledger are the fence repair's (`FENCE_REPAIR_LEDGER`, `fences.repair.max_usd_per_page` / `_per_day`, `fences.repair.llm`, `--no-llm`, `--max-usd`); the receipt is a `content_repair` receipt (action, tier, confidence, model, cost, before/after sha256) carried by the write and the commit trailer `gbrain-repair: <hold_code> <tier> <confidence>`. Tests: `test/repair-slug-conflicts.test.ts`, `test/repair-slug-conflicts-sync-screen.test.ts`.
- `src/core/repair/frontmatter.ts` — `gbrain repair frontmatter` (#5988), explicit-only, preview-bound, destructive consent (`--yes` with the hash, registry `consent`). #5966 (W14 P1.7): the slug rule itself is `slugStampedFrontmatter(slug, fm)` in `src/core/markdown.ts` (stamps `slug:` when the path cannot derive it, such as a doubled hyphen, and replaces a foreign `fm.slug`; used by `serializePageToMarkdown` and `commands/export.ts`, digest-neutral since `parseMarkdown` drops `fm.slug`); `slugStampCandidate` proposes a SAFE `slug:` stamp for a well-formed file at a page's recorded `source_path` whose path derives another slug and that declares none (a legacy render of a slug the path cannot derive), inserted as `serializeMarkdown` writes it; never normalizes or guesses. Scope: Git-visible `.md`/`.mdx` per source (managed owner root or legacy `local_path`) plus every Git hold row; database side, pages whose body begins with an embedded frontmatter block or whose title is the humanized slug while the file names one. `frontmatterCandidates` builds a safe rewrite (NUL strip, nested-quote swap, `repairRecoverableFrontmatter` quoting; parsed values must be unchanged) and an interpretive one (`autoFixFrontmatter` missing close / slug line, fold, dup, unclosed, `#` rescue); both must strict-parse with no hold. `prepareRepairPublication` binds each proposal to the page fields its import would store; a refusal or canonical overlay is `needs_review`. The hash covers sources, `include_ambiguous`, `--only`/`--skip`, and per file before/after sha256, page id/revision, result digest and `rename_from`; the approved set stores no frontmatter text. An `invalid_fence` hold is listed with a resolution that defers to `gbrain repair fences --source <id> --only <path>` (frontmatter repair never changes fences). Apply refuses while an unfinished managed sync cursor names a selected path, re-derives each change, then publishes through `managed_file_repair` (managed) or backup, write, `importFromFile`, hold clear and a printed commit step (legacy). Tests: `test/repair-frontmatter.test.ts`.
- `src/core/persistence/mirror-read-only.ts` and `src/commands/sources-mirror.ts` — #5409 read-only mirror sources. `sourceMirrorReadOnly(engine, sourceId)` reads `sources.config.mirror_read_only` (default false). When true, `prepareFileTarget` (`page-prepare.ts`) returns no file for any coordinated page write into the source (receipt `write_through.skipped: 'mirror_read_only'`, `storage: 'database_only'`, set in `coordinator.ts`), and managed sync (`sync-prepare.ts`) imports an overlay (canonical form differs from the file bytes) database-only: no `file`, no newer-working-tree refusal, and `contentUnchanged` ignores the overlay. A page created that way with no recorded file is stamped `pages.database_only_reason='mirror_read_only'` (`classifyMirrorPage`, in the publication) and stays database-only after the flag is cleared; the coordinator refuses (`source_changed`) a file target prepared before the flag was set (rechecked under the publication with the source row `FOR SHARE`); `gitPage` (`effects.ts`) completes a mirror source's Git effects as skipped. `gbrain sources mirror-readonly|mirror-writable <id>` set and clear the key like `federate`/`unfederate`; `sources list --json` reports `mirror_read_only`.
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index 135d3fc00a..12ac2d22ab 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -16,8 +16,8 @@
- **`src/core/persistence/sync-window.ts`** — #5984 admit-ahead for draining managed Postgres syncs. While the cursor's `group` publishes, `admitAhead` (`sync-run.ts`) freezes and admits the next group and records it in the cursor's `window` (at most one group), so the consumer claims it as soon as the publishing group commits under the unchanged per-worktree FIFO claim. Window members name the previous group's last request in `intent.after`. `cancelOrphanedWindowGroup` runs before the consumer prepares a claimed group: a window group whose predecessor did not commit is cancelled (`WINDOW_CANCEL_MESSAGE`), never published after a failed page. Publication validation (`sync-prepare.ts`) re-checks the predecessor once per transaction and reads the cursor `FOR KEY SHARE`, accepting `pending`, `group` and `window` members, so the drain's cursor saves never wait for the publishing group. After a failed page the drain cancels the window's queued members (`cancelWindow`) and drops the window; resume re-freezes those entries. Nothing is admitted ahead while foreground writes are recent (one was queued on the worktree in the last minute, `FOREGROUND_RECENT_MS`) or when the next entry is not groupable. Older binaries refuse a window member they did not admit (cursor membership), so a mixed-version drain fails closed instead of publishing twice; finish a drain before downgrading. A claimed head is ordered by `claimedPredecessorState`: a group member follows the member before it in its own group (its `after` names only the previous group), anything else follows `after`. `claimedHeadOrder` (the consumer, before claiming followers) cancels a head whose predecessor ended without committing, and under lanes a member whose predecessor is unfinished releases its claim and waits; `cancelOrphanedLaneRows` uses the same rule, so a member released mid-group (its group fell back to the single path and an earlier member went back to the queue) never publishes after that member fails. Test: `test/sync-group-member-order.test.ts`. #6402: a group head whose window predecessor was not admitted is cancelled naming it.
- **`src/core/persistence/sync-lanes.ts`** + **`worktree-lease.ts`** — #5984 lanes. The drain opens a lane policy for its worktree (`openLanes`, keyed by a per-drain run id that lane groups carry as `intent.lane`; `closeLaneRun` at drain end stops new lane claims and waits up to 90 s for the lane tasks still running, counted from the head's claim by `laneTask`; the drain then cancels its run's still-queued rows whose predecessor ended without committing, `cancelOrphanedLaneRows` in sync-window.ts, so a blocked drain never reports while one of its groups is still publishing, aborting or released). While it is open, this process's consumer claims the next admitted lane group head out of FIFO order (`claimNextLaneHead` in journal.ts: every earlier request claimed, any unfinished one a running request of the same run) up to the effective lane count (`laneRoots`), and runs it as a lane (`executeClaimedGroup` with `lane`). Lane publications share the worktree's native lock in this process (`acquireWorktreeShared` / `worktree-lease.ts`; one lane acquires the lock while lanes arriving meanwhile wait and join, and a lease stays registered until its lock is released); every exclusive `acquireWorktree` first yields the lease (marks it draining and wounded, waits up to its budget), and a lease drains for new claims after `LEASE_TURN_MS` of continuous holding. Lane transactions begin in manifest order (`awaitLaneBegin`) and commit in manifest order (`awaitLaneTurn`, inside the transaction before the counters: the predecessor `intent.after` must be committed; a failed one cancels the group, a requeued or unadmitted one releases it, a wounded lease or 60 s rolls it back). Publication validation accepts a lane group whose predecessor is still queued or running (`windowPredecessorAllows`). `laneFallback` in group-publish.ts cancels, releases or falls back to the single path, and a lock or statement timeout steps the lane count down (`stepDownLanes`). Lane settings (`--lanes`/`--no-lanes` > `GBRAIN_SYNC_LANES` > `sync.lanes` > 6, clamped to the pool's long-hold capacity minus 3) resolve in `resolveBulkSettings` (sync-group.ts); with lanes the drain keeps twice the lane count of groups admitted ahead (`admitAhead`).
- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. A completed discovery that finds nothing to do (`up_to_date`) stamps only `sources.last_sync_at`, inside `withCoordinatedWrite` and guarded by source id and incarnation, so a quiet managed source stays fresh in doctor and a run that outlived a re-added source stamps nothing; dry runs and partial runs do not stamp. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. A resume adopts the stored options for every option the caller did not set explicitly (`SyncOpts.explicitProcessing`: CLI flags, wire flags, job params; autopilot and the cycle set none); an explicit conflict refuses with `detail: cursor_processing_options_conflict`, the stored options and the exact resume command. Callers that omit `explicitProcessing` stay strict. Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts, also when the run has a recorded failure and its pending write already committed before the cursor advanced; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. #5522: a new-file entry (`pageId: null`) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them into `legacySkips` (printed by `sync-diagnostics.ts` with `gbrain repair contextual-mode`). A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. Content holds (#5988, `sync-screen.ts`): `freezeEntry` screens each import (company-profile cursors and `sync.holds=fail` excepted); a refused file becomes a hold written in the same transaction as the cursor step (`saveCursor`'s `inTx`), with no request admitted, and an over-bound pinned blob is held by size before it is read. A cursor whose pending request failed with a content refusal (`isContentRefusal`, old message shapes included) converts in place with its stored options: held, or re-frozen once per distinct bytes (`converted`), so a refusal the screen misses stays blocked without minting receipts. #6188: a failed fence refusal (`fenceReceiptLocation`: the durable `error_detail.fence`, the message, or an older release's message) holds the same bytes even when the screen admits them (`prepareTimeFenceHold`, reason `prepare_time`); a compacted `invalid_params` / `take_row_collision` receipt converts only when the re-screen holds. A page request of the run that fails with a fence refusal is held in the same invocation at the terminal-failure branch (single path and a bulk group's failed member) after the source's other requests settle within the run's wait budget, else the run returns `partial`; it is converted once, gets no failure-ledger row and is logged as a conversion. `sync.holds=fail` and company-profile cursors keep blocking with the typed refusal. #6278: a `preparation_stalled` receipt (the owner gave up preparing a member) is converted the same way by both converters: an import holds by its bytes, a delete as a delete hold (`meta.deleted`, `upstream_version` null), the checkpoint never holds; `preparationStalledHold` (sync-screen.ts) records the receipt's step and the resume arguments. Both converters write their hold through `holdUnderGate`, the narrowed gate: the failed entry's admitted suffix (window, later group members, this run's queued lane rows) is cancelled first, then the hold waits only for active suffix descendants and unfinished requests naming the entry's page (`UNFINISHED_PAGE_REQUEST_SQL`, now matching path and origin too), evaluated inside the transaction that writes the hold under the page-key → cursor lock order; its doc comment states the invariant the old source-wide wait protected. The cursor's `breaker` counts the run's stalled receipts (identities and streak, saved with each CAS): `holdsEscalated`'s rule over the run's screened imports or `BREAKER_STREAK` (5) in a row trips it, the run stops `blocked_by_failures` with `SyncResult.breaker` (drain `preparation_systemic`), and the next run's `convertBlockedCursor` re-freezes the entry and schedules the run's stalled holds for a re-screen instead of holding; a committed page resets the streak. `sameContentAtOrigin` and the waiver screens race the sync preparer against `persistence.sync_preparation_ms` (`raceSyncBudget`, sync-waivers.ts) and fail open. Tests: `test/managed-sync-preparation-stalled-holds.test.ts`, `test/sync-waiver-budget.test.ts`. Results carry this run's holds, the outstanding total, escalation, `converted_from_failed` and `recovered_frontmatter` (`buildHoldReport`); dry runs list `would_hold` / `screen_skipped`. After the checkpoint commits (and unless `noExtract`), the owner derives links for the source's stale pages through `links-maintenance.ts`, so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync. #6278 (B7): when the checkpoint commits while `sources retry-held` re-screens are scheduled for the source (scheduled against a backlog, or while this cursor ran), the pass returns `partial` / `writer_yield` instead of `synced`, so the drain's next pass retires the finished cursor and discovers again, taking them; a `queue_capacity` refused for outstanding requests (`isWriteCapacityWait`) is left out of the failure ledger because the drain waits it out.
-- **`src/core/persistence/sync-holds.ts`** + **`sync-screen.ts`** + **`sync-blobs.ts`** — Git holds (#5988). One `op_checkpoints` row per held file (`sync-hold`, fingerprint `source:incarnation:path`) plus a per-source `sync-hold-summary` row (`count`, and `stale`: holds whose page exists); `writeGitHold` / `clearGitHold` lock the summary row and are conditional on the writing run's discovery time (`observed_at`), so an older run never replaces or clears a newer hold. Managed and legacy sync write the same rows; `readGitSourceHolds` (current incarnation only) feeds `retry-held` and legacy sync, and `readGitHoldListing` (count from the summary row, rows limited per source in SQL) feeds `sources status`, never `readAllSourceHolds`. `recordSyncConversion` logs each blocked request a managed run converted in place (`sync-conversions`, newest 20 per source, in the transaction that saves the converted cursor); `sources status` shows the newest 5. `gitHoldItem` gives every surface code, reason, key, line, location-only message, `fix` Action and `docs` anchor. #6188 `invalid_fence` holds carry `meta.fence` (reason, fence, section, rows, columns, section line), the file line of the first bad row (`meta.line`, from `fenceFileLine` when the screen holds it), `fence_version` and the last repair attempt (`fence_repair`); the summary row counts them (`fences`), and `holdRepairSteps` is the one router (D6) every surface prints: fence and slug-conflict holds (`HoldRepairRoute.fences` + `slug_conflicts`) preview the content-repair lane, `gbrain repair content --source <id>` (`contentRepairArgv`, #6377; the text says the next maintenance run repairs the fence and slug-conflict holds it can by itself when `FenceAutoRepair.active`), other holds preview `gbrain repair frontmatter`, a mixed source names both; one fence hold's own fix stays that file's `gbrain repair fences --only <path>` preview (`fenceHoldFix`). One fence hold's fix (`gitHoldFix` → `fence-repair/hold-fix.ts` `fenceHoldFix`) is that file's `--only <path>` preview with the step its state calls for, and `gitHoldItem` carries the D16 `fence` object (classes, tier, `auto_retry`, `next_attempt_after`); callers that can read the maintenance state pass it (`fenceAutoRepairFor`). `holdRescreenDue` is the one re-screen predicate managed discovery and legacy sync share (retry request, database-dependent codes, an older frontmatter reader or fence screen). Policy keys: `sync.holds` (`hold`/`fail`), `sync.hold_cap` (detail shown, default 500), `sync.hold_escalate_count` (50), `sync.hold_escalate_pct` (5, from 40 screened imports), `sync.parser_regression` (`stop`/`hold`). #6278: `preparation_stalled` holds carry `meta.stall` (request, step, `waiting_on`, attempts, the writing gbrain version, the sync's resume arguments) and count under `stalled` in the summary row and `HoldRepairRoute`; `gitHoldFix` routes them to `gbrain sources writer status --source <id> --json`, then `sources retry-held`, then the option-preserving sync (`stalledHoldSteps`), never to frontmatter repair, and `holdRescreenDue` re-screens them on a gbrain version change; `buildHoldReport` routes the escalation text by code. `screenFrozenImport` admits a fence Tier 1 fixes (`fences.normalize`, read once per run only when needed; the dry run lists it in `would_normalize`), turns a refusal into a hold, or throws `sync_parser_regression` only when `sync-import-provenance` proves a validating gbrain imported the same bytes. `sync-blobs.ts` reads blob ids/sizes with chunked `ls-tree -l` and contents with `cat-file --batch`; `freezeEntry` reads each entry's pinned blob and content through `readPinnedBlob` / `readPinnedContent` (via `sync-screen.ts` `pinnedBlob` / `pinnedContent`): a miss lists that entry and up to 255 of the next committed imports in one `ls-tree` and loads their contents (8 MiB slices cut by window position, not read order; over-bound blobs excluded) in one `cat-file --batch`, kept per (Git root, full commit id) until the next window, so a managed first sync spawns a few Git processes per window instead of an `ls-tree` and a `git show` per page; a non-commit target, a window git refuses to list, or a blob the window cannot answer falls back to the per-entry read (`__setPinnedWindowForTests(0)` restores per-entry reads; `test/managed-sync-pinned-reads.test.ts` proves identical rows on PGLite and Postgres). `held-reads.ts` is the read side: `get_page.file_held`, `stale` on search/query hits and the `held_files` retrieval meta and notice, from one lookup by page id (`op_checkpoints_sync_hold_page_idx`, migration v200) and one summary read per call, cached per request; `stalled` coverage routes a `preparation_stalled` hold to the host operator's writer-status fix instead of a file repair; remote callers get codes and counts, never paths, and a fix addressed to the brain host operator (a held fence page gets `fenceHoldRelay`: the owner-host command and whether it clears by itself). Tests: `test/sync-holds-store.test.ts`, `test/persistence-sync-holds.test.ts`, `test/sync-all-hold-notes.test.ts`, `test/held-read-signals.test.ts`. #5493/#6529: managed discovery admits image imports whenever multimodal embedding is on (company plans refuse). Off, `freezeEntry` holds each image import as `managed_image_sync_unsupported` (`managedImageHold`, dry-run screen too) before any content read, whatever `sync.holds` says: the rest of the source imports, the hold is keyed by the pinned blob (or working bytes), and `holdRescreenDue` re-screens it on change, removal, multimodal on or `sources retry-held`. On, `freezeEntry` freezes the bytes as base64 (`pinnedImageBytes`, `frozenImageIntent`), an oversize image takes `oversizeHold`, identical bytes are a no-op by hash, and `sync-prepare.ts` routes the entry to `sync-image.ts`. The summary row counts `images`; those holds never count toward `holds_escalated` or `git_held_files`.
-- **`src/core/persistence/file-repair.ts`** — `managed_file_repair` (#5988), the owner-internal `put_page` kind `gbrain repair frontmatter --apply` submits (accepted only from the trusted local CLI with `managedFileImport`; MCP is refused by the reserved-field gate, remote authority by the preparer). `managedRepairRoot` resolves the owner through `checkOwner` (`owner-refusal.ts`) and refuses `owner_unavailable` with the condition as its reason; `submitManagedFileRepair` re-reads the source's `RepairBusySet` (`repair-busy.ts`) right before admission and refuses `sync_in_progress` when a write in flight or an unfinished sync's frozen manifest names the path, origin, slug or a rename endpoint (#6278: a sync can start while a fence repair waits on its model call). The preparer confines the path (`isWriteTargetContained` plus a component-wise `lstat` walk, no symlinks), requires the file's sha256 to equal the previewed `beforeHash` (`changed_since_preview` otherwise), recomputes `prepareRepairPublication` (the `screenSyncImport` + `importFromContent` preparation a managed sync import gets) and refuses a different result digest or a canonical overlay. It publishes the exact bytes as `file` (`expectedBeforeHash` = previewed hash; no `file_database_drift` check), applies the import (a held new file creates its page, a `renameFrom` moves the page with `updateSlug`), clears the Git hold and records `sync-import-provenance` in the same transaction; the file write queues the Git target effect. A fence repair (`gbrain repair fences`) passes its `FenceRepairReceipt` as `fenceRepair`: submission and the preparer refuse (`invalid_params`, nothing written) a receipt `parseFenceRepairReceipt` rejects or whose `before_sha256`/`after_sha256` are not the previewed and written bytes; the outcome carries it as `fence_repair`, the file target carries the commit note from `fenceRepairCommit` (`effect-model.ts`), and every refusal and fix names `gbrain repair fences --source <id>` instead of `gbrain repair frontmatter` (`FileRepairKind`, also taken by `confinedRepairTarget` and `managedRepairRoot`). Tests: `test/repair-frontmatter.test.ts`, `test/fence-repair-receipts.test.ts`.
+- **`src/core/persistence/sync-holds.ts`** + **`sync-screen.ts`** + **`sync-blobs.ts`** — Git holds (#5988). One `op_checkpoints` row per held file (`sync-hold`, fingerprint `source:incarnation:path`) plus a per-source `sync-hold-summary` row (`count`, and `stale`: holds whose page exists); `writeGitHold` / `clearGitHold` lock the summary row and are conditional on the writing run's discovery time (`observed_at`), so an older run never replaces or clears a newer hold. Managed and legacy sync write the same rows; `readGitSourceHolds` (current incarnation only) feeds `retry-held` and legacy sync, and `readGitHoldListing` (count from the summary row, rows limited per source in SQL) feeds `sources status`, never `readAllSourceHolds`. `recordSyncConversion` logs each blocked request a managed run converted in place (`sync-conversions`, newest 20 per source, in the transaction that saves the converted cursor); `sources status` shows the newest 5. `gitHoldItem` gives every surface code, reason, key, line, location-only message, `fix` Action and `docs` anchor. #6188 `invalid_fence` holds carry `meta.fence` (reason, fence, section, rows, columns, section line), the file line of the first bad row (`meta.line`, from `fenceFileLine` when the screen holds it), `fence_version` and the last repair attempt (`fence_repair`); the summary row counts them (`fences`), and `holdRepairSteps` is the one router (D6) every surface prints: fence and slug-conflict holds (`HoldRepairRoute.fences` + `slug_conflicts`) preview the content-repair lane, `gbrain repair content --source <id>` (`contentRepairArgv`, #6377; the text says the next maintenance run repairs the fence and slug-conflict holds it can by itself when `FenceAutoRepair.active`), other holds preview `gbrain repair frontmatter`, a mixed source names both; one fence hold's own fix stays that file's `gbrain repair fences --only <path>` preview (`fenceHoldFix`). One fence hold's fix (`gitHoldFix` → `fence-repair/hold-fix.ts` `fenceHoldFix`) is that file's `--only <path>` preview with the step its state calls for, and `gitHoldItem` carries the D16 `fence` object (classes, tier, `auto_retry`, `next_attempt_after`); callers that can read the maintenance state pass it (`fenceAutoRepairFor`). `holdRescreenDue` is the one re-screen predicate managed discovery and legacy sync share (retry request, database-dependent codes, an older frontmatter reader or fence screen). Policy keys: `sync.holds` (`hold`/`fail`), `sync.hold_cap` (detail shown, default 500), `sync.hold_escalate_count` (50), `sync.hold_escalate_pct` (5, from 40 screened imports), `sync.parser_regression` (`stop`/`hold`). #6278: `preparation_stalled` holds carry `meta.stall` (request, step, `waiting_on`, attempts, the writing gbrain version, the sync's resume arguments) and count under `stalled` in the summary row and `HoldRepairRoute`; `gitHoldFix` routes them to `gbrain sources writer status --source <id> --json`, then `sources retry-held`, then the option-preserving sync (`stalledHoldSteps`), never to frontmatter repair, and `holdRescreenDue` re-screens them on a gbrain version change; `buildHoldReport` routes the escalation text by code. `screenFrozenImport` builds its input with `frozenImportScreenInput` (rename base, the run's pack, sanity and purge tombstones) and screens it with `screenFrozenContent`, both shared with the slug-conflict repair so it judges a held file exactly as the next sync would; it admits a fence Tier 1 fixes (`fences.normalize`, read once per run only when needed; the dry run lists it in `would_normalize`), turns a refusal into a hold, or throws `sync_parser_regression` only when `sync-import-provenance` proves a validating gbrain imported the same bytes. `sync-blobs.ts` reads blob ids/sizes with chunked `ls-tree -l` and contents with `cat-file --batch`; `freezeEntry` reads each entry's pinned blob and content through `readPinnedBlob` / `readPinnedContent` (via `sync-screen.ts` `pinnedBlob` / `pinnedContent`): a miss lists that entry and up to 255 of the next committed imports in one `ls-tree` and loads their contents (8 MiB slices cut by window position, not read order; over-bound blobs excluded) in one `cat-file --batch`, kept per (Git root, full commit id) until the next window, so a managed first sync spawns a few Git processes per window instead of an `ls-tree` and a `git show` per page; a non-commit target, a window git refuses to list, or a blob the window cannot answer falls back to the per-entry read (`__setPinnedWindowForTests(0)` restores per-entry reads; `test/managed-sync-pinned-reads.test.ts` proves identical rows on PGLite and Postgres). `held-reads.ts` is the read side: `get_page.file_held`, `stale` on search/query hits and the `held_files` retrieval meta and notice, from one lookup by page id (`op_checkpoints_sync_hold_page_idx`, migration v200) and one summary read per call, cached per request; `stalled` coverage routes a `preparation_stalled` hold to the host operator's writer-status fix instead of a file repair; remote callers get codes and counts, never paths, and a fix addressed to the brain host operator (a held fence page gets `fenceHoldRelay`: the owner-host command and whether it clears by itself). Tests: `test/sync-holds-store.test.ts`, `test/persistence-sync-holds.test.ts`, `test/sync-all-hold-notes.test.ts`, `test/held-read-signals.test.ts`. #5493/#6529: managed discovery admits image imports whenever multimodal embedding is on (company plans refuse). Off, `freezeEntry` holds each image import as `managed_image_sync_unsupported` (`managedImageHold`, dry-run screen too) before any content read, whatever `sync.holds` says: the rest of the source imports, the hold is keyed by the pinned blob (or working bytes), and `holdRescreenDue` re-screens it on change, removal, multimodal on or `sources retry-held`. On, `freezeEntry` freezes the bytes as base64 (`pinnedImageBytes`, `frozenImageIntent`), an oversize image takes `oversizeHold`, identical bytes are a no-op by hash, and `sync-prepare.ts` routes the entry to `sync-image.ts`. The summary row counts `images`; those holds never count toward `holds_escalated` or `git_held_files`.
+- **`src/core/persistence/file-repair.ts`** — `managed_file_repair` (#5988), the owner-internal `put_page` kind `gbrain repair frontmatter --apply` submits (accepted only from the trusted local CLI with `managedFileImport`; MCP is refused by the reserved-field gate, remote authority by the preparer). `managedRepairRoot` resolves the owner through `checkOwner` (`owner-refusal.ts`) and refuses `owner_unavailable` with the condition as its reason; `submitManagedFileRepair` re-reads the source's `RepairBusySet` (`repair-busy.ts`) right before admission and refuses `sync_in_progress` when a write in flight or an unfinished sync's frozen manifest names the path, origin, slug or a rename endpoint (#6278: a sync can start while a fence repair waits on its model call). The preparer confines the path (`isWriteTargetContained` plus a component-wise `lstat` walk, no symlinks), requires the file's sha256 to equal the previewed `beforeHash` (`changed_since_preview` otherwise), recomputes `prepareRepairPublication` (the `screenSyncImport` + `importFromContent` preparation a managed sync import gets) and refuses a different result digest or a canonical overlay. It publishes the exact bytes as `file` (`expectedBeforeHash` = previewed hash; no `file_database_drift` check), applies the import (a held new file creates its page, a `renameFrom` moves the page with `updateSlug`), clears the Git hold (only while it is the `holdObservedAt` observation when the intent carries one, so a hold a newer sync wrote stays) and records `sync-import-provenance` in the same transaction; the file write queues the Git target effect. A fence repair (`gbrain repair fences`) passes its `FenceRepairReceipt` as `fenceRepair`: submission and the preparer refuse (`invalid_params`, nothing written) a receipt `parseFenceRepairReceipt` rejects or whose `before_sha256`/`after_sha256` are not the previewed and written bytes; the outcome carries it as `fence_repair`, the file target carries the commit note from `fenceRepairCommit` (`effect-model.ts`), and every refusal and fix names `gbrain repair fences --source <id>` instead of `gbrain repair frontmatter` (`FileRepairKind`, also taken by `confinedRepairTarget` and `managedRepairRoot`). Tests: `test/repair-frontmatter.test.ts`, `test/fence-repair-receipts.test.ts`.
- **`src/core/persistence/sync-prepare.ts`** — guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. Old imports/checkpoints without durable processing consent refuse under their original IDs; old deletions require their immutable origin manifest and a still-matching page origin. `noEmbed` suppresses the effect itself; `noSchemaPack` bypasses pack loading; optional extraction stays disabled, but mandatory provider-free canonical projections remain. A filename-derived slug mismatch is accepted on every platform only when the page's stored canonical path is this file and the parsed slug is that page's slug; a different declared slug still refuses. CRLF equivalence never weakens raw CAS. No uncoordinated filesystem writes. The checkpoint validates receipts through `checkpoint-validation.ts` and, for a run whose entries another cursor imported (`overtaken`, #5522), also commits when that cursor already checkpointed the same target. Markdown imports pass `screenSyncImport` (the already-published working-tree exemption, then `screenImportContent` with the expected slug and recorded-origin exemption), the same screen the freeze-time hold screen runs, so a file is held exactly when publication would refuse it. Each import, deletion and no-op apply clears the path's Git hold (`holdObservedAt`), the checkpoint clears `releasedHolds` and ignores `supersededRequests` (failed content refusals the run converted in place), and every Markdown import records `sync-import-provenance` (raw sha256, blob, gbrain version, quoting recoveries) and reports `recovered_frontmatter` / `comment_value` in its outcome. Tests: `persistence-sync-origin-native.serial.test.ts`, `persistence-sync-options.serial.test.ts`, `persistence-sync-company.serial.test.ts`. A same-slug `renameFrom` accepts the page's recorded old origin. A different-slug rename prepares against the page where it stands, locks the old slug as an additional page key, and at publication moves the page with `updateSlug` (same id, inbound links and history, `old -> new` in `slug_aliases`, withdrawn claims follow), re-infers an implicit type from the new path, then re-prepares and applies the file content at the new slug, so the move never writes back to the file. Tests: `persistence-managed-lifecycle.test.ts`. `syncGitTopLevel` answers the checkout's `git rev-parse --show-toplevel` once per root and sync run, reading it again when the top level's `.git` entry is replaced or removed or a `.git` appears between it and the root. #6278: `prepareManagedSyncMutation` calls `enterClaimStep` at each await boundary (`managed_sync_active`, `authority`, `worktree_binding`, `configured_root`, `knowledge_publication`, `manifest_entry`, `git_rev_parse`, `origin_check`, `page_snapshot`, `import_screen`, `import_content`, `canonical_projections` and the rest, each naming `git`, `fs` or `db` where it knows), so a stall reports its step; the consumer's budget and the cancellation reaching those boundaries are in persistence-stalls.md.
- **`src/core/persistence/links-maintenance.ts`** — `extractManagedStaleLinks` (then the mention pass unless `mentions: false`, which sync passes) derives links for pages whose extraction watermark is stale with `prepareAutomaticLinks` (put_page's replace contract; other producers' edges stay) and adds the coordinator's unrecorded canonical timeline tuples (insert-only) and each page's watermark in the same `withCoordinatedWrite` transaction, bound to the revision it read; an edited page or unresolved attendance stays stale. A page skipped for unresolved attendance is marked attendance-blocked at that revision (`pages.links_attendance_blocked_revision` / `_at`, written by `markPagesAttendanceBlocked` in `engine-sql/pages.ts` only while the revision still matches, cleared by `markPagesExtractedBatch` with the watermark); it is still reconsidered every run, and the `links_extraction_lag` doctor check counts it apart from lag while the marker equals the page's current revision. It is the one managed extraction path: managed sync, `extractStaleFromDB` on a managed brain, and the owner delegation all run it. `runManagedStaleExtraction` backs `gbrain extract --stale` on managed brains, locally or through the `writer_extract_stale` administration operation inside a PGLite owner (`src/commands/extract-stale-delegate.ts`, trusted CLI registration only). `links-preparation.ts` retargets a link written against a renamed page's old slug to the live canonical page through `slug_aliases`, as `get_page` does. Tests: `persistence-managed-lifecycle.test.ts`, `persistence-sync-stdio-owner.serial.test.ts`.
- **`src/core/persistence/sync-authority.ts`** — trusted CLI or original remote generic job authority; rejects stdio bulk privilege promotion and runtime option expansion, intersects original grants with current principal/source policy.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 53e2265a98..43b8081975 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -2841,6 +2841,16 @@ More: [docs/guides/repair.md#setup-owner-conflict](../../docs/guides/repair.md#s
More: [docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover](../../docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover)
+### slug_page_mismatch
+
+<a id="slug_page_mismatch"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| Managed sync files a held file as a page whose slug the file does not carry as written, so removing its frontmatter `slug:` line would not clear the `frontmatter_slug_conflict` hold; nothing was written. | The content-repair lane judges a held file with the screen managed sync froze it with (#6696). Sync keys a file to the page that records it as its origin (or its path-derived slug) and accepts a `slug:` line only when it equals the path-derived slug or that page's slug as written. When the page's slug differs from the path-derived slug (an older import that honored the line, or a source in a subdirectory of its Git repository), or the line reaches the page only through an alias, neither removing the line nor keeping it imports the file, so the lane records `slug_page_mismatch` with both slugs instead of a generic `still_invalid`. | Make the slug: line of the held file name the page it is filed as exactly (the hold slug in gbrain sources status <id> --json), or move the file to the path that derives that slug; commit and run gbrain sync --source <id> --no-pull. gbrain repair content --source <id> --only <path> previews the current state read-only. Run: gbrain sources status '{source_id}' --json | agent | `gbrain sources status '{source_id}' --json` | 1 | no |
+
+More: [docs/guides/write-refusals.md#slug_page_mismatch](../../docs/guides/write-refusals.md#slug_page_mismatch)
+
### source_binding_required
<a id="source_binding_required"></a>
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index f665295a34..855c2f4275 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -1308,6 +1308,17 @@ approval ([`tail_exposure_approval`](write-refusals.md#tail_exposure_approval)).
paragraph in `human_reason`; `fences.repair.llm false` turns the model tier
off for the whole lane.
+**Slug conflicts agree with sync.** The `slug-conflicts` kind screens a held
+file, and the edit it would write, with the same screen managed sync froze
+the file with. A held file the screen now admits as it is (its `slug:` line
+names the file's own page, or it no longer conflicts) is listed as `import`
+and imported unchanged; the write clears only the hold observation the
+preview read, so a hold a newer sync wrote stays and the next run retries it.
+A file sync would hold whatever the lane writes (the page it is filed as
+carries a different slug than its path, or the line reaches the page only
+through an alias) is held [`slug_page_mismatch`](write-refusals.md#slug_page_mismatch)
+with both slugs and the exact hand edit.
+
**Say to your agent:** *"Sync is holding a few files over their tables or
slugs. Repair what gbrain can by itself and tell me what it wants me to
decide."*
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index d822bed6b3..07fdef66c5 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -172,7 +172,7 @@ with each file and fix the ones that need no guessing."*
| <a id="invalid_frontmatter-needs_interpretation"></a>`invalid_frontmatter` (`needs_interpretation`) | Reading it means choosing an interpretation: unquoted continuation lines after a value, a duplicated key, an unclosed `[` or `{`. gbrain never imports a guess. | `gbrain repair frontmatter --source <source> --include-ambiguous` shows the exact interpretation per file. Show the user each diff; apply only what they approve (`--only <path>` / `--skip <path>` select files). |
| <a id="invalid_frontmatter-ambiguous_identity_key"></a>`invalid_frontmatter` (`ambiguous_identity_key`) | `slug`, `type`, `id` or `source_id` appears twice, or its line was swallowed into another value, so gbrain cannot tell which page the file is. | Edit the file by hand: keep exactly one line for the key. The user decides which value is right. |
| <a id="invalid_frontmatter-ambiguous_protected_key"></a>`invalid_frontmatter` (`ambiguous_protected_key`) | A key that decides access or provenance (`visibility`, `derived_from`, …) is malformed, duplicated, swallowed into another value, rewritten by quoting, or inside an unclosed fence. gbrain never reads such a key as a broader value. | Edit the file by hand: write the key on one line with one quoted value. Ask the user which visibility is intended; never guess it. |
-| <a id="frontmatter_slug_conflict"></a>`frontmatter_slug_conflict` | The file's frontmatter `slug:` names a different page than its path does (earlier releases reported this as `invalid_params`). The path decides the slug. The hold has three outcomes once the content-repair lane's `slug-conflicts` kind runs it (the maintenance run's `content_repair` phase, `gbrain sync unblock --apply`, or `gbrain repair content --source <source>`): **removed** (the named slug resolves to no page and names no other file, or to a page of a different type sharing no title token: the stray `slug:` line is removed, the file imported and committed, the hold cleared, with a receipt; a model under the `fences.repair` caps makes the same call when the two pages are not obviously different), **merge recommended** ([`merge_recommended`](#merge_recommended): the two files describe the same thing; gbrain recommends the merge and names the canonical page but never merges pages by itself), or **undecided** ([`content_repair_needs_human`](#content_repair_needs_human)). Until that kind ships, the lane leaves the hold to the frontmatter repair preview below. | Nothing to run when the lane removes the line: the hold clears on the sync it prints. For a recommendation or an undecided hold, `gbrain sync status --source <source> --json` carries the paragraph (`human_reason`): merge the unique sections into the canonical page by hand or decide which page keeps the slug, delete or edit the file, commit, then `gbrain sync --source <source> --no-pull`. By hand at any time: remove the `slug:` line or make it match the path, or move the file to the path its slug names (`gbrain repair frontmatter --source <source> --include-ambiguous` proposes removing the line, for approval). |
+| <a id="frontmatter_slug_conflict"></a>`frontmatter_slug_conflict` | The file's frontmatter `slug:` names a different page than its path does (earlier releases reported this as `invalid_params`). The path decides the slug. The hold has three outcomes once the content-repair lane's `slug-conflicts` kind runs it (the maintenance run's `content_repair` phase, `gbrain sync unblock --apply`, or `gbrain repair content --source <source>`): **removed** (the named slug resolves to no page and names no other file, or to a page of a different type sharing no title token: the stray `slug:` line is removed, the file imported and committed, the hold cleared, with a receipt; a model under the `fences.repair` caps makes the same call when the two pages are not obviously different), **merge recommended** ([`merge_recommended`](#merge_recommended): the two files describe the same thing; gbrain recommends the merge and names the canonical page but never merges pages by itself), or **undecided** ([`content_repair_needs_human`](#content_repair_needs_human)). The lane judges the file with the screen managed sync froze it with: a hold the sync screen now admits as the file is (its slug line names the file's own page as written, or it no longer declares a conflicting slug) is **imported** unchanged in one guarded write that clears only the hold observation the lane read (a hold a newer sync wrote stays, with a retry), and a file sync would hold whatever the lane writes is [`slug_page_mismatch`](#slug_page_mismatch). Until that kind ships, the lane leaves the hold to the frontmatter repair preview below. | Nothing to run when the lane removes the line: the hold clears on the sync it prints. For a recommendation or an undecided hold, `gbrain sync status --source <source> --json` carries the paragraph (`human_reason`): merge the unique sections into the canonical page by hand or decide which page keeps the slug, delete or edit the file, commit, then `gbrain sync --source <source> --no-pull`. By hand at any time: remove the `slug:` line or make it match the path, or move the file to the path its slug names (`gbrain repair frontmatter --source <source> --include-ambiguous` proposes removing the line, for approval). |
| <a id="file_too_large"></a>`file_too_large` | Over the import size limit (5 MB for Markdown and code, 10 MiB for any sync read). The limit is fixed. | Split the file into smaller files and commit, or leave it out of the source: read `gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,<path>'`. The next `gbrain sync --source <source> --no-pull` clears the hold. |
| <a id="managed_image_sync_unsupported"></a>`managed_image_sync_unsupported` | Managed sync imports image files only while multimodal embedding is on (`GBRAIN_EMBEDDING_MULTIMODAL=true`): the image page, its OCR text and its image vector are built by the coordinated image importer at preparation, and `source_path` is recorded. While multimodal embedding is off, each image import is held with this code instead of refusing the whole sync (#5493); deleting or renaming an image still reconciles its page. These holds count as missing coverage (the image is not searchable) but never escalate, because they are not a content fault. | Nothing is broken. To import the images, set `GBRAIN_EMBEDDING_MULTIMODAL=true` on the owner and run `gbrain sync --source <source> --no-pull`: the next discovery re-screens every image hold and imports the files (#6529). To stop holding them instead, leave them out of the source (`gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,**/*.png'`); that clears the holds on the next sync. A held image is also re-screened when it changes and on `gbrain sources retry-held <source>`. |
| <a id="content_rejected"></a>`content_rejected` | The content-sanity gate matched junk and the operator set `content_sanity.junk_disposition` to `reject`, so the file is never imported and always visible. | Remove the matched junk from the file, or ask the user whether `junk_disposition` should go back to `quarantine`; that setting is the user's decision. |
@@ -418,7 +418,7 @@ runs every other kind of the lane (`src/core/repair/content-lane.ts`), and
now. Each repair is a hash-bound write with a receipt and a Git trailer; a
model decides only the cases the deterministic rules mark ambiguous, under the
`fences.repair` caps, and every byte written comes from a rule and passes the
-gates. The lane records four outcomes a person reads, each with the agent
+gates. The lane records five outcomes a person reads, each with the agent
operator envelope (`code`, `message`, `why`, `fix.next`); `gbrain errors <code>`
explains each offline. Walkthrough: [held files](repair.md#held-files).
@@ -431,6 +431,7 @@ can and tell me what it wants me to decide about the rest."*
| <a id="tail_exposure_approval"></a>`tail_exposure_approval` | An `invalid_fence` reason on a world-visible page: the repair model read the trailing lines as prose, so closing the fence after its last row is safe for the table but makes those lines visible to remote readers. The close is previewable, never unattended: the preview prints the exact lines (`L1-L2`) that would become visible and the hash binds them. `paid: false`. | `fix.next: ask_user`, actor `user`, `consent: []`: the hold's `fix` is `gbrain repair content --source <source> --only <path> --apply --expect <hash>` with `preview_argv` the lane preview and `plan_hash` the hash; relay the preview's exposed lines, run the fix only after the user agrees. A changed tail invalidates the hash (`changed_since_preview`). `why`: the privacy boundary hid those lines until now. |
| <a id="merge_recommended"></a>`merge_recommended` | A `frontmatter_slug_conflict` hold whose two files describe the same thing (a duplicate person or company page): the lane's deterministic tier found something to merge into and the model answered `merge_into <canonical>`, so removing the `slug:` line would have minted a second page. Nothing was written; the hold carries `meta.content_repair: { action: 'merge_into', canonical }` (codes and slugs only) and `sync status` renders the paragraph. gbrain does not merge pages by itself yet. | `fix.next: tell_user_to_run`, actor `user`: "This file and page `<canonical>` describe the same `<type>`; gbrain recommends merging the unique sections of `<path>` into `<canonical>` and deleting `<path>`, then committing; the hold clears on the next sync." `fix.argv` reads both pages (`gbrain get --source <source> -- <slug>`); `verify` is `gbrain sync status --source <source> --json`. Not retried until the file changes. |
| <a id="content_repair_needs_human"></a>`content_repair_needs_human` | A `frontmatter_slug_conflict` hold the lane could not decide: the deterministic tier marked it ambiguous and the model answered `needs_human` (or model repair is off, out of budget or unavailable for the day). Nothing was written; the hold carries `meta.content_repair: { action: 'needs_human' }` and `sync status` says `needs_human: true`. | `fix.next: tell_user_to_run`, actor `user`: "gbrain could not decide whether `<path>` and `<canonical>` are the same page; decide which keeps the slug: remove the `slug:` line, move the file, or merge the pages, then commit." A budget or model wait names its setting instead (`fences.repair.max_usd_per_day`, `fences.repair.llm`, consent `paid`, `fix.next: ask_user`). `verify` is `gbrain sync status --source <source> --json`. |
+| <a id="slug_page_mismatch"></a>`slug_page_mismatch` | A `frontmatter_slug_conflict` hold the lane judged with the same screen managed sync froze it with, and sync would still hold whatever the lane writes: sync files the file as page `<slug>` (the page that records it as its origin, or its path-derived slug), but the path derives another slug, or the `slug:` line reaches that page only through an alias or another spelling. Removing the line would not clear the hold, so nothing was written; the hold carries `meta.content_repair: { action: 'remove_slug', reason: 'slug_page_mismatch', named }` with the other slug. Earlier releases reported this as a generic `still_invalid` ("the frontmatter needs other changes too") or skipped it as `already_exempt`. | `fix.next: run`, actor `agent`: make the `slug:` line name `<slug>` exactly, or move the file to the path that derives `<slug>`, commit, then `gbrain sync --source <source> --no-pull`. `fix.argv` is `gbrain repair content --source <source> --only <path>` (read-only preview); `verify` is `gbrain sources status <source> --json`. |
## Worktree refresh refusals
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 2c10c4be1a..654053438c 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -566,6 +566,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.223.0', text: '`gbrain apply-migrations` no longer prints "All migrations up to date" (exit 0) while a migration is wedged (3 or more consecutive partial runs). It exits 1 with `migrations_pending` reason `wedged` and a fix to ask the user about (`gbrain apply-migrations --force-retry <version>` after fixing the cause); `--list` names the wedged migration and its clearing command, `--list --json` adds a `wedged` list, `gbrain post-upgrade` exits non-zero and `gbrain upgrade` prints `Migrations: wedged` instead of `Migrations: complete`.' },
{ since: '0.60.223.0', text: '`gbrain repair file-drift` now takes `--only <path>` and `--skip <path>` (repeatable; source-relative canonical file paths, `*` within a segment and `**` across segments, so `--only \'concepts/**\'` selects every drifted page filed under concepts/). The globs narrow the selection before the mixed-class check, are bound into the preview hash and appear in the printed apply command, so running that command applies exactly the previewed pages; an apply under other globs refuses `preview_changed`. `--keep` on file-drift is now refused with a pointer at `--prefer database` (keep the database copy) or `--prefer file`, instead of the stuck-recovery value error.' },
{ since: '0.60.223.0', text: 'gbrain.yml `storage:` accepts an opt-in `keep_db:` list of directory prefixes. On the canonical owner host, the resident `gbrain serve`, `gbrain jobs` or `gbrain autopilot` consumer reconciles each drifted page under those prefixes with the database copy (the `gbrain repair file-drift --prefer database` resolution, inside reconcile\'s protections and backups), at most 10 requests every 10 minutes, never twice for the same drift and never past 90% of the write-quota stop line; other hosts and remote or caller writes are unchanged and keep refusing `source_changed`. Doctor `maintenance_write_drift` echoes each declared policy with how many drifted pages it matches and their receipt cost. An unknown key under `storage:` now prints a warning instead of being ignored silently.' },
+ { since: '0.60.223.0', text: '`gbrain repair content` (the `slug-conflicts` kind) now judges a held `frontmatter_slug_conflict` file with the same screen managed sync froze it with. A held file sync would now import as it is (its `slug:` line names the file\'s own page, or it no longer conflicts) is listed as `import` and imported unchanged, clearing the hold only while it is still the observation the repair read; before, it was skipped as `already_exempt` or `already_clean` and the hold stayed. A file in a source that is a subdirectory of its Git repository now loses its stray `slug:` line instead of being held `still_invalid`. A file sync would hold whatever the repair writes is now held `slug_page_mismatch` naming both slugs, instead of the generic `still_invalid` or `already_exempt` (an alias to the file\'s own page is one).' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/content-repair/hold-fix.ts b/src/core/content-repair/hold-fix.ts
index df8a922c31..c5bf083126 100644
--- a/src/core/content-repair/hold-fix.ts
+++ b/src/core/content-repair/hold-fix.ts
@@ -22,6 +22,9 @@
* run retries after `next_attempt_after`.
* - `remove_slug` recorded (the edit could not be written: `canonical_overlay`,
* `still_invalid`, `changed_since_read`): the exact one-line edit by hand.
+ * - `slug_page_mismatch` (#6696 C8): sync files the file as a page whose
+ * slug the file does not carry, so removing the line would not clear it:
+ * name that page's slug exactly or move the file.
*
* Location only: path, slugs, codes and amounts.
*/
@@ -41,6 +44,7 @@ export function contentPreviewArgv(sourceId: string, path?: string): string[] {
export function contentHoldDocs(state: ContentHoldRepairState | undefined): string {
if (state?.action === 'merge_into') return 'docs/guides/write-refusals.md#merge_recommended';
if (state?.action === 'needs_human') return 'docs/guides/write-refusals.md#content_repair_needs_human';
+ if (state?.reason === 'slug_page_mismatch') return 'docs/guides/write-refusals.md#slug_page_mismatch';
return 'docs/guides/write-refusals.md#frontmatter_slug_conflict';
}
@@ -93,6 +97,12 @@ export function contentHoldFix(record: { source_id: string; path: string; slug?:
why: `${record.path} is held until the content-repair model can judge it (${state.reason}); the maintenance run tries again${state.next_attempt_after ? ` after ${state.next_attempt_after}` : ''}. `
+ `Run the preview now to retry immediately (read-only), then its apply command.` };
}
+ if (state.reason === 'slug_page_mismatch') {
+ return { ...base, actor: 'agent',
+ why: `Sync files ${record.path} as page ${record.slug ?? '?'}, and ${state.named && state.named !== record.slug ? `its path derives ${state.named}` : 'its slug: line does not name that page as written'}, `
+ + `so removing the line would not clear the hold (slug_page_mismatch). By hand: make the slug: line name ${record.slug ?? 'the page'} exactly or move the file to the path that derives it, `
+ + `commit, and run gbrain sync --source ${source} --no-pull; the preview shows the current state.` };
+ }
return { ...base, actor: 'agent',
why: `gbrain decided to remove the slug: line of ${record.path} but could not write it (${state.reason}); the preview shows the current state. `
+ `By hand: delete the slug: line of ${record.path} (the path decides the slug), commit, and run gbrain sync --source ${source} --no-pull.` };
diff --git a/src/core/content-repair/receipt.ts b/src/core/content-repair/receipt.ts
index 329be1d2e3..ed0e3ad338 100644
--- a/src/core/content-repair/receipt.ts
+++ b/src/core/content-repair/receipt.ts
@@ -3,9 +3,10 @@
* subject and trailer of a repaired file.
*
* The receipt rides the write's durable outcome (`content_repair`): the
- * actor `content-repair`, the action written (`remove_slug` is the only one
- * that writes; a recommended merge or an undecidable pair writes nothing
- * and lives on the hold instead), the tier that decided it (`deterministic`
+ * actor `content-repair`, the action written (`remove_slug` edits the file;
+ * `import` (#6696 C8) imports the held bytes unchanged because the sync
+ * screen now admits them; a recommended merge or an undecidable pair writes
+ * nothing and lives on the hold instead), the tier that decided it (`deterministic`
* or `llm`) with its confidence (`high` for the deterministic rules, `medium`
* for a model verdict), the model (llm only), the model spend and the sha256
* of the bytes before and after. Hashes and codes only, so it is safe in
@@ -18,7 +19,7 @@ export const CONTENT_REPAIR_HOLD_CODE = 'frontmatter_slug_conflict';
export interface ContentRepairReceipt {
actor: typeof CONTENT_REPAIR_ACTOR;
hold_code: typeof CONTENT_REPAIR_HOLD_CODE;
- action: 'remove_slug';
+ action: 'remove_slug' | 'import';
tier: 'deterministic' | 'llm';
confidence: 'high' | 'medium';
/** The model that judged (llm tier); null for the deterministic tier. */
@@ -35,13 +36,14 @@ const SHA = /^[0-9a-f]{64}$/;
export function parseContentRepairReceipt(value: unknown): ContentRepairReceipt | null {
if (!value || typeof value !== 'object') return null;
const r = value as Record<string, unknown>;
- if (r.actor !== CONTENT_REPAIR_ACTOR || r.hold_code !== CONTENT_REPAIR_HOLD_CODE || r.action !== 'remove_slug') return null;
+ if (r.actor !== CONTENT_REPAIR_ACTOR || r.hold_code !== CONTENT_REPAIR_HOLD_CODE || (r.action !== 'remove_slug' && r.action !== 'import')) return null;
if (r.tier !== 'deterministic' && r.tier !== 'llm') return null;
if (r.confidence !== 'high' && r.confidence !== 'medium') return null;
if (r.model !== null && (typeof r.model !== 'string' || r.model.length > 200 || /[\r\n]/.test(r.model))) return null;
if (r.cost_usd !== null && (typeof r.cost_usd !== 'number' || !Number.isFinite(r.cost_usd) || r.cost_usd < 0)) return null;
if (typeof r.before_sha256 !== 'string' || !SHA.test(r.before_sha256) || typeof r.after_sha256 !== 'string' || !SHA.test(r.after_sha256)) return null;
- return { actor: CONTENT_REPAIR_ACTOR, hold_code: CONTENT_REPAIR_HOLD_CODE, action: 'remove_slug', tier: r.tier, confidence: r.confidence,
+ if (r.action === 'import' && r.before_sha256 !== r.after_sha256) return null;
+ return { actor: CONTENT_REPAIR_ACTOR, hold_code: CONTENT_REPAIR_HOLD_CODE, action: r.action, tier: r.tier, confidence: r.confidence,
model: r.model as string | null, cost_usd: r.cost_usd as number | null, before_sha256: r.before_sha256, after_sha256: r.after_sha256 };
}
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index a9f1a63738..419b5932af 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -429,6 +429,14 @@ export const CODES = {
skill_not_found: { class: 'caller', summary: "No authorized published skill matches this key." },
skill_retention_capacity: { class: 'caller', summary: "Retained skill revisions exceed this source storage budget." },
skill_unavailable: { class: 'caller', summary: "The qualified shared skill is not in this installation's current authorized view.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },
+ slug_page_mismatch: { class: 'caller', retryable: false, actor: 'agent',
+ summary: "Managed sync files a held file as a page whose slug the file does not carry as written, so removing its frontmatter `slug:` line would not clear the `frontmatter_slug_conflict` hold; nothing was written.",
+ why: "The content-repair lane judges a held file with the screen managed sync froze it with (#6696). Sync keys a file to the page that records it as its origin (or its path-derived slug) and accepts a `slug:` line only when it equals the path-derived slug or that page's slug as written. When the page's slug differs from the path-derived slug (an older import that honored the line, or a source in a subdirectory of its Git repository), or the line reaches the page only through an alias, neither removing the line nor keeping it imports the file, so the lane records `slug_page_mismatch` with both slugs instead of a generic `still_invalid`.",
+ docs: 'docs/guides/write-refusals.md#slug_page_mismatch',
+ suggestion: 'Make the slug: line of the held file name the page it is filed as exactly (the hold slug in gbrain sources status <id> --json), or move the file to the path that derives that slug; commit and run gbrain sync --source <id> --no-pull. gbrain repair content --source <id> --only <path> previews the current state read-only.',
+ fix: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Read-only: lists the held file with the slug sync files it as and its fix, which names the exact edit and the content-repair preview; nothing is written.',
+ verify: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'] } } },
source_binding_required: { class: 'caller', summary: "A write needs an explicit source binding on this MCP server (--source-guard)." },
source_changed: { class: 'caller', summary: "The source changed during the operation; nothing was committed.", why: "Covers a replaced, archived or re-bound source and a canonical file that differs from the page's database copy (detail file_database_drift). A page that records no file of its own reconciles against the file at its slug path only with gbrain sources reconcile <source> <slug> --preview --adopt-slug-path. A canonical file that is gone while its page is live (reason canonical_file_missing, a ghost page) never clears by retrying or syncing: a person restores the file and syncs, or removes the page (docs/guides/write-refusals.md#canonical_file_missing)." },
source_id_taken: { class: 'caller', summary: "This source already exists and does not match this exact admitted request." },
diff --git a/src/core/persistence/file-repair.ts b/src/core/persistence/file-repair.ts
index e101d02168..4422faeed6 100644
--- a/src/core/persistence/file-repair.ts
+++ b/src/core/persistence/file-repair.ts
@@ -30,7 +30,10 @@
* `ContentRepairReceipt` (`contentRepair`), outcome field `content_repair`,
* subject `gbrain: repair frontmatter slug in <path>` and trailer
* `gbrain-repair: frontmatter_slug_conflict <tier> <confidence>`; its
- * refusals route to `gbrain repair content`.
+ * refusals route to `gbrain repair content`. #6696 C8: an intent carrying
+ * `holdObservedAt` (the slug-conflict `import` of unchanged held bytes)
+ * clears the hold only while it is that observation, so a hold a sync wrote
+ * after the repair read it stays.
*
* Trusted local CLI only: admission refuses remote and delegated callers, the
* `put_page` reserved-field gate refuses the kind from MCP, and the preparer
@@ -96,6 +99,8 @@ export interface ManagedFileRepairIntent extends Record<string, unknown> {
fenceRepair?: FenceRepairReceipt;
/** #6377 a slug-conflict repair's receipt (codes and hashes only). */
contentRepair?: ContentRepairReceipt;
+ /** #6696 C8: the hold observation the repair read; the publication clears the path's hold only while it is that observation (a newer hold stays). */
+ holdObservedAt?: string;
}
/** The repair command a refusal names (D6 router): a fence repair's, the content repair's, or the frontmatter repair's. */
@@ -272,6 +277,8 @@ export interface ManagedFileRepairInput {
fenceRepair?: FenceRepairReceipt;
/** #6377 set by the `slug-conflicts` kind: the write's receipt, and its refusals route to `gbrain repair content`. */
contentRepair?: ContentRepairReceipt;
+ /** #6696 C8: clear the hold only while it is this observation. */
+ holdObservedAt?: string;
}
export async function submitManagedFileRepair(ctx: OperationContext, input: ManagedFileRepairInput): Promise<Record<string, unknown>> {
@@ -297,7 +304,7 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:
const kind = repairKindOf(p ?? {});
if (row.authority.remote || row.principal_kind !== 'local_cli') throw trustedCliRequired('A managed file repair requires a trusted local CLI writer.');
if (!p || p.kind !== 'managed_file_repair' || typeof p.content !== 'string' || typeof p.path !== 'string' || typeof p.sourcePath !== 'string'
- || typeof p.beforeHash !== 'string' || typeof p.resultDigest !== 'string') {
+ || typeof p.beforeHash !== 'string' || typeof p.resultDigest !== 'string' || (p.holdObservedAt !== undefined && typeof p.holdObservedAt !== 'string')) {
throw opError('invalid_params', 'The durable file repair intent is incomplete.',
`Repair request ${row.request_id} in source ${row.source_id} has no complete intent, so it published nothing. Preview the repair again: gbrain repair ${kind} --source ${row.source_id}.`,
{ fix: previewFix(row.source_id, kind) });
@@ -373,7 +380,7 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:
await applied.apply(tx);
await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND source_path IS DISTINCT FROM $3', [row.source_id, row.slug, p.sourcePath]);
if (!applied.noop) { await project(tx); await sealPageTextProjection(tx, row.slug, row.source_id); }
- const holdCleared = await clearGitHold(tx, { sourceId: row.source_id, incarnation: row.source_incarnation, path: p.path, observedAt: new Date().toISOString() });
+ const holdCleared = await clearGitHold(tx, { sourceId: row.source_id, incarnation: row.source_incarnation, path: p.path, observedAt: p.holdObservedAt ?? new Date().toISOString() });
const [page] = await tx.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [row.source_id, row.slug]);
if (page) await recordSyncImportProvenance(tx, { source_id: row.source_id, incarnation: row.source_incarnation, page_id: Number(page.id), origin: p.sourcePath,
raw_sha256: sha256(importContent), gbrain_version: VERSION });
diff --git a/src/core/repair/slug-conflicts.ts b/src/core/repair/slug-conflicts.ts
index c360a999ff..baee9a1383 100644
--- a/src/core/repair/slug-conflicts.ts
+++ b/src/core/repair/slug-conflicts.ts
@@ -54,7 +54,7 @@ import { trustedCliRequired } from '../ops/op-fix.ts';
import { shellQuote, type Action } from '../agent-output.ts';
import { autoFixFrontmatter, createFrontmatterBackup, makeFrontmatterBackupRunId } from '../brain-writer.ts';
import { classifyImportHold, parseMarkdown, serializePageToMarkdown } from '../markdown.ts';
-import { MAX_FILE_SIZE } from '../import-screen.ts';
+import { MAX_FILE_SIZE, type ImportScreenResult } from '../import-screen.ts';
import { importFromFile } from '../import-file.ts';
import { resolveSlugForPath, slugifyPath } from '../sync.ts';
import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';
@@ -68,6 +68,7 @@ import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, sa
import { clearGitHold, readGitHold, readGitSourceHolds, recordContentHoldRepair, type ContentHoldRepairState, type GitHoldRecord } from '../persistence/sync-holds.ts';
import { confinedRepairTarget, prepareRepairPublication, repairScreenConfig, submitManagedFileRepair } from '../persistence/file-repair.ts';
import { repairBusy, repairBusyMessage } from '../persistence/repair-busy.ts';
+import { frozenImportScreenInput, loadSyncScreenRun, screenFrozenContent } from '../persistence/sync-screen.ts';
import type { PageSnapshot } from '../page-state/types.ts';
import { attemptStore } from '../fence-repair/attempts.ts';
import { fenceRepairLlmEnabled, readFenceRepairCaps } from '../fence-repair/config.ts';
@@ -83,17 +84,21 @@ import { gitChildEnv } from '../git-env.ts';
type Tier = 'deterministic' | 'llm';
type DeterministicRule = 'absent_page' | 'different_type';
+/** #6696 C8: a hold the sync screen now admits as the file is: the file is imported unchanged and the hold clears. */
+type ImportReason = 'already_clean' | 'already_exempt';
interface Selection { source_ids: string[]; only: string[]; skip: string[]; no_llm: boolean }
/** One previewed candidate: everything the hash binds (location, hashes, tier), never a frontmatter value. */
interface ApprovedConflict {
source_id: string; path: string; source_path: string; slug: string; mode: 'managed' | 'legacy';
page_id: number | null; revision: string | null; before: string; upstream_version: string | null; held: boolean;
+ /** #6696 C8: the observation time of the hold the plan read; an import clears only that observation, never a newer one. */
+ observed_at: string | null;
/** The slug the `slug:` line resolves to (alias followed), and that page's id and content hash; null when no page has it. */
named: string | null; named_page_id: number | null; named_sha256: string | null;
tier: Tier;
- /** Deterministic: the rule and the sha256 of the edited bytes; null for the model tier (decided at apply time). */
- rule: DeterministicRule | null; after: string | null;
+ /** Deterministic: the rule (or the import reason) and the sha256 of the bytes written; null for the model tier (decided at apply time). */
+ rule: DeterministicRule | ImportReason | null; after: string | null;
estimate_usd: number;
/** Model items from this one to the end of the plan (the pages a budget stop leaves waiting). */
llm_waiting: number;
@@ -107,6 +112,8 @@ export interface SlugConflictsPreviewDetails {
model: string | null;
llm_enabled: boolean;
diffs: Array<{ item: string; rule: DeterministicRule; diff: string }>;
+ /** #6696 C8: held files the sync screen now admits as they are (imported unchanged, the hold cleared). */
+ imports: Array<{ item: string; reason: ImportReason }>;
llm_items: Array<{ item: string; named: string | null; estimate_usd: number }>;
held: HeldEntry[];
skipped: Array<{ item: string; reason: string }>;
@@ -131,6 +138,7 @@ const TRANSIENT: ReadonlySet<string> = new Set(['llm_unavailable', 'ledger_unava
const STOPWORDS: ReadonlySet<string> = new Set(['a', 'an', 'the', 'of', 'and', 'or', 'for', 'to', 'in', 'on', 'at', 'by', 'with', 'from', 'inc', 'llc', 'ltd', 'co', 'corp', 'company', 'mr', 'ms', 'dr']);
const itemName = (entry: Pick<ApprovedConflict, 'source_id' | 'path'>) => `${entry.source_id}:${entry.path}`;
+const isImport = (entry: Pick<ApprovedConflict, 'rule'>) => entry.rule === 'already_clean' || entry.rule === 'already_exempt';
function previewArgv(scope: RepairScope, selection: Selection): string[] {
return ['gbrain', 'repair', 'slug-conflicts', ...(scope.source_ids.length === 1 ? ['--source', scope.source_ids[0]!] : []),
@@ -175,7 +183,7 @@ function lookupSlugs(declared: string): string[] {
* file path decides that this is the one fix the file needs, as `repair frontmatter` proposes it; null when the
* file needs other frontmatter changes too, or the result still fails to strict-parse or earns a hold.
*/
-export function removeSlugLine(content: string, sourcePath: string, path: string, activePack?: FenceSource['activePack']): string | null {
+export function removeSlugLine(content: string, sourcePath: string, activePack?: FenceSource['activePack']): string | null {
const fixed = autoFixFrontmatter(content, { filePath: sourcePath });
if (fixed.fixes.length !== 1 || fixed.fixes[0]!.code !== 'SLUG_MISMATCH' || fixed.content === content) return null;
const block = /^(\uFEFF?---[ \t]*(\r?\n))([\s\S]*?)(\r?\n---[ \t]*(?:\r?\n|$))/.exec(content);
@@ -185,7 +193,7 @@ export function removeSlugLine(content: string, sourcePath: string, path: string
const at = lines.findIndex(line => /^slug:\s*\S/.test(line));
if (at < 0) return null;
const after = `${block[1]}${[...lines.slice(0, at), ...lines.slice(at + 1)].join(newline)}${block[4]}${content.slice(block[0].length)}`;
- const parsed = parseMarkdown(after, path, { validate: true, ...(activePack ? { activePack } : {}) });
+ const parsed = parseMarkdown(after, sourcePath, { validate: true, ...(activePack ? { activePack } : {}) });
if (parsed.errors?.some(error => error.code === 'YAML_PARSE')) return null;
if (classifyImportHold(parsed, { expectedSlug: resolveSlugForPath(sourcePath), byteLength: Buffer.byteLength(after), maxBytes: MAX_FILE_SIZE })) return null;
return after;
@@ -223,9 +231,30 @@ interface Candidate {
type Analysis =
| { status: 'skip'; reason: 'already_exempt' | 'already_clean' | 'gone' | 'unsafe_path' | 'not_utf8'; message: string }
+ | { status: 'import'; reason: ImportReason }
| { status: 'deterministic'; rule: DeterministicRule; after: string }
| { status: 'llm'; input: JudgmentInput }
- | { status: 'held'; reason: string; message: string };
+ | { status: 'held'; reason: string; message: string; named?: string };
+
+/** #6696 C8: the managed sync screen of a candidate's bytes, exactly as the next sync freezes them; null when `sync.holds=fail` (sync screens nothing). */
+type SyncScreen = ((cand: Candidate, content: string) => Promise<ImportScreenResult>) | null;
+
+async function syncScreen(engine: BrainEngine, src: FenceSource): Promise<SyncScreen> {
+ const run = src.root ? await loadSyncScreenRun(engine, src.id, undefined, false) : null;
+ if (!run) return null;
+ return async (cand, content) => {
+ const snapshot = await engine.readPageSnapshot(cand.slug, { sourceId: src.id, includeDeleted: true });
+ const entry = { path: cand.path, sourcePath: cand.sourcePath, action: 'import' as const, working: cand.hold?.meta.working === true };
+ return screenFrozenContent(await frozenImportScreenInput(engine, { cursor: { sourceId: src.id, incarnation: src.incarnation, root: src.root! }, entry, slug: cand.slug, snapshot,
+ content, rawHash: sha256(content), lineEndingOnly: false }, run), run);
+ };
+}
+
+/** Sync files the candidate as page `cand.slug` but still holds it for its slug: both slugs, and the exact hand edit (`other` is recorded on the hold). */
+function slugPageMismatch(cand: Candidate, other: string, why: string): Analysis {
+ return { status: 'held', reason: 'slug_page_mismatch', named: other, message: `Sync files ${cand.path} as page ${cand.slug}, ${why}, so sync still holds it. `
+ + `By hand: make the slug: line name ${cand.slug} exactly or move the file to the path that derives ${cand.slug}, commit, and run gbrain sync --source ${cand.src.id} --no-pull.` };
+}
async function readCandidate(engine: BrainEngine, src: FenceSource, path: string): Promise<{ ok: true; cand: Candidate } | { ok: false; reason: 'gone' | 'unsafe_path' | 'not_utf8' | 'no_checkout' }> {
if (!src.root) return { ok: false, reason: 'no_checkout' };
@@ -253,33 +282,42 @@ async function readCandidate(engine: BrainEngine, src: FenceSource, path: string
named, namedSlug: named?.page.slug ?? null } };
}
-/** The free tier over a candidate: exempt, clean, a deterministic edit, or the model's question. */
-function analyze(cand: Candidate, slugsInCheckout: () => Set<string>): Analysis {
+/**
+ * The free tier over a candidate: exempt, clean, a deterministic edit, or the model's question. #6696 C8: with the
+ * sync screen, an exempt or clean file whose hold sync would now drop is imported as it is; one sync still holds is
+ * `slug_page_mismatch`; an edit is planned only when sync would import the edited bytes.
+ */
+async function analyze(cand: Candidate, slugsInCheckout: () => Set<string>, screen: SyncScreen): Promise<Analysis> {
const expected = resolveSlugForPath(cand.sourcePath);
- if (!cand.declared || cand.declared === expected || slugifyPath(cand.declared) === expected) {
- return { status: 'skip', reason: 'already_clean', message: `${cand.path} no longer declares a conflicting slug; the next gbrain sync --source ${cand.src.id} --no-pull clears its hold.` };
- }
- const own = cand.named && ((cand.hold?.page_id !== null && cand.hold?.page_id !== undefined && cand.named.page.id === cand.hold.page_id)
+ const clean = !cand.declared || cand.declared === expected || slugifyPath(cand.declared) === expected;
+ const own = !clean && cand.named && ((cand.hold?.page_id !== null && cand.hold?.page_id !== undefined && cand.named.page.id === cand.hold.page_id)
|| (cand.named.page.source_path != null && cand.named.page.source_path === cand.sourcePath) || (cand.snapshot !== null && cand.named.page.id === cand.snapshot.page.id));
- if (own) return { status: 'skip', reason: 'already_exempt', message: `The slug: line of ${cand.path} resolves to the file's own page (${cand.named!.page.slug}); nothing to repair.` };
- const after = () => removeSlugLine(cand.content, cand.sourcePath, cand.path, cand.src.activePack);
+ if (clean || own) {
+ const skip: Analysis = clean ? { status: 'skip', reason: 'already_clean', message: `${cand.path} no longer declares a conflicting slug; the next gbrain sync --source ${cand.src.id} --no-pull clears its hold.` }
+ : { status: 'skip', reason: 'already_exempt', message: `The slug: line of ${cand.path} resolves to the file's own page (${cand.named!.page.slug}); nothing to repair.` };
+ if (!screen || !cand.hold) return skip;
+ const now = await screen(cand, cand.content);
+ if (now.status !== 'refused') return { status: 'import', reason: skip.reason as ImportReason };
+ if (now.refusal.code === 'frontmatter_slug_conflict') return slugPageMismatch(cand, clean ? expected : cand.named!.page.slug, clean ? `but its path derives ${expected}`
+ : `and its slug: line resolves to page ${cand.named!.page.slug} only through an alias or another spelling, while sync compares the line as written with the path-derived slug ${expected}`);
+ return { status: 'held', reason: now.refusal.code, message: `Sync now holds ${cand.path} for ${now.refusal.code}, not for its slug: line; the next gbrain sync --source ${cand.src.id} --no-pull records that hold.` };
+ }
+ const edit = async (rule: DeterministicRule): Promise<Analysis> => {
+ const after = removeSlugLine(cand.content, cand.sourcePath, cand.src.activePack);
+ if (after === null) return { status: 'held', reason: 'still_invalid', message: `Removing the slug: line of ${cand.path} alone does not make it importable (the frontmatter needs other changes too); preview gbrain repair frontmatter --source ${cand.src.id} --only ${cand.path} --include-ambiguous.` };
+ const screened = screen ? await screen(cand, after) : null;
+ if (screened?.status !== 'refused') return { status: 'deterministic', rule, after };
+ if (screened.refusal.code === 'frontmatter_slug_conflict') return slugPageMismatch(cand, expected, `but its path derives ${expected}`);
+ return { status: 'held', reason: 'still_invalid', message: `Removing the slug: line of ${cand.path} would leave it held for ${screened.refusal.code}; preview gbrain repair frontmatter --source ${cand.src.id} --only ${cand.path} --include-ambiguous.` };
+ };
if (!cand.named) {
- const inCheckout = lookupSlugs(cand.declared).some(slug => slugsInCheckout().has(slug));
- if (!inCheckout) {
- const edited = after();
- return edited === null ? { status: 'held', reason: 'still_invalid', message: `Removing the slug: line of ${cand.path} alone does not make it importable (the frontmatter needs other changes too); preview gbrain repair frontmatter --source ${cand.src.id} --only ${cand.path} --include-ambiguous.` }
- : { status: 'deterministic', rule: 'absent_page', after: edited };
- }
+ if (!lookupSlugs(cand.declared).some(slug => slugsInCheckout().has(slug))) return edit('absent_page');
} else {
const parsed = parseMarkdown(cand.content, cand.path, cand.src.activePack ? { activePack: cand.src.activePack } : undefined);
const shared = [...titleTokens(parsed.title)].some(token => titleTokens(cand.named!.page.title ?? '').has(token));
- if (parsed.type !== cand.named.page.type && !shared) {
- const edited = after();
- return edited === null ? { status: 'held', reason: 'still_invalid', message: `Removing the slug: line of ${cand.path} alone does not make it importable (the frontmatter needs other changes too); preview gbrain repair frontmatter --source ${cand.src.id} --only ${cand.path} --include-ambiguous.` }
- : { status: 'deterministic', rule: 'different_type', after: edited };
- }
+ if (parsed.type !== cand.named.page.type && !shared) return edit('different_type');
}
- if (after() === null) return { status: 'held', reason: 'still_invalid', message: `Removing the slug: line of ${cand.path} alone would not make it importable, so no model is asked; preview gbrain repair frontmatter --source ${cand.src.id} --only ${cand.path} --include-ambiguous.` };
+ if (removeSlugLine(cand.content, cand.sourcePath, cand.src.activePack) === null) return { status: 'held', reason: 'still_invalid', message: `Removing the slug: line of ${cand.path} alone would not make it importable, so no model is asked; preview gbrain repair frontmatter --source ${cand.src.id} --only ${cand.path} --include-ambiguous.` };
const held = judgmentParticipant({ path: cand.path, slug: cand.slug, content: cand.content, otherSlug: cand.namedSlug });
const named = cand.named ? judgmentParticipant({ path: cand.named.page.source_path ?? null, slug: cand.named.page.slug, content: pageContent(cand.named), otherSlug: cand.slug, type: cand.named.page.type }) : null;
return { status: 'llm', input: { held, named, reason: 'frontmatter_slug_conflict' } };
@@ -348,6 +386,7 @@ export const slugConflictsRepair: RepairHandler = {
const held: HeldEntry[] = [];
const skipped: SlugConflictsPreviewDetails['skipped'] = [];
const llmItems: SlugConflictsPreviewDetails['llm_items'] = [];
+ const imports: SlugConflictsPreviewDetails['imports'] = [];
let unpricedWarned = false;
for (const sourceId of scope.source_ids) {
const src = await loadFenceSource(engine, sourceId, { remote: opts?.remote !== false, work: 'content repair' });
@@ -356,6 +395,7 @@ export const slugConflictsRepair: RepairHandler = {
warnings.push(...unknown.map(path => `--only ${path}: no held or conflicting file at that path in ${sourceId}; check the source-relative path.`));
let slugs: Set<string> | null = null;
const slugsInCheckout = () => (slugs ??= src.root ? checkoutSlugs(src.root) : new Set<string>());
+ const screen = await syncScreen(engine, src);
for (const path of paths) {
const name = `${sourceId}:${path}`;
const keep = async (entry: Omit<HeldEntry, 'item'>, state?: Omit<ContentHoldRepairState, 'at'>) => {
@@ -375,12 +415,20 @@ export const slugConflictsRepair: RepairHandler = {
continue;
}
const cand = read.cand;
- const analysis = analyze(cand, slugsInCheckout);
+ const analysis = await analyze(cand, slugsInCheckout, screen);
if (analysis.status === 'skip') { skip(analysis.reason); continue; }
- if (analysis.status === 'held') { await keep({ reason: analysis.reason, tier: 'manual', resolution: analysis.message }, { action: 'remove_slug', reason: analysis.reason, next_attempt_after: null }); continue; }
+ if (analysis.status === 'held') {
+ await keep({ reason: analysis.reason, tier: 'manual', resolution: analysis.message }, { action: 'remove_slug', reason: analysis.reason, ...(analysis.named ? { named: analysis.named } : {}), next_attempt_after: null });
+ continue;
+ }
const base: Omit<ApprovedConflict, 'tier' | 'rule' | 'after' | 'estimate_usd' | 'llm_waiting'> = { source_id: src.id, path, source_path: cand.sourcePath, slug: cand.slug, mode: src.managed ? 'managed' : 'legacy',
page_id: cand.snapshot?.page.id ?? null, revision: cand.snapshot?.revision ?? null, before: cand.before, upstream_version: cand.hold?.upstream_version ?? null, held: cand.hold !== null,
- named: cand.namedSlug, named_page_id: cand.named?.page.id ?? null, named_sha256: cand.named ? sha256(pageContent(cand.named)) : null };
+ observed_at: cand.hold?.observed_at ?? null, named: cand.namedSlug, named_page_id: cand.named?.page.id ?? null, named_sha256: cand.named ? sha256(pageContent(cand.named)) : null };
+ if (analysis.status === 'import') {
+ approved.push({ ...base, tier: 'deterministic', rule: analysis.reason, after: cand.before, estimate_usd: 0, llm_waiting: 0 });
+ imports.push({ item: name, reason: analysis.reason });
+ continue;
+ }
if (analysis.status === 'deterministic') {
approved.push({ ...base, tier: 'deterministic', rule: analysis.rule, after: sha256(Buffer.from(analysis.after, 'utf8')), estimate_usd: 0, llm_waiting: 0 });
diffs.push({ item: name, rule: analysis.rule, diff: lineDiff(path, cand.content, analysis.after) });
@@ -419,7 +467,8 @@ export const slugConflictsRepair: RepairHandler = {
const hash = previewHash({ kind: 'slug-conflicts-v1', brain_id: scope.brain_id, sources: sourcesRows, selection, items: approved });
if (approved.length && !opts?.apply) await saveApprovedSet<ApprovedSetItem>(engine, { command: 'slug-conflicts', hash }, approved.map(entry => ({ ...entry, selection })));
const listing: RepairListing[] = [
- ...approved.map(entry => ({ item: itemName(entry), class: entry.tier, detail: entry.tier === 'deterministic' ? `remove_slug (${entry.rule}): the slug: line is removed; the path decides the slug`
+ ...approved.map(entry => ({ item: itemName(entry), class: isImport(entry) ? 'import' : entry.tier, detail: isImport(entry) ? `import (${entry.rule}): sync would import the file as it is, so it is imported unchanged and its hold clears`
+ : entry.tier === 'deterministic' ? `remove_slug (${entry.rule}): the slug: line is removed; the path decides the slug`
: `model decides (${s.model}) at apply time: remove_slug, merge_into ${entry.named ?? '?'} or needs_human; est. $${entry.estimate_usd.toFixed(4)}` })),
...held.map(entry => ({ item: entry.item, class: entry.reason, detail: entry.resolution })),
...skipped.map(entry => ({ item: entry.item, class: entry.reason })),
@@ -430,7 +479,7 @@ export const slugConflictsRepair: RepairHandler = {
why: `Applies exactly the ${approved.length} previewed slug-conflict repair(s)${llmItems.length ? `, ${llmItems.length} of them judged by the model (estimated $${llmUsd.toFixed(4)}; a recommended merge or an undecidable pair writes nothing and is recorded on the hold)` : ''}; a file that changed since this preview is skipped.`,
verify: { argv: ['gbrain', 'sources', 'status', ...(scope.source_ids.length === 1 ? [scope.source_ids[0]!] : []), '--json'] } }] : [];
const counts = { deterministic: approved.filter(e => e.tier === 'deterministic').length, llm: llmItems.length, held: held.length, skipped: skipped.length };
- const details: SlugConflictsPreviewDetails = { counts, model: s.llmEnabled ? s.model : null, llm_enabled: s.llmEnabled, diffs, llm_items: llmItems, held, skipped,
+ const details: SlugConflictsPreviewDetails = { counts, model: s.llmEnabled ? s.model : null, llm_enabled: s.llmEnabled, diffs, imports, llm_items: llmItems, held, skipped,
caps: { max_usd_per_page: s.perPageUsd, max_usd_per_day: s.perDayUsd, day_remaining_usd: s.dayRemaining, run_max_usd: s.runMaxUsd }, next_actions };
return { items: approved.map((entry, index) => item(entry, index, null, index === approved.length - 1)), preview_hash: hash, residuals, listing,
...(warnings.length ? { warnings } : {}), details: details as unknown as Record<string, unknown>, llm: { usd: llmUsd, cap_remaining_usd: s.llmEnabled ? s.dayRemaining : 0 } };
@@ -454,6 +503,7 @@ export const slugConflictsRepair: RepairHandler = {
const shown = opts.diff ? d.diffs : d.diffs.slice(0, 1);
for (const diff of shown) lines.push(` deterministic: ${diff.item} (remove_slug, ${diff.rule})`, ...diff.diff.split('\n').map(line => ` ${line}`));
if (!opts.diff && d.diffs.length > shown.length) lines.push(` (one sample diff; --diff or --json shows all ${d.diffs.length})`);
+ for (const entry of d.imports ?? []) lines.push(` import: ${entry.item} (${entry.reason}): sync would import it as it is; it is imported unchanged and its hold clears`);
for (const llm of d.llm_items) lines.push(` model decides: ${llm.item}${llm.named ? ` vs page ${llm.named}` : ' (no page has the named slug)'}: remove_slug, merge_into or needs_human at apply time; est. $${llm.estimate_usd.toFixed(4)}`);
for (const h of d.held) lines.push(` held ${h.item} [${h.reason}]: ${h.resolution}`);
for (const s of d.skipped) lines.push(` skipped ${s.item} [${s.reason}]`);
@@ -496,42 +546,64 @@ async function applyConflict(ctx: OperationContext, entry: ApprovedConflict, opt
return skipped(moved, `${entry.path} or the page its slug: line names changed since it was ${opts.expect ? 'previewed' : 'read'}; preview again with ${shellQuote(contentPreviewArgv(src.id, entry.path))}.`);
}
let slugs: Set<string> | null = null;
- const analysis = analyze(cand, () => (slugs ??= src.root ? checkoutSlugs(src.root) : new Set<string>()));
+ const analysis = await analyze(cand, () => (slugs ??= src.root ? checkoutSlugs(src.root) : new Set<string>()), await syncScreen(engine, src));
if (analysis.status === 'skip') return skipped(analysis.reason, analysis.message);
- if (analysis.status === 'held') return held(analysis.reason, analysis.message, { action: 'remove_slug', reason: analysis.reason, next_attempt_after: null });
+ if (analysis.status === 'held') return held(analysis.reason, analysis.message, { action: 'remove_slug', reason: analysis.reason, ...(analysis.named ? { named: analysis.named } : {}), next_attempt_after: null });
+ if (analysis.status === 'import') {
+ // #6696 C8: the clear is bound to the hold observation the plan read; a hold a sync wrote since is kept and retried.
+ if (opts.expect && cand.hold?.observed_at !== entry.observed_at) {
+ await recordState(engine, cand, { action: 'pending', reason: 'changed_since_read', next_attempt_after: nextAttempt('changed_since_read') });
+ return skipped(moved, `A sync observed ${entry.path} again after it was previewed, so its newer hold is kept; the next run reads that hold and imports the file the same way.`);
+ }
+ return write(ctx, src, cand, cand.content, { action: 'import', tier: 'deterministic', confidence: 'high', model: null, cost_usd: 0 }, opts, held, { reason: analysis.reason }, cand.hold!.observed_at);
+ }
if (analysis.status === 'deterministic') {
if (opts.expect && sha256(Buffer.from(analysis.after, 'utf8')) !== entry.after) return skipped('changed_since_preview', `The repair of ${entry.path} differs from the preview; preview again.`);
- return write(ctx, src, cand, analysis.after, { tier: 'deterministic', confidence: 'high', model: null, cost_usd: 0 }, opts, held, { rule: analysis.rule });
+ return write(ctx, src, cand, analysis.after, { action: 'remove_slug', tier: 'deterministic', confidence: 'high', model: null, cost_usd: 0 }, opts, held, { rule: analysis.rule });
}
return judge(ctx, src, cand, analysis.input, entry, opts, held);
}
type HeldFn = (reason: string, message: string, state: Omit<ContentHoldRepairState, 'at'> | null, extra?: Record<string, unknown>) => Promise<RepairItemOutcome>;
-/** Writes the edited file through the source's path with its receipt; the hold clears in the same write (managed) or right after the import (legacy). */
-async function write(ctx: OperationContext, src: FenceSource, cand: Candidate, after: string, parts: Pick<ContentRepairReceipt, 'tier' | 'confidence' | 'model' | 'cost_usd'>, opts: ApplyOptions, held: HeldFn,
- extra: Record<string, unknown>): Promise<RepairItemOutcome> {
+/**
+ * Writes the edited file through the source's path with its receipt; the hold clears in the same write (managed) or right after the import (legacy).
+ * #6696 C8: `import` writes no file: the held bytes are imported as they are, and the hold clears only while it is still the observation
+ * `observedAt` the repair read (a hold a sync wrote since is kept, with a retry recorded on it).
+ */
+async function write(ctx: OperationContext, src: FenceSource, cand: Candidate, after: string, parts: Pick<ContentRepairReceipt, 'action' | 'tier' | 'confidence' | 'model' | 'cost_usd'>, opts: ApplyOptions, held: HeldFn,
+ extra: Record<string, unknown>, observedAt?: string): Promise<RepairItemOutcome> {
const engine = ctx.engine;
const local = { ...ctx, remote: false, sourceId: src.id } as OperationContext;
- const receipt: ContentRepairReceipt = { actor: CONTENT_REPAIR_ACTOR, hold_code: CONTENT_REPAIR_HOLD_CODE, action: 'remove_slug', ...parts, before_sha256: cand.before, after_sha256: sha256(Buffer.from(after, 'utf8')) };
- const detail = { path: cand.path, slug: cand.slug, action: 'remove_slug', tier: parts.tier, confidence: parts.confidence, ...(cand.namedSlug ? { named: cand.namedSlug } : {}), ...extra };
+ const receipt: ContentRepairReceipt = { actor: CONTENT_REPAIR_ACTOR, hold_code: CONTENT_REPAIR_HOLD_CODE, ...parts, before_sha256: cand.before, after_sha256: sha256(Buffer.from(after, 'utf8')) };
+ const detail = { path: cand.path, slug: cand.slug, action: parts.action, tier: parts.tier, confidence: parts.confidence, ...(cand.namedSlug ? { named: cand.namedSlug } : {}), ...extra };
const spend = parts.cost_usd ? { llm_usd: parts.cost_usd } : {};
+ const what = parts.action === 'import' ? `${cand.path} as it is` : `the repaired ${cand.path}`;
+ const refused = (code: string, how: string, reason = code) => code === 'frontmatter_slug_conflict'
+ ? held('slug_page_mismatch', `Importing ${what} would still be held: sync files it as page ${cand.slug}, but its path derives ${resolveSlugForPath(cand.sourcePath)}, ${how}. `
+ + `By hand: make the slug: line name ${cand.slug} exactly or move the file to the path that derives ${cand.slug}, commit, and run gbrain sync --source ${src.id} --no-pull.`,
+ { action: 'remove_slug', reason: 'slug_page_mismatch', named: resolveSlugForPath(cand.sourcePath), next_attempt_after: null }, spend)
+ : held(reason, `Importing ${what} would be refused (${code}), ${how}.`, { action: 'remove_slug', reason: 'still_invalid', next_attempt_after: null }, spend);
+ const kept = async (cleared: boolean) => {
+ if (!cleared && observedAt && cand.hold) await recordState(engine, cand, { action: 'pending', reason: 'changed_since_read', next_attempt_after: nextAttempt('changed_since_read') });
+ return cleared;
+ };
if (src.managed) {
const config = await repairScreenConfig(engine, src.id);
const publication = await prepareRepairPublication(engine, { sourceId: src.id, slug: cand.slug, sourcePath: cand.sourcePath, path: cand.path, root: src.root!, content: after,
snapshot: cand.snapshot, base: cand.snapshot, ...config });
- if (publication.status === 'refused') return held(publication.refusal.code === 'frontmatter_slug_conflict' ? 'still_invalid' : publication.refusal.code, `Importing the repaired ${cand.path} would be refused (${publication.refusal.code}), so nothing was written.`,
- { action: 'remove_slug', reason: 'still_invalid', next_attempt_after: null }, spend);
- if (publication.status === 'overlay') return held('canonical_overlay', `Importing the repaired ${cand.path} would keep page data the file does not carry (tags added outside the file, a withdrawal or sanitized text), so nothing was written. `
+ if (publication.status === 'refused') return refused(publication.refusal.code, 'so nothing was written');
+ if (publication.status === 'overlay') return held('canonical_overlay', `Importing ${what} would keep page data the file does not carry (tags added outside the file, a withdrawal or sanitized text), so nothing was written. `
+ `Edit the file by hand to carry them (gbrain get --source ${src.id} -- ${cand.slug} shows the page), remove the slug: line, and commit.`, { action: 'remove_slug', reason: 'canonical_overlay', next_attempt_after: null }, spend);
try {
- const outcome = await submitManagedFileRepair(local, { sourceId: src.id, requestId: await repairRequestId(local, 'slug-conflicts', { source_id: src.id, slug: cand.slug }, `${receipt.before_sha256}:${receipt.after_sha256}`),
+ const outcome = await submitManagedFileRepair(local, { sourceId: src.id, requestId: await repairRequestId(local, 'slug-conflicts', { source_id: src.id, slug: cand.slug }, `${receipt.before_sha256}:${receipt.after_sha256}${observedAt ? `:${observedAt}` : ''}`),
slug: cand.slug, path: cand.path, sourcePath: cand.sourcePath, content: after, beforeHash: cand.before, resultDigest: publication.digest,
- ...(cand.snapshot ? { expected_revision: cand.snapshot.revision } : {}), noEmbed: !opts.embed, contentRepair: receipt });
+ ...(cand.snapshot ? { expected_revision: cand.snapshot.revision } : {}), noEmbed: !opts.embed, contentRepair: receipt, ...(observedAt ? { holdObservedAt: observedAt } : {}) });
const persistence = outcome.persistence as { git_state?: string } | undefined;
- return { applied: true, outcome: 'repaired', detail: { ...detail, mode: 'managed', imported: outcome.status, hold_cleared: outcome.hold_cleared === true, committed: persistence?.git_state ?? 'not_requested' }, ...spend };
+ return { applied: true, outcome: 'repaired', detail: { ...detail, mode: 'managed', imported: outcome.status, hold_cleared: await kept(outcome.hold_cleared === true), committed: persistence?.git_state ?? 'not_requested' }, ...spend };
} catch (error) {
if (error instanceof OperationError && ['changed_since_preview', 'revision_conflict', 'page_identity_changed', 'source_changed'].includes(error.code)) {
+ await kept(false);
return { applied: false, outcome: 'skipped', reason: 'changed_since_read', detail: { ...detail, message: `${cand.path} changed while it was being repaired; the next run reads it again.` }, ...spend };
}
if (error instanceof OperationError && error.code === 'sync_in_progress') {
@@ -548,14 +620,16 @@ async function write(ctx: OperationContext, src: FenceSource, cand: Candidate, a
throw error;
}
if (sha256(readFileSync(abs)) !== cand.before) return { applied: false, outcome: 'skipped', reason: 'changed_since_read', detail: { ...detail, message: `${cand.path} changed after the repair read it, so nothing was written.` }, ...spend };
- const backup = createFrontmatterBackup(abs, { sourcePath: root, backupRoot: gbrainPath('backups', 'content-repair', makeFrontmatterBackupRunId()) });
- writeFileSync(abs, after);
+ const edits = after !== cand.content;
+ const backup = edits ? createFrontmatterBackup(abs, { sourcePath: root, backupRoot: gbrainPath('backups', 'content-repair', makeFrontmatterBackupRunId()) }) : null;
+ if (edits) writeFileSync(abs, after);
const imported = await importFromFile(engine, abs, cand.sourcePath, { sourceId: src.id, noEmbed: !opts.embed });
if (imported.status === 'error' || imported.refusal) {
- writeFileSync(abs, cand.content);
- return held('still_invalid', `The repaired ${cand.path} did not import (${imported.refusal?.code ?? 'error'}), so the file was restored from its backup.`, { action: 'remove_slug', reason: 'still_invalid', next_attempt_after: null }, spend);
+ if (edits) writeFileSync(abs, cand.content);
+ return refused(imported.refusal?.code ?? 'error', edits ? 'so the file was restored from its backup' : 'so the hold stays', 'still_invalid');
}
- const holdCleared = cand.hold ? await clearGitHold(engine, { sourceId: src.id, incarnation: src.incarnation, path: cand.path, observedAt: new Date().toISOString() }) : false;
+ const holdCleared = cand.hold ? await kept(await clearGitHold(engine, { sourceId: src.id, incarnation: src.incarnation, path: cand.path, observedAt: observedAt ?? new Date().toISOString() })) : false;
+ if (!edits) return { applied: true, outcome: 'repaired', detail: { ...detail, mode: 'legacy', imported: imported.status, hold_cleared: holdCleared, content_repair: receipt }, ...spend };
const commitStep = `git -C ${shellQuote([root])} add -- ${shellQuote([cand.path])} && git -C ${shellQuote([root])} commit -m ${shellQuote([contentRepairCommitSubject(cand.path)])} -m ${shellQuote([contentRepairTrailer(receipt)])} -- ${shellQuote([cand.path])}`;
return { applied: true, outcome: 'repaired', detail: { ...detail, mode: 'legacy', backup, imported: imported.status, hold_cleared: holdCleared, content_repair: receipt, committed: 'commit_step', commit_step: commitStep }, ...spend };
}
@@ -578,7 +652,7 @@ async function judge(ctx: OperationContext, src: FenceSource, cand: Candidate, i
if (!result.ok) {
const spend = result.spentUsd ? { llm_usd: result.spentUsd } : {};
if (result.reason === 'claimed_elsewhere') return { applied: false, outcome: 'skipped', reason: 'claimed_elsewhere', detail: { path: cand.path, slug: cand.slug, message: result.message }, ...spend };
- if (result.memoHit && result.reason === 'remove_slug') return write(ctx, src, cand, removeSlugLine(cand.content, cand.sourcePath, cand.path, src.activePack)!, { tier: 'llm', confidence: 'medium', model, cost_usd: 0 }, opts, held, { memo: 'judged_before' });
+ if (result.memoHit && result.reason === 'remove_slug') return write(ctx, src, cand, removeSlugLine(cand.content, cand.sourcePath, src.activePack)!, { action: 'remove_slug', tier: 'llm', confidence: 'medium', model, cost_usd: 0 }, opts, held, { memo: 'judged_before' });
if (result.memoHit) {
const state = cand.hold?.meta.content_repair;
const out = await held(result.reason, result.message, state && state.reason === result.reason ? null : { action: result.reason === 'merge_recommended' ? 'merge_into' : result.reason === 'content_repair_needs_human' ? 'needs_human' : 'pending',
@@ -604,9 +678,9 @@ async function judge(ctx: OperationContext, src: FenceSource, cand: Candidate, i
const spend = result.spentUsd ? { llm_usd: result.spentUsd } : {};
const why = verdict.why ? { why: verdict.why } : {};
if (verdict.action === 'remove_slug') {
- const after = removeSlugLine(cand.content, cand.sourcePath, cand.path, src.activePack);
+ const after = removeSlugLine(cand.content, cand.sourcePath, src.activePack);
if (after === null) { await store.reject(result.claim, { reason: 'still_invalid' }); return held('still_invalid', `The model chose remove_slug for ${cand.path}, but removing the line alone does not make it importable.`, { action: 'remove_slug', reason: 'still_invalid', model, next_attempt_after: null }, { ...why, ...spend }); }
- const written = await write(ctx, src, cand, after, { tier: 'llm', confidence: 'medium', model, cost_usd: result.spentUsd }, opts, held, why);
+ const written = await write(ctx, src, cand, after, { action: 'remove_slug', tier: 'llm', confidence: 'medium', model, cost_usd: result.spentUsd }, opts, held, why);
if (written.applied) await store.publish(result.claim);
else if (written.reason === 'changed_since_read' || written.reason === 'sync_in_progress') await store.transient(result.claim, written.reason);
else await store.reject(result.claim, { reason: written.reason ?? 'still_invalid' });
diff --git a/test/repair-slug-conflicts-sync-screen.test.ts b/test/repair-slug-conflicts-sync-screen.test.ts
new file mode 100644
index 0000000000..9ff3bdf33c
--- /dev/null
+++ b/test/repair-slug-conflicts-sync-screen.test.ts
@@ -0,0 +1,191 @@
+/**
+ * #6696 C8: the slug-conflict repair judges a held file with the same screen
+ * managed sync froze it with (`frozenImportScreenInput` + `loadSyncScreenRun`),
+ * so the repair and the next sync agree on whether the file is still held.
+ *
+ * Protects: a slug: line in a source that is a subdirectory of its Git
+ * repository under `slug_root_mode=git-root` (the page slug carries the
+ * directory) is removed and imported instead of being held `still_invalid`;
+ * a hold the screen would now admit (the file's own page records it) is
+ * cleared through a guarded canonical import instead of being skipped as
+ * `already_exempt` forever; a slug: line resolving to the own page only
+ * through an alias, which sync still holds, is held `slug_page_mismatch`
+ * naming both slugs instead of `already_exempt`; the clear is bound to the
+ * hold observation the repair read, so a newer hold is preserved and the
+ * hold keeps a durable retry.
+ * Fails when: the repair screens a file differently from sync (a hold the
+ * repair calls clean or exempt survives every run, or an edit sync would
+ * import is refused), or a repair clears a hold a newer sync wrote.
+ * Why new: C8 of the #6696 fix wave.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { gitHoldItem, readGitSourceHolds, writeGitHold } from '../src/core/persistence/sync-holds.ts';
+import { prepareRepairPublication, repairScreenConfig, submitManagedFileRepair } from '../src/core/persistence/file-repair.ts';
+import { sha256 } from '../src/core/persistence/digest.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { CONTENT_REPAIR_ACTOR, CONTENT_REPAIR_HOLD_CODE, parseContentRepairReceipt, type ContentRepairReceipt } from '../src/core/content-repair/receipt.ts';
+import { resolveRepairScope, type RepairResult } from '../src/core/repair/core.ts';
+import { repairRunner } from '../src/core/repair/registry.ts';
+import type { SlugConflictsPreviewDetails } from '../src/core/repair/slug-conflicts.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-slug-conflicts-sync-screen-'));
+let engine: PGLiteEngine;
+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string, message = 'content') => { git(root, 'add', '-A'); git(root, 'commit', '-qm', message); };
+const quiet = { info() {}, warn() {}, error() {} };
+const page = (title: string, type: string, body: string, extra = '') => `---\ntitle: ${title}\ntype: ${type}\n${extra}---\n${body}\n`;
+
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);
+afterAll(async () => {
+ await withEnv(env, async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });
+ rmSync(home, { recursive: true, force: true });
+});
+
+/** A managed source; `subdir` makes the source a directory of its Git repository with slugs pinned to the Git root. */
+async function managed(files: Record<string, string>, subdir?: string) {
+ const id = `c8-${randomUUID().replace(/-/g, '').slice(0, 16)}`, gitRoot = join(home, id), root = subdir ? join(gitRoot, subdir) : gitRoot;
+ mkdirSync(root, { recursive: true }); git(gitRoot, 'init', '-q');
+ git(gitRoot, 'config', 'user.name', 'Example'); git(gitRoot, 'config', 'user.email', '[email protected]');
+ const write = (path: string, content: string) => { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), content); };
+ for (const [path, content] of Object.entries(files)) write(path, content);
+ commit(gitRoot, 'fixture');
+ writeFileSync(join(gitRoot, '.git', 'hooks', 'post-commit'), '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\n'); chmodSync(join(gitRoot, '.git', 'hooks', 'post-commit'), 0o755);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)", [id, root, JSON.stringify(subdir ? { slug_root_mode: 'git-root' } : {})]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const sync = () => performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true });
+ const holds = async () => (await readGitSourceHolds(engine, { sourceIds: [id] }))[0]?.holds ?? [];
+ const run = async (opts: { apply?: boolean; expect?: string } = {}) => {
+ const runner = await repairRunner(engine, { apply: opts.apply === true, noEmbed: true, logger: quiet });
+ return runner.run('slug-conflicts', await resolveRepairScope(engine, id), { explicit: true, sourceFlag: id, expect: opts.expect, noLlm: true });
+ };
+ return { id, root, gitRoot, write, sync, holds, run, read: (path: string) => readFileSync(join(root, path), 'utf8') };
+}
+
+const details = (result: RepairResult) => result.details as unknown as SlugConflictsPreviewDetails;
+const hashOf = (result: RepairResult) => result.apply_command.split('--expect ')[1]!.split(' ')[0]!;
+const classes = (result: RepairResult) => result.listing!.map(entry => [entry.item.split(':').slice(1).join(':'), entry.class]);
+
+function each(run: () => Promise<void>) {
+ return withEnv(env, async () => { try { await run(); } finally { await disposePersistenceConsumer(engine); } });
+}
+
+/** The state an older gbrain left: the page the file's slug: line names records the file as its origin, and a hold from before still stands. */
+async function ownPageRecordsTheFile(sourceId: string, slug: string, sourcePath: string) {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.putPage(slug, { type: 'company', title: 'Acme Example', compiled_truth: 'An older import of the company page.' }, { sourceId });
+ await engine.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2', [sourceId, slug, sourcePath]);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+}
+
+test('a git-root source in a subdirectory: the slug: line is removed and imported (the page slug carries the directory), not held still_invalid', () => each(async () => {
+ const s = await managed({ 'companies/acme-example.md': page('Acme Example', 'company', 'A synthetic company.', 'slug: acme-example\n') }, 'brain');
+ expect((await s.sync()).held_count).toBe(1);
+ const [hold] = await s.holds();
+ expect(hold).toMatchObject({ path: 'companies/acme-example.md', source_path: 'brain/companies/acme-example.md', slug: 'brain/companies/acme-example', code: 'frontmatter_slug_conflict' });
+ const preview = await s.run();
+ expect(classes(preview)).toEqual([['companies/acme-example.md', 'deterministic']]);
+ expect(details(preview).diffs.map(d => d.rule)).toEqual(['absent_page']);
+ const applied = await s.run({ apply: true, expect: hashOf(preview) });
+ expect(applied).toMatchObject({ applied: 1, repaired: 1 });
+ expect(s.read('companies/acme-example.md')).not.toContain('slug:');
+ expect(await s.holds()).toEqual([]);
+ expect((await engine.getPage('brain/companies/acme-example', { sourceId: s.id }))?.compiled_truth).toContain('A synthetic company.');
+}), 240_000);
+
+test('a hold the sync screen now admits (the own page records the file) is cleared through a guarded canonical import, not skipped already_exempt', () => each(async () => {
+ const s = await managed({ 'companies/acme-example.md': page('Acme Example', 'company', 'The company as the file has it.', 'slug: acme-example\n') });
+ expect((await s.sync()).held_count).toBe(1);
+ await ownPageRecordsTheFile(s.id, 'acme-example', 'companies/acme-example.md');
+ const preview = await s.run();
+ expect(classes(preview)).toEqual([['companies/acme-example.md', 'import']]);
+ expect(s.read('companies/acme-example.md')).toContain('slug: acme-example');
+ const applied = await s.run({ apply: true, expect: hashOf(preview) });
+ expect(applied).toMatchObject({ applied: 1, repaired: 1 });
+ expect(applied.outcome_items![0]).toMatchObject({ outcome: 'repaired', detail: { action: 'import', hold_cleared: true } });
+ // The file is untouched; its page now carries the held bytes.
+ expect(s.read('companies/acme-example.md')).toContain('slug: acme-example');
+ expect(await s.holds()).toEqual([]);
+ expect((await engine.getPage('acme-example', { sourceId: s.id }))?.compiled_truth).toContain('The company as the file has it.');
+ expect(git(s.root, 'status', '--porcelain')).toBe('');
+}), 240_000);
+
+test('the clear is bound to the hold observation the repair read: a newer hold is preserved and keeps a durable retry', () => each(async () => {
+ const s = await managed({ 'companies/acme-example.md': page('Acme Example', 'company', 'The company as the file has it.', 'slug: acme-example\n') });
+ expect((await s.sync()).held_count).toBe(1);
+ await ownPageRecordsTheFile(s.id, 'acme-example', 'companies/acme-example.md');
+ const preview = await s.run();
+ expect(classes(preview)).toEqual([['companies/acme-example.md', 'import']]);
+ // A sync observes the path again after the preview read it.
+ const [held] = await s.holds();
+ // Newer than the observation the repair read, older than the publication.
+ const newer = new Date(Date.parse(held!.observed_at) + 1).toISOString();
+ await engine.transaction(tx => writeGitHold(tx, { ...held!, observed_at: newer }));
+ const applied = await s.run({ apply: true, expect: hashOf(preview) });
+ expect(applied).toMatchObject({ applied: 0 });
+ expect(applied.outcome_items![0]).toMatchObject({ outcome: 'skipped', reason: 'changed_since_preview' });
+ const [kept] = await s.holds();
+ expect(kept).toMatchObject({ path: 'companies/acme-example.md', observed_at: newer });
+ expect(kept!.meta.content_repair).toMatchObject({ action: 'pending', reason: 'changed_since_read' });
+ expect(Date.parse(kept!.meta.content_repair!.next_attempt_after!)).toBeGreaterThan(Date.now());
+ expect(gitHoldItem(kept!).fix.why).toContain('tries again');
+ // The next run reads the newer observation and clears it the same way.
+ const again = await s.run({ apply: true });
+ expect(again).toMatchObject({ applied: 1, repaired: 1 });
+ expect(await s.holds()).toEqual([]);
+}), 240_000);
+
+test('the publishing transaction clears only the bound observation: an import bound to an older hold keeps the newer one; an import receipt must name unchanged bytes', () => each(async () => {
+ const path = 'companies/acme-example.md', content = page('Acme Example', 'company', 'The company as the file has it.', 'slug: acme-example\n');
+ const s = await managed({ [path]: content });
+ expect((await s.sync()).held_count).toBe(1);
+ await ownPageRecordsTheFile(s.id, 'acme-example', path);
+ const [held] = await s.holds();
+ // Newer than the observation the repair read, older than the publication.
+ const newer = new Date(Date.parse(held!.observed_at) + 1).toISOString();
+ await engine.transaction(tx => writeGitHold(tx, { ...held!, observed_at: newer }));
+ const snapshot = await engine.readPageSnapshot('acme-example', { sourceId: s.id, includeDeleted: true });
+ const publication = await prepareRepairPublication(engine, { sourceId: s.id, slug: 'acme-example', sourcePath: path, path, root: s.root, content, snapshot, base: snapshot, ...await repairScreenConfig(engine, s.id) });
+ expect(publication.status).toBe('ready');
+ const before = sha256(Buffer.from(content, 'utf8'));
+ const receipt: ContentRepairReceipt = { actor: CONTENT_REPAIR_ACTOR, hold_code: CONTENT_REPAIR_HOLD_CODE, action: 'import', tier: 'deterministic', confidence: 'high', model: null, cost_usd: 0, before_sha256: before, after_sha256: before };
+ const ctx = { engine, config: { engine: engine.kind }, logger: quiet, dryRun: false, remote: false, sourceId: s.id } as unknown as OperationContext;
+ const outcome = await submitManagedFileRepair(ctx, { sourceId: s.id, requestId: randomUUID(), slug: 'acme-example', path, sourcePath: path, content, beforeHash: before,
+ resultDigest: publication.status === 'ready' ? publication.digest : '', expected_revision: snapshot!.revision, noEmbed: true, contentRepair: receipt, holdObservedAt: held!.observed_at });
+ expect(outcome).toMatchObject({ state: 'committed', file_repaired: false, hold_cleared: false, content_repair: receipt });
+ expect((await s.holds())[0]).toMatchObject({ path, observed_at: newer });
+ expect(parseContentRepairReceipt({ ...receipt, after_sha256: 'c'.repeat(64) })).toBeNull();
+}), 240_000);
+
+test('a slug: line resolving to the own page only through an alias, which sync holds, is slug_page_mismatch naming both slugs, not already_exempt', () => each(async () => {
+ const s = await managed({ 'people/carol-example.md': page('Carol Example', 'person', 'A synthetic person.') });
+ await s.sync();
+ await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.write_sources', $1, true)", [JSON.stringify([s.id])]);
+ await tx.executeRaw('INSERT INTO slug_aliases (source_id, alias_slug, canonical_slug) VALUES ($1, $2, $3)', [s.id, 'people/carol', 'people/carol-example']);
+ });
+ s.write('people/carol-example.md', page('Carol Example', 'person', 'A synthetic person.', 'slug: people/carol\n')); commit(s.root, 'alias slug');
+ expect((await s.sync()).held_count).toBe(1);
+ const preview = await s.run();
+ expect(classes(preview)).toEqual([['people/carol-example.md', 'slug_page_mismatch']]);
+ const resolution = details(preview).held[0]!.resolution;
+ expect(resolution).toContain('people/carol');
+ expect(resolution).toContain('people/carol-example');
+ const applied = await s.run({ apply: true });
+ expect(applied).toMatchObject({ applied: 0, remaining: { slug_page_mismatch: 1 } });
+ const [kept] = await s.holds();
+ expect(kept!.meta.content_repair).toMatchObject({ action: 'remove_slug', reason: 'slug_page_mismatch', named: 'people/carol-example' });
+ expect(gitHoldItem(kept!).fix.why).toContain('people/carol-example');
+}), 240_000);
diff --git a/test/repair-slug-conflicts.test.ts b/test/repair-slug-conflicts.test.ts
index 7c55ea0444..2ed89dbba4 100644
--- a/test/repair-slug-conflicts.test.ts
+++ b/test/repair-slug-conflicts.test.ts
@@ -7,8 +7,8 @@
* no title word in common, through the coordinated file repair (file
* rewritten, imported, hold cleared, Git commit `gbrain: repair frontmatter
* slug in <path>` with the `gbrain-repair:` trailer, a content_repair
- * receipt); a slug that resolves through an alias to the file's own page is
- * `already_exempt`; a duplicate pair goes to the model tier at apply time
+ * receipt); a slug that resolves through an alias to the file's own page,
+ * which sync still holds, is `slug_page_mismatch` (#6696 C8); a duplicate pair goes to the model tier at apply time
* while the preview calls no model; a stubbed `merge_into` writes nothing,
* records the verdict on the hold as codes and slugs, and `sync status`
* renders `needs_human` with a paragraph naming the canonical; a stubbed
@@ -126,7 +126,7 @@ test('registry: preview-bound, spends llm, clears no doctor check, not explicit-
expect(parseRepairArgs(['slug-conflicts', '--source', 's', '--only', 'notes/a.md', '--no-llm', '--apply', '--expect', 'abc'])).toMatchObject({ kind: 'slug-conflicts', only: ['notes/a.md'], noLlm: true, expect: 'abc' });
});
-test('deterministic tier: a stray slug (no page, no file) and a slug naming a page of another type lose the line; an alias to the own page is exempt; the preview writes nothing', () => each(async () => {
+test('deterministic tier: a stray slug (no page, no file) and a slug naming a page of another type lose the line; an alias to the own page, which sync holds, is slug_page_mismatch; the preview writes nothing', () => each(async () => {
const s = await managed({
'companies/acme-example.md': page('Acme Widgets', 'company', 'A synthetic company.'),
'people/carol-example.md': page('Carol Example', 'person', 'A synthetic person.'),
@@ -134,7 +134,7 @@ test('deterministic tier: a stray slug (no page, no file) and a slug naming a pa
'people/bob-example.md': page('Bob Example', 'person', 'A synthetic person who works at the company.', 'slug: companies/acme-example\n'),
});
expect((await s.sync()).held_count).toBe(2);
- // An alias to the file's own page: held by the screen, exempt for the lane.
+ // An alias to the file's own page: held by the screen, so the lane (#6696 C8: the same screen) keeps it as slug_page_mismatch.
await engine.transaction(async tx => {
await tx.executeRaw("SELECT set_config('gbrain.write_sources', $1, true)", [JSON.stringify([s.id])]);
await tx.executeRaw('INSERT INTO slug_aliases (source_id, alias_slug, canonical_slug) VALUES ($1, $2, $3)', [s.id, 'people/carol', 'people/carol-example']);
@@ -145,8 +145,8 @@ test('deterministic tier: a stray slug (no page, no file) and a slug naming a pa
const preview = await s.run();
expect(calls).toHaveLength(0);
expect(preview.listing!.map(entry => [entry.item, entry.class]).sort()).toEqual([
- [`${s.id}:notes/stray.md`, 'deterministic'], [`${s.id}:people/bob-example.md`, 'deterministic'], [`${s.id}:people/carol-example.md`, 'already_exempt']]);
- expect(details(preview).counts).toEqual({ deterministic: 2, llm: 0, held: 0, skipped: 1 });
+ [`${s.id}:notes/stray.md`, 'deterministic'], [`${s.id}:people/bob-example.md`, 'deterministic'], [`${s.id}:people/carol-example.md`, 'slug_page_mismatch']]);
+ expect(details(preview).counts).toEqual({ deterministic: 2, llm: 0, held: 1, skipped: 0 });
expect(details(preview).diffs.map(d => d.rule).sort()).toEqual(['absent_page', 'different_type']);
expect(details(preview).diffs[0]!.diff).toContain('-slug: ');
expect(preview.cost.llm_usd).toBe(0);
@@ -171,7 +171,7 @@ test('deterministic tier: a stray slug (no page, no file) and a slug naming a pa
expect(git(s.root, 'log', '-1', '--format=%(trailers:key=gbrain-repair,valueonly)')).toMatch(/^frontmatter_slug_conflict deterministic high/);
expect(git(s.root, 'status', '--porcelain')).toBe('');
expectNoSecrets([holds, rows, surfaceOf(applied), log]);
- // The hold fix of the remaining (exempt) hold names the content repair preview.
+ // The hold fix of the remaining (slug_page_mismatch) hold names the content repair preview.
expect(gitHoldItem(holds[0]!).fix.argv).toEqual(['gbrain', 'repair', 'content', '--source', s.id, '--only', 'people/carol-example.md']);
}), 240_000);