Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(markdown): stamp a slug the file path cannot derive, and repair legacy files (#5966)

garrytana56ad7349230
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.md
index 0872b10c86..c228a64278 100644
--- a/docs/architecture/key-files/canonical-reconciliation.md
+++ b/docs/architecture/key-files/canonical-reconciliation.md
@@ -4,7 +4,7 @@
- `src/core/persistence/reconcile*.ts` — trusted-local exact-page reconciliation: loss-preserving semantic preview, explicit JSON Pointer choices, pinned identity/revision/raw-file/policy checks, durable private preimages and same-ID replay through the existing coordinator. Normal overwrite protection stays unchanged. The bounded audit reports source-scoped drift without repair or checkpoint changes; a database-only page (`isDatabaseOnlyPage`, with no file at its slug-derived path) counts as `database_only` with no reconcile suggestion, never as drift, while a legacy row that merely lacks `source_path` is audited as usual. `src/commands/source-reconcile.ts` provides strict CLI parsing, private artifact I/O, brain routing and resident-owner delegation; the operations stay outside public MCP. Operator flow: `docs/guides/concurrent-writes.md`. Tests cover merge choices, both engines, grants, stale previews, read-only audit, and private files. A database-only page (no `source_path`, no `source_uri`; `isDatabaseOnlyPage` in `src/core/persistence/unbound-pages.ts`) is matched to the canonical file at its slug-derived path (`ReconcileState.origin: 'slug_derived'`), and apply records that path as its `source_path` (the #5254 unbound collision; `test/reconcile-unbound-collision.test.ts`). Private fact rows (#6137): `reconcile-prepare.ts` `privateFactViolation` identifies a fact row by (row number, claim), as `restoreHiddenFactRows` does. A stored non-world row carried at its identity must be unchanged; a row at no stored identity may not carry a stored private claim under another visibility, and a world row may not carry (or newly gain) a stored private row's context of 24 or more characters verbatim; sources are not compared. The `permission_denied` refusal names only the row number, with a `gbrain get` read fix. It guards verbatim copies, not reworded text. #6138: an `--auto-additive` preview classified `no_drift` asks Git (`hardened-git.ts` `hardenedPathDirty`: filter-free plumbing, never `git status`, so the checkout's clean/process filters never run; `null` when only repository config could decide) whether the canonical file differs from its last commit and returns `git_dirty`; a dirty file's `next_action` says the content agrees, the difference is only how it is written, reconcile does not commit, and names `git -C <root> diff -- <file>` (committing it is the user's decision; the managed commit path is deferred, D5). The "retry the original write" step is conditional on the preview coming from a refused write. Tests: `test/persistence-reconcile-git-dirty-6138.test.ts`. #6222/#6254: `assertSoleFileClaim` (reconcile-state.ts) pages the "no other page claims this file" census 100 rows at a time below the source's highest page id, so a common file name no longer refuses; realpath still decides each candidate. Its predicates (`fileClaimCandidatesSql`) match the v219 expression indexes `pages_source_path_name_idx` and `pages_file_uri_name_idx` (built online, one statement per call). `sources reconcile` help says writes to one source publish one at a time. Tests: `test/persistence-reconcile.test.ts`, `test/e2e/pages-reconcile-name-indexes-postgres.test.ts`.
-- `src/core/persistence/reconcile-additive.ts` (#5974) — pure structural drift classifier over the complete file/database delta: inserted whole lines (two-pointer subsequence, CRLF-normalized; fence, heading and table insertions excluded) are `suggested`; an append-only `contacts` list, an allowlisted activity date moving forward, and one-sided ordinary fields are `auto`; policy/privacy/identity/tag changes and everything else are `review`. `--auto-additive` previews write `take_file` only for `auto` (and `suggested` with `--accept-suggested`), recorded as format-2 `auto_decisions` with an evidence digest that apply and owner preparation recheck. `--audit --classify` reports per-page verdicts and counts, never values.
+- `src/core/persistence/reconcile-additive.ts` (#5974) — pure structural drift classifier over the complete file/database delta: inserted whole lines (two-pointer subsequence, CRLF-normalized; fence, heading and table insertions excluded) are `suggested`; an append-only `contacts` list, an allowlisted activity date moving forward, and one-sided ordinary fields are `auto`; policy/privacy/identity/tag changes and everything else are `review`. `--auto-additive` previews write `take_file` only for `auto` (and `suggested` with `--accept-suggested`), recorded as format-2 `auto_decisions` with an evidence digest that apply and owner preparation recheck. `--audit --classify` reports per-page verdicts and counts, never values; #5966 (W14 P1.7) adds the `slug_rule_mismatch` verdict (a legacy unstamped file of a slug the path cannot derive, fix: `gbrain repair frontmatter`) read from `readReconcileState`'s refusal (`detail: slug_rule_mismatch` once the wave-13 `reconcile-state.ts` hunk lands; until then an `invalid_params` refusal on a non-fixed-point slug).
- `src/core/persistence/publication-failure.ts` (#5974) — maps a P0001 from the managed-writer guard (which raises TABLE/SCHEMA, `managed_writer_guard:<branch>` and a JSON DETAIL) or another trigger to a bounded `error_detail` (origin, raiser, table, op, branch, relationship, stage, plus owner-only source ids and the attempt's build/host). Receipts expose only `publicFailureDetail`; `sources writer status` lists the full detail under `recent_failures`. #5929: `ownerExceptionFailure` (the coordinator `requestError` fallback) keeps an unexpected exception's class, errno and top `src/...:line` frame as `origin: owner_exception` (never its message), so `withAttempt` stamps the build; `publicFailureDetail` is an allow-list (origin, sqlstate, raiser, table, op, branch, relationship, stage, fence), so `error_class`/`errno`/`frame`, `sources` and `attempt` stay owner-only; `ownerBuildMismatch` drives the local `owner_build` receipt field (`ops/persistence.ts`) and the submit-time why/fix (`page-mutations.ts`), and `ownerExceptionLogText` the consumer log line.
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index 07a4aacd56..82d1c5cbc8 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -17,7 +17,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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/frontmatter.ts` — `gbrain repair frontmatter` (#5988), explicit-only, preview-bound, destructive consent (`--yes` with the hash, registry `consent`). 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/repair/frontmatter.ts` — `gbrain repair frontmatter` (#5988), explicit-only, preview-bound, destructive consent (`--yes` with the hash, registry `consent`). #5966 (W14 P1.7): `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`.
- `src/core/restore-target.ts` -- `resolveRestoreTarget(engine, source, repo)`: the source and repo `gbrain export --restore-only` restores, shared with `gbrain storage status` so its printed restore command restores exactly the files it lists. An explicit source (already resolved) wins; a repo without a source selects the one active source registered at that exact path, refuses a repo registered only to an archived source, else selects the only active source; neither selects the flagless resolver chain's source and its `local_path` (the legacy `sync.repo_path` answers for `default` only). `restoreFilePath(repo, slug, sourcePath, sourcePathBytes, slugRootMode)` is the file whose absence makes the restore write a page: the recorded `source_path` resolved in the repo in the source's slug-root mode (`scannerSlugRootMode`), else `<slug>.md`; an over-long or unsafe recorded path throws. Refusals throw `RestoreTargetError`; resolver and database errors propagate unchanged.
diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.md
index b446a7da6c..4e83f0f61f 100644
--- a/docs/architecture/key-files/files-and-sync-1.md
+++ b/docs/architecture/key-files/files-and-sync-1.md
@@ -33,7 +33,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/link-source-check-repair.ts` — schema-drift self-heal for the `links_link_source_check` CHECK constraint (third instance of the `timeline-dedup-repair.ts` / `pages-upsert-arbiter.ts` class). Migration v114 opened `link_source` from a closed allowlist to the kebab-case gate; the migrator trusts the version ledger, so a brain stamped >= 114 whose live constraint reverted to the pre-v114 allowlist (drifted restore, manual DDL) rejects every kebab provenance write (`atom-provenance`, `concept-provenance`) while the ledger reads current. `LINK_SOURCE_KEBAB_RE` is the ONE exported copy of the regex (a drift-guard test pins it to the literal in migrate.ts v114, `schema.sql`, `pglite-schema.ts`). `checkLinkSourceCheck(engine)` probes `pg_constraint` (`pg_get_constraintdef` + `convalidated`) and classifies the drift as `absent` / `wrong_def` / `not_validated` (read-only; powers the `links_link_source_check` doctor check in `doctor/checks/core-health.ts`, whose severity follows what writes do: only `wrong_def` rejects kebab writes → fail; `absent` / `not_validated` still accept them → warn). `repairLinkSourceCheck(engine)` first COUNTs rows that fail the gate and returns `reason: 'violations'` WITHOUT any DDL when there are any (the prior constraint survives; rows are never touched; a brain with a bad row never pays for a failing ALTER at every engine open), then restores v114's definition mirroring the migration's engine split: Postgres runs DROP + `ADD ... NOT VALID` in one `engine.transaction` (atomic, no scan) and `VALIDATE CONSTRAINT` as a separate `engine.runMigration` outside it (SHARE UPDATE EXCLUSIVE, never a plain ADD's ACCESS EXCLUSIVE + full-table scan), with a `not_validated` drift getting the VALIDATE only; PGLite keeps the one-shot DROP+ADD transaction. A DDL failure re-counts violators (a row written between probe and ALTER) and rethrows when there are none. `LINK_SOURCE_GATE_MIGRATION_VERSION` (114) is the ledger gate `runMigrations` applies before calling it. Pinned by `test/link-source-check-repair.test.ts` (PGLite, incl. a recording-engine assertion that violators trigger no DDL and that a sub-114 ledger never probes) and the DATABASE_URL-gated `test/e2e/link-source-check-repair-postgres.test.ts` (two-phase DDL sequence on real Postgres).
-- `src/core/markdown.ts` — Frontmatter parsing + body splitter. `coerceFrontmatterString(v)` coerces a non-string `title`/`slug`/`type` to a deterministic string at parse time so a YAML-typed value never reaches `.toLowerCase()` and throws (`title: 2024-06-01` parses as a `Date`, `title: 1458` as a number, and a throw would block the sync bookmark from advancing); a `Date` becomes its UTC ISO date (`2024-06-01`, machine-independent and matching the on-disk token, unlike `String(date)`), `null`/`undefined` become `''`, everything else uses `String()`. `splitBody` requires an explicit timeline sentinel (`<!-- timeline -->`, `--- timeline ---`, or `---` immediately before `## Timeline`/`## History`). Plain `---` in body text is a markdown horizontal rule, not a separator. `inferType` auto-types `/wiki/analysis/` → analysis, `/wiki/guides/` → guide, `/wiki/hardware/` → hardware, `/wiki/architecture/` → architecture, `/writing/` → writing (plus existing people/companies/deals/etc heuristics). `resolveSourceLocalFilePath` maps Git-root-relative `pages.source_path` values into a source whose `local_path` scopes a repo subdirectory; it finds the Git root with filesystem checks only, strips the exact root-relative scope, rejects unsafe/non-markdown paths, and when given a slug it tolerates historical basename-relative `source_path` rows by checking the slug directory only after the direct path is absent. It leaves write containment to the caller. After its pre-quote pass, a block the strict parse refuses goes to `recoverFrontmatter`; only `quote` recoveries are applied. Under `validate`, YAML_PARSE stays in `errors` (location-only message, `recoverable` plus a content-free `recovery` record), advisories go to `warnings` (`FRONTMATTER_RECOVERED`, `FRONTMATTER_COMMENT_VALUE`), and `recovery` carries interpretive, protected-key and identity-key findings. `HOLD_CODES` and `classifyImportHold(parsed, ctx)` define the ingestion hold set once; `isFrontmatterHoldMessage` recognizes its exact messages. Tests: `test/frontmatter-recovery.test.ts`.
+- `src/core/markdown.ts` — #5966 (W14 P1.7): `slugStampedFrontmatter(slug, frontmatter)` is the one slug rule every render follows (`serializePageToMarkdown` and `commands/export.ts`): a slug the path cannot derive (a doubled hyphen `slugifyPath` collapses) is stamped `slug:`, and a `frontmatter.slug` naming another identity is replaced by the page slug; digest-neutral because `parseMarkdown` drops `frontmatter.slug` (`test/slug-stamp-double-hyphen.test.ts`). Frontmatter parsing + body splitter. `coerceFrontmatterString(v)` coerces a non-string `title`/`slug`/`type` to a deterministic string at parse time so a YAML-typed value never reaches `.toLowerCase()` and throws (`title: 2024-06-01` parses as a `Date`, `title: 1458` as a number, and a throw would block the sync bookmark from advancing); a `Date` becomes its UTC ISO date (`2024-06-01`, machine-independent and matching the on-disk token, unlike `String(date)`), `null`/`undefined` become `''`, everything else uses `String()`. `splitBody` requires an explicit timeline sentinel (`<!-- timeline -->`, `--- timeline ---`, or `---` immediately before `## Timeline`/`## History`). Plain `---` in body text is a markdown horizontal rule, not a separator. `inferType` auto-types `/wiki/analysis/` → analysis, `/wiki/guides/` → guide, `/wiki/hardware/` → hardware, `/wiki/architecture/` → architecture, `/writing/` → writing (plus existing people/companies/deals/etc heuristics). `resolveSourceLocalFilePath` maps Git-root-relative `pages.source_path` values into a source whose `local_path` scopes a repo subdirectory; it finds the Git root with filesystem checks only, strips the exact root-relative scope, rejects unsafe/non-markdown paths, and when given a slug it tolerates historical basename-relative `source_path` rows by checking the slug directory only after the direct path is absent. It leaves write containment to the caller. After its pre-quote pass, a block the strict parse refuses goes to `recoverFrontmatter`; only `quote` recoveries are applied. Under `validate`, YAML_PARSE stays in `errors` (location-only message, `recoverable` plus a content-free `recovery` record), advisories go to `warnings` (`FRONTMATTER_RECOVERED`, `FRONTMATTER_COMMENT_VALUE`), and `recovery` carries interpretive, protected-key and identity-key findings. `HOLD_CODES` and `classifyImportHold(parsed, ctx)` define the ingestion hold set once; `isFrontmatterHoldMessage` recognizes its exact messages. Tests: `test/frontmatter-recovery.test.ts`.
- `src/core/quarantine.ts` — the two frontmatter markers the content-quality gate writes, sibling of `src/core/embed-skip.ts` (same JSONB-object marker and `?` existence check on both engines; no migration). `quarantine` (key `QUARANTINE_KEY`) HIDES: set ONLY for high-confidence junk, writes zero chunks, excluded from search via `quarantineFilterFragment(pageAlias)` / `QUARANTINE_FILTER_FRAGMENT` (the `p`-aliased constant), the single source of truth `buildVisibilityClause` calls so the search filter and marker key can't drift. `content_flag` (key `CONTENT_FLAG_KEY`) WARNS, does NOT hide: set for fuzzy markup-heavy / oversize, page stays searchable, marker is READ INTO search/get_page output — deliberately NO SQL filter fragment. Three markers, three reasons: `embed_skip` = oversized-but-clean, `quarantine` = junk hidden, `content_flag` = odd-examine-still-here; a page can carry more than one (oversize → embed_skip + content_flag:oversized) and each clears independently. Exports `buildQuarantineMarker` / `isQuarantined` / `filterOutQuarantined`, `buildContentFlagMarker` / `getContentFlag` / `hasContentFlag`, plus the two key constants. Pinned by `test/quarantine.test.ts`. #6259: [quarantine cluster](quarantine.md). A quarantined page is skipped by every derived-data scan (stale listing via the engine-sql stale predicate, NER, meeting timeline projection, file walks via `quarantinedSlugs`, DB walks, the managed link derivation) and is not in the `links_extraction_lag` denominator. Pinned by `test/quarantine-extraction.test.ts`.
diff --git a/src/commands/export.ts b/src/commands/export.ts
index 02a397d1e9..e33d6b3fda 100644
--- a/src/commands/export.ts
+++ b/src/commands/export.ts
@@ -1,11 +1,10 @@
import { existsSync } from 'node:fs';
import type { BrainEngine } from '../core/engine.ts';
-import { serializeMarkdown } from '../core/markdown.ts';
+import { serializeMarkdown, slugStampedFrontmatter } from '../core/markdown.ts';
import { scannerSlugRootMode } from '../core/write-through.ts';
import { createProgress } from '../core/progress.ts';
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
import { loadStorageConfig, isDbOnly } from '../core/storage-config.ts';
-import { slugifyPath } from '../core/sync.ts';
import { resolveSourceId } from '../core/source-resolver.ts';
import { ALL_SOURCES, assertValidSourceId } from '../core/source-id.ts';
import { resolveRestoreTarget, restoreFilePath } from '../core/restore-target.ts';
@@ -95,11 +94,8 @@ a fresh directory. See docs/storage-tiering.md#safe-export.`);
if (Number(key.bytes) > EXPORT_PAYLOAD_LIMIT) throw new Error('Export page payload limit exceeded. No destination output was published.');
const snapshot = await readExportPage(tx, key, withdrawals);
const page = snapshot.page;
- const fmSlug = page.frontmatter?.slug;
- const needsSlugStamp = slugifyPath(page.slug + '.md') !== page.slug;
- const frontmatter = (needsSlugStamp || fmSlug !== undefined) && fmSlug !== page.slug
- ? { ...(page.frontmatter ?? {}), slug: page.slug } : page.frontmatter;
- staged.add(page.slug + '.md', 'file', serializeMarkdown(frontmatter, page.compiled_truth, page.timeline,
+ // #5966: the slug stamp rule lives in slugStampedFrontmatter (markdown.ts), shared with every render.
+ staged.add(page.slug + '.md', 'file', serializeMarkdown(slugStampedFrontmatter(page.slug, page.frontmatter ?? {}), page.compiled_truth, page.timeline,
{ type: page.type, title: page.title, tags: snapshot.tags }));
const raw = Number(key.raw_count) ? await tx.getRawData(page.slug, undefined, { sourceId: page.source_id, includeDeleted: true }) : [];
if (raw.length) {
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 9f2090d9f4..7f63b69cc6 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -385,6 +385,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.156.0', text: 'A root-level `AGENTS.md` or `CLAUDE.md` in a source (the agent instructions `gbrain harden` writes) is no longer imported as a page: sync and `gbrain import` classify it as a metafile like `README.md`, while the same file inside a directory is still a page. A root `agents` or `claude` page an earlier version indexed is kept, not deleted; `gbrain delete agents` removes it if it is unwanted.' },
// W14 PR1 P1.9 (#5430). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
{ since: '0.60.156.0', text: 'The conversation parser now reads chat timestamps in the page\'s declared `timezone:` (an IANA zone such as Asia/Tokyo) and stores them in UTC, so a 09:00 Tokyo message is 00:00Z and the facts extracted from it carry the right `valid_from`; before, the zone only silenced the UTC warning and every timestamp was stored as if it were UTC. Conversation pages with a declared zone give different timestamps than before on re-extraction. A zone the runtime does not know keeps UTC and the warning names it. In a daylight-saving fold the first occurrence is taken; a time inside a spring-forward gap resolves with the offset in force before the change.' },
+ // W14 PR1 P1.7 (#5966). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
+ { since: '0.60.156.0', text: 'A page whose slug its file path cannot derive (a doubled hyphen, which the path rule collapses to one) is now written with a `slug:` frontmatter stamp by every render (write-through, repairs, export), so sync, reconcile and repair find the page again; the stamp does not change the page\'s content digest. A file an earlier version rendered without the stamp still refuses `source_changed` on reconcile until it is repaired: `gbrain repair frontmatter --source <id>` proposes the stamp as a safe repair, and the reconcile audit\'s classify mode reports such pages as `slug_rule_mismatch`.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/markdown.ts b/src/core/markdown.ts
index 9bfe3edea5..827c8a5bea 100644
--- a/src/core/markdown.ts
+++ b/src/core/markdown.ts
@@ -1241,7 +1241,7 @@ export function serializePageToMarkdown(
opts: SerializePageOpts = {},
): string {
const frontmatter: Record<string, unknown> = {
- ...((page.frontmatter ?? {}) as Record<string, unknown>),
+ ...slugStampedFrontmatter(page.slug, (page.frontmatter ?? {}) as Record<string, unknown>),
...(opts.frontmatterOverrides ?? {}),
};
return serializeMarkdown(
@@ -1256,6 +1256,21 @@ export function serializePageToMarkdown(
);
}
+/**
+ * #5966 (W14 P1.7): the one slug rule every render follows. A slug the file
+ * path cannot derive (a doubled hyphen, which `slugifyPath` collapses to one) is
+ * stamped as `slug:` so every path-derived reader (sync, reconcile, repair)
+ * finds the page again; a `frontmatter.slug` naming another identity is
+ * replaced by the page slug (the export rule, #3772). The stamp is
+ * digest-neutral: `parseMarkdown` drops `frontmatter.slug`, so canonical
+ * fields compare equal with or without it.
+ */
+export function slugStampedFrontmatter(slug: string, frontmatter: Record<string, unknown>): Record<string, unknown> {
+ const declared = frontmatter.slug;
+ if (slugifyPath(slug + '.md') !== slug || (declared !== undefined && declared !== slug)) return { ...frontmatter, slug };
+ return frontmatter;
+}
+
/**
* Compute the on-disk path for a (brainDir, slug, source_id) tuple per
* the v0.32.8 multi-source filing layout:
diff --git a/src/core/persistence/reconcile-audit.ts b/src/core/persistence/reconcile-audit.ts
index 2d2a8560e2..eeab55837d 100644
--- a/src/core/persistence/reconcile-audit.ts
+++ b/src/core/persistence/reconcile-audit.ts
@@ -5,6 +5,7 @@ import { OperationError, opError, type OperationContext } from '../ops/contract.
import { isValidSourceId } from '../source-id.ts';
import { validateSlug } from '../utils.ts';
import { resolveSourceLocalFilePath } from '../markdown.ts';
+import { slugifyPath } from '../sync.ts';
import { recordedPathFromFileUri, scannerSlugRootMode } from '../write-through.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { submissionAuthority } from './authority.ts';
@@ -62,7 +63,7 @@ export async function auditCanonicalSource(engine: BrainEngine, sourceId: string
ORDER BY slug LIMIT $3`, [sourceId, options.after ?? '', limit + 1]);
const report: ReconcileAuditReport = { source_id: sourceId, inspected: 0, drifted: 0, errors: 0, database_only: 0, findings: [],
next_after: rows.length > limit ? rows[limit - 1].slug : null, complete: rows.length <= limit, snapshot_only: true,
- ...(options.classify ? { classified: { structurally_additive: 0, additive_with_suggestions: 0, review_required: 0, formatting_only: 0, error: 0 } } : {}) };
+ ...(options.classify ? { classified: { structurally_additive: 0, additive_with_suggestions: 0, review_required: 0, formatting_only: 0, slug_rule_mismatch: 0, error: 0 } } : {}) };
const mode = await scannerSlugRootMode(engine, sourceId, root);
for (const candidate of rows.slice(0, limit)) {
report.inspected++;
@@ -124,7 +125,14 @@ async function classifyFinding(engine: BrainEngine, sourceId: string, slug: stri
: `Preview gbrain sources reconcile ${sourceId} ${slug} --brain <brain> --preview --auto-additive --out <new file>${verdict === 'additive_with_suggestions' ? ', read the inserted lines, then add --accept-suggested' : ''}; apply it with a new request ID.`;
return { classification: verdict, suggestion, drift_paths: classification.paths.map(({ path, class: kind, reason }) => ({ path, class: kind, reason })),
...(Number.isFinite(updated) ? { file_modified_after_database: statSync(state.path).mtimeMs > updated } : {}) };
- } catch {
+ } catch (error) {
+ // #5966 (W14 P1.7): a legacy render of a slug the path cannot derive, with no slug stamp; the frontmatter repair is the fix.
+ const slugRule = error instanceof OperationError && (error.detail === 'slug_rule_mismatch' || (error.code === 'invalid_params' && slugifyPath(slug + '.md') !== slug));
+ if (slugRule) {
+ counts.slug_rule_mismatch++;
+ return { classification: 'slug_rule_mismatch',
+ suggestion: `The canonical file carries no slug stamp, so its path derives ${slugifyPath(slug + '.md')} instead of ${slug}. Preview gbrain repair frontmatter --source ${sourceId} (a safe repair stamps slug: ${slug}), apply it, then audit again.` };
+ }
counts.error++;
return { classification: 'error' };
}
diff --git a/src/core/repair/frontmatter.ts b/src/core/repair/frontmatter.ts
index 3eecf383e4..698c2d6462 100644
--- a/src/core/repair/frontmatter.ts
+++ b/src/core/repair/frontmatter.ts
@@ -46,9 +46,10 @@ import { opError, OperationError, type OperationContext } from '../ops/contract.
import { shellQuote, type Action } from '../agent-output.ts';
import { autoFixFrontmatter, createFrontmatterBackup, makeFrontmatterBackupRunId, repairRecoverableFrontmatter } from '../brain-writer.ts';
import { classifyImportHold, parseMarkdown, type ContentHold, type ParsedMarkdown } from '../markdown.ts';
+import { dataFrontmatter as matter } from '../data-frontmatter.ts';
import { MAX_FILE_SIZE, type ContentRefusal } from '../import-screen.ts';
import { importFromFile } from '../import-file.ts';
-import { resolveSlugForPath } from '../sync.ts';
+import { resolveSlugForPath, slugifyPath } from '../sync.ts';
import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';
import { digest, sha256 } from '../persistence/digest.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
@@ -244,6 +245,26 @@ function pageDamage(page: PageRow | undefined, content: string): string | null {
return null;
}
+/**
+ * #5966 (W14 P1.7): a file an earlier gbrain rendered for a slug its path
+ * cannot derive (a doubled hyphen the path collapses to one) carries no `slug:`
+ * stamp, so every path-derived reader loses the page. The stamp is a SAFE
+ * candidate only when the file is the page's recorded `source_path` (one page
+ * records a path), the file declares no slug and the page slug is not the
+ * derived one; nothing is ever normalized or guessed. Inserted as
+ * `serializeMarkdown` would write it, right after the opening `---`.
+ */
+function slugStampCandidate(content: string, path: string, sourcePath: string, page: PageRow | undefined, parsed: ParsedMarkdown, ctx: SlugContext): { content: string; fixes: string[] } | null {
+ if (!page || page.source_path !== sourcePath || slugifyPath(sourcePath) === page.slug || parsed.slug === page.slug) return null;
+ const open = /^(\uFEFF?---[ \t]*\r?\n)/.exec(content);
+ if (!open) return null;
+ const eol = open[1].endsWith('\r\n') ? '\r\n' : '\n';
+ const line = matter.stringify('', { slug: page.slug }).split('\n')[1] ?? `slug: ${page.slug}`;
+ const stamped = open[1] + line + eol + content.slice(open[1].length);
+ if (!clean(stamped, path, ctx) || reading(stamped, path) !== reading(content, path) || parseMarkdown(stamped, path).slug !== page.slug) return null;
+ return { content: stamped, fixes: [`Stamp slug: ${page.slug} (the path ${sourcePath} derives ${slugifyPath(sourcePath)}, so readers lose the page without it)`] };
+}
+
interface Analysis {
proposal?: { content: string; fixes: string[]; class: RepairClass; rename_from?: SyncRename; reimport?: string };
pending?: { content: string; fixes: string[] };
@@ -282,6 +303,8 @@ async function analyzeFile(ctx: FileContext, path: string, hold: GitHoldRecord |
}
const problem = found.errors.length > 0 || found.hold !== null || found.recovered > 0 || found.comments > 0;
const damage = !problem && !hold ? pageDamage(page, content) : null;
+ const stamp = !problem && !hold && !damage ? slugStampCandidate(content, path, sourcePath, page, found.parsed, slugCtx) : null;
+ if (stamp) return { proposal: { ...stamp, class: 'safe' } };
if (!problem && !hold && !damage) return null;
if (damage) {
const body = parseMarkdown(content, path).compiled_truth;
diff --git a/test/e2e/slug-stamp-double-hyphen.test.ts b/test/e2e/slug-stamp-double-hyphen.test.ts
new file mode 100644
index 0000000000..b5f8f1ec47
--- /dev/null
+++ b/test/e2e/slug-stamp-double-hyphen.test.ts
@@ -0,0 +1,4 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+// #5966 (W14 P1.7): the slug-stamp repair candidate on Postgres.
+await registerPostgresTests(() => import('../slug-stamp-double-hyphen.test.ts'));
diff --git a/test/fixtures/goldens/exports/runtime.json b/test/fixtures/goldens/exports/runtime.json
index ea0e4ebcf1..390fbf3dcf 100644
--- a/test/fixtures/goldens/exports/runtime.json
+++ b/test/fixtures/goldens/exports/runtime.json
@@ -703,6 +703,7 @@
"resolveSourceLocalFilePath",
"serializeMarkdown",
"serializePageToMarkdown",
+ "slugStampedFrontmatter",
"sourceGitScope",
"splitBody",
"yamlAliasesWithinLimit",
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index d7b5104117..6705e69e1b 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -5473,6 +5473,13 @@
"(page: Page, tags: string[], opts?: SerializePageOpts) => string"
]
},
+ {
+ "kind": "function",
+ "name": "slugStampedFrontmatter",
+ "signature": [
+ "(slug: string, frontmatter: Record<string, unknown>) => Record<string, unknown>"
+ ]
+ },
{
"kind": "function",
"name": "sourceGitScope",
diff --git a/test/persistence-reconcile-additive-5974.test.ts b/test/persistence-reconcile-additive-5974.test.ts
index 9badfb5e75..3a7427425d 100644
--- a/test/persistence-reconcile-additive-5974.test.ts
+++ b/test/persistence-reconcile-additive-5974.test.ts
@@ -139,7 +139,7 @@ test('the reporter\'s additive page reconciles under --auto-additive; a replaced
.rejects.toMatchObject({ writeError: 'source_changed' });
const audit = await auditCanonicalSource(engine, f.id, { classify: true });
- expect(audit.classified).toEqual({ structurally_additive: 0, additive_with_suggestions: 1, review_required: 1, formatting_only: 0, error: 0 });
+ expect(audit.classified).toEqual({ structurally_additive: 0, additive_with_suggestions: 1, review_required: 1, formatting_only: 0, slug_rule_mismatch: 0, error: 0 });
expect(JSON.stringify(audit)).not.toContain('carol-example');
expect(audit.findings.find(x => x.slug === 'people/replaced-example')).toMatchObject({ classification: 'review_required',
drift_paths: [{ path: '/compiled_truth', class: 'review', reason: 'database_text_changed_or_removed' }] });
diff --git a/test/slug-stamp-double-hyphen.test.ts b/test/slug-stamp-double-hyphen.test.ts
new file mode 100644
index 0000000000..225c5c3ad1
--- /dev/null
+++ b/test/slug-stamp-double-hyphen.test.ts
@@ -0,0 +1,117 @@
+/**
+ * #5966 (W14 P1.7): a slug that is not a `slugifyPath` fixed point (`x/a--b`:
+ * the path `x/a--b.md` derives `x/a-b`) must carry a `slug:` stamp in every
+ * rendered file, or no path-derived reader (sync, reconcile, repair) can find
+ * the page again. The stamp is digest-neutral: `parseMarkdown` drops
+ * `frontmatter.slug`, so canonical fields compare equal with or without it.
+ * `repair frontmatter` proposes the stamp as a SAFE candidate only when the
+ * file sits at the page's recorded `source_path` and no other page claims it.
+ */
+import { afterAll, beforeAll, describe, 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 type { BrainEngine } from '../src/core/engine.ts';
+import { parseMarkdown, serializePageToMarkdown } from '../src/core/markdown.ts';
+import type { Page } from '../src/core/types.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { resolveRepairScope, type RepairResult } from '../src/core/repair/core.ts';
+import { repairRunner } from '../src/core/repair/registry.ts';
+import type { FrontmatterPreviewDetails } from '../src/core/repair/frontmatter.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const page = (slug: string, frontmatter: Record<string, unknown> = {}): Page => ({
+ id: 1, slug, type: 'note', title: 'Double', frontmatter, compiled_truth: 'Body.', timeline: '',
+ created_at: new Date(), updated_at: new Date(), source_id: 'default',
+} as unknown as Page);
+
+describe('serializePageToMarkdown stamps a slug the path cannot derive', () => {
+ test('x/a--b renders slug: x/a--b and reads back as itself; a fixed-point slug gets no stamp', () => {
+ const md = serializePageToMarkdown(page('x/a--b'), []);
+ expect(md).toContain('slug: x/a--b');
+ expect(parseMarkdown(md, 'x/a--b.md').slug).toBe('x/a--b');
+ expect(parseMarkdown(md, 'x/a--b.md', { validate: true, expectedSlug: 'x/a--b' }).errors ?? []).toEqual([]);
+ expect(serializePageToMarkdown(page('x/a-b'), [])).not.toContain('slug:');
+ });
+ test('the stamp is digest-neutral: canonical fields parse the same with and without it', () => {
+ const stamped = parseMarkdown(serializePageToMarkdown(page('x/a--b'), ['t']), 'x/a--b.md');
+ const plain = parseMarkdown(serializePageToMarkdown(page('x/a-b'), ['t']), 'x/a-b.md');
+ expect(stamped.frontmatter).toEqual(plain.frontmatter);
+ expect(stamped.frontmatter.slug).toBeUndefined();
+ expect([stamped.title, stamped.type, stamped.tags, stamped.compiled_truth]).toEqual([plain.title, plain.type, plain.tags, plain.compiled_truth]);
+ });
+ test('a legacy frontmatter slug that names another identity is replaced by the page slug (export rule)', () => {
+ const md = serializePageToMarkdown(page('people/jane-doe', { slug: 'people/Jane Doe' }), []);
+ expect(md).toContain('slug: people/jane-doe');
+ expect(md).not.toContain('Jane Doe');
+ });
+});
+
+const backends = testBackends();
+const home = mkdtempSync(join(tmpdir(), 'gbrain-slug-stamp-'));
+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home };
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], env: process.env }).trim();
+const quiet = { info() {}, warn() {}, error() {} };
+const localCtx = (engine: BrainEngine, sourceId: string): OperationContext => ({ engine, remote: false, sourceId } as OperationContext);
+const details = (result: RepairResult) => result.details as unknown as FrontmatterPreviewDetails;
+
+for (const kind of backends) describe(`repair frontmatter stamps a legacy unstamped -- file (${kind})`, () => {
+ let engine: BrainEngine, close: (() => Promise<void>) | undefined;
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
+ }, 120_000);
+ afterAll(async () => { await withEnv(env, async () => { await disposePersistenceConsumer(engine); }); if (close) await close(); else await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });
+
+ test('a safe candidate inserts the stamp at the recorded source_path; apply re-imports the same page', () => withEnv(env, async () => {
+ const id = `ss-${randomUUID().replace(/-/g, '').slice(0, 20)}`, root = join(home, id);
+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');
+ writeFileSync(join(root, '.git', 'hooks', 'post-commit'), '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\n'); chmodSync(join(root, '.git', 'hooks', 'post-commit'), 0o755);
+ writeFileSync(join(root, 'notes', 'ok.md'), '---\ntitle: Ok\n---\nFine.\n');
+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'fixture');
+ 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,'{}')", [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ try {
+ await submitPageMutation(localCtx(engine, id), { operation: 'put_page', params: { slug: 'notes/a--b', source_id: id, content: '---\ntitle: Double\n---\nTwo hyphens.\n' } });
+ const written = readFileSync(join(root, 'notes', 'a--b.md'), 'utf8');
+ expect(written).toContain('slug: notes/a--b');
+ // A file an earlier gbrain rendered without the stamp.
+ const legacy = written.split('\n').filter(line => line !== 'slug: notes/a--b').join('\n');
+ writeFileSync(join(root, 'notes', 'a--b.md'), legacy);
+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'legacy unstamped render');
+
+ const runner = await repairRunner(engine, { apply: false, noEmbed: true, logger: quiet });
+ const preview = await runner.run('frontmatter', await resolveRepairScope(engine, id), { explicit: true, sourceFlag: id });
+ expect(preview).toMatchObject({ mode: 'dry_run', affected: 1 });
+ expect(details(preview).counts).toMatchObject({ safe: 1, interpretive: 0, needs_review: 0 });
+ expect(details(preview).samples.safe!.diff).toContain('+slug: notes/a--b');
+ expect(details(preview).diffs[0]!.fixes.join(' ')).toContain('notes/a-b');
+ const hash = preview.apply_command.split('--expect ')[1]!.split(' ')[0]!;
+ const applier = await repairRunner(engine, { apply: true, noEmbed: true, logger: quiet });
+ const applied = await applier.run('frontmatter', await resolveRepairScope(engine, id), { explicit: true, sourceFlag: id, expect: hash });
+ expect(applied).toMatchObject({ applied: 1, outcomes: { repaired: 1 } });
+ const repaired = readFileSync(join(root, 'notes', 'a--b.md'), 'utf8');
+ expect(repaired).toContain('slug: notes/a--b');
+ expect(parseMarkdown(repaired, 'notes/a--b.md').slug).toBe('notes/a--b');
+ const rows = await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL ORDER BY slug', [id]);
+ expect(rows.map(r => r.slug)).toEqual(['notes/a--b']);
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('DELETE FROM sources WHERE id=$1', [id]);
+ }
+ }), 180_000);
+
+ test.todo('P1.7 (#5966) stack hunk: sources reconcile --preview of a legacy unstamped -- file refuses with detail slug_rule_mismatch naming the repair command (reconcile-state.ts is wave-13 owned; see ~/.capy/work/w14/pr1/stack-hunks)', () => {});
+});