Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
GBRA-161 PR 4: synthesis restore puts files back; docs and behavior notice (#7065)
garrytan1d767741e930
diff --git a/docs/architecture/generations.md b/docs/architecture/generations.mdindex 2605d95fe4..a34e3c12fa 100644--- a/docs/architecture/generations.md+++ b/docs/architecture/generations.md@@ -67,6 +67,36 @@ the one the live generation recorded, or it is exactly what this publication prooperator-deleted event is never an item, so nothing overwrites, retires or revives it.`gbrain repair generations --kind chronicle-event --mode restore` brings retired events and their rows back.+### Synthesis++Dream synthesis outputs (kind `synthesis`, one key per transcript: the PR 1b transcript key, `transcript:<root>/<path>`;+`adapters/synthesis.ts`, GBRA-161 PR 4, #7065) publish in place (`publishesInPlace`): the synthesize phase's children+write the reflection and original pages as they always did, and after postprocess and the provenance stamp+`cycle/synthesize-generations.ts` records each synthesized transcript's outputs as its new generation. The decision is+the plan approved on Oct 21: replace only on a complete, non-empty result, always version first, always reversible.++- An earlier output retires at activation (versioned, `retired_by: synthesis-resynthesis`, its file removed when the+ database holds everything in it) only when it is matched (`generations/synthesis-coverage.ts`): an exact duplicate of a+ new page, or a page of the new generation with the same subject (slug without its hash suffix and date, or the same+ lowercased title tokens) while every claim unit (each sentence outside a quote), every verbatim quote (a `>` block or a+ quoted span of three or more words) and every citation (wikilink or link target) of the earlier page appears in the new+ generation.+- Every other earlier output is carried into the new generation, stays live and is recorded on it as an unmatched+ predecessor (why, and how many claims, quotes and citations it holds alone; a segmented page is never compared and is+ listed `unreadable`). `gbrain repair generations --kind synthesis --mode cleanup --since 30d` lists them and+ `--apply --expect <hash> --yes` retires exactly the previewed ones (`retired_by: synthesis-cleanup`).+- A transcript is complete only when every child of every chunk completed and nothing of the run is deferred or still+ pending publication. Otherwise, or with `generations.synthesis.retire_previous` set to false, the generation is+ partial: the new outputs are recorded and nothing retires.+- An output from before the ledger is never adopted as an earlier output (no legacy evidence), so the duplicate backlog+ an upgraded brain already holds is untouched. The shrink floor applies, measured against the live generation's items+ (an in-place kind's new outputs carry new keys), and so does the valve: a mass re-synthesis retires at most its share+ per run window and holds the rest (`valve`).+- `--mode restore` brings a retired earlier output back from its ledger preimage, retires the outputs that replaced it+ and puts the files back the same way (unmanaged brains). A managed brain admits the activation and one versioned+ delete per retirement (`managed_generation_retire`, `generations/managed-retire.ts`) in one transaction; the next run+ resumes a retirement left behind.+### Managed sourcesA managed source (`generations/managed.ts`) never composes a generation in one transaction: every page write is its own@@ -104,7 +134,8 @@ doctor `atom_retirements_restorable` leaves out an atom whose retirement the led`gbrain repair generations --kind <kind>` is explicit-only and preview-bound (docs/guides/repair.md#generations):`--mode restore` (the default) republishes the item set the selected live generation replaced, `--mode release-held`publishes a held result once (a managed source releases an atom page key through its writer), and `--mode cleanup` lists-pending members and orphan candidates, read-only. A managed source restores retired atoms with `gbrain repair+pending members and orphan candidates, read-only (for `synthesis` it also lists unmatched predecessors, which its+`--apply` retires; see [Synthesis](#synthesis)). A managed source restores retired atoms with `gbrain repairatoms-restore`; `--mode restore` refuses there. Doctor reports `generation_retirements` (ok, with the restorablecount), `generation_held` (warn) and `generation_pending` (warn).@@ -128,6 +159,7 @@ proposal carrying the claim (`ledger-scrub.ts`). Restore then refuses that item| `generations.max_items` | 64 | 8 to 1024 || `generations.valve.max_per_run` | 500 | 1 to 100000 || `generations.valve.max_ratio` | 0.5 | 0.01 to 1 |+| `generations.synthesis.retire_previous` | true | true or false |`gbrain config set` refuses a value out of range; a stored value out of range reads as the default.@@ -155,3 +187,11 @@ proposal carrying the claim (`ledger-scrub.ts`). Restore then refuses that item- Managed `--mode restore` is refused and `atoms-restore` stays the managed restore path, because a generation restorewrites pages in one transaction, which a managed source cannot do; a managed restore through member requests is leftfor a later PR.+- Synthesis subject matching accepts the slug stem (hash suffix and date prefix removed) or the lowercased title tokens,+ because a re-run may rename either; the coverage test (every sentence, quote and citation) is what makes a retirement+ safe, and an earlier page that fails it stays live whatever its subject.+- An in-place kind's shrink floor counts the live generation's items only, because its new outputs carry new keys and+ would otherwise count as owned before the run: a re-synthesis with fewer pages than before would always hold.+- A managed brain's synthesis restore is refused like every non-fence managed restore (see above); its retirements are+ versioned deletes, and the earlier pages come back through `gbrain repair generations` on an unmanaged brain or a+ later managed restore path.diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex c80eafd12e..be17641edb 100644--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -11,6 +11,8 @@ See [generations](generations.md).- `src/core/persistence/publication-failure.ts` (#5974) — maps a P0001 from the managed-writer guard (which raises TABLE/SCHEMA, `managed_writer_guard:<branch>` and a JSON DETAIL) or another trigger to a bounded `error_detail` (origin, raiser, table, op, branch, relationship, stage, plus owner-only source ids and the attempt's build/host). Receipts expose only `publicFailureDetail`; `sources writer status` lists the full detail under `recent_failures`. #5929: `ownerExceptionFailure` (the coordinator `requestError` fallback) keeps an unexpected exception's class, errno and top `src/...:line` frame as `origin: owner_exception` (never an application error's message), so `withAttempt` stamps the build; #7112: a server-generated database error (a five-character SQLSTATE, a severity and a routine; never a PL/pgSQL RAISE or ASSERT or another class P0 error) also keeps `error_text` (its primary message, at most 240 characters; object names survive only in a known catalog message such as a not-null violation, or a syntax-error or does-not-exist message whose name the statement holds as an identifier; any other message loses everything from its first quote to its last, because Postgres does not escape quotes inside a value) and `statement` (the failing SQL tokenized: keywords, identifiers, parameter markers and operators, with every literal, E-string, dollar-quoted body, number and comment replaced or dropped, cut at anything unrecognized, at most 160 characters, never the parameters) and `position`, all owner-only; a trusted local `gbrain write-request <id>` returns the full `error_detail`; `publicFailureDetail` is an allow-list (origin, sqlstate, raiser, table, op, branch, relationship, reason, stage, fence), so `error_class`/`errno`/`frame`/`error_text`/`statement`/`position`, `sources` and `attempt` stay owner-only; `ownerBuildMismatch` drives the local `owner_build` receipt field (`ops/persistence.ts`) and the submit-time why/fix (`page-mutations.ts`), and `ownerExceptionLogText` the consumer log line. Wave 16 (GBRA-79, #6513 comments): an untyped refusal carries a CLOSED `reason` (`PUBLICATION_REASONS`: `attribution_unclassified_table` and `trust_unclassified_table` from the two stamp triggers' own "is not classified for table" raise, `graduation_in_progress` from the engine-graduation fence, which raises SQLSTATE 55000 and which `databaseRefusal` now recognizes, else `unknown`); the message decides nothing on its own (the same text from another raiser, or the fence's text under P0001, is `unknown`), the public message names only the enum (`Publication failed (P0001 in <raiser>: <reason>)`), and no part of the message is stored, owner-side included (#5974's rule). `publicFailureDetail` passes `reason` only as a member of the enum, whatever a stored detail holds. The projection rides the managed failure (`sync-failures.ts` `ManagedSyncFailure.write_error_detail`, recorded with the failure and re-read from the pending receipt by `readManagedSyncFailures`; `publicationDetailText` appends ` raiser= table= reason=` to `formatManagedSyncFailure`, so the ledger mirror and doctor carry it) and `gbrain sync status --json` (`last_error.write_error_detail`, `last_error.detail` = the reason, which `classifySyncFault` refines by: `graduation_in_progress` is `connection` / retry / no human in `sync-fault-class.ts`). Tests: `test/publication-failure-reason-6513.test.ts` (mapping, privacy negatives, allow-list), `test/sync-status-failure-detail-6513.test.ts` (both engines, a real operator trigger).- `src/core/cycle/extract-atoms-page-state.ts` — derived page scan/failure state keyed by source incarnation, stable page identity and content hash. Compare-and-swap stamps never update canonical frontmatter. Reviewed reconciliation can carry matching state across removal of legacy bookkeeping fields. Unmanaged atom items complete as one generation; managed extraction uses journaled publication and a durable completion receipt after trusted local source-wide authority checks and, for filesystem publication, owner preflight.+- `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/persistence/grandfather.ts` — provider-free canonical publication for the grandfather compatibility flag on active managed Markdown pages. Admission retains a checkpointed request UUID, exact source/incarnation/page/revision identity and a private rollback snapshot. Publication preserves chunks/vectors and only already-valid text seals, carries matching atom scan state across the metadata hash change, and defers embeddings without queuing fact extraction. Explicit validation choices, archived sources and non-Markdown artifacts remain untouched; unpublished file edits refuse. Pages under a declared `storage.db_only` dir without a local cache file publish database-only. The committed revision is returned so the migration's verify phase can tell a later rewrite from a lost write. `admitCanonicalGrandfather` splits admission from `complete()` (wait, then settle the checkpoint exactly as the serial `grandfatherCanonicalPage` does); the migration admits a 50-page window before waiting, so the pages' Git effects coalesce (#5530). The unmanaged migration keeps its bounded SQL batches. `test/grandfather-managed.test.ts` covers both engines, replay, races and preserved artifacts; the unchanged local-install lifecycle exercises the public upgrade path.diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 2ebdc0d073..efa4b9566d 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -1577,6 +1577,31 @@ Life Chronicle events publish the same way (`--kind chronicle-event`, keydepth page retired, with their timeline rows on the depth page, and it runs onmanaged brains as one coordinated request.+Dream synthesis outputs publish as a generation per transcript (`--kind+synthesis`, key `transcript:<root>/<path>`): a complete re-synthesis retires an+earlier output it matched (an exact duplicate, or the same subject with every+claim, quote and citation covered; `retired_by: synthesis-resynthesis`) and+keeps every other one live. `--mode cleanup` lists those unmatched+predecessors with why and what each holds alone; show the user the preview, and+`--apply --expect <hash> --yes` retires exactly the listed ones+(`retired_by: synthesis-cleanup`). `--mode restore` brings a retired output back+and puts its file back (unmanaged brains). `gbrain config set+generations.synthesis.retire_previous false` stops automatic retirement.++```bash+gbrain repair generations --kind synthesis --mode cleanup --since 30d --json+gbrain repair generations --kind synthesis --mode cleanup --since <ISO-8601> --apply --expect <hash> --yes+gbrain repair generations --kind synthesis --mode restore --since 30d --json+```+++++++```++### Extractor factsA managed write by a gbrain older than v0.60.11.0 to a conversation pagediff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 09b4862183..5286e1c7b2 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1149,6 +1149,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;// GBRA-151 wave (#7388, #7394). `since` is stamped at the merge slot.{ 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).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cycle/derived-write-through.ts b/src/core/cycle/derived-write-through.tsindex cd66368d4f..26937e62b6 100644--- a/src/core/cycle/derived-write-through.ts+++ b/src/core/cycle/derived-write-through.ts@@ -190,7 +190,7 @@ export async function writeDreamPageFile(engine: BrainEngine, brainDir: string,if (await isWriteThroughDisabled(engine)) return { written: false, skipped: 'disabled_by_config' };if (await urlCloneReadOnly(engine, sourceId)) return { written: false, skipped: 'url_clone' };const target = await resolvePageWriteTarget(engine, slug, sourceId);- if (!target.ok && target.skipped !== 'no_repo_configured' && target.skipped !== 'repo_not_found') return { written: false, skipped: target.skipped };+ if (!target.ok && (!brainDir || (target.skipped !== 'no_repo_configured' && target.skipped !== 'repo_not_found'))) return { written: false, skipped: target.skipped };try {const storage = loadStorageConfig(target.ok ? target.writeRoot : brainDir);if (storage && isDbOnly(slug, storage)) return { written: false, skipped: 'db_only' };diff --git a/src/core/generations/repair.ts b/src/core/generations/repair.tsindex ef3a10d4a9..fb6647d4ed 100644--- a/src/core/generations/repair.ts+++ b/src/core/generations/repair.ts@@ -313,7 +313,9 @@ async function applyEntry(ctx: OperationContext, adapter: GenerationAdapter<unkn}if (restored === 'changed') return changed('the live generation or its items changed since the preview');if (Array.isArray(restored)) return { applied: false, outcome: 'refused', reason: restored.join(', ') };- return { applied: true, outcome: 'restored', detail: { generation: restored.generation, restore_of: approved.restore_to, revived: approved.revive.length, retired: approved.retire.length } };+ const fileHolds = adapter.publishesInPlace ? await restoreInPlaceFiles(ctx.engine, key.sourceId, approved.revive, approved.retire) : [];+ return { applied: true, outcome: 'restored', detail: { generation: restored.generation, restore_of: approved.restore_to, revived: approved.revive.length, retired: approved.retire.length,+ ...(fileHolds.length ? { file_holds: fileHolds } : {}) } };}/**@@ -345,6 +347,20 @@ async function retireUnmatched(engine: BrainEngine, adapter: GenerationAdapter<ureturn { applied: true, outcome: 'retired', detail: { generation: outcome.generation, retired_by: SYNTHESIS_CLEANUP_RETIRED_BY, ...(file.held ? { file_held: file.held } : {}) } };}+/**+ * GBRA-161 PR 4: the files of an in-place kind (synthesis pages) after its unmanaged restore committed: each revived page is+ * written back to its file and each retired page's file removed, both only where the file holds nothing the database+ * lacks (otherwise its `file_database_drift` entry is returned and the file stays).+ */+async function restoreInPlaceFiles(engine: BrainEngine, sourceId: string, revived: readonly string[], retired: readonly string[]): Promise<string[]> {+ const { removeDreamPageFile, reverseWriteDreamRefs } = await import('../cycle/derived-write-through.ts');+ const { renderPageToMarkdown } = await import('../cycle/synthesize.ts');+ const held: string[] = [];+ for (const slug of retired) { const file = await removeDreamPageFile(engine, '', slug, sourceId, ''); if (file.held) held.push(file.held); }+ await reverseWriteDreamRefs(engine, '', revived.map(slug => ({ slug, source_id: sourceId })), { phase: 'repair generations', nativeSourceId: '', render: renderPageToMarkdown, held });+ return held;+}+/** The approved restore of one key, under its locks in the caller's transaction: 'changed', the refused keys, or the new generation. */async function restoreGeneration(tx: BrainEngine, adapter: GenerationAdapter<unknown>, key: GenerationKey, approved: RestoreEntry): Promise<'changed' | string[] | { generation: number }> {const live = await readLiveGeneration(tx, key);diff --git a/test/pathological/g4-synthesis-resynthesis-7065.test.ts b/test/pathological/g4-synthesis-resynthesis-7065.test.tsindex 5bedd8d8a2..0fd3401011 100644--- a/test/pathological/g4-synthesis-resynthesis-7065.test.ts+++ b/test/pathological/g4-synthesis-resynthesis-7065.test.ts@@ -199,7 +199,7 @@ describe('unmanaged re-synthesis (#7065): what stays live', () => {});}, 300_000);- test('restore brings the retired earlier output back and retires the successor, both versioned', async () => {+ test('restore brings the retired earlier output back and retires the successor, both versioned, files following', async () => {await fixture(false, async f => {await synthesize(f, () => [{ stem: 'storage-plan', title: 'Storage plan', body: PLAN }]);const [first] = await byStem(f, 'storage-plan');@@ -214,6 +214,8 @@ describe('unmanaged re-synthesis (#7065): what stays live', () => {expect(after.find(p => p.slug === successor)).toMatchObject({ deleted: true, retired_by: 'generation-restore' });const [body] = await f.engine.executeRaw<{ compiled_truth: string }>('SELECT compiled_truth FROM pages WHERE source_id=$1 AND slug=$2', [f.sourceId, first!.slug]);expect(body!.compiled_truth).toContain('The storage plan moved to object storage.');+ expect(existsSync(join(f.root, `${first!.slug}.md`))).toBe(true);+ expect(existsSync(join(f.root, `${successor}.md`))).toBe(false);});}, 180_000);