Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(cycle): re-compare the canonical and dream files right before their renames (#6982, GBRA-131 D-5/D-7/D-8/D-9)
garrytan11ed9467722c
diff --git a/docs/architecture/key-files/core-cycle-patterns.md b/docs/architecture/key-files/core-cycle-patterns.mdindex 4db5c61526..7bcb35eba8 100644--- a/docs/architecture/key-files/core-cycle-patterns.md+++ b/docs/architecture/key-files/core-cycle-patterns.md@@ -21,7 +21,7 @@ Patterns, drift reports and the cycle modules listed after them.- `src/core/cycle/triage-rescue.ts` — THE dream triage gate (`passesTriageGate`) + the verified-segment rescue (`applyTriageRescue`). Rescue fires only for scores in `[floor, threshold)` (floor inclusive; at/above threshold is the plain gate's job) with content_type in the buried-signal allowlist (default mixed/reflection/idea/strategy/people — never routine/technical) and ≥ minSegments of the judge's own segments verifying as normalized transcript substrings (`normForGrounding`, ≥40 chars, deduped by normalized quote — repetition is not more evidence). $0 — no LLM calls; fabricated segments cannot fire it; works on cached verdicts (gate-time only). Fail-closed on every malformed shape (null score, missing/short/non-string segments), never throws. `minSegments: 0` is the kill switch (gate degenerates to the plain threshold). ONE-GATE RULE: `runTriagePass` (report construction — `worth`/`rescued`/telemetry/dry-run), the synthesize fan-out, and `dream retriage` (reconcile-queue cancels + `--audit-rejects` sampling) all read this predicate — a second hand-rolled `score >= threshold` check is how an operator sweep cancels exactly the jobs the rescue admitted. Config: `dream.triage.rescue_floor` / `rescue_min_segments` / `rescue_content_types`. Pinned by `test/cycle-triage-rescue.test.ts` + the rescue suites in `test/cycle-synthesize-triage.test.ts` / `test/dream-retriage.test.ts`. System One S7: a decide verdict (`model` starting with `DECIDE_VERDICT_PREFIX`) is gated against the S7 slot threshold (the optional fifth argument) and never enters the rescue band.-- `src/core/cycle/derived-write-through.ts` — opt-in markdown write-through for generated pages on an unmanaged brain (#5041). `cycle.extract_atoms.write_through` / `cycle.synthesize_concepts.write_through` (off by default; `true`/`1`/`yes`/`on`) make `derivedWriteThrough` return a hook (null when off, managed or dry run): `extract_atoms` writes each item's atoms after the completion flip and removes the files of atoms it retired; `synthesize_concepts` writes through `publishClassicConcept`, which also rewrites a concept that already has a file whatever the key says. Creating the hook writes up to 200 generated pages per run that have no file yet (`source_path` NULL; pending atoms excluded), so enabling the key backfills. `writeDerivedPageThrough` keeps a page database-only when its target is ignored by git or sits in a declared `storage.db_only` directory (`derivedFileTarget`), replaces an existing file only when `replaceableFile` (`facts/file-body-guard.ts`) finds it equal to the page or one of its recent page_versions rows, then calls `writePageThrough` bound to the bytes compared and returns its result (`written`, `skipped`, `error`) so `publishClassicConcept` can surface a failed write. A retired atom's file is removed under the same filter and comparison, the unlink rechecking the bytes under the source filesystem lock. A file holding an edit the database lacks (or an unindexed file at a backfilled page's path) is left as it is and listed in the hook's `held`, which both phases report as `details.file_holds` (`file_database_drift`) with a `warn` status. Tests: `test/cycle/derived-write-through.test.ts`, `test/pathological/d10-derived-atom-file-overwrite.test.ts`, `test/pathological/d11-derived-retired-atom-unlink.test.ts`. #6982: `writeDreamPageFile` is the dream reverse-write (synthesize, patterns, the cycle summary): nothing with `sync.write_through` off, for an owned url clone or a `storage.db_only` slug; the path is `resolvePageWriteTarget`'s (recorded source_path), falling back to the caller's brainDir layout when the source has no root or its root is missing; the file is replaced only when `replaceableFile` (facts/file-body-guard.ts) finds nothing in it the database lacks and still holds the compared bytes right before a staged rename, else the result carries the `file_database_drift` hold. It writes directly (not `writePageThrough`/`atomicWriteFileSync`) because a checkout a subagent tool write claimed through the coordinator refuses those with `writer_coordinator_required`. `reportFileHolds` lists every phase's holds in `details.file_holds` and turns ok into warn.+- `src/core/cycle/derived-write-through.ts` — opt-in markdown write-through for generated pages on an unmanaged brain (#5041). `cycle.extract_atoms.write_through` / `cycle.synthesize_concepts.write_through` (off by default; `true`/`1`/`yes`/`on`) make `derivedWriteThrough` return a hook (null when off, managed or dry run): `extract_atoms` writes each item's atoms after the completion flip and removes the files of atoms it retired; `synthesize_concepts` writes through `publishClassicConcept`, which also rewrites a concept that already has a file whatever the key says. Creating the hook writes up to 200 generated pages per run that have no file yet (`source_path` NULL; pending atoms excluded), so enabling the key backfills. `writeDerivedPageThrough` keeps a page database-only when its target is ignored by git or sits in a declared `storage.db_only` directory (`derivedFileTarget`), replaces an existing file only when `replaceableFile` (`facts/file-body-guard.ts`) finds it equal to the page or one of its recent page_versions rows, then calls `writePageThrough` bound to the bytes compared and returns its result (`written`, `skipped`, `error`) so `publishClassicConcept` can surface a failed write. A retired atom's file is removed under the same filter and comparison, the unlink rechecking the bytes under the source filesystem lock. A file holding an edit the database lacks (or an unindexed file at a backfilled page's path) is left as it is and listed in the hook's `held`, which both phases report as `details.file_holds` (`file_database_drift`) with a `warn` status. Tests: `test/cycle/derived-write-through.test.ts`, `test/pathological/d10-derived-atom-file-overwrite.test.ts`, `test/pathological/d11-derived-retired-atom-unlink.test.ts`. #6982: `writeDreamPageFile` is the dream reverse-write (synthesize, patterns, the cycle summary): nothing with `sync.write_through` off, for an owned url clone or a `storage.db_only` slug; the path is `resolvePageWriteTarget`'s (recorded source_path), falling back to the caller's brainDir layout when the source has no root or its root is missing; the file is replaced only when `replaceableFile` (facts/file-body-guard.ts) finds nothing in it the database lacks and, once the replacement is staged, still holds the compared bytes right before the rename, else the result carries the `file_database_drift` hold. It writes directly (not `writePageThrough`/`atomicWriteFileSync`) because a checkout a subagent tool write claimed through the coordinator refuses those with `writer_coordinator_required`. `reportFileHolds` lists every phase's holds in `details.file_holds` and turns ok into warn.- `src/core/cycle/concept-publication.ts` — managed `synthesize_concepts` publication: `publishManagedConcept` publishes through `publishMaintenancePage` (a concept with a recorded `source_path` republishes to its file unless a `db_only` tier covers it; new concepts are database-only), and `composeConceptRepublication` keeps an existing concept's facts/takes fences, timeline, tags and other frontmatter, holding the concept (`concept_preservation_hold`) when a fence is duplicated, unbalanced, unparseable or below the timeline sentinel. `addManagedProvenanceLinks` commits the concept-provenance edges inside a coordinated transaction. On an unmanaged brain `publishClassicConcept` writes under the page lock the fence writers take: it re-reads the page, defers (`revision_conflict`) when the narrative changed since synthesis started, another writer owns it, or the page's canonical file holds anything the database lacks (`replaceableFile`: body, fences, timeline, frontmatter, tags, type or title equal to neither the page nor a recent page_versions row; formatting is ignored; this also covers an unindexed file at a new concept's path, and the message names the page with `file_database_drift`), and otherwise composes the new narrative with the database's latest fences, timeline, tags and frontmatter, so a take added during synthesis survives (`test/pathological/d12-concept-stale-fences.test.ts`, `d13-concept-occupied-path.test.ts`). The file write after `importPage` passes the bytes read under the lock as `expectedFileBytes`, so an edit landing during the import is kept and the concept deferred; a failed file write holds the concept (`concept_write_through_failed`) instead of reporting success (W9F item 3, `test/cycle/concept-publication-file-recheck.test.ts`). `stripFenceSections` is the shared narrative view. Tests: `test/cycle/synthesize-concepts-fences.test.ts`. The phase keeps the private-first, provenance, then promotion order; revision races are deferred and holds rep... (line truncated to 2000 chars)- `src/core/cycle/connector-atoms.ts` — the connector atom setting (#5856). `CONNECTOR_ATOM_PAGES_KEY` (`cycle.extract_atoms.connector_pages`, on when unset; `connectorAtomPagesEnabled` treats only false/0/off/no as opted out) gates `CONNECTOR_ATOM_PAGE_TYPES` (`email`, `meeting`) of sources whose `config.kind` is a connector kind (`CONNECTOR_SOURCE_KINDS`). `connectorAtomExclusionSql` returns the `pages p` predicate atom discovery and the backlog count append (empty unless opted out), so the routine cycle, `dream --drain` and autopilot auto-drain extract connector mail and calendar pages under the auto-drain budget until the user opts out. Other page types of a connector source and every checkout-backed page are unaffected. Tests: `test/connector-atom-pages.test.ts`, `test/autopilot-auto-drain-dispatch.test.ts`, and the `atom_drain_default_on` / `atom_drain_opted_out` cases of `test/helpers/managed-connector-job-contract.ts`, run by `test/managed-connector-job-contract.test.ts` and its Postgres twin `test/e2e/managed-connector-job-contract.test.ts`.diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex c87940b5c3..889892d297 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -4,7 +4,7 @@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.- `src/core/cycle/dream-provenance.ts` — `summaryProvenanceLines` (#6642) writes the cycle summary's provenance section: `dream_cycle_date` is first-write provenance, so it reports the count the recovery query returns and, separately, the pages this cycle rewrote that keep an earlier cycle's date. `stampDreamProvenance`, the unmanaged dream-output identity stamp shared by synthesize and patterns: sets `dream_generated`, a stable `dream_cycle_date` / `dream_created_cycle_date` and an optional `raw_source` in page frontmatter, and leaves a page that existed before the child's first write to it (`first_write_at`) unstamped. Managed brains stamp through maintenance writes instead. A ref's optional `seat` is stamped beside `raw_source` (the capturing agent seat, #4618). #5575 I2: a ref carrying `derivation` is stamped in `derivedMaintenanceTransaction` at the child's derived tier, and the page is lowered to it and gets its `derivation_inputs` edges even when it is not dream-owned (the child wrote it from that prompt). Pinned by `test/trust-taint-dream.test.ts`.-- `src/core/cycle/dream-taint.ts` — #5575 I2 taint for the dream derivers (ENG-3): `transcriptDerivation` gives a synthesis transcript's tier (a `gbrain-page://` conversation page = that page's stored tier, with an edge to it; a file under `dream.synthesize.meeting_transcripts_dir` = external_untrusted; any other corpus file = the cap its frontmatter names, else agent_written); `transcriptsDerivation` takes the least trusted of several; `withTranscriptTaint` attaches it to unmanaged output refs; `summaryDerivation` / `putDerivedPage` write the dream summary at the tier of the pages it indexes; `patternsDerivation` is one patterns pass's tier over the reflections in its prompt. The tier is read when outputs are stamped (a page can only be lowered meanwhile). Pinned by `test/trust-taint-dream.test.ts`. #6982 (GBRA-131 D-9): `putDerivedPage` keeps a live body it replaces with a different one in page_versions first (raw putPage keeps none).+- `src/core/cycle/dream-taint.ts` — #5575 I2 taint for the dream derivers (ENG-3): `transcriptDerivation` gives a synthesis transcript's tier (a `gbrain-page://` conversation page = that page's stored tier, with an edge to it; a file under `dream.synthesize.meeting_transcripts_dir` = external_untrusted; any other corpus file = the cap its frontmatter names, else agent_written); `transcriptsDerivation` takes the least trusted of several; `withTranscriptTaint` attaches it to unmanaged output refs; `summaryDerivation` / `putDerivedPage` write the dream summary at the tier of the pages it indexes; `patternsDerivation` is one patterns pass's tier over the reflections in its prompt. The tier is read when outputs are stamped (a page can only be lowered meanwhile). Pinned by `test/trust-taint-dream.test.ts`. #6982 (GBRA-131 D-9): `putDerivedPage` keeps a live body it replaces with a different one in page_versions first (raw putPage keeps none) and stores the tags the summary file declares, so a same-date rerun finds its own file replaceable.- `src/core/cycle/extract-atoms-schema.ts` — shared atom-type vocabulary and the extraction response schema. The private model prompt requests an object containing `atoms`; the schema uses closed objects and nullable optional metadata. `extract-atoms.ts` passes it through the gateway's capability gate and existing schema-rejection fallback, while its tolerant parser still accepts legacy bare arrays. Schema submission does not replace grounding or malformed-output checks. Covered by `test/cycle/extract-atoms-structured-output.test.ts` using a local HTTP protocol fixture and isolated PGLite, without live model inference.- `src/core/cycle/extract-atoms-parse.ts` — extract_atoms response parsing, re-exported by `extract-atoms.ts`. `parseAtomsOutcome` returns a typed outcome (`ok: false` with a stable reason string for malformed output, `ok: true, atoms: []` for an honest zero-yield), retrying once with reasoning blocks stripped. `parseAtomsOutcome(text, stopReason)` takes the gateway stop reason: `length`/`refusal`/`content_filter` are never parsed, and an empty answer under `other`/`tool_calls` is not taken as complete; both return `ok: false, stopped: true`, which `extract-atoms.ts` counts in `details.stopped_outputs` and fails like malformed output (unmanaged: the bounded streak; managed: a failure receipt that never retires earlier atoms; `test/cycle/extract-atoms-stop-reason.test.ts`, `test/managed-atoms-stop-reason.test.ts`). A bounded anchor scan (`MAX_ARRAY_ANCHOR_CANDIDATES`) tries successive `[` offsets; each candidate ends at its own closing bracket (`matchingCloseBracket` in `llm-json.ts`), the first array yielding an atom-shaped element wins, a literal `[]` is zero-yield only when no earlier `[` is still open at its offset (an atom's own `"concepts": []` inside a clipped or malformed array is malformed output, `test/extract-atoms-nested-empty-array.test.ts`), and failure reasons always describe the first bracket. `atomsFromParsedArray` is the single atom shape gate.@@ -43,7 +43,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cycle/dream-breaker.ts` — dream paid-loop circuit breaker. `countDeadDreamSubmissions` is the one counting rule shared by synthesize, patterns, `gbrain dream reset-key` and the `dream_paid_loop` doctor check: dead `subagent` rows finished in the last 24 h (partial index `idx_minion_jobs_dead_subagent_finished`, migration 173), keyed by the live or released idempotency key with the `:c<i>of<n>` chunk suffix stripped, counted as distinct queues (one per run), ignoring deaths before the key's persisted reset (`dream.breaker.resets` config JSON, database clock). A key at `dream.breaker.max_dead_submissions` (default 3; 0 disables) is refused before synthesis submission; a failed count leaves the breaker off for that run with a warning. Completed jobs, including legitimate zero-write completions, never count. Growing transcripts change their content-hashed key and unkeyed patterns runs are not covered. Contained cycle-phase failures after paid model calls (`recordContainedPaidFailure`, `dream.breaker.contained_failures` config JSON, 24 h window, database clock) are counted under `dream:phase:<phase>:<source>` keys; the breaker never refuses those phases, doctor reports them and `gbrain dream reset-key` clears them. Tests: `test/dream-breaker.test.ts`, `test/cycle-synthesize-breaker.test.ts`, `test/e2e/dream-breaker-postgres.test.ts`. Patterns rows count under the per-source key `dream:patterns:source:<data.source_id or default>` (never their content key), and a patterns child `cancelled` with recorded tokens counts as a death; `patternsBreakerSkip` returns the phase skip (`dream_breaker_tripped`, paid reset `fix`, read-only `--list --json` verify) and `clearPatternsSourceDeaths` resets the source after a completed child (`test/dream-breaker-patterns-source.test.ts`).-- `src/core/cycle/phantom-redirect.ts` — Phantom-redirect orchestrator. Exports `runPhantomRedirectPass(engine, brainDir, sourceId, dryRun): Promise<PhantomPassResult>` (per-cycle wrapper acquiring the `gbrain-sync` writer lock once for the whole pass, 30s bounded retry, walks up to `GBRAIN_PHANTOM_REDIRECT_LIMIT` unprefixed phantoms) + `tryRedirectPhantom(engine, page, sourceId, brainDir, dryRun): Promise<RedirectResult>` + `stripFenceAndFrontmatterAndLeadingH1` (pure body-shape gate helper — strips facts fence incl. preceding `## Facts` heading and the leading H1). Only fence rows migrate, so the residue gate also counts the page's timeline text, any `timeline_entries` row, and frontmatter keys beyond `title`/`type`/`tags`; any residue = not a phantom. Handler order: body-shape gate → `resolvePhantomCanonical` (bypasses exact-self-match; a fuzzy hit needs a 0.1 margin over the runner-up) → `findPrefixCandidates` ambiguity check (a canonical that is not the single prefix candidate is ambiguous too) → `fenceDbDrift` bi-directional check → a phantom fence that parses with warnings is `drift` (its skipped rows would go with the deleted phantom, #6385 R12) → dry-run early exit → canonical file resolved through `resolvePageWriteTarget` (recorded `source_path`, own-`local_path` roots; only a brain with no configured root falls back to `brainDir`) → materialize canonical via `serializeMarkdown` if DB-only → append phantom fence rows to that file with `(claim, valid_from)` dedup-guard, numbering past both the file's and the DB's highest row number and rewriting `superseded by #N` to the new numbers → `engine.refreshPageBody` → move the phantom's fact withdrawals to the canonical subject → move every phantom fact row by id (a row takes its on-disk canonical row number unless the canonical index already holds it; history, duplicates and rows absent from the fence move expired and detached, never deleted) → move the phantom's links to the canonical page id (skipping duplicates and self-links) → `recordRenameAlias` (phantom → canonical in `slug_aliases`) → `engine.softDeletePage` + unlink. `RedirectResult.canonical` populated on `'redirected'` (incl. dry-run preview) so the caller builds `touched_canonicals`. Idempotent on re-run: phantom soft-deleted → predicate fails (`deleted_at IS NULL`); migrate UPDATE matches no rows; dedup-guard prevents double-append. `mergePhantomFenceRows` (pure body merge; throws `FenceRewriteRefusal` on a canonical fence that parses with warnings, which the pass records as `drift`), `movePhantomFacts` (row move inside the caller's transaction) and `mergePhantomLinks` are shared with `phantom-redirect-managed.ts`, which a managed brain uses instead of the file-first commit phase. GBRA-130 A-24: the pass resumes after the last slug it examined (`slug > cursor`, op_checkpoints op `PHANTOM_REDIRECT_CURSOR_OP` = `phantom-redirect-cursor`, fingerprint the source id, via `rotationAfter`/`saveRotation`), so root prose notes that are not phantoms no longer starve later phantoms; the cursor resets to `''` after a full pass and stays put on a dry run, an abort or a stop. Phantoms run as `ItemRun` items (`extract_facts.phantom_redirect`): an item error is a `failures[]` entry (`key`, `code`, `message`, `fix` `gbrain dream --phase extract_facts --source <id>`) and the next phantom still runs; a run-scoped error rethrows and `item_failures_systemic` sets `stopped`. `extract-facts.ts` turns them into `phantom_redirect_failed: <slug> (<code>); retry: <fix>` and `phantom_redirect_stopped: …` warnings. Pinned by `test/pathological/a24-phantom-redirect-cursor.test.ts` (both engines). #6982 (GBRA-131 D-5/D-6): with `sync.write_through` off the phantom's rows merge into the canonical's database body under a row lock (prior body in page_versions) and no file is written or removed. With it on, the phantom's file is removed only when `replaceableFile` finds nothing in it its row lacks (re-read right before the unlink; a changed file is kept and reported), and the canonical file takes the rows only when its body and timeline equal the canonical's database body; the mirror then runs under the row lock (`mirrorFileBody`, prior body in page_versions, importer hash) with the `.tmp` renamed last, and a body or file that moved holds the phantom. Holds are `drift` outcomes listed in `PhantomPassResult.held` (`<slug> (file_database_drift: …)` with its fix), which extract_facts turns into `phantom_redirect_held:` warnings. Pinned by `test/pathological/d5-phantom-canonical-overwrite.test.ts` and `test/pathological/d6-phantom-file-unlink.test.ts` (both engines).+- `src/core/cycle/phantom-redirect.ts` — Phantom-redirect orchestrator. Exports `runPhantomRedirectPass(engine, brainDir, sourceId, dryRun): Promise<PhantomPassResult>` (per-cycle wrapper acquiring the `gbrain-sync` writer lock once for the whole pass, 30s bounded retry, walks up to `GBRAIN_PHANTOM_REDIRECT_LIMIT` unprefixed phantoms) + `tryRedirectPhantom(engine, page, sourceId, brainDir, dryRun): Promise<RedirectResult>` + `stripFenceAndFrontmatterAndLeadingH1` (pure body-shape gate helper — strips facts fence incl. preceding `## Facts` heading and the leading H1). Only fence rows migrate, so the residue gate also counts the page's timeline text, any `timeline_entries` row, and frontmatter keys beyond `title`/`type`/`tags`; any residue = not a phantom. Handler order: body-shape gate → `resolvePhantomCanonical` (bypasses exact-self-match; a fuzzy hit needs a 0.1 margin over the runner-up) → `findPrefixCandidates` ambiguity check (a canonical that is not the single prefix candidate is ambiguous too) → `fenceDbDrift` bi-directional check → a phantom fence that parses with warnings is `drift` (its skipped rows would go with the deleted phantom, #6385 R12) → dry-run early exit → canonical file resolved through `resolvePageWriteTarget` (recorded `source_path`, own-`local_path` roots; only a brain with no configured root falls back to `brainDir`) → materialize canonical via `serializeMarkdown` if DB-only → append phantom fence rows to that file with `(claim, valid_from)` dedup-guard, numbering past both the file's and the DB's highest row number and rewriting `superseded by #N` to the new numbers → `engine.refreshPageBody` → move the phantom's fact withdrawals to the canonical subject → move every phantom fact row by id (a row takes its on-disk canonical row number unless the canonical index already holds it; history, duplicates and rows absent from the fence move expired and detached, never deleted) → move the phantom's links to the canonical page id (skipping duplicates and self-links) → `recordRenameAlias` (phantom → canonical in `slug_aliases`) → `engine.softDeletePage` + unlink. `RedirectResult.canonical` populated on `'redirected'` (incl. dry-run preview) so the caller builds `touched_canonicals`. Idempotent on re-run: phantom soft-deleted → predicate fails (`deleted_at IS NULL`); migrate UPDATE matches no rows; dedup-guard prevents double-append. `mergePhantomFenceRows` (pure body merge; throws `FenceRewriteRefusal` on a canonical fence that parses with warnings, which the pass records as `drift`), `movePhantomFacts` (row move inside the caller's transaction) and `mergePhantomLinks` are shared with `phantom-redirect-managed.ts`, which a managed brain uses instead of the file-first commit phase. GBRA-130 A-24: the pass resumes after the last slug it examined (`slug > cursor`, op_checkpoints op `PHANTOM_REDIRECT_CURSOR_OP` = `phantom-redirect-cursor`, fingerprint the source id, via `rotationAfter`/`saveRotation`), so root prose notes that are not phantoms no longer starve later phantoms; the cursor resets to `''` after a full pass and stays put on a dry run, an abort or a stop. Phantoms run as `ItemRun` items (`extract_facts.phantom_redirect`): an item error is a `failures[]` entry (`key`, `code`, `message`, `fix` `gbrain dream --phase extract_facts --source <id>`) and the next phantom still runs; a run-scoped error rethrows and `item_failures_systemic` sets `stopped`. `extract-facts.ts` turns them into `phantom_redirect_failed: <slug> (<code>); retry: <fix>` and `phantom_redirect_stopped: …` warnings. Pinned by `test/pathological/a24-phantom-redirect-cursor.test.ts` (both engines). #6982 (GBRA-131 D-5/D-6): with `sync.write_through` off the phantom's rows merge into the canonical's database body under a row lock (prior body in page_versions) and no file is written or removed. With it on, the phantom's file is removed only when `replaceableFile` finds nothing in it its row lacks (re-read right before the unlink; a changed file is kept and reported), and the canonical file takes the rows only when its body and timeline equal the canonical's database body; the mirror then runs under the row lock (`mirrorFileBody`, prior body in page_versions, importer hash), the file is re-read immediately before the `.tmp` is renamed last, and a body that moved, or a file that moved (which rolls the transaction back), holds the phantom. Holds are `drift` outcomes listed in `PhantomPassResult.held` (`<slug> (file_database_drift: …)` with its fix), which extract_facts turns into `phantom_redirect_held:` warnings. Pinned by `test/pathological/d5-phantom-canonical-overwrite.test.ts` and `test/pathological/d6-phantom-file-unlink.test.ts` (both engines).- `src/core/cycle/phantom-redirect-managed.ts` — managed-brain phantom redirect (#5280). After the same gates, `redirectManagedPhantom` runs `maintenancePreflight`, renders the canonical body with the phantom's fence rows appended and submits `managed_maintenance_phantom_merge` on the canonical page (keyed by its intent): `preparePhantomMerge` rechecks the phantom's id and revision, and its publication moves withdrawals, the phantom's fact rows by id, links and the rename alias in the canonical page's publication transaction. It then submits `managed_maintenance_phantom_delete` on the phantom, bound to the merged revision: `preparePhantomDelete` holds both page keys, moves any edge added to the phantom since the merge, defers if timeline rows appeared, then soft-deletes and removes the file. A missing canonical page or a changed phantom is reported as `drift`. Tests: `test/managed-facts-writers.test.ts`.diff --git a/src/core/cycle/derived-write-through.ts b/src/core/cycle/derived-write-through.tsindex c9886cdc0c..8672ec9b7e 100644--- a/src/core/cycle/derived-write-through.ts+++ b/src/core/cycle/derived-write-through.ts@@ -21,7 +21,7 @@* the page is reported in the hook's `held` list (`file_database_drift`).*/import { execFileSync } from '../spawn.ts';-import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';import { dirname, join, relative } from 'node:path';import type { BrainEngine } from '../engine.ts';import type { PhaseResult } from '../cycle.ts';@@ -177,7 +177,8 @@ export type DreamPageFileWrite = { written: true; path: string } | { written: fa* file of record (`resolvePageWriteTarget`: recorded source_path, own-local_path roots); a source with no usable* checkout (no root configured, or the root is missing) keeps the caller's brainDir layout (`<brainDir>/<slug>.md`,* foreign sources under `.sources/<id>/`). The file is replaced only when `replaceableFile` finds nothing in it the- * database lacks, and is re-read right before the atomic write, so an edit that lands in between is kept as well.+ * database lacks, and is re-read after the replacement is staged, right before the rename, so an edit that lands in+ * between is kept as well.** This is the reverse-write's own direct write (a staged sibling renamed over the file), as before, not* `writePageThrough` or `atomicWriteFileSync`: once a subagent's tool write has gone through the coordinator, the@@ -198,12 +199,13 @@ export async function writeDreamPageFile(engine: BrainEngine, brainDir: string,: sourceId === opts.nativeSourceId ? join(brainDir, `${slug}.md`) : join(brainDir, '.sources', sourceId, `${slug}.md`);const check = await replaceableFile(engine, sourceId, slug, filePath);if (!check.ok) return { written: false, held: dreamFileDriftToken(slug, sourceId, 'before') };- if ((existsSync(filePath) ? readFileSync(filePath, 'utf-8') : null) !== check.expectedFileBytes) {- return { written: false, held: dreamFileDriftToken(slug, sourceId, 'during') };- }mkdirSync(dirname(filePath), { recursive: true });const staged = `${filePath}.${process.pid}.tmp`;writeFileSync(staged, opts.markdown, 'utf-8');+ if ((existsSync(filePath) ? readFileSync(filePath, 'utf-8') : null) !== check.expectedFileBytes) {+ rmSync(staged, { force: true });+ return { written: false, held: dreamFileDriftToken(slug, sourceId, 'during') };+ }renameSync(staged, filePath);return { written: true, path: filePath };}diff --git a/src/core/cycle/dream-taint.ts b/src/core/cycle/dream-taint.tsindex 8c31835ddd..49b81bfbf4 100644--- a/src/core/cycle/dream-taint.ts+++ b/src/core/cycle/dream-taint.ts@@ -70,14 +70,16 @@ export async function summaryDerivation(engine: BrainEngine, sourceId: string, s/*** An unmanaged derived page write (the dream summary): putPage at the derivation's tier, lowered, with its input edges.- * #6982: a live body it replaces with a different one is kept in page_versions first (putPage itself keeps none).+ * #6982: a live body it replaces with a different one is kept in page_versions first (putPage itself keeps none), and+ * `tags` (the ones its file declares) are stored as the importer stores them, so the file compares equal to the page.*/export async function putDerivedPage(engine: BrainEngine, derivation: Derivation, slug: string,- page: Parameters<BrainEngine['putPage']>[1], opts: { sourceId: string }): Promise<void> {+ page: Parameters<BrainEngine['putPage']>[1], opts: { sourceId: string; tags?: readonly string[] }): Promise<void> {await derivedMaintenanceTransaction(engine, derivation, async tx => {const prior = await readStoredBody(tx, opts.sourceId, slug, true);- if (prior && (prior.compiled_truth !== page.compiled_truth || (prior.timeline ?? '') !== (page.timeline ?? ''))) await tx.createVersion(slug, opts);- const written = await tx.putPage(slug, page, opts);+ if (prior && (prior.compiled_truth !== page.compiled_truth || (prior.timeline ?? '') !== (page.timeline ?? ''))) await tx.createVersion(slug, { sourceId: opts.sourceId });+ const written = await tx.putPage(slug, page, { sourceId: opts.sourceId });+ for (const tag of opts.tags ?? []) await tx.addTag(slug, tag, { sourceId: opts.sourceId, tagSource: 'frontmatter' });return { result: undefined, rows: [{ table: 'pages' as const, id: Number(written.id), sourceId: opts.sourceId }] };});}diff --git a/src/core/cycle/phantom-redirect.ts b/src/core/cycle/phantom-redirect.tsindex 9973e5bee0..43d3b7d17b 100644--- a/src/core/cycle/phantom-redirect.ts+++ b/src/core/cycle/phantom-redirect.ts@@ -241,10 +241,12 @@ async function acquireLockWithRetry(* #6982: the rows are planned on the file only when its body and timeline* equal the canonical's database body, so the mirror can only add them. The* canonical row is then locked and re-read in a maintenance transaction: when- * the database body or the file moved since the comparison, nothing is- * written and the phantom is held (`file_database_drift`). Otherwise the prior- * body is kept in page_versions, the body is mirrored and stamped with the- * hash the importer computes for the new file, and the `.tmp` is renamed last.+ * the database body moved since the comparison, nothing is written and the+ * phantom is held (`file_database_drift`). Otherwise the prior body is kept in+ * page_versions, the body is mirrored and stamped with the hash the importer+ * computes for the new file, and the file is re-read immediately before the+ * `.tmp` is renamed last: a file that moved rolls the transaction back and+ * holds the phantom the same way.* A parse-validation failure throws before any DB state has moved.*/async function mergeIntoCanonicalFile(@@ -280,11 +282,13 @@ async function mergeIntoCanonicalFile(const parsed = parseMarkdown(newBody, `${canonical}.md`);const hash = contentHash({ title: parsed.title, type: parsed.type, compiled_truth: parsed.compiled_truth, timeline: parsed.timeline,frontmatter: parsed.frontmatter, tags: await engine.getTags(canonical, { sourceId }) });+ const fileMoved = new Error('canonical file changed during the phantom redirect');const written = await maintenanceTransaction(engine, async tx => {- if (fs.readFileSync(canonicalPath, 'utf-8') !== bytes || !await mirrorFileBody(tx, sourceId, canonical, newBody, stored, hash)) return false;+ if (!await mirrorFileBody(tx, sourceId, canonical, newBody, stored, hash)) return false;+ if (fs.readFileSync(canonicalPath, 'utf-8') !== bytes) throw fileMoved;fs.renameSync(tmpPath, canonicalPath);return true;- });+ }).catch(err => { if (err === fileMoved) return false; throw err; });if (written) return { renumber };fs.rmSync(tmpPath, { force: true });return { held: canonicalDriftToken(canonical, phantomSlug, sourceId, 'during') };diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.tsindex 1eb2926067..8033aecb0b 100644--- a/src/core/cycle/synthesize.ts+++ b/src/core/cycle/synthesize.ts@@ -3104,7 +3104,7 @@ async function writeSummaryPage(compiled_truth: parsed.compiled_truth,timeline: parsed.timeline,frontmatter: parsed.frontmatter,- }, { sourceId });+ }, { sourceId, tags: parsed.tags });const fileWriteRaw = (await engine.getConfig('dream.synthesize.summary_file_write'))?.trim().toLowerCase();const fileWriteEnabled = !(fileWriteRaw === 'false' || fileWriteRaw === '0' || fileWriteRaw === 'off');diff --git a/test/cycle-synthesize-summary-page.test.ts b/test/cycle-synthesize-summary-page.test.tsindex 6113f4315e..e5680f168f 100644--- a/test/cycle-synthesize-summary-page.test.ts+++ b/test/cycle-synthesize-summary-page.test.ts@@ -48,6 +48,7 @@ async function renderSummary(writtenSlugs: string[]): Promise<{ body: string; ma// The summary write runs in a maintenance transaction; the stub is its own transaction engine.executeRaw: async () => [],transaction: async <T>(fn: (tx: BrainEngine) => Promise<T>) => fn(engine),+ addTag: async () => {},} as unknown as BrainEngine;try {await writeSummaryPage(diff --git a/test/pathological/d5-phantom-canonical-overwrite.test.ts b/test/pathological/d5-phantom-canonical-overwrite.test.tsindex a4b9c6732b..c1629e4707 100644--- a/test/pathological/d5-phantom-canonical-overwrite.test.ts+++ b/test/pathological/d5-phantom-canonical-overwrite.test.ts@@ -15,10 +15,14 @@* the body it replaces is kept in page_versions.* Fails when: the redirect appends to the canonical file and mirrors the whole* file over the database body without comparing (the pre-fix refreshPageBody- * path), which drops the database-only edit with no page_versions row.+ * path), which drops the database-only edit with no page_versions row; or when+ * the file is compared only before the transaction's database work, so a save+ * inside it is renamed over.* Seams: an engine proxy whose first transaction after the redirect prepared- * the canonical write lands a concurrent edit (database or file). PGLite- * always, Postgres when DATABASE_URL is set.+ * the canonical write lands a concurrent edit (database or file), and one that+ * saves the canonical file from inside that transaction, after the redirect's+ * row lock and page_versions read. PGLite always, Postgres when DATABASE_URL+ * is set.*/import { describe, expect, test } from 'bun:test';import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';@@ -123,6 +127,29 @@ function editsOnceCanonicalPrepared(engine: BrainEngine, file: string, before: (});}+/**+ * The engine whose first transaction after the redirect staged the canonical `.tmp` runs `during` inside that+ * transaction, when it first saves a page version: an edit that lands after the redirect's database work began.+ */+function editsInsideCanonicalTransaction(engine: BrainEngine, file: string, during: () => void): BrainEngine {+ let fired = false;+ return new Proxy(engine, {+ get(target, prop) {+ if (prop === 'transaction') return async <T>(fn: (tx: BrainEngine) => Promise<T>) => {+ if (fired || !existsSync(`${file}.tmp`)) return target.transaction(fn);+ fired = true;+ return target.transaction(async tx => {+ const createVersion = tx.createVersion;+ tx.createVersion = async (...args) => { during(); return createVersion.apply(tx, args); };+ try { return await fn(tx); } finally { tx.createVersion = createVersion; }+ });+ };+ const value = Reflect.get(target, prop, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+}+for (const { backend, databaseUrl } of pathologicalArms()) {describe(`D-5 phantom redirect and a canonical database body that differs from its file (${backend})`, () => {test('D-5 db-newer, write-through on: the phantom is held with file_database_drift and both canonical copies stay', async () => {@@ -205,5 +232,21 @@ for (const { backend, databaseUrl } of pathologicalArms()) {.toEqual({ redirected: 0, held: 1, phantomLive: true });});}, 180_000);++ test('D-5 file edit inside the redirect\'s transaction: the editor\'s bytes survive, the transaction rolls back and the phantom is held', async () => {+ await withBrain(databaseUrl, async b => {+ const [bodyBefore, versionsBefore] = [await b.body(CANONICAL), await b.versionsHolding(CANONICAL, 'works at acme-example')];+ const edited = `${CANONICAL_BODY}\n${LATE_EDIT}\n`;+ let landed = false;+ const racing = editsInsideCanonicalTransaction(b.engine, b.path(CANONICAL), () => { writeFileSync(b.path(CANONICAL), edited); landed = true; });+ const result = await expectUnitNotAborted(() => b.pass(racing));+ expect(landed).toBe(true);+ expect({ file: b.file(CANONICAL) === edited, tmp: existsSync(`${b.path(CANONICAL)}.tmp`) }).toEqual({ file: true, tmp: false });+ expect({ body: (await b.body(CANONICAL)) === bodyBefore, versions: await b.versionsHolding(CANONICAL, 'works at acme-example') })+ .toEqual({ body: true, versions: versionsBefore });+ expect({ redirected: result.redirected, held: heldFor(result, CANONICAL).length, phantomLive: await b.live(PHANTOM) })+ .toEqual({ redirected: 0, held: 1, phantomLive: true });+ });+ }, 180_000);});}diff --git a/test/pathological/dream-reverse-write-fixture.ts b/test/pathological/dream-reverse-write-fixture.tsindex 67083c3e43..e136425fe0 100644--- a/test/pathological/dream-reverse-write-fixture.ts+++ b/test/pathological/dream-reverse-write-fixture.ts@@ -3,8 +3,9 @@* source checkout is a temp directory, one dream output page imported twice (the second import is the child's write,* which keeps the first in page_versions), and the reverse-write under test run against it.*/-import { describe, expect, test } from 'bun:test';-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { describe, expect, spyOn, test } from 'bun:test';+import * as fs from 'node:fs';+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';import type { BrainEngine } from '../../src/core/engine.ts';@@ -157,6 +158,24 @@ export function reverseWriteCases(id: string, phase: string, reverseWrite: Rever});}, 180_000);+ test(`${id} file edit while the replacement is staged: the editor's bytes survive, the staged file is removed and the page is held`, async () => {+ await withBrain(databaseUrl, reverseWrite, async b => {+ b.writeFirstRunFile();+ const edited = `${b.file()}\n${LATE_EDIT}\n`;+ const realWrite = fs.writeFileSync;+ let landed = false;+ const staging = spyOn(fs, 'writeFileSync').mockImplementation(((path: fs.PathOrFileDescriptor, ...rest: unknown[]) => {+ if (!landed && String(path).startsWith(`${b.path}.`) && String(path).endsWith('.tmp')) { realWrite(b.path, edited); landed = true; }+ return (realWrite as (...a: unknown[]) => void)(path, ...rest);+ }) as typeof fs.writeFileSync);+ let result: { written: number; held: string[] };+ try { result = await expectUnitNotAborted(() => b.run()); } finally { staging.mockRestore(); }+ expect(landed).toBe(true);+ expect({ written: result.written, held: heldFor(result.held).length, file: b.file() === edited,+ staged: readdirSync(dirname(b.path)).filter(name => name.endsWith('.tmp')) }).toEqual({ written: 0, held: 1, file: true, staged: [] });+ });+ }, 180_000);+test(`${id} control, no file yet: the page's file is written`, async () => {await withBrain(databaseUrl, reverseWrite, async b => {const result = await expectUnitNotAborted(() => b.run());