Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(repair): agent-session-facts re-attributes facts saved from agent-launched sessions and retires their self takes (#8064)
garrytan7d6d19a4e57b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c67abc2b6b..93500588b7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,8 @@ identifiers and attribution are available in the pre-removal Git revisionSet `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.+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.+### Itemized changes- `src/core/context/session-speaker.ts` (new): the env contract, ancestry detection, the speaker sidecar.@@ -23,7 +25,8 @@ Set `GBRAIN_SESSION_AGENT=<label>` on a worker's process and the capture hooks s- `src/core/facts/backstop.ts`, `src/core/facts/extract.ts`, `src/core/facts/speaker-context.ts`, `src/core/persistence/facts-maintenance.ts`: the `speaker` pipeline option.- `src/core/context/checkpoint-harvest.ts`, `src/core/sweep.ts`: the capture lanes pass the corpus file's speaker.- `src/core/transcripts/codex-hook-lane.ts`: `event_msg` / `thread_settings_applied` counts as a recognized record.-- `docs/guides/ambient-writeback.md`: "Sessions an agent launches".+- `src/core/repair/agent-session-facts.ts` (new), `src/commands/doctor/checks/agent-session-facts.ts` (new): the explicit-only repair kind, its `managed_maintenance_agent_session_facts` request and the `agent_session_facts` doctor check; registry, preview-approval and doctor goldens updated.+- `docs/guides/ambient-writeback.md`: "Sessions an agent launches"; `docs/guides/repair.md`: the new kind.## [0.60.519.0] - 2026-10-30diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex c3e6280c79..40e24be55b 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -232,6 +232,7 @@ src/core/persistence/connector-path.ts 1 coordinator Connector path clear lockssrc/core/source-delete.ts 1 engine_guard Unmanaged source delete with its incarnation binding; managed brains route removal through source lifecycle first and the writer guard refuses a direct delete.src/core/repair/extractor-facts.ts 1 coordinator `gbrain repair extractor-facts` (#5731) clears expired_at on preview-approved conversation-extractor facts and gives each a fresh row number. On a managed brain the UPDATE runs only inside the managed_maintenance_restore_extractor_facts publication (withCoordinatedWrite, page key locked, each fact reclassified first); an unmanaged brain runs the same function in one transaction under the page lock.src/core/repair/captured-facts.ts 1 coordinator `gbrain repair captured-facts` expires preview-approved capture-lane facts that have no fence row. On a managed brain the UPDATE runs only inside the managed_maintenance_expire_captured_facts publication (owner-checked by maintenancePreflight, page key locked); an unmanaged brain runs it in one transaction. Fenced rows are never updated here: they are struck in the page and expired by the canonical projection of a revision-bound put_page.+src/core/repair/agent-session-facts.ts 2 coordinator gbrain repair agent-session-facts (#8064) re-attributes preview-approved database-only capture facts to the agent (attributed_to other plus a speaker note) and retires fact/self takes whose every contributing fact is then non-user. On a managed brain both UPDATEs run only inside the managed_maintenance_agent_session_facts publication (owner-checked by maintenancePreflight, page key locked); an unmanaged brain runs them in one maintenanceTransaction. The UPDATEs recheck attribution, activity and fence position under the row lock. Fenced facts and takes are never updated here: they are rewritten in the page through a revision-bound put_page and the canonical projection rewrites the rows in place.src/core/repair/redacted-facts.ts 1 coordinator `gbrain repair redacted-facts` (#7125) rewrites the text of preview-approved database-only facts to the words a source page proves. On a managed brain the UPDATE runs only inside the managed_maintenance_restore_redacted_facts publication (owner-checked by maintenancePreflight, page key locked); an unmanaged brain runs it in one maintenanceTransaction. The UPDATE compares text, visibility, entity and holding page under the row lock. Fenced rows are never updated here: their claim is rewritten in the page through a revision-bound put_page and the canonical projection replaces the row.src/core/repair/secret-spans.ts 2 coordinator `gbrain repair secret-spans` (GST-327) replaces only the credential spans the secret scanner finds in the preview-approved pages' stored copies with <REDACTED:rule> markers, one page per transaction under the page key after a digest recheck: inside withCoordinatedWrite with maintenance attribution on a managed brain, withWriteAttribution on an unmanaged one. Database only: the file side of a redaction goes through Git, history is kept, and a sync hold stays.src/core/repair/ontology-facts.ts 1 coordinator `gbrain repair ontology-facts` (#6264) gives preview-approved ontology observations their own provenance back, clears their fence row number and expiry. On a managed brain the UPDATE runs only inside coordinatedDatabaseWrite (the ontology_propose path: write authority checked, source incarnation revalidated, entity and page keys locked); an unmanaged brain runs it in one maintenance transaction. It writes database-only ontology rows and never a page or file.diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.mdindex 2f33645466..c53208bb26 100644--- a/docs/architecture/key-files/commands-2.md+++ b/docs/architecture/key-files/commands-2.md@@ -16,6 +16,7 @@ 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.mdindex 2cd46c69f3..c57851c801 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -11,6 +11,7 @@ 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/architecture/system-of-record.md b/docs/architecture/system-of-record.mdindex caa04a8219..d6dd1bfd43 100644--- a/docs/architecture/system-of-record.md+++ b/docs/architecture/system-of-record.md@@ -292,6 +292,7 @@ or a physical projection that leaves attribution untouched):- `src/core/persistence/sync-prepare.ts` (4): managed sync request preparer.- `src/core/persistence/sync-streamed.ts` (1): the streamed sync of a file over the single-string ceiling moves a renamed page (`updateSlug`) in its request's apply, inside the coordinated publication.- `src/core/persistence/takes-prepare.ts` (3): takes request preparer.+- `src/core/repair/agent-session-facts.ts` (2): a `managed_maintenance_agent_session_facts` request on managed brains (database-only fact re-attribution and take retirement); the unmanaged write runs in `maintenanceTransaction`.- `src/core/repair/atoms-restore.ts` (3): the unmanaged `gbrain repair atoms-restore` apply archives the retired atom's version, restores it and drops its `retired_by`/`retired_at` stamp in one `maintenanceTransaction`; managed brains publish a `managed_maintenance_restore_reextract_atom` request instead.- `src/core/repair/captured-facts.ts` (1): a request on managed brains; the unmanaged captured-facts expiry runs in `maintenanceTransaction`.- `src/core/repair/consolidate-ties.ts` (1): `gbrain repair consolidate-ties` reopens facts inside `coordinatedDatabaseWrite` on managed brains (the `relink_facts` operation) and in one `maintenanceTransaction` per fact on unmanaged brains.diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex bf1d4dc2fd..fa71e7fdf9 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -9,7 +9,7 @@ fixes those and the other kinds listed in[What each kind fixes](#what-each-kind-fixes). Every run is a preview unlessyou pass `--apply`.The explicit-only kinds, among them `google-file-modes`, `stale-atoms`, `atoms-restore`, `extractor-facts`,-`captured-facts`, `redacted-facts`, `loop-facts`, `ontology-facts`, `orphan-children`, `failed-writes`, `frontmatter`, `managed-sync-orphans`, `content-receipt-root`, `stuck-recovery`, `aliases`, `rename-identity` and `segmented-mirror`, run only when you name them (see [Explicit-only repair kinds](#explicit-only-repair-kinds)).+`captured-facts`, `agent-session-facts`, `redacted-facts`, `loop-facts`, `ontology-facts`, `orphan-children`, `failed-writes`, `frontmatter`, `managed-sync-orphans`, `content-receipt-root`, `stuck-recovery`, `aliases`, `rename-identity` and `segmented-mirror`, run only when you name them (see [Explicit-only repair kinds](#explicit-only-repair-kinds)).`gbrain doctor --remediation-plan` lists the same kinds as repair steps, and`gbrain doctor --remediate --yes --include-repairs --expect <plan_hash>` runs them under a budget(see [Run repairs through doctor](#run-repairs-through-doctor)).@@ -126,7 +126,7 @@ gives each a fresh row number); it never deletes or rewrites a page.| `--no-embed` | `safe-chunks` and `contextual-mode`: skip the embedding provider. Run `gbrain embed --stale` later. `timeline` and `visibility` pages are re-embedded by their publication either way. || `--all` | Run every automatic kind in order. Explicit-only kinds are listed with their preview command, never run. || `--expect <hash>` | Explicit-only kinds: apply exactly the set the preview printed under this hash. Required with `--apply` for `stale-atoms`, `atoms-restore`, `extractor-facts`, `captured-facts`, `redacted-facts`, `loop-facts`, `failed-writes`, `frontmatter`, `managed-sync-orphans` and `content-receipt-root`. |-| `--include-ambiguous` | `extractor-facts` and `captured-facts`: widen the hashed set to `ambiguous` facts. `frontmatter`: add interpretive file changes. Pass it to both the preview and the apply. See [Extractor facts](#extractor-facts), [Captured facts](#captured-facts) and [Frontmatter](#frontmatter). |+| `--include-ambiguous` | `extractor-facts`, `captured-facts` and `agent-session-facts`: widen the hashed set to `ambiguous` facts. `frontmatter`: add interpretive file changes. Pass it to both the preview and the apply. See [Extractor facts](#extractor-facts), [Captured facts](#captured-facts) and [Frontmatter](#frontmatter). || `--only <path>`, `--skip <path>` | `frontmatter` only: select source-relative files (repeatable). The hash covers the selection, so pass the same flags to the apply. || `--diff` | `frontmatter` only: print every per-file diff instead of one sample per class (`--json` always carries all of them). || `--yes` | `frontmatter --apply` only: the user agreed to the previewed file changes (destructive consent). Without it a terminal asks, and a run without a terminal exits 3 with the consent payload. |@@ -2003,6 +2003,56 @@ cannot reactivate it; a fact with no fence row expires database-only (onemaintenance request per page on a managed brain). Nothing is withdrawn, so`gbrain remember` can save the same claim again.+<a id="agent-session-facts"></a>+### Agent-session facts++An orchestrator that launches headless worker sessions on your account (for+example `claude -p` workers) renders each worker's first message from a+template brief. Before #8064 the capture hooks banked those sessions as yours,+so the briefs were saved as your own preferences, beliefs and commitments, and+consolidate could promote them into takes held by you. New captures from such+sessions now carry a speaker sidecar and are attributed to the agent.+`gbrain repair agent-session-facts` fixes the facts already stored. It is+explicit-only, preview-bound and destructive, and it runs on the brain host (it+reads the session corpus there). It never deletes anything.++**Say to your agent:** *"Doctor says some facts came from agent-launched+sessions. Show me which ones and which takes would be retired before changing+anything."* The agent runs `gbrain repair agent-session-facts`, shows you the+list and, after you agree, runs the printed apply command.++```bash+gbrain doctor # agent_session_facts+gbrain repair agent-session-facts # preview: every candidate with its class, and the takes to retire+gbrain repair agent-session-facts --cwd /srv/agent-workers --session <session-id> --principal worker-a+gbrain repair agent-session-facts --apply --expect <hash> --yes+gbrain doctor+```++| Class | Meaning | Re-attributed |+| --- | --- | --- |+| `evidenced` | The fact's session has a speaker sidecar (`<session>.speaker.json` in the corpus directory, its `sourced/` spool or beside the session's corpus files), you named it with `--session <id>`, or its `<session>.source.json` records a working directory under a `--cwd <prefix>` you passed (compared on whole path segments after resolving symlinks). | By `--apply --expect <hash> --yes` |+| `ambiguous` | The session's first message (spaces collapsed, lowercased, at least 40 characters) matches the first 160 characters of the first message of at least 3 other sessions: a template brief. A heuristic, so it is listed in every preview but applied only on request. | Only with `--include-ambiguous` and that preview's hash |+| `excluded:owner_also_said` | The same claim and entity also has an active fact attributed to you from a session that is not suspect, so you said it too. | Never |++Only active capture-lane facts (`hook:writeback`, `hook:compact`,+`sweep:corpus`) attributed to you or to nobody are candidates. Facts of a+session with no retained corpus file, sidecar or source record are counted as+`unclassifiable` and kept. `--cwd` and `--session` are repeatable; pass the+same flags to the apply (the printed apply command carries them).++The apply sets `attributed_to` to `other` and appends+`speaker: agent <label>, not the owner` to the fact's context. The label is the+sidecar's, else `--principal <label>`, else `agent-launched`. A fact with a row+in its page's `## Facts` fence is rewritten in the page (one revision-bound+`put_page` per page); a fact with no fence row is rewritten database-only (one+maintenance request per page on a managed brain, one transaction otherwise).+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.+<a id="redacted-facts"></a>### Redacted facts@@ -3569,6 +3619,7 @@ walk me through it before changing anything."*| Working-tree sync prints `legacy file(s) skipped … not valid UTF-8` | `find <checkout> -name '*.md' ! -exec iconv -f UTF-8 -t UTF-8 -o /dev/null {} \; -print` | re-save each listed file as UTF-8 | the next `gbrain sync --working-tree` no longer prints the line | user (re-saves the files) | none || Doctor `google_file_modes` warns, or the upgrade printed `[google] Google source <id> keeps its files in <dir>, outside ~/.gbrain` | `gbrain repair google-file-modes --source <id>` | `gbrain repair google-file-modes --source <id> --apply` | `gbrain doctor --only google_file_modes --json` (`google_file_modes` ok) | brain host, after the user agrees | none || Recall or hot memory returns facts from gbrain's own claude-cli sessions or from pasted text; doctor `captured_facts_active` warns; the upgrade banner prints `captured_facts_active: N (explicit_kind_required; …)` | `gbrain repair captured-facts` (add `--include-ambiguous` to include paste candidates) | `gbrain repair captured-facts --apply --expect <hash>` with the hash that preview printed | `gbrain doctor --only captured_facts_active --json` (`captured_facts_active` ok) | brain host, after the user agrees | `destructive` (quarantines facts) |+| Recall, hot memory or takes treat an orchestrator's worker briefs as your own preferences or commitments; doctor `agent_session_facts` warns | `gbrain repair agent-session-facts` (add `--cwd <prefix>` or `--session <id>` for sessions you know an orchestrator launched, `--include-ambiguous` for repeated openings) | `gbrain repair agent-session-facts --apply --expect <hash> --yes` with the hash that preview printed | `gbrain doctor --only agent_session_facts --json` (`agent_session_facts` ok) | brain host, after the user agrees | `destructive` (re-attributes facts, retires takes) || A stored fact reads `[redacted](…)` where a word such as "System" belongs; doctor `facts_redaction_marker` warns; `trust scan` flags the marker | `gbrain repair redacted-facts` | `gbrain repair redacted-facts --apply --expect <hash>` with the hash that preview printed | `gbrain doctor --only facts_redaction_marker --json` (ok, or only facts the preview listed as `ambiguous` or `unproven`) | brain host, after the user agrees | none || Timelines put hundreds of facts on one day; doctor `fact_bulk_dates` warns that a day holds a bulk-loaded share of a source's facts | `gbrain repair fact-claim-dates --source <id>` | `gbrain repair fact-claim-dates --source <id> --apply --expect <hash> --yes` with the hash that preview printed | `gbrain repair fact-claim-dates --source <id>` lists nothing to move (doctor keeps warning while facts without a date in the claim keep the load day) | brain host, after the user agrees | none || Doctor `provenance_stamp_drift` warns that pages lost their provenance stamps or trust marker, or would re-read above their stored tier | `gbrain repair provenance --source <id>` | `gbrain repair provenance --source <id> --apply --expect <hash> --yes` with the hash that preview printed | `gbrain doctor --only provenance_stamp_drift` is ok | brain host, after the user agrees | destructive |@@ -3825,7 +3876,7 @@ Each heading below is the `docs` anchor a refusal carries.### Explicit-only repair kinds-`google-file-modes`, `stale-atoms`, `extractor-facts`, `captured-facts`,+`google-file-modes`, `stale-atoms`, `extractor-facts`, `captured-facts`, `agent-session-facts`,`loop-facts`, `ontology-facts`, `file-drift`, `missing-tables`, `segmented-mirror` and `secret-spans` run only when named: `gbrain repair <kind>` previews, and`gbrain repair <kind> --apply` applies (every kind but `google-file-modes`also needs `--expect <hash>`, so it applies exactly the previewed set; `google-file-modes` re-checks each file's owner,@@ -3856,7 +3907,7 @@ saved preview is older than 7 days, or the selection no longer matches it (forhash." Re-run the printed preview command and apply with the new hash. Itapplies to `gbrain jobs authorize-legacy --select`, `gbrain jobs cancel--select`, `gbrain repair stale-atoms`, `gbrain repair extractor-facts`,-`gbrain repair captured-facts` and `gbrain repair loop-facts`.+`gbrain repair captured-facts`, `gbrain repair agent-session-facts` and `gbrain repair loop-facts`.### Recovery bundle unsupporteddiff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex 7040ea2964..f6f34d77fe 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -518,6 +518,9 @@ src/core/reindex-consent.ts estimateReindexSpend sql METAsrc/core/repair/accepted-takes.ts archivedRow field SEGW inline versions only: a segmented archived version counts as version_missing (the v0.60.253.0 accept refused segmented pages, so none exists)src/core/repair/accepted-takes.ts archivedRow sql SEGW selects body_storage; a segmented archived version counts as version_missingsrc/core/repair/accepted-takes.ts livePage call:serializePageToMarkdown SEGW materializedSnapshot within the single-string ceiling; over it counts as fence_unreadable (no fences there)+src/core/repair/agent-session-facts.ts retireTakes call:serializePageToMarkdown INLINE inline pages only: a segmented page returns before the read and its takes are kept (changed_since_preview)+src/core/repair/agent-session-facts.ts rewriteFencedFacts call:serializePageToMarkdown INLINE inline pages only: a segmented page returns before the read and its fenced facts are kept (changed_since_preview)+src/core/repair/agent-session-facts.ts rewriteFencedFacts field INLINE inline pages only: a segmented page returns before the read and its fenced facts are kept (changed_since_preview)src/core/repair/captured-facts.ts strikeFencedRows call:serializePageToMarkdown SEGWsrc/core/repair/captured-facts.ts strikeFencedRows field SEGWsrc/core/repair/connector-fences.ts candidates sql STREAMdiff --git a/src/commands/doctor/checks/agent-session-facts.ts b/src/commands/doctor/checks/agent-session-facts.tsnew file mode 100644index 0000000000..10f66d021f--- /dev/null+++ b/src/commands/doctor/checks/agent-session-facts.ts@@ -0,0 +1,34 @@+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { classifyAgentSessionFacts } from '../../../core/repair/agent-session-facts.ts';++/**+ * `agent_session_facts` (#8064): active capture-lane facts still attributed to+ * the owner although their session was launched by an agent (a speaker+ * sidecar, evidenced) or opens with a brief three or more other sessions share+ * (ambiguous). Counts them without operator flags and names the explicit-only+ * `gbrain repair agent-session-facts` preview; the apply needs the user's+ * agreement. Read-only; reads the brain host's session corpus.+ */+export async function agentSessionFactsCheck(engine: BrainEngine, sourceIds?: string[], opts: { corpusDir?: string | null } = {}): Promise<Check> {+ const name = 'agent_session_facts';+ try {+ const sources = sourceIds ?? (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(row => row.id);+ const { candidates, unclassifiable } = await classifyAgentSessionFacts(engine, sources, opts);+ const count = (klass: string) => candidates.filter(c => c.class === klass).length;+ const details = { evidenced: count('evidenced'), ambiguous: count('ambiguous'), excluded: count('excluded'), unclassifiable,+ repair: 'agent-session-facts', docs: 'docs/guides/repair.md#agent-session-facts' };+ if (!details.evidenced && !details.ambiguous) {+ return { name, status: 'ok', details, message: 'No active owner-attributed fact from an agent-launched session remains.' };+ }+ return { name, status: 'warn', details,+ message: `${details.evidenced + details.ambiguous} active fact(s) from agent-launched sessions are still attributed to the owner `+ + `(${details.evidenced} with a speaker sidecar, ${details.ambiguous} by a repeated session opening, heuristic); recall and consolidate treat them as the owner's own. `+ + 'Preview on the brain host: gbrain repair agent-session-facts (add --cwd <prefix> or --session <id> for sessions you know an orchestrator launched) '+ + '— the apply it prints re-attributes them and retires the takes built only from them, and needs the user\'s agreement '+ + '(repeated-opening candidates only with --include-ambiguous).' };+ } catch (error) {+ return { name, status: 'warn', message: `Agent-session facts could not be inspected: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,+ details: { count: 'unknown' } };+ }+}diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.tsindex ed78ee2e6c..b9e9328315 100644--- a/src/commands/doctor/checks/graph-health.ts+++ b/src/commands/doctor/checks/graph-health.ts@@ -376,6 +376,7 @@ export const timelineHistoryEntry: DoctorEntry = {'conversation_label_facts','conversation_outcomes_stale','captured_facts_active',+ 'agent_session_facts','facts_redaction_marker','fact_bulk_dates','loop_facts_drift',diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.tsindex 4a0281967c..db7b8adf4f 100644--- a/src/commands/doctor/wave-checks.ts+++ b/src/commands/doctor/wave-checks.ts@@ -372,6 +372,13 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [impact: 'Some active facts were captured from gbrain\'s own model sessions or from pasted text before v0.60.30.0',run: async (engine, scope) => (await import('./checks/captured-facts.ts')).capturedFactsCheck(engine, scope.sourceIds),},+ {+ id: 'agent_session_facts', resolution: 'repair', registration: 'wave',+ hostOnly: 'Classifying agent-session facts reads the session corpus on the brain host; the repair is explicit-only and needs the user\'s agreement.',+ count: d => Number(d.evidenced ?? 0) + Number(d.ambiguous ?? 0),+ impact: 'Some active facts from agent-launched sessions are still attributed to the owner',+ run: async (engine, scope) => (await import('./checks/agent-session-facts.ts')).agentSessionFactsCheck(engine, scope.sourceIds),+ },{id: 'facts_redaction_marker', resolution: 'repair', registration: 'wave',hostOnly: 'Restoring redacted fact text reads the facts\' source pages and versions on the brain host; the repair is explicit-only.',diff --git a/src/commands/repair.ts b/src/commands/repair.tsindex 58ba5a32b5..cb093ba08d 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -36,6 +36,9 @@ import { createProgress } from '../core/progress.ts';import { registerSignalOwner } from '../core/process-cleanup.ts';import { cliOptsToProgressOptions, getCliOptions } from '../core/cli-options.ts';import { resolveSecretRules } from '../core/secret-spans.ts';+import { normalizeSeatLabel } from '../core/context/seat.ts';+import { agentSessionFlagArgs } from '../core/repair/agent-session-facts.ts';+import { isAbsolute } from 'node:path';/** The content-repair lane's command word (#6377): parsed like a kind, dispatched to repair-content.ts, never a RepairKind. */export const CONTENT_LANE = 'content';@@ -88,6 +91,8 @@ export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <igbrain repair generations --kind <kind> [--mode restore|release-held] (--run <id> | --since <ISO-8601|7d> | --key <owner> | --generation <id> | --held)[--source <id>] [--apply --expect <preview-hash> --yes] [--json]gbrain repair url-clone-fences [--source <id>] [--apply --expect <preview-hash> --yes] [--json]+ gbrain repair agent-session-facts [--source <id>] [--cwd <prefix>]... [--session <id>]... [--principal <label>] [--include-ambiguous]+ [--apply --expect <preview-hash> --yes] [--json]gbrain repair duplicate-facts [--source <id>] [--include-cross-entity] [--apply --expect <preview-hash> --yes] [--json]gbrain repair fact-claim-dates --source <id> [--day YYYY-MM-DD] [--apply --expect <preview-hash> --yes] [--json]gbrain repair provenance [--source <id>] [--slug <slug>]... [--include-ambiguous] [--apply --expect <preview-hash> --yes] [--json]@@ -127,6 +132,9 @@ Options:--slug <slug> fences, file-drift: select a database page by slug (repeatable); the hash covers the selection.rename-identity: the new page of the one open pair to preview (--from <old-slug> when two pairs share it).--close rename-identity: release the pair's purge hold instead of carrying its identity; nothing moves.+ --cwd <prefix>, --session <id>, --principal <label>+ agent-session-facts: sessions whose recorded cwd is under an absolute prefix, or this session id, are agent-launched+ (both repeatable); --principal names the agent in the note when no speaker sidecar does. The hash covers them.--prefer file|database, --request <id>, --all-drifted, --class <name>file-drift: the side that wins; select conflict receipts by request id (repeatable), or every pagestill drifted (refused across mixed drift classes unless --class keeps one). --keep is refused here:@@ -191,7 +199,7 @@ A sources add --url clone whose pull stops at pull_blocked_local_changes: docs/gRenames whose identity sync did not keep (rename-identity): docs/guides/live-sync.md#renaming-a-page.`;const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--include-cross-entity', '--diff', '--yes', '--no-llm', '--all-drifted', '--include-failures', '--force', '--close', '--held']);-const VALUE_FLAGS = new Set(['--rules', '--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--since', '--keep', '--request-id', '--older-than', '--from', '--side', '--state', '--after', '--cursor', '--provenance', '--kind', '--mode', '--run', '--key', '--generation', '--day']);+const VALUE_FLAGS = new Set(['--rules', '--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--since', '--keep', '--request-id', '--older-than', '--from', '--side', '--state', '--after', '--cursor', '--provenance', '--kind', '--mode', '--run', '--key', '--generation', '--day', '--cwd', '--session', '--principal']);/** Flags only some kinds accept, with the kinds that do. */const KIND_FLAGS: Record<string, readonly string[]> = {'--only': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery', 'ghost-pages', 'legacy-twins', 'rename-identity', 'url-clone-fences'],@@ -202,11 +210,13 @@ const KIND_FLAGS: Record<string, readonly string[]> = {'--older-than': ['receipt-compaction'], '--include-failures': ['receipt-compaction'], '--force': ['receipt-compaction'],'--after': ['uncommitted-deletions'],'--kind': ['generations'], '--mode': ['generations'], '--run': ['generations'], '--key': ['generations'], '--generation': ['generations'], '--day': ['fact-claim-dates'], '--rules': ['secret-spans'],+ '--cwd': ['agent-session-facts'], '--session': ['agent-session-facts'], '--principal': ['agent-session-facts'],};const VALUE_EXAMPLES: Record<string, string> = { '--source': 'default', '--limit': '50', '--expect': 'PLAN_HASH', '--only': 'notes/a.md', '--skip': 'notes/a.md','--slug': 'notes/a', '--max-usd': '0.50', '--prefer': 'file', '--request': 'REQUEST_UUID', '--class': 'review_required', '--since': '7d', '--side': 'deleted', '--state': 'tombstone_edited', '--keep': 'prior','--request-id': '123e4567-e89b-42d3-a456-426614174000', '--older-than': '30d', '--from': 'notes/old', '--after': '1200', '--cursor': 'NEXT_CURSOR', '--provenance': 'never_committed',- '--kind': 'atom', '--mode': 'restore', '--run': 'RUN_ID', '--key': 'page:notes/a', '--generation': '42', '--day': '2026-01-15', '--rules': 'openai,aws_access_key' };+ '--kind': 'atom', '--mode': 'restore', '--run': 'RUN_ID', '--key': 'page:notes/a', '--generation': '42', '--day': '2026-01-15', '--rules': 'openai,aws_access_key',+ '--cwd': '/srv/agent-workers', '--session': 'SESSION_ID', '--principal': 'worker-a' };/** A usage refusal whose fix is the read-only preview (gbrain repair without --apply writes nothing). */const invalid = (message: string, suggestion: string, preview: string[] = ['gbrain', 'repair', '--json']) => opError('invalid_params', message, suggestion,{ fix: readFix('Previews the repair; without --apply it writes nothing.', { argv: preview }) });@@ -216,7 +226,8 @@ interface RepairArgs { kind?: string; apply: boolean; all: boolean; json: booleaallDrifted: boolean; prefer?: 'file' | 'database'; requests: string[]; driftClass?: string; since?: string;held: boolean; side?: string; state?: string; provenance?: string; cursor?: string;keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures: boolean; force: boolean; from?: string; close: boolean; afterPage?: number;- generationKind?: string; generationMode?: string; run?: string; key?: string; generation?: number; day?: string; rules?: string[] }+ generationKind?: string; generationMode?: string; run?: string; key?: string; generation?: number; day?: string; rules?: string[];+ cwdPrefixes: string[]; sessions: string[]; principal?: string }/** `--max-usd` on a kind that never calls a paid model: the cap belongs to the doctor remediation run. */function maxUsdRefusal(flag: string, cap: string | undefined, kind: string | undefined): OperationError {@@ -249,7 +260,7 @@ function fileDriftKeepRefusal(args: string[], keep: string): OperationError {/** Strict parse: every flag is known, value flags carry a value, at most one kind. */export function parseRepairArgs(args: string[]): RepairArgs {const parsed: RepairArgs = { apply: false, all: false, json: false, noEmbed: false, includeAmbiguous: false, includeCrossEntity: false, diff: false, yes: false, noLlm: false, only: [], skip: [], slugs: [],- allDrifted: false, held: false, requests: [], includeFailures: false, force: false, close: false };+ allDrifted: false, held: false, requests: [], includeFailures: false, force: false, close: false, cwdPrefixes: [], sessions: [] };const used = new Set<string>();const positional: string[] = [];let maxUsdText: string | undefined;@@ -327,6 +338,22 @@ export function parseRepairArgs(args: string[]): RepairArgs {['gbrain', 'repair', 'fact-claim-dates', ...(parsed.source ? ['--source', parsed.source] : []), '--json']);parsed.day = value;}+ else if (flag === '--cwd') {+ if (!isAbsolute(value)) throw invalid(`--cwd takes an absolute directory prefix (got "${value}").`, 'Pass the directory the agent sessions ran under, e.g. --cwd /srv/agent-workers.',+ ['gbrain', 'repair', 'agent-session-facts', '--json']);+ parsed.cwdPrefixes.push(value);+ }+ else if (flag === '--session') {+ if (!/^[A-Za-z0-9._:-]{1,200}$/.test(value)) throw invalid(`--session takes a harness session id (got "${value}").`, 'Pass the session id the preview lists, e.g. --session SESSION_ID.',+ ['gbrain', 'repair', 'agent-session-facts', '--json']);+ parsed.sessions.push(value);+ }+ else if (flag === '--principal') {+ const label = normalizeSeatLabel(value);+ if (!label) throw invalid(`--principal takes a label of lowercase letters, digits, dot, dash and underscore (got "${value}").`, 'Pass the agent\'s label, e.g. --principal worker-a.',+ ['gbrain', 'repair', 'agent-session-facts', '--json']);+ parsed.principal = label;+ }else if (flag === '--rules') parsed.rules = resolveSecretRules(value.split(',').map(rule => rule.trim()).filter(Boolean)).rules;else if (flag === '--kind') parsed.generationKind = value;else if (flag === '--mode') parsed.generationMode = value;@@ -428,7 +455,7 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Proif (args.includes('--help') || args.includes('-h')) { console.log(REPAIR_HELP); return; }const { kind, apply, all, json, noEmbed, includeAmbiguous, includeCrossEntity, source, expect, only, skip, slugs, diff, noLlm, maxUsd, limit: limitText,prefer, requests, allDrifted, driftClass, since, held, side, state, provenance, cursor, keep, requestId, olderThan, includeFailures, force, from, close, afterPage,- generationKind, generationMode, run, key, generation, day, rules } = parseRepairArgs(args);+ generationKind, generationMode, run, key, generation, day, rules, cwdPrefixes, sessions, principal } = parseRepairArgs(args);const generations: GenerationsSelection | undefined = kind === 'generations' ? { kind: generationKind ?? '', mode: (generationMode ?? 'restore') as GenerationMode,...(run ? { run } : {}), ...(since ? { since } : {}), ...(key ? { key } : {}), ...(generation !== undefined ? { generation } : {}), ...(held ? { held } : {}) } : undefined;if (generations) {@@ -462,7 +489,8 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro...(afterPage !== undefined ? ['--after', String(afterPage)] : []), ...(day ? ['--day', day] : []),...(kind === 'rename-identity' ? [...slugs.flatMap(slug => ['--slug', slug]), ...(from ? ['--from', from] : []), ...(close ? ['--close'] : [])] : []),...(kind === 'origin-twins' || kind === 'timeline-order' || kind === 'provenance' ? slugs.flatMap(slug => ['--slug', slug]) : []),- ...(generations ? generationsSelectionArgv(generations) : [])];+ ...(generations ? generationsSelectionArgv(generations) : []),+ ...(kind === 'agent-session-facts' ? agentSessionFlagArgs({ cwdPrefixes, sessions, principal }) : [])];const custom = repairSpec(kind as RepairKind).consentText;const text = custom ? { ...custom, why: `Preview ${expect}: ${custom.why}`, user_message: `${custom.user_message} (preview ${expect.slice(0, 12)}${keep ? `, keep ${keep}` : ''})` } : {what: `Rewrite the previewed ${kind} changes on disk and import them`,@@ -491,6 +519,7 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro...(k === kind && k === 'receipt-compaction' ? { olderThan, includeFailures, force } : {}),...(k === kind && k === 'rename-identity' ? { from, close } : {}), ...(k === kind && afterPage !== undefined ? { afterPage } : {}),...(k === kind && generations ? { generations } : {}), ...(k === kind && day ? { day } : {}), ...(k === kind && rules ? { rules } : {}),+ ...(k === kind && k === 'agent-session-facts' ? { cwdPrefixes, sessions, principal } : {}),...(apply ? { stop: stop.signal, recordDatabaseStops: true } : {}) })).finally(() => releaseSignals?.());if (apply) clearHealthMemo(engine);const paidKinds = results.filter(r => r.paid).map(r => r.kind);diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex b59ff9edbd..d29b8c6bcf 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -50,7 +50,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--accept-capabilities', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--cursor', '--dataset', '--day', '--db-url', '--deadline', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--rules', '--run', '--runtime', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-tree', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-capabilities', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--principal', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--rules', '--run', '--runtime', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],@@ -83,7 +83,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'lint': ['--abbrev-ref', '--accept-pending', '--add', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--timings', '--unset-all', '--wait', '--yes'],'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],- 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--clear', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-instructions', '--no-pull', '--no-renames', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--workspace', '--yes'],+ 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--clear', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-instructions', '--no-pull', '--no-renames', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--session', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--workspace', '--yes'],'mcp': ['--admin-token-file', '--advertise', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--statement-timeout', '--status', '--timeout', '--timings', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],@@ -110,7 +110,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'reindex-search-vector': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--source', '--timeout', '--timings', '--wait', '--yes'],'reinit-pglite': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--chat-model', '--check', '--concurrency', '--confirm-destructive', '--content-root', '--cursor', '--db-only', '--detail', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--hold-state', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--plan', '--prefer', '--prefer-postgres', '--preview', '--priority', '--provenance', '--query', '--quiet', '--redact-paths', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--search-mode', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],'remote': ['--brain', '--help', '--json', '--mcp-only', '--only', '--remediation-plan', '--request-id', '--scopes', '--source', '--timeout'],- 'repair': ['--accept-pending', '--acknowledge-managed', '--after', '--all', '--all-drifted', '--apply', '--background', '--brain', '--break-lock', '--class', '--client', '--close', '--cursor', '--day', '--diff', '--expect', '--explain', '--ff-only', '--follow', '--force', '--force-break-lock', '--from', '--full', '--full-history', '--generation', '--held', '--help', '--id', '--include-ambiguous', '--include-cross-entity', '--include-failures', '--include-repairs', '--json', '--keep', '--key', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--mode', '--no-accept-pending', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--probe', '--progress-interval', '--progress-json', '--provenance', '--quiet', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--rules', '--run', '--scopes', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--state', '--timeout', '--timings', '--url', '--wait', '--yes'],+ 'repair': ['--accept-pending', '--acknowledge-managed', '--after', '--all', '--all-drifted', '--apply', '--background', '--brain', '--break-lock', '--class', '--client', '--close', '--cursor', '--cwd', '--day', '--diff', '--expect', '--explain', '--ff-only', '--follow', '--force', '--force-break-lock', '--from', '--full', '--full-history', '--generation', '--held', '--help', '--id', '--include-ambiguous', '--include-cross-entity', '--include-failures', '--include-repairs', '--json', '--keep', '--key', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--mode', '--no-accept-pending', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--principal', '--probe', '--progress-interval', '--progress-json', '--provenance', '--quiet', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--rules', '--run', '--scopes', '--seat', '--session', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--state', '--timeout', '--timings', '--url', '--wait', '--yes'],'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--timings', '--url', '--wait'],'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--sample', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],@@ -131,7 +131,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--check', '--concurrency', '--confirm-destructive', '--count', '--cursor', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--hold-state', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--limit', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--source-id', '--stale', '--timeout', '--timings', '--wait'],- 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--class', '--clear', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cursor', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-instructions', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--workspace', '--yes'],+ 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--class', '--clear', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-instructions', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--session', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--workspace', '--yes'],'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--failed', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--retry-failed', '--row', '--semantic', '--since', '--slug', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--request-id', '--rounds', '--save', '--since', '--source', '--source-id', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--timings', '--wait'],diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 47a09a31b7..995ec31983 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -60,6 +60,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([// #7013: atoms an empty managed re-extraction retired that atoms-restore can bring back (doctor/checks/atom-retirements.ts).'atom_retirements_restorable','captured_facts_active',+ // #8064: owner-attributed capture facts from agent-launched sessions (doctor/checks/agent-session-facts.ts).+ 'agent_session_facts',// #7125: facts whose stored text holds a pre-fix sanitizer redaction marker (doctor/checks/facts-redaction-marker.ts).'facts_redaction_marker',// #7247: a calendar day holding a bulk-loaded share of a source's facts as their valid_from (doctor/checks/fact-bulk-dates.ts).diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex 3682b449df..7261994d51 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -581,6 +581,7 @@ async function prepareMaintenanceKind(engine: BrainEngine, row: WriteRequest, coenterClaimStep(clock, 'maintenance_dispatch');if (row.intent?.kind === 'managed_maintenance_restore_extractor_facts') return (await import('../repair/extractor-facts.ts')).prepareExtractorFactsRestore(engine, row);if (row.intent?.kind === 'managed_maintenance_expire_captured_facts') return (await import('../repair/captured-facts.ts')).prepareCapturedFactsExpiry(engine, row);+ if (row.intent?.kind === 'managed_maintenance_agent_session_facts') return (await import('../repair/agent-session-facts.ts')).prepareAgentSessionFactsWrite(engine, row);if (row.intent?.kind === 'managed_maintenance_restore_redacted_facts') return (await import('../repair/redacted-facts.ts')).prepareRedactedFactsRestore(engine, row);if (row.intent?.kind === 'managed_maintenance_tighten_fact_visibility') return (await import('../repair/visibility.ts')).prepareFactVisibilityTighten(engine, row);if (row.intent?.kind === 'managed_maintenance_conversation_label_retire') return (await import('../repair/conversation-labels.ts')).prepareConversationLabelRetirement(engine, row);diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsindex a62a4236e2..0c0ffcd856 100644--- a/src/core/persistence/preview-approval.ts+++ b/src/core/persistence/preview-approval.ts@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */export const APPROVAL_MAX_AGE_DAYS = 7;-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'redacted-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'duplicate-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'uncommitted-deletions' | 'visibility' | 'generations' | 'fact-claim-dates' | 'timeline-order' | 'provenance' | 'secret-spans';+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'agent-session-facts' | 'redacted-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'duplicate-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'uncommitted-deletions' | 'visibility' | 'generations' | 'fact-claim-dates' | 'timeline-order' | 'provenance' | 'secret-spans';export interface ApprovedSetKey {command: PreviewApprovalCommand;diff --git a/src/core/repair/agent-session-facts.ts b/src/core/repair/agent-session-facts.tsnew file mode 100644index 0000000000..44e34f7d60--- /dev/null+++ b/src/core/repair/agent-session-facts.ts@@ -0,0 +1,530 @@+/**+ * `gbrain repair agent-session-facts` (#8064): re-attribute facts the capture+ * lanes (`hook:writeback`, `hook:compact`, `sweep:corpus`) saved as the+ * owner's own from sessions an orchestrator launched (headless workers on the+ * owner's account), and retire the takes consolidate promoted from them. The+ * capture fix stops new damage (agent sessions get a speaker sidecar and their+ * facts `attributed_to: other`); this kind repairs the facts already stored.+ *+ * Candidates are active capture-lane facts of the scoped sources whose+ * `attributed_to` is `user` or unset. Each is classified from its session+ * (`source_session`; corpus rows resolve with `corpusFileSessionId`):+ * - evidenced: the session has a speaker sidecar (`<sid>.speaker.json` in+ * the corpus dir, its spool dir or beside the session's corpus files);+ * the operator listed it with `--session <id>`; or its `<sid>.source.json`+ * records a cwd under an operator `--cwd <prefix>` (realpath-normalized,+ * compared on path boundaries).+ * - ambiguous: the session's first user turn (whitespace-normalized,+ * lowercased, at least 40 characters) shares its first 160 characters with+ * the first user turn of at least 3 other retained sessions (a template+ * brief). Listed fact by fact; re-attributed only with+ * `--include-ambiguous` and the hash of that preview.+ * - excluded: an evidenced or ambiguous row whose claim and entity also have+ * an active user-attributed row from a session that is not suspect (the+ * owner said it too); kept.+ * Rows of sessions with no retained corpus file, sidecar or source record are+ * counted `unclassifiable` and never touched.+ *+ * The apply (`--apply --expect <hash> --yes`) never deletes. Each approved+ * fact still exactly as previewed gets `attributed_to: other` and the speaker+ * note (`speakerContextNote`) in its context: a fenced row (`row_num` on its+ * page) in the page's `## Facts` fence by one revision-bound `put_page` per+ * page, so the canonical projection rewrites the row in place; database-only+ * rows by one maintenance request on a managed brain (one transaction on an+ * unmanaged brain). Then each `kind: fact`, `holder: self` take that is still+ * active and unresolved and whose every contributing fact (`consolidated_into`)+ * is now non-user is retired (`active = false`): struck in the page's takes+ * fence by a revision-bound `put_page` when the fence holds it, otherwise in+ * the database by the same kind of request or transaction. A fact or take that+ * changed since the preview is reported `changed_since_preview` and kept.+ */+import { closeSync, existsSync, openSync, readdirSync, readSync, realpathSync, statSync, type Dirent } from 'node:fs';+import { basename, dirname, join, relative, resolve, sep } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import { opError, OperationError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';+import { parseFactsFence } from '../facts-fence.ts';+import { strikeFenceRow } from '../facts/forget.ts';+import { parseTakesFence } from '../takes-fence.ts';+import { takesPreparation } from '../takes-write.ts';+import { serializePageToMarkdown } from '../markdown.ts';+import { digest } from '../persistence/digest.ts';+import { managedPersistenceEnabled } from '../persistence/ownership.ts';+import { maintenancePreflight, submitDatabaseMaintenanceIntent } from '../persistence/prepared-maintenance.ts';+import { authorizeWrite } from '../persistence/authority.ts';+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 { 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';+import { parseCorpusTurns } from '../context/corpus-turns.ts';+import { DETECTED_PRINCIPAL, readSpeakerSidecar, speakerContextNote } from '../context/session-speaker.ts';+import { stripPastedContent } from '../transcripts/pasted-content.ts';+import { isSegmentedPage } from '../page-body/page-shape.ts';+import { shellQuote } from '../shell-quote.ts';+import { pruneDir } from '../sync.ts';+import { CAPTURE_LANES, captureSessionId } from './captured-facts.ts';+import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairListing, type RepairPlan, type RepairPlanOptions,+ type RepairScope } from './core.ts';++export const AGENT_SESSION_FACTS_INTENT = 'managed_maintenance_agent_session_facts';+const COMMAND = 'agent-session-facts';+const CORPUS_KEY = 'dream.synthesize.session_corpus_dir';+const OPENING_CHARS = 160;+const OPENING_MIN_CHARS = 40;+const OPENING_MIN_OTHERS = 3;+const HEAD_BYTES = 64 * 1024;+const NOTE_SEPARATOR = '; ';+const NOTE_MARK = 'speaker: agent ';++export type AgentSessionFactClass = 'evidenced' | 'ambiguous' | 'excluded';++/** The operator's evidence flags: `--cwd <prefix>`, `--session <id>` (both repeatable) and `--principal <label>`. */+export interface AgentSessionOptions { cwdPrefixes?: string[]; sessions?: string[]; principal?: string }++export interface AgentSessionFactCandidate {+ id: number;+ source_id: string;+ /** The page the fact lives on (fenced rows) or its entity key (database-only rows). */+ slug: string;+ row_num: number | null;+ class: AgentSessionFactClass;+ /** `speaker_sidecar`, `operator_session`, `operator_cwd`, `repeated_opening` or `excluded:owner_also_said`. */+ reason: string;+ session: string;+ evidence: string;+ /** The agent the speaker note names. */+ principal: string;+ /** Digest of the row's claim, visibility, entity, fence position, attribution and context, so an edited row is not rewritten. */+ fact_hash: string;+}++export interface AgentSessionTake { id: number; source_id: string; slug: string; row_num: number; claim: string; fact_ids: number[]; take_hash: string }++export interface AgentSessionFactsClassification {+ candidates: AgentSessionFactCandidate[];+ unclassifiable: number;+ not_suspect: number;+ /** Corpus directories and session files the classification could not read (relative to the corpus dir). */+ unreadable_corpus_files: string[];+}++interface ApprovedPage {+ source_id: string;+ slug: string;+ include_ambiguous: boolean;+ scope: string[];+ /** The normalized evidence flags of the preview; an apply with other flags refuses. */+ options: string;+ facts?: AgentSessionFactCandidate[];+ takes?: AgentSessionTake[];+}++interface PageItem extends RepairItem { page: ApprovedPage; hash: string; last: boolean; options: AgentSessionOptions }++interface FactRow {+ id: number | string; source_id: string; source_session: string | null; fact: string; visibility: string; entity_slug: string | null;+ row_num: number | null; source_markdown_slug: string | null; attributed_to: string | null; context: string | null;+ owner_twin: boolean; twin_sessions: Array<string | null> | null;+}++type Verdict = { klass: 'evidenced' | 'ambiguous'; reason: string; evidence: string; principal: string } | 'not_suspect' | 'unclassifiable';++interface CorpusIndex {+ corpusDir: string | null;+ files: Map<string, string[]>;+ openings: Map<string, string>;+ openingSessions: Map<string, Set<string>>;+ unreadSessions: Set<string>;+ unreadable: string[];+}++/** Sorted, deduplicated flags: the form the hash, the commands and the approved set carry. */+export function normalizeAgentSessionOptions(opts: AgentSessionOptions): AgentSessionOptions & { cwdPrefixes: string[]; sessions: string[] } {+ return { cwdPrefixes: [...new Set(opts.cwdPrefixes ?? [])].sort(), sessions: [...new Set(opts.sessions ?? [])].sort(), ...(opts.principal ? { principal: opts.principal } : {}) };+}++function canonicalPath(path: string): string {+ const absolute = resolve(path);+ try { return realpathSync(absolute); } catch { return absolute; }+}++const under = (path: string, prefix: string) => path === prefix || path.startsWith(prefix.endsWith(sep) ? prefix : prefix + sep);++function readHead(path: string): string {+ const fd = openSync(path, 'r');+ try {+ const buffer = Buffer.alloc(HEAD_BYTES);+ return buffer.subarray(0, readSync(fd, buffer, 0, HEAD_BYTES, 0)).toString('utf8');+ } finally { closeSync(fd); }+}++/** The session's first user turn, normalized; null when no retained file holds one long enough to compare, 'unread' when its files could not be read. */+function openingKey(paths: string[], unreadable: string[]): string | null {+ const ranked = paths.map(path => {+ let mtime = Number.POSITIVE_INFINITY;+ try { mtime = statSync(path).mtimeMs; } catch { /* ranked last */ }+ return { path, wb: parseWbFileName(basename(path)) !== null, mtime };+ }).sort((a, b) => Number(a.wb) - Number(b.wb) || a.mtime - b.mtime || a.path.localeCompare(b.path));+ let unread = false;+ for (const { path, wb } of ranked) {+ let head: string;+ try { head = readHead(path); } catch { unreadable.push(path); unread = true; continue; }+ const turn = wb ? stripPastedContent(head).text : parseCorpusTurns(head).find(t => t.role === 'user')?.body;+ const key = turn?.replace(/\s+/g, ' ').trim().toLowerCase().slice(0, OPENING_CHARS);+ if (key) return key.length >= OPENING_MIN_CHARS ? key : null;+ }+ return unread ? 'unread' : null;+}++/** Every corpus `.txt` (dream discovery's pruning, the spool dir included) by session, and each session's opening. */+function corpusIndex(corpusDir: string | null): CorpusIndex {+ const index: CorpusIndex = { corpusDir, files: new Map(), openings: new Map(), openingSessions: new Map(), unreadSessions: new Set(), unreadable: [] };+ if (!corpusDir || !existsSync(corpusDir)) return index;+ const walk = (dir: string) => {+ let entries: Dirent[];+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { index.unreadable.push(dir); return; }+ for (const entry of entries) {+ const full = join(dir, entry.name);+ if (entry.isDirectory()) { if (pruneDir(entry.name, dir)) walk(full); }+ else if (entry.isFile() && entry.name.endsWith('.txt')) {+ const session = corpusFileSessionId(entry.name);+ index.files.set(session, [...(index.files.get(session) ?? []), full]);+ }+ }+ };+ walk(corpusDir);+ for (const [session, paths] of index.files) {+ const key = openingKey(paths, index.unreadable);+ if (key === 'unread') { index.unreadSessions.add(session); continue; }+ if (!key) continue;+ index.openings.set(session, key);+ index.openingSessions.set(key, (index.openingSessions.get(key) ?? new Set<string>()).add(session));+ }+ return index;+}++function sessionVerdict(session: string, index: CorpusIndex, opts: AgentSessionOptions, cwdPrefixes: string[]): Verdict {+ const fallbackPrincipal = opts.principal ?? DETECTED_PRINCIPAL;+ const corpusDir = index.corpusDir;+ const dirs = corpusDir ? [...new Set([corpusDir, corpusSpoolDir(corpusDir), ...(index.files.get(session) ?? []).map(path => dirname(path))])] : [];+ for (const dir of dirs) {+ const sidecar = readSpeakerSidecar(dir, session);+ if (sidecar) {+ return { klass: 'evidenced', reason: 'speaker_sidecar', principal: sidecar.principal,+ evidence: `${relative(corpusDir!, join(dir, speakerFileName(session)))} (principal ${sidecar.principal})` };+ }+ }+ if (opts.sessions?.includes(session)) return { klass: 'evidenced', reason: 'operator_session', principal: fallbackPrincipal, evidence: `--session ${session}` };+ const record = corpusDir ? readSessionSource(corpusSpoolDir(corpusDir), session) : null;+ if (record?.cwd) {+ const cwd = canonicalPath(record.cwd);+ const prefix = cwdPrefixes.find(p => under(cwd, p));+ if (prefix) return { klass: 'evidenced', reason: 'operator_cwd', principal: fallbackPrincipal, evidence: `cwd ${record.cwd} under --cwd ${prefix}` };+ }+ const key = index.openings.get(session);+ const others = key ? index.openingSessions.get(key)!.size - 1 : 0;+ if (others >= OPENING_MIN_OTHERS) {+ return { klass: 'ambiguous', reason: 'repeated_opening', principal: fallbackPrincipal, evidence: `first user turn shared with ${others} other session(s)` };+ }+ return !index.unreadSessions.has(session) && (index.files.has(session) || record) ? 'not_suspect' : 'unclassifiable';+}++const factHash = (row: FactRow) => digest(['agent-session-fact-v1', row.fact, row.visibility, row.entity_slug, row.row_num, row.source_markdown_slug,+ row.attributed_to, row.context]);+const targetSlug = (row: Pick<FactRow, 'source_markdown_slug' | 'entity_slug'>) => row.source_markdown_slug ?? row.entity_slug ?? 'memory/unattributed';++/** 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> {+ 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+ AND a.entity_slug IS NOT DISTINCT FROM f.entity_slug AND gbrain_fact_fingerprint(a.fact)=gbrain_fact_fingerprint(f.fact)+ AND (a.attributed_to IS NULL OR a.attributed_to='user') AND COALESCE(a.source,'') <> ALL($2::text[])) AS owner_twin,+ ARRAY(SELECT DISTINCT COALESCE(a.source_session,'') 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 AND a.entity_slug IS NOT DISTINCT FROM f.entity_slug AND gbrain_fact_fingerprint(a.fact)=gbrain_fact_fingerprint(f.fact)+ AND (a.attributed_to IS NULL OR a.attributed_to='user') AND a.source=ANY($2::text[])) AS twin_sessions+ FROM facts f+ WHERE f.source_id=ANY($1::text[]) AND f.source=ANY($2::text[]) AND f.expired_at IS NULL AND f.superseded_by IS NULL+ 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 cwdPrefixes = (opts.cwdPrefixes ?? []).map(canonicalPath);+ const verdicts = new Map<string, Verdict>();+ const verdict = (sourceSession: string | null): Verdict => {+ const session = captureSessionId(sourceSession || null);+ if (!session) return 'unclassifiable';+ if (!verdicts.has(session)) verdicts.set(session, sessionVerdict(session, index, opts, cwdPrefixes));+ return verdicts.get(session)!;+ };+ const candidates: AgentSessionFactCandidate[] = [];+ let unclassifiable = 0;+ let notSuspect = 0;+ for (const row of rows) {+ const hit = verdict(row.source_session);+ if (hit === 'unclassifiable') { unclassifiable++; continue; }+ if (hit === 'not_suspect') { notSuspect++; continue; }+ const owner = row.owner_twin || (row.twin_sessions ?? []).some(s => typeof verdict(s) === 'string');+ candidates.push({ id: Number(row.id), source_id: row.source_id, slug: targetSlug(row), row_num: row.row_num === null ? null : Number(row.row_num),+ class: owner ? 'excluded' : hit.klass, reason: owner ? 'excluded:owner_also_said' : hit.reason, session: captureSessionId(row.source_session)!,+ evidence: hit.evidence, principal: hit.principal, fact_hash: factHash(row) });+ }+ candidates.sort((a, b) => a.source_id.localeCompare(b.source_id) || a.slug.localeCompare(b.slug) || a.id - b.id);+ return { candidates, unclassifiable, not_suspect: notSuspect,+ unreadable_corpus_files: index.unreadable.map(path => !corpusDir ? path : relative(corpusDir, path) || basename(path)) };+}++/**+ * Active, unresolved `kind: fact` / `holder: self` takes whose every contributing fact is non-user once the facts in+ * `reattributed` are: at least one of them must be in that set or already carry a speaker note, so takes this repair+ * has nothing to do with are never listed.+ */+export async function agentSessionTakes(db: BrainEngine, sourceIds: string[], reattributed: ReadonlySet<number>, ids?: number[]): Promise<AgentSessionTake[]> {+ const rows = await db.executeRaw<{ id: number | string; source_id: string; slug: string; row_num: number | string; claim: string;+ fact_ids: Array<number | string>; user_fact_ids: Array<number | string>; noted: boolean }>(`+ SELECT t.id, p.source_id, p.slug, t.row_num, t.claim,+ ARRAY(SELECT f.id FROM facts f WHERE f.consolidated_into=t.id ORDER BY f.id) AS fact_ids,+ ARRAY(SELECT f.id FROM facts f WHERE f.consolidated_into=t.id AND (f.attributed_to IS NULL OR f.attributed_to='user') ORDER BY f.id) AS user_fact_ids,+ EXISTS (SELECT 1 FROM facts f WHERE f.consolidated_into=t.id AND f.attributed_to='other' AND position($3::text in COALESCE(f.context,''))>0) AS noted+ 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)+ 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 => {+ const factIds = row.fact_ids.map(Number);+ return { id: Number(row.id), source_id: row.source_id, slug: row.slug, row_num: Number(row.row_num), claim: row.claim, fact_ids: factIds,+ take_hash: digest(['agent-session-take-v1', Number(row.id), row.slug, Number(row.row_num), row.claim, factIds]) };+ });+}++/** The evidence flags as CLI arguments, in their normalized order. */+export function agentSessionFlagArgs(opts: AgentSessionOptions): string[] {+ const normal = normalizeAgentSessionOptions(opts);+ return [...normal.cwdPrefixes.flatMap(p => ['--cwd', p]), ...normal.sessions.flatMap(s => ['--session', s]), ...(normal.principal ? ['--principal', normal.principal] : [])];+}++function previewCommand(scope: RepairScope, all: string[], opts: AgentSessionOptions, includeAmbiguous: boolean): string {+ const source = scope.source_ids.length === 1 && all.length > 1 ? ` --source ${scope.source_ids[0]}` : '';+ return `gbrain repair ${COMMAND}${source}${agentSessionFlagArgs(opts).map(arg => ` ${shellQuote(arg)}`).join('')}${includeAmbiguous ? ' --include-ambiguous' : ''}`;+}++async function activeSources(engine: BrainEngine): Promise<string[]> {+ return (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(row => row.id);+}++async function brainId(engine: BrainEngine): Promise<string> {+ const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1').catch(() => []);+ 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 };+}++function groupByPage<T extends { source_id: string; slug: string }>(rows: T[], make: (first: T) => ApprovedPage, field: 'facts' | 'takes'): ApprovedPage[] {+ const pages = new Map<string, ApprovedPage>();+ for (const row of rows) {+ const key = `${row.source_id}\u0000${row.slug}`;+ const page = pages.get(key) ?? make(row);+ (page[field] as unknown as T[]).push(row);+ pages.set(key, page);+ }+ return [...pages.values()];+}++const evidenceOptions = (opts: RepairPlanOptions | undefined) =>+ normalizeAgentSessionOptions({ cwdPrefixes: opts?.cwdPrefixes, sessions: opts?.sessions, principal: opts?.principal });++export const agentSessionFactsRepair: RepairHandler = {+ kind: 'agent-session-facts',+ embeds: false,+ async plan(engine, scope, after, opts): Promise<RepairPlan> {+ const includeAmbiguous = opts?.includeAmbiguous === true;+ const options = evidenceOptions(opts);+ const optionsKey = JSON.stringify(options);+ const command = previewCommand(scope, await activeSources(engine), options, includeAmbiguous);+ const hashOf = async (candidates: AgentSessionFactCandidate[], takes: AgentSessionTake[]) => previewHash(['agent-session-facts-v1', await brainId(engine),+ scope.source_ids, includeAmbiguous, options, candidates.map(c => [c.id, c.class, c.reason, c.principal, c.fact_hash]), takes.map(t => [t.id, t.take_hash])]);+ if (!opts?.apply) {+ const { candidates, unclassifiable, not_suspect, unreadable_corpus_files } = await classifyAgentSessionFacts(engine, scope.source_ids, options);+ const approvedFacts = candidates.filter(c => c.class === 'evidenced' || (c.class === 'ambiguous' && includeAmbiguous));+ const takes = await agentSessionTakes(engine, scope.source_ids, new Set(approvedFacts.map(c => c.id)));+ const hash = await hashOf(candidates, takes);+ const base = (row: { source_id: string; slug: string }) => ({ source_id: row.source_id, slug: row.slug, include_ambiguous: includeAmbiguous,+ scope: scope.source_ids, options: optionsKey });+ const approved = [...groupByPage(approvedFacts, row => ({ ...base(row), facts: [] }), 'facts'), ...groupByPage(takes, row => ({ ...base(row), takes: [] }), 'takes')];+ if (approved.length) await saveApprovedSet(engine, { command: COMMAND, hash }, approved);+ const count = (klass: AgentSessionFactClass) => candidates.filter(c => c.class === klass).length;+ const listing: RepairListing[] = candidates.map(c => ({ item: `${c.source_id}:${c.slug}#${c.id}`, class: c.class === 'excluded' ? c.reason : c.class,+ detail: `${c.reason}; session ${c.session}; ${c.evidence}; principal ${c.principal}` }));+ for (const take of takes) listing.push({ item: `${take.source_id}:${take.slug}@take:${take.id}`, class: 'take_to_retire',+ 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,+ 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 } : {}) } };+ }+ if (!opts.expect) {+ throw new OperationError('invalid_params', `gbrain repair ${COMMAND} --apply re-attributes only the set a preview printed.`,+ `Preview first: ${command} — then run the apply command it prints after the user agrees: ${command} --apply --expect <preview-hash> --yes`,+ 'docs/guides/repair.md#explicit-only-repair-kinds');+ }+ const approved = await loadApprovedSet<ApprovedPage>(engine, { command: COMMAND, hash: opts.expect, previewCommand: command, emptyHash: () => hashOf([], []) });+ const scopeKey = JSON.stringify(scope.source_ids);+ 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));+ 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 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 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]);+ });+ const dbOnly = unchanged.filter(f => f.row_num === null);+ if (dbOnly.length) done.push(...await databaseWrite(engine, page, hash, { facts: dbOnly.map(f => ({ id: f.id, note: speakerContextNote(f.principal) })) }));+ const fenced = unchanged.filter(f => f.row_num !== null);+ if (fenced.length) done.push(...await rewriteFencedFacts(ctx, entry, page, fenced));+ } else {+ const live = new Map((await agentSessionTakes(engine, [page.source_id], new Set(), page.takes!.map(t => t.id))).map(t => [t.id, t]));+ const unchanged = page.takes!.filter(t => live.get(t.id)?.take_hash === t.take_hash);+ if (unchanged.length) done.push(...await retireTakes(ctx, entry, page, hash, unchanged));+ }+ if (last) await clearApprovedSet(engine, { command: COMMAND, hash });+ const all = (page.facts ?? page.takes!).map(row => row.id);+ const changed = all.filter(id => !done.includes(id));+ const verb = page.facts ? 'reattributed' : 'retired';+ return { applied: done.length > 0, outcome: !changed.length ? verb : done.length ? `partially_${verb}` : 'changed_since_preview',+ ...(changed.length ? { reason: `${done.length} of ${all.length} ${verb}; changed since the preview: ${changed.join(', ')}` } : {}) };+ },+};++/** One approved database-only write: facts to re-attribute (each with its speaker note) and takes to retire. */+export interface AgentSessionWrite { facts?: Array<{ id: number; note: string }>; take_ids?: number[] }++/**+ * Re-attributes each named database-only fact still user-attributed and active, appending its note once, and retires+ * each named take still active, unresolved, `kind: fact` / `holder: self` on a page of the source whose every+ * contributing fact is non-user. The checks run in the UPDATEs, under the row locks. Returns the changed ids.+ */+export async function applyAgentSessionWrite(tx: BrainEngine, sourceId: string, write: AgentSessionWrite): Promise<{ reattributed: number[]; retired: number[] }> {+ const reattributed = write.facts?.length ? (await tx.executeRaw<{ id: number | string }>(`UPDATE facts f+ SET attributed_to='other',+ context=CASE WHEN position(r.note in COALESCE(f.context,''))>0 THEN f.context ELSE concat_ws($3::text, NULLIF(f.context,''), r.note) END+ FROM jsonb_to_recordset($2::text::jsonb) AS r(id bigint, note text)+ WHERE f.source_id=$1 AND f.id=r.id AND (f.attributed_to IS NULL OR f.attributed_to='user') AND f.expired_at IS NULL AND f.superseded_by IS NULL+ AND f.row_num IS NULL+ RETURNING f.id`, [sourceId, JSON.stringify(write.facts), NOTE_SEPARATOR])).map(row => Number(row.id)) : [];+ 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 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 };+}++/** Database-only rows: one maintenance request on the page key on a managed brain (owner-checked, receipted); one transaction otherwise. */+async function databaseWrite(engine: BrainEngine, page: ApprovedPage, hash: string, write: AgentSessionWrite): Promise<number[]> {+ const key = write.facts ? 'reattributed' : 'retired';+ if (!await managedPersistenceEnabled(engine)) return (await maintenanceTransaction(engine, tx => applyAgentSessionWrite(tx, page.source_id, write)))[key];+ const authority = (await maintenancePreflight(engine, page.source_id))!;+ const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });+ const h = digest(['agent-session-facts-write-v1', hash, page.source_id, page.slug, write, snapshot?.revision ?? null]);+ const receipt = await submitDatabaseMaintenanceIntent(engine, authority, page.slug,+ { kind: AGENT_SESSION_FACTS_INTENT, expected_revision: snapshot?.revision ?? null, ...write },+ `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`);+ return (receipt[key] as number[] | undefined) ?? [];+}++/** Preparer for `managed_maintenance_agent_session_facts`: re-attributes the named database-only facts and retires the named takes. */+export async function prepareAgentSessionFactsWrite(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {+ const intent = (row.intent ?? {}) as { facts?: unknown; take_ids?: unknown };+ const facts = intent.facts ?? [];+ const takeIds = intent.take_ids ?? [];+ const valid = Array.isArray(facts) && facts.every(f => !!f && typeof f === 'object' && Number.isSafeInteger((f as { id: unknown }).id)+ && typeof (f as { note: unknown }).note === 'string') && Array.isArray(takeIds) && takeIds.every(id => Number.isSafeInteger(id)) && facts.length + takeIds.length > 0;+ if (!valid) {+ throw opError('invalid_params', 'The agent-session facts intent does not name its facts or takes.',+ `Request ${row.request_id} in source ${row.source_id} does not name the facts or takes to change, so nothing changed. Preview the repair again and apply the new preview after the user approves.`,+ { fix: readFix('Previews the agent-session-facts repair without changing anything.', { argv: ['gbrain', 'repair', COMMAND, '--source', row.source_id, '--json'] }) });+ }+ const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });+ await authorizeWrite(engine, row.authority, 'submit_job', row.slug);+ return { observedRevision: snapshot?.revision ?? null, noop: true,+ validate: async tx => { await authorizeWrite(tx, row.authority, 'submit_job', row.slug); },+ apply: async tx => ({ status: 'completed', ...await applyAgentSessionWrite(tx, row.source_id,+ { facts: facts as Array<{ id: number; note: string }>, take_ids: takeIds as number[] }) }) };+}++/**+ * Fenced facts: set `attributed_to: other` and append the note on each still-matching, still user-attributed active+ * fence row and publish the page once, bound to the revision read; the canonical projection rewrites the rows in+ * place. Returns the facts that now read back as `other`. A page stored in segments is not rewritten.+ */+async function rewriteFencedFacts(ctx: Parameters<RepairHandler['apply']>[0], item: RepairItem, page: ApprovedPage, facts: AgentSessionFactCandidate[]): Promise<number[]> {+ const engine = ctx.engine;+ const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });+ if (!snapshot || isSegmentedPage(snapshot.page)) return [];+ const rows = await engine.executeRaw<{ id: number | string; fact: string; row_num: number }>(+ 'SELECT id, fact, row_num FROM facts WHERE source_id=$1 AND id=ANY($2::bigint[]) AND expired_at IS NULL', [page.source_id, facts.map(f => f.id)]);+ let body = snapshot.page.compiled_truth ?? '';+ const rewritten: number[] = [];+ for (const row of rows) {+ const note = speakerContextNote(facts.find(f => f.id === Number(row.id))!.principal);+ const fenceRow = parseFactsFence(body).facts.find(f => f.rowNum === Number(row.row_num));+ if (!fenceRow?.active || fenceRow.claim.trim() !== row.fact.trim() || (fenceRow.attributedTo !== undefined && fenceRow.attributedTo !== 'user')) continue;+ const next = strikeFenceRow(body, Number(row.row_num), current => ({ ...current, attributedTo: 'other',+ context: current.context?.includes(note) ? current.context : [current.context?.trim(), note].filter(Boolean).join(NOTE_SEPARATOR) }));+ if (next === null) continue;+ body = next;+ rewritten.push(Number(row.id));+ }+ if (!rewritten.length) return [];+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: page.slug, source_id: page.source_id,+ content: serializePageToMarkdown({ ...snapshot.page, compiled_truth: body }, snapshot.tags), expected_revision: snapshot.revision,+ request_id: await repairRequestId(ctx, 'agent-session-facts', item, snapshot.revision) } });+ return (await engine.executeRaw<{ id: number | string }>("SELECT id FROM facts WHERE source_id=$1 AND id=ANY($2::bigint[]) AND attributed_to='other'",+ [page.source_id, rewritten])).map(row => Number(row.id));+}++/**+ * Takes: a take the page's takes fence holds (same row and claim, active) is struck there by one revision-bound+ * `put_page` (the projection sets `active = false`); the rest are retired in the database. A page stored in+ * segments is not rewritten. Returns the retired takes.+ */+async function retireTakes(ctx: Parameters<RepairHandler['apply']>[0], item: RepairItem, page: ApprovedPage, hash: string, takes: AgentSessionTake[]): Promise<number[]> {+ const engine = ctx.engine;+ const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });+ if (snapshot && isSegmentedPage(snapshot.page)) return [];+ const body = snapshot ? serializePageToMarkdown(snapshot.page, snapshot.tags) : '';+ 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));+ 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));+ const content = takesPreparation.replaceFence(body, fence.takes.map(row => rows.has(row.rowNum) ? { ...row, active: false } : row));+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: page.slug, source_id: page.source_id, content,+ expected_revision: snapshot.revision, request_id: await repairRequestId(ctx, 'agent-session-facts', item, snapshot.revision) } });+ retired.push(...(await engine.executeRaw<{ id: number | string }>('SELECT id FROM takes WHERE id=ANY($1::bigint[]) AND active=false',+ [fenced.map(t => t.id)])).map(row => Number(row.id)));+ }+ return retired;+}diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 1f53ca7e86..a359b39c30 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -51,7 +51,7 @@ import { classifyItemFailure, ItemRun, type ItemFailure } from '../item-failure.import type { ProgressReporter } from '../progress.ts';import type { GenerationsSelection } from '../generations/repair.ts';-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'timeline-order', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'uncommitted-deletions', 'generations', 'fact-claim-dates', 'provenance', 'secret-spans'] as const;+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'timeline-order', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'uncommitted-deletions', 'generations', 'fact-claim-dates', 'provenance', 'secret-spans'] as const;export type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }@@ -130,7 +130,9 @@ export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmb/** `fact-claim-dates` (#7247): the bulk-loaded UTC day to repair (`--day`) instead of the detected ones. */day?: string;/** `secret-spans` (GST-327): the secret scanner rules to redact (`--rules`); default every named rule. */- rules?: string[] }+ rules?: string[];+ /** `agent-session-facts` (#8064): operator evidence, sessions whose cwd is under a prefix (`--cwd`) or named (`--session`), and the note's agent (`--principal`). */+ cwdPrefixes?: string[]; sessions?: string[]; principal?: string }export interface RepairHandler {kind: RepairKind;@@ -333,6 +335,7 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, sprefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string; held?: boolean; side?: string; state?: string;provenance?: string; cursor?: string; progress?: ProgressReporter;keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean; afterPage?: number; generations?: GenerationsSelection; day?: string; rules?: string[];+ cwdPrefixes?: string[]; sessions?: string[]; principal?: string;spec?: Pick<RepairKindSpec, 'explicit_only' | 'consent' | 'spends'>; maxLlmUsd?: number; deadline?: number; now?: () => number;/** GBRA-133: the CLI's termination signal; the apply stops before the next item with a result instead of dying mid-run. */stop?: AbortSignal;@@ -364,7 +367,8 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc...(opts.olderThan ? { olderThan: opts.olderThan } : {}), ...(opts.includeFailures ? { includeFailures: true } : {}), ...(opts.force ? { force: true } : {}),...(opts.from ? { from: opts.from } : {}), ...(opts.close ? { close: true } : {}), ...(opts.afterPage !== undefined ? { afterPage: opts.afterPage } : {}),...(opts.limit !== undefined ? { limit: opts.limit } : {}), ...(opts.generations ? { generations: opts.generations } : {}),- ...(opts.day ? { day: opts.day } : {}), ...(opts.rules?.length ? { rules: opts.rules } : {}) };+ ...(opts.day ? { day: opts.day } : {}), ...(opts.rules?.length ? { rules: opts.rules } : {}),+ ...(opts.cwdPrefixes?.length ? { cwdPrefixes: opts.cwdPrefixes } : {}), ...(opts.sessions?.length ? { sessions: opts.sessions } : {}), ...(opts.principal ? { principal: opts.principal } : {}) };const plan = await handler.plan(ctx.engine, scope, resumed, planOpts);const pending = opts.limit !== undefined ? plan.items.slice(0, opts.limit) : plan.items;const counters = await capacity(ctx);diff --git a/src/core/repair/failed-writes.ts b/src/core/repair/failed-writes.tsindex 39e7b54322..23bea8ed74 100644--- a/src/core/repair/failed-writes.ts+++ b/src/core/repair/failed-writes.ts@@ -160,6 +160,7 @@ function producerCommand(producer: string, sourceId: string): string {if (parts.includes('managed_file_repair')) return `gbrain repair frontmatter --source ${sourceId} (a frontmatter repair) or gbrain repair fences --source ${sourceId} (a fence repair)`;if (parts.includes('relink_facts')) return `gbrain facts relink --source ${sourceId} --dry-run`;if (parts.includes('managed_maintenance_expire_captured_facts')) return `gbrain repair captured-facts --source ${sourceId}`;+ if (parts.includes('managed_maintenance_agent_session_facts')) return `gbrain repair agent-session-facts --source ${sourceId}`;if (parts.includes('managed_maintenance_restore_extractor_facts')) return `gbrain repair extractor-facts --source ${sourceId}`;if (parts.includes('managed_maintenance_restore_redacted_facts')) return `gbrain repair redacted-facts --source ${sourceId}`;if (parts.includes('managed_maintenance_conversation_facts')) return `gbrain extract-conversation-facts --source-id ${sourceId} --dry-run`;diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex ebe06d611e..01cbbf955a 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -55,6 +55,7 @@ import { atomsRestoreRepair } from './atoms-restore.ts';import { extractorFactsRepair } from './extractor-facts.ts';import { conversationLabelsRepair } from './conversation-labels.ts';import { capturedFactsRepair } from './captured-facts.ts';+import { agentSessionFactsRepair, agentSessionFlagArgs } from './agent-session-facts.ts';import { redactedFactsRepair } from './redacted-facts.ts';import { loopFactsRepair } from './loop-facts.ts';import { ontologyFactsRepair } from './ontology-facts.ts';@@ -89,6 +90,7 @@ import { secretSpansRepair } from './secret-spans.ts';import { generationsRepair, generationsSelectionArgv, type GenerationsSelection } from '../generations/repair.ts';import { restoreDaysHint } from '../generations/config.ts';import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';+import { shellQuote } from '../shell-quote.ts';import type { OperationError } from '../ops/contract.ts';import type { ProgressReporter } from '../progress.ts';@@ -241,6 +243,22 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ '--expect <hash> expires exactly the previewed set; a fact that changed since reports changed_since_preview. Rows are expired, never withdrawn, '+ 'so remember can save the same claim again; fenced rows are struck in their page, which is re-embedded by its publication.',},+ 'agent-session-facts': {+ handler: agentSessionFactsRepair, embeds: 'effect', checks: ['agent_session_facts'], explicit_only: true, preview_bound: true, consent: 'destructive',+ consentText: {+ what: 'Re-attribute the previewed agent-session facts to the agent that wrote them and retire the takes built only from them',+ why: 'The preview listed each fact with its evidence and each take to retire; applying it changes exactly those rows, with no model calls.',+ risk: 'Nothing is deleted. Each fact gets attributed_to other and a "speaker: agent <label>, not the owner" note (fenced rows are rewritten in their page); '+ + 'each listed take becomes inactive (struck in its page when the page holds it). A fact or take that changed since the preview is kept.',+ user_message: 'Re-attribute the previewed facts from agent-launched sessions to their agent and retire the takes built only from them? Nothing is deleted.',+ },+ summary: 'Re-attribute capture-lane facts (writeback, compact, corpus sweep) saved as the owner\'s own from sessions an orchestrator launched (#8064): '+ + 'evidence is a speaker sidecar beside the session corpus, an operator --session <id>, or a session cwd under an operator --cwd <prefix>; a first user '+ + 'turn shared with three or more other sessions is ambiguous and applies only with --include-ambiguous. A claim the owner also stated is kept. '+ + 'Preview-bound and destructive: --apply --expect <hash> --yes sets attributed_to other with a speaker note (--principal <label> names the agent when '+ + 'no sidecar does) and retires the fact/self takes whose every contributing fact is then non-user; nothing is deleted, and a row that changed since '+ + 'reports changed_since_preview.',+ },'redacted-facts': {handler: redactedFactsRepair, embeds: 'effect', checks: ['facts_redaction_marker'], explicit_only: true,summary: 'Restore the words the prompt sanitizer deleted from stored facts before the fix (#7125: "Business System (ABS)" stored as '@@ -682,16 +700,19 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;async run(kind: RepairKind, scope: RepairScope, run: { limit?: number; sourceFlag?: string; explicit?: boolean; expect?: string; includeAmbiguous?: boolean; includeCrossEntity?: boolean; only?: string[]; skip?: string[];slugs?: string[]; noLlm?: boolean; maxLlmUsd?: number; deadline?: number; stop?: AbortSignal; recordDatabaseStops?: boolean;prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string; held?: boolean; side?: string; state?: string; provenance?: string; cursor?: string; progress?: ProgressReporter;- keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean; afterPage?: number; generations?: GenerationsSelection; day?: string; rules?: string[] } = {}): Promise<RepairResult> {+ keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean; afterPage?: number; generations?: GenerationsSelection; day?: string; rules?: string[];+ cwdPrefixes?: string[]; sessions?: string[]; principal?: string } = {}): Promise<RepairResult> {const ctx = { engine, config, logger, dryRun: !opts.apply, remote: false, sourceId: scope.source_ids[0], writeWaitMs } as OperationContext;const spec = repairSpec(kind, opts.registry);return runRepair(ctx, spec.handler, scope, { apply: opts.apply, limit: run.limit, embeddingModel, sourceFlag: run.sourceFlag, spec,embed: !opts.noEmbed && embeddingModel !== undefined, applyArgs: [...(opts.noEmbed && spec.embeds === 'inline' ? ['--no-embed'] : []),...(run.olderThan ? ['--older-than', run.olderThan] : []), ...(run.includeFailures ? ['--include-failures'] : []), ...(run.force ? ['--force'] : []),- ...(run.afterPage !== undefined ? ['--after', String(run.afterPage)] : []), ...(run.generations ? generationsSelectionArgv(run.generations) : []), ...(run.day ? ['--day', run.day] : []), ...(run.rules?.length ? ['--rules', run.rules.join(',')] : [])],+ ...(run.afterPage !== undefined ? ['--after', String(run.afterPage)] : []), ...(run.generations ? generationsSelectionArgv(run.generations) : []), ...(run.day ? ['--day', run.day] : []), ...(run.rules?.length ? ['--rules', run.rules.join(',')] : []),+ ...(kind === 'agent-session-facts' ? agentSessionFlagArgs(run).map(arg => shellQuote(arg)) : [])],explicit: run.explicit, expect: run.expect, includeAmbiguous: run.includeAmbiguous, includeCrossEntity: run.includeCrossEntity, only: run.only, skip: run.skip, slugs: run.slugs, noLlm: run.noLlm,maxLlmUsd: run.maxLlmUsd, deadline: run.deadline, ...(run.stop ? { stop: run.stop } : {}), ...(run.recordDatabaseStops ? { recordDatabaseStops: true } : {}), prefer: run.prefer, requests: run.requests, allDrifted: run.allDrifted, driftClass: run.driftClass, since: run.since,- held: run.held, side: run.side, state: run.state, provenance: run.provenance, cursor: run.cursor, progress: run.progress, keep: run.keep, requestId: run.requestId, olderThan: run.olderThan, includeFailures: run.includeFailures, force: run.force, from: run.from, close: run.close, afterPage: run.afterPage, generations: run.generations, day: run.day, rules: run.rules });+ held: run.held, side: run.side, state: run.state, provenance: run.provenance, cursor: run.cursor, progress: run.progress, keep: run.keep, requestId: run.requestId, olderThan: run.olderThan, includeFailures: run.includeFailures, force: run.force, from: run.from, close: run.close, afterPage: run.afterPage, generations: run.generations, day: run.day, rules: run.rules,+ cwdPrefixes: run.cwdPrefixes, sessions: run.sessions, principal: run.principal });},};}diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.tsindex 064a316e54..dc663489b1 100644--- a/test/fix-wave-5-integration.test.ts+++ b/test/fix-wave-5-integration.test.ts@@ -194,7 +194,7 @@ for (const backend of testBackends()) {const activeFacts = async () => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE source_markdown_slug='conversations/expired' AND expired_at IS NULL"))[0].n;const untouched = async () => { expect(await liveAtoms()).toBe(30); expect(await activeFacts()).toBe(0); };const previews = { 'accepted-takes': 'gbrain repair accepted-takes', 'google-file-modes': 'gbrain repair google-file-modes', 'stale-atoms': 'gbrain repair stale-atoms', 'atoms-restore': 'gbrain repair atoms-restore', 'extractor-facts': 'gbrain repair extractor-facts',- 'conversation-labels': 'gbrain repair conversation-labels', 'captured-facts': 'gbrain repair captured-facts', 'redacted-facts': 'gbrain repair redacted-facts', 'loop-facts': 'gbrain repair loop-facts', 'ontology-facts': 'gbrain repair ontology-facts', 'facts-rehome': 'gbrain repair facts-rehome', 'consolidate-ties': 'gbrain repair consolidate-ties', 'duplicate-facts': 'gbrain repair duplicate-facts', 'orphan-children': 'gbrain repair orphan-children', 'failed-writes': 'gbrain repair failed-writes', 'split-facts': 'gbrain repair split-facts',+ 'conversation-labels': 'gbrain repair conversation-labels', 'captured-facts': 'gbrain repair captured-facts', 'agent-session-facts': 'gbrain repair agent-session-facts', 'redacted-facts': 'gbrain repair redacted-facts', 'loop-facts': 'gbrain repair loop-facts', 'ontology-facts': 'gbrain repair ontology-facts', 'facts-rehome': 'gbrain repair facts-rehome', 'consolidate-ties': 'gbrain repair consolidate-ties', 'duplicate-facts': 'gbrain repair duplicate-facts', 'orphan-children': 'gbrain repair orphan-children', 'failed-writes': 'gbrain repair failed-writes', 'split-facts': 'gbrain repair split-facts',frontmatter: 'gbrain repair frontmatter', 'timeline-comments': 'gbrain repair timeline-comments', 'timeline-order': 'gbrain repair timeline-order', 'managed-sync-orphans': 'gbrain repair managed-sync-orphans', 'content-receipt-root': 'gbrain repair content-receipt-root', 'frontmatter-keys': 'gbrain repair frontmatter-keys', 'file-drift': 'gbrain repair file-drift','stuck-recovery': 'gbrain repair stuck-recovery', 'ghost-pages': 'gbrain repair ghost-pages', 'origin-twins': 'gbrain repair origin-twins', 'receipt-compaction': 'gbrain repair receipt-compaction', aliases: 'gbrain repair aliases', 'rename-identity': 'gbrain repair rename-identity','overwritten-edits': 'gbrain repair overwritten-edits', 'legacy-twins': 'gbrain repair legacy-twins', 'missing-tables': 'gbrain repair missing-tables', 'url-clone-fences': 'gbrain repair url-clone-fences', 'segmented-mirror': 'gbrain repair segmented-mirror',diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.jsonindex 1fffff2345..b9f96710bf 100644--- a/test/fixtures/goldens/doctor/content-pglite-human.json+++ b/test/fixtures/goldens/doctor/content-pglite-human.json@@ -134,6 +134,7 @@" [OK] conversation_label_facts: No conversation fact carries the pre-fix meeting-label signature (a 1970-01-01 segment on a label page)."," [OK] conversation_outcomes_stale: No conversation extraction outcome predates extractor version 1."," [OK] captured_facts_active: No active fact from a gbrain self-capture or paste candidate remains. This counts facts in the database; the self_capture check counts corpus files.",+ " [OK] agent_session_facts: No active owner-attributed fact from an agent-launched session remains."," [OK] facts_redaction_marker: No active fact holds a redaction marker."," [OK] fact_bulk_dates: No calendar day holds a bulk-loaded share of any source's facts."," [OK] loop_facts_drift: Every closed commitment loop has its fact retired.",diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.jsonindex 399d3d1fc0..38da984eca 100644--- a/test/fixtures/goldens/doctor/content-pglite-json.json+++ b/test/fixtures/goldens/doctor/content-pglite-json.json@@ -1838,6 +1838,21 @@"name": "captured_facts_active","status": "ok"},+ {+ "category": "brain",+ "details": {+ "ambiguous": 0,+ "docs": "docs/guides/repair.md#agent-session-facts",+ "evidenced": 0,+ "excluded": 0,+ "repair": "agent-session-facts",+ "unclassifiable": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "No active owner-attributed fact from an agent-launched session remains.",+ "name": "agent_session_facts",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.jsonindex aab53fdfa5..a65e860c5f 100644--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json@@ -2017,6 +2017,21 @@"name": "captured_facts_active","status": "ok"},+ {+ "category": "brain",+ "details": {+ "ambiguous": 0,+ "docs": "docs/guides/repair.md#agent-session-facts",+ "evidenced": 0,+ "excluded": 0,+ "repair": "agent-session-facts",+ "unclassifiable": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "No active owner-attributed fact from an agent-launched session remains.",+ "name": "agent_session_facts",+ "status": "ok"+ },{"category": "brain","details": {@@ -6798,6 +6813,21 @@"name": "captured_facts_active","status": "ok"},+ {+ "category": "brain",+ "details": {+ "ambiguous": 0,+ "docs": "docs/guides/repair.md#agent-session-facts",+ "evidenced": 0,+ "excluded": 0,+ "repair": "agent-session-facts",+ "unclassifiable": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "No active owner-attributed fact from an agent-launched session remains.",+ "name": "agent_session_facts",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.jsonindex 2ef292748e..4dc9bb433a 100644--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json@@ -2022,6 +2022,21 @@"name": "captured_facts_active","status": "ok"},+ {+ "category": "brain",+ "details": {+ "ambiguous": 0,+ "docs": "docs/guides/repair.md#agent-session-facts",+ "evidenced": 0,+ "excluded": 0,+ "repair": "agent-session-facts",+ "unclassifiable": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "No active owner-attributed fact from an agent-launched session remains.",+ "name": "agent_session_facts",+ "status": "ok"+ },{"category": "brain","details": {@@ -6804,6 +6819,21 @@"name": "captured_facts_active","status": "ok"},+ {+ "category": "brain",+ "details": {+ "ambiguous": 0,+ "docs": "docs/guides/repair.md#agent-session-facts",+ "evidenced": 0,+ "excluded": 0,+ "repair": "agent-session-facts",+ "unclassifiable": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "No active owner-attributed fact from an agent-launched session remains.",+ "name": "agent_session_facts",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 119a317be6..fd80d995e4 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -1715,6 +1715,21 @@"name": "captured_facts_active","status": "ok"},+ {+ "category": "brain",+ "details": {+ "ambiguous": 0,+ "docs": "docs/guides/repair.md#agent-session-facts",+ "evidenced": 0,+ "excluded": 0,+ "repair": "agent-session-facts",+ "unclassifiable": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "No active owner-attributed fact from an agent-launched session remains.",+ "name": "agent_session_facts",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 1bdc34428d..b07938c391 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -1771,6 +1771,21 @@"name": "captured_facts_active","status": "ok"},+ {+ "category": "brain",+ "details": {+ "ambiguous": 0,+ "docs": "docs/guides/repair.md#agent-session-facts",+ "evidenced": 0,+ "excluded": 0,+ "repair": "agent-session-facts",+ "unclassifiable": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "No active owner-attributed fact from an agent-launched session remains.",+ "name": "agent_session_facts",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 107359436b..d3d065ea87 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -1776,6 +1776,21 @@"name": "captured_facts_active","status": "ok"},+ {+ "category": "brain",+ "details": {+ "ambiguous": 0,+ "docs": "docs/guides/repair.md#agent-session-facts",+ "evidenced": 0,+ "excluded": 0,+ "repair": "agent-session-facts",+ "unclassifiable": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "No active owner-attributed fact from an agent-launched session remains.",+ "name": "agent_session_facts",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex 8a88f77037..1f685dbcae 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -581,6 +581,10 @@"category": "brain","name": "captured_facts_active"},+ {+ "category": "brain",+ "name": "agent_session_facts"+ },{"category": "brain","name": "facts_redaction_marker"diff --git a/test/repair-agent-session-facts.test.ts b/test/repair-agent-session-facts.test.tsnew file mode 100644index 0000000000..fcf6328d5e--- /dev/null+++ b/test/repair-agent-session-facts.test.ts@@ -0,0 +1,275 @@+/**+ * `gbrain repair agent-session-facts` (#8064) and doctor `agent_session_facts`, on keyless PGLite brains with no+ * git repository (an unmanaged brain, and a managed one whose content root is a plain directory).+ *+ * Protects: capture-lane facts from agent-launched sessions (speaker sidecar, an operator --cwd prefix or --session id)+ * are re-attributed to the agent with a speaker note; a session whose first user turn repeats across 3+ other sessions+ * is listed ambiguous and applied only with --include-ambiguous; a claim the owner also stated is kept; facts of a+ * session with no retained corpus are counted and untouched; fenced rows are rewritten in their page and database-only+ * 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 { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { serializePageToMarkdown } from '../src/core/markdown.ts';+import { runRepairCommand } from '../src/commands/repair.ts';+import { agentSessionFactsCheck } from '../src/commands/doctor/checks/agent-session-facts.ts';+import { runWaveChecks } from '../src/commands/doctor/wave-checks.ts';+import { writeSpeakerSidecar, speakerContextNote } from '../src/core/context/session-speaker.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { writeSingleFact } from '../src/core/facts/write-single.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+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';++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;+ listing?: Array<{ item: string; class: string; detail?: string }>; outcomes?: Record<string, number> }> }++async function repair(engine: BrainEngine, args: string[]): Promise<RepairJson> {+ const lines: string[] = [];+ const original = console.log;+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };+ try { await runRepairCommand(engine, ['agent-session-facts', ...args, '--json']); } finally { console.log = original; }+ return JSON.parse(lines.join('\n')) as RepairJson;+}+const applyArgs = (json: RepairJson) => json.results[0].apply_command.split(' ').slice(3);+const classes = (json: RepairJson) => Object.fromEntries((json.results[0].listing ?? []).filter(l => l.item.includes('#')).map(l => [Number(l.item.split('#')[1]), l.class]));++async function refusal(run: () => Promise<unknown>): Promise<OperationError> {+ try { await run(); } catch (error) { if (error instanceof OperationError) return error; throw error; }+ throw new Error('expected a refusal');+}++const attribution = async (engine: BrainEngine, id: number) => (await engine.executeRaw<{ attributed_to: string | null; context: string | null; active: boolean }>(+ 'SELECT attributed_to, context, expired_at IS NULL AS active FROM facts WHERE id=$1', [id]))[0]!;+const takeActive = async (engine: BrainEngine, id: number) => (await engine.executeRaw<{ active: boolean }>('SELECT active FROM takes WHERE id=$1', [id]))[0]!.active;+const counts = async (engine: BrainEngine) => (await engine.executeRaw<{ facts: number; takes: number }>(+ 'SELECT (SELECT count(*)::int FROM facts) AS facts, (SELECT count(*)::int FROM takes) AS takes'))[0]!;++/** A session corpus with: a sidecar session, a cwd session, a listed session, four sessions opening with one brief, an owner session. */+function corpusFixture(base: string) {+ const corpus = join(base, 'corpus');+ const spool = join(corpus, 'sourced');+ mkdirSync(spool, { recursive: true });+ const agents = join(base, 'agents');+ mkdirSync(join(agents, 'run-1'), { recursive: true });+ mkdirSync(join(base, 'agents-other'), { recursive: true });+ const session = (id: string, firstTurn: string) => writeFileSync(join(corpus, `${id}.txt`), `[user]\n${firstTurn}\n\n[assistant]\nOn it.`);+ const record = (id: string, cwd: string) => writeFileSync(join(spool, `${id}.source.json`), JSON.stringify({ version: 1, session_id: id, source_id: null,+ tier: null, cwd, harness: 'claude', created_at: '2026-10-01T00:00:00Z', resolved_at: null, source_incarnation: null }));+ session('sess-sidecar', 'Please triage the open issues for the docs lane.');+ writeSpeakerSidecar(corpus, 'sess-sidecar', { principal: 'worker-a', source: 'env' }, 'claude');+ session('sess-cwd', 'Run the nightly lint pass and fix what it reports.');+ record('sess-cwd', join(agents, 'run-1'));+ session('sess-sibling', 'Summarize the metrics dashboard for this week.');+ record('sess-sibling', join(base, 'agents-other'));+ session('sess-listed', 'Rebuild the search index for the archive.');+ for (const n of [1, 2, 3, 4]) session(`sess-t${n}`, `${BRIEF}\nTask ${n}: handle ticket ${n * 11}.`);+ session('sess-owner', 'Alice Example and I talked about the launch plan today.');+ return { corpus, agents };+}++describe('gbrain repair agent-session-facts, unmanaged repo-less brain', () => {+ let engine: PGLiteEngine;+ let base: string;+ let corpus: string;+ let agents: string;++ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ });++ afterAll(async () => {+ await engine.disconnect();+ });++ beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ base = mkdtempSync(join(tmpdir(), 'gbrain-agent-session-facts-'));+ ({ corpus, agents } = corpusFixture(base));+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpus);+ });+ afterAll(() => { if (base) rmSync(base, { recursive: true, force: true }); });++ const insert = async (fact: string, session: string | null, opts: { entity?: string; source?: string; attributed?: string | null } = {}) => Number((await engine.executeRaw<{ id: number }>(+ `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 [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]);+ await engine.executeRaw('UPDATE facts SET consolidated_into=$1, consolidated_at=now() WHERE id=ANY($2::bigint[])', [row!.id, factIds]);+ return Number(row!.id);+ };++ test('classification: sidecar, --cwd on path boundaries, --session, repeated opening, owner twin, unclassifiable', async () => {+ const sidecar = await insert('Prefers terse status updates', 'sess-sidecar');+ const sidecarCorpus = await insert('Wants every ticket closed by Friday', 'sweep:corpus:sess-sidecar.txt', { source: 'sweep:corpus' });+ const cwd = await insert('Believes lint warnings must block merges', 'sess-cwd', { source: 'hook:compact' });+ const sibling = await insert('Likes weekly metric summaries', 'sess-sibling');+ const listed = await insert('Commits to rebuilding the index nightly', 'sess-listed');+ const template = await insert('Prefers small commits', 'sess-t1');+ const ownerTwin = await insert('Prefers dark roast coffee', 'sess-sidecar');+ await insert('Prefers dark roast coffee', null, { source: 'cli:remember' });+ const owner = await insert('Is planning the launch', 'sess-owner');+ const gone = await insert('Likes long walks', 'sess-gone');+ const assistant = await insert('Assistant suggested a rollback', 'sess-sidecar', { attributed: 'assistant' });++ const bare = await repair(engine, []);+ expect(classes(bare)).toEqual({ [sidecar]: 'evidenced', [sidecarCorpus]: 'evidenced', [template]: 'ambiguous', [ownerTwin]: 'excluded:owner_also_said' });+ expect(bare.results[0].residuals).toMatchObject({ evidenced: 2, ambiguous: 1, excluded: 1, unclassifiable: 1, not_suspect: 4 });+ expect(bare.results[0].listing!.find(l => l.item.endsWith(`#${sidecar}`))!.detail).toContain('principal worker-a');++ const flagged = await repair(engine, ['--cwd', agents, '--session', 'sess-listed', '--principal', 'crew-b']);+ expect(classes(flagged)).toMatchObject({ [cwd]: 'evidenced', [listed]: 'evidenced' });+ expect(classes(flagged)[sibling]).toBeUndefined();+ expect(classes(flagged)[owner]).toBeUndefined();+ expect(classes(flagged)[gone]).toBeUndefined();+ expect(classes(flagged)[assistant]).toBeUndefined();+ expect(flagged.results[0].listing!.find(l => l.item.endsWith(`#${cwd}`))!.detail).toContain('principal crew-b');+ expect(flagged.results[0].apply_command).toContain(`--cwd ${agents} --session sess-listed --principal crew-b --apply --expect`);++ const finding = await agentSessionFactsCheck(engine);+ expect(finding.status).toBe('warn');+ expect(finding.details).toMatchObject({ evidenced: 2, ambiguous: 1, excluded: 1, unclassifiable: 1 });+ expect(finding.message).toContain('gbrain repair agent-session-facts');+ expect(finding.message).toContain('agreement');+ const wave = (await runWaveChecks(engine, { only: 'wave' })).find(f => f.spec.id === 'agent_session_facts')!;+ expect(wave.state).toBe('finding');+ expect(wave.spec.count(wave.check.details!)).toBe(3);+ }, 120_000);++ test('apply re-attributes, adds the note, retires only all-agent takes, deletes nothing; ambiguous needs --include-ambiguous', async () => {+ await engine.putPage(ALICE, { type: 'person', title: 'Alice Example', compiled_truth: '# Alice Example' }, { sourceId: 'default' });+ const a = await insert('Prefers terse status updates', 'sess-sidecar');+ const b = await insert('Prefers async standups', 'sess-cwd');+ const c = await insert('Prefers small commits', 'sess-t1');+ const ownerFact = await insert('Prefers async standups too', 'sess-owner');+ const agentOnly = await take('Prefers terse async updates', [a, b]);+ const mixed = await take('Prefers async standups', [b, ownerFact]);+ const ambiguousTake = await take('Prefers small commits', [c]);+ const before = await counts(engine);++ const preview = await repair(engine, ['--cwd', agents]);+ expect(preview.results[0].residuals).toMatchObject({ evidenced: 2, ambiguous: 1, takes_to_retire: 1 });+ expect(preview.results[0].listing!.filter(l => l.class === 'take_to_retire').map(l => l.item)).toEqual([`default:${ALICE}@take:${agentOnly}`]);+ expect((await refusal(() => repair(engine, ['--cwd', agents, '--apply']))).code).toBe('invalid_params');+ expect((await refusal(() => repair(engine, ['--cwd', agents, '--apply', '--expect', 'f'.repeat(16), '--yes']))).code).toBe('preview_changed');+ expect((await refusal(() => repair(engine, [...applyArgs(preview).filter(arg => arg !== agents && arg !== '--cwd')]))).code).toBe('preview_changed');++ const applied = await repair(engine, applyArgs(preview));+ expect(applied.results[0].outcomes).toEqual({ reattributed: 1, retired: 1 });+ for (const id of [a, b]) {+ const row = await attribution(engine, id);+ expect(row.attributed_to).toBe('other');+ expect(row.active).toBe(true);+ }+ expect((await attribution(engine, a)).context).toBe(speakerContextNote('worker-a'));+ expect((await attribution(engine, b)).context).toBe(speakerContextNote('agent-launched'));+ expect((await attribution(engine, c)).attributed_to).toBe('user');+ expect((await attribution(engine, ownerFact)).attributed_to).toBe('user');+ expect(await takeActive(engine, agentOnly)).toBe(false);+ expect(await takeActive(engine, mixed)).toBe(true);+ expect(await takeActive(engine, ambiguousTake)).toBe(true);+ expect(await counts(engine)).toEqual(before);++ const widened = await repair(engine, ['--cwd', agents, '--include-ambiguous']);+ expect(widened.results[0].apply_command).toContain('--include-ambiguous --apply --expect');+ expect(widened.results[0].residuals).toMatchObject({ evidenced: 0, ambiguous: 1, takes_to_retire: 1 });+ expect((await repair(engine, applyArgs(widened))).results[0].outcomes).toEqual({ reattributed: 1, retired: 1 });+ expect((await attribution(engine, c)).attributed_to).toBe('other');+ expect(await takeActive(engine, ambiguousTake)).toBe(false);+ expect(await takeActive(engine, mixed)).toBe(true);+ expect(await counts(engine)).toEqual(before);+ expect((await agentSessionFactsCheck(engine)).status).toBe('ok');+ }, 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, []);+ await engine.executeRaw("UPDATE facts SET visibility='world' WHERE id=$1", [id]);+ const applied = await repair(engine, applyArgs(preview));+ expect(applied.results[0].outcomes).toEqual({ changed_since_preview: 1 });+ expect((await attribution(engine, id)).attributed_to).toBe('user');+ }, 120_000);+});++async function seedEntity(engine: BrainEngine, root: string, slug: string, title: string, type: string) {+ const page = await engine.putPage(slug, { type: type as 'person', title, compiled_truth: `# ${title}` }, { sourceId: 'default' });+ await engine.executeRaw('UPDATE pages SET source_path=$1 WHERE id=$2', [`${slug}.md`, page.id]);+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;+ mkdirSync(join(root, slug.split('/')[0]!), { recursive: true });+ writeFileSync(join(root, `${slug}.md`), serializePageToMarkdown(snapshot.page, snapshot.tags));+}++describe('gbrain repair agent-session-facts, managed repo-less brain', () => {+ test('fenced rows are rewritten in their page, database-only rows by one maintenance request; a fenced take struck in its page, a database-only one retired by the request', async () => {+ const base = mkdtempSync(join(tmpdir(), 'gbrain-agent-session-managed-'));+ try {+ const { corpus } = corpusFixture(base);+ await managedBrain(async ({ engine, ctx }) => {+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpus);+ const write = (fact: string, entity: string | null) => writeSingleFact(engine, 'default', { fact, entity, provenance: 'hook:writeback', sessionId: 'sess-sidecar' }).then(r => r.id);+ const fenced = await write('Alice Example prefers terse status updates', ALICE);+ const fencedAcme = await write('Acme Example ships on Fridays', ACME);+ const dbOnly = await write('Carol Absent dislikes long meetings', 'Carol Absent');+ expect((await engine.executeRaw<{ row_num: number | null }>('SELECT row_num FROM facts WHERE id=$1', [fenced]))[0]!.row_num).not.toBeNull();+ expect((await engine.executeRaw<{ row_num: number | null }>('SELECT row_num FROM facts WHERE id=$1', [dbOnly]))[0]!.row_num).toBeNull();+ const [page] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE slug=$1 AND source_id='default'", [ACME]);+ const takeId = await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => {+ const [row] = await tx.executeRaw<{ id: number }>(`INSERT INTO takes (page_id, row_num, claim, kind, holder, weight, since_date, source, active)+ VALUES ($1, 90, 'Acme Example ships on Fridays', 'fact', 'self', 0.8, '2026-10-01', 'hook:writeback', true) RETURNING id`, [page!.id]);+ await tx.executeRaw('UPDATE facts SET consolidated_into=$1, consolidated_at=now() WHERE id=$2', [row!.id, fencedAcme]);+ return Number(row!.id);+ }, TEST_WRITE_ATTRIBUTION));+ await submitPageMutation(ctx, { operation: 'takes_add', params: { request_id: randomUUID(), slug: ALICE, claim: 'Alice Example prefers terse updates',+ kind: 'fact', holder: 'self', weight: 0.8 } });+ const [fencedTake] = await engine.executeRaw<{ id: number }>("SELECT t.id FROM takes t JOIN pages p ON p.id=t.page_id WHERE p.slug=$1 AND t.claim='Alice Example prefers terse updates'", [ALICE]);+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () =>+ tx.executeRaw('UPDATE facts SET consolidated_into=$1, consolidated_at=now() WHERE id=$2', [fencedTake!.id, fenced]), TEST_WRITE_ATTRIBUTION));+ const before = await counts(engine);++ const preview = await repair(engine, []);+ expect(classes(preview)).toEqual({ [fenced]: 'evidenced', [fencedAcme]: 'evidenced', [dbOnly]: 'evidenced' });+ expect(preview.results[0].residuals).toMatchObject({ takes_to_retire: 2 });+ const applied = await repair(engine, applyArgs(preview));+ expect(applied.results[0].outcomes).toEqual({ reattributed: 3, retired: 2 });+ for (const id of [fenced, fencedAcme, dbOnly]) {+ const row = await attribution(engine, id);+ expect(row).toMatchObject({ attributed_to: 'other', active: true });+ expect(row.context).toContain(speakerContextNote('worker-a'));+ }+ const alice = (await engine.readPageSnapshot(ALICE, { sourceId: 'default' }))!;+ expect(alice.page.compiled_truth).toContain('attributed_to');+ expect(alice.page.compiled_truth).toContain(speakerContextNote('worker-a'));+ expect(await takeActive(engine, takeId)).toBe(false);+ expect(await takeActive(engine, Number(fencedTake!.id))).toBe(false);+ expect((await engine.readPageSnapshot(ALICE, { sourceId: 'default' }))!.page.compiled_truth).toContain('~~Alice Example prefers terse updates~~');+ expect((await engine.executeRaw<{ n: number }>(+ "SELECT count(*)::int AS n FROM persistence_requests WHERE state='committed' AND intent->>'kind'='managed_maintenance_agent_session_facts'"))[0]!.n).toBe(2);+ expect(await counts(engine)).toEqual(before);+ expect((await agentSessionFactsCheck(engine)).status).toBe('ok');+ }, { setup: async ({ engine, root }) => {+ await seedEntity(engine, root, ALICE, 'Alice Example', 'person');+ await seedEntity(engine, root, ACME, 'Acme Example', 'company');+ } });+ } finally { rmSync(base, { recursive: true, force: true }); }+ }, 180_000);+});diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.tsindex eb3f353068..53c7e101d5 100644--- a/test/repair-explicit-only.test.ts+++ b/test/repair-explicit-only.test.ts@@ -24,7 +24,7 @@ import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';import { withEnv } from './helpers/with-env.ts';-const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'timeline-order', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'uncommitted-deletions', 'generations', 'fact-claim-dates', 'provenance', 'secret-spans'];+const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'timeline-order', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'uncommitted-deletions', 'generations', 'fact-claim-dates', 'provenance', 'secret-spans'];// GBRA-161: the generations preview carries its ledger kind and the restore window, so the printed command runs as is.const PREVIEW = (kind: RepairKind): string => kind === 'generations' ? 'gbrain repair generations --kind atom --since 30d' : `gbrain repair ${kind}`;let engine: PGLiteEngine;@@ -111,7 +111,7 @@ describe('surfaces that list instead of run', () => {expect(out.explicit_kinds).toEqual(EXPLICIT.map(kind => ({ kind, code: 'explicit_kind_required', preview_command: PREVIEW(kind),docs: 'docs/guides/repair.md#explicit-only-repair-kinds' })));}- expect(await captured(['--all'])).toContain('Explicit-only kinds (not run without their name; preview each): gbrain repair accepted-takes; gbrain repair google-file-modes; gbrain repair stale-atoms; gbrain repair atoms-restore; gbrain repair extractor-facts; gbrain repair conversation-labels; gbrain repair captured-facts; gbrain repair redacted-facts; gbrain repair loop-facts');+ expect(await captured(['--all'])).toContain('Explicit-only kinds (not run without their name; preview each): gbrain repair accepted-takes; gbrain repair google-file-modes; gbrain repair stale-atoms; gbrain repair atoms-restore; gbrain repair extractor-facts; gbrain repair conversation-labels; gbrain repair captured-facts; gbrain repair agent-session-facts; gbrain repair redacted-facts; gbrain repair loop-facts');});test('gbrain repair --all --apply exits 0 when explicit kinds are the only ones left', async () => {diff --git a/test/trust-write-gate-drift.test.ts b/test/trust-write-gate-drift.test.tsindex 8da93f280c..22132905bb 100644--- a/test/trust-write-gate-drift.test.ts+++ b/test/trust-write-gate-drift.test.ts@@ -52,6 +52,7 @@ const EXEMPT: Record<string, string> = {'src/core/persistence/loop-fact-retirement.ts': 'expires a loop fact (lifecycle)','src/core/persistence/memory-mutations.ts': 'forget (lifecycle); remember is gated in memory-prepare.ts','src/core/repair/captured-facts.ts': 'owner repair of existing rows',+ 'src/core/repair/agent-session-facts.ts': 'owner repair of existing rows','src/core/repair/consolidate-ties.ts': 'owner repair reopening the validity of existing facts (lifecycle)','src/core/repair/duplicate-facts.ts': 'owner repair behind a preview hash: supersedes exact copies of an existing fact with its oldest row (expired_at, superseded_by; lifecycle, no new text); fenced copies are struck through put_page, which runs the gate','src/core/generations/managed-retire.ts': 'versioned delete of a synthesis output a managed generation retires, plus its retired_by/retired_at stamp (lifecycle); no new text',