Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
GBRA-161 PR 5: revision fence for timeline retraction, mention rebuild and concept provenance edges (T-2, L-6, C-4)
garrytanb7d7d47e7b11
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex 6fc00fc40d..d8f7d86213 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -6,6 +6,7 @@ src/core/persistence/derived-retirement-hold.ts 2 contract retireDerivedPages vesrc/core/generations/adapters/page.ts 1 contract GBRA-161: importPageItem writes a derived page item through importFromContent inside the generation activation's maintenanceTransaction (publish.ts), behind the canonical table trigger; managed brains keep the coordinator path.src/core/generations/adapters/atoms.ts 1 contract GBRA-161: the unmanaged atom completion flip (source_hash) runs in the generation activation's maintenanceTransaction after every atom and provenance edge was written and before the items are rechecked live; managed brains keep the coordinator path.src/core/generations/adapters/chronicle-events.ts 4 contract GBRA-161 PR 3: the Life Chronicle event adapter writes event pages and their depth timeline projection rows, and removes a retired event's projection row, only inside publishGeneration's maintenanceTransaction or the coordinated managed_generation_activate/_restore request, under the depth and event page keys; managed event pages keep the managed_maintenance_chronicle_event request.+src/core/generations/adapters/single-page.ts 2 contract GBRA-161 PR 5: the single-item page adapter writes the dream summary, think synthesis or drift report page (its live prior copied to page_versions first) and its tags only inside publishGeneration's maintenanceTransaction under the page key, bound to the expected revision the writer read before composing; managed brains keep their managed_maintenance page request.src/core/generations/managed-retire.ts 1 coordinator GBRA-161 PR 4: a managed synthesis generation retires each matched earlier output through one managed_generation_retire request, whose preparer runs the versioned page delete and stamps retired_by/retired_at inside the coordinated write, refusing unless the item is pending on the live generation its activation madesrc/core/persistence/links-maintenance.ts 1 coordinator Managed extract --stale and post-sync extraction add only the coordinator's unrecorded canonical timeline tuples inside a revision-bound withCoordinatedWrite transaction that also replaces the page's derived links and stamps its watermark.src/core/extract-takes-from-pages.ts 0 coordinator Managed bootstrap submits one revision-checked put_page per source page so its complete takes fence and projected rows commit together; unmanaged writes retain the md-first helper.@@ -200,6 +201,7 @@ src/core/persistence/purge-deleted.ts 3 coordinator Unmanaged brains keep the ensrc/core/persistence/unbound-source.ts 1 coordinator Stamps the durable unbound_source classification on a page inside the coordinator publication transaction that published it; the column is not a canonical content column.src/core/persistence/detached-pages.ts 1 coordinator #6609 restore --detach: clears source_path and stamps database_only_reason='detached' on the restored page only from classifyUnboundPage inside the restore_page coordinator publication transaction; neither is a canonical content column.src/core/cycle/synthesize-concepts.ts 2 coordinator A managed brain publishes concepts through publishMaintenancePage after maintenancePreflight; the unmanaged importFromContent path refuses on managed brains.+src/core/cycle/concept-publication.ts 1 coordinator GBRA-161 PR 5 (C-4): replaceConceptProvenanceLinks retires the concept-provenance edges of atoms that left a republished concept's group and banks the new edges in one transaction, coordinated (withCoordinatedWrite) on a managed brain, and only while the concept is still at the revision its publication produced.src/core/cycle/synthesize-verify.ts 2 early_refusal Legacy direct content import. Direct importFromContent calls without prepare refuse on managed brains before any write (assertUnmanagedCanonicalWriter).src/core/persistence/reconcile-prepare.ts 3 coordinator Coordinated preparation module. Its importFromContent calls carry prepare and run inside the coordinator publication. The reconcile publication callback records the slug-derived source_path of a database-only page (the #5254 unbound collision) inside the admitted put_page transaction, after the pinned preimages and backup verify; it touches only the reconciled page and only while its source_path is still NULL. When the reconciled page gains a canonical origin, the same callback clears its #5254 unbound_source classification.src/commands/brainstorm.ts 1 early_refusal Legacy direct content import. Direct importFromContent calls without prepare refuse on managed brains before any write (assertUnmanagedCanonicalWriter).@@ -254,7 +256,6 @@ src/core/persistence/page-purge.ts 4 coordinator purgePageInTransaction deletessrc/core/trust/fence-append.ts 1 coordinator withPageTierKept restores the page's prior trust_tier and write_origin in the same coordinated fence-append transaction that wrote the page (fence-write, facts-prepare and memory-prepare callers); it changes no content column.src/commands/sources-trust.ts 1 engine_guard gbrain sources set-trust rewrites only the source's config jsonb (its default trust tier for future writes); the managed writer guard exempts sources rows whose id, incarnation, local_path, archived and checkpoint columns are unchanged, and no knowledge row changes.src/core/trust/claim.ts 2 engine_guard gbrain trust claim-sources records the claim and its lift receipt in the source's config jsonb only (like sources set-trust); the managed writer guard exempts sources rows whose identity columns are unchanged. The tier lift itself runs through trust/backfill.ts inside withCoordinatedWrite on a managed brain.-src/core/cycle/dream-taint.ts 2 engine_guard putDerivedPage writes the unmanaged dream summary page inside derivedMaintenanceTransaction (attributed, tier lowered to the derivation's taint); on a managed brain the canonical table trigger refuses the write outside the coordinator. It also stores the frontmatter tags the summary file declares (addTag, same transaction) so its own file stays replaceable on a same-date rerun (#6982), after saving a page_versions row of a different prior body.src/core/persistence/derived-facts.ts 1 coordinator insertGatedFacts inserts only gate-allowed conversation fact rows; writeDerivedFacts refuses on a managed brain (writer_coordinator_required) and otherwise runs it inside the attributed maintenance transaction with taint edges.src/core/trust/fence-guard.ts 2 coordinator guardFenceRows detaches and renumbers fence rows more trusted than the writer inside the canonical fence re-projection of the page publication (canonical-projections.ts), in the same journal transaction as the receipt.src/core/trust/held-removals.ts 3 coordinator The owner accept of a held take or timeline removal deletes or re-projects that one row as the page now says, inside withCoordinatedWrite under the page key on a managed brain (withWriteAttribution otherwise), in the transaction that decides the proposal; a refused takes_remove instead reruns as an owner takes_remove through the takes request preparer.diff --git a/docs/architecture/generations.md b/docs/architecture/generations.mdindex a34e3c12fa..4a10501f0f 100644--- a/docs/architecture/generations.md+++ b/docs/architecture/generations.md@@ -97,6 +97,32 @@ the plan approved on Oct 21: replace only on a complete, non-empty result, alwaydelete per retirement (`managed_generation_retire`, `generations/managed-retire.ts`) in one transaction; the next runresumes a retirement left behind.+### Single-page kinds and fence-only writers (PR 5)++Three derived pages one writer rewrites in place under a fixed slug publish as single-item generations+(`adapters/single-page.ts`, owner key `page:<slug>`): the dream summary (kind `dream_summary`, S-2), the `think`+synthesis page (`think_synthesis`, S-10) and the drift report (`drift_report`, S-11). The writer reads the page revision+before it composes (the summary before its children are submitted, the drift report before the judge loop, the `think`+page before gathering, carried on `ThinkResult.persist_base`) and passes it as the generation's input pin. Activation+rechecks it under the page lock: a page that changed since is fenced (`generation_fenced`, `pin_moved`), keeps the+edit, and the writer reports it (the summary and drift report on stderr, `think --save` as an error) instead of writing.+A write that changes a live page copies it to `page_versions` first (`gbrain restore`) and keeps its bounded preimage+on the ledger, so `gbrain repair generations --kind dream_summary|think_synthesis|drift_report --mode restore` puts the+earlier page back. A segmented live page is held `segmented_unsupported`. Managed brains keep their coordinated+maintenance page request, which binds the revision it reads at publish time and versions first.++Derived links and timeline rows are fence-only kinds (plan: the revision fence and the guard, no ledger). Each delete+runs with the page row locked (`FOR SHARE`) and only while the page is still at the revision its producer read:++- Timeline orphan retraction (T-2): `retractRemovedTimelineEntries` takes `expectedRevision`; `pruneTimelineOrphans`+ (unmanaged), `gbrain extract timeline --source db` (unmanaged) and `extract --stale` pass the revision they read. A+ page that moved deletes nothing. File-source extraction reconciles against the file and keeps no fence here.+- The by-mention rebuild sweep (L-6): `gbrain extract links --by-mention --rebuild` reads the revision before the body;+ a page that moved before the sweep is not swept and stays unchecked, so a resume retries it.+- Concept provenance edges (C-4, #4589): `replaceConceptProvenanceLinks` banks a republished concept's edges and retires+ the edges of atoms that left its member group in one transaction, only while the concept is at the revision its+ publication produced. Edges retire only when a concept generation replaces the previous one.+### Managed sourcesA managed source (`generations/managed.ts`) never composes a generation in one transaction: every page write is its owndiff --git a/docs/architecture/key-files/core-cycle-patterns.md b/docs/architecture/key-files/core-cycle-patterns.mdindex 9bfde597f4..8c0cb77542 100644--- a/docs/architecture/key-files/core-cycle-patterns.md+++ b/docs/architecture/key-files/core-cycle-patterns.md@@ -22,7 +22,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, 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/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. `replaceConceptProvenanceLinks` banks the concept-provenance edges and retires the edges of atoms that left the group in one transaction (coordinated on a managed brain), only while the concept is at the revision its publication produced (GBRA-161 PR 5, C-4). 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 1940940472..2b67404143 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) and stores the tags the summary file declares, so a same-date rerun finds its own file replaceable.+- `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` gives the dream summary the tier of the pages it indexes (written as a `dream_summary` single-page generation, GBRA-161 PR 5); `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): the summary write keeps a live body it replaces with a different one in page_versions first 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.diff --git a/docs/architecture/key-files/generations.md b/docs/architecture/key-files/generations.mdindex e4e53b04e3..7e9cc29c84 100644--- a/docs/architecture/key-files/generations.md+++ b/docs/architecture/key-files/generations.md@@ -5,3 +5,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/generations/{contract,plan,publish,proofs,config,repair,ledger-scrub}.ts` + `adapters/{page,atoms,index}.ts` (GBRA-161) — the generation primitive: one ledger row per derived key generation (`derived_generations`, items and bounded preimages in `derived_generation_items`); `publishGeneration` holds a shrunk, oversize, unproven-empty, valve or segmented result and otherwise writes, completes, rechecks, retires (versioned, stamped) and activates in one transaction. `gbrain repair generations` restores or releases from previews; doctor `generation_retirements` / `generation_held`. Reference: [generations](../generations.md). Tests: `test/pathological/g1-generations.test.ts`, `test/pathological/g1-atom-generations.test.ts`.- `src/core/generations/adapters/synthesis.ts`, `src/core/generations/synthesis-coverage.ts`, `src/core/generations/managed-retire.ts`, `src/core/cycle/synthesize-generations.ts` (GBRA-161 PR 4, #7065) — synthesis on the primitive: each re-synthesized transcript's outputs become its `synthesis` generation after postprocess; an earlier output retires (versioned, `synthesis-resynthesis`) only when it is an exact duplicate or the same subject with every claim, quote and citation covered (pure match in `synthesis-coverage.ts`); others stay live and `gbrain repair generations --kind synthesis --mode cleanup` lists and, on apply, retires them (`synthesis-cleanup`). A chunk failure, deferral or `generations.synthesis.retire_previous=false` makes the generation partial. Managed brains admit the activation plus one `managed_generation_retire` delete per retirement (`managed-retire.ts`). Reference: [generations](../generations.md#synthesis). Tests: `test/pathological/g4-synthesis-resynthesis-7065.test.ts`.+- `src/core/generations/adapters/single-page.ts` (GBRA-161 PR 5) — dream summary, `think` page and drift report as single-item generations: revision-bound, versioned first, restorable. Reference: [generations](../generations.md#single-page-kinds-and-fence-only-writers-pr-5). Tests: `test/pathological/g5-*` to `g7-*`.diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex efa4b9566d..b8c26cbc46 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -1594,6 +1594,17 @@ gbrain repair generations --kind synthesis --mode cleanup --since <ISO-8601> --agbrain repair generations --kind synthesis --mode restore --since 30d --json```+The dream summary, the `think` synthesis page and the drift report publish as+single-page generations (`--kind dream_summary`, `think_synthesis`,+`drift_report`, key `page:<slug>`): a writer whose page changed while it+composed writes nothing and the edit stays, and every overwrite keeps the+earlier page, so `--mode restore` puts it back (`gbrain restore <slug>` reads+the same copy from page history).++```bash+gbrain repair generations --kind drift_report --mode restore --since 7d --json+```+diff --git a/src/commands/extract-timeline-db.ts b/src/commands/extract-timeline-db.tsindex e58ad26c6e..be9eb3eb2d 100644--- a/src/commands/extract-timeline-db.ts+++ b/src/commands/extract-timeline-db.ts@@ -183,7 +183,7 @@ export async function extractTimelineFromDB(engine: BrainEngine, opts: TimelineD// A segmented body is read block by block (segmentedTimelineText), never as one string.const segmented = isSegmentedPage(page) ? await segmentedTimelineText(engine, page) : null;const fullContent = segmented ?? page.compiled_truth + '\n' + page.timeline;- if (!opts.dryRun) await retractRemovedTimelineEntries(engine, slug, source_id, fullContent);+ if (!opts.dryRun) await retractRemovedTimelineEntries(engine, slug, source_id, fullContent, snapshot ? { expectedRevision: snapshot.revision } : {});let entries = segmented ? segmented.entries : parseTimelineEntries(page.compiled_truth + '\n' + page.timeline);// --infer-dates: pages with no in-body timeline line but a trustworthy// content date (frontmatter / filename) get one anchor entry at that date.diff --git a/src/commands/extract.ts b/src/commands/extract.tsindex 75ac2cc086..7aec18dde9 100644--- a/src/commands/extract.ts+++ b/src/commands/extract.ts@@ -53,7 +53,7 @@ import { readLineGrammarSettings, statedRelationTypes } from '../core/line-grammimport { effectiveLinkExtractorWatermark, linkExtractorWatermarkFor } from '../core/link-extraction-watermark.ts';import { concurrentWriteSkipLine, replaceDerivedLinksBatchOrReplay, replaceDerivedLinksDeferringConflicts, settingsChangedSkipLine, unknownSourceSkipLine, type DerivedLinkBatchItem, type UnknownSourceSkip } from '../core/derived-links.ts';import { pageSnapshotKey } from '../core/page-snapshot-batch.ts';-import type { PageSnapshot } from '../core/page-state/types.ts';+import { PageRevisionConflictError, type PageSnapshot } from '../core/page-state/types.ts';import { LostWrites, extractionWrite, timelineSnapshotRefs } from '../core/extract-watermark.ts';export { reconcileSourceLinks, type SourceLinkReconciliationResult } from '../core/link-reconciliation.ts';export { extractMarkdownLinks } from '../core/link-extraction.ts';@@ -2320,7 +2320,7 @@ export async function extractStaleFromDB(if ('unknownSource' in written) { unknownSource.push({ slug: page.slug, source_id: page.source_id, missing_source: written.unknownSource }); continue; }linksCreated += written.created;const timelineText = fullContent ?? await segmentedTimelineText(engine, snapshot.page);- await retractRemovedTimelineEntries(engine, page.slug, page.source_id, timelineText);+ await retractRemovedTimelineEntries(engine, page.slug, page.source_id, timelineText, { expectedRevision: snapshot.revision });for (const entry of typeof timelineText === 'string' ? parseTimelineEntries(timelineText) : timelineText.entries) {// #3957: carry the parsed source label — omitting it wrote source=''// while the FS path wrote the split label, so the same bullet@@ -2548,6 +2548,8 @@ async function extractMentionsFromDb(}for (const { slug, source_id } of remaining) {+ // GBRA-161 PR 5 (L-6): the revision the rebuild scans, read before the body; the sweep runs only at it.+ const scannedRevision = rebuild ? (await engine.readPageSnapshot(slug, { sourceId: source_id }))?.revision ?? null : null;const page = await engine.getPage(slug, { sourceId: source_id });// v0.41.19.0 (T5 — codex fix #4): even when we skip a page (filter// miss, missing row, empty body, no mentions), MARK IT COMPLETED so@@ -2593,6 +2595,9 @@ async function extractMentionsFromDb(let pageRemoved = 0;let pageCreated = 0;await engine.transaction(async (tx) => {+ const [current] = await tx.executeRaw<{ revision: string }>(+ 'SELECT knowledge_revision::text AS revision FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL FOR SHARE', [source_id, slug]);+ if (current?.revision !== scannedRevision) throw new PageRevisionConflictError(scannedRevision, current?.revision ?? null);pageRemoved = await tx.removeLinksByPagesAndSource([{ slug, source_id }],{diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 5286e1c7b2..dcb59db9df 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1150,6 +1150,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.390.0', text: 'doctor `multi_source_drift` now verifies a source with 65,534 or more files. Its existence probe sent one bind parameter per file, so past the Postgres cap it reported "Not verified: ... MAX_PARAMETERS_EXCEEDED" on Postgres (and failed on PGLite), and no `GBRAIN_DRIFT_LIMIT` could make it verify.' },{ since: '0.60.390.0', text: '`gbrain extract links|timeline|all` with `--type`, `--since` or `--infer-dates` on the default `--source fs` file walk now exits 2 and prints the same command with `--source db`. Before, the walk ignored those filters and reported a full-corpus pass as if it were filtered. `--source db` applies them as before.' },{ since: 'TBD', text: 'A dream synthesis re-run of a transcript now retires the earlier outputs it replaced (GBRA-161 PR 4, #7065): after a complete re-synthesis (every chunk completed), an earlier reflection or original is versioned and soft-deleted (`retired_by: synthesis-resynthesis`, restorable for `generations.restore_days`, 30 by default) only when a new page is an exact duplicate of it, or has the same subject and covers every sentence, verbatim quote and citation it held. Every other earlier output stays live and `gbrain repair generations --kind synthesis --mode cleanup --since 30d` lists it with what it holds alone; its `--apply --expect <hash> --yes` retires exactly the previewed ones. A failed chunk or `gbrain config set generations.synthesis.retire_previous false` retires nothing, outputs written before this release are never retired, and `--mode restore` brings a retired output back. Separately, changing `models.dream.synthesize` no longer rewrites every deterministic (T3) concept page (#7269, reported by @p3ob7o).' },+ { since: 'TBD', text: 'The dream summary, the `think --save` synthesis page and the drift report now keep an edit made while they were being composed (GBRA-161 PR 5): each writer binds its write to the page revision it read before composing, and a page that changed since is left as it is (`generation_fenced`; the summary and drift report note it on stderr and the next run writes them, `think --save` exits non-zero). Each overwrite keeps the earlier page in page history first, and `gbrain repair generations --kind dream_summary|think_synthesis|drift_report --mode restore` (or `gbrain restore <slug>`) puts it back. Timeline orphan retraction, `gbrain extract links --by-mention --rebuild` and concept provenance edges now delete only while the page is still at the revision they read; a page edited in between keeps its rows. A republished concept now drops the provenance edges of atoms that left its group (#4589).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cycle/concept-publication.ts b/src/core/cycle/concept-publication.tsindex 9382c34afe..4810b4a24c 100644--- a/src/core/cycle/concept-publication.ts+++ b/src/core/cycle/concept-publication.ts@@ -73,11 +73,37 @@ export async function publishManagedConcept(engine: BrainEngine, authority: Mainreturn typeof receipt.revision === 'string' ? receipt.revision : null;}-/** Provenance edges inside a coordinated transaction scoped to the concept's source. */-export async function addManagedProvenanceLinks(engine: BrainEngine, sourceId: string, links: LinkBatchInput[]): Promise<number> {+/**+ * A published concept's provenance edges (#4589; GBRA-161 PR 5, C-4): banks `links` and retires the concept-provenance+ * edges to atoms that left the member group, in one transaction (coordinated on a managed brain) and only while the concept+ * is still at `expectedRevision`, the revision its publication produced (null: read here, right after an unmanaged+ * publication released its page lock). Edges retire only here, when a concept generation replaced the previous one; a+ * concept that moved since changes no edge (`moved`) and the next run reconciles it.+ */+export async function replaceConceptProvenanceLinks(engine: BrainEngine, sourceId: string, conceptSlug: string, links: LinkBatchInput[],+ opts: { expectedRevision: string | null; managed: boolean }): Promise<{ inserted: number; retired: number } | 'moved'> {+ const members = [...new Set(links.filter(link => link.from_slug === conceptSlug).map(link => link.to_slug))];+ const expectedRevision = opts.expectedRevision ?? (await engine.readPageSnapshot(conceptSlug, { sourceId }))?.revision ?? null;+ const write = async (tx: BrainEngine) => {+ const [current] = await tx.executeRaw<{ revision: string }>(+ 'SELECT knowledge_revision::text AS revision FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL FOR SHARE', [sourceId, conceptSlug]);+ if (!current || current.revision !== expectedRevision) return 'moved' as const;+ const stale = await tx.executeRaw<{ from_slug: string; to_slug: string; link_type: string; from_source_id: string; to_source_id: string }>(+ `SELECT f.slug AS from_slug, t.slug AS to_slug, l.link_type, f.source_id AS from_source_id, t.source_id AS to_source_id+ FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id+ WHERE l.link_source = 'concept-provenance'+ AND ((f.source_id = $1 AND f.slug = $2 AND NOT (t.source_id = $1 AND t.slug = ANY($3::text[])))+ OR (t.source_id = $1 AND t.slug = $2 AND NOT (f.source_id = $1 AND f.slug = ANY($3::text[]))))`, [sourceId, conceptSlug, members]);+ let retired = 0;+ for (const edge of stale) {+ retired += await tx.removeLink(edge.from_slug, edge.to_slug, edge.link_type, 'concept-provenance', { fromSourceId: edge.from_source_id, toSourceId: edge.to_source_id });+ }+ const inserted = links.length ? await tx.addLinksBatch(links, { auditSite: 'cycle.synthesize_concepts.provenance' }) : 0; // gbrain-allow-direct-insert: concept-provenance edges derived from the synthesis itself, under the concept's revision fence+ return { inserted, retired };+ };+ if (!opts.managed) return engine.transaction(write);const attribution = await maintenanceAttribution(engine);- return engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () =>- tx.addLinksBatch(links, { auditSite: 'cycle.synthesize_concepts.provenance' }), attribution)); // gbrain-allow-direct-insert: concept-provenance edges derived from the synthesis itself, inside the coordinated transaction+ return engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => write(tx), attribution));}/**diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.tsindex 1008bcf1e8..f5d8a363cd 100644--- a/src/core/cycle/synthesize-concepts.ts+++ b/src/core/cycle/synthesize-concepts.ts@@ -45,7 +45,7 @@ import { maintenancePreflight } from '../persistence/prepared-maintenance.ts';import { derivedWriteThrough, reportFileHolds } from './derived-write-through.ts';import { addSpellingRedirects, canonicalConceptStem, loadConceptRedirects, loadLiveConceptStems } from './concept-redirects.ts';import {- addManagedProvenanceLinks, CONCEPT_DEFERRAL_CODES, CONCEPT_HOLD_CODES, conceptPublicationHold, publishClassicConcept, publishManagedConcept, stripFenceSections,+ replaceConceptProvenanceLinks, CONCEPT_DEFERRAL_CODES, CONCEPT_HOLD_CODES, conceptPublicationHold, publishClassicConcept, publishManagedConcept, stripFenceSections,} from './concept-publication.ts';import { readPhaseConfigNumber, SYNTHESIZE_CONCEPTS_BUDGET_KEY, SYNTHESIZE_CONCEPTS_DEFAULT_BUDGET_USD } from './phase-config-values.ts';import { ConceptRetryBound, MAX_CONCEPT_ATTEMPTS } from './concept-retry-bound.ts';@@ -550,13 +550,13 @@ export async function runPhaseSynthesizeConcepts({ from_slug: atomSlug, to_slug: conceptSlug, link_type: 'synthesizes', link_source: 'concept-provenance', context: 'concept synthesized from this atom', from_source_id: src, to_source_id: src },]);try {- const inserted = maintenance ? await addManagedProvenanceLinks(engine, src, provenanceLinks)- : await engine.addLinksBatch(provenanceLinks, { auditSite: 'cycle.synthesize_concepts.provenance' }); // gbrain-allow-direct-insert: concept-provenance edges derived from the synthesis itself (no markdown body to reconcile from)+ const written = await replaceConceptProvenanceLinks(engine, src, conceptSlug, provenanceLinks, { expectedRevision: maintenance ? conceptRevision : null, managed: !!maintenance });// Zero rows back with edges requested means every member atom fell// out of the batch JOIN (not in this source) — unless a prior run// already banked them (ON CONFLICT DO NOTHING also returns 0). A// silent 'ok' here is a graph orphan with a clean receipt.- if (inserted === 0 && provenanceLinks.length > 0) {+ if (written === 'moved') linkWarnings.push({ concept: group.conceptSlug, warning: 'provenance links: the concept changed after it was published, so its edges were left as they were; the next run reconciles them' });+ else if (written.inserted === 0 && provenanceLinks.length > 0) {const banked = (await engine.getLinks(conceptSlug, { sourceId: src })).some((l) => l.link_source === 'concept-provenance');if (!banked) {diff --git a/src/core/timeline-extract.ts b/src/core/timeline-extract.tsindex 0578364fb1..aa7f219249 100644--- a/src/core/timeline-extract.ts+++ b/src/core/timeline-extract.ts@@ -325,13 +325,15 @@ export async function unkeptTimelineRows(engine: Pick<BrainEngine, 'executeRaw'>* Returns the orphaned rows; they are deleted unless `dryRun`. `storedRows`* is the caller's own read of those rows (a batched walk), used instead of reading them here.* `current` is the page text, or its keys when the caller read a segmented body (segmentedTimelineText).+ * `expectedRevision` is the page revision `current` was read at (GBRA-161 PR 5, T-2): the delete then runs with the page+ * row locked and only while the page is still at that revision; a page that moved deletes nothing and returns no rows.*/export async function retractRemovedTimelineEntries(engine: Pick<BrainEngine, 'executeRaw' | 'readManifest' | 'readSegmentTexts'>,slug: string,sourceId: string,current: string | TimelineTextKeys,- opts: { dryRun?: boolean; storedRows?: ReadonlyArray<StoredTimelineTuple>; stop?: () => boolean } = {},+ opts: { dryRun?: boolean; storedRows?: ReadonlyArray<StoredTimelineTuple>; stop?: () => boolean; expectedRevision?: string } = {},): Promise<Array<TimelineTuple & { id: number }>> {const kept = typeof current === 'string' ? markdownTimelineKeys(current, slug) : current.kept;const within = typeof current === 'string' ? undefined : current.within;@@ -370,10 +372,21 @@ export async function retractRemovedTimelineEntries(await contestHeldRows(engine as BrainEngine, { sourceId, slug, table: 'timeline_entries', proposer: 'timeline_reconcile', writer,rows: [...held].map(([id, tier]) => ({ id, tier, change: 'removed' as const })) });if (!orphans.length) return orphans;- await engine.executeRaw(+ const remove = (db: Pick<BrainEngine, 'executeRaw'>) => db.executeRaw(`DELETE FROM timeline_entries WHERE id IN (SELECT jsonb_array_elements_text($1::text::jsonb)::int)`,[JSON.stringify(orphans.map(row => row.id))]);- return orphans;+ if (opts.expectedRevision === undefined) {+ await remove(engine);+ return orphans;+ }+ const expected = opts.expectedRevision;+ return (engine as BrainEngine).transaction(async tx => {+ const [current] = await tx.executeRaw<{ revision: string }>(+ 'SELECT knowledge_revision::text AS revision FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL FOR SHARE', [sourceId, slug]);+ if (current?.revision !== expected) return [];+ await remove(tx);+ return orphans;+ });}/**@@ -381,7 +394,7 @@ export async function retractRemovedTimelineEntries(* keys of its stored rows (segmentedTimelineText `within`, a TimelineKeySet), and the rows are streamed, not held.*/async function retractStoredPage(engine: BrainEngine, page: { id: number; slug: string; source_id: string; compiled_truth: string; timeline: string | null; body_storage: string },- opts: { dryRun?: boolean }) {+ opts: { dryRun?: boolean; expectedRevision?: string }) {if (page.body_storage !== 'segmented') return retractRemovedTimelineEntries(engine, page.slug, page.source_id, `${page.compiled_truth}\n${page.timeline ?? ''}`, opts);const within = new TimelineKeySet();await eachStoredTimelineRow(engine, page.id, row => within.add(tupleKey(row)));@@ -431,8 +444,8 @@ export async function pruneTimelineOrphans(if (pageSize <= 0) break;const params: unknown[] = [afterId, pageSize];if (opts.sourceId) params.push(opts.sourceId);- const pages = await engine.executeRaw<{ id: number; slug: string; source_id: string; compiled_truth: string; timeline: string | null; body_storage: string }>(- `SELECT p.id, p.slug, p.source_id, p.compiled_truth, p.timeline, p.body_storage FROM pages p+ const pages = await engine.executeRaw<{ id: number; slug: string; source_id: string; compiled_truth: string; timeline: string | null; body_storage: string; revision: string }>(+ `SELECT p.id, p.slug, p.source_id, p.compiled_truth, p.timeline, p.body_storage, p.knowledge_revision::text AS revision FROM pages pWHERE p.id > $1 AND p.deleted_at IS NULL${opts.sourceId ? ' AND p.source_id = $3' : ''}AND EXISTS (SELECT 1 FROM timeline_entries t WHERE t.page_id = p.id AND t.event_page_id IS NULL)ORDER BY p.id LIMIT $2`, params);@@ -440,7 +453,7 @@ export async function pruneTimelineOrphans(for (const page of pages) {const orphans = opts.coordinated && !opts.dryRun? await retractCoordinated(engine, page.id, page.slug, page.source_id)- : await retractStoredPage(engine, page, { dryRun: opts.dryRun });+ : await retractStoredPage(engine, page, { dryRun: opts.dryRun, expectedRevision: page.revision });result.orphans += orphans.length;if (!opts.dryRun) result.removed += orphans.length;for (const row of orphans.slice(0, Math.max(0, 5 - result.examples.length))) {diff --git a/test/cycle/extract-atoms-synthesize-concepts.test.ts b/test/cycle/extract-atoms-synthesize-concepts.test.tsindex b862a8af39..cb34af6622 100644--- a/test/cycle/extract-atoms-synthesize-concepts.test.ts+++ b/test/cycle/extract-atoms-synthesize-concepts.test.ts@@ -843,7 +843,9 @@ describe('#4589: synthesize_concepts persists concept<->atom provenance edges',test('a failed edge write is reported as warn, not swallowed; the concept page still lands', async () => {await seedMembers();- const orig = engine.addLinksBatch.bind(engine);+ // Shadow the prototype method and delete the shadow afterwards: restoring a copy bound to the root engine would+ // leave it pinned there, and the edges are now written inside a transaction (GBRA-161 PR 5), where a call through+ // the root engine waits on the transaction's own connection.engine.addLinksBatch = async () => { throw new Error('links table unavailable'); };try {const result = await runPhaseSynthesizeConcepts(engine, { _atoms: memberAtoms });@@ -853,7 +855,7 @@ describe('#4589: synthesize_concepts persists concept<->atom provenance edges',expect(warnings.some((w) => w.concept === CONCEPT && /links table unavailable/.test(w.warning))).toBe(true);expect(await engine.getPage(CONCEPT_SLUG, { sourceId: 'default' })).not.toBeNull();} finally {- engine.addLinksBatch = orig;+ delete (engine as { addLinksBatch?: unknown }).addLinksBatch;}});});diff --git a/test/e2e/g6-fence-only-writers-postgres.test.ts b/test/e2e/g6-fence-only-writers-postgres.test.tsnew file mode 100644index 0000000000..52417d8dcd--- /dev/null+++ b/test/e2e/g6-fence-only-writers-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../pathological/g6-fence-only-writers.test.ts'));diff --git a/test/e2e/g7-concept-provenance-edges-postgres.test.ts b/test/e2e/g7-concept-provenance-edges-postgres.test.tsnew file mode 100644index 0000000000..0e23fabffa--- /dev/null+++ b/test/e2e/g7-concept-provenance-edges-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../pathological/g7-concept-provenance-edges.test.ts'));diff --git a/test/pathological/g6-fence-only-writers.test.ts b/test/pathological/g6-fence-only-writers.test.tsnew file mode 100644index 0000000000..45c818fee9--- /dev/null+++ b/test/pathological/g6-fence-only-writers.test.ts@@ -0,0 +1,83 @@+/**+ * GBRA-161 PR 5 (T-2, L-6): the fence-only derived writers. Timeline orphan retraction (pruneTimelineOrphans and the+ * extract paths that read the page from the database) and the by-mention rebuild sweep delete rows the page text no longer+ * produces; each now deletes only while the page is still at the revision it read. A page edited between the read and the+ * delete keeps its rows. No ledger: these kinds take the revision fence only (plan line 8). Real engines, PGLite and Postgres.+ */+import { describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { pruneTimelineOrphans } from '../../src/core/timeline-extract.ts';+import { runExtract } from '../../src/commands/extract.ts';+import { setCliOptions } from '../../src/core/cli-options.ts';+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';+import { pathologicalArms } from './harness.ts';++/** The engine as a writer sees it, with a person's page edit landing at the first call \`when\` picks. */+function editingAt(engine: BrainEngine, when: (method: string, args: unknown[], armed: boolean) => boolean, arm: (method: string, args: unknown[]) => boolean,+ edit: () => Promise<unknown>): BrainEngine {+ let armed = false, edited = false;+ return new Proxy(engine, { get(target, prop) {+ const value = Reflect.get(target, prop, target);+ if (typeof value !== 'function') return value;+ return async (...args: unknown[]) => {+ if (arm(String(prop), args)) armed = true;+ if (!edited && when(String(prop), args, armed)) { edited = true; await edit(); }+ return value.apply(target, args);+ };+ } }) as BrainEngine;+}++const timeline = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ d: string; s: string }>(+ "SELECT to_char(t.date, 'YYYY-MM-DD') AS d, t.summary AS s FROM timeline_entries t JOIN pages p ON p.id=t.page_id WHERE p.slug=$1 ORDER BY t.date", [slug])).map(r => `${r.d} ${r.s}`);+const person = (bullets: string) => ({ type: 'person' as const, title: 'Erin Example', compiled_truth: 'Erin is an engineer.', timeline: bullets, frontmatter: {} });++const mentions = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ to_slug: string }>(+ "SELECT tp.slug AS to_slug FROM links l JOIN pages fp ON fp.id=l.from_page_id JOIN pages tp ON tp.id=l.to_page_id WHERE fp.slug=$1 AND l.link_source='mentions' ORDER BY tp.slug", [slug])).map(r => r.to_slug);+async function quietly<T>(run: () => Promise<T>): Promise<T> {+ const [out, err, log, error] = [process.stdout.write, process.stderr.write, console.log, console.error];+ process.stdout.write = (() => true) as never; process.stderr.write = (() => true) as never; console.log = () => {}; console.error = () => {};+ try { return await run(); } finally { process.stdout.write = out; process.stderr.write = err; console.log = log; console.error = error; }+}++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`GBRA-161 PR 5 fence-only writers (${backend})`, () => {+ test('T-2: a timeline row the page re-gained between the read and the delete is kept', async () => {+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ const slug = 'people/erin-example';+ await engine.putPage(slug, person('- **2024-01-01** | first'));+ await engine.addTimelineEntry(slug, { date: '2024-01-01', source: 'markdown', summary: 'first' });+ await engine.createVersion(slug);+ await engine.putPage(slug, person('- **2024-02-01** | second'));+ await engine.addTimelineEntry(slug, { date: '2024-02-01', source: 'markdown', summary: 'second' });+ expect((await pruneTimelineOrphans(engine, { dryRun: true })).orphans).toBe(1);++ const racing = editingAt(engine, (method, args) => method === 'executeRaw' && String(args[0]).includes('FROM page_versions v JOIN pages p'), () => false,+ () => engine.putPage(slug, person('- **2024-01-01** | first\n- **2024-02-01** | second')));+ const applied = await pruneTimelineOrphans(racing, { dryRun: false });+ expect(applied.removed).toBe(0);+ expect(await timeline(engine, slug)).toEqual(['2024-01-01 first', '2024-02-01 second']);+ } finally { await close(); }+ }, 120_000);++ test('L-6: a mention the page re-gained between the scan and the rebuild sweep is kept', async () => {+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ setCliOptions({ quiet: true, progressJson: false, progressInterval: 1000, explain: false, timeoutMs: null, brain: null });+ try {+ await engine.putPage('companies/acme-example', { type: 'company', title: 'Acme Example', compiled_truth: 'acme body', timeline: '', frontmatter: {} });+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'alice body', timeline: '', frontmatter: {} });+ const note = (body: string) => engine.putPage('writing/post-1', { type: 'note', title: 'post', compiled_truth: body, timeline: '', frontmatter: {} }, { allowEmptyOverwrite: true });+ await note('We met with Acme Example yesterday.');+ await quietly(() => runExtract(engine, ['links', '--by-mention', '--source', 'db']));+ expect(await mentions(engine, 'writing/post-1')).toEqual(['companies/acme-example']);+ await note('Alice Example joined the call.');++ const racing = editingAt(engine, (method, _args, armed) => armed && method === 'transaction',+ (method, args) => method === 'getPage' && args[0] === 'writing/post-1',+ () => note('Alice Example joined the call, and Acme Example sent the notes.'));+ await quietly(() => runExtract(racing, ['links', '--by-mention', '--rebuild', '--source', 'db']).catch(() => undefined));+ expect(await mentions(engine, 'writing/post-1')).toContain('companies/acme-example');+ } finally { await close(); }+ }, 120_000);+ });+}diff --git a/test/pathological/g7-concept-provenance-edges.test.ts b/test/pathological/g7-concept-provenance-edges.test.tsnew file mode 100644index 0000000000..aa689af273--- /dev/null+++ b/test/pathological/g7-concept-provenance-edges.test.ts@@ -0,0 +1,74 @@+/**+ * GBRA-161 PR 5 (C-4, #4589): a concept's provenance edges (link_source concept-provenance) were insert-only, so an atom+ * that left the concept's member group kept its edges forever. They now retire when a concept generation replaces the+ * previous one, in the transaction that banks the new edges, and only while the concept is still at the revision its+ * publication produced (the revision fence of a derived-link kind; no ledger). Real phase, PGLite and Postgres.+ */+import { describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { ChatResult } from '../../src/core/ai/gateway.ts';+import { runPhaseSynthesizeConcepts } from '../../src/core/cycle/synthesize-concepts.ts';+import { replaceConceptProvenanceLinks } from '../../src/core/cycle/concept-publication.ts';+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';+import { withEnv } from '../helpers/with-env.ts';+import { pathologicalArms } from './harness.ts';++const MODEL = 'anthropic:claude-sonnet-4-6';+const CONCEPT = 'concepts/storage-example';+const atoms = (ids: number[]) => ids.map(i => ({ slug: `atoms/storage-${i}`, concept_refs: [CONCEPT], body: `Atom ${i} about storage.`, title: `storage atom ${i}` }));+const chat = async (): Promise<ChatResult> => {+ const text = 'A complete narrative about this concept.';+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end', usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: MODEL, providerId: 'anthropic' };+};+const edges = async (engine: BrainEngine) => (await engine.executeRaw<{ e: string }>(+ `SELECT f.slug || ' ' || l.link_type || ' ' || t.slug AS e FROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id WHERE l.link_source='concept-provenance' ORDER BY 1`)).map(r => r.e);+const expected = (ids: number[]) => ids.flatMap(i => [`${CONCEPT} synthesized_from atoms/storage-${i}`, `atoms/storage-${i} synthesizes ${CONCEPT}`]).sort();++async function world(databaseUrl: string | undefined, run: (engine: BrainEngine) => Promise<void>): Promise<void> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-g7-'));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ _resetWriteThroughCacheForTest();+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ await engine.setConfig('models.dream.synthesize', MODEL);+ for (const atom of atoms([0, 1, 2, 3, 4, 5])) await engine.putPage(atom.slug, { type: 'note', title: atom.title, compiled_truth: atom.body, timeline: '', frontmatter: {} });+ await run(engine);+ } finally { await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+}++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`GBRA-161 PR 5 concept provenance edges (${backend})`, () => {+ test('C-4: a republished concept retires the edges of the atom that left its group and banks the new one', async () => {+ await world(databaseUrl, async engine => {+ await runPhaseSynthesizeConcepts(engine, { _atoms: atoms([0, 1, 2, 3, 4]), _chat: chat });+ expect(await edges(engine)).toEqual(expected([0, 1, 2, 3, 4]));+ const before = (await engine.readPageSnapshot(CONCEPT, { sourceId: 'default' }))!.revision;+ await runPhaseSynthesizeConcepts(engine, { _atoms: atoms([0, 1, 2, 3, 5]), _chat: chat });+ expect((await engine.readPageSnapshot(CONCEPT, { sourceId: 'default' }))!.revision).not.toBe(before);+ expect(await edges(engine)).toEqual(expected([0, 1, 2, 3, 5]));+ });+ }, 240_000);++ test('C-4: a concept that moved past the revision its publication produced keeps every edge', async () => {+ await world(databaseUrl, async engine => {+ await runPhaseSynthesizeConcepts(engine, { _atoms: atoms([0, 1, 2, 3, 4]), _chat: chat });+ const published = (await engine.readPageSnapshot(CONCEPT, { sourceId: 'default' }))!.revision;+ const page = (await engine.getPage(CONCEPT, { sourceId: 'default' }))!;+ await engine.putPage(CONCEPT, { type: page.type, title: page.title, compiled_truth: `${page.compiled_truth}\n\nA person added this line.`, timeline: page.timeline ?? '', frontmatter: page.frontmatter });+ const links = atoms([0, 1, 2, 3]).flatMap(a => [+ { from_slug: CONCEPT, to_slug: a.slug, link_type: 'synthesized_from', link_source: 'concept-provenance', context: 'member atom', from_source_id: 'default', to_source_id: 'default' },+ { from_slug: a.slug, to_slug: CONCEPT, link_type: 'synthesizes', link_source: 'concept-provenance', context: 'concept synthesized from this atom', from_source_id: 'default', to_source_id: 'default' },+ ]);+ expect(await replaceConceptProvenanceLinks(engine, 'default', CONCEPT, links, { expectedRevision: published, managed: false })).toBe('moved');+ expect(await edges(engine)).toEqual(expected([0, 1, 2, 3, 4]));+ });+ }, 240_000);+ });+}