Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(repair): keep owner takes, never retire a fenced page's take in the database alone; windows-hide spawn seam, core-guard exemption, key-files placement; review follow-ups (#8064)

garrytan5554f7f5e156
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 93500588b7..f8f3af9389 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,7 +14,7 @@ identifiers and attribution are available in the pre-removal Git revision
**A launcher can now tell gbrain that a session's user turns are an agent's, not yours, so orchestrator worker briefs stop landing in your brain as your own preferences (#8064). Codex sessions that open and close with no prompt no longer raise a week-long parser_drift alert (#8016), and task notifications and agent-team messages no longer get brain context injected as if you typed them (#8028).**
-Set `GBRAIN_SESSION_AGENT=<label>` on a worker's process and the capture hooks still save the session, but every claim from its user turns is saved as `attributed_to: other` with the context note `speaker: agent <label>, not the owner`, and the extractor is told the agent wrote them. `GBRAIN_SESSION_AGENT=off` saves nothing from the session; `owner` declares the turns yours. With the variable unset, a headless `claude -p` or `codex exec` session whose ancestors include another claude or codex process is detected and saved as agent `agent-launched`'s. The marker is a `<session>.speaker.json` sidecar written before any corpus file; if it can't be written, nothing is saved. Agent claims are never consolidated into your own takes.
+Set `GBRAIN_SESSION_AGENT=<label>` on a worker's process and the capture hooks still save the session, but every claim from its user turns is saved as `attributed_to: other` with the context note `speaker: agent <label>, not the owner`, and the extractor is told the agent wrote them. `GBRAIN_SESSION_AGENT=off` saves nothing from the session; `owner` declares the turns yours. With the variable unset, a headless `claude -p` or `codex exec` session whose ancestors include another claude or codex process is detected and saved as agent `agent-launched`'s. The marker is a `<session>.speaker.json` sidecar written before any corpus file; if it can't be written, nothing is saved. Agent claims are never consolidated into your own takes. The marker covers the Claude Code and Codex hook lanes; the OpenClaw context-engine lane and dream synthesis don't read it yet.
For facts already saved as yours, `gbrain repair agent-session-facts` previews a re-attribution: facts from sessions with a speaker marker, sessions you name (`--session`), or sessions whose working directory sits under a path you name (`--cwd`, for an orchestrator's worktree root). Sessions whose first turn opens with the same 160 characters as at least 3 other sessions (a template brief) are listed as ambiguous and change only with `--include-ambiguous`. `--apply --expect <hash> --yes` sets exactly the previewed facts to `attributed_to: other` with the speaker note and retires the self takes consolidate built only from them. It deletes nothing, keeps a claim you also made in another session, and works on repo-less brains. `gbrain doctor` (`agent_session_facts`) counts the candidates, and `doctor --remediation-plan` lists the preview command.
diff --git a/docs/architecture/key-files/ambient-capture.md b/docs/architecture/key-files/ambient-capture.md
index 299cbb2924..11fbba7138 100644
--- a/docs/architecture/key-files/ambient-capture.md
+++ b/docs/architecture/key-files/ambient-capture.md
@@ -10,3 +10,5 @@ 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/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`.
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index c53208bb26..2f33645466 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -16,7 +16,6 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `src/commands/doctor/checks/extractor-facts.ts` — `extractor_facts_expired` (#5731): counts conversation-extractor facts the pre-v0.60.11.0 projection expired, by class (`evidenced`, `ambiguous`; `excluded` reported but never a finding) through `classifyExtractorFacts`, and names `gbrain repair extractor-facts` (explicit-only, so the remediation plan and banner list it with its preview). Read-only; health unknown when the query fails.
- `src/commands/doctor/checks/atom-retirements.ts` — `atom_retirements_restorable` (#7013, BRAIN, a `WAVE_CHECKS` entry with `resolution: 'repair'`, host-only, cleared by the explicit-only `atoms-restore`, so remediation classifies it `explicit_kind_required`): counts the `restorable` rows of `atomRetirementsSql` per source; `warn` names the count, origins, oldest and newest `retired_at`, the end of the earliest purge hold (`hold_until`) and the read-only preview `gbrain repair atoms-restore --source <id> --json` as an agent `fix`; the apply is the user's call.
- `src/commands/doctor/checks/conversation-outcomes.ts` — `conversation_label_facts` (wave check, host-only, resolution `repair`): bounded count (capped at 1000, reported as at least N) of the default set `gbrain repair conversation-labels` would retire; names the preview, never the apply. `conversation_outcomes_stale` (wave check, host-only, resolution `operator`): counts active conversation extraction outcomes stamped with an older `extractor_version` than `CONVERSATION_EXTRACTOR_VERSION` (outcomes are never reopened automatically) and names the `--force --dry-run` re-extract preview; outcomes older than the stamp are counted as `unstamped` and never warn. Bounded scan of the extractor rows, capped at 5000 (reported as at least N). Read-only.
-- `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/commands/doctor/checks/captured-facts.ts` — `captured_facts_active` (wave check, host-only): counts active capture-lane facts (`hook:writeback`, `hook:compact`, `sweep:corpus`) that `classifyCapturedFacts` classes as self-capture (`evidenced`) or paste candidates (`ambiguous`); `excluded` and `unclassifiable` are reported, never a finding. Names `gbrain repair captured-facts` (explicit-only) and says it counts facts while `self_capture` counts corpus files. Read-only; health unknown when the scan fails.
- `src/commands/doctor/checks/facts-redaction-marker.ts` — `facts_redaction_marker` (wave check, host-only, #7125): counts active facts of active sources whose text holds `[redacted` (one scan of active facts) and names the explicit-only `gbrain repair redacted-facts` preview. Read-only; health unknown when the count fails.
- `src/commands/doctor/checks/loop-facts.ts` — `loop_facts_drift` (#5869): counts closed commitment loops whose fact is still active and retirable (`loopFactDrift`) and names `gbrain repair loop-facts` (explicit-only). Read-only; health unknown when the query fails.
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index c57851c801..2cd46c69f3 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -11,7 +11,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/repair/extractor-facts.ts` — `gbrain repair extractor-facts` (#5731), explicit-only and preview-bound. `classifyExtractorFacts` (read-only; also the doctor check's count) takes conversation-extractor facts with `expired_at` set and `row_num` NULL and classes each: `excluded` (page missing or deleted, `superseded_by` set, withdrawn, an active same-text fact on the page, or an earlier same-text candidate), `ambiguous` (unmanaged brain; no committed request of the page with `completed_at = expired_at`, compared in SQL as microsecond UTC text, which only a same-transaction completion satisfies on Postgres; a consumer at or above v0.60.11.0; or the page has ever held fence-projected facts) or `evidenced`. The preview lists every candidate, hashes them with the selection (`--include-ambiguous`) and saves one approved item per page (with its request id) through `preview-approval.ts`; the apply loads only that set, replays a still-pending request with the ctx's CLI write wait, skips pages whose request already committed or whose facts are active again, and restores each still-identical fact with a fresh `row_num` above the page's facts and fence rows. Managed brains publish one database-only `managed_maintenance_restore_extractor_facts` request per page (`submitDatabaseMaintenanceIntent`, dispatched by `prepareMaintenanceMutation` to `prepareExtractorFactsRestore`, which reclassifies under the page lock); unmanaged brains run the same restore in one locked transaction. Previews warn, naming the host, when a consumer older than this release published after `writer_version_cutoff`. On PGLite `now()` has millisecond resolution, so the same-transaction rule is millisecond-exact there.
- `src/core/repair/conversation-labels.ts` — `gbrain repair conversation-labels`, explicit-only, preview-bound and destructive (consent payload from the registry's `consentText`). `classifyLabelFacts` (read-only) takes active per-segment extractor facts (`source` exactly `cli:extract-conversation-facts`) on live pages with a bold `METADATA_LABELS` line and classes each `excluded` (page outcome stamped with `extractor_version`, withdrawn, superseded, named by another fact's `superseded_by`, referenced by `open_loops.fact_id`), `evidenced` (context carries `segment 1970-01-01`) or `ambiguous`. The preview decides each page's outcome with the current parser at no cost (`non_extractable`, `awaiting_reextraction`, `cleaned`), hashes it all, saves one approved item per page and prints the capped hand-off (`extract-conversation-facts --slugs … --dry-run`, then `--max-cost-usd`). The apply expires the approved ids still as previewed (appending `retired: conversation-labels <hash>` to the context), expires the completion marker and writes the stamped not-extractable outcome for a page still at the previewed parser input; approved pages apply in batches of `LABEL_BATCH_PAGES` (25): one database-only `managed_maintenance_conversation_label_retire` request per batch on `LABELS_ANCHOR_SLUG` on a managed brain (`prepareConversationLabelRetirement`, every page key locked, each page rechecked), one transaction per batch otherwise. No model calls. Segmented pages are not classified (the label filter reads the body columns): their unstamped per-segment facts are counted as `segmented_pages` / `segmented_facts` and named in a warning. `countLabelFacts` is doctor `conversation_label_facts`' bounded count. Pinned by `test/repair-conversation-labels.test.ts` (+ Postgres arm) and `test/conversation-facts-retained-history.test.ts`.
- `src/core/repair/captured-facts.ts` — `gbrain repair captured-facts`, explicit-only and preview-bound. `classifyCapturedFacts` (read-only; also the `captured_facts_active` count) takes active capture-lane facts and classes each by its session (`captureSessionId`: `sweep:corpus:<file>` resolves through `corpusFileSessionId`): `evidenced` when a gbrain claude-cli scratch project holds the session's harness transcript or its corpus file sits in `<corpus>.quarantine/`; `ambiguous` (paste candidate) when a retained corpus file of the session holds a paste block and at least 60% of the claim's content words occur there only inside paste blocks; `excluded:legitimate_duplicate` when the claim and entity also have an active row that is not proven suspect. Sessions with no transcript and no corpus file are counted `unclassifiable`. The preview hashes every candidate with the selection (`--include-ambiguous`) and saves one approved item per page through `preview-approval.ts`; the apply reclassifies each fact, expires database-only rows through one database-only `managed_maintenance_expire_captured_facts` request per page on a managed brain (owner-checked by `maintenancePreflight`; `prepareCapturedFactsExpiry`, dispatched from `prepareMaintenanceMutation`) or one transaction on an unmanaged brain, and strikes fenced rows in the page's `## Facts` fence through one revision-bound `put_page`, so the canonical projection expires them and a later page write cannot reactivate them. No withdrawal is recorded, so `remember` can save the same claim again. Pinned by `test/repair-captured-facts.test.ts` (+ Postgres arm).
-- `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/redacted-facts.ts` — `gbrain repair redacted-facts` (#7125), explicit-only and preview-bound. `classifyRedactedFacts` (read-only) takes active facts whose text holds a redaction marker and runs `restoreNeutralized` (`think/sanitize.ts`, with the pre-fix `LEGACY_EVAL_SHELL` shape) against the page the fact's context names and the page holding it (`pageTexts`: an inline page's body + timeline, a segmented page's body through `readBodyRange` up to 16 MiB, then up to 50 `page_versions` bodies): `evidenced` when every proving text proves the same restoration, `ambiguous` (`conflicting_sources`) when a text holds two spans around the words or texts disagree, `unproven` (`no_source_page` / `not_in_source`) otherwise. A proved fenced row on a segmented page is `segmented` (`segmented_page`): listed with its restoration, never rewritten (`restoreFencedRows` reads and publishes inline bodies only). The preview hashes every candidate with its restoration and saves one approved item per page; the apply reclassifies each fact, rewrites database-only rows through one database-only `managed_maintenance_restore_redacted_facts` request per page on a managed brain (`prepareRedactedFactsRestore`, dispatched from `prepareMaintenanceMutation`) or one transaction on an unmanaged brain (exact-text compare-and-set; context gets `restored: redacted-facts repair`), and rewrites fenced rows' claims in the page's `## Facts` fence through one revision-bound `put_page`, so the canonical projection replaces the row. Pinned by `test/repair-redacted-facts.test.ts` (+ Postgres arm).
- `src/core/repair/loop-facts.ts` — `gbrain repair loop-facts` (#5869), explicit-only and preview-bound (`--apply --expect <hash>`): candidates are `loopFactDrift` rows (closed `done`/`dropped` loops whose commitment fact is active, in the loop's source and shared with no open loop); each item is rechecked (`changed_since_preview`) and retired through `retireLoopFact`, the same coordinated strike-plus-expire publication `loops_close` uses.
- `src/core/repair/failed-writes.ts` — `gbrain repair failed-writes` (#5983), explicit-only and preview-bound: candidates are failed, uncompacted `persistence_requests` refused by the managed writer guard (`writer_coordinator_required`, or `storage_error` "Publication failed (P0001)"). Caller writes (`put_page` without an internal `kind`, `add_timeline_entry`, `remember`) are classified `replay` / `already_written` / `duplicate` / `superseded` / `unpinned_target` by later requests on the same page and by a committed replay request id, and `file_database_drift` (W4.11) when its last replay attempt was refused `source_changed` and the page has not been written since (`lastFailedAttempt`; the detail and an apply's `file_database_drift` outcome name `gbrain sources reconcile <source> <slug> --preview`; `test/repair-failed-writes-drift-w411.test.ts`); owner-produced writes are `producer_owned` residuals with the producer command (a failed `managed_file_repair` names both `gbrain repair frontmatter` and `gbrain repair fences`). #7602 fact rows: `factsRecovery` ([Facts](core-persistence-facts.md)). The approved set records each target page's revision. Apply resumes an admitted replay attempt, otherwise reclassifies and rechecks the revision, re-runs `authorizeStoredRequest` on the failed row, and resubmits the retained intent on the original trust lane (`laneContext`: remote, take holders, delegated prefixes) through `submitPageMutation` / `submitRememberMutation`, with `put_page` bound to the previewed revision and `remember` pinned to its resolved subject, under a request id derived from the failed request id and attempt (`repair-failed-writes-5983.test.ts`). #5994: `laneContext` sets `ctx.replayAuthority` to the stored authority, so admission (`submissionAuthority` → `replayedAuthority` in `persistence/authority.ts`, and `requestPrincipalForContext`) reuses its principal, delegation, scopes and autoLinkTrusted for the same source incarnation and re-authorizes it live; a restricted write gets back its recorded job (`delegatedJobId`, or the id in a single legacy `wiki/agents/<id>/*` prefix, replayed on the legacy sandboxed path when its original was), and one with neither is accepted by `enforceSubagentSlugFence` (`ops/context.ts`) only through that marker with the exact non-empty stored allow-list. The fence still fails closed for every live dispatch. A put_page replay passes the stored `timeline_section` (#5969). The superseded / already-written / duplicate rule lives in `persistence/terminal-classify.ts`, shared with the #6650 terminal-failure readers.
diff --git a/docs/guides/ambient-writeback.md b/docs/guides/ambient-writeback.md
index b57cf25606..eadf5499d7 100644
--- a/docs/guides/ambient-writeback.md
+++ b/docs/guides/ambient-writeback.md
@@ -311,8 +311,13 @@ as agent-launched when its harness process runs headless (`claude -p` or
`--print`, `codex exec`) and another `claude` or `codex` process is one of
its ancestors. Its claims are saved as agent `agent-launched`'s. A headless
session you start yourself from a terminal is still yours. Detection reads the
-process table and can miss a launcher that detaches its workers, so set the
-variable in any launcher you control.
+process table and can miss a launcher that detaches its workers, and it never
+fires for a launcher that is not itself claude or codex (a cron job, a script
+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.
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
diff --git a/scripts/check-core-guard-coverage.mjs b/scripts/check-core-guard-coverage.mjs
index 672ff1a33b..e7db22a635 100644
--- a/scripts/check-core-guard-coverage.mjs
+++ b/scripts/check-core-guard-coverage.mjs
@@ -42,6 +42,7 @@ const EXEMPT = {
'src/core/persistence/effect-journal.ts': 'post-publication effects; no page text',
'src/core/repair/file-drift.ts': 'removes a held file whose page is deleted: no live page records the path (re-read under the publication guard), the page row is untouched, and core counts only live pages; --prefer file publishes through file-repair.ts',
'src/core/repair/captured-facts.ts': 'owner-run repair that expires fact rows (shrinks only)',
+ 'src/core/repair/agent-session-facts.ts': 'owner-run repair that re-attributes capture-lane facts and retires their takes (no content added)',
'src/core/repair/extractor-facts.ts': 'owner-run repair restoring expired fact rows',
'src/core/repair/redacted-facts.ts': 'owner-run, preview-bound repair rewriting the text of database-only fact rows to words a source page proves; page text is unchanged (fenced rows publish through put_page, preparePageMutation)',
'src/core/repair/visibility.ts': 'owner-run, preview-first repair that only tightens database-only fact rows from world to private; page text is unchanged (fenced rows and page labels publish through put_page, preparePageMutation)',
diff --git a/src/core/context/session-speaker.ts b/src/core/context/session-speaker.ts
index e30eb6fb57..1c6b7fbc1d 100644
--- a/src/core/context/session-speaker.ts
+++ b/src/core/context/session-speaker.ts
@@ -25,7 +25,7 @@
*/
import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
-import { spawnSync } from 'node:child_process';
+import { spawnSync } from '../spawn.ts';
import { basename, dirname, join } from 'node:path';
import { corpusFileSessionId, speakerFileName } from './corpus-segments.ts';
@@ -93,7 +93,7 @@ function linuxParent(pid: number): AncestorProcess & { ppid: number } | null {
}
function psParent(pid: number, timeout: number): AncestorProcess & { ppid: number } | null {
- const r = spawnSync('ps', ['-o', 'ppid=,args=', '-p', String(pid)], { encoding: 'utf8', timeout });
+ const r = spawnSync('ps', ['-ww', '-o', 'ppid=,args=', '-p', String(pid)], { encoding: 'utf8', timeout });
const m = /^\s*(\d+)\s+(.*)$/.exec((r.stdout ?? '').trim());
return m ? { pid, ppid: Number(m[1]), args: m[2].split(/\s+/) } : null;
}
diff --git a/src/core/repair/agent-session-facts.ts b/src/core/repair/agent-session-facts.ts
index 44e34f7d60..2fde3ca196 100644
--- a/src/core/repair/agent-session-facts.ts
+++ b/src/core/repair/agent-session-facts.ts
@@ -56,6 +56,7 @@ import type { PreparedMutation } from '../persistence/coordinator.ts';
import type { WriteRequest } from '../persistence/model.ts';
import { submitPageMutation } from '../persistence/page-mutations.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
+import { CONTEXT_NOTE_SEPARATOR } from '../facts/subject-infer.ts';
import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
import { corpusFileSessionId, corpusSpoolDir, parseWbFileName, speakerFileName } from '../context/corpus-segments.ts';
import { readSessionSource } from '../context/corpus-source.ts';
@@ -76,7 +77,7 @@ const OPENING_CHARS = 160;
const OPENING_MIN_CHARS = 40;
const OPENING_MIN_OTHERS = 3;
const HEAD_BYTES = 64 * 1024;
-const NOTE_SEPARATOR = '; ';
+const NOTE_SEPARATOR = CONTEXT_NOTE_SEPARATOR;
const NOTE_MARK = 'speaker: agent ';
export type AgentSessionFactClass = 'evidenced' | 'ambiguous' | 'excluded';
@@ -294,6 +295,7 @@ export async function agentSessionTakes(db: BrainEngine, sourceIds: string[], re
FROM takes t JOIN pages p ON p.id=t.page_id
WHERE p.source_id=ANY($1::text[]) AND t.kind='fact' AND t.holder='self' AND t.active AND t.resolved_at IS NULL
AND ($2::bigint[] IS NULL OR t.id=ANY($2::bigint[])) AND EXISTS (SELECT 1 FROM facts f WHERE f.consolidated_into=t.id)
+ AND t.created_at >= (SELECT min(f.consolidated_at) FROM facts f WHERE f.consolidated_into=t.id) - interval '1 second'
ORDER BY p.source_id, p.slug, t.id`, [sourceIds, ids ?? null, NOTE_MARK]);
return rows.filter(row => row.user_fact_ids.every(id => reattributed.has(Number(id))) && (row.noted || row.user_fact_ids.length > 0))
.map(row => {
@@ -434,6 +436,7 @@ export async function applyAgentSessionWrite(tx: BrainEngine, sourceId: string,
const retired = write.take_ids?.length ? (await tx.executeRaw<{ id: number | string }>(`UPDATE takes t SET active=false, updated_at=now()
FROM pages p
WHERE p.id=t.page_id AND p.source_id=$1 AND t.id=ANY($2::bigint[]) AND t.active AND t.resolved_at IS NULL AND t.kind='fact' AND t.holder='self'
+ AND t.created_at >= (SELECT min(f.consolidated_at) FROM facts f WHERE f.consolidated_into=t.id) - interval '1 second'
AND NOT EXISTS (SELECT 1 FROM facts f WHERE f.consolidated_into=t.id AND (f.attributed_to IS NULL OR f.attributed_to='user'))
RETURNING t.id`, [sourceId, write.take_ids])).map(row => Number(row.id)) : [];
return { reattributed, retired };
@@ -516,7 +519,7 @@ async function retireTakes(ctx: Parameters<RepairHandler['apply']>[0], item: Rep
const fence = parseTakesFence(body);
const fenced = takes.filter(t => fence.takes.some(row => row.rowNum === t.row_num && row.claim.trim() === t.claim.trim() && row.active));
const retired: number[] = [];
- const databaseOnly = takes.filter(t => !fenced.includes(t));
+ const databaseOnly = fence.takes.length ? [] : takes.filter(t => !fenced.includes(t)); // a fenced page's unmatched take stays: the file is the parent
if (databaseOnly.length) retired.push(...await databaseWrite(engine, page, hash, { take_ids: databaseOnly.map(t => t.id) }));
if (fenced.length && snapshot) {
const rows = new Set(fenced.map(t => t.row_num));
diff --git a/test/repair-agent-session-facts.test.ts b/test/repair-agent-session-facts.test.ts
index fcf6328d5e..e1f8c2feac 100644
--- a/test/repair-agent-session-facts.test.ts
+++ b/test/repair-agent-session-facts.test.ts
@@ -110,11 +110,11 @@ describe('gbrain repair agent-session-facts, unmanaged repo-less brain', () => {
`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, source_session, attributed_to)
VALUES ('default', $1, $2, 'preference', 'private', $3, $4, $5) RETURNING id`,
[opts.entity ?? ALICE, fact, opts.source ?? 'hook:writeback', session, opts.attributed === undefined ? 'user' : opts.attributed]))[0]!.id);
- const take = async (claim: string, factIds: number[]) => {
+ const take = async (claim: string, factIds: number[], createdBefore = '0 seconds') => {
const [page] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE slug=$1 AND source_id='default'", [ALICE]);
- const [row] = await engine.executeRaw<{ id: number }>(`INSERT INTO takes (page_id, row_num, claim, kind, holder, weight, since_date, source, active)
- VALUES ($1, (SELECT COALESCE(MAX(row_num), 0) + 1 FROM takes WHERE page_id=$1), $2, 'fact', 'self', 0.8, '2026-10-01', 'hook:writeback', true) RETURNING id`,
- [page!.id, claim]);
+ const [row] = await engine.executeRaw<{ id: number }>(`INSERT INTO takes (page_id, row_num, claim, kind, holder, weight, since_date, source, active, created_at)
+ VALUES ($1, (SELECT COALESCE(MAX(row_num), 0) + 1 FROM takes WHERE page_id=$1), $2, 'fact', 'self', 0.8, '2026-10-01', 'hook:writeback', true, now() - $3::interval) RETURNING id`,
+ [page!.id, claim, createdBefore]);
await engine.executeRaw('UPDATE facts SET consolidated_into=$1, consolidated_at=now() WHERE id=ANY($2::bigint[])', [row!.id, factIds]);
return Number(row!.id);
};
@@ -201,6 +201,17 @@ describe('gbrain repair agent-session-facts, unmanaged repo-less brain', () => {
expect((await agentSessionFactsCheck(engine)).status).toBe('ok');
}, 120_000);
+ test('an owner take that consolidate later attached agent facts to is kept', async () => {
+ await engine.putPage(ALICE, { type: 'person', title: 'Alice Example', compiled_truth: '# Alice Example' }, { sourceId: 'default' });
+ const agentFact = await insert('Prefers written decisions over meetings', 'sess-sidecar');
+ const ownerTake = await take('Prefers written decisions', [agentFact], '1 day');
+ const preview = await repair(engine, ['--cwd', agents]);
+ expect(preview.results[0].listing!.filter(l => l.class === 'take_to_retire').map(l => l.item)).not.toContain(`default:${ALICE}@take:${ownerTake}`);
+ await repair(engine, applyArgs(preview));
+ expect((await attribution(engine, agentFact)).attributed_to).toBe('other');
+ expect(await takeActive(engine, ownerTake)).toBe(true);
+ });
+
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, []);