Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Source deletes never strand pages, and agent sessions are not saved as the owner

garrytan6804924e42da
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv
index e9aa1ba585..b5bdd92062 100644
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@ -24,7 +24,6 @@ src/commands/frontmatter.ts 0 filesystem_guard Batch frontmatter repair prefligh
src/commands/import.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.
src/commands/jobs.ts 0 coordinator The purge job (registered here, body in src/core/minions/handlers/purge.ts) runs purgeDeletedPagesCoordinated; remaining canonical writes live in delegated coordinated modules.
src/commands/migrate-engine.ts 12 early_refusal Managed mode refuses this legacy entry point before its canonical filesystem/provider effects. #6286: the legacy copier also writes each copied page's frontmatter aliases (setPageAliases) on the unmanaged target.
-src/commands/migrations/v0_13_1.ts 2 engine_guard Unmanaged metadata batches retain page guards and row locks; managed active Markdown pages route through the canonical grandfather publisher instead of direct SQL.
src/commands/migrations/v0_32_2.ts 2 coordinator On a managed brain each entity page publishes its rendered facts fence through a managed_maintenance_adopt_fact_fence request that adopts the legacy rows in place inside the coordinated publication, database-only pages included; unmanaged brains keep the file-first backfill, which the trigger refuses on managed brains.
src/commands/pages.ts 2 engine_guard Both engine references are dry-run previews (the --dry-run listing and the D6 consent count before a hard purge, #6114); the purge runs purgeDeletedPagesCoordinated, which is coordinated on managed brains.
src/commands/reconcile-links.ts 2 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.
@@ -205,7 +204,6 @@ src/core/shared-skills/source-opt-out.ts 2 projection Trusted local CLI only (re
src/core/shared-skills/setup.ts 1 engine_guard Trusted preactivation empty-source root binding uses an incarnation and null-path CAS; managed topology SQL remains guarded and skill bytes publish only through owner claim and bundle adoption.
src/core/shared-skills/optimizer.ts 0 coordinator Shared optimization preserves the exact approved closure and original grants in private staging; only accepted body changes reach put_skill with the original revision and stable request UUID.
src/core/persistence/import-prepare.ts 2 coordinator The prepared local import updates source_path only inside canonical publication; owner, input and target hashes, source confinement and knowledge-versus-skill boundary revalidate before apply. Its importFromContent calls carry prepare and run inside the coordinator publication.
-src/core/persistence/grandfather.ts 2 coordinator Private migration intents preserve exact page/source/incarnation/revision identity and rollback snapshots; frontmatter/hash and existing text seals change only inside canonical file publication, without new embedding or fact-backstop effects.
src/core/mentions/pass.ts 7 coordinator Derived page_aliases rows (origin declared/subject) are replaced per page; on a managed brain the mention pass runs each alias batch inside withCoordinatedWrite for its source after re-reading page revisions, import writes them inside the caller's coordinated import transaction, and reindex --aliases holds the coordinated write itself. Frontmatter alias rows are never touched; unmanaged brains keep the SQL guard.
src/core/page-state/rename-alias.ts 13 engine_guard Rename aliases (slug_aliases), moveSlugBindings (facts entity/fence slugs, page_aliases, withdrawal subjects) and movePageIdReferences (#5431: versions, timeline, links deduplicated on the links key) run inside the rename's maintenanceTransaction; the canonical table SQL trigger requires coordinator capability, so legacy calls fail before publication. #6865: recordSlugLineAlias writes the removed slug: line's alias inside the content-repair publication transaction (coordinated managed file repair).
src/core/timeline-extract.ts 1 engine_guard Retracting removed markdown timeline rows is canonical table SQL; the trigger requires coordinator capability, so legacy calls fail before canonical DB publication.
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.md
index c27cc00a5a..ed8f67c4c9 100644
--- a/docs/architecture/key-files/agent-bootstrap-continued.md
+++ b/docs/architecture/key-files/agent-bootstrap-continued.md
@@ -25,7 +25,7 @@
- Tests: `test/writeback-config.test.ts`, `test/mcp-instructions-writeback.test.ts`, `test/facts/writeback-gate.test.ts`, `test/hook-writeback-stop.serial.test.ts`, writeback-lane cases in `test/checkpoint-harvest.serial.test.ts`, `test/bootstrap-instructions-block.test.ts` + harness serial additions, `test/writeback-nudge.serial.test.ts`, `test/doctor-memory-writeback.test.ts`, the hermetic 5-step `test/ambient-writeback-lifecycle.serial.test.ts`, and the NON-GATING real-codex door (`test/e2e/bootstrap-real-codex.serial.test.ts`, ambient-writeback describe).
- `src/core/sweep.ts` + `src/commands/sweep.ts` — the serve-resident maintenance sweep (the lock owner closes the persistence loop): facts-fence reconciliation (zero-LLM, reuses the cycle extractor with a slug subset), deterministic link/timeline extraction over recent workspace pages (the same cores as `gbrain extract` — remote put_page deliberately skips these, the sweep is where the graph compounds), and spend-gated corpus ingest (skipped keyless; turn-boundary windows through `src/core/context/corpus-windows.ts`, at most `CORPUS_WINDOWS_PER_SWEEP` (8) per file and `CORPUS_WINDOWS_PER_SWEEP_TOTAL` (32, env `GBRAIN_CORPUS_WINDOWS_PER_SWEEP`) per sweep, each windowed file reported in `corpus_files[]` as `{file, windows_done, windows_remaining}`; `.ingested` is written when the last window of the current snapshot finishes, and a finished file re-enters when its stat no longer matches its `.progress`; writeback `.wb-` turn files stay one call; dream outputs and claude-cli self-captures classified by `isClaudeCliSelfSessionId` get a terminal `.ingested` sidecar with `skipped: dream_output` / `self_capture` (the shared `selfCaptureSidecarJson` writer) and are never extracted; the extractor input is `corpusTextForExtraction`, so pasted blocks never reach it). Bounded, fail-soft, never throws; the wall-clock budget stops the corpus pass between files and windows, never mid-extraction (an in-flight extraction finishes and writes its sidecar, E-N2, pinned by `test/sweep-budget-between-items.test.ts`); armed at serve startup (3s, best-effort) and on 10-min idle ticks through the injectable timer seam, everything unref'd; `serve --http` arms `armCorpusDrain` instead (X8: every `CORPUS_DRAIN_INTERVAL_MS`, 10 min, one sweep on a `CORPUS_DRAIN_BUDGET_MS` 60 s budget while a corpus `.txt` has no final `.ingested` sidecar; never overlaps itself; its sweep diagnostics and thrown ticks reach stderr, each distinct line once per run, plus the skip reasons whenever their set changes (#6785); pinned by `test/serve-http-corpus-drain.test.ts`); `GBRAIN_SWEEP=0` kills both. `bootstrap verify` runs the sweep in-process with `corpus: false` (#6786: its engine has no configured gateway, so every window answered `chat_unavailable`). Before any model call the corpus pass runs the facts-absorb owner-readiness preflight per source (`assertSourceLegacyWriter` in `persistence/filesystem-guard.ts`): a claimed, not activated canonical worktree skips the file as `writer_coordinator_required` and logs `gbrain sources writer status <id>` (#6785; the compact and writeback harvest lanes do the same). A `chat_unavailable` result is not terminal: the windowed file or `.wb-` turn keeps no sidecar, nothing is recorded, and the pass stops (`corpus_chat_unavailable`). Failures thrown after a chat call are counted per window (`<file>.failures.json`, see `corpus-windows.ts`) and skipped as `corpus_window_backoff` / `corpus_window_dead_lettered`; `gbrain sweep --retry-failed [--apply]` previews or clears them (doctor `memory_writeback` names the paid retry as its fix). Pinned by `test/sweep-corpus-chat-unavailable-6786.test.ts` and `test/sweep-corpus-failure-cap-6785.test.ts`. `gbrain sweep --once` is the trusted CLI seam for operator catch-up runs (CLI-only, never over MCP). The link pass threads the same `link_resolution.cross_source` opt-in and configured `sources.default` the CLI extract lanes pass into `resolveCandidateSources`, so an edge into another source is created (flag on) or counted as `cross_source_link` in `skipped` (flag off) — never silently dropped, and the reconcile never deletes a cross-source edge `extract links --source db` created. A corpus window's facts batch is keyed by its text (the sweep passes `reAdmitFileRefusals`), so when the canonical file check refused some of its entity requests, `resumeManagedFacts` admits their retained facts as a follow-up batch once every refused page passes that check again: no new extraction, the page's current revision, never wider than the current default visibility, committed requests reported rather than re-admitted, the stored and current writer grants re-checked, at most three follow-ups. Pinned by `test/managed-sweep-refused-window-retry.test.ts`.
- `src/core/context/corpus-windows.ts` — windowed fact extraction of session-corpus files (#5887). `retireCorpusFile` / `retireCorpusTurns` (#6091) record a file or its off-period turns as finished without extracting (`skipped_reason`; a retire overrides another extractor's lease, and a later rewrite extracts only unrecorded turns). `parseCorpusTurns` (defined in the provider-free `corpus-turns.ts`, re-exported here) splits only at the exact `\n\n[user]\n` / `\n\n[assistant]\n` markers `toCorpusText` emits (text before the first marker is a header-less preamble); each user turn is paste-stripped whole before windowing; `planCorpusWindows` packs whole turns into windows of at most `MAX_TURN_TEXT_CHARS` (exported from `facts/extract.ts`) and splits a turn that cannot fit a fresh window at a newline or space, never inside a surrogate pair, repeating its `[role]` header on every piece. `<file>.progress` (suffix constants in `corpus-segments.ts`, GC'd by the session-end hook with the `.txt`, never deleted by its resume rewrite) holds `{version, generation, turns[{start,end,sha256}], continuation{turn_sha256, stripped_offset}|null, windows_done, finished(stat)|null, totals, entity_slugs, skipped_reason?, lease}`: `resumePoint` resumes at the first turn whose hash is unrecorded (appends, compaction remainders and same-size or shorter rewrites cost only their new turns). Every write is compare-and-set under the O_EXCL `<file>.progress.lock` (stale after 30 s): a window commits only when generation, last turn hash and lease owner still match and progress grows; the lease (stale after an hour, like the claim) stops a sweep whose `.in-progress` claim the hook deleted from extracting a window another extractor holds. `runCorpusWindows` returns `complete`/`partial`/`aborted`/`contended`/`changed`/`source_changed`/`unavailable`/`backoff`/`dead_lettered` with cumulative counts; an aborted or `unavailable` window records nothing, and a progress a pre-#6786 build finished with `skipped_reason: chat_unavailable` is rewound under the lease CAS to its retired turns (source binding, totals and links kept). Transport and write errors release the lease and throw; one thrown after a chat call (`extractUnderFailureCount`, observed through the AI invocation preflight) counts against the window's start key (`<turn sha256>@<offset>`) and source incarnation in `<file>.failures.json`: retried on the next sweep, then after 10, 20 and 40 minutes (`CORPUS_WINDOW_RETRY_BASE_MS`), stopped at `CORPUS_WINDOW_FAILURE_CAP` (5); tail growth and error labels never reset it, a commit of that window removes it, and one change of `extractionConfigFingerprint` (model, provider, key presence) re-arms a stopped window once (#6785). `corpusFileCompletion` in `corpus-segments.ts` is the one completion classifier (selection, the under-claim re-check, retention GC; `corpusSidecarState` for the drain and the doctor backlog): a `chat_unavailable` sidecar is pending, and only `done`/`legacy` files get the plain retention (#6786); `adoptFinishedCorpusFile` records a pre-window `.ingested` file at its current turns once (only when the sidecar is newer than the file). `checkpoint-harvest.ts` (`hook:compact`) extracts window 1 only: when more remains it publishes window 1's links, releases the receipt and leaves `.progress` for the sweep; an existing `.progress` means window 1 is done. Pinned by `test/corpus-windows.test.ts`, `test/sweep-corpus-windows.test.ts` and `test/managed-sweep-corpus-windows.test.ts` (managed coordinator, PGLite and Postgres).
-- `src/core/context/corpus-source.ts` — #6268, the session's source for every corpus file. Writers (`hook.ts` compact/stop/session-end, the OpenClaw `compact()`) call `openSessionCorpus`, which freezes one source per session at first use (GBRAIN_SOURCE, then the `.gbrain-source` dotfile, else unresolved) into `<sid>.source.json` in the `sourced/` spool and stamps it into the file name (`.src-<id>`, `default` included; `_unresolved` cannot collide with a real id). Pre-stamp sweepers never list the spool. `resolveCorpusFileSource` is the sweep/harvest/serve and dream-synthesize/extract_atoms read: the stamp or frozen record, else tier 4 alone (`resolveRegisteredLocalPathSource` in `source-resolver.ts`: a registered source whose local_path contains the recorded cwd, active over archived; frozen, tier `engine`), else on a single-source brain that source unfrozen (`sole_source`), else held `corpus_source_unresolved`, never a fallback tier (#7868); `{ readOnly: true }` (dry runs, the synthesis child re-check) freezes and binds nothing; legacy top-level files are held (`corpus_legacy_unstamped`) unless a legacy wb stamp, a frozen record or a single-source brain proves the source, never assigned the pass source. The first engine resolution binds the source incarnation; a recreated source holds the session (`corpus_source_incarnation_changed`). `gbrain sweep --assign-corpus <source>` is the operator mapping (preview, then `--apply`; it also lists sessions the sweep already extracted, because dream synthesis and extract_atoms hold those until their source is mapped, #7805, #7846); doctor `memory_writeback` reports `details.corpus_source_holds`. Tests: `test/corpus-source-stamp.test.ts`.
+- `src/core/context/corpus-source.ts` — #6268, the session's source for every corpus file. Writers (`hook.ts` compact/stop/session-end, the OpenClaw `compact()`) call `openSessionCorpus`, which freezes one source per session at first use (GBRAIN_SOURCE, then the `.gbrain-source` dotfile, else unresolved) into `<sid>.source.json` in the `sourced/` spool and stamps it into the file name (`.src-<id>`, `default` included; `_unresolved` cannot collide with a real id). Pre-stamp sweepers never list the spool. `resolveCorpusFileSource` is the sweep/harvest/serve and dream-synthesize/extract_atoms read: the stamp or frozen record, else tier 4 alone (`resolveRegisteredLocalPathSource` in `source-resolver.ts`: a registered source whose local_path contains the recorded cwd, active over archived; frozen, tier `engine`), else on a single-source brain that source unfrozen (`sole_source`), else held `corpus_source_unresolved`, never a fallback tier (#7868); `{ readOnly: true }` (dry runs, the synthesis child re-check) freezes and binds nothing; legacy top-level files are held (`corpus_legacy_unstamped`) unless a legacy wb stamp, a frozen record or a single-source brain proves the source, never assigned the pass source. The first engine resolution binds the source incarnation; a recreated source holds the session (`corpus_source_incarnation_changed`). `gbrain sweep --assign-corpus <source>` is the operator mapping (preview, then `--apply`; it lists what routing holds, `.txt` and `.md` files in nested folders included, and sessions the sweep already extracted, because dream synthesis and extract_atoms hold those until their source is mapped, #7805, #7846, #7849); it releases only `corpus_legacy_unstamped` and `corpus_source_unresolved` holds, and the phases print each other reason's own fix (`corpusHoldRelease` in `synthesize-source-routing.ts`); doctor `memory_writeback` reports the same listing as `details.corpus_source_holds`. Tests: `test/corpus-source-stamp.test.ts`.
- `src/core/context/sync-ipc.ts` + `src/core/serve-sync-runner.ts` + `src/commands/sync-delegate.ts` — serve-delegated sync. `sync-ipc.ts` is the LEAF wire module: `DELEGATED_SYNC_OPTION_FIELDS` (the fields `SYNC_FLAGS` in `src/core/sync-flags.ts` forwards through the serve, plus `sourceId`, `embedDeferred`, `timeoutSeconds` and `origin`) drives the validator, the CLI wire-builder, and the serve-side SyncOpts builder; `validateDelegatedSyncOptions` rejects unknown keys fail-closed (repoPath/skipLock/lockId/concurrency are unreachable from the socket), requires `timeoutSeconds` (0 = the explicit `--no-hard-deadline` unbounded encoding; everything else clamps to 24h), and `toWireSyncResult` truncates `pagesAffected` to 50 + a true total under the 256KB message cap. `serve-sync-runner.ts` is the serve-side module singleton: one job at a time (correctness still rests on the `gbrain-sync:<source>` row lock inside performSync), clientToken attach (a lost-ack retry finds its own running OR retained-terminal job instead of duplicate-running), per-job deadline timer, `[serve-sync]` lifecycle stderr lines, an idempotent shared `shutdownDelegatedSync()` both serve shutdown paths await BEFORE `engine.disconnect()` (the disconnect-mode drain is allowAbort:false after `_db` is nulled, so settle writes need the live engine; a registered drainer remains as backstop), and `maybeDrainDeferredEmbeds` (delegated jobs always run noEmbed — the cost gate lives in runSync — and the serve drains stale embeds afterwards via `runEmbedCore`, keyless-safe, cleared only when a drain finds nothing left; wire `noEmbed` records that the USER declined embeds and suppresses the drain). `sync-delegate.ts` is the CLI half: read-only holder probe (`probeLivePgliteHolder`), DEFAULT-DENY argv gate (any unclassified token refuses by name — a silently dropped `--exclude` would perform the wrong sync), engine-free source tiers (`resolveSourceIdEngineFree`), 1s poll loop tolerant of event-loop-blocked serves with a PID-probe backstop, `unknown_job` → serve-restarted resume hint, Ctrl-C → `sync_abort` (second Ctrl-C exits 130), and runSync's `pull_failed` verdict mirroring. Mounts never delegate; opt-outs `--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve). #6317 (D1 a′), managed Postgres brains: `maybeDelegateManagedSyncToServe(engine, args, opts)` runs post-connect from `runSingleSourceSync` right before `performSync`; it probes the host's live full `serve` consumer through `persistence_consumers` (`consumer-heartbeat.ts`, the database, never a socket), admits the catch-up's flags (`--no-bulk`, `--lanes`/`--no-lanes`, `--json`, the processing flags), sends the CLI's durable `cli` registration in `sync_start`, prints the drain's own numbered lines from `sync_status` (`managed`, `lines`, `drain`, `next`) and returns the SyncResult to the in-process printers, so exit codes and the JSON envelope do not change. The serve verifies the registration (`withVerifiedLocalRegistration`) and runs `performSync({ drain: true })` as that writer under `withHumanLineSink`; the shared-secret lane stays under `withLegacySyncDelegation` and is still refused on a managed brain; a denied, revoked or stdio registration answers `sync_start` with `permission_denied` and the envelope (`refusal`), which the CLI rethrows. Every other rung (no owner, a non-serve owner, an unsupported flag, no socket, the kill switch, `stale_serve` / `unsupported_kind` from an older serve, `source_mismatch`, a serve lost mid-drain) runs without the serve with one actionable line; only the opt-out, a serve not answering its socket and a `stale_serve` serve call `forceOwnConsumer` (#6543), the rest admit writes the serve consumes under `persistence.single_consumer`. #6712 PR 1: neither builder sends `explicitProcessing` any more; the serve validates one from an older CLI by shape and drops it (`WIRE_SKEW_WINDOWS` in `src/core/wire-skew.ts`), and a resume inherits the cursor's processing opt-outs. #6712 PR 2: `WIRE_BOOL_FLAGS` / `VALUE_FLAGS` / `IGNORED_FLAGS` and the managed pick list are views of `SYNC_FLAGS`; a retired field the validator drops comes back as `ignored`, and the serve logs `retiredWireNotice` and streams it to the older client as a progress line (`test/sync-flag-table-6712.test.ts`). The serve's delegated run follows the source's drain lease as holder `serve` (`followDrainLease`, `drainHolder`). Wire `embedDeferred` (sent only when true) carries the cost gate's runtime deferral, so adopting a cursor that stores `noEmbed=false` never embeds in that run. `maybeDelegateManagedSyncToServe` refuses `--skip-failed` / `--include-gitignored` on a managed source with `managed_sync_flag_refused` before any probe or socket call (`test/sync-delegated-options-6696.serial.test.ts`, `test/sync-managed-forbidden-flags-6696.test.ts`). Pinned by `test/context/sync-ipc-validation.test.ts`, `test/sync-delegate-ladder.test.ts`, `test/serve-sync-runner.serial.test.ts`, `test/serve-sync-handoff.serial.test.ts`, `test/context/resolve-ipc-sync-kinds.test.ts`, `test/e2e/sync-delegation-under-serve.serial.test.ts` (gating tier1 step) and `test/e2e/serve-delegated-managed-sync.serial.test.ts` (Postgres, spawned serve, MCP latency printed). GBRA-133 2b.3: the deferred-embed drain re-arms itself until the backlog is gone: a pass that left work retries after `GBRAIN_DEFERRED_EMBED_RETRY_MS` (default 5000), a failing provider backs off 1x/3x/12x/60x, a running delegated sync defers it at most `DEFERRED_EMBED_BUSY_MAX` (3) times before it drains beside the sync, and a keyless brain keeps the backlog with no provider call or timer; `deferredEmbedDecisions` records each decision. #7243: `startDelegatedSync`'s in-process `logLines` option (never on the wire) also writes a verified job's human lines to the serve log, for the resident notifier's runs that nobody polls.
- `src/core/capability.ts` — config-plane keyless/keyed detection + the honest capability report (per-provider keyless banner: OpenAI = semantic search + auto-extraction, Voyage = semantic search, Anthropic = auto-extraction) rendered by verify and the runbook. The extraction probe resolves through the SAME shared `resolveEffectiveChatModel` the gateway's reconfigure fallback uses (`GBRAIN_MODEL` > servable file pin > key-aware tier default), so a stale unservable pin degrades identically in the report and at runtime. Key/env fold comes from `mergedProviderEnv` (`src/core/ai/provider-env.ts`). Accepted limitation (documented in the module): DB-plane overrides (`models.default`, `facts.extraction_model`) are invisible to this engine-less probe; the runtime gate in `facts/extract.ts` and the engine-aware pre-enqueue gate in `facts/backstop.ts` are the backstops.
- `src/core/readiness.ts` — capability readiness (agent operator contract A7): `ReadinessEntry {capability, state, reason, why, fix, tier, asset?, http_visible}` for embeddings, chat_llm, writeback, tool_surface, sync, harness_wiring (config tier) and worker, backup per asset, migrations, sync (probed tier); each capability's reasons are a closed exported const (`EMBEDDINGS_REASONS`, …). `configReadiness(cfg, {transport})` is synchronous and memoized per (config object, transport); its only file read is one memoized `peekLock()` (none when this process holds the lock, via `heldLockFor`), plus one process-wide gbrain-binary PATH lookup on the CLI transport only. The HTTP view drops `http_visible:false` entries and passes the rest through `redactForTransport`. `probedReadiness(engine, {cache})` never calls `getStats`/`getHealth`; 60 s cache (`createReadinessCache()` per ServeHttpContext, process-wide otherwise), single-flight, 2 s per-probe bound, stale-while-revalidate; `readinessTail` is MCP initialize's best-effort 250 ms tail. `embeddingEnablement(cfg)` is the one "turn on embeddings" fix: resolves the datastore (PGLite path, Postgres, a mount from `--brain`/`GBRAIN_BRAIN_ID`) and the column width, picks a keyed provider that fits (or asks for a key with `inputs`), and emits in-place `init --force --embedding-model … --embedding-dimensions … [--path …]` or, for a mount, `embeddings enable --brain …`; it never rebuilds a column. `exclusiveFix` turns an exclusive fix into a two-step plan (actor `user` stops the owning serve named by `lock_owner`, `then` the command) unless the command delegates to the owner. A live status-only `serve --http` marker (`liveStatusMarkers`, config plane) makes CLI `harness_wiring` `serve_status_only` with `transport: 'http'` and the status reason's fix (`httpStatusServerEntry`, shared with doctor), never "start `gbrain serve --http`" on the port it holds. `harnessWiringEntry` builds harness-native stdio registration (absolute binary, `stdioServeArgv` with `REGISTRATION_SURFACE` = `starter`, or `input.surface` from `gbrain init --surface`; `configReadiness(cfg, {transport, surface})` skips the memo when a surface is passed), shared-HTTP `bootstrap harness`, or the MEMORY_VERBS install anchor, with effects and destinations disclosed. Consumers never coach on `disabled_by_choice`. Tests: `test/readiness.test.ts`, `test/readiness-http-cost.test.ts`, `test/readiness-advice-lint.test.ts` (no hand-written enablement advice outside this module; shrink-only baseline), `test/readiness-embedding-enablement.serial.test.ts` (the E2E matrix).
diff --git a/docs/architecture/key-files/ambient-capture.md b/docs/architecture/key-files/ambient-capture.md
index 11fbba7138..63009a257f 100644
--- a/docs/architecture/key-files/ambient-capture.md
+++ b/docs/architecture/key-files/ambient-capture.md
@@ -9,6 +9,6 @@ each lane's claim, and a re-check at fact admission. User guide:
Key files:
- `src/core/context/capture-consent.ts` + `src/core/facts/capture-sources.ts` (+ `captureGateDecision` in `src/core/facts/writeback-config.ts`) — `captureGateDecision(cfg, lane)` is the ONE truth table for the ambient capture lanes (`writeback` = `.wb-` Stop-hook turns, `compact` = PreCompact segments + OpenClaw compactions, `session_end` = SessionEnd `<sid>.txt`): explicit `off` retires every lane; unset retires `writeback` and extracts `compact`/`session_end` (the hooks are their opt-in); read error, plane drift, invalid mode, and (compact/session_end) a DB-absent file-mirror `off` (`off_unsynced`) hold. `captureLaneStates`/`captureLaneSummary`/`writebackOffMessage`/`writebackUnsetMessage`/`WRITEBACK_RESTART_AFTER_OFF` render it for `config set|unset|get` (stderr lane line), doctor `memory_writeback` (`details.capture_lanes`, `details.restart_after_off`) and the guide's truth table. `src/core/context/capture-consent.ts`: capture side `recordCaptureIfOff` (the PreCompact `bankCompactSegment` `beforeWrite` callback, the SessionEnd corpus write and the OpenClaw spool write this brain's own `<file>.capture-off.<brain>.json` (`captureOffRecordPath`; brain identity = hash of the resolved config dir, turn hashes via `corpus-turns.ts`) BEFORE the file lands, unioning a pre-wave-12 single `<file>.capture-off.json` that names this brain, so two brains sharing a corpus directory never overwrite each other's off turns; GC (`corpus-segments.ts`, `CAPTURE_OFF_INFIX`) reaps any brain's orphan record only after the seat grace); extraction side `resolveCaptureGate` + `applyCaptureGate` (hold / `retireCorpusFile` / fold this brain's turns, own record plus a matching legacy record, via `retireCorpusTurns`, retiring a file whose every turn was captured under off; foreign-brain records ignored; an unreadable or invalid record holds `capture_record_unreadable` and makes `recordCaptureIfOff` throw, never reads as "no record"), called under the claim before any provider call or receipt republish in `checkpoint-harvest.ts` (`runOne`, `runWritebackTurn`), `context-engine.ts` rung 3 and `sweep.ts` (including the keyless/extraction-disabled early returns). Publication side: `src/core/facts/capture-sources.ts` holds `FACTS_BACKSTOP_SOURCES` (`as const`; `FactsBackstopCtx['source']` derives from it), the ambient subset, `captureGateLaneForSource` and `assertAmbientCaptureAdmissible` (code `ambient_capture_off`), re-checked inside `admitManagedFactsBatch`'s transaction (`facts-maintenance.ts`; sessions and intents carry `captureSource` / `capture_source`, so #6048 follow-up batches are re-checked too) and before the unmanaged fence write in `backstop.ts`; requests admitted before `off` publish. Tests: `test/capture-consent-gate.serial.test.ts`, `test/capture-consent-admission.test.ts` (PGLite + Postgres), `test/capture-consent-inventory.test.ts`. Retired turn hashes also land in `.progress` `retired_turns` (`retireCorpusFile`, `retireCorpusTurns`); `planCorpusWindows` skips them wherever a rewrite places them, and `withoutOffPeriodTurns` (capture-consent.ts) strips them from what `discoverTranscripts` hands dream synthesis.
-- `src/core/context-engine.ts` + `src/openclaw-context-engine.ts` — the deterministic context engine OpenClaw loads on every turn (`assemble()` injects the Live Context block, zero-LLM). `createGBrainContextEngine({workspaceDir, resolveEntities?})` accepts an OPTIONAL host-injected resolver (`ENGINE_API_VERSION` 0.3.0, additive — older hosts work unchanged; the plugin entry maps `ctx.resolveEntities`/`ctx.brainQuery` onto it). Checkpoint compaction: `compact()` runs a time-bounded (8s), fail-open, lazily-imported checkpoint step BEFORE delegating — spools the since-last-boundary window (openclaw tail reader over the exported adapter mapper, 40-turn cap = the no-prior-boundary fallback) as a content-addressed corpus segment + ledger entry, then rung 2 (PGLite: one `bankOnly`+`flushCorpusFile` IPC round trip to serve) or rung 3 (Postgres: inline harvest over the reflex ladder's exported `getDirectPostgresEngine` singleton, under sweep claim fencing + capability/kill-switch gates, abort post-check) — and rides an additive `result.gbrain_checkpoint` bag on the delegate's return (`ownsCompaction` stays false). After the segment is spooled, the Memorable receipt lane runs (gate + stamp via `memorableGateAllowed`, span-filtered redacted tool calls, `recordAndRelayReceipt` with `harness: 'openclaw'` — per-compaction capture, content-hash dedup on retries, fail-open for the checkpoint; the whole block is skipped once the host's compact() deadline has fired; the rendered segment text is re-scanned with highEntropy at receipt time and the relay REFUSED fail-closed on any hit — the segment rendering feeds the ledger hash and cannot change, so the next compaction window re-evaluates; this lane NEVER compacts the receipts file — the hook lane is the ONE compactor, single-rewriter rule — but DOES trim the relay file, since an openclaw-only host has no hook lane and converging newest-keeping trims make concurrent trims safe). `assemble()` consumes `sessionId ?? sessionKey` and splices a deterministic envelope-bearing Compaction-checkpoint block at parts[1] (after Live Context) from the banked manifest via an in-process memo + hash-keyed polls (≤5; stale manifests can't satisfy a poll for the new segment; no manifest ⇒ byte-identical output). `assemble()` runs the Retrieval Reflex after the Live Context block: extracts the current turn's user text, builds prior-context text (every message EXCEPT the current turn — suppression must not see the triggering mention), passes the rolling window (`getWindowTurns`, last 12 user/assistant turns; the reflex slices to its configured `retrieval_reflex_window_turns`), and appends the pointer block. `warmReflex()` fires at construction. Current-host plugin factories may be called with zero arguments. The host workspace takes precedence; ambiguous/unbound legacy fallback warns and reads no source. The canonical slot ID is `gbrain-context-engine`; `gbrain-context` remains a registry alias, not a current-host slot alias. The exclusive context-engine contract and no-write stateless admitted-turn acknowledgement are additive. `assemble` uses an authoritative separate prompt: sqlite transcript-storage metadata fences historic turns, whereas an identical final legacy user message already represents the current turn. Reflex-only synthesis leaves messages intact; absent prompt keeps message extraction. These contracts do not prove model recall. `compact()` records the session's seat sidecar (`context/seat.ts`, harness `openclaw`, seat keyed to the agent directory holding `sessions/`) before spooling the segment; a failure never fails the checkpoint. OpenClaw 2026.9.x calls `compact()` with a `sessionTarget` and no `sessionFile`; `readCompactTail` then reads the transcript through the host's `openclaw/plugin-sdk/session-transcript-runtime` (`readSessionTranscriptEvents`, lazily imported; `__setTranscriptRuntimeLoaderForTests` is the seam) and maps the events with the JSONL mapper (`readOpenclawEventsTail` in `corpus-segments.ts`), keeping the file path for older hosts. Every compaction writes one `openclaw-compact` heartbeat (status and reason codes); doctor `memory_writeback` warns when a week of compactions banked none (`details.openclaw_compactions_7d`). Pinned-host proof: `test/openclaw-context-engine-native.serial.test.ts` (gateway plus `openclaw sessions compact`); fake runtime: `test/openclaw-compact-transcript-runtime.serial.test.ts`.
+- `src/core/context-engine.ts` + `src/openclaw-context-engine.ts` — the deterministic context engine OpenClaw loads on every turn (`assemble()` injects the Live Context block, zero-LLM). `createGBrainContextEngine({workspaceDir, resolveEntities?})` accepts an OPTIONAL host-injected resolver (`ENGINE_API_VERSION` 0.3.0, additive — older hosts work unchanged; the plugin entry maps `ctx.resolveEntities`/`ctx.brainQuery` onto it). Checkpoint compaction: `compact()` runs a time-bounded (8s), fail-open, lazily-imported checkpoint step BEFORE delegating — spools the since-last-boundary window (openclaw tail reader over the exported adapter mapper, 40-turn cap = the no-prior-boundary fallback) as a content-addressed corpus segment + ledger entry, then rung 2 (PGLite: one `bankOnly`+`flushCorpusFile` IPC round trip to serve) or rung 3 (Postgres: inline harvest over the reflex ladder's exported `getDirectPostgresEngine` singleton, under sweep claim fencing + capability/kill-switch gates, abort post-check) — and rides an additive `result.gbrain_checkpoint` bag on the delegate's return (`ownsCompaction` stays false). After the segment is spooled, the Memorable receipt lane runs (gate + stamp via `memorableGateAllowed`, span-filtered redacted tool calls, `recordAndRelayReceipt` with `harness: 'openclaw'` — per-compaction capture, content-hash dedup on retries, fail-open for the checkpoint; the whole block is skipped once the host's compact() deadline has fired; the rendered segment text is re-scanned with highEntropy at receipt time and the relay REFUSED fail-closed on any hit — the segment rendering feeds the ledger hash and cannot change, so the next compaction window re-evaluates; this lane NEVER compacts the receipts file — the hook lane is the ONE compactor, single-rewriter rule — but DOES trim the relay file, since an openclaw-only host has no hook lane and converging newest-keeping trims make concurrent trims safe). `assemble()` consumes `sessionId ?? sessionKey` and splices a deterministic envelope-bearing Compaction-checkpoint block at parts[1] (after Live Context) from the banked manifest via an in-process memo + hash-keyed polls (≤5; stale manifests can't satisfy a poll for the new segment; no manifest ⇒ byte-identical output). `assemble()` runs the Retrieval Reflex after the Live Context block: extracts the current turn's user text, builds prior-context text (every message EXCEPT the current turn — suppression must not see the triggering mention), passes the rolling window (`getWindowTurns`, last 12 user/assistant turns; the reflex slices to its configured `retrieval_reflex_window_turns`), and appends the pointer block. `warmReflex()` fires at construction. Current-host plugin factories may be called with zero arguments. The host workspace takes precedence; ambiguous/unbound legacy fallback warns and reads no source. The canonical slot ID is `gbrain-context-engine`; `gbrain-context` remains a registry alias, not a current-host slot alias. The exclusive context-engine contract and no-write stateless admitted-turn acknowledgement are additive. `assemble` uses an authoritative separate prompt: sqlite transcript-storage metadata fences historic turns, whereas an identical final legacy user message already represents the current turn. Reflex-only synthesis leaves messages intact; absent prompt keeps message extraction. These contracts do not prove model recall. `compact()` records the session's seat sidecar (`context/seat.ts`, harness `openclaw`, seat keyed to the agent directory holding `sessions/`) before spooling the segment; a failure never fails the checkpoint. A sub-agent session (`isOpenClawSubagentKey`: `agent:<id>:subagent:<uuid>`) is marked first with a speaker sidecar (`agent-launched`, #8080; nothing is banked when it cannot be written), and rung 3 passes the speaker to the facts pipeline. OpenClaw 2026.9.x calls `compact()` with a `sessionTarget` and no `sessionFile`; `readCompactTail` then reads the transcript through the host's `openclaw/plugin-sdk/session-transcript-runtime` (`readSessionTranscriptEvents`, lazily imported; `__setTranscriptRuntimeLoaderForTests` is the seam) and maps the events with the JSONL mapper (`readOpenclawEventsTail` in `corpus-segments.ts`), keeping the file path for older hosts. Every compaction writes one `openclaw-compact` heartbeat (status and reason codes); doctor `memory_writeback` warns when a week of compactions banked none (`details.openclaw_compactions_7d`). Pinned-host proof: `test/openclaw-context-engine-native.serial.test.ts` (gateway plus `openclaw sessions compact`); fake runtime: `test/openclaw-compact-transcript-runtime.serial.test.ts`.
- `src/commands/doctor/checks/agent-session-facts.ts` — `agent_session_facts` (wave check, host-only, #8064): counts active owner-attributed capture-lane facts `classifyAgentSessionFacts` classes `evidenced` (speaker sidecar; no operator flags) or `ambiguous` (repeated first user turn); `excluded` and `unclassifiable` are reported, never a finding. Names `gbrain repair agent-session-facts` (explicit-only) and says the apply needs the user's agreement. Read-only; health unknown when the scan fails.
-- `src/core/repair/agent-session-facts.ts` — `gbrain repair agent-session-facts` (#8064), explicit-only, preview-bound and destructive (`--apply --expect <hash> --yes`). `classifyAgentSessionFacts` (read-only; also doctor `agent_session_facts`) takes active capture-lane facts attributed to `user` or nobody and classes each by its session (`captureSessionId`): `evidenced` by a speaker sidecar (`readSpeakerSidecar` in the corpus dir, its spool dir or beside the session's files), an operator `--session <id>`, or a `<sid>.source.json` cwd under an operator `--cwd <prefix>` (realpath, path-boundary compare); `ambiguous` when the session's first user turn (head of its earliest retained file, whitespace-normalized, lowercased, at least 40 chars) shares its first 160 chars with 3+ other sessions; `excluded:owner_also_said` when the claim and entity also have an active user-attributed row from a non-suspect session; no retained corpus, sidecar or record is `unclassifiable`. `agentSessionTakes` lists active, unresolved fact/self takes whose every `consolidated_into` fact is non-user once the approved facts are. Approved items: fact pages (phase 0) then take pages (phase 1). The apply rechecks each row; fenced facts get `attributed_to: other` and `speakerContextNote(principal)` in the `## Facts` fence and fenced takes are struck in the takes fence, each by one revision-bound `put_page`; database-only facts and takes change through one `managed_maintenance_agent_session_facts` request per page on a managed brain (`prepareAgentSessionFactsWrite`, dispatched from `prepareMaintenanceMutation`) or one `maintenanceTransaction` otherwise (`applyAgentSessionWrite` rechecks under the row lock). Nothing is deleted. Pinned by `test/repair-agent-session-facts.test.ts`.
+- `src/core/repair/agent-session-facts.ts` — `gbrain repair agent-session-facts` (#8064), explicit-only, preview-bound and destructive (`--apply --expect <hash> --yes`). `classifyAgentSessionFacts` (read-only; also doctor `agent_session_facts`) takes active capture-lane facts attributed to `user` or nobody and classes each by its session (`captureSessionId`): `evidenced` by a speaker sidecar (`readSpeakerSidecar` in the corpus dir, its spool dir or beside the session's files), an operator `--session <id>`, or a `<sid>.source.json` cwd under an operator `--cwd <prefix>` (realpath, path-boundary compare); `ambiguous` when the session's first user turn (head of its earliest retained file, whitespace-normalized, lowercased, at least 40 chars) shares its first 160 chars with 3+ other sessions; `excluded:owner_also_said` when the claim and entity also have an active user-attributed row from a non-suspect session; no retained corpus, sidecar or record is `unclassifiable`. `agentSessionTakes` lists active, unresolved fact/self takes whose every `consolidated_into` fact is non-user once the approved facts are. Approved items, one write each: fact pages (phase 0; a page with database-only and fenced rows is two items, the fenced one after every fact page, so a pending database write never skips its fenced rows) then take pages (phase 1); one apply run builds the corpus index once (`PageItem.indexes`). The apply rechecks each row; fenced facts get `attributed_to: other` and `speakerContextNote(principal)` in the `## Facts` fence and fenced takes are struck in the takes fence, each by one revision-bound `put_page`; database-only facts and takes change through one `managed_maintenance_agent_session_facts` request per page on a managed brain (`prepareAgentSessionFactsWrite`, dispatched from `prepareMaintenanceMutation`) or one `maintenanceTransaction` otherwise (`applyAgentSessionWrite` rechecks under the row lock). Nothing is deleted. Pinned by `test/repair-agent-session-facts.test.ts`.
diff --git a/docs/architecture/key-files/canonical-reconciliation-continued.md b/docs/architecture/key-files/canonical-reconciliation-continued.md
index bda6b7f80a..8a88e5698e 100644
--- a/docs/architecture/key-files/canonical-reconciliation-continued.md
+++ b/docs/architecture/key-files/canonical-reconciliation-continued.md
@@ -7,3 +7,5 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/doctor/checks/rows-behind.ts` — doctor `sync_rows_behind_checkpoint` (BRAIN, after `sync_overwritten_db_edits`): per source counts and first slugs from `scanRowsBehind`; `warn` on `behind` rows with the read-only `gbrain repair rows-behind --source <id> --json` preview as the fix; `unknown` (info) when the `GBRAIN_DOCTOR_ROWS_BEHIND_TIMEOUT_MS` budget (default 10 s) stopped a scan or a checkout is unreadable; not applicable (ok) off the owner host and on repo-less brains.
- `src/core/repair/rows-behind.ts` — `gbrain repair rows-behind --source <id>`: explicit-only, preview-bound (`--apply --expect <hash>`, `--include-ambiguous` adds rows with no import record). `reimport` submits the committed bytes through `submitManagedFileRepair`; `hold:<code>` writes the hold sync would have written (`writeGitHold`). Refused off the owner host (`not_owner_host`). Never runs on upgrade. Tests: `test/rows-behind-checkpoint-8071.test.ts` (PGLite and Postgres via `test/e2e/rows-behind-checkpoint-8071-postgres.test.ts`).
- GST-2201, a file that comes back after sync deleted its page: `readShadowLevel` (`sync-pass.ts`) reads whether a tombstone is sync-made (`syncDeleteOrigin`, `sync-delete-tombstones.ts`) into `page.syncDeleted`, and `sync-classify.ts` classifies such a path `import` ahead of `deleted_same` / `deleted_edited` (uncommitted bytes take `dirty`; an old hold on it re-runs). The selection fingerprint carries `sync_deleted_restore`, so the first pass after the upgrade reads the whole level once. `originCommitted` (`sync-markers.ts`) says whether a page's file is in the tree at the source's `last_commit` or at HEAD (false off a managed checkout or for a company-brain source; an unreadable checkout counts as committed). A retention purge (`page-prepare.ts`) of a tombstone whose file is committed defers a sync-made tombstone (`revision_conflict`) and purges any other database-only (`databaseOnlyReason: committed_file`), so the file stays. Tests: `test/sync-restored-file-purge.test.ts` (PGLite and Postgres), `test/sync-classify-6712.test.ts`.
+
+- `src/core/persistence/grandfather.ts` — the retired v0.13.1 grandfather's request preparer (#7814). Upgrades no longer stamp `validate: false` into pages, so a `managed_grandfather` put_page request an older binary admitted and left queued is refused `revision_conflict` (the request ends `conflict`) and the page, its file and its revision stay unchanged. The refusal records origin `grandfather_retired` (it outlives receipt compaction), and `classifyTerminal` reads it, or an uncompacted `managed_grandfather` intent, as the always-historical `retired_operation` category, so doctor `persistence_terminal_failures` counts it as history with a "retired grandfather, nothing to do" note (#7837). Neither file holds a canonical write reference any more, so neither has a `canonical-writers.tsv` row and a new write there trips the census. `test/grandfather-managed.test.ts` covers it.
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.md
index ee48444d6c..03259e0473 100644
--- a/docs/architecture/key-files/canonical-reconciliation.md
+++ b/docs/architecture/key-files/canonical-reconciliation.md
@@ -12,8 +12,6 @@ See [generations](generations.md) and [continued entries](canonical-reconciliati
- `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/persistence/grandfather.ts` — the retired v0.13.1 grandfather's request preparer (#7814). Upgrades no longer stamp `validate: false` into pages, so a `managed_grandfather` put_page request an older binary admitted and left queued is refused `revision_conflict` (the request ends `conflict`) and the page, its file and its revision stay unchanged. `test/grandfather-managed.test.ts` covers it.
-
- `src/core/persistence/managed-mode.ts` — the one reader of the brain's persistence mode (#6482). `readManagedMode` / `readPersistenceBrain` accept exactly one `persistence_brain` row with a boolean `enabled` (optionally `FOR SHARE` / `FOR UPDATE`) and refuse anything else (`storage_error`, `detail: persistence_mode_unknown`, fix `gbrain sources writer status --probe --json`); only a well-formed `enabled: false` row selects the unmanaged path, so a missing, duplicated or malformed row can never route a write around the owner. Every non-test reader of the mode goes through it (`test/persistence-mode-reader-guard.test.ts` lists the few schema and admin-intent files allowed their own statement); `ownership.ts` re-exports it for callers that already import ownership.
- `src/core/persistence/sync-slices.ts` — #6349 path-sliced staging for a managed target that exceeds the cursor bound with no commit axis to stage on (a first sync, a `--full` tree walk, one commit above the bound). `sliceEntries` cuts the whole resolved manifest in `(phase, code-unit path)` order: every import slice, then bounded deletion slices, the longest prefix the bound admits. The slice cursor `{ phase, after, head, target }` lives in `op_checkpoints` (`managed-sync-slice`, keyed by source, incarnation and the run's cursor options so a resumed invocation with other exclusions starts over), written or cleared by the slice's checkpoint in the same transaction that leaves `last_commit` untouched until the last slice settles; `sync-discovery.ts` resumes an unfinished target pinned at its recorded commit.
diff --git a/docs/architecture/key-files/core-cycle-patterns.md b/docs/architecture/key-files/core-cycle-patterns.md
index 31c47d71b7..6c6a65d3b5 100644
--- a/docs/architecture/key-files/core-cycle-patterns.md
+++ b/docs/architecture/key-files/core-cycle-patterns.md
@@ -17,7 +17,7 @@ Patterns, drift reports and the cycle modules listed after them.
- `src/core/cycle/synthesize-verify-epochs.ts` — the scope side of dream-page verification, peeled move-only from `synthesize-verify.ts` (module-size ratchet) and re-exported from it: `readVerifyEpoch`, `loadChildWriteEpochs`, `loadPreRunRevision`, `isDreamOwnedPage`, `resolveVerifyPrior`, exactly as described under `synthesize-verify.ts` above. Pure database reads; no claim check lives here.
- `src/core/cycle/synthesize.ts` — Synthesize phase (a transcript whose estimate alone exceeds `dream.synthesize.budget_usd` is skipped as `over_budget_alone`, never a budget deferral of the rest): conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir` (session routing read-only in a dry run; each kept corpus file is pinned on its child job as `corpus_source`, file, corpus dir and source incarnation, which the child re-resolves before any model call, #7850), runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached as verdicts: `triage-backoff.ts` upserts a score-NULL backoff marker instead and the next passes report the file `deferred` with `code: 'triage_unreliable_backoff'` (counted in `details.triage.unreliable_backoff`, not in `deferred`, so the cooldown and autopilot's maintenance stamp are not held) without a judge call until the backoff ends; nor is a verdict a `chat_fallback_chain` model gave (`TriageResult.answeredBy`, from the judge client's `answered_by` marker): it decides the run and the next cycle re-judges on the configured model. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the... (line truncated to 2000 chars) #7240: a transcript whose child cannot be queued (any error but a lost connection or cancellation) is skipped `submit_failed (<code>)` with its own fresh chunks rolled back, and the fan-out continues instead of failing the phase, whose private-queue cleanup would cancel every child already queued (`test/dream-synthesize-submit-failure-7240.test.ts`).
-- `src/core/cycle/transcript-discovery.ts` — Pure filesystem walk for synthesize. `discoverTranscripts(opts)` filters `.txt` files by date range, min_chars, and word-boundary regex `excludePatterns` (`medical` matches "medical advice" but NOT "comedical"; power users may pass full regex). `readSingleTranscript(path)` is the `gbrain dream --input <file>` ad-hoc path. Self-consumption guard: `DREAM_OUTPUT_MARKER_RE` (anchored at frontmatter open `---\n`, optional BOM + CRLF tolerance, scans first 2000 chars for `dream_generated: true` with case-insensitive value and word boundary on `true`) drives `isDreamOutput(content, bypass=false)`. Both functions skip matching files and emit a `[dream] skipped <basename>: dream_generated marker` stderr log (no silent skips). An `excludePatterns` hit is never logged per file (the matching files are sensitive by definition); instead both functions emit ONE `[dream] excluded N transcript(s) matching exclude_patterns (<label>: n, ...)` stderr line at the end of discovery, naming only the count and the configured pattern labels that fired, never a path, basename, or content. `DEFAULT_EXCLUDE_PATTERNS` is unchanged (`medical`, `therapy`). `bypassGuard?: boolean` on `DiscoverOpts` and `readSingleTranscript`'s opts disables the guard for the explicit `--unsafe-bypass-dream-guard` escape hatch only — never auto-applied for `--input`. Two path-level guards run before the content read: `selfCaptureSessionIds` (from `claudeCliSelfSessionIds`) skips a `.txt` corpus file (session-end, checkpoint segment or writeback form, via `corpusFileSessionId`) captured from gbrain's own claude-cli call, and `excludeDirs` (synthesize passes the reflections, originals, patterns-output and cycle-summary directories under `brainDir`, empty under `--unsafe-bypass-dream-guard`) skips any file whose resolved path sits inside one, so an output a failed postprocess left unmarked is never re-synthesized while a transcript that merely names such a path is still disc... (line truncated to 2000 chars)
+- `src/core/cycle/transcript-discovery.ts` — Pure filesystem walk for synthesize. `discoverTranscripts(opts)` filters `.txt` files by date range, min_chars, and word-boundary regex `excludePatterns` (`medical` matches "medical advice" but NOT "comedical"; power users may pass full regex). `readSingleTranscript(path)` is the `gbrain dream --input <file>` ad-hoc path. Both carry a `.txt` session's agent `speaker` (its `.speaker.json` sidecar, `corpusFileSpeaker`, #8080), and `buildSynthesisPrompt` then tells the model the user turns are that agent's brief. Self-consumption guard: `DREAM_OUTPUT_MARKER_RE` (anchored at frontmatter open `---\n`, optional BOM + CRLF tolerance, scans first 2000 chars for `dream_generated: true` with case-insensitive value and word boundary on `true`) drives `isDreamOutput(content, bypass=false)`. Both functions skip matching files and emit a `[dream] skipped <basename>: dream_generated marker` stderr log (no silent skips). An `excludePatterns` hit is never logged per file (the matching files are sensitive by definition); instead both functions emit ONE `[dream] excluded N transcript(s) matching exclude_patterns (<label>: n, ...)` stderr line at the end of discovery, naming only the count and the configured pattern labels that fired, never a path, basename, or content. `DEFAULT_EXCLUDE_PATTERNS` is unchanged (`medical`, `therapy`). `bypassGuard?: boolean` on `DiscoverOpts` and `readSingleTranscript`'s opts disables the guard for the explicit `--unsafe-bypass-dream-guard` escape hatch only — never auto-applied for `--input`. Two path-level guards run before the content read: `selfCaptureSessionIds` (from `claudeCliSelfSessionIds`) skips a `.txt` corpus file (session-end, checkpoint segment or writeback form, via `corpusFileSessionId`) captured from gbrain's own claude-cli call, and `excludeDirs` (synthesize passes the reflections, originals, patterns-output and cycle-summary directories under `brainDir`, empty under `--unsafe-bypass-dream-guard`) skips any file whose resolved path sits inside one, so an output a failed postprocess left unmarked is never re-synthesized while a transcript that merely names such a path is still disc... (line truncated to 2000 chars)
- `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.
diff --git a/docs/architecture/key-files/core-services-1-continued.md b/docs/architecture/key-files/core-services-1-continued.md
index 03debf2fe9..69b95e9840 100644
--- a/docs/architecture/key-files/core-services-1-continued.md
+++ b/docs/architecture/key-files/core-services-1-continued.md
@@ -12,7 +12,7 @@ The content-repair judgment tier under `src/core/content-repair/`, then the Retr
- `src/core/context/` — Retrieval Reflex (Layer 1). `entity-salience.ts`: pure, zero-LLM, precision-biased `extractCandidates(text)` (capitalized runs + `@handles`, STOPWORDS + soft COMMON_WORDS + sentence-start guard, deterministic, capped; a lowercase weak pass additionally emits `weak: true` candidates — lowercase words ≥3 chars on a separate `MAX_WEAK_CANDIDATES=32` budget that never evicts strong candidates — which downstream may resolve through the alias arm ONLY) + `extractCandidatesFromWindow(turns)` (merges per-turn extraction across the last N turns by normalizeAlias form with occurrence/newest-turn/user-mention metadata; salience-ordered — recency > frequency > user-role — so the cap drops stale assistant chatter first). `retrieval-reflex.ts`: `resolveEntitiesToPointers(engine, sourceId, candidates, opts)` — alias arm (`resolveAliases`, caught per-arm for pre-v110 brains) + exact title/slug-suffix arm (real slugs are namespaced `people/x` but `slugify` drops the prefix) + two lexical identity arms behind `opts.lexicalArms` (kill switch: config `retrieval_reflex_lexical_arms` / env `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`, default on): weak lowercase candidates probe the ALIAS arm ONLY (never title/slug-suffix, where ordinary lowercase words would fabricate pointers) and require GLOBAL uniqueness across all sources in play; the surname arm resolves a strong single capitalized token ≥3 chars via a `lower(title) LIKE '% <token>'` predicate on the same query, with exact-arm precedence and ambiguity counted over ALL person rows carrying the surname — ambiguity in either arm injects nothing; pointers carry `source_id`/`arm`/`confidence`/`matchedNorm` (`ARM_CONFIDENCE` alias 0.9 / title 0.8 / title-surname 0.72 (deliberately above the volunteer layer's 0.70 gate, below title) / slug-suffix 0.6 lives next to the arm definitions; arm-2 provenance classified in JS since the combined OR can't report which predicate matched); opts: `sourceIds?` federated scope (alias arm loops per source, arm 2 uses `source_id = ANY`), `suppression?` ('slug-and-title' default; 'slug-only' REQUIRED under windowing — the title rule would suppress every entity merely mentioned in a prior window turn), ambient-channel event logging is DELIVERY-side, not in-resolver — `logDeliveredReflexPointers(engine, pointers)` fires only once a block is actually handed to the consumer (serve's resolve-IPC `onDelivered` hook post-write; `buildReflexAddition` post-timeout on the direct rung), so abandoned/timed-out blocks never pollute the volunteered-vs-used stats; its event write is registered synchronously before return so the CLI background-work drain cannot miss it; synopsis runs through `stripTakesFence`/`stripFactsFence` (the same privacy boundary `get_page` applies) so private facts never reach the prompt; `visibility: private` (and derived-private) pages never resolve on any arm unless the caller passes `excludePrivate: false` (default true, the caller's read policy `privatePagesFilterForCaller`, the predicate get_page uses, so a bound member resolves the pages its readers allow; only `volunteer_context` widens, via `resolveExcludePrivatePages` for a trusted local caller — gbrain-evals N8-1/N8-2, pinned by `test/reflex-private-visibility.test.ts`); capped at `MAX_POINTERS`. `reflex.ts`: the orchestrator + engine-aware resolver ladder (host `resolveEntities` → PGLite serve IPC → Postgres cached process-singleton → disabled), zero-candidate fast path, fail-open + timeout, heartbeat write for the doctor check, `reflexEnabled(cfg)` (file/env gate, default ON; DB-plane does NOT gate — `assemble()` is sync); windowed extraction when `windowTurns` present and `retrieval_reflex_window_turns` (default 4; 1 = single-turn behavior) > 1 — switches suppression to slug-only; accept-side reflex-channel logging fires after the per-turn timeout admits the block (direct-Postgres rung only — IPC logs server-side at delivery; host-injected resolvers are a documented gap). `resolve-ipc.ts`: local unix-socket resolve protocol (client + server) so PGLite resolves through the single connection `gbrain serve` holds (a second opener would hit the exclusive lock; a subprocess would force-steal it past the 5-min staleness window and crash). Wired into both serve transports via `src/mcp/resolve-ipc-binding.ts` (engine-uniform; socket + secret keyed off `hash12(database_url)` under `~/.gbrain/run`, cleaned up on shutdown). A lean read-only Postgres serve binds the `read` socket kind instead (#7612); `hookResolveSocketForConfig` falls back to it after the source socket, and a `delegation: true` caller never targets it. Doctor surface: `retrieval_reflex_health` in `src/commands/doctor/checks/verbs-reflex.ts` (reads the heartbeat for truthful runtime status; categorized in `doctor-categories.ts`) + `volunteer_channels` (engine-aware sibling: groups `context_volunteer_events` by channel over 7 days so operators see which push channels — reflex/op/watch/claude-code/codex — actually fire; info-only; the LOCAL doctor runs it brain-wide while the remote report path threads the caller's source scope, so a source-bound token never sees other sources' activity counts/timestamps; counts are reconciled against the hook heartbeat over the same 7-day window — a mostly-degraded week gets a CAUTION note, since a server-side delivery count isn't proof of injection; quiet-channel guidance is engine-aware — Postgres brains are told the hook lane is quiet by design rather than to chase registration — and walks both quiet classes (installed-but-unregistered vs registered-but-quiet; the check can't inspect registration itself); pre-v117 tolerant, and transient DB errors are reported as such, never as an old schema; pinned by `test/doctor-volunteer-channels.test.ts`). Config: `retrieval_reflex` + `retrieval_reflex_max_pointers` + `retrieval_reflex_window_turns` + `retrieval_reflex_lexical_arms` in `src/core/config.ts` (env `GBRAIN_RETRIEVAL_REFLEX_WINDOW_TURNS`, `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`). `volunteer.ts`: `parseWindow` (lenient `user:`/`assistant:` prefixes, unprefixed → one user turn), `volunteerContext` (extract → resolve → +0.05 multi-turn/newest-turn boost → `min_confidence` 0.7 gate → cap 3/5; deterministic rationale strings, never raw conversation text; slug-only suppression), `volunteerUsageStats` (per-arm/channel precision from the `pages.last_retrieved_at > volunteered_at` join — APPROXIMATE: the 5-min last-retrieved throttle causes false negatives, unrelated reads false positives). `volunteer-events.ts`: `insertVolunteerEvents` (ONE multi-row parameterized INSERT that keeps only rows whose page still exists, probed under the page row's key-share lock, so a late write never restores a purged page; #9068), `logVolunteerEventsFireAndForget` + bounded drain registered as the `volunteer-events` background-work sink (order 4), `purgeStaleVolunteerEvents` (90-day GC, called from the dream cycle's purge phase). Policy layer ships as the `retrieval-reflex` recipe (`recipes/retrieval-reflex/`). Pinned by `test/context/entity-salience.test.ts`, `test/retrieval-reflex.test.ts`, `test/retrieval-reflex-pre-v110.test.ts`, `test/context/resolve-ipc.test.ts`, `test/doctor-retrieval-reflex.test.ts`, `test/volunteer-context.test.ts`, `test/e2e/volunteer-context-postgres.test.ts`. Checkpoint-compaction modules in this dir: `corpus-segments.ts` — engine-free content-addressed compaction segments (`<session>.seg-<hash24>.txt`, idempotent by name; parsers accept 12–64 hex), the hash-keyed per-session ledger (atomic tmp+rename, fail-open, entry order = the only ordinal), `sliceBoundaryWindow`/`splitByBoundaries`, the redacted `renderSegmentText` (a segment is NEVER written unscanned — unlike the session-end full write, which degrades-and-writes), exact-set `coverageComplete`/`decideCorpusMode` (count equality can be fooled by a duplicated boundary), the compact-time `bankCompactSegment` step (per-step deadline degrades, segment-then-ledger crash order), the openclaw tail boundary reader (`readOpenclawBoundaryTail`, delegates mapping to the adapter's exported `mapOpenclawLine`; also returns turn-stamped `toolCalls`/`toolCallTurnIndexes` for the Memorable receipt — name-only v1, `input: null` by design until an observation run characterizes OpenClaw's args field), and orphan-sidecar/aged-ledger GC — pinned by `test/corpus-segments.test.ts`. `checkpoint-harvest.ts` — the serve-side prompt harvest of a segment: bounded FIFO (cap 8, 60s abort), sweep-shared claim fencing, capability-then-kill-switch gates, `signal.aborted` POST-check (the pipeline returns partials on abort; an aborted run writes nothing and stays retryable), receipt sidecar before idempotent manifest publish (source-scoped `getPage` verification — a link that resolves to nothing is never banked), `.ingested` last, explicit `shutdownCheckpointHarvest()` called by serve BEFORE `engine.disconnect()` (the background-work drain is CLI-exit-only by contract), a writeback turn whose facts preflight finds the canonical writer busy (`writer_lock_unavailable`, before any model call) re-queued after 5, 15 and 45 s (`writer_busy_requeued`; the retry skips admission, a pending retry dedups a re-schedule as `already_queued`, shutdown clears pending retries) while a compact segment's busy refusal stays an error the sweep resumes, and error reasons that keep the error's code or `reason` within the 48-char reason-code shape (`operationerror:writer_lock_unavailable`), the first failure of each reason logged to stderr once per serve run — pinned by `test/checkpoint-harvest.serial.test.ts`. `hook-heartbeat.ts` — the hooks telemetry JSONL extracted from hook.ts (hook.ts re-exports; serve-side writers never import the command module); allowlist carries the checkpoint `segment`/`inserted`/`duplicate`/`links` count-only fields. `session-state.ts` also carries the v132 `checkpoint_manifest` helpers (`getCheckpointManifest`/`appendCheckpointManifest`: newest-first, dedup-by-slug, cap 20, seg-hash completion key, fail-open on pre-v132 schema) — pinned by `test/checkpoint-manifest.test.ts`. `sensitivity-scan.ts` + `compile-view.ts` — the compile-context stack: composed detector (secret-scan + ordered `PII_PATTERNS` + path/blocklist families + operator pattern file; uniform `.gbrain-scan-allow` fingerprint escape hatch; CONTENT hits drop an entry, CONFIG/loader failures THROW so the caller aborts without writing) and the deterministic compiled-view builder (recency decay anchored to the newest candidate `updated_at`, never wall-clock; total-order (score desc, slug asc); source-scoped listPages/getPage reads that skip op-layer write-backs and pass `excludePrivate: true` on every arm, so private pages never reach the compiled file; whole-file `packToBudget` math that never passes a <=0 budget) — pinned by `test/sensitivity-scan.test.ts` + `test/compile-view.test.ts` + `test/e2e/compile-context-pglite.test.ts`; the CLI shell is `src/commands/compile-context.ts` (targets claude-code|codex|openclaw, AGENTS.md managed-marker splice that throws on damaged markers, atomic writes, `--check` recompile-and-compare exit codes; the guide is `docs/guides/checkpoint-compaction.md`). It also owns the whole Memorable seam's engine-free plumbing: the session-receipt JSONL (`session-receipts.jsonl`, `appendSessionReceipt` — dedup by post-redaction `content_hash` so a resumed session neither duplicates its receipt nor re-fires the relay; tail-rewrite compaction triggered by the 32 MB byte ceiling alone — the read fires exactly when the pass will act, with the 2000-line budget enforced inside the pass — and a `skipCompaction` seam the openclaw compact() lane sets unconditionally: the hook lane is the ONE receipts compactor, so two processes can never race the read-filter-rename rewrite); ONE bounded adaptive `readJsonlTail` reader shared by `lastReceiptMatches`, `lastRelayResult` and `readSessionReceiptsTail` (a receipt line can exceed the 1 MB window — the window doubles rather than reading "empty"); `maybeTrimRelayResults` (BOTH capture lanes trim the child-appended `memorable-relay.jsonl` — an openclaw-only host has no hook lane, and converging newest-keeping trims make concurrent trims safe: mtime-stale preferred, hard 8 MB force backstop, line-boundary cut keeping the newest lines — the child appends open-by-path, so the residual loss window is one in-flight write); the CONSENT STAMP (`memorable-consent.json`, 0600, written ONLY by config-set's disclosure flow — deliberately outside config.json, which the external CLI full-file-rewrites; scope-bound to the disclosure sha256 + `MEMORABLE_CAPTURE_HARNESSES`, so widening the capture surface invalidates old stamps); `memorableGateAllowed(cfg)` ({allowed, reason: kill_switch|disabled|disclosure_missing} — one reason vocabulary for hook, context-engine and doctor); `memorableConsentEvidence()` (the CLI-side opt-in read fail-closed from ~/.memorable/config.json, dated provisional spec note, GBRAIN_MEMORABLE_CONFIG test seam); `redactedToolCallsJson` (the security-load-bearing span-filter + highEntropy redaction, ONE implementation for both capture lanes; string LEAVES are redacted raw before serialization — scanning the serialized JSON would let quoted secrets through via \" escaping — with a post-serialization re-scan as belt-and-braces); `recordAndRelayReceipt` (per-receipt harness scope-binding first — a harness outside `MEMORABLE_CAPTURE_HARNESSES` is refused with `memorable_harness_undisclosed` → receipt → prior-run outcome surfacing with the child's reason clamped via the shared `clampRelayCause` (32 chars, so the 16-char prefix keeps composites inside the 48-char reason bound) and appended LAST → consent evidence → `resolveMemorableBin` → detached spawn; never throws; `spawnFn` test seam); and `priorRelayFailure`, which surfaces the PREVIOUS relay run's self-reported exit status so a relay that records nothing is never reported healthy. `resolveMemorableBin` does the pre-spawn PATH/`MEMORABLE_BIN` resolution so a missing CLI is a named heartbeat reason rather than a silent async ENOENT. #6195: `entity-salience.extractCandidates` also emits lowercase 2-3-word weak n-grams (`multiToken`, own budget `MAX_WEAK_NGRAM_CANDIDATES` = 16, never across punctuation, never all stopwords/common words) that ride the exact weak-alias fold, and `retrieval-reflex` arm 2.6 (`weak-title`, 0.72, behind `lexicalArms`, private pages hidden by default) matches them to the exact title of a person/company/organization page whose title is globally unique; single lowercase words stay alias-only.
- `src/core/context/hook-heartbeat.ts` — the hooks telemetry plane under `<gbrain home>/integrations/hooks/` (`heartbeat.jsonl`, `status.json`, session receipts, the memorable relay log; directories 0700, appends 0600). Entries hold counters, durations and codes only: `HEARTBEAT_ALLOWED_KEYS` is the full key allowlist CI greps the fixture against, and includes `pattern` (scanner pattern name), `fingerprint` (`sha256:<16 hex>`) and `hint` (fixed text) for refusals. `near_duplicate` is the shadow count on the `writeback_dedup` event that `facts/capture-dedup.ts` appends (lane in `reason`, exact drops in `duplicate`). `relayRefusalHeartbeat(hit)` builds the line `context-engine.ts` writes when its high-entropy re-scan refuses a memorable relay (`event: relay`, `outcome: degraded`, `reason: secret_scan_refused`); the receipt and relay are skipped for that compaction window and the checkpoint is kept. `memorableGateAllowed` gates the relay lane; span redaction runs `redactFindings` with `highEntropy: true`. Tests: `test/context-engine-checkpoint.serial.test.ts`.
- `src/core/context/seat.ts` — seat identity for captured sessions (#4618), engine-free. `resolveSeat` returns the lowercased `GBRAIN_SEAT` label when it matches `SEAT_LABEL_RE` (`^[a-z0-9][a-z0-9._-]{0,63}$`), else `home-<8 hex>` over the realpath of the harness home (Claude Code: the directory holding `projects/` in the transcript path, then `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `~/.claude`; codex: `CODEX_HOME` or `~/.codex`; OpenClaw: the agent directory holding `sessions/`), so no raw path reaches frontmatter; `GBRAIN_SEAT=off` (the opt-out) resolves to null and nothing is recorded. `writeSeatSidecar` writes `<sessionId>.seat.json` (`{version: 1, seat, seat_source, hook_lane, harness, first_seen}`, 0600, tmp+rename) unless one exists, reporting `seat_conflict` when the existing seat differs; `readSeatSidecar` accepts only a valid v1 record. `SEAT_REASON_HINTS` holds the fixed heartbeat hints. The sidecar name and its GC live in `corpus-segments.ts` (`seatFileName`, `SEAT_SIDECAR_SUFFIX`).
-- `src/core/context/session-speaker.ts` — who wrote a captured session's user turns (#8064), engine-free. `resolveSessionSpeaker` reads `GBRAIN_SESSION_AGENT` (a label: agent; `off`: skip banking; `owner`: no detection; invalid: agent `agent`), else `detectAgentLaunched` over `readProcessAncestry` (Linux /proc, else `ps`; 12 levels, 300 ms): the nearest claude/codex process runs headless (`-p`/`--print`, `exec`) and another claude/codex process is an ancestor, principal `agent-launched`. `bankAsSpeaker` writes `<sessionId>.speaker.json` (`{version: 1, principal, source, harness, first_seen}`, 0600, first write wins) before the hook's compact, stop and session-end banking; a write failure banks nothing (`speaker_write_failed`), `off` records `capture_opt_out`. `corpusFileSpeaker`/`speakerOf` give the capture lanes (checkpoint-harvest, sweep) the `speaker` they pass to `runFactsPipeline`, which saves user and unattributed claims as `other` (`asAgentSpoken`), adds `speakerContextNote` to the context (`facts/speaker-context.ts`, also used by the managed facts batch) and names the agent in the extractor prompt. Name and GC: `speakerFileName`, `SPEAKER_SIDECAR_SUFFIX` in `corpus-segments.ts`. Pinned by `test/agent-session-speaker-8064.serial.test.ts`.
+- `src/core/context/session-speaker.ts` — who wrote a captured session's user turns (#8064), engine-free. `resolveSessionSpeaker` reads `GBRAIN_SESSION_AGENT` (a label: agent; `off`: skip banking; `owner`: the owner, detection only noted as `speaker_owner_override_detected` by `hookSpeakerDecision`; invalid: agent `agent`), else `detectAgentLaunched` over `readProcessAncestry` (Linux /proc, else `ps`; 12 levels, 300 ms): the nearest claude/codex process runs headless (`-p`/`--print`, `exec`) and another claude/codex process is an ancestor, principal `agent-launched`. `bankAsSpeaker` writes `<sessionId>.speaker.json` (`{version: 1, principal, source, harness, first_seen}`, 0600, first write wins; a differing speaker notes `speaker_mismatch`, and an agent in a session already banked without one banks nothing, `speaker_mismatch`) before the hook's compact, stop and session-end banking; a write failure banks nothing (`speaker_write_failed`), `off` records `capture_opt_out`. `corpusFileSpeaker`/`speakerOf` give the capture lanes (checkpoint-harvest, sweep) the `speaker` they pass to `runFactsPipeline`, which saves user and unattributed claims as `other` (`asAgentSpoken`), adds `speakerContextNote` to the context (`facts/speaker-context.ts`, also used by the managed facts batch) and names the agent in the extractor prompt. Name and GC: `speakerFileName`, `SPEAKER_SIDECAR_SUFFIX` in `corpus-segments.ts`. Pinned by `test/agent-session-speaker-8064.serial.test.ts`.
- `src/core/context/ipc-path.ts` — engine-free local socket discovery and private Unix fallback when the complete role-specific address exceeds 103 UTF8 bytes. Hashes the physical parent plus basename under a fixed OS temporary root, verifies ownership/0700 directory/0600 client socket without following fallback symlinks, and retains a native binding claim through actual server close. Existing Unix socket accessibility is rechecked even when a runtime reports ENOENT; permission/resource probe failures never authorize stale takeover; on Windows a PGLite data-dir socket (`.gbrain-<kind>.sock`) over afunix's 107 UTF-8 bytes moves to `%USERPROFILE%\.gbrain\run\<kind>-<hash12(canonical data dir, case-folded)>.sock` (`windowsLocalIpcSocketPath`, the Postgres run-dir scheme; the secret stays in the data dir), and `localIpcPathTooLong` reports a resolved path still over the platform budget, which `ipc-path-too-long.ts` turns into the typed `ipc_path_too_long` serve log line and doctor `ipc_socket_path` warning (#6573; `test/ipc-path-windows-fallback-6573.test.ts` on every OS, the native bind and 20-cycle stability probe in `test/windows-ipc-long-path-6573.serial.test.ts` on windows-latest); Windows named pipes retain a native Global mutex through actual close; `windows-ipc.ts` normalizes namespace prefixes while native Windows Unicode casing defines the mutex identity. `test/local-ipc-path.test.ts` covers concurrent real processes, SIGKILL recovery, active-connection shutdown, aliases and unsafe paths. The published CLI smoke also uses a long Unicode datastore path.
- `src/core/entities/near-name.ts` — Flag-only near-name matcher for #2942 (never merges, never writes `entity_identities`; `entity-identity.ts` stays manual-only). `classifyNearName` returns `same` (normalized-equal after corporate suffixes, or a strong `name-variants.ts` shape), `typo` (Damerau distance 1 on 3–64 normalized characters) or `acronym` (one word equals a multi-word name's initials, at most one letter different). Candidates come from symmetric one-deletion keys plus initials keys, so recall is complete for those kinds; past `NEAR_NAME_MAX_KEYS_PER_SHARD` the index splits into shards by key hash (a pair shares a key, so it lands whole in one shard). `loadEntityNames` reads one source's fact-entity pages plus the source pack's linkable types, leaving out private pages for callers that exclude them. Pinned by `test/review-lists.test.ts`.
diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.md
index 2aebe0b84b..b7f65c7226 100644
--- a/docs/architecture/key-files/files-and-sync-1.md
+++ b/docs/architecture/key-files/files-and-sync-1.md
@@ -51,7 +51,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/source-resolver.ts` — 6-tier source resolution. `resolveSourceWithTier(engine, explicit, cwd)` returns `{ source_id, tier: SourceTier, detail? }` alongside `resolveSourceId()` (unchanged). `SOURCE_TIER_NAMES = ['flag', 'env', 'dotfile', 'local_path', 'sole_non_default', 'brain_default', 'seed_default']` (7 entries; order matches priority). Tier `sole_non_default` slots between `local_path` and `brain_default`: when NO `sources.default` config is set AND exactly one registered source has `local_path` AND isn't `'default'` AND the `'default'` source holds no active pages (the emptiness guard — the tier's charter is rescuing brains whose `'default'` is empty; when `'default'` carries an established corpus, auto-routing would hijack every bare write into the side-source, so the resolver falls through to `seed_default` and prints a one-line stderr notice naming both sides so the suppressed flip is diagnosable, same `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1` suppression knob as the routing nudge; a failed pages probe on an exotic/legacy schema keeps the auto-route), auto-route to it; archived sources excluded (try/catch for pre-v34 brains); private `pickSoleNonDefaultSource(engine)` shared by both resolver entry points so they cannot drift. Exported `formatSoleNonDefaultNudge(sourceId): string | null` builds the user-facing stderr nudge (null when `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1`). `resolveCliSyncSource` in `src/commands/sync/run.ts` calls `resolveSourceWithTier` unconditionally so the tier fires; `src/commands/import.ts:96-128` mirrors with the tier-gated nudge. Consumed by `gbrain sources current`, `import --source-id`, `extract --source-id`, and the `source_routing_health` doctor check. Pinned by `test/source-resolver-with-tier.test.ts` (`withEnv()` per test-isolation lint), `test/source-resolver-sole-non-default.test.ts` (20 cases incl. both-ways emptiness-guard + probe-failure fallback), `test/sync-sole-non-default-routing.test.ts` (3 PGLite cases driving real `runSync`), `test/pages-source-scoping-4329.test.ts` (real-engine both-ways guard coverage). Also exports `noGrantFederatedScope(engine, hasSourceGrant, sourceId)`, the widening decision transports share: returns `localFederatedSourceIds(..., 'seed_default')` ONLY when `hasSourceGrant === false` (the legacy-bearer no-grant floor), `undefined` for a granted token, for an OAuth client (flag `undefined` — a falsy gate here would widen every OAuth client), and when the resolver throws (best-effort; the scalar scope stands rather than failing the request). Called by `src/commands/serve-http.ts`; pinned by `test/no-grant-federated-scope.test.ts` (6 cases). `explicitReadBinding(engine, sourceId, tier)` (#5081) is the explicit-tier twin used by the stdio transport for `GBRAIN_SOURCE` (`env`) and `.gbrain-source` (`dotfile`) bindings: `{ sourceId, via, sourceIds, optedOut }`, where `sourceIds` is the same set `localFederatedSourceIds` computes (shared `federatedSetFor`, so an isolated anchor admits only itself) and `optedOut` lists `federated === false` sources for the denial hint; `undefined` for every other tier. Pinned by `test/explicit-read-admission-5081.test.ts`. Unscoped default-write guard family (the `seed_default` tier is the only one that actually lands a write in `'default'`): `assessDefaultWriteGuard(engine)` → `DefaultWriteAssessment { shouldGuard, defaultPages, nonDefaultPages, nonDefaultSources, failed? }` — an unindexed full-`pages` aggregate; `shouldGuard` when ≥1 non-default source holds pages AND non-default pages outnumber default's; a query failure returns the fail-open no-guard verdict stamped `failed: true`, which cachers/latchers must not treat as settled. `assessDefaultWriteGuardOnce(engine)` is the per-engine WeakMap memo (arms on the first SUCCESSFUL assessment whatever its verdict, forgets a failed attempt so the next caller retries, coalesces concurrent callers; `__resetDefaultWriteGuardMemo` is the test seam). `assessUnscopedDefaultWrite(engine, tier, mutating)` → `{ warning, assessed }` (`assessed: false` only when the aggregate failed); `formatDefaultWriteWarning(a, sourceFlag?)` / `formatDefaultWriteRefusal(cmd, a)` render the two surfaces; `defaultWriteAllowedByEnv()` is the `GBRAIN_ALLOW_DEFAULT_WRITE=1` escape hatch. Consumers: `sync` refuses (dry-run warns), `import` warns via the memo, MCP stdio's `createDefaultWriteAdvisory` prints once. Also exports `isResolverUserError(e)` — the ONE predicate for this module's user-facing throws (`Source "…" not found.` / `not found or is archived.`, `Invalid --source value`, `Invalid GBRAIN_SOURCE value`), consumed by dream.ts, agent.ts and code-scope.ts so a CLI command turns an unknown/archived source into a clean stderr line + exit 1 while anything else keeps propagating. A request snapshot serves tiers 4, 5.5 (its rows carry the 'default' emptiness probe, `default_has_pages`), `assertSourceExists` and the federated set from one sources read, sent with the config table (`resolveSourceWithTier` reads tier 5's key beside the tier-4 listing) (GBRA-156).
-- `src/core/source-delete.ts` — `deleteSourceRow`: every unmanaged source delete (`sources remove`/`purge`, `sources_remove`, expired-archive purge) deletes the `sources` row, that incarnation's `persistence_source_bindings` row and its `managed-sync` cursors in `op_checkpoints` (#8741) in one statement (neither has an FK to `sources`). #9068: that statement also runs `removedSourceScrubCtes` (the managed `remove`/`purge` in `source-lifecycle.ts` runs them in its final transaction too), which delete the source's `retrieval_event_pages`, `retrieval_event_links`, `retrieval_feedback` and `context_volunteer_events` rows and strip from `eval_candidates.retrieved_slugs` each slug no other source the candidate covers has a page for (`retrieval_weights` and `mention_gazetteer_entries` cascade from `sources`); a second statement runs them again, for a feedback write or capture that held a page row while the delete waited, unless a source with the same id exists again (so a re-created source keeps its rows). Pinned by `test/purge-scrub-followups-9068.test.ts`. Other incarnations' bindings go to `gbrain repair orphan-bindings` (`src/core/persistence/orphan-bindings.ts`, doctor `orphan_persistence_bindings`). The unmanaged claim check (`sync-authority.ts`) and doctor `unbound_source` count only the current incarnation's binding. `EXPIRED_ARCHIVE_SQL` is the one purge-eligibility predicate (unmanaged sweep, its per-row DELETE and the managed `expiredOnly` purge): both archive timestamps must be later than the epoch and the expiry past; `UNVERIFIED_ARCHIVE_SQL` lists archived rows with a missing or epoch timestamp, which the sweep reports blocked with restore-then-archive guidance, never purged.
+- `src/core/source-delete.ts` — `deleteSourceRow`: every unmanaged source delete (`sources remove`/`purge`, `sources_remove`, expired-archive purge) deletes the `sources` row, that incarnation's `persistence_source_bindings` row and its `managed-sync` cursors in `op_checkpoints` (#8741) in one statement (neither has an FK to `sources`). #9068: that statement also runs `removedSourceScrubCtes` (the managed `remove`/`purge` in `source-lifecycle.ts` runs them in its final transaction too), which delete the source's `retrieval_event_pages`, `retrieval_event_links`, `retrieval_feedback` and `context_volunteer_events` rows and strip from `eval_candidates.retrieved_slugs` each slug no other source the candidate covers has a page for (`retrieval_weights` and `mention_gazetteer_entries` cascade from `sources`); a second statement runs them again, for a feedback write or capture that held a page row while the delete waited, unless a source with the same id exists again (so a re-created source keeps its rows). Pinned by `test/purge-scrub-followups-9068.test.ts`. Other incarnations' bindings go to `gbrain repair orphan-bindings` (`src/core/persistence/orphan-bindings.ts`, doctor `orphan_persistence_bindings`). The unmanaged claim check (`sync-authority.ts`) and doctor `unbound_source` count only the current incarnation's binding. `EXPIRED_ARCHIVE_SQL` is the one purge-eligibility predicate (unmanaged sweep, its per-row DELETE and the managed `expiredOnly` purge): both archive timestamps must be later than the epoch and the expiry past; `UNVERIFIED_ARCHIVE_SQL` lists archived rows with a missing or epoch timestamp, which the sweep reports blocked with restore-then-archive guidance, never purged. A source that still has pages is deleted only when the pages -> sources ON DELETE CASCADE fires on this brain (the same statement checks the foreign key and its delete trigger); otherwise nothing is deleted and `source_pages_remain` is thrown (#7072, `test/source-purge-stranded-pages-7072.test.ts`); the expired-archive sweep reports the source in `blocked` with that code. The managed remove and purge delete the pages themselves in bounded batches first (#7702/#8905).
- `src/core/sources-ops.ts` — Multi-source registration + clone-lifecycle ops (`addSource`, `recloneIfMissing`, `defaultCloneDir`, `isOwnedClone`, `unownedHint`). **Reclone-ownership invariant (must-never-violate): gbrain may only delete/re-clone a clone it created, NEVER a user working tree.** `recloneIfMissing` deletes `local_path`, so it gates on `isOwnedClone(src)` and throws a `SourceOpError('unmanaged_path', ...)` BEFORE any filesystem op when ownership is unprovable — fail-closed. Ownership is proven by `config.managed_clone === true` (written by `addSource`'s `--url` path, covering default-location and `--clone-dir` clones) OR `local_path === defaultCloneDir(id)` (back-compat for pre-marker clones, via exact normalized-path equality, symlink-free). A row with `remote_url` + an unowned `local_path` (a user-registered working tree, e.g. `sources add --path`) is refused untouched; re-add with `--url` to regain auto-reclone. The reclone is EXDEV-safe: clone into a SIBLING temp of `local_path` (not the shared `clones/.tmp`, which may sit on a different mount than a `--clone-dir` target), then swap (move old aside → move new in → drop old) so `local_path` is never left missing-and-unrecoverable; on swap failure the original is restored, and if restore fails the error names the `aside` path so it's never reflexively deleted. A TOCTOU re-check re-confirms ownership immediately before the destructive move and rejects a symlink leaf swapped in after the entry check (`symlink_escape`). `unownedHint(src, state)` is the shared recovery message used by both the core error and the `gbrain sync --source` CLI error; `gbrain sources restore` special-cases `unmanaged_path` to print "DB row restored; gbrain syncs this path read-only" instead of the misleading "try sync to recover" guidance. `SourceOpErrorCode` includes `unmanaged_path`. Pinned by `test/sources-ops.test.ts`, `test/sources-resync-recovery.test.ts`. `assertNoOverlappingPath(engine, id, path)` is the ONE overlapping-path guard shared by every surface that binds a `local_path` (`addSource`, `gbrain sources set-path`): a path equal to, nested inside, or enclosing another source's `local_path` throws `SourceOpError('overlapping_path')` — overlapping trees make sync/write-through attribute files to the wrong source, so no add or repair path may skip it. The guard compares by spelling AND by realpath (both the candidate and each sibling `local_path` are `realpathSync`'d when they exist, fail-open to the spelling otherwise), so a symlink resolving into or over another source's tree cannot slip past it; the stored pointer and the error message keep the operator's spelling. #6946: `isOwnedClone`/`defaultCloneDir` live in `src/core/url-clone.ts`, re-exported here.
- `src/core/sync-cost-gate.ts` + `sync-git.ts` + `sync-anchor.ts` + `sync-lock.ts` + `sync-reconcile.ts` + `sync-status-report.ts` — six pure-function clusters behind the `src/commands/sync.ts` façade, which re-exports them; `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps exactly these six (NOT the other `sync-*` siblings, which are ordinary deps) on the sync command's flag-scan surface. `sync-cost-gate.ts`: the inline-embed cost gate + token estimation for `gbrain sync`. `sync-git.ts`: git plumbing — invocation building, repo discovery, baseline-commit self-heal, path-containment guards, OS-relative paths normalized to Git slash form by `gitRelativePath`, and the delete/rename slug resolvers (`resolveSlugByPathOrSourcePath` — see its dedicated entry above — plus the verified `resolveSlugsForRemovedPaths`/`resolveRemovedPathSlug`). `sync-anchor.ts`: sync anchor + chunker-version state helpers (source-scoped vs legacy global-config storage). `sync-lock.ts`: the lock layer — typed lock-busy error, the rich busy message, `--break-lock` handling, the partial-result envelope (`performSync` itself stays in the façade). `sync-reconcile.ts`: full-sync reconcile planning (the mass-delete valve and ever-committed gate), with stored paths normalized before scope filtering, plus sync deadline/stall resolution (the default and env deadlines are progress-aware; `syncWatchdogPlan` and `syncDeadlineStopNotice` build the watchdog options and its stdout stop notice — see the `process-watchdog.ts` entry). `sync-status-report.ts`: the per-source sync status report backing `gbrain sources status` and the `get_status_snapshot` op. Its queue context is engine-aware: only an explicitly worker-backed surface may promise job deferral; otherwise non-interactive cost deferral returns `manual_drain_required` with exact per-source `gbrain embed --stale --source <id>` commands and never writes or claims an embed-backfill row. GBRA-133 2b.3: a `--no-pull` estimate (`estimateInlineNewTokens` / `CostGateContext.noPull`) prices local HEAD and never fetches origin. `sync-git.ts` adds `gitAsync` / `discoverGitRootAsync` / `isDetachedHeadAsync`, which classic sync preflight, finalize, the lossless delta, upstream observation and the source filesystem lock now use, so a resident sync spawns no synchronous Git.
diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.md
index 94dd1b4769..4a8073cf5b 100644
--- a/docs/architecture/key-files/managed-sync-bookkeeping.md
+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md
@@ -35,7 +35,7 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The
- `src/core/persistence/sync-cursor-moves.ts` — #6712 (L2, one page, one fate): the managed-sync cursor's pure transitions, peeled out of `sync-run.ts`; each returns the next cursor and writes nothing (sync-run.ts saves it with one compare-and-swap). `advanceHeld`/`settledPast` pass an entry without a commit (held, waived via `waivedCursor`, an idempotent deletion via `deletionSettled`) and add its index to the settled ranges the checkpoint skips; a deferred entry (`Cursor.deferred`, a `source_changed` file retried after the manifest end) leaves the deferred list instead of moving the index. `promoteWindow` makes the window's first group the cursor's group once the cursor reaches it, so requests admitted after a failed or held entry are read by their own receipts, never frozen again; `committedPast` does the same after a commit. `withHeldKeys` records a held entry's page keys (`dependencyKeys`) so a later entry of the run that shares one is held behind it (`blocked_on`).
- `src/core/persistence/sync-stop-class.ts` — #6712 (L2; #6565): how the settle path in `sync-run.ts` classifies a page request that ended without committing. `receiptClass` reads the terminal classifier: `transport` (a dropped connection or a retryable refusal, re-frozen in place), `page` (held, deferred or blocked under the hold policy) or `systemic` (the run stops with the classifier's action). `resumableStop` is a systemic stop the fault table retries (an unrecognised P0001 or a 55000 surfacing as `storage_error`); `stopRecorded` says an earlier invocation already stopped this run (its failure ledger row carries the run id), so the next plain sync re-freezes every page that refusal failed, bounded by `STOPS_PER_ENTRY`. #6712 PR 3 (L7): `recordedStop` also returns the row's `gbrain_version`. `retryRecordedFailure` in `sync-run.ts` (what `--retry-failed`, now its deprecated alias, did on request) retries every recorded failure on the next plain sync, except a refusal nothing changed since the same version recorded it (`replaysUnchangedRefusal`: a content refusal while the file has its frozen bytes; a `source_changed` pinned import while HEAD is the run's target and the file still holds the working-tree bytes that refused, compared by hash rather than by mtime), a slug-mode refusal and a checkpoint whose source's `last_commit` moved (#6834), which wait for a changed file or `gbrain repair managed-sync-orphans`.
- `src/core/persistence/sync-knock-on.ts` — #6643, shrunk by #6712 (one page, one fate): no producer is left. It keeps the legacy predicate over receipts older builds wrote (`error_detail` `{ origin: 'sync_knock_on', reason, root_request_id }`, or the pre-#6643 producers' exact messages, never an operator cancel): `isSyncKnockOn`/`syncKnockOnSql` (one predicate, never NULL) feed the terminal classifier, which renders such a receipt superseded, and `sync-run.ts` `refreezeInPlace`, which re-freezes the entry when a resumed cursor meets one (bounded by `STOPS_PER_ENTRY`, no config key). `cursorFenceCause` reads the two live causes of "cursor changed" (`run_replaced`, `outside_fence`; an older `window_dropped` still parses). `checkpoint-validation.ts` clause 3 skips converted receipts and the cursor's settled index ranges only; #6712 removed the knock-on exemption. `reviveCheckpoint` re-assesses a refused checkpoint at the cursor's end. `sync status` shows the cursor the recorded failure belongs to, `cursors`, and `checkpoint_blockers` (`listIncompleteSyncReceipts`, each with `knock_on`).
-- `src/core/persistence/terminal-classify.ts` — #6650: `classifyTerminal` turns one terminal receipt (`failed` / `conflict` / `cancelled`, or any row still holding `recovery`) into a `TerminalVerdict` (category, code, origin, class, `safe_actions`, `needs_human`, `defect`, `historical`, `root_request_id`, one structured `action`) at read time; nothing is persisted. A recovery record outranks the code (`recovery_pending` / `recovery_blocked`); a knock-on is read through `isSyncKnockOn` (typed marker survives compaction) or the SQL twin `terminalKnockOnSql`; `storage_error` and `source_changed` route by their recorded origin or cause, and a row whose code and origin do not say what happened is `diagnosis_required` (read-only writer status, never a guessed fix). A `source_changed` whose canonical file is missing is `canonical_file_missing` (a ghost page; its exit is the `gbrain repair ghost-pages` preview, never a sync retry), and an origin-less `fence_unrenderable` adoption refusal is its own defect category. A retryable sync fault's `action` follows its operation (`faultOperation`: a `put_page` under a `canonical_reconcile` or `managed_*` intent kind reads as that kind): `submit_job` and a canonical reconcile keep the sync retry, a caller-submitted page or memory write (`RESUBMITTED_WRITES`) gets the read-only writer-status inspect and a resubmit with a new request_id, a `managed_*` write the inspect and a rerun of its command, any other operation the inspect alone. `TERMINAL_FIXED_IN` names the release that fixed a category; a row whose build (`error_detail.attempt.consumer_version`, else `admitter_version`) is older is historical. It also owns the supersession rule `repair/failed-writes.ts` reuses (`supersessionSql`, `supersessionOrderSql`, `dispositionOf`, `PAGE_REMOVAL_OPERATIONS`). Tests: `test/terminal-failures-6650.test.ts` (TS↔SQL twin parity included), `test/terminal-classify-6696.test.ts`.
+- `src/core/persistence/terminal-classify.ts` — #6650: `classifyTerminal` turns one terminal receipt (`failed` / `conflict` / `cancelled`, or any row still holding `recovery`) into a `TerminalVerdict` (category, code, origin, class, `safe_actions`, `needs_human`, `defect`, `historical`, `root_request_id`, one structured `action`) at read time; nothing is persisted. A recovery record outranks the code (`recovery_pending` / `recovery_blocked`); a knock-on is read through `isSyncKnockOn` (typed marker survives compaction) or the SQL twin `terminalKnockOnSql`; `storage_error` and `source_changed` route by their recorded origin or cause, and a row whose code and origin do not say what happened is `diagnosis_required` (read-only writer status, never a guessed fix). A `source_changed` whose canonical file is missing is `canonical_file_missing` (a ghost page; its exit is the `gbrain repair ghost-pages` preview, never a sync retry), and an origin-less `fence_unrenderable` adoption refusal is its own defect category. A retryable sync fault's `action` follows its operation (`faultOperation`: a `put_page` under a `canonical_reconcile` or `managed_*` intent kind reads as that kind): `submit_job` and a canonical reconcile keep the sync retry, a caller-submitted page or memory write (`RESUBMITTED_WRITES`) gets the read-only writer-status inspect and a resubmit with a new request_id, a `managed_*` write the inspect and a rerun of its command, any other operation the inspect alone. `TERMINAL_FIXED_IN` names the release that fixed a category; a row whose build (`error_detail.attempt.consumer_version`, else `admitter_version`) is older is historical. `legacy_publication_refusal` and `retired_operation` (a `revision_conflict` with origin `grandfather_retired` or a `managed_grandfather` intent, #7837) are historical whatever build wrote them, since only a request an older build admitted produces them. It also owns the supersession rule `repair/failed-writes.ts` reuses (`supersessionSql`, `supersessionOrderSql`, `dispositionOf`, `PAGE_REMOVAL_OPERATIONS`). Tests: `test/terminal-failures-6650.test.ts` (TS↔SQL twin parity included), `test/terminal-classify-6696.test.ts`.
- `src/core/persistence/terminal-failures.ts` — #6650: the bounded readers over that classifier. `readTerminalFailureSummary` is one set-based aggregate (GROUPING SETS per source; `TERMINAL_STATEMENT_MS` 5 s statement and `TERMINAL_ACQUIRE_MS` 2 s connection deadlines; past either it returns `status: 'unknown'`, never an empty pile) splitting active blockers (recovery records plus the passed-in `checkpoint_blockers` of `sync-status.ts`, read by `readCheckpointBlockerMap`), unresolved rows (count, distinct slugs and intents, oldest age), historical rows (a later write superseded them, or older than `TERMINAL_FIXED_IN` via the SQL twin `TERMINAL_HISTORICAL_SQL`), 24 h and 7-day daily counts, categories and defect classes; archived sources are skipped. Thresholds `persistence.terminal_failures.window_days` (clamped to `persistence.receipt_retention_days`), `spike_factor`, `spike_min` (`readTerminalThresholds`, `validateTerminalConfigValue`, refused at `config set` by `commands/config/preparation-keys.ts`); `isSpike` against `sevenDayMedian`. `readTerminalFailures` is the drill-down (batches of 200, each selected before the supersession lateral join, which with the summary's probe tests the failed row's intent kind first so later large sync intents are not detoasted per row (#8729), at most 2,000 rows scanned per call, a sequence cursor, verdict filters, `--group-by category` groups, a `sync_fault` group also split by its operation, with an exact `drill_down` argv each; `--operation` filters on `faultOperation`). Consumers: doctor `persistence_terminal_failures` (`commands/doctor/checks/persistence-requests.ts`), `sync status` `terminal_failures` (`sync-status.ts`, `next` falls back to a recovery blocker's action), the `writer_failures` administration operation, and the admin `/metrics` gauges (`serve-http-metrics.ts` `renderTerminalFailureMetrics`, one aggregate per engine shared by scrapes for `TERMINAL_METRICS_TTL_MS` = 60 s via `cachedTerminalSummary`; never `/health`). Each source also reports `new_last_24h_older_builds` (rows and builds older than their class's fix), and doctor's spike message says an older write owner is producing them when they are most of the spike. Tests: `test/terminal-failures-6650.test.ts`, `test/sync-status-terminal-6650.test.ts`, `test/terminal-failure-metrics-6650.test.ts`, the CLI journey `test/agent-journey-terminal-failures-6650.test.ts`.
- `src/commands/sources-writer-failures.ts` — #6650: output of `gbrain sources writer failures <source> [--state all] [--group-by category] [--since Nd] [--limit N] [--before <cursor>] [--category|--code|--origin|--operation] [--json]`, dispatched by `persistence-admin.ts` as `writer_failures` (validated in `administration.ts` `writerFailuresQuery`, locally or through the resident owner). A table by default, one JSON document with `--json`; row and group `fix` / `inspect` actions are rendered for the CLI; a full page prints `truncated` with the exact next command. The operation is advertised to clients in the owner's `administration_extensions` (`ipc.ts`, `admin-contract.ts` `PERSISTENCE_ADMIN_EXTENSIONS`), never in the `administration` list an older client validates strictly, and `local-client.ts` delegates it only to an owner that lists it (`ownerAdministers`). Tests: `test/writer-failures-cli-6650.test.ts`.
- `src/core/persistence/public-category.ts` — #6712 PR 2 (L5): `publicCategory({ category?, code })`, the closed public vocabulary (`drift`, `conflict`, `content_refused`, `file_missing`, `permission`, `storage`, `config`, `superseded`, `transient`, `defect`) that sits beside the unchanged diagnosis `category`. `PUBLIC_BY_TERMINAL` maps every `TerminalCategory`, `PUBLIC_BY_CODE` every `SYNC_FAULT_TABLE` code (a new fault code needs a row: `test/public-category.test.ts`), and anything else goes by its registry class (unknown codes are `defect`). `classifyTerminal` carries it as `public_category`; `classifyRecordedFault` (terminal-classify.ts) reads a hold, a managed-sync failure row or a run stop as the failed receipt it stands for, so the receipt diagnosis, `managedWrite`, sync status holds and `last_error`, the terminal summary and doctor `sync_failures` (`details.failures`) render one verdict.
diff --git a/docs/guides/ambient-writeback.md b/docs/guides/ambient-writeback.md
index 0f704298bf..8f1be7da02 100644
--- a/docs/guides/ambient-writeback.md
+++ b/docs/guides/ambient-writeback.md
@@ -296,7 +296,7 @@ on the worker's process:
|---|---|
| `<label>` (a-z, 0-9, `.`, `_`, `-`, up to 64) | The session is saved. Claims from its user turns are saved as that agent's (`attributed_to: other`, context `speaker: agent <label>, not the owner`), never as yours. |
| `off` | Nothing from the session is saved. Context injection still runs. |
-| `owner` | The turns are yours; automatic detection is skipped. |
+| `owner` | The turns are yours. Detection still runs, only to report a session it finds agent-launched (heartbeat reason `speaker_owner_override_detected`), so an `owner` inherited by a worker is visible. |
| unset | Automatic detection, below. |
```bash
@@ -317,12 +317,19 @@ or a daemon running `claude -p`). For those the variable is the only signal,
so set it in any launcher you control.
The marker covers the Claude Code and Codex hook lanes and the facts they
-save. The OpenClaw context-engine lane and dream synthesis do not read it yet.
+save. The OpenClaw context engine marks a sub-agent session (session key
+`agent:<id>:subagent:<uuid>`) as agent `agent-launched`'s, since its user turns
+are the parent agent's brief. Dream synthesis reads the marker too and tells
+the model that the session's user turns are the agent's, never yours.
The marker is a `<session>.speaker.json` file beside the session's corpus
-files, written before any of them. If it cannot be written, nothing from the
-session is saved (heartbeat reason `speaker_write_failed`); `off` records
-`capture_opt_out`. Agent claims are never promoted into your own takes by
+files, written before any of them; the first record is kept. If it cannot be
+written, nothing from the session is saved (heartbeat reason
+`speaker_write_failed`); `off` records `capture_opt_out`. A resumed session
+whose speaker differs from the record (you resuming a worker's session, or
+another agent label) keeps the record and reports `speaker_mismatch`. An
+agent's `claude -p --continue` in a session already saved as yours saves
+nothing and reports `speaker_mismatch`, so your earlier turns stay yours. Agent claims are never promoted into your own takes by
the consolidate phase and are not linked to entity pages as your statements.
Facts saved as yours before this marker existed can be re-attributed:
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 7522623a64..2e27a2a319 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -5024,6 +5024,14 @@ More: [docs/guides/write-refusals.md#slug_page_mismatch](../../docs/guides/write
|---|---|---|---|---|---|---|
| A committed source and approved schema are required. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+### source_pages_remain
+
+<a id="source_pages_remain"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A source delete did not cascade to the source's pages, so it was rolled back and the source and its pages are unchanged. | Every source delete relies on the pages -> sources ON DELETE CASCADE foreign key; without it the pages would stay live with no sources row, where no write, export or per-source audit can reach them (#7072). | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. | host_admin | `gbrain doctor --json` | 1 | no |
+
### source_profile_no_backfill
<a id="source_profile_no_backfill"></a>
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index df400a25cb..f79d2e6128 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -2637,7 +2637,9 @@ Then each take of kind `fact` held by you that is still active and unresolved,
and whose every contributing fact is no longer yours, is retired: struck in its
page's takes fence when the page holds it, otherwise made inactive in the
database. The preview lists those as `take_to_retire`. A fact or take that
-changed since the preview reports `changed_since_preview` and is kept.
+changed since the preview reports `changed_since_preview` and is kept; a fact
+that already reads as the agent's with its speaker note (a resumed apply whose
+accepted request committed meanwhile) reports `reattributed`.
<a id="redacted-facts"></a>
### Redacted facts
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index 52f553f07a..915098bc7c 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -252,7 +252,7 @@ Two calls, no SQL: the doctor or `sources status` row names the command, and `wr
- **Active blockers** hold work now: a receipt still holding a publication recovery record (it blocks every queued write on its root), or a receipt that blocks a managed sync's checkpoint. Doctor warns whenever one exists, whatever the trend, and its `fix.command` is the next step (for a recovery record, `gbrain sync --source <id> --no-pull`, which runs the owner pass that clears it; a `recovery_blocked` record names the file to inspect instead).
- **Unresolved rows** are terminal receipts in the window (`persistence.terminal_failures.window_days`, default 7, never longer than `persistence.receipt_retention_days`) that no later write superseded. Doctor warns when any of them is a gbrain-defect class (`owner_exception`, `database_refusal`, `writer_guard`, `outside_fence`, `gbrain_defect`): report those with the receipt ids. The rest are ordinary refusals the caller already received (`caller_conflict`, `caller_refusal`, `operator_cancelled`) or sync faults a rerun retries. A `schema_missing` row (#6904) is a write that met a missing table or column: when the schema is behind, its fix is `gbrain apply-migrations --yes` as the database role that owns the gbrain tables, then resubmit; at head, it asks the user and points at doctor's `schema_missing_tables` check and the `gbrain repair missing-tables` preview.
-- **Historical rows** do not block: a later write superseded them (`superseded`, `already_written`, `duplicate`), or they came from a build older than the release that fixed their cause (sync knock-on cancels before 0.60.216.0, the `Publication failed (P0001)` refusal before 0.60.40.0). Doctor counts them and never warns on them.
+- **Historical rows** do not block: a later write superseded them (`superseded`, `already_written`, `duplicate`), or they came from a build older than the release that fixed their cause (sync knock-on cancels before 0.60.216.0, the `Publication failed (P0001)` refusal before 0.60.40.0), or they refused a write gbrain retired (`retired_operation`: a v0.13.1 grandfather request an older build queued, which now ends without writing; nothing to do). Doctor counts them and never warns on them.
A spike warns only on its own: when at least `persistence.terminal_failures.spike_min` (default 25) receipts ended in the last 24 h and that is more than `persistence.terminal_failures.spike_factor` (default 3) times the median of the 7 days before. When most of those receipts were written by a gbrain build older than the release that fixed their class, the warning says an older write owner is still producing them and names the build; its fix is the read-only `gbrain sources writer status --source <id> --json` that names the owner, so upgrade or restart that process. A `file_database_drift` row is the page-drift class: [file drift](repair.md#file-drift) resolves it with `gbrain repair file-drift`. A read that does not finish within its deadline (5 s per statement, 2 s to get a connection) reports `unknown`, never a clean pile; rerun it.
diff --git a/llms-full.txt b/llms-full.txt
index 15e0d5011f..ffc6215362 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -9548,7 +9548,7 @@ Two calls, no SQL: the doctor or `sources status` row names the command, and `wr
- **Active blockers** hold work now: a receipt still holding a publication recovery record (it blocks every queued write on its root), or a receipt that blocks a managed sync's checkpoint. Doctor warns whenever one exists, whatever the trend, and its `fix.command` is the next step (for a recovery record, `gbrain sync --source <id> --no-pull`, which runs the owner pass that clears it; a `recovery_blocked` record names the file to inspect instead).
- **Unresolved rows** are terminal receipts in the window (`persistence.terminal_failures.window_days`, default 7, never longer than `persistence.receipt_retention_days`) that no later write superseded. Doctor warns when any of them is a gbrain-defect class (`owner_exception`, `database_refusal`, `writer_guard`, `outside_fence`, `gbrain_defect`): report those with the receipt ids. The rest are ordinary refusals the caller already received (`caller_conflict`, `caller_refusal`, `operator_cancelled`) or sync faults a rerun retries. A `schema_missing` row (#6904) is a write that met a missing table or column: when the schema is behind, its fix is `gbrain apply-migrations --yes` as the database role that owns the gbrain tables, then resubmit; at head, it asks the user and points at doctor's `schema_missing_tables` check and the `gbrain repair missing-tables` preview.
-- **Historical rows** do not block: a later write superseded them (`superseded`, `already_written`, `duplicate`), or they came from a build older than the release that fixed their cause (sync knock-on cancels before 0.60.216.0, the `Publication failed (P0001)` refusal before 0.60.40.0). Doctor counts them and never warns on them.
+- **Historical rows** do not block: a later write superseded them (`superseded`, `already_written`, `duplicate`), or they came from a build older than the release that fixed their cause (sync knock-on cancels before 0.60.216.0, the `Publication failed (P0001)` refusal before 0.60.40.0), or they refused a write gbrain retired (`retired_operation`: a v0.13.1 grandfather request an older build queued, which now ends without writing; nothing to do). Doctor counts them and never warns on them.
A spike warns only on its own: when at least `persistence.terminal_failures.spike_min` (default 25) receipts ended in the last 24 h and that is more than `persistence.terminal_failures.spike_factor` (default 3) times the median of the 7 days before. When most of those receipts were written by a gbrain build older than the release that fixed their class, the warning says an older write owner is still producing them and names the build; its fix is the read-only `gbrain sources writer status --source <id> --json` that names the owner, so upgrade or restart that process. A `file_database_drift` row is the page-drift class: [file drift](repair.md#file-drift) resolves it with `gbrain repair file-drift`. A read that does not finish within its deadline (5 s per statement, 2 s to get a connection) reports `unknown`, never a clean pile; rerun it.
diff --git a/scripts/postgres-arm-weights.json b/scripts/postgres-arm-weights.json
index a6abbfd3f8..a39ee37e32 100644
--- a/scripts/postgres-arm-weights.json
+++ b/scripts/postgres-arm-weights.json
@@ -576,6 +576,7 @@
"test/shared-skills-source-opt-out.test.ts": 4679,
"test/shared-skills-writer-boundary.test.ts": 23530,
"test/source-lifecycle-dry-run-physical-root-6849.test.ts": 4712,
+ "test/source-purge-stranded-pages-7072.test.ts": 2807,
"test/source-retire-missing-checkout.test.ts": 6258,
"test/source-row-diagnostics.test.ts": 5513,
"test/sources-git-reconcile.test.ts": 19780,
diff --git a/src/commands/doctor/checks/memory-writeback.ts b/src/commands/doctor/checks/memory-writeback.ts
index 0f91e7d9be..f86f20d308 100644
--- a/src/commands/doctor/checks/memory-writeback.ts
+++ b/src/commands/doctor/checks/memory-writeback.ts
@@ -122,18 +122,20 @@ async function sessionCorpusDir(engine: BrainEngine, fileCfg: ReturnType<typeof
/**
* #6268: captured session files held because nothing proves their source
- * (legacy top-level files on a multi-source brain, or sessions whose source
- * never resolved). Only the operator can say where they belong, so the
- * warning names the preview command. Records `details.corpus_source_holds`.
+ * (legacy files on a multi-source brain, or sessions whose source never
+ * resolved), counted as the operator mapping lists them: already-swept files
+ * included, since dream synthesis and extract_atoms still hold them (#7849).
+ * Only the operator can say where they belong, so the warning names the
+ * preview command. Records `details.corpus_source_holds`.
*/
async function corpusSourceHoldProblem(engine: BrainEngine, fileCfg: ReturnType<typeof loadConfig>, details: Record<string, unknown>): Promise<string | null> {
const sources = await engine.executeRaw<{ id: string }>('SELECT id FROM sources ORDER BY id LIMIT 2');
- const holds = listCorpusSourceHolds(await sessionCorpusDir(engine, fileCfg), sources.length === 1);
+ const holds = listCorpusSourceHolds(await sessionCorpusDir(engine, fileCfg), sources.length === 1, { includeIngested: true });
details.corpus_source_holds = { legacy_unstamped: holds.legacy_unstamped, unresolved: holds.unresolved, sessions: holds.sessions.length };
const held = holds.legacy_unstamped + holds.unresolved;
if (held === 0) return null;
return `${held} captured session file(s) from ${holds.sessions.length} session(s) are held because nothing records which source they belong to `
- + '(written before corpus files carried their source, or the session never resolved one); they are not extracted until mapped. '
+ + '(written before corpus files carried their source, or the session never resolved one); nothing extracts, synthesizes or mines them for atoms until they are mapped. '
+ 'Ask the user which source they belong to, preview with gbrain sweep --assign-corpus <source>, then add --apply';
}
diff --git a/src/commands/hook.ts b/src/commands/hook.ts
index c9e26853e6..39ef1fb12c 100644
--- a/src/commands/hook.ts
+++ b/src/commands/hook.ts
@@ -80,7 +80,7 @@ import {
} from '../core/context/corpus-segments.ts';
import { openSessionCorpus } from '../core/context/corpus-source.ts';
import { hookLaneLabel, resolveSeat, seatReasonHint, writeSeatSidecar } from '../core/context/seat.ts';
-import { bankAsSpeaker, resolveSessionSpeaker, type AncestorProcess } from '../core/context/session-speaker.ts';
+import { hookSpeakerDecision, type AncestorProcess } from '../core/context/session-speaker.ts';
import { gateWritebackTurn, WRITEBACK_SKIP_REASONS } from '../core/facts/writeback-gate.ts';
import { resolveWritebackConfigFromFile } from '../core/facts/writeback-config.ts';
import { recordCaptureIfOff } from '../core/context/capture-consent.ts';
@@ -1693,10 +1693,9 @@ async function clearDriftStatus(harness: string): Promise<void> {
} catch { /* absent or unreadable: nothing to clear */ }
}
-/** #8064: whether this session may be banked; an agent speaker is recorded first, and a failed record banks nothing. */
+/** #8064: whether this session may be banked; an agent speaker is recorded first, and a failed record banks nothing (#8080 notes ride `reasons`). */
function hookSpeaker(io: HookIo, dir: string, sessionId: string) {
- const speaker = resolveSessionSpeaker({ env: io.env ?? process.env, ...(io.processAncestry ? { ancestry: io.processAncestry } : {}) });
- return bankAsSpeaker(dir, sessionId, speaker, io.harness ?? 'claude-code');
+ return hookSpeakerDecision(dir, sessionId, { env: io.env ?? process.env, ...(io.processAncestry ? { ancestry: io.processAncestry } : {}) }, io.harness ?? 'claude-code');
}
function captureSeat(io: HookIo, dir: string, sessionId: string, transcriptPath: string | undefined): string[] {
diff --git a/src/core/context-engine.ts b/src/core/context-engine.ts
index cb874c0a51..a3c64ec5aa 100644
--- a/src/core/context-engine.ts
+++ b/src/core/context-engine.ts
@@ -135,6 +135,11 @@ function hostSessionTarget(raw: unknown): Record<string, string> | null {
return target.sessionId ? target : null;
}
+/** #8080: an OpenClaw sub-agent session key (`agent:<id>:subagent:<uuid>`, nested lineage included, or a bare `subagent:` key). */
+export function isOpenClawSubagentKey(key: unknown): boolean {
+ return typeof key === 'string' && /^(agent:[^:]+:)?subagent:/i.test(key.trim());
+}
+
/** Test-only: reset the lazy-load state so a test can re-exercise the load path. */
export function __resetSdkLoadStateForTests(): void {
_sdkLoaded = false;
@@ -1085,7 +1090,7 @@ export function createGBrainContextEngine(ctx: {
/** compact()-side: spool-first checkpoint over the ladder. Never throws. */
async function runCompactCheckpoint(params: {
- sessionId?: unknown; sessionFile?: unknown; sessionTarget?: unknown;
+ sessionId?: unknown; sessionKey?: unknown; sessionFile?: unknown; sessionTarget?: unknown;
}, deadlineHit: () => boolean = () => false): Promise<Record<string, unknown>> {
// Host-supplied id, sanitized to the hook lane's charset before ANY
// filename/key use (pre-landing review, security: OpenClaw session keys
@@ -1123,6 +1128,12 @@ export function createGBrainContextEngine(ctx: {
// #6268: the session's frozen source rides in the segment NAME, inside the spool.
const { root, dir, stamp, source } = await (await import('./context/corpus-source.ts')).openSessionCorpus(await engineCorpusDir(cfg), sessionId, { cwd: workspaceDir, harness: 'openclaw' });
const segName = (hash: string) => segs.segmentFileName(sessionId, hash, stamp);
+ // #8080: a sub-agent session's user turns are its parent agent's brief: the speaker marker precedes its first segment.
+ if (isOpenClawSubagentKey(params.sessionKey) || isOpenClawSubagentKey((params.sessionTarget as { sessionKey?: unknown } | null | undefined)?.sessionKey)) {
+ const speaker = await import('./context/session-speaker.ts');
+ const marked = speaker.bankAsSpeaker(dir, sessionId, { kind: 'agent', principal: speaker.DETECTED_PRINCIPAL, source: 'detected' }, 'openclaw');
+ if (marked.bank !== true) return { status: 'skipped', reason: marked.reason };
+ }
await recordOpenclawSeat(dir, sessionId, sessionFile ?? target?.storePath ?? null);
(await import('./context/capture-consent.ts')).recordCaptureIfOff(cfg, `${dir}/${segName(segs.segmentHash(rendered.text))}`, rendered.text, source);
const w = segs.writeSegment(dir, sessionId, rendered.text, stamp);
@@ -1241,6 +1252,7 @@ export function createGBrainContextEngine(ctx: {
if (await rung3WriterHeld(pg, sourceId)) return { status: 'banked', reason: 'writer_coordinator_required' };
if (deadlineHit()) return { status: 'banked', reason: 'deadline' };
const { runFactsPipeline } = await import('./facts/backstop.ts');
+ const speaker = (await import('./context/session-speaker.ts')).speakerOf(fullPath); // #8080: the session's agent speaker, as the sweep and harvest pass it
const abort = new AbortController();
// Inner backstop timer PLUS a poll of the outer compact() deadline —
// the outer budget started before this rung, so when it wins the race
@@ -1254,6 +1266,7 @@ export function createGBrainContextEngine(ctx: {
sourceId,
sessionId,
source: 'hook:compact',
+ ...speaker,
mode: 'inline',
remote: false,
abortSignal: abort.signal,
diff --git a/src/core/context/corpus-source.ts b/src/core/context/corpus-source.ts
index b5288dc33d..8c3f236b97 100644
--- a/src/core/context/corpus-source.ts
+++ b/src/core/context/corpus-source.ts
@@ -35,9 +35,10 @@
* argument and lazy-imports the resolver.
*/
-import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync, type Dirent } from 'node:fs';
import { join } from 'node:path';
import type { BrainEngine } from '../engine.ts';
+import { pruneDir } from '../sync.ts';
import {
CORPUS_UNRESOLVED_STAMP,
SESSION_SOURCE_LOCK_SUFFIX,
@@ -311,7 +312,7 @@ export async function resolveCorpusFileSource(
}
export interface CorpusSourceHolds {
- /** Top-level files with no `.ingested` sidecar and no evidence of their source. */
+ /** Corpus files outside the spool (top-level or nested, `.txt` or `.md`) with no evidence of their source. */
legacy_unstamped: number;
/** Spool files stamped unresolved whose session record still names no source (on a sole-source brain, only those with no recorded cwd). */
unresolved: number;
@@ -322,20 +323,26 @@ export interface CorpusSourceHolds {
/**
* Doctor/CLI view of the held files that only an operator mapping can
* release (a multi-source brain's legacy files and unresolved sessions).
- * Engine-free; `soleSource` is the caller's `SELECT id FROM sources` answer.
- * `includeIngested` (the operator mapping) also lists sessions the sweep already
- * extracted: dream synthesis holds them too until their source is known (#7805).
+ * Walks what dream discovery walks (#7849): every `.txt` and `.md` file under
+ * the corpus, nested folders included, with sync's descent pruning; a file
+ * directly in the spool is a spool file, any other is legacy, as routing reads
+ * it. Engine-free; `soleSource` is the caller's `SELECT id FROM sources`
+ * answer. `includeIngested` also lists sessions the sweep already extracted:
+ * dream synthesis holds them too until their source is known (#7805).
*/
export function listCorpusSourceHolds(corpusDir: string, soleSource: boolean, opts: { includeIngested?: boolean } = {}): CorpusSourceHolds {
const out: CorpusSourceHolds = { legacy_unstamped: 0, unresolved: 0, sessions: [] };
const spool = corpusSpoolDir(corpusDir);
const sessions = new Set<string>();
- const scan = (dir: string, location: CorpusFileLocation) => {
- let names: string[];
- try { names = readdirSync(dir); } catch { return; }
- const present = new Set(names);
- for (const name of names) {
- if (!name.endsWith('.txt') || (!opts.includeIngested && present.has(name + '.ingested'))) continue;
+ const scan = (dir: string) => {
+ let entries: Dirent[];
+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
+ const present = new Set(entries.map(entry => entry.name));
+ const location: CorpusFileLocation = dir === spool ? 'spool' : 'legacy';
+ for (const entry of entries) {
+ const name = entry.name;
+ if (entry.isDirectory()) { if (pruneDir(name, dir)) scan(join(dir, name)); continue; }
+ if (!(name.endsWith('.txt') || name.endsWith('.md')) || (!opts.includeIngested && present.has(name + '.ingested'))) continue;
const sid = corpusFileSessionId(name);
const record = readSessionSource(spool, sid);
if (record?.source_id) continue;
@@ -350,8 +357,7 @@ export function listCorpusSourceHolds(corpusDir: string, soleSource: boolean, op
sessions.add(sid);
}
};
- scan(spool, 'spool');
- scan(corpusDir, 'legacy');
+ scan(corpusDir);
out.sessions = [...sessions].sort();
return out;
}
diff --git a/src/core/context/session-speaker.ts b/src/core/context/session-speaker.ts
index 1c6b7fbc1d..dc5f46d398 100644
--- a/src/core/context/session-speaker.ts
+++ b/src/core/context/session-speaker.ts
@@ -12,7 +12,8 @@
* session is banked; extraction attributes them to that agent, never to
* the owner.
* - `off`: nothing from the session is banked.
- * - `owner`: the turns are the owner's; automatic detection is skipped.
+ * - `owner`: the turns are the owner's; detection still runs, only to note
+ * (`speaker_owner_override_detected`) a session it finds agent-launched.
* - anything else: agent `agent`, reported as `speaker_label_invalid`.
* Unset: detection (`detectAgentLaunched`) — a headless harness process
* (claude `-p`/`--print`, codex `exec`) with a claude or codex process
@@ -21,13 +22,16 @@
*
* Sidecar `<sessionId>.speaker.json` (0600, tmp+rename) beside the corpus
* files, written BEFORE any corpus file of the session; the first record is
- * kept. Its absence means the owner.
+ * kept. Its absence means the owner. A resolved speaker that differs from the
+ * record is noted as `speaker_mismatch` (#8080), never rewritten; an agent in
+ * a session the owner already banked banks nothing (`speaker_mismatch`), since
+ * a sidecar would re-attribute the owner's banked turns.
*/
-import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
+import { existsSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import { spawnSync } from '../spawn.ts';
import { basename, dirname, join } from 'node:path';
-import { corpusFileSessionId, speakerFileName } from './corpus-segments.ts';
+import { corpusFileSessionId, SPEAKER_SIDECAR_SUFFIX, speakerFileName } from './corpus-segments.ts';
export const SESSION_AGENT_ENV = 'GBRAIN_SESSION_AGENT';
/** Principal recorded for a session detection marked as agent-launched. */
@@ -167,17 +171,34 @@ export function speakerContextNote(principal: string): string {
return `speaker: agent ${principal}, not the owner`;
}
+/** True when the session already has corpus files in `dir` (banked as the owner's when no sidecar exists). */
+function sessionHasCorpusFiles(dir: string, sessionId: string): boolean {
+ const id = speakerFileName(sessionId).slice(0, -SPEAKER_SIDECAR_SUFFIX.length);
+ try {
+ return readdirSync(dir).some((name) => name.endsWith('.txt') && corpusFileSessionId(name) === id);
+ } catch {
+ return false;
+ }
+}
+
+type BankDecision =
+ { bank: true; reasons: string[] } | { bank: 'skip' | 'failed'; reason: 'capture_opt_out' | 'speaker_write_failed' | 'speaker_mismatch'; reasons: string[] };
+
/**
* The hook's banking decision for one event: `bank: true` (an agent speaker
* is recorded first), `'skip'` (the launcher opted out) or `'failed'` (the
- * marker could not be written, so nothing is banked rather than banking an
- * agent session as the owner's). `reasons` are heartbeat notes.
+ * marker could not be written, or an agent continues a session already banked
+ * as the owner's, so nothing is banked rather than mixing the two). `reasons`
+ * are heartbeat notes; a speaker that differs from the recorded one adds
+ * `speaker_mismatch` (#8080).
*/
-export function bankAsSpeaker(dir: string, sessionId: string, speaker: SessionSpeaker, harness: string):
- { bank: true; reasons: string[] } | { bank: 'skip' | 'failed'; reason: 'capture_opt_out' | 'speaker_write_failed'; reasons: string[] } {
+export function bankAsSpeaker(dir: string, sessionId: string, speaker: SessionSpeaker, harness: string): BankDecision {
if (speaker.kind === 'skip') return { bank: 'skip', reason: 'capture_opt_out', reasons: [] };
- if (speaker.kind === 'owner') return { bank: true, reasons: [] };
+ const recorded = readSpeakerSidecar(dir, sessionId);
+ if (speaker.kind === 'owner') return { bank: true, reasons: recorded ? ['speaker_mismatch'] : [] };
const reasons = speaker.invalid ? ['speaker_label_invalid'] : [];
+ if (!recorded && sessionHasCorpusFiles(dir, sessionId)) return { bank: 'failed', reason: 'speaker_mismatch', reasons };
+ if (recorded && recorded.principal !== speaker.principal) reasons.push('speaker_mismatch');
try {
writeSpeakerSidecar(dir, sessionId, speaker, harness);
} catch {
@@ -185,3 +206,14 @@ export function bankAsSpeaker(dir: string, sessionId: string, speaker: SessionSp
}
return { bank: true, reasons };
}
+
+/**
+ * The hook's speaker and banking decision for one event. `owner` from the env
+ * still runs detection, so an inherited override that hides an agent-launched
+ * session is noted (`speaker_owner_override_detected`, #8080).
+ */
+export function hookSpeakerDecision(dir: string, sessionId: string, opts: { env: Env; ancestry?: () => readonly AncestorProcess[] }, harness: string): BankDecision {
+ const decision = bankAsSpeaker(dir, sessionId, resolveSessionSpeaker(opts), harness);
+ const overridden = opts.env[SESSION_AGENT_ENV]?.trim().toLowerCase() === 'owner' && detectAgentLaunched((opts.ancestry ?? readProcessAncestry)());
+ return overridden ? { ...decision, reasons: [...decision.reasons, 'speaker_owner_override_detected'] } : decision;
+}
diff --git a/src/core/cycle/synthesize-source-routing.ts b/src/core/cycle/synthesize-source-routing.ts
index 1ce5f6e42b..6cd3df017b 100644
--- a/src/core/cycle/synthesize-source-routing.ts
+++ b/src/core/cycle/synthesize-source-routing.ts
@@ -130,7 +130,32 @@ export async function refuseChangedSessionSource(engine: BrainEngine,
const pin = data.corpus_source ?? { raw_source: data.dream_output!.raw_source,
corpus_dir: await engine.getConfig('dream.synthesize.session_corpus_dir').catch(() => null) };
const changed = await corpusSourceChanged(engine, pin, sourceId);
- if (changed) throw new UnrecoverableError(`session_source_changed: ${changed}: the session of ${pin.raw_source} no longer resolves to source ${sourceId} as it did when this job was queued, so nothing was synthesized or written. It synthesizes when the dream runs for its own source, or after gbrain sweep --assign-corpus <source> maps it.`);
+ if (!changed) return;
+ const release = corpusHoldRelease([changed]);
+ throw new UnrecoverableError(`session_source_changed: ${changed}: the session of ${pin.raw_source} no longer resolves to source ${sourceId} as it did when this job was queued, so nothing was synthesized or written. ${changed === 'corpus_source_other' ? 'It synthesizes when the dream runs for its own source.'
+ : release.fix.length ? `It synthesizes after ${release.fix.at(-1)}.` : `It stays held: ${release.stays[0] ?? changed}.`}`);
+}
+
+/**
+ * What releases a held corpus file, by hold reason (#7849). The operator mapping fills only records naming no source, so it
+ * releases only unstamped legacy files and unresolved sessions; an archived source's sessions wait for its restore; nothing
+ * releases the rest, since a session's frozen source is never rewritten.
+ */
+const HOLD_RELEASE: Record<string, { fix: string[] } | { why: string }> = {
+ corpus_legacy_unstamped: { fix: ['gbrain sweep --assign-corpus <source>'] },
+ corpus_source_unresolved: { fix: ['gbrain sweep --assign-corpus <source>'] },
+ corpus_source_archived: { fix: ['gbrain sources archived', 'gbrain sources restore <archived-source>'] },
+ corpus_source_incarnation_changed: { why: 'their source was removed and re-created under the same id' },
+ corpus_source_missing: { why: 'the source they name is not in this brain' },
+ corpus_stamp_missing: { why: 'their spool name carries no source' },
+ corpus_path_unresolvable: { why: 'their real path could not be read; check the corpus folder\'s permissions' },
+};
+
+/** The commands that release these held reasons, and why the others stay held. */
+export function corpusHoldRelease(reasons: string[]): { fix: string[]; stays: string[] } {
+ const release = reasons.map(reason => [reason, HOLD_RELEASE[reason]] as const);
+ return { fix: [...new Set(release.flatMap(([, r]) => r && 'fix' in r ? r.fix : []))],
+ stays: release.flatMap(([reason, r]) => r && 'why' in r ? [`${reason}: ${r.why}`] : []) };
}
/** Names every corpus file the phase left out, with the command that synthesizes (or extracts) or releases it. */
@@ -143,17 +168,19 @@ export function withSessionSourceRouting(result: PhaseResult, routing: SessionSo
const otherCount = others.reduce((n, [, c]) => n + c, 0);
const heldCount = held.reduce((n, [, c]) => n + c, 0);
const memberCount = members.reduce((n, [, c]) => n + c, 0);
+ const release = corpusHoldRelease(held.map(([r]) => r));
const fix = [
...others.map(([id]) => `gbrain dream --source ${id} --phase ${phase}`),
- ...(heldCount ? ['gbrain sweep --assign-corpus <source>'] : []),
+ ...release.fix,
...(memberCount ? [`gbrain doctor --only generation_pending --json`] : []),
];
const parts = [
...(otherCount ? [`${otherCount} corpus file(s) belong to other sources (${others.map(([id, c]) => `${id}: ${c}`).join(', ')}) and ${phase === 'synthesize' ? 'synthesize' : 'extract'} only under their own source`] : []),
...(heldCount ? [`${heldCount} held with no frozen session source (${held.map(([r, c]) => `${r}: ${c}`).join(', ')})`] : []),
+ ...(release.stays.length ? [`nothing releases ${release.stays.join('; ')}`] : []),
...(memberCount ? [`${memberCount} pending generation member(s) held, not resubmitted: their transcript no longer resolves to this source (${members.map(([r, c]) => `${r}: ${c}`).join(', ')})`] : []),
];
- process.stderr.write(`[dream] ${phase} for source ${sourceId}: ${parts.join('; ')}. Fix: ${fix.join(' | ')}\n`);
+ process.stderr.write(`[dream] ${phase} for source ${sourceId}: ${parts.join('; ')}.${fix.length ? ` Fix: ${fix.join(' | ')}` : ''}\n`);
return { ...result, summary: `${result.summary}; ${parts.join('; ')}`,
details: { ...result.details, source_routing: { source_id: sourceId, ...routing, fix } } };
}
diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.ts
index 114de100d5..f079c4523d 100644
--- a/src/core/cycle/synthesize.ts
+++ b/src/core/cycle/synthesize.ts
@@ -2888,7 +2888,7 @@ function buildSynthesisPrompt(
CONTEXT
${dateContextLine}
- Transcript hash suffix (USE THIS in slugs): ${hashSuffix}
-- Source file basename: ${baseSlugSegment}${chunkBanner}${priorContradictionsBlock}${triageMapBlock}${linkManifestBlock}${allowedPathsBlock}
+- Source file basename: ${baseSlugSegment}${t.speaker ? `\n- Speaker: this session was launched by the automated agent "${t.speaker}". Its user turns are that agent's brief, not the user's words: never present them as what the user said, requested or prefers; attribute them to Agent ${t.speaker}.` : ''}${chunkBanner}${priorContradictionsBlock}${triageMapBlock}${linkManifestBlock}${allowedPathsBlock}
OUTPUT POLICY (ALL of these are required)
1. Quote the user verbatim. Quotation marks are ONLY for spans reproducible EXACTLY from the transcript below — if you cannot reproduce a span exactly, paraphrase it WITHOUT quotation marks. Do not paraphrase memorable phrasings you can quote exactly.
diff --git a/src/core/cycle/transcript-discovery.ts b/src/core/cycle/transcript-discovery.ts
index 6ffa911c34..a985f90413 100644
--- a/src/core/cycle/transcript-discovery.ts
+++ b/src/core/cycle/transcript-discovery.ts
@@ -20,6 +20,7 @@ import { realpathOrResolve, resolvedPrefixContained } from '../path-confine.ts';
import { CORPUS_SPOOL_SUBDIR, corpusFileSessionId } from '../context/corpus-segments.ts';
import { withoutOffPeriodTurns } from '../context/capture-consent.ts';
import { readSeatSidecar } from '../context/seat.ts';
+import { corpusFileSpeaker } from '../context/session-speaker.ts';
import { claudeCliSelfSessionIds } from '../ai/providers/claude-cli-scratch.ts';
import type { BrainEngine } from '../engine.ts';
import type { PhaseResult } from '../cycle.ts';
@@ -37,6 +38,8 @@ export interface DiscoveredTranscript {
inferredDate: string | null;
/** #4618: the capturing seat from the session's `.seat.json` sidecar, when one exists. */
seat?: string;
+ /** #8080: the agent that wrote the session's user turns (its `.speaker.json` sidecar); absent means the owner. */
+ speaker?: string;
}
export interface DiscoverOpts {
@@ -370,6 +373,7 @@ export function discoverTranscripts(opts: DiscoverOpts): DiscoveredTranscript[]
basename: baseName,
inferredDate,
...(seat ? { seat } : {}),
+ ...transcriptSpeaker(filePath),
});
}
}
@@ -428,6 +432,7 @@ export function readSingleTranscript(
basename: baseName,
inferredDate: DATE_RE.exec(baseName)?.[1] ?? frontmatterDay(transcriptFrontmatter(content)),
...(seat ? { seat } : {}),
+ ...transcriptSpeaker(filePath),
};
}
@@ -465,6 +470,12 @@ function transcriptSeat(filePath: string): string | undefined {
return readSeatSidecar(dirname(filePath), key)?.seat;
}
+/** #8080: a `.txt` corpus file's agent speaker (the session's speaker sidecar beside it), as a spread; the owner adds nothing. */
+function transcriptSpeaker(filePath: string): { speaker?: string } {
+ const speaker = filePath.endsWith('.txt') ? corpusFileSpeaker(filePath) : undefined;
+ return speaker ? { speaker: speaker.principal } : {};
+}
+
// ── #4419: imported type: conversation pages (database discovery) ───────
/*
* Dream's synthesize phase discovers imported `type: conversation`
diff --git a/src/core/destructive-guard.ts b/src/core/destructive-guard.ts
index 14e091a4c1..61409c047e 100644
--- a/src/core/destructive-guard.ts
+++ b/src/core/destructive-guard.ts
@@ -25,6 +25,7 @@ import { gbrainPath } from './config.ts';
import { isMissingSchemaObject } from './utils.ts';
import { deleteSourceRow, EXPIRED_ARCHIVE_SQL, UNVERIFIED_ARCHIVE_SQL, unverifiedArchiveReason } from './source-delete.ts';
import { ItemRun } from './item-failure.ts';
+import { OperationError } from './ops/contract.ts';
import { cliRenderContext, renderAction, type RenderedAction } from './agent-output.ts';
// ── Types ───────────────────────────────────────────────────
@@ -495,7 +496,10 @@ export async function purgeExpiredSources(
const result:PurgeExpiredResult={purged:[],blocked:await unverifiedArchives(engine)};
for(const source of candidates){
try{const receipt=await runManagedSourceLifecycle(engine,{operation:'purge',sourceId:source.id,expectedIncarnation:source.incarnation,confirmDestructive:true,expiredOnly:true});if(!receipt.noop)result.purged.push(source.id);}
- catch(error){result.blocked.push({id:source.id,reason:error instanceof Error?error.message:'Source lifecycle could not finish.'});}
+ catch(error){
+ const code=error instanceof OperationError&&error.code==='source_pages_remain'?error.code:undefined;
+ result.blocked.push({id:source.id,reason:error instanceof Error?error.message:'Source lifecycle could not finish.',...(code?{code,fix:renderAction((error as OperationError).fix!,cliRenderContext())}:{})});
+ }
}
return result;
}
@@ -547,6 +551,10 @@ export async function purgeExpiredSources(
} catch (err) {
// SQLSTATE 23503 foreign_key_violation — same detection idiom as
// oauth-provider.ts's delete path for this exact FK.
+ if (err instanceof OperationError && err.code === 'source_pages_remain') {
+ blocked.push({ id, code: err.code, reason: `${err.message} ${err.suggestion}`, fix: renderAction(err.fix!, cliRenderContext()) });
+ continue;
+ }
if ((err as { code?: string })?.code === '23503') {
blocked.push({
id,
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index de906e3675..e5e61a8b93 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -793,6 +793,7 @@ export const CODES = {
source_mismatch: { class: 'caller', summary: "The request names a different source than the one this serve is bound to; it is refused, never rerouted." },
source_not_ready: { class: 'caller', summary: "A committed source and approved schema are required." },
source_profile_no_backfill: { class: 'unavailable', summary: "This source profile disables automatic embedding backfill." },
+ source_pages_remain: { class: 'host_only', summary: "A source delete did not cascade to the source's pages, so it was rolled back and the source and its pages are unchanged.", why: "Every source delete relies on the pages -> sources ON DELETE CASCADE foreign key; without it the pages would stay live with no sources row, where no write, export or per-source audit can reach them (#7072)." },
source_referenced: { class: 'caller', summary: "OAuth clients still reference this source." },
source_retire_superseded: { class: 'caller', summary: "A retried source remove or purge was superseded: its source has since been removed, replaced or changed by another lifecycle operation; nothing was changed.", why: "A remove or purge records the source incarnation it was admitted against before it deletes its first page, so a retry of its request id can never delete the pages of a source re-added under the same ID, and a later lifecycle change to the source (such as a restore) abandons the request. A request refused this way stays refused.", suggestion: "Do not retry this request id. Read the source's current state; removing the current source is a new decision for the user, made with a new request id.", fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Read-only: shows the source's current incarnation, binding, pending work and its stopped or superseded remove and purge requests (topology_requests).", requires_exclusive: false } },
source_root_conflict: { class: 'caller', summary: "Multiple active sources alias this canonical skill root; resolve ownership before publishing." },
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index cbb5db5221..b41040f1ed 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -48,7 +48,7 @@ import { assertBundleRecoveryBinding, bundleFileHash, prepareBundleRecovery, pub
import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';
import { classifyMirrorPage, sourceMirrorReadOnly } from './mirror-read-only.ts';
import { headCommit, landedCommit, PENDING_IMPORT, SYNC_HELD } from './pending-import.ts';
-import { CANONICAL_FILE_MISSING, CHECKOUT_REFUSAL_ORIGINS, type CheckoutRefusalOrigin, SOURCE_CHANGED_ORIGINS, type SourceChangedDetail, type SourceChangedOrigin, databaseRefusal, ownerExceptionFailure, stagingFailureDetail, withAttempt, type PublicationFailure, type PublicationFailureDetail, type PublicationStage } from './publication-failure.ts';
+import { CANONICAL_FILE_MISSING, CHECKOUT_REFUSAL_ORIGINS, type CheckoutRefusalOrigin, GRANDFATHER_RETIRED, SOURCE_CHANGED_ORIGINS, type SourceChangedDetail, type SourceChangedOrigin, databaseRefusal, ownerExceptionFailure, stagingFailureDetail, withAttempt, type PublicationFailure, type PublicationFailureDetail, type PublicationStage } from './publication-failure.ts';
import { SYNC_CURSOR_REPLACED, SYNC_PASS_SUPERSEDED } from './sync-checkpoint-replaced.ts';
import { fenceFailureDetail } from '../fence-repair/refusal.ts';
import { withdrawalFailureDetail } from '../facts/withdrawal.ts';
@@ -233,7 +233,7 @@ function requestError(error: unknown): PublicationFailure {
if (error instanceof OperationError) {
// #6188: a typed fence refusal keeps its location in the bounded detail, which outlives receipt compaction.
const detail = fenceFailureDetail(error) ?? withdrawalFailureDetail(error) ?? (error.syncRefusal as PublicationFailure['detail'] | undefined)
- ?? (error.detail === CANONICAL_FILE_MISSING ? { origin: CANONICAL_FILE_MISSING } : undefined)
+ ?? (error.detail === CANONICAL_FILE_MISSING || error.detail === GRANDFATHER_RETIRED ? { origin: error.detail } : undefined)
?? ((CHECKOUT_REFUSAL_ORIGINS as readonly unknown[]).includes(error.detail) ? { origin: error.detail as CheckoutRefusalOrigin } : undefined)
// #6693: a refusal on a page whose file awaits import or is held by sync; the replay after import selects on it.
?? (error.code === 'source_changed' && (error.reason === PENDING_IMPORT || error.reason === SYNC_HELD) ? { origin: error.reason } : undefined)
diff --git a/src/core/persistence/grandfather.ts b/src/core/persistence/grandfather.ts
index 29d8284008..aea145b5ea 100644
--- a/src/core/persistence/grandfather.ts
+++ b/src/core/persistence/grandfather.ts
@@ -2,15 +2,17 @@ import type { BrainEngine } from '../engine.ts';
import { opError } from '../ops/contract.ts';
import type { WriteRequest } from './model.ts';
import type { PreparedMutation } from './coordinator.ts';
+import { GRANDFATHER_RETIRED } from './publication-failure.ts';
/**
* #7814: the v0.13.1 grandfather no longer writes `validate: false` into pages
* (src/commands/migrations/v0_13_1.ts). A `managed_grandfather` request an
* older binary admitted and left queued ends here without writing, so an
- * upgrade never finishes a grandfather rewrite of the user's files.
+ * upgrade never finishes a grandfather rewrite of the user's files. Its receipt
+ * records origin `grandfather_retired`, which doctor reads as history (#7837).
*/
export async function prepareGrandfatherMutation(_engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {
throw opError('revision_conflict', 'Grandfathering is retired; the page was left unchanged.',
`${row.slug} in ${row.source_id} was queued for the retired v0.13.1 validate: false stamp by an older gbrain; `
- + 'upgrades no longer rewrite pages (#7814), so nothing changed and nothing else is needed.');
+ + 'upgrades no longer rewrite pages (#7814), so nothing changed and nothing else is needed.', { detail: GRANDFATHER_RETIRED });
}
diff --git a/src/core/persistence/public-category.ts b/src/core/persistence/public-category.ts
index 2508f68dc2..1464d7f655 100644
--- a/src/core/persistence/public-category.ts
+++ b/src/core/persistence/public-category.ts
@@ -28,7 +28,7 @@ export const PUBLIC_BY_TERMINAL: Readonly<Record<TerminalCategory, PublicCategor
operator_cancelled: 'superseded', caller_conflict: 'conflict', file_conflict: 'drift', canonical_file_missing: 'file_missing', fence_unrenderable: 'defect',
writer_guard: 'defect', database_refusal: 'config', owner_exception: 'defect', legacy_publication_refusal: 'superseded',
sync_fault: 'defect', transport: 'transient', caller_refusal: 'content_refused', gbrain_defect: 'defect', diagnosis_required: 'defect',
- schema_missing: 'storage',
+ schema_missing: 'storage', retired_operation: 'superseded',
};
/** Fault codes (holds, run stops, receipts) by name; a test pins that every `SYNC_FAULT_TABLE` code is here. */
diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.ts
index ba0de5cfdc..fcd7789488 100644
--- a/src/core/persistence/publication-failure.ts
+++ b/src/core/persistence/publication-failure.ts
@@ -59,7 +59,9 @@ export interface OwnerExceptionDetail extends Pick<PublicationFailureDetail, 'st
export type WithdrawalRefusalDetail = WithdrawalFailureDetail & Pick<PublicationFailureDetail, 'stage' | 'attempt'>;
/** #6696 (A12): the page's recorded canonical file is gone (`prepareFileTarget`); a producer refuses the same write before admission. */
export const CANONICAL_FILE_MISSING = 'canonical_file_missing';
-export interface CanonicalFileDetail { origin: typeof CANONICAL_FILE_MISSING; stage?: PublicationStage; attempt?: { consumer_version: string; consumer_host_id: string | null } }
+/** #7837: a `managed_grandfather` request an older binary queued, refused because the v0.13.1 grandfather is retired (#7814). */
+export const GRANDFATHER_RETIRED = 'grandfather_retired';
+export interface CanonicalFileDetail { origin: typeof CANONICAL_FILE_MISSING | typeof GRANDFATHER_RETIRED; stage?: PublicationStage; attempt?: { consumer_version: string; consumer_host_id: string | null } }
/** GST-465: the source's whole canonical checkout is missing on this host (`prepareFileTarget`, `sourceCheckoutMissingRefusal`). */
export const SOURCE_CHECKOUT_MISSING = 'source_checkout_missing';
/**
diff --git a/src/core/persistence/terminal-classify.ts b/src/core/persistence/terminal-classify.ts
index b57bb8a0c1..70ac798a1a 100644
--- a/src/core/persistence/terminal-classify.ts
+++ b/src/core/persistence/terminal-classify.ts
@@ -26,6 +26,7 @@ import { isSyncKnockOn, knockOnRoot, SYNC_CURSOR_FENCE_ORIGIN, SYNC_KNOCK_ON_ORI
import { writeFailureDiagnostic } from './verb-errors.ts';
import { publicCategory, type PublicCategory } from './public-category.ts';
import { ownerMarkerRestoreFix } from './owner-marker.ts';
+import { GRANDFATHER_RETIRED } from './publication-failure.ts';
export type TerminalCategory =
| 'recovery_pending' | 'recovery_blocked'
@@ -34,7 +35,9 @@ export type TerminalCategory =
| 'writer_guard' | 'database_refusal' | 'owner_exception' | 'legacy_publication_refusal'
| 'sync_fault' | 'transport' | 'caller_refusal' | 'gbrain_defect' | 'diagnosis_required'
// #6904: the write met a missing relation or column (42P01 / 42703); the schema is behind this build or lost a table.
- | 'schema_missing';
+ | 'schema_missing'
+ // #7837: a request for a write gbrain retired (the v0.13.1 grandfather, #7814) that an older build queued; nothing to do.
+ | 'retired_operation';
/** The receipt columns the classifier reads; every one but `intent_kind` and `error_message` survives compaction. */
export interface TerminalInput {
@@ -94,6 +97,8 @@ export const TERMINAL_FIXED_IN = {
legacy_publication_refusal: '0.60.40.0',
// #6657: a refused fact-fence adoption is no longer resubmitted every cycle and keeps its metadata.
fence_unrenderable: '0.60.218.0',
+ // #7814: the v0.13.1 grandfather writes nothing; a queued managed_grandfather request only an older build admitted ends refused.
+ retired_operation: '0.60.479.0',
} as const satisfies Partial<Record<TerminalCategory, string>>;
/** The connection-loss texts `classifySyncFault` reads as `connection_lost`; POSIX-compatible, so readers match it in SQL (`~*`). */
@@ -149,7 +154,7 @@ export function classifyTerminal(input: TerminalInput): TerminalVerdict | null {
const verdict = route(input);
const fixedIn = (TERMINAL_FIXED_IN as Partial<Record<TerminalCategory, string>>)[verdict.category] ?? null;
const ran = build(input);
- const historical = fixedIn !== null && (verdict.category === 'legacy_publication_refusal' || (ran !== null && compareVersions(ran, fixedIn) < 0));
+ const historical = fixedIn !== null && (verdict.category === 'legacy_publication_refusal' || verdict.category === 'retired_operation' || (ran !== null && compareVersions(ran, fixedIn) < 0));
return { ...verdict, public_category: publicCategory(verdict), escalate: verdict.escalate ?? escalateOf(verdict.code), defect: DEFECTS.has(verdict.category), fixed_in: fixedIn, historical };
}
@@ -291,6 +296,12 @@ function route(input: TerminalInput): Partial_ {
why: 'A fact-extraction batch was not recorded complete because some of its per-entity requests did not commit (__managed_facts_complete__ is bookkeeping, not a page). The receipt is read-only history; run the extraction again only if facts are still missing.',
verify: { argv: failuresArgv(source) } } };
}
+ if (code === 'revision_conflict' && (origin === GRANDFATHER_RETIRED || input.intent_kind === 'managed_grandfather')) {
+ return { category: 'retired_operation', code, origin, class: 'page', safe_actions: ['none'], needs_human: false,
+ escalate: 'never: the page was left unchanged and nothing retries it',
+ action: { argv: terminalInspectArgv(input.request_id ?? '<request_id>'), consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Retired grandfather, nothing to do: an older gbrain queued the v0.13.1 validate: false stamp for this page, and upgrades no longer rewrite pages (#7814), so the request ended without writing. Do not resubmit it; the receipt is read-only history.' } };
+ }
if (code === 'revision_conflict' || code === 'page_identity_changed') {
return { category: 'caller_conflict', code, origin, class: 'page', safe_actions: ['retry'], needs_human: false, escalate: escalateOf(code),
action: { argv: ['gbrain', 'get', '--source', source, '--', input.slug], consent: [], actor: 'agent', requires_exclusive: false,
diff --git a/src/core/persistence/terminal-failures.ts b/src/core/persistence/terminal-failures.ts
index 3340f9d666..eb5e2c410a 100644
--- a/src/core/persistence/terminal-failures.ts
+++ b/src/core/persistence/terminal-failures.ts
@@ -28,6 +28,7 @@ import { readReceiptRetentionDays, DEFAULT_RECEIPT_RETENTION_DAYS } from './limi
import { MANAGED_SYNC_PASS_OP } from './sync-pass-row.ts';
import { SYNC_PASS_SUPERSEDED } from './sync-checkpoint-replaced.ts';
import type { PublicCategory } from './public-category.ts';
+import { GRANDFATHER_RETIRED } from './publication-failure.ts';
import { classifyTerminal, dispositionOf, driftSinceAction, faultOperation, TERMINAL_FIXED_IN, supersessionOrderSql, supersessionSql, terminalInspectArgv, terminalKnockOnSql, type TerminalCategory,
type TerminalDisposition, type TerminalVerdict, CONNECTION_MESSAGE_PATTERN, LEGACY_PUBLICATION_PREFIX } from './terminal-classify.ts';
@@ -77,6 +78,7 @@ export const TERMINAL_HISTORICAL_SQL: Readonly<Record<keyof typeof TERMINAL_FIXE
knock_on: b => `(${b}.knock_on AND NOT ${b}.has_recovery AND ${OLDER_THAN(`${b}.build`, TERMINAL_FIXED_IN.knock_on)})`,
legacy_publication_refusal: b => `(NOT ${b}.has_recovery AND NOT ${b}.knock_on AND ${b}.routed_message = '${LEGACY_PUBLICATION_PREFIX}' AND ${b}.origin IS NULL AND ${b}.error_code IN ('storage_error','writer_coordinator_required'))`,
fence_unrenderable: b => `(NOT ${b}.has_recovery AND NOT ${b}.knock_on AND ${b}.origin IS NULL AND ${b}.error_code = 'fence_unrenderable' AND ${OLDER_THAN(`${b}.build`, TERMINAL_FIXED_IN.fence_unrenderable)})`,
+ retired_operation: b => `(NOT ${b}.has_recovery AND NOT ${b}.knock_on AND ${b}.error_code = 'revision_conflict' AND (${b}.origin IS NOT DISTINCT FROM '${GRANDFATHER_RETIRED}' OR ${b}.intent_kind IS NOT DISTINCT FROM 'managed_grandfather'))`,
};
const HISTORICAL_BY_BUILD = (b: string) => `COALESCE(${Object.values(TERMINAL_HISTORICAL_SQL).map(sql => sql(b)).join(' OR ')}, false)`;
const BUILD = (r: string) => `COALESCE(${r}.error_detail->'attempt'->>'consumer_version', ${r}.admitter_version)`;
diff --git a/src/core/repair/agent-session-facts.ts b/src/core/repair/agent-session-facts.ts
index 2fde3ca196..1aff58ac22 100644
--- a/src/core/repair/agent-session-facts.ts
+++ b/src/core/repair/agent-session-facts.ts
@@ -123,7 +123,8 @@ interface ApprovedPage {
takes?: AgentSessionTake[];
}
-interface PageItem extends RepairItem { page: ApprovedPage; hash: string; last: boolean; options: AgentSessionOptions }
+/** `indexes`: the run's corpus index by corpus dir, shared by every item of one run (each run plans new items). */
+interface PageItem extends RepairItem { page: ApprovedPage; hash: string; last: boolean; options: AgentSessionOptions; indexes: Map<string | null, CorpusIndex> }
interface FactRow {
id: number | string; source_id: string; source_session: string | null; fact: string; visibility: string; entity_slug: string | null;
@@ -239,7 +240,7 @@ const targetSlug = (row: Pick<FactRow, 'source_markdown_slug' | 'entity_slug'>)
/** Read-only: every user-attributed (or unattributed) capture-lane fact of these sources from a suspect session, classified, in (source, page, id) order. */
export async function classifyAgentSessionFacts(db: BrainEngine, sourceIds: string[],
- opts: AgentSessionOptions & { corpusDir?: string | null; ids?: number[] } = {}): Promise<AgentSessionFactsClassification> {
+ opts: AgentSessionOptions & { corpusDir?: string | null; ids?: number[]; indexes?: Map<string | null, CorpusIndex> } = {}): Promise<AgentSessionFactsClassification> {
const rows = await db.executeRaw<FactRow>(`
SELECT f.id, f.source_id, f.source_session, f.fact, f.visibility, f.entity_slug, f.row_num, f.source_markdown_slug, f.attributed_to, f.context,
EXISTS (SELECT 1 FROM facts a WHERE a.source_id=f.source_id AND a.id<>f.id AND a.expired_at IS NULL AND a.superseded_by IS NULL
@@ -253,8 +254,9 @@ export async function classifyAgentSessionFacts(db: BrainEngine, sourceIds: stri
AND (f.attributed_to IS NULL OR f.attributed_to='user') AND ($3::bigint[] IS NULL OR f.id=ANY($3::bigint[]))
ORDER BY f.source_id, f.id`, [sourceIds, [...CAPTURE_LANES], opts.ids ?? null]);
if (!rows.length) return { candidates: [], unclassifiable: 0, not_suspect: 0, unreadable_corpus_files: [] };
- const corpusDir = opts.corpusDir === undefined ? await db.getConfig(CORPUS_KEY) : opts.corpusDir;
- const index = corpusIndex(corpusDir ?? null);
+ const corpusDir = (opts.corpusDir === undefined ? await db.getConfig(CORPUS_KEY) : opts.corpusDir) ?? null;
+ const index = opts.indexes?.get(corpusDir) ?? corpusIndex(corpusDir);
+ opts.indexes?.set(corpusDir, index);
const cwdPrefixes = (opts.cwdPrefixes ?? []).map(canonicalPath);
const verdicts = new Map<string, Verdict>();
const verdict = (sourceSession: string | null): Verdict => {
@@ -325,9 +327,20 @@ async function brainId(engine: BrainEngine): Promise<string> {
return brain?.brain_id ?? 'host';
}
-function pageItem(page: ApprovedPage, hash: string, index: number, last: boolean, options: AgentSessionOptions): PageItem {
- return { cursor: { phase: page.facts ? 0 : 1, id: index }, source_id: page.source_id, slug: page.slug, chars: 0,
- action: page.facts ? `re-attribute ${page.facts.length} agent-session fact(s)` : `retire ${page.takes!.length} take(s)`, page, hash, last, options };
+/**
+ * One item per write, in cursor order. A fact page with both database-only and fenced rows is two items, the fenced one
+ * after every fact page (`id` = page count + index), so a database write still pending never skips the page's fenced
+ * rows and the runner holds the fenced rewrite until that write settles, like any later write to the same page.
+ */
+function pageItems(approved: ApprovedPage[], hash: string, options: AgentSessionOptions, indexes: Map<string | null, CorpusIndex>): PageItem[] {
+ const parts = approved.flatMap((page, i) => {
+ const fenced = page.facts?.filter(f => f.row_num !== null) ?? [];
+ return !fenced.length || fenced.length === page.facts!.length ? [{ page, id: i }]
+ : [{ page: { ...page, facts: page.facts!.filter(f => f.row_num === null) }, id: i }, { page: { ...page, facts: fenced }, id: approved.length + i }];
+ }).sort((a, b) => Number(!a.page.facts) - Number(!b.page.facts) || a.id - b.id);
+ return parts.map(({ page, id }, i) => ({ cursor: { phase: page.facts ? 0 : 1, id }, source_id: page.source_id, slug: page.slug, chars: 0,
+ action: page.facts ? `re-attribute ${page.facts.length} agent-session fact(s)` : `retire ${page.takes!.length} take(s)`, page, hash, last: i === parts.length - 1,
+ options, indexes }));
}
function groupByPage<T extends { source_id: string; slug: string }>(rows: T[], make: (first: T) => ApprovedPage, field: 'facts' | 'takes'): ApprovedPage[] {
@@ -370,7 +383,7 @@ export const agentSessionFactsRepair: RepairHandler = {
detail: `row ${take.row_num}; contributing facts ${take.fact_ids.join(', ')}` });
for (const path of unreadable_corpus_files) listing.push({ item: path, class: 'unreadable_corpus_file',
detail: 'not read (check its permissions); facts of its sessions are counted unclassifiable and kept' });
- return { items: approved.map((page, i) => pageItem(page, hash, i, i === approved.length - 1, options)), preview_hash: hash, listing,
+ return { items: pageItems(approved, hash, options, new Map()), preview_hash: hash, listing,
residuals: { evidenced: count('evidenced'), ambiguous: count('ambiguous'), excluded: count('excluded'), unclassifiable, not_suspect, takes_to_retire: takes.length,
...(unreadable_corpus_files.length ? { unreadable_corpus_files: unreadable_corpus_files.length } : {}) } };
}
@@ -384,17 +397,21 @@ export const agentSessionFactsRepair: RepairHandler = {
if (approved.items.some(page => page.include_ambiguous !== includeAmbiguous || JSON.stringify(page.scope) !== scopeKey || page.options !== optionsKey)) {
throw previewChangedError(opts.expect, command);
}
- const items = approved.items.map((page, i) => pageItem(page, opts.expect!, i, i === approved.items.length - 1, options))
- .filter(item => afterCursor(item.cursor, after));
+ const items = pageItems(approved.items, opts.expect, options, new Map()).filter(item => afterCursor(item.cursor, after));
if (!items.length) await clearApprovedSet(engine, { command: COMMAND, hash: opts.expect });
return { items, preview_hash: opts.expect, residuals: { approved_pages: approved.items.length, pending_pages: items.length } };
},
async apply(ctx, entry): Promise<RepairItemOutcome> {
- const { page, hash, last, options } = entry as PageItem;
+ const { page, hash, last, options, indexes } = entry as PageItem;
const engine = ctx.engine;
const done: number[] = [];
if (page.facts) {
- const live = new Map((await classifyAgentSessionFacts(engine, [page.source_id], { ...options, ids: page.facts.map(f => f.id) })).candidates.map(c => [c.id, c]));
+ const live = new Map((await classifyAgentSessionFacts(engine, [page.source_id], { ...options, ids: page.facts.map(f => f.id), indexes })).candidates.map(c => [c.id, c]));
+ const gone = page.facts.filter(f => !live.has(f.id));
+ const settled = gone.length ? await engine.executeRaw<{ id: number | string; context: string | null }>(
+ "SELECT id, context FROM facts WHERE source_id=$1 AND id=ANY($2::bigint[]) AND attributed_to='other' AND expired_at IS NULL AND superseded_by IS NULL",
+ [page.source_id, gone.map(f => f.id)]) : [];
+ done.push(...gone.filter(f => settled.some(row => Number(row.id) === f.id && (row.context ?? '').includes(speakerContextNote(f.principal)))).map(f => f.id));
const unchanged = page.facts.filter(f => {
const current = live.get(f.id);
return !!current && (['class', 'reason', 'principal', 'fact_hash', 'slug', 'row_num'] as const).every(field => current[field] === f[field]);
diff --git a/src/core/source-delete.ts b/src/core/source-delete.ts
index b4de05de19..eaee1e55cf 100644
--- a/src/core/source-delete.ts
+++ b/src/core/source-delete.ts
@@ -1,4 +1,6 @@
import type { BrainEngine } from './engine.ts';
+import { opError } from './ops/contract.ts';
+import { readFix } from './ops/op-fix.ts';
/**
* An archived source is purge-eligible only when both archive timestamps are real
@@ -12,6 +14,20 @@ export const UNVERIFIED_ARCHIVE_SQL = `archived = true AND (archived_at IS NULL
export const unverifiedArchiveReason = (id: string) =>
`archive timestamps are missing or invalid, so the 72h recovery window cannot be verified; run gbrain sources restore ${id}, then gbrain sources archive ${id} to restart it`;
+/**
+ * #7072: a source delete removes its pages only through the pages -> sources
+ * ON DELETE CASCADE. True when that cascade fires on this brain: the foreign key
+ * exists on pages.source_id, cascades, and its delete trigger on sources is enabled
+ * for this session. Where it does not, a delete would leave the pages live with no
+ * sources row, unwritable and outside every per-source audit.
+ */
+const PAGES_CASCADE_SQL = `EXISTS (
+ SELECT 1 FROM pg_constraint c JOIN pg_trigger t ON t.tgconstraint = c.oid AND t.tgrelid = c.confrelid
+ WHERE c.contype = 'f' AND c.conrelid = 'pages'::regclass AND c.confrelid = 'sources'::regclass AND c.confdeltype = 'c'
+ AND c.conkey = ARRAY[(SELECT a.attnum FROM pg_attribute a WHERE a.attrelid = 'pages'::regclass AND a.attname = 'source_id')]
+ AND t.tgfoid = 'pg_catalog."RI_FKey_cascade_del"'::regproc
+ AND (t.tgenabled = 'A' OR (t.tgenabled = 'O' AND current_setting('session_replication_role') <> 'replica')))`;
+
/**
* Delete a `sources` row together with that incarnation's persistence source
* binding (#5732). `persistence_source_bindings` has no FK to `sources`, so a
@@ -22,7 +38,9 @@ export const unverifiedArchiveReason = (id: string) =>
* that fails `unknown_source`. The same statement runs
* removedSourceScrubCtes, and a second statement repeats it once the row is
* gone, unless a source with this id exists again by then: a replacement
- * created between the two statements keeps its rows. Returns whether a row
+ * created between the two statements keeps its rows. A source that still has
+ * pages is deleted only when the pages cascade (#7072), in the same statement;
+ * otherwise nothing is deleted and `source_pages_remain` is thrown. Returns whether a row
* was deleted.
*/
export async function deleteSourceRow(
@@ -33,16 +51,20 @@ export async function deleteSourceRow(
const expired = opts.expiredArchiveOnly
? `AND ${EXPIRED_ARCHIVE_SQL}`
: '';
- const rows = await engine.executeRaw<{ id: string }>(
- `WITH gone AS (DELETE FROM sources WHERE id = $1 ${expired} RETURNING id, incarnation),
+ const rows = await engine.executeRaw<{ id: string | null; stranded: number }>(
+ `WITH stranded AS (SELECT count(*)::int AS n FROM pages WHERE source_id = $1 AND NOT ${PAGES_CASCADE_SQL}),
+ gone AS (DELETE FROM sources WHERE id = $1 ${expired} AND (SELECT n FROM stranded) = 0 RETURNING id, incarnation),
unbound AS (DELETE FROM persistence_source_bindings b USING gone
WHERE b.source_id = gone.id AND b.source_incarnation = gone.incarnation),
cursors AS (DELETE FROM op_checkpoints c USING gone
WHERE c.op = 'managed-sync' AND c.completed_keys->0->>'sourceId' = gone.id),
${removedSourceScrubCtes('EXISTS (SELECT 1 FROM gone)')}
- SELECT id FROM gone`,
+ SELECT id, 0 AS stranded FROM gone
+ UNION ALL SELECT NULL, n FROM stranded WHERE n > 0 AND EXISTS (SELECT 1 FROM sources WHERE id = $1 ${expired})`,
[id],
);
+ const stranded = rows.find(row => row.id === null);
+ if (stranded) throw sourcePagesRemain(id, Number(stranded.stranded));
if (!rows.length) return false;
await engine.executeRaw(`WITH ${removedSourceScrubCtes('NOT EXISTS (SELECT 1 FROM sources WHERE id = $1)')} SELECT 1`, [id]);
return true;
@@ -65,3 +87,10 @@ export function removedSourceScrubCtes(gate: string): string {
SET retrieved_slugs = ARRAY(SELECT u.s FROM unnest(c.retrieved_slugs) WITH ORDINALITY AS u(s, n) WHERE ${elsewhere('u.s')} ORDER BY u.n)
WHERE $1 = ANY(c.source_ids) AND EXISTS (SELECT 1 FROM unnest(c.retrieved_slugs) AS r(s) WHERE NOT ${elsewhere('r.s')}) AND ${gate})`].join(',\n ');
}
+
+function sourcePagesRemain(id: string, n: number) {
+ return opError('source_pages_remain', `Deleting source '${id}' would leave ${n} page(s) with no source row, so nothing was deleted.`,
+ `The database would not cascade the delete of source '${id}' to its ${n} page(s): the pages -> sources foreign key on this brain is missing, does not cascade or is disabled. `
+ + `The source and its pages are unchanged. Keep the source (if it is archived, gbrain sources restore ${id} makes it active again) and give the brain host's operator the output of the command in fix.`,
+ { fix: { ...readFix('Reports the brain\'s schema and health, read-only.', { argv: ['gbrain', 'doctor', '--json'] }), actor: 'host_admin' } });
+}
diff --git a/test/agent-session-speaker-8064.serial.test.ts b/test/agent-session-speaker-8064.serial.test.ts
index 59819c5ac7..0edf37ec18 100644
--- a/test/agent-session-speaker-8064.serial.test.ts
+++ b/test/agent-session-speaker-8064.serial.test.ts
@@ -152,6 +152,56 @@ describe('hook banking with a session speaker', () => {
});
});
+describe('#8080 speaker notes: first record wins, a differing speaker is reported', () => {
+ const ws = () => { const w = join(tmp, 'ws'); mkdirSync(w, { recursive: true }); return w; };
+ const end = (env: Record<string, string>, ancestry: AncestorProcess[], sid = 's-agent', more: { role: 'user' | 'assistant'; text: string }[] = []) => {
+ const t = writeTurns([{ role: 'user', text: BRIEF }, { role: 'assistant', text: 'ok' }, ...more]);
+ return runHook(['session-end'], { ...io, transcriptRoot: t.root, env, processAncestry: () => ancestry,
+ stdin: JSON.stringify({ session_id: sid, transcript_path: t.path, cwd: ws() }) });
+ };
+ const last = async () => { const hb = (await readHeartbeatTail(1))[0]; return [hb?.outcome, hb?.reason]; };
+
+ test('the owner resuming an agent session banks as before and notes speaker_mismatch; the sidecar stays', async () => {
+ writeConfig();
+ await end({ GBRAIN_SESSION_AGENT: 'fleet-worker' }, []);
+ expect((await last())[1]).not.toBe('speaker_mismatch');
+ await end({}, [ORCH]);
+ expect(await last()).toEqual(['degraded', 'speaker_mismatch']);
+ expect(readSpeakerSidecar(corpus(), 's-agent')).toMatchObject({ principal: 'fleet-worker', source: 'env' });
+ expect(files().some((f) => f.startsWith('s-agent') && f.endsWith('.txt'))).toBe(true);
+ });
+
+ test('a different agent label notes speaker_mismatch and keeps the first record', async () => {
+ writeConfig();
+ await end({ GBRAIN_SESSION_AGENT: 'fleet-worker' }, []);
+ await end({ GBRAIN_SESSION_AGENT: 'other-worker' }, []);
+ expect(await last()).toEqual(['degraded', 'speaker_mismatch']);
+ expect(readSpeakerSidecar(corpus(), 's-agent')?.principal).toBe('fleet-worker');
+ });
+
+ test('an agent continuing a session the owner already banked banks nothing and notes speaker_mismatch', async () => {
+ writeConfig();
+ await end({}, [ORCH]);
+ expect(readSpeakerSidecar(corpus(), 's-agent')).toBeNull();
+ const banked = files().filter((f) => f.startsWith('s-agent') && f.endsWith('.txt'));
+ expect(banked.length).toBeGreaterThan(0);
+ await end({}, [WORKER, SHELL, ORCH], 's-agent', [{ role: 'user', text: 'continue the sweep' }, { role: 'assistant', text: 'done' }]);
+ expect(await last()).toEqual(['degraded', 'speaker_mismatch']);
+ expect(readSpeakerSidecar(corpus(), 's-agent')).toBeNull();
+ expect(files().filter((f) => f.startsWith('s-agent') && f.endsWith('.txt'))).toEqual(banked);
+ });
+
+ test('GBRAIN_SESSION_AGENT=owner still saves as the owner, and notes a session detection finds agent-launched', async () => {
+ writeConfig();
+ await end({ GBRAIN_SESSION_AGENT: 'owner' }, [WORKER, SHELL, ORCH]);
+ expect(await last()).toEqual(['degraded', 'speaker_owner_override_detected']);
+ expect(readSpeakerSidecar(corpus(), 's-agent')).toBeNull();
+ expect(files().some((f) => f.startsWith('s-agent') && f.endsWith('.txt'))).toBe(true);
+ await end({ GBRAIN_SESSION_AGENT: 'owner' }, [ORCH], 's-own');
+ expect((await last())[1]).toBeUndefined();
+ });
+});
+
describe('#8028 user-prompt skips harness prompts', () => {
for (const prompt of ['<task-notification>\n<task-id>t1</task-id> done</task-notification>', ' <teammate-message from="lead">rebase now</teammate-message>']) {
test('no turn context for ' + prompt.trim().slice(0, 20), async () => {
diff --git a/test/corpus-source-holds-7849.test.ts b/test/corpus-source-holds-7849.test.ts
new file mode 100644
index 0000000000..f1181bc081
--- /dev/null
+++ b/test/corpus-source-holds-7849.test.ts
@@ -0,0 +1,105 @@
+/**
+ * #7849: synthesis corpus holds after #7805.
+ *
+ * 1. Dream discovery walks the session corpus recursively for .txt and .md
+ * files, and routing holds every one of them that names no source on a
+ * multi-source brain (corpus_legacy_unstamped). The operator mapping
+ * (gbrain sweep --assign-corpus) listed only top-level .txt files, so a
+ * .md note or a file in a nested folder could never be released.
+ * 2. Only corpus_legacy_unstamped and corpus_source_unresolved holds are
+ * released by the mapping (it fills only records naming no source); every
+ * other reason prints its own fix.
+ * 3. Doctor counts the sessions dream synthesis holds, already-swept ones
+ * included, as the mapping does.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { assignCorpusSessions, listCorpusSourceHolds } from '../src/core/context/corpus-source.ts';
+import { corpusFileOwner, refuseChangedSessionSource, withSessionSourceRouting } from '../src/core/cycle/synthesize-source-routing.ts';
+import { ensureCorpusSpoolDir, sessionCorpusFileName } from '../src/core/context/corpus-segments.ts';
+import { buildMemoryWritebackCheck } from '../src/commands/doctor/checks/memory-writeback.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+const dirs: string[] = [];
+const scratch = (tag: string) => { const dir = mkdtempSync(join(tmpdir(), tag)); dirs.push(dir); return dir; };
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('source-a','source-a')");
+}, 120_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
+});
+
+const transcript = '[user]\nwe keep the quarterly plan in one place.\n\n[assistant]\nNoted.\n';
+
+describe('#7849 held corpus files beyond top-level .txt', () => {
+ test('a .md note and a nested file routing holds are listed by the operator mapping, which releases them', async () => {
+ const corpus = join(scratch('gbrain-holds-7849-'), 'corpus');
+ mkdirSync(join(corpus, 'meetings'), { recursive: true });
+ const note = join(corpus, 'planning-notes.md');
+ const nested = join(corpus, 'meetings', 'standup-example.txt');
+ writeFileSync(note, transcript);
+ writeFileSync(nested, transcript);
+
+ for (const file of [note, nested]) expect(await corpusFileOwner(engine, file, corpus)).toEqual({ ok: false, reason: 'corpus_legacy_unstamped' });
+ const holds = listCorpusSourceHolds(corpus, false, { includeIngested: true });
+ expect(holds).toMatchObject({ legacy_unstamped: 2, sessions: ['planning-notes.md', 'standup-example'] });
+
+ expect(assignCorpusSessions(corpus, holds.sessions, 'source-a')).toEqual(['planning-notes.md', 'standup-example']);
+ for (const file of [note, nested]) expect(await corpusFileOwner(engine, file, corpus)).toMatchObject({ ok: true, sourceId: 'source-a' });
+ expect(listCorpusSourceHolds(corpus, false, { includeIngested: true }).sessions).toEqual([]);
+ });
+});
+
+describe('#7849 each hold reason prints its own fix', () => {
+ const route = (held: Record<string, number>) => withSessionSourceRouting({ phase: 'synthesize', status: 'ok', duration_ms: 0, summary: 'done', details: {} },
+ { corpus_source_other: {}, held }, 'source-a').details.source_routing as { fix: string[] };
+
+ test('archived and re-created sources never print the mapping, which releases nothing for them', () => {
+ expect(route({ corpus_source_archived: 1 }).fix).toEqual(['gbrain sources archived', 'gbrain sources restore <archived-source>']);
+ expect(route({ corpus_source_incarnation_changed: 1 }).fix).toEqual([]);
+ expect(route({ corpus_source_archived: 1, corpus_source_incarnation_changed: 2 }).fix.join(' ')).not.toContain('--assign-corpus');
+ });
+
+ test('a queued synthesis child whose session source was archived names the restore, not the mapping', async () => {
+ await engine.executeRaw("INSERT INTO sources(id,name,archived) VALUES('source-archived','source-archived',true)");
+ const corpus = join(scratch('gbrain-holds-refuse-7849-'), 'corpus');
+ const file = join(ensureCorpusSpoolDir(corpus), sessionCorpusFileName('sess-archived', 'source-archived'));
+ writeFileSync(file, transcript);
+ const refusal = await refuseChangedSessionSource(engine, { corpus_source: { raw_source: file, corpus_dir: corpus, incarnation: 'x' }, source_id: 'source-archived' })
+ .then(() => null, (error: Error) => error.message);
+ expect(refusal).toContain('session_source_changed: corpus_source_archived');
+ expect(refusal).toContain('It synthesizes after gbrain sources restore <archived-source>.');
+ expect(refusal).not.toContain('--assign-corpus');
+ });
+
+ test('held sessions with no source keep the mapping, once', () => {
+ expect(route({ corpus_legacy_unstamped: 1, corpus_source_unresolved: 1, corpus_source_archived: 1 }).fix)
+ .toEqual(['gbrain sweep --assign-corpus <source>', 'gbrain sources archived', 'gbrain sources restore <archived-source>']);
+ });
+});
+
+describe('#7849 doctor counts what dream synthesis holds', () => {
+ test('a legacy file the sweep already extracted is still counted as held', async () => {
+ const home = scratch('gbrain-holds-doctor-7849-');
+ const corpus = join(home, '.gbrain', 'transcripts', 'corpus');
+ mkdirSync(corpus, { recursive: true });
+ writeFileSync(join(corpus, 'sess-extracted.txt'), transcript);
+ writeFileSync(join(corpus, 'sess-extracted.txt.ingested'), '{}\n');
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ const check = await buildMemoryWritebackCheck(engine);
+ expect(check.details?.corpus_source_holds).toEqual({ legacy_unstamped: 1, unresolved: 0, sessions: 1 });
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('gbrain sweep --assign-corpus <source>');
+ });
+ });
+});
diff --git a/test/grandfather-managed.test.ts b/test/grandfather-managed.test.ts
index 675deb6e26..a85b814e4f 100644
--- a/test/grandfather-managed.test.ts
+++ b/test/grandfather-managed.test.ts
@@ -24,6 +24,9 @@ import { durableGitRepo, git } from './helpers/git-publication.ts';
import { localHostId } from '../src/core/persistence/identity.ts';
import { resolveRepairScope, runRepair } from '../src/core/repair/core.ts';
import { visibilityRepair } from '../src/core/repair/visibility.ts';
+import { terminalFailuresCheck } from '../src/commands/doctor/checks/persistence-requests.ts';
+import { readTerminalFailures } from '../src/core/persistence/terminal-failures.ts';
+import { classifyTerminal } from '../src/core/persistence/terminal-classify.ts';
type FixtureOptions = { databaseUrl?: string; setup?: (f: { engine: BrainEngine; root: string }) => Promise<void> };
async function fixture(run: (f: { engine: BrainEngine; ctx: OperationContext; home: string; root: string; slug: string }) => Promise<void>,
@@ -75,6 +78,36 @@ async function queuedGrandfatherEndsWithoutWriting(databaseUrl?: string) {
}
test('a queued managed_grandfather request ends in conflict without writing', () => queuedGrandfatherEndsWithoutWriting(), 120_000);
+
+// #7837: doctor reads the refused grandfather receipt as history with a "retired grandfather, nothing to do" note, also
+// after compaction nulls its intent and message, instead of generic revision_conflict advice to resubmit.
+test('doctor persistence_terminal_failures reads a retired grandfather receipt as history, before and after compaction', () => fixture(async ({ engine, ctx, slug }) => {
+ const before = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;
+ const authority = await submissionAuthority(ctx, 'put_page', 'default', before.sourceIncarnation, slug);
+ const binding = await getWorktreeBinding(engine, 'default');
+ const request = await admitWrite(engine, { principal: await requestPrincipalForContext(ctx), operation: 'put_page', sourceId: 'default', sourceIncarnation: before.sourceIncarnation,
+ pageId: before.page.id, slug, requestId: randomUUID(), authority, callerIntent: { migration: '0.13.1', expected_revision: before.revision },
+ intent: { kind: 'managed_grandfather', expected_revision: before.revision }, worktreeId: binding?.worktree_id, topologyGeneration: binding?.topology_generation });
+ await waitForWrite(engine, request, ctx.config, 30_000).catch(() => undefined);
+ expect(await engine.executeRaw('SELECT state,error_code,error_detail->>\'origin\' AS origin FROM persistence_requests WHERE request_id=$1::uuid', [request.request_id]))
+ .toEqual([{ state: 'conflict', error_code: 'revision_conflict', origin: 'grandfather_retired' }]);
+ const expectHistory = async () => {
+ const check = (await terminalFailuresCheck(engine))!;
+ expect(check).toMatchObject({ status: 'ok', details: { unresolved: { rows: 0, distinct_slugs: 0 }, historical_rows: 1 } });
+ expect(check.message).toContain('Historical: 1 row(s)');
+ const listing = await readTerminalFailures(engine, { sourceId: 'default', state: 'all' });
+ expect(listing.status === 'ok' && listing.rows?.map(row => [row.request_id, row.category, row.historical, row.safe_actions])).toEqual([[request.request_id, 'retired_operation', true, ['none']]]);
+ const verdict = classifyTerminal({ source_id: 'default', slug, operation: 'put_page', state: 'conflict', error_code: 'revision_conflict', error_detail: { origin: 'grandfather_retired' },
+ recovery: null, blocked_reason: null, compacted: true, request_id: request.request_id })!;
+ expect(verdict.action.why).toContain('Retired grandfather, nothing to do');
+ };
+ await expectHistory();
+ await engine.transaction(async tx => {
+ await declarePersistenceProtocol(tx);
+ await tx.executeRaw('UPDATE persistence_requests SET intent=NULL,error_message=NULL,compacted=true WHERE request_id=$1::uuid', [request.request_id]);
+ });
+ await expectHistory();
+}), 120_000);
test.skipIf(!process.env.DATABASE_URL)('Postgres: a queued managed_grandfather request ends in conflict without writing',
() => queuedGrandfatherEndsWithoutWriting(process.env.DATABASE_URL), 120_000);
diff --git a/test/openclaw-compact-transcript-runtime.serial.test.ts b/test/openclaw-compact-transcript-runtime.serial.test.ts
index 9fbdf690b2..12e421dd53 100644
--- a/test/openclaw-compact-transcript-runtime.serial.test.ts
+++ b/test/openclaw-compact-transcript-runtime.serial.test.ts
@@ -16,6 +16,7 @@ import {
createGBrainContextEngine,
} from '../src/core/context-engine.ts';
import { OPENCLAW_COMPACT_EVENT, readHeartbeatTail } from '../src/core/context/hook-heartbeat.ts';
+import { readSpeakerSidecar } from '../src/core/context/session-speaker.ts';
const event = (type: string, extra: Record<string, unknown> = {}) => ({ type, timestamp: '2026-10-01T10:00:00Z', ...extra });
const message = (text: string) => event('message', { id: crypto.randomUUID(), message: { role: 'user', content: [{ type: 'text', text }] } });
@@ -108,4 +109,13 @@ describe('compact() through the host session-transcript-runtime (#6316)', () =>
const engine = createGBrainContextEngine({ workspaceDir: workspace });
expect(checkpoint(await engine.compact({ sessionId: 'oc-e', sessionTarget: target } as never))).toEqual({ status: 'skipped', reason: 'unparseable' });
});
+
+ it('#8080: a sub-agent session is marked as the agent\'s before its segment is banked; a main session is not', async () => {
+ __setTranscriptRuntimeLoaderForTests(async () => ({ readSessionTranscriptEvents: async () => [event('session', { id: 'oc-sub' }), message('Parent brief for the worker')] }));
+ const engine = createGBrainContextEngine({ workspaceDir: workspace });
+ expect(checkpoint(await engine.compact({ sessionId: 'oc-sub', sessionTarget: { ...target, sessionId: 'oc-sub', sessionKey: 'agent:main:subagent:1f2e3d4c' } } as never))).toMatchObject({ status: 'banked' });
+ expect(checkpoint(await engine.compact({ sessionId: 'oc-main', sessionTarget: { ...target, sessionId: 'oc-main' } } as never))).toMatchObject({ status: 'banked' });
+ expect(readSpeakerSidecar(spool(), 'oc-sub')).toMatchObject({ principal: 'agent-launched', source: 'detected', harness: 'openclaw' });
+ expect(readSpeakerSidecar(spool(), 'oc-main')).toBeNull();
+ });
});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 41010b473e..d09aaeca55 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -589,6 +589,7 @@ test/shared-skills-retention-capacity.test.ts
test/shared-skills-source-opt-out.test.ts
test/shared-skills-writer-boundary.test.ts
test/source-lifecycle-dry-run-physical-root-6849.test.ts
+test/source-purge-stranded-pages-7072.test.ts
test/source-retire-missing-checkout.test.ts
test/source-row-diagnostics.test.ts
test/sources-git-reconcile.test.ts
diff --git a/test/repair-agent-session-facts.test.ts b/test/repair-agent-session-facts.test.ts
index e1f8c2feac..ecb0cca9be 100644
--- a/test/repair-agent-session-facts.test.ts
+++ b/test/repair-agent-session-facts.test.ts
@@ -9,7 +9,8 @@
* rows in place; a fact/self take is retired only when every contributing fact is non-user; nothing is deleted; the
* apply is bound to the preview hash and flags; a fact edited since the preview is kept.
*/
-import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+import * as fs from 'node:fs';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -28,13 +29,18 @@ import { randomUUID } from 'node:crypto';
import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
import { managedBrain } from './helpers/managed-brain.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { __setMaintenanceWriteWaitForTests } from '../src/core/persistence/maintenance-wait.ts';
+import { getCliOptions, setCliOptions } from '../src/core/cli-options.ts';
+import { resolveRepairScope } from '../src/core/repair/core.ts';
+import { repairRunner } from '../src/core/repair/registry.ts';
const ALICE = 'people/alice-example';
const ACME = 'companies/acme-example';
const BRIEF = 'You are worker agent seven for the release crew. Read the brief below, follow the repository rules, keep commits small, '
+ 'and report back to the coordinator with a summary of what changed and what is still open.';
-interface RepairJson { results: Array<{ affected: number; residuals: Record<string, number>; apply_command: string; applied: number;
+interface RepairJson { results: Array<{ affected: number; preview_hash?: string; residuals: Record<string, number>; apply_command: string; applied: number;
listing?: Array<{ item: string; class: string; detail?: string }>; outcomes?: Record<string, number> }> }
async function repair(engine: BrainEngine, args: string[]): Promise<RepairJson> {
@@ -212,6 +218,20 @@ describe('gbrain repair agent-session-facts, unmanaged repo-less brain', () => {
expect(await takeActive(engine, ownerTake)).toBe(true);
});
+ test('one apply run walks the session corpus once, however many pages it re-attributes (#8080)', async () => {
+ const ids: number[] = [];
+ for (const entity of [ALICE, ACME, 'people/bob-example']) ids.push(await insert(`Prefers terse status updates on ${entity}`, 'sess-sidecar', { entity }));
+ const preview = await repair(engine, []);
+ expect(preview.results[0].residuals).toMatchObject({ evidenced: 3 });
+ const walks = spyOn(fs, 'readdirSync');
+ try {
+ const applied = await repair(engine, applyArgs(preview));
+ expect(applied.results[0].outcomes).toEqual({ reattributed: 3 });
+ expect(walks.mock.calls.filter(([dir]) => dir === corpus).length).toBe(1);
+ } finally { walks.mockRestore(); }
+ for (const id of ids) expect(await attribution(engine, id)).toMatchObject({ attributed_to: 'other', context: speakerContextNote('worker-a'), active: true });
+ }, 120_000);
+
test('a fact edited after the preview reports changed_since_preview and keeps its attribution', async () => {
const id = await insert('Prefers tea', 'sess-sidecar');
const preview = await repair(engine, []);
@@ -283,4 +303,65 @@ describe('gbrain repair agent-session-facts, managed repo-less brain', () => {
} });
} finally { rmSync(base, { recursive: true, force: true }); }
}, 180_000);
+
+ /** Holds the first publication `ms` and makes maintenance publishes report pending at once, so a database-only write stays accepted and pending. */
+ const slowFirstPublication = (ms: number) => {
+ let seen = 0;
+ installFaultHook(async point => { if (point === 'consumer:prepared' && seen++ === 0) await new Promise(resolve => setTimeout(resolve, ms)); });
+ restoreWait = __setMaintenanceWriteWaitForTests(0);
+ };
+ let restoreWait: (() => void) | undefined;
+ afterEach(() => { installFaultHook(undefined); restoreWait?.(); restoreWait = undefined; });
+
+ test('a database-only write still pending does not skip the fenced rows of its page (#8080)', async () => {
+ const base = mkdtempSync(join(tmpdir(), 'gbrain-agent-session-pending-'));
+ try {
+ const { corpus } = corpusFixture(base);
+ await managedBrain(async ({ engine }) => {
+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpus);
+ const fenced = (await writeSingleFact(engine, 'default', { fact: 'Alice Example prefers terse status updates', entity: ALICE, provenance: 'hook:writeback', sessionId: 'sess-sidecar' })).id;
+ const dbOnly = await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => Number((await tx.executeRaw<{ id: number }>(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, source_session, attributed_to)
+ VALUES ('default', $1, 'Alice Example dislikes long meetings', 'preference', 'private', 'hook:writeback', 'sess-sidecar', 'user') RETURNING id`, [ALICE]))[0]!.id),
+ TEST_WRITE_ATTRIBUTION));
+ expect((await engine.executeRaw<{ row_num: number | null }>('SELECT row_num FROM facts WHERE id=$1', [dbOnly]))[0]!.row_num).toBeNull();
+ const preview = await repair(engine, []);
+ expect(classes(preview)).toEqual({ [fenced]: 'evidenced', [dbOnly]: 'evidenced' });
+ slowFirstPublication(1_500);
+ await repair(engine, applyArgs(preview));
+ for (const id of [fenced, dbOnly]) expect(await attribution(engine, id)).toMatchObject({ attributed_to: 'other', active: true });
+ expect((await engine.readPageSnapshot(ALICE, { sourceId: 'default' }))!.page.compiled_truth).toContain(speakerContextNote('worker-a'));
+ expect((await agentSessionFactsCheck(engine)).status).toBe('ok');
+ }, { setup: async ({ engine, root }) => { await seedEntity(engine, root, ALICE, 'Alice Example', 'person'); } });
+ } finally { rmSync(base, { recursive: true, force: true }); }
+ }, 180_000);
+
+ test('a resumed apply reports rows its accepted request already re-attributed as reattributed, not changed since the preview (#8080)', async () => {
+ const base = mkdtempSync(join(tmpdir(), 'gbrain-agent-session-resume-'));
+ try {
+ const { corpus } = corpusFixture(base);
+ await managedBrain(async ({ engine }) => {
+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpus);
+ const dbOnly = (await writeSingleFact(engine, 'default', { fact: 'Carol Absent dislikes long meetings', entity: 'Carol Absent', provenance: 'hook:writeback', sessionId: 'sess-sidecar' })).id;
+ const preview = await repair(engine, []);
+ expect(classes(preview)).toEqual({ [dbOnly]: 'evidenced' });
+ const scope = await resolveRepairScope(engine);
+ const run = { explicit: true, expect: preview.results[0].preview_hash! };
+ const quiet = { info() {}, warn() {}, error() {} };
+ slowFirstPublication(1_500);
+ const previous = getCliOptions();
+ setCliOptions({ ...previous, writeWaitMs: 0 });
+ let first;
+ try { first = await (await repairRunner(engine, { apply: true, noEmbed: true, logger: quiet })).run('agent-session-facts', scope, run); }
+ finally { setCliOptions(previous); }
+ expect(first.stopped?.reason).toBe('write_pending');
+ const until = Date.now() + 15_000;
+ while ((await attribution(engine, dbOnly)).attributed_to !== 'other' && Date.now() < until) await new Promise(resolve => setTimeout(resolve, 100));
+ expect((await attribution(engine, dbOnly)).attributed_to).toBe('other');
+ const resumed = await (await repairRunner(engine, { apply: true, noEmbed: true, logger: quiet })).run('agent-session-facts', scope, run);
+ expect(resumed.outcomes).toEqual({ reattributed: 1 });
+ expect(resumed.stopped).toBeUndefined();
+ });
+ } finally { rmSync(base, { recursive: true, force: true }); }
+ }, 180_000);
});
diff --git a/test/source-purge-stranded-pages-7072.test.ts b/test/source-purge-stranded-pages-7072.test.ts
new file mode 100644
index 0000000000..d54708105e
--- /dev/null
+++ b/test/source-purge-stranded-pages-7072.test.ts
@@ -0,0 +1,83 @@
+/**
+ * #7072: a source delete never leaves live pages behind with no `sources` row.
+ *
+ * Every source delete removes the source's pages through the pages -> sources
+ * ON DELETE CASCADE foreign key. On a brain where that cascade does not run (the
+ * foreign key is missing), the expired-archive purge used to delete the sources
+ * row anyway and leave every page of the source live, unwritable and outside
+ * every per-source audit (`extract links` then reports them as
+ * `skipped_unknown_source`). The purge now refuses that source with
+ * `source_pages_remain` and changes nothing; a brain whose cascade runs still
+ * purges as before. (A managed remove or purge deletes the pages itself in
+ * bounded batches before the source row, so it never relies on the cascade.)
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { purgeExpiredSources, softDeleteSource } from '../src/core/destructive-guard.ts';
+import { deleteSourceRow } from '../src/core/source-delete.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const databaseUrl = process.env.DATABASE_URL;
+
+async function dropPagesSourceForeignKey(engine: BrainEngine): Promise<void> {
+ const rows = await engine.executeRaw<{ conname: string }>(
+ `SELECT conname FROM pg_constraint WHERE contype = 'f' AND conrelid = 'pages'::regclass AND confrelid = 'sources'::regclass`);
+ for (const { conname } of rows) await engine.executeRaw(`ALTER TABLE pages DROP CONSTRAINT "${conname}"`);
+}
+
+async function seedExpiredArchive(engine: BrainEngine, id: string, pages: number): Promise<void> {
+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1)', [id]);
+ for (let i = 0; i < pages; i++) {
+ await engine.executeRaw(`INSERT INTO pages (source_id, slug, type, title) VALUES ($1, $2, 'note', $2)`, [id, `notes/page-${i}`]);
+ }
+ await softDeleteSource(engine, id);
+ await engine.executeRaw(`UPDATE sources SET archive_expires_at = now() - interval '1 hour' WHERE id = $1`, [id]);
+}
+
+const count = async (engine: BrainEngine, sql: string, id: string) =>
+ Number((await engine.executeRaw<{ n: string }>(sql, [id]))[0]!.n);
+const sourceRows = (engine: BrainEngine, id: string) => count(engine, 'SELECT count(*)::text AS n FROM sources WHERE id = $1 AND archived', id);
+const pageRows = (engine: BrainEngine, id: string) => count(engine, 'SELECT count(*)::text AS n FROM pages WHERE source_id = $1 AND deleted_at IS NULL', id);
+
+for (const flavor of ['pglite', ...(databaseUrl ? ['postgres'] : [])] as const) {
+ describe(`#7072 source delete without a pages cascade (${flavor})`, () => {
+ let engine: BrainEngine;
+ let closePostgres: (() => Promise<void>) | undefined;
+
+ beforeAll(async () => {
+ if (flavor === 'postgres') ({ engine, close: closePostgres } = await isolatedPersistencePostgres(databaseUrl!));
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
+ }, 180_000);
+
+ afterAll(async () => {
+ if (!engine) return;
+ await disposePersistenceConsumer(engine);
+ if (closePostgres) await closePostgres();
+ else await engine.disconnect();
+ });
+
+ test('a healthy brain still purges the expired archive with its pages', async () => {
+ await seedExpiredArchive(engine, 'source-a', 2);
+ const { purged, blocked } = await purgeExpiredSources(engine);
+ expect({ purged, blocked }).toEqual({ purged: ['source-a'], blocked: [] });
+ expect(await count(engine, 'SELECT count(*)::text AS n FROM pages WHERE source_id = $1', 'source-a')).toBe(0);
+ });
+
+ test('unmanaged: the expired-archive purge refuses the source and keeps its pages and row', async () => {
+ await dropPagesSourceForeignKey(engine);
+ await seedExpiredArchive(engine, 'source-b', 3);
+ await seedExpiredArchive(engine, 'source-c', 0);
+ const { purged, blocked } = await purgeExpiredSources(engine);
+ expect(purged).toEqual(['source-c']);
+ expect(blocked.map(b => [b.id, b.code, b.fix?.command])).toEqual([['source-b', 'source_pages_remain', 'gbrain doctor --json']]);
+ expect(blocked[0]!.reason).toContain('3 page(s)');
+ expect(await sourceRows(engine, 'source-b')).toBe(1);
+ expect(await pageRows(engine, 'source-b')).toBe(3);
+
+ await expect(deleteSourceRow(engine, 'source-b')).rejects.toMatchObject({ code: 'source_pages_remain' });
+ expect(await sourceRows(engine, 'source-b')).toBe(1);
+ });
+ });
+}
diff --git a/test/synthesize-session-speaker-8080.test.ts b/test/synthesize-session-speaker-8080.test.ts
new file mode 100644
index 0000000000..0dc7193705
--- /dev/null
+++ b/test/synthesize-session-speaker-8080.test.ts
@@ -0,0 +1,42 @@
+/**
+ * #8080 item 1: dream synthesis reads the speaker marker #8075 records for an
+ * agent-launched session, so the worker's brief is never synthesized as what
+ * the user said or requested. The facts pipeline's choice applies here too:
+ * the session is kept and labeled as the agent's, not skipped.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { discoverTranscripts, readSingleTranscript } from '../src/core/cycle/transcript-discovery.ts';
+import { __testing } from '../src/core/cycle/synthesize.ts';
+import { ensureCorpusSpoolDir, sessionCorpusFileName } from '../src/core/context/corpus-segments.ts';
+import { writeSpeakerSidecar } from '../src/core/context/session-speaker.ts';
+
+const corpus = mkdtempSync(join(tmpdir(), 'gbrain-synth-speaker-8080-'));
+afterAll(() => rmSync(corpus, { recursive: true, force: true }));
+const body = (topic: string) => `[user]\nPlease draft the release notes for ${topic}.\n\n${'[assistant]\nDrafting the notes now.\n\n'.repeat(10)}`;
+
+describe('#8080 synthesis labels an agent-launched session', () => {
+ const spool = ensureCorpusSpoolDir(corpus);
+ const worker = join(spool, sessionCorpusFileName('sess-worker', 'default'));
+ const owner = join(spool, sessionCorpusFileName('sess-owner', 'default'));
+ writeFileSync(worker, body('the worker task'));
+ writeFileSync(owner, body('the owner task'));
+ writeSpeakerSidecar(spool, 'sess-worker', { principal: 'build-bot', source: 'env' }, 'claude-code');
+
+ test('discovery carries the session speaker; an owner session has none', () => {
+ const found = new Map(discoverTranscripts({ corpusDir: corpus, minChars: 10 }).map(t => [t.filePath, t]));
+ expect(found.get(worker)?.speaker).toBe('build-bot');
+ expect(found.get(owner)?.speaker).toBeUndefined();
+ expect(readSingleTranscript(worker, { minChars: 10 })?.speaker).toBe('build-bot');
+ });
+
+ test("the synthesis prompt says the user turns are the agent's brief; an owner session's prompt is unchanged", () => {
+ const found = new Map(discoverTranscripts({ corpusDir: corpus, minChars: 10 }).map(t => [t.filePath, t]));
+ const prompt = (path: string) => __testing.buildSynthesisPrompt(found.get(path)!, found.get(path)!.content, 0, 1);
+ expect(prompt(worker)).toContain('- Speaker: this session was launched by the automated agent "build-bot"');
+ expect(prompt(worker)).toContain('attribute them to Agent build-bot');
+ expect(prompt(owner)).not.toContain('Speaker:');
+ });
+});
diff --git a/test/terminal-failures-6650.test.ts b/test/terminal-failures-6650.test.ts
index 9f99957c6e..a2779033a9 100644
--- a/test/terminal-failures-6650.test.ts
+++ b/test/terminal-failures-6650.test.ts
@@ -518,15 +518,18 @@ for (const kind of testBackends()) describe(`the aggregate, doctor and the drill
await seed({ slug: 'h6', operation: 'submit_job', state: 'cancelled', code: 'cancelled', detail: knock, build: 'dev-build' });
await seed({ slug: 'h7', operation: 'submit_job', state: 'failed', code: 'fence_unrenderable', message: 'The adopted fence row does not render its legacy fact.', build: '0.60.217.0' });
await seed({ slug: 'h8', operation: 'submit_job', state: 'failed', code: 'fence_unrenderable', message: 'The adopted fence row does not render its legacy fact.', build: '0.60.218.0' });
+ await seed({ slug: 'h9', state: 'conflict', code: 'revision_conflict', detail: { origin: 'grandfather_retired' }, compacted: true, build: '0.60.500.0' });
+ await seed({ slug: 'h9b', state: 'conflict', code: 'revision_conflict', kind: 'managed_grandfather', build: '0.60.500.0' });
+ await seed({ slug: 'h9c', state: 'conflict', code: 'revision_conflict', build: '0.60.500.0' });
const all = Object.values(TERMINAL_HISTORICAL_SQL).map(sql => sql('b')).join(' OR ');
const rows = await engine.executeRaw<{ slug: string; flag: boolean; state: string; error_code: string; error_message: string | null; error_detail: Record<string, unknown> | null; operation: string;
compacted: boolean; build: string | null }>(`SELECT b.*, (${all}) AS flag FROM (SELECT r.slug, r.state, r.error_code, r.error_message, r.error_detail, r.operation, r.compacted,
- r.error_detail->>'origin' AS origin, r.recovery IS NOT NULL AS has_recovery, ${terminalKnockOnSql('r')} AS knock_on,
+ r.error_detail->>'origin' AS origin, r.intent->>'kind' AS intent_kind, r.recovery IS NOT NULL AS has_recovery, ${terminalKnockOnSql('r')} AS knock_on,
CASE WHEN r.error_detail IS NULL AND r.error_message LIKE 'Publication failed (P0001)%' THEN 'Publication failed (P0001)' END AS routed_message,
COALESCE(r.error_detail->'attempt'->>'consumer_version', r.admitter_version) AS build FROM persistence_requests r) b ORDER BY b.slug`);
const ts = rows.map(row => [row.slug, classifyTerminal({ ...base, ...row, recovery: null, blocked_reason: null })!.historical]);
expect(rows.map(row => [row.slug, row.flag])).toEqual(ts as never);
- expect(ts).toEqual([['h1', true], ['h2', false], ['h3', true], ['h4', true], ['h5', false], ['h6', false], ['h7', true], ['h8', false]]);
+ expect(ts).toEqual([['h1', true], ['h2', false], ['h3', true], ['h4', true], ['h5', false], ['h6', false], ['h7', true], ['h8', false], ['h9', true], ['h9b', true], ['h9c', false]]);
});
test('the extracted supersession rule is the one failed-writes applies', async () => {