Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): read canonical files the way the importer does under path inference (#6605)
time-attack19fa5f82015c
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex 3c9e50a4a1..b45d2a877a 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -16,7 +16,7 @@ Managed facts extraction (withdrawn-candidate skip and recovery, conversation fa- `src/core/persistence/{admin-lock,blocking-effects,writer-versions}.ts` — `admin-lock.ts` owns the opt-in brain-level writer admin lock: reserved config key `persistence.writer_admin_lock` (`{locked, set_at, host_id, generation}`), written only by local `gbrain sources writer lock|unlock` under the `persistence_brain` row `FOR UPDATE`; lock refuses while a prepared transfer is unaccepted. `assertWriterAdminUnlocked` runs inside the claim, managed claim, activation, shared-skill activation and transfer prepare/accept transactions for every caller (share lock on the brain row) and refuses with `writer_admin_locked`; only the ordinary first-write auto-claim (`claimWorktree(..., { automatic: true })` from page and memory mutations) is exempt. Generic `config set`/`unset`/`unset --pattern` refuse the key; engine migration copies it. It is not a security boundary and older binaries ignore it. `blocking-effects.ts` lists queued, running or recovering effects (`listBlockingEffects`) and builds `writer_not_quiesced` suggestions naming the first blocking request or effect with `gbrain sources writer status <source> --json`. `writer-versions.ts` stamps admitter version/host at admission and consumer version/host/`published_at` only on committed publication (migration 178, cutoff `persistence_brain.writer_version_cutoff` on the database clock); replay and compaction keep stamps. `sources writer status` reports `admin_lock`, `local_host_id`, `blocking_effects` and `writer_versions`; `src/commands/doctor/checks/writer-version.ts` is the seven-day `writer_version` advisory. Tests: `test/persistence-writer-admin-lock.test.ts`, `test/persistence-writer-versions.test.ts`, `test/persistence-blocking-effects.test.ts`, `test/e2e/persistence-writer-{admin-lock,stamps}.test.ts`.-- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry, authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `page-prepare.ts` exports `fileMatchesSnapshot`, the canonical file-versus-page comparison `prepareFileTarget` applies, so lint can bind a repair to the revision it read; the uncoordinated-local-edit refusal carries detail `file_database_drift` and a `sources reconcile <src> <slug> --brain host --preview` fix; a shared-origin delete: canonical-reconciliation.md. In `prepareFileTarget`, a live page whose canonical file is missing refuses `source_changed` unless it is declared or derive-phase database-only, or it is a `delete_page` (`deleting`, no content) of a page with no recorded `source_path` and no captured file URI: that delete plans no file, so it publishes database-only and its receipt reports no file or Git effect (`test/persistence-captured-file-target.test.ts`, `test/persistence-never-published-delete.test.ts`). `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `submitMaintenance` scans every content-carrying intent with `scanCanonicalFences` (the check the canonical projection runs) over the whole submitted body and timeline before a request exists (#6278): a defect no adoption clears (a second facts fence in the timeline; `replaceOrInsertFactsFence` replaces only the first) is refused with its fence reason, so `fenceManaged` reports the page in `failed_pages` and the others still adopt, while a repair whose postimage is clean passes. `prepareFactFenceAdoption` names its steps for `enterClaimStep`, compares the fence cell with the legacy fact modulo whitespace, writes the cell's parsed text back into `facts.fact` in the same `UPDATE` that sets `row_num` (so the projection keeps the fact's id), and throws the registered `fence_unrenderable` (class `server`) as its last-line defence. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests; its owner check goes through `checkOwner` / `ownerUnavailableError` (`owner-refusal.ts`), so a missing binding, a changed incarnation, another owner host, a draining or recovering worktree and a missing local or coordination path each refuse `owner_unavailable` with their own `reason`, and nothing claims or transfers ownership to get past them. #6325: `resumeManagedAtoms` returns `run | done | held`. The drain does not replay a failed batch: it resumes the next automatic attempt, whose run key is `digest([drainKey, failedRequestId, 'automatic'])` (one stable id per failure, so a crashed attempt resumes and two runs admit the same requests), and whose completion advances the failed drain-key checkpoint by the same compare-and-set an explicit retry uses. The completion counts one strike per completed failure on that checkpoint (`attempts`); at `MAX_DETERMINISTIC_FAILURES` it sets `held`, which `MANAGED_ATOM_DISCOVERY_SQL` excludes from discovery and the backlog and `listHeldManagedAtoms` reports (doctor `extract_atoms_held_failed`, code `held_failed`). Reading a held or failed checkpoint never strikes; storage, authority and conflict errors fail the attempt without completing it, so they never strike either. A content change is a new drain key, so the count starts over. An explicit retry (`session.retry`) ignores `held`, and its failure refusal (`extraction_failed`) names the recorded failure reason (malformed output or a response stopped before the end) and carries a paid `fix` (`gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'`) with a read-only `gbrain write-request` verify; the drain raises it only for a failed batch whose checkpoint is gone. Tests: `test/managed-atoms-retry.test.ts`. Managed facts extraction (the withdrawn-candidate skip and its recovery route, the conversation facts batches, the unmanaged derived index) continues in [Core Persistence (managed facts)](core-persistence-facts.md).+- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry, authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `page-prepare.ts` exports `fileMatchesSnapshot`, the canonical file-versus-page comparison `prepareFileTarget` applies, so lint can bind a repair to the revision it read (it takes the importer's path for the file: a frontmatter-less file under a directory-inference rule also matches when `readCanonicalAsImported` (BOM strip + `applyInference` at `scannerSourcePath`) reproduces the stored row, with an inferred type treated as undeclared, #6605; reconcile reads the file side through `reconcileFileReading` in `reconcile-state.ts`); the uncoordinated-local-edit refusal carries detail `file_database_drift` and a `sources reconcile <src> <slug> --brain host --preview` fix; a shared-origin delete: canonical-reconciliation.md. In `prepareFileTarget`, a live page whose canonical file is missing refuses `source_changed` unless it is declared or derive-phase database-only, or it is a `delete_page` (`deleting`, no content) of a page with no recorded `source_path` and no captured file URI: that delete plans no file, so it publishes database-only and its receipt reports no file or Git effect (`test/persistence-captured-file-target.test.ts`, `test/persistence-never-published-delete.test.ts`). `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `submitMaintenance` scans every content-carrying intent with `scanCanonicalFences` (the check the canonical projection runs) over the whole submitted body and timeline before a request exists (#6278): a defect no adoption clears (a second facts fence in the timeline; `replaceOrInsertFactsFence` replaces only the first) is refused with its fence reason, so `fenceManaged` reports the page in `failed_pages` and the others still adopt, while a repair whose postimage is clean passes. `prepareFactFenceAdoption` names its steps for `enterClaimStep`, compares the fence cell with the legacy fact modulo whitespace, writes the cell's parsed text back into `facts.fact` in the same `UPDATE` that sets `row_num` (so the projection keeps the fact's id), and throws the registered `fence_unrenderable` (class `server`) as its last-line defence. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests; its owner check goes through `checkOwner` / `ownerUnavailableError` (`owner-refusal.ts`), so a missing binding, a changed incarnation, another owner host, a draining or recovering worktree and a missing local or coordination path each refuse `owner_unavailable` with their own `reason`, and nothing claims or transfers ownership to get past them. #6325: `resumeManagedAtoms` returns `run | done | held`. The drain does not replay a failed batch: it resumes the next automatic attempt, whose run key is `digest([drainKey, failedRequestId, 'automatic'])` (one stable id per failure, so a crashed attempt resumes and two runs admit the same requests), and whose completion advances the failed drain-key checkpoint by the same compare-and-set an explicit retry uses. The completion counts one strike per completed failure on that checkpoint (`attempts`); at `MAX_DETERMINISTIC_FAILURES` it sets `held`, which `MANAGED_ATOM_DISCOVERY_SQL` excludes from discovery and the backlog and `listHeldManagedAtoms` reports (doctor `extract_atoms_held_failed`, code `held_failed`). Reading a held or failed checkpoint never strikes; storage, authority and conflict errors fail the attempt without completing it, so they never strike either. A content change is a new drain key, so the count starts over. An explicit retry (`session.retry`) ignores `held`, and its failure refusal (`extraction_failed`) names the recorded failure reason (malformed output or a response stopped before the end) and carries a paid `fix` (`gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'`) with a read-only `gbrain write-request` verify; the drain raises it only for a failed batch whose checkpoint is gone. Tests: `test/managed-atoms-retry.test.ts`. Managed facts extraction (the withdrawn-candidate skip and its recovery route, the conversation facts batches, the unmanaged derived index) continues in [Core Persistence (managed facts)](core-persistence-facts.md).- `src/core/persistence/maintenance-wait.ts` — how long a maintenance publisher waits for its accepted write to commit before the receipt reports `write_pending` (#5854). `MAINTENANCE_WRITE_WAIT_MS` is 30 s; `MaintenanceWriteWait` is one budget per job: each wait is capped by the job's remaining deadline (zero at or past it), and once one publish is still pending after its wait (`observe`) every later publish in that job waits zero and is deferred like it. A pending write keeps its request identity and commits later; it is never reported as committed. A `MaintenanceWriteWait` with no deadline also sets the replay window of a subagent tool write whose job has none (`minions/tool-write-identity.ts`). `__setMaintenanceWriteWaitForTests` replaces the base wait, those tool writes included. Tests: `test/maintenance-write-wait.test.ts`, `test/e2e/maintenance-write-wait.test.ts`.Atom completion admits replacement and revision-pinned stale-atom deletion children together.Each retirement stamps `retired_by`/`retired_at` into the tombstone in the same publication; `publishManagedAtoms` restores a retired atom of the same origin when an extraction produces it again, and a user-deleted atom stays deleted. Each committed retirement bumps the origin page's regeneration generation (`op_checkpoints` op `managed-atoms-generation`, part of the drain's run key only above 0, never of the explicit retry identity; the content whose extraction retired keeps the generation its accepted batch used, so that batch stays resumable) and clears that page's older `extract_atoms_page_state` rows and completed `managed-atoms` checkpoints in the same publication, so an A→B→A edit, even after a partly failed batch, re-extracts instead of replaying a retained receipt. Retirements are admitted in slug order.diff --git a/src/commands/lint.ts b/src/commands/lint.tsindex d6922b7109..e1f7c8687b 100644--- a/src/commands/lint.ts+++ b/src/commands/lint.ts@@ -41,6 +41,7 @@ import { pathToSlug } from '../core/sync.ts';import { isManagedBrain } from '../core/cycle/phase-table.ts';import { maintenancePreflight, publishMaintenancePage, type MaintenanceAuthority } from '../core/persistence/prepared-maintenance.ts';import { fileMatchesSnapshot, prepareFileTarget } from '../core/persistence/page-prepare.ts';+import { scannerSlugRootMode, scannerSourcePath } from '../core/write-through.ts';import { heldFileDiagnostic, writeFailureDiagnostic } from '../core/persistence/verb-errors.ts';import { loadActivePackForEngine } from '../core/schema-pack/engine-resolution.ts';import { OperationError, opError } from '../core/ops/contract.ts';@@ -729,7 +730,8 @@ async function publishLintFix(engine: BrainEngine, authority: MaintenanceAuthoriconst scanned = existsSync(page) ? readSourceFileSync(page, 'utf-8') : null;const fixed = scanned === null ? null : fixContent(scanned);if (scanned === null ? !authority.binding : fixed === scanned) return null;- if (authority.binding && (scanned === null || !await fileMatchesSnapshot(engine, slug, scanned, snapshot, activePack))) {+ const importPath = async () => scannerSourcePath(root, page, await scannerSlugRootMode(engine, sourceId, root));+ if (authority.binding && (scanned === null || !await fileMatchesSnapshot(engine, slug, scanned, snapshot, importPath, activePack))) {const current = await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });if (current?.revision !== snapshot.revision) return pendingIssue(relPath, slug, 'revision_changed', changedWhileLinting(sourceId, slug));try {diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 717e365be7..27f0ebf451 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -13,6 +13,7 @@ import type { Page, PageVersion } from '../types.ts';import { importFromContent, verifyPageReadable, type ParsedPage } from '../import-file.ts';import { comparableFrontmatter, frontmatterHoldMessageWithoutKeys, parseMarkdown, resolveParsedSubtype, serializePageToMarkdown, resolveSourceLocalFilePath, type ParseOpts } from '../markdown.ts';import { assertLargePageReplacement } from './large-page-guard.ts';+import { applyInference } from '../frontmatter-inference.ts';import { OperationError, opError } from '../ops/contract.ts';import { CANONICAL_FILE_MISSING } from './publication-failure.ts';import { readFix } from '../ops/op-fix.ts';@@ -134,29 +135,53 @@ export function publishesDatabaseOnly(root: string, slug: string, snapshot: { paif (!snapshot || snapshot.page.deleted_at) return false;return isSourceDbOnlySlug(root, slug, 'refuse') || isNeverFiledDerivedPage(slug, snapshot.page);}+/**+ * #6605: a canonical file read the way the importer reads it. A file with no frontmatter under a+ * directory-inference rule is imported with the frontmatter and tags inferred from its path+ * (`applyInference` after stripping a BOM: import-prepare.ts, import-file.ts), so comparing its raw bytes+ * with the stored row reads every untouched file as drift. `sourcePath` is the path the importer infers+ * from (`scannerSourcePath`). Inference is deterministic, so this reproduces what the import stored;+ * `inferred` is false when no rule applies (the bytes are read as they are).+ */+export function readCanonicalAsImported(bytes: string, sourcePath: string): { content: string; inferred: boolean } {+ const inference = applyInference(sourcePath, bytes.replace(/^\uFEFF/, ''));+ return inference.inferred.skipped === true ? { content: bytes, inferred: false } : { content: inference.content, inferred: true };+}+/*** Whether file bytes hold the snapshot's page: the canonical (format-insensitive)* comparison prepareFileTarget applies before replacing a canonical file. Lint* uses it to bind a repair to the revision it read before reading the file.+ * `sourcePath` (the importer's path for the file, or a resolver for it) lets a+ * frontmatter-less file match the row an inferring import stored (#6605); the+ * raw reading still matches a row imported without inference (`gbrain reindex`+ * on an unmanaged brain passes `inferFrontmatter: false`).*/export async function fileMatchesSnapshot(engine: BrainEngine, slug: string, bytes: string, snapshot: PageSnapshot,- activePack?: ParseOpts['activePack']): Promise<boolean> {- const parsed = parseMarkdown(bytes, slug, { activePack });- // #5521 parity for subtype (#5928): a pack rule is not part of the file's bytes, so a file- // without an explicit `subtype:` keeps the stored subtype (or none); the import still stamps it.- delete parsed.inferredSubtype;- resolveParsedSubtype(parsed, snapshot.page);- // #6429: the v0.13.1 grandfather stamped `validate: false` into the database; on an unmanaged brain that path- // never wrote the file, so the file lacks a key the database carries. The mechanical stamp authors nothing- // (grandfather.ts): a file without a `validate:` key keeps the stored stamp, and the next coordinated write publishes it.- if (!Object.hasOwn(parsed.frontmatter, 'validate') && snapshot.page.frontmatter?.validate === false) parsed.frontmatter.validate = false;- // #1035 parity (#5521): a file without an explicit `type:` keeps the stored type on import.- const type = parsed.typeExplicit ? parsed.type : snapshot.page.type;- // Withdrawal overlays intentionally precede physical mirroring. The ledger- // is applied by the import preparation and cannot be undone by this check.- const actual = canonical({ ...parsed, type, ...await overlayCanonicalBodies(engine.executeRaw.bind(engine),- parsed.compiled_truth, parsed.timeline ?? '', snapshot.withdrawals, { sourceId: snapshot.page.source_id, marker: snapshot.globalPurges }) }, parsed.tags);- return digest(actual) === digest(canonical(snapshot.page, snapshot.tags));+ sourcePath: string | (() => Promise<string>), activePack?: ParseOpts['activePack']): Promise<boolean> {+ const expected = digest(canonical(snapshot.page, snapshot.tags));+ const matches = async (content: string, inferred: boolean) => {+ const parsed = parseMarkdown(content, slug, { activePack });+ // #5521 parity for subtype (#5928): a pack rule is not part of the file's bytes, so a file+ // without an explicit `subtype:` keeps the stored subtype (or none); the import still stamps it.+ delete parsed.inferredSubtype;+ resolveParsedSubtype(parsed, snapshot.page);+ // #6429: the v0.13.1 grandfather stamped `validate: false` into the database; on an unmanaged brain that path+ // never wrote the file, so the file lacks a key the database carries. The mechanical stamp authors nothing+ // (grandfather.ts): a file without a `validate:` key keeps the stored stamp, and the next coordinated write publishes it.+ if (!Object.hasOwn(parsed.frontmatter, 'validate') && snapshot.page.frontmatter?.validate === false) parsed.frontmatter.validate = false;+ // #1035 parity (#5521): a file without an explicit `type:` keeps the stored type on import. An inferred+ // type is not one the file declared (#6605): inference only applies to a file with no frontmatter.+ const type = parsed.typeExplicit && !inferred ? parsed.type : snapshot.page.type;+ // Withdrawal overlays intentionally precede physical mirroring. The ledger+ // is applied by the import preparation and cannot be undone by this check.+ const actual = canonical({ ...parsed, type, ...await overlayCanonicalBodies(engine.executeRaw.bind(engine),+ parsed.compiled_truth, parsed.timeline ?? '', snapshot.withdrawals, { sourceId: snapshot.page.source_id, marker: snapshot.globalPurges }) }, parsed.tags);+ return digest(actual) === expected;+ };+ if (await matches(bytes, false)) return true;+ const reading = readCanonicalAsImported(bytes, typeof sourcePath === 'string' ? sourcePath : await sourcePath());+ return reading.inferred && await matches(reading.content, true);}export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequest, 'source_id' | 'worktree_id' | 'slug'>, snapshot: PageSnapshot | null,content: string | null, hostId?: string, options: { allowMissing?: boolean; deleting?: boolean; capture?: { path: string; hash: string }; activePack?: ParseOpts['activePack']; remote?: boolean;@@ -224,7 +249,8 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ// A normal edit may replace only the bytes represented by its read snapshot.// Unknown local edits require explicit import/recovery, even for force writes.if (before && snapshot) {- if (!await fileMatchesSnapshot(engine, row.slug, before.toString('utf8'), snapshot, options.activePack)) {+ const importPath = async () => scannerSourcePath(root, path, mode ?? await scannerSlugRootMode(engine, row.source_id, root));+ if (!await fileMatchesSnapshot(engine, row.slug, before.toString('utf8'), snapshot, importPath, options.activePack)) {const held = await heldFileRefusal(engine, row, root, path, 'drift', options.remote === true);if (held) throw held;// #6394: a page that never recorded its file reconciles against the file at its slug path only when adopted explicitly.diff --git a/src/core/persistence/reconcile-prepare.ts b/src/core/persistence/reconcile-prepare.tsindex 731d2c7183..da1e0d4ab5 100644--- a/src/core/persistence/reconcile-prepare.ts+++ b/src/core/persistence/reconcile-prepare.ts@@ -21,7 +21,7 @@ import { preserveProtectedTakes } from './protected-takes.ts';import { digest, sha256 } from './digest.ts';import { mergeReconcile, reconcileCanonical, type ReconcileDecision } from './reconcile-merge.ts';import { stabilizeSafetyAssessments } from './reconcile-safety.ts';-import { assertReconcilePins, readReconcileState, reconcilePreviewAdopts, staleReconcile, validateReconcileArtifact, type ReconcileState } from './reconcile-state.ts';+import { assertReconcilePins, readReconcileState, reconcileFileReading, reconcilePreviewAdopts, staleReconcile, validateReconcileArtifact, type ReconcileState } from './reconcile-state.ts';import { verifyReconcileBackup } from './reconcile-backup.ts';import { assertAutoDecisions } from './reconcile-additive.ts';@@ -165,7 +165,9 @@ export async function prepareReconcileMutation(engine: BrainEngine, row: WriteReif (!ready.noop) { await prepared.project!(tx); await sealPageTextProjection(tx, row.slug, row.source_id); }const final = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id });const scanStateTransferred = final ? await transferLegacyAtomPageState(tx, state.snapshot, final) : false;- const file = parseMarkdown(readFileSync(state.path, 'utf8'), row.slug);+ const reading = reconcileFileReading(readFileSync(state.path, 'utf8'), state.importPath, final?.page ?? state.snapshot.page);+ const file = parseMarkdown(reading.content, row.slug);+ if (reading.inferred && final) file.type = final.page.type;if (!sameCanonicalImport(final, prepared.result) || digest(reconcileCanonical(file, file.tags)) !== artifact.result_digest) {throw opError('storage_error', 'Reconciliation canonical readback did not match the reviewed result.',`After publishing, ${row.slug} in source ${row.source_id} read back differently from the reviewed result, so the database change rolled back and the owner's recovery restores the file. Inspect request ${row.request_id}'s receipt before anything else and do not apply the preview again until it is terminal.`,diff --git a/src/core/persistence/reconcile-state.ts b/src/core/persistence/reconcile-state.tsindex 2f5354ff4a..62216ed8df 100644--- a/src/core/persistence/reconcile-state.ts+++ b/src/core/persistence/reconcile-state.ts@@ -9,7 +9,7 @@ import { OperationError, opError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';import type { PageSnapshot } from '../page-state/types.ts';import { isWriteTargetContained } from '../path-confine.ts';-import { recordedPathFromFileUri, scannerSlugRootMode } from '../write-through.ts';+import { recordedPathFromFileUri, scannerSlugRootMode, scannerSourcePath } from '../write-through.ts';import { findLiveFileClaimants, recordedReconcilePath, type FileClaimTarget } from './file-claims.ts';import { sharedOriginExit } from './sync-origin.ts';export { fileClaimCandidatesSql } from './file-claims.ts';@@ -21,7 +21,7 @@ import { digest, requireUuid, sha256, stableJson } from './digest.ts';import { reconcileCanonical, strictReconcileKeys, validateReconcileJson, type ReconcileConflict, type ReconcileDecision } from './reconcile-merge.ts';import type { ParsedPage } from '../import-file.ts';import type { AutoDecision } from './reconcile-additive.ts';-import { publishesDatabaseOnly } from './page-prepare.ts';+import { publishesDatabaseOnly, readCanonicalAsImported } from './page-prepare.ts';import { isMirrorOnlyPage } from './mirror-read-only.ts';export interface ReconcilePins {@@ -39,6 +39,8 @@ export interface ReconcileArtifact {}export interface ReconcileState {binding: WorktreeBinding; root: string; path: string; raw: Buffer; snapshot: PageSnapshot;+ /** The path the importer reads the file under (`scannerSourcePath`), for path inference (#6605). */+ importPath: string;storedPage: Record<string, unknown>; file: ParsedPage; pins: ReconcilePins;/** `slug_derived`: a database-only page matched to the canonical file at its slug path. */origin: 'recorded' | 'slug_derived';@@ -141,7 +143,10 @@ export async function readReconcileState(engine: BrainEngine, sourceId: string,`Nothing changed. Fix the frontmatter of the canonical file of ${slug} in '${sourceId}' (quote values containing ': ', close the --- block), then preview the page again.`);}// Preserve a terminal .md in the page key while parsing the canonical Markdown.- const parsed = parseMarkdown(text, `${slug}.md`, { validate: true, expectedSlug: slug });+ const importPath = scannerSourcePath(root, path, mode);+ const reading = reconcileFileReading(text, importPath, snapshot.page);+ const parsed = parseMarkdown(reading.content, `${slug}.md`, { validate: true, expectedSlug: slug });+ if (reading.inferred) parsed.type = snapshot.page.type;const errors = parsed.errors?.filter(e => !['MISSING_OPEN', 'MISSING_CLOSE', 'EMPTY_FRONTMATTER'].includes(e.code)) ?? [];if (!errors.length && !parsed.errors?.some(e => e.code === 'MISSING_CLOSE') && parsed.slug !== slug) {// #5966 (W14 P1.7): a well-formed file whose path derives another slug is a legacy render of a slug the@@ -158,7 +163,7 @@ export async function readReconcileState(engine: BrainEngine, sourceId: string,page_id: snapshot.page.id, worktree_id: binding.worktree_id, binding_digest: digest({ binding, root, path: canonicalPath }), owner_epoch: String(binding.owner_epoch),revision: snapshot.revision, raw_file_hash: sha256(raw), relative_path: relative(root, path),policy_digest: await reconcilePolicyDigest(engine, sourceId), withdrawals_digest: digest({ withdrawals: snapshot.withdrawals, global_purges: snapshot.globalPurges ?? null }), assessment_at: assessmentAt };- return { binding, root, path, raw, snapshot, storedPage, file: reconcileCanonical(parsed, parsed.tags), pins, origin, originSourcePath: derived?.sourcePath ?? null };+ return { binding, root, path, importPath, raw, snapshot, storedPage, file: reconcileCanonical(parsed, parsed.tags), pins, origin, originSourcePath: derived?.sourcePath ?? null };}/** #6394: a preview made with --adopt-slug-path recorded a page with no origin; apply and publication adopt the same pinned file. */export function reconcilePreviewAdopts(artifact: Pick<ReconcileArtifact, 'preimages'>): boolean {@@ -225,3 +230,17 @@ export function validateReconcileArtifact(value: unknown): ReconcileArtifact {for (const withdrawal of value.preimages.database.withdrawals as unknown[]) strictReconcileKeys(withdrawal, ['visibility', 'fact_hash', 'withdrawn_at', 'purged'], ['visibility', 'fact_hash', 'withdrawn_at']);return JSON.parse(stableJson(value)) as ReconcileArtifact;}++/**+ * #6605: the file side of a reconciliation, read the way the importer stored it. A frontmatter-less file under a+ * directory-inference rule was imported with the frontmatter its path infers, so its raw bytes would show every+ * inferred key as a difference. The inferred reading is used when the stored row carries every key it adds (an+ * inferring import wrote the row); a row imported without inference (`gbrain reindex` on an unmanaged brain) is+ * compared with the raw bytes. An inferred `type:` is not one the file declared: the caller keeps the stored type.+ */+export function reconcileFileReading(text: string, sourcePath: string, stored: { frontmatter?: Record<string, unknown> | null }): { content: string; inferred: boolean } {+ const reading = readCanonicalAsImported(text, sourcePath);+ if (!reading.inferred) return reading;+ const keys = Object.keys(parseMarkdown(reading.content, sourcePath).frontmatter);+ return keys.every(key => Object.hasOwn(stored.frontmatter ?? {}, key)) ? reading : { content: text, inferred: false };+}diff --git a/test/persistence-guard-digest.test.ts b/test/persistence-guard-digest.test.tsindex 3172a7670d..addbc22f0d 100644--- a/test/persistence-guard-digest.test.ts+++ b/test/persistence-guard-digest.test.ts@@ -6,6 +6,8 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { parseMarkdown, serializePageToMarkdown } from '../src/core/markdown.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';import { prepareFileTarget } from '../src/core/persistence/page-prepare.ts';+import { applyInference } from '../src/core/frontmatter-inference.ts';+import { slugifyPath } from '../src/core/sync.ts';// #5521 / #5635: the coordinated write guard compares the parsed canonical file// with the stored row. A file with no frontmatter `type:` keeps the stored type@@ -91,3 +93,77 @@ test('#5622 a new captured page claims its in-source file only when the bytes ar.rejects.toMatchObject({ code: 'source_changed' });expect((await prepareFileTarget(engine, row, null, 'Rendered page', undefined, { capture: { path: 'notes/captured-race.md', hash: sha256('x2 observation\n') } }))?.path).toBe(file);});++// Directory-inferred pages: an importer prepends path-inferred frontmatter (`date`, `source`, tags) to a+// frontmatter-less file before it parses it (applyInference in import-prepare.ts), so the stored row carries those+// fields while the canonical file never does. The guard must read the file the way the importer did.+async function seedInferred(rel: string, body: string, opts: { storedType?: string; bom?: boolean } = {}) {+ const slug = slugifyPath(rel);+ const parsed = parseMarkdown(applyInference(rel, body).content, rel);+ await engine.putPage(slug, { type: (opts.storedType ?? parsed.type) as typeof parsed.type, title: parsed.title, compiled_truth: parsed.compiled_truth,+ timeline: parsed.timeline, frontmatter: parsed.frontmatter, tags: parsed.tags }, { sourceId });+ for (const tag of parsed.tags) await engine.addTag(slug, tag, { sourceId, tagSource: 'frontmatter' });+ await engine.executeRaw('UPDATE pages SET source_path=$1 WHERE source_id=$2 AND slug=$3', [rel, sourceId, slug]);+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;+ const file = join(root, rel);+ mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, `${opts.bom ? '\uFEFF' : ''}${body}`);+ return { snapshot, file, row: { source_id: sourceId, worktree_id: worktreeId, slug } };+}+const INFERRED_REL = 'Apple Notes/Ideas/2021-06-20 Packing list.md';++test('a frontmatter-less file under a directory-inference rule is not drift against the row the importer stored', async () => {+ const { snapshot, row, file } = await seedInferred(INFERRED_REL, 'Passport, charger, notebook.\n');+ // The premises: the row holds inferred fields the file cannot carry.+ expect(Object.keys(snapshot.page.frontmatter ?? {}).sort()).toEqual(['date', 'source']);+ expect(snapshot.tags.length).toBeGreaterThan(0);+ expect(readFileSync(file, 'utf8')).not.toMatch(/^---/);+ for (const attempt of [1, 2]) {+ expect((await prepareFileTarget(engine, row, snapshot, `Replacement ${attempt}`))?.path).toBe(file);+ }+ expect((await prepareFileTarget(engine, row, snapshot, null))?.path).toBe(file);+});++test('a real body edit to a directory-inferred file is still refused', async () => {+ const { snapshot, row, file } = await seedInferred('Apple Notes/Ideas/2021-06-21 Edited.md', 'Original text.\n');+ writeFileSync(file, 'Original text.\nUncoordinated local edit.\n');+ await expect(prepareFileTarget(engine, row, snapshot, 'Replacement')).rejects.toMatchObject({ code: 'source_changed', detail: 'file_database_drift' });+});++test('an explicit frontmatter value that disagrees with the inferred row is still refused', async () => {+ const { snapshot, row, file } = await seedInferred('Apple Notes/Ideas/2021-06-22 Explicit.md', 'Body.\n');+ writeFileSync(file, '---\ndate: 1999-01-01\n---\nBody.\n');+ await expect(prepareFileTarget(engine, row, snapshot, 'Replacement')).rejects.toMatchObject({ code: 'source_changed' });+});++test('an inferred type is not a declared one: a stored type that differs from the path default is kept', async () => {+ const { snapshot, row, file } = await seedInferred('Apple Notes/Ideas/2021-06-23 Retyped.md', 'Body.\n', { storedType: 'note' });+ expect(snapshot.page.type).toBe('note');+ expect(parseMarkdown(applyInference('Apple Notes/Ideas/2021-06-23 Retyped.md', readFileSync(file, 'utf8')).content, row.slug).type).not.toBe('note');+ expect((await prepareFileTarget(engine, row, snapshot, 'Replacement'))?.path).toBe(file);+});++test('a BOM in front of an inferred heading title does not make an untouched file drift', async () => {+ // runbooks/ takes its title from the first heading; the importer strips the BOM before inferring it.+ const { snapshot, row, file } = await seedInferred('runbooks/restore-db.md', '# Restore the database\n\nSteps.\n', { bom: true });+ expect(snapshot.page.title).toBe('Restore the database');+ expect(readFileSync(file, 'utf8').charCodeAt(0)).toBe(0xFEFF);+ expect((await prepareFileTarget(engine, row, snapshot, 'Replacement'))?.path).toBe(file);+});++// #6605 review: `gbrain reindex` on an unmanaged brain imports with `inferFrontmatter: false`, so its row carries no+// inferred keys. The raw reading of the untouched file still matches it after the brain is managed.+test('a row imported without inference (unmanaged reindex) still matches its untouched frontmatter-less file', async () => {+ const rel = 'Apple Notes/Ideas/2021-06-24 Reindexed.md';+ const slug = slugifyPath(rel);+ const parsed = parseMarkdown('Body without inference.\n', rel);+ await engine.putPage(slug, { type: parsed.type, title: parsed.title, compiled_truth: parsed.compiled_truth, timeline: parsed.timeline,+ frontmatter: parsed.frontmatter, tags: parsed.tags }, { sourceId });+ await engine.executeRaw('UPDATE pages SET source_path=$1 WHERE source_id=$2 AND slug=$3', [rel, sourceId, slug]);+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;+ expect(snapshot.page.frontmatter ?? {}).toEqual({});+ const file = join(root, rel);+ mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, 'Body without inference.\n');+ expect((await prepareFileTarget(engine, { source_id: sourceId, worktree_id: worktreeId, slug }, snapshot, 'Replacement'))?.path).toBe(file);+});diff --git a/test/purge-global-marker.test.ts b/test/purge-global-marker.test.tsindex 5f1c862fbf..b840e13370 100644--- a/test/purge-global-marker.test.ts+++ b/test/purge-global-marker.test.ts@@ -116,8 +116,8 @@ describe("subject-'*' purges resolve per overlay", () => {await purgedEverywhere(engine, slug);const snapshot = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;expect(snapshot.withdrawals.filter(w => w.purged)).toEqual([]);- expect(await fileMatchesSnapshot(engine, slug, pageBody(slug), snapshot)).toBe(true);- expect(await fileMatchesSnapshot(engine, slug, pageBody(slug) + '\nAn uncoordinated local edit.\n', snapshot)).toBe(false);+ expect(await fileMatchesSnapshot(engine, slug, pageBody(slug), snapshot, `${slug}.md`)).toBe(true);+ expect(await fileMatchesSnapshot(engine, slug, pageBody(slug) + '\nAn uncoordinated local edit.\n', snapshot, `${slug}.md`)).toBe(false);}}), 60_000);diff --git a/test/reconcile-inferred-6605.test.ts b/test/reconcile-inferred-6605.test.tsnew file mode 100644index 0000000000..5868a5c285--- /dev/null+++ b/test/reconcile-inferred-6605.test.ts@@ -0,0 +1,59 @@+/**+ * #6605 (revision 2): reconcile read a canonical file's raw bytes, so a frontmatter-less file under a+ * directory-inference rule showed every key the importer inferred from its path as a difference from the+ * stored row. The file side is now read the way the importer read it.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromFile } from '../src/core/import-file.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { registerLocalWriter, withVerifiedLocalRegistration } from '../src/core/persistence/identity.ts';+import { runReconcileApply, runReconcilePreview } from '../src/core/persistence/reconcile.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { slugifyPath } from '../src/core/sync.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-reconcile-inferred-'));+let engine: PGLiteEngine;+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);+afterAll(async () => {+ await withEnv({ GBRAIN_HOME: home }, async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });+ rmSync(home, { recursive: true, force: true });+});++const REL = 'Apple Notes/Ideas/2021-06-20 Packing list.md';++test('an untouched inferred-path file reconciles as unchanged; a body edit shows only the body', async () => {+ await withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {+ const id = `inferred-${randomUUID().slice(0, 8)}`, root = join(home, id);+ mkdirSync(join(root, 'Apple Notes/Ideas'), { recursive: true });+ writeFileSync(join(root, REL), 'Passport, charger, notebook.\n');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{"slug_root_mode":"source-root"}\')', [id, root]);+ const imported = await importFromFile(engine, join(root, REL), REL, { sourceId: id, noEmbed: true });+ expect(imported.status).toBe('imported');+ const slug = slugifyPath(REL);+ const stored = (await engine.readPageSnapshot(slug, { sourceId: id }))!;+ expect(Object.keys(stored.page.frontmatter ?? {}).sort()).toEqual(['date', 'source']);+ await claimWorktree(engine, id, root);+ const registration = await registerLocalWriter(engine, 'cli');+ await withVerifiedLocalRegistration(engine, registration, async () => {+ const untouched = await runReconcilePreview(engine, { source_id: id, slug });+ expect(untouched.conflict_paths ?? []).toEqual([]);+ expect(untouched.status).toBe('ready');+ writeFileSync(join(root, REL), 'Passport, charger, notebook, adapter.\n');+ const edited = await runReconcilePreview(engine, { source_id: id, slug });+ expect(edited.conflict_paths).toEqual(['/compiled_truth']);+ const resolved = await runReconcilePreview(engine, { source_id: id, slug, from: edited.preview, decisions: [{ path: '/compiled_truth', action: 'take_file' }] });+ expect(resolved.status).toBe('ready');+ const receipt = await runReconcileApply(engine, { source_id: id, slug, preview: resolved.preview, request_id: randomUUID() });+ expect(receipt.state).toBe('committed');+ const after = (await engine.readPageSnapshot(slug, { sourceId: id }))!;+ expect(after.page.compiled_truth).toContain('adapter');+ expect(Object.keys(after.page.frontmatter ?? {}).sort()).toEqual(['date', 'source']);+ });+ });+}, 120_000);