Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(review): extraction_review decisions through the page door, plus distinct
garrytanb2abf0d169bb
diff --git a/docs/architecture/derived-census.tsv b/docs/architecture/derived-census.tsvindex 3f1e3a88a6..f86a9167ee 100644--- a/docs/architecture/derived-census.tsv+++ b/docs/architecture/derived-census.tsv@@ -12,7 +12,6 @@ src/core/generations/adapters/chronicle-events.ts 1 primitive the Life Chroniclesrc/core/generations/adapters/single-page.ts 1 primitive the single-item page adapter (dream_summary, think_synthesis, drift_report) retires only through retireDerivedPagesInTransaction inside the generation activation (publish.ts); a publish replaces its one page in place and never retires it (GBRA-161 PR 5)src/core/generations/adapters/synthesis.ts 1 primitive the synthesis adapter retires matched earlier outputs of a re-synthesized transcript (synthesis-resynthesis) and operator-approved cleanup retirements (synthesis-cleanup) through retireDerivedPagesInTransaction inside the generation activation (publish.ts; GBRA-161 PR 4, #7065)src/core/minions/handlers/ingest-capture.ts 1 pending:inventory derived or mixed writer not yet on the generation primitive; reviewed in a later GBRA-161 PR-src/core/ops/extraction.ts 1 pending:inventory derived or mixed writer not yet on the generation primitive; reviewed in a later GBRA-161 PRsrc/core/page-body/segment-rewrite.ts 1 pending:inventory derived or mixed writer not yet on the generation primitive; reviewed in a later GBRA-161 PRsrc/core/persistence/connector-sync.ts 1 canonical connector sync applies an upstream deletion of a connected itemsrc/core/persistence/derived-retirement-hold.ts 4 primitive retireDerivedPagesInTransaction: versions, soft-deletes and stamps retired_by; the helper every generation adapter retires throughdiff --git a/docs/architecture/key-files/core-services-1-continued.md b/docs/architecture/key-files/core-services-1-continued.mdindex 2a2ceef85c..af25af547e 100644--- a/docs/architecture/key-files/core-services-1-continued.md+++ b/docs/architecture/key-files/core-services-1-continued.md@@ -9,10 +9,11 @@ The content-repair judgment tier under `src/core/content-repair/`, then the Retr- `src/core/content-repair/judgment.ts` — #6377 (Lane B3) the content-repair lane's model tier for a slug conflict: `judgeSlugConflict` builds the prompt from both files' frontmatter, headings and first 60 lines of body plus every line that mentions the other's slug anywhere in either body (evidence past line 60 counts), both slugs and paths, the hold's reason and the allowed answers, and parses exactly one JSON object `{"action":"remove_slug"}`, `{"action":"merge_into","canonical":"<one of the two slugs>"}` or `{"action":"needs_human"}` with an optional `why` sentence that reaches the run's output only, never hold metadata. The same failure classes, `thinkingOffControl` and output ceiling as the fence tier; a `canonical` outside the two slugs is `llm_malformed`. Memo key: sha256 of both participants' content + both ids + model + prompt version + rules version. The model is `models.content_repair` (an explicit model always runs), else `models.fence_repair`, else `CONTENT_REPAIR_MEASURED_MODELS` (the eval's qualifiers, best first, ties to the cheaper), else the fence list. Tests: `test/repair-slug-conflicts.test.ts`.- `src/core/content-repair/llm.ts` — #6377 (Lane B3) the paid call behind `judgment.ts`: one gateway chat under the fence repair's caps and ledger (`FENCE_REPAIR_LEDGER`, so one `fences.repair.max_usd_per_day` covers the whole lane and today's fence spend counts; the per-page cap applies per candidate), `fences.repair.llm=false` and `--no-llm` turn it off, the attempt memo keeps rejected bytes from costing twice, and a transient `llm_unavailable` does not consume the memo. Spend is reported as the item's `llm_usd` and carried into the `content_repair` receipt (`model`, `cost`); prompts never include the rest of either page.-- `src/core/context/` — Retrieval Reflex (Layer 1). `entity-salience.ts`: pure, zero-LLM, precision-biased `extractCandidates(text)` (capitalized runs + `@handles`, STOPWORDS + soft COMMON_WORDS + sentence-start guard, deterministic, capped; a lowercase weak pass additionally emits `weak: true` candidates — lowercase words ≥3 chars on a separate `MAX_WEAK_CANDIDATES=32` budget that never evicts strong candidates — which downstream may resolve through the alias arm ONLY) + `extractCandidatesFromWindow(turns)` (merges per-turn extraction across the last N turns by normalizeAlias form with occurrence/newest-turn/user-mention metadata; salience-ordered — recency > frequency > user-role — so the cap drops stale assistant chatter first). `retrieval-reflex.ts`: `resolveEntitiesToPointers(engine, sourceId, candidates, opts)` — alias arm (`resolveAliases`, caught per-arm for pre-v110 brains) + exact title/slug-suffix arm (real slugs are namespaced `people/x` but `slugify` drops the prefix) + two lexical identity arms behind `opts.lexicalArms` (kill switch: config `retrieval_reflex_lexical_arms` / env `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`, default on): weak lowercase candidates probe the ALIAS arm ONLY (never title/slug-suffix, where ordinary lowercase words would fabricate pointers) and require GLOBAL uniqueness across all sources in play; the surname arm resolves a strong single capitalized token ≥3 chars via a `lower(title) LIKE '% <token>'` predicate on the same query, with exact-arm precedence and ambiguity counted over ALL person rows carrying the surname — ambiguity in either arm injects nothing; pointers carry `source_id`/`arm`/`confidence`/`matchedNorm` (`ARM_CONFIDENCE` alias 0.9 / title 0.8 / title-surname 0.72 (deliberately above the volunteer layer's 0.70 gate, below title) / slug-suffix 0.6 lives next to the arm definitions; arm-2 provenance classified in JS since the combined OR can't report which predicate matched); opts: `sourceIds?` federated scope (alias arm loops per source, arm 2 uses `source_id = ANY`), `suppression?` ('slug-and-title' default; 'slug-only' REQUIRED under windowing — the title rule would suppress every entity merely mentioned in a prior window turn), ambient-channel event logging is DELIVERY-side, not in-resolver — `logDeliveredReflexPointers(engine, pointers)` fires only once a block is actually handed to the consumer (serve's resolve-IPC `onDelivered` hook post-write; `buildReflexAddition` post-timeout on the direct rung), so abandoned/timed-out blocks never pollute the volunteered-vs-used stats; its event write is registered synchronously before return so the CLI background-work drain cannot miss it; synopsis runs through `stripTakesFence`/`stripFactsFence` (the same privacy boundary `get_page` applies) so private facts never reach the prompt; `visibility: private` (and derived-private) pages never resolve on any arm unless the caller passes `excludePrivate: false` (default true, the remote-search predicate `privatePagesFilterFragment`; only `volunteer_context` widens, via `resolveExcludePrivatePages` for a trusted local caller — gbrain-evals N8-1/N8-2, pinned by `test/reflex-private-visibility.test.ts`); capped at `MAX_POINTERS`. `reflex.ts`: the orchestrator + engine-aware resolver ladder (host `resolveEntities` → PGLite serve IPC → Postgres cached process-singleton → disabled), zero-candidate fast path, fail-open + timeout, heartbeat write for the doctor check, `reflexEnabled(cfg)` (file/env gate, default ON; DB-plane does NOT gate — `assemble()` is sync); windowed extraction when `windowTurns` present and `retrieval_reflex_window_turns` (default 4; 1 = single-turn behavior) > 1 — switches suppression to slug-only; accept-side reflex-channel logging fires after the per-turn timeout admits the block (direct-Postgres rung only — IPC logs server-side at delivery; host-injected resolvers are a documented gap). `resolve-ipc.ts`: local unix-socket resolve protocol (client + server) so PGLite resolves through the single connection `gbrain serve` holds (a second opener would hit the exclusive lock; a subprocess would force-steal it past the 5-min staleness window and crash). Wired into both serve transports via `src/mcp/resolve-ipc-binding.ts` (engine-uniform; socket + secret keyed off `hash12(database_url)` under `~/.gbrain/run`, cleaned up on shutdown). Doctor surface: `retrieval_reflex_health` in `src/commands/doctor/checks/verbs-reflex.ts` (reads the heartbeat for truthful runtime status; categorized in `doctor-categories.ts`) + `volunteer_channels` (engine-aware sibling: groups `context_volunteer_events` by channel over 7 days so operators see which push channels — reflex/op/watch/claude-code/codex — actually fire; info-only; the LOCAL doctor runs it brain-wide while the remote report path threads the caller's source scope, so a source-bound token never sees other sources' activity counts/timestamps; counts are reconciled against the hook heartbeat over the same 7-day window — a mostly-degraded week gets a CAUTION note, since a server-side delivery count isn't proof of injection; quiet-channel guidance is engine-aware — Postgres brains are told the hook lane is quiet by design rather than to chase registration — and walks both quiet classes (installed-but-unregistered vs registered-but-quiet; the check can't inspect registration itself); pre-v117 tolerant, and transient DB errors are reported as such, never as an old schema; pinned by `test/doctor-volunteer-channels.test.ts`). Config: `retrieval_reflex` + `retrieval_reflex_max_pointers` + `retrieval_reflex_window_turns` + `retrieval_reflex_lexical_arms` in `src/core/config.ts` (env `GBRAIN_RETRIEVAL_REFLEX_WINDOW_TURNS`, `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`). `volunteer.ts`: `parseWindow` (lenient `user:`/`assistant:` prefixes, unprefixed → one user turn), `volunteerContext` (extract → resolve → +0.05 multi-turn/newest-turn boost → `min_confidence` 0.7 gate → cap 3/5; deterministic rationale strings, never raw conversation text; slug-only suppression), `volunteerUsageStats` (per-arm/channel precision from the `pages.last_retrieved_at > volunteered_at` join — APPROXIMATE: the 5-min last-retrieved throttle causes false negatives, unrelated reads false positives). `volunteer-events.ts`: `insertVolunteerEvents` (ONE multi-row parameterized INSERT), `logVolunteerEventsFireAndForget` + bounded drain registered as the `volunteer-events` background-work sink (order 4), `purgeStaleVolunteerEvents` (90-day GC, called from the dream cycle's purge phase). Policy layer ships as the `retrieval-reflex` recipe (`recipes/retrieval-reflex/`). Pinned by `test/context/entity-salience.test.ts`, `test/retrieval-reflex.test.ts`, `test/retrieval-reflex-pre-v110.test.ts`, `test/context/resolve-ipc.test.ts`, `test/doctor-retrieval-reflex.test.ts`, `test/volunteer-context.test.ts`, `test/e2e/volunteer-context-postgres.test.ts`. Checkpoint-compaction modules in this dir: `corpus-segments.ts` — engine-free content-addressed compaction segments (`<session>.seg-<hash24>.txt`, idempotent by name; parsers accept 12–64 hex), the hash-keyed per-session ledger (atomic tmp+rename, fail-open, entry order = the only ordinal), `sliceBoundaryWindow`/`splitByBoundaries`, the redacted `renderSegmentText` (a segment is NEVER written unscanned — unlike the session-end full write, which degrades-and-writes), exact-set `coverageComplete`/`decideCorpusMode` (count equality can be fooled by a duplicated boundary), the compact-time `bankCompactSegment` step (per-step deadline degrades, segment-then-ledger crash order), the openclaw tail boundary reader (`readOpenclawBoundaryTail`, delegates mapping to the adapter's exported `mapOpenclawLine`; also returns turn-stamped `toolCalls`/`toolCallTurnIndexes` for the Memorable receipt — name-only v1, `input: null` by design until an observation run characterizes OpenClaw's args field), and orphan-sidecar/aged-ledger GC — pinned by `test/corpus-segments.test.ts`. `checkpoint-harvest.ts` — the serve-side prompt harvest of a segment: bounded FIFO (cap 8, 60s abort), sweep-shared claim fencing, capability-then-kill-switch gates, `signal.aborted` POST-check (the pipeline returns partials on abort; an aborted run writes nothing and stays retryable), receipt sidecar before idempotent manifest publish (source-scoped `getPage` verification — a link that resolves to nothing is never banked), `.ingested` last, explicit `shutdownCheckpointHarvest()` called by serve BEFORE `engine.disconnect()` (the background-work drain is CLI-exit-only by contract), a writeback turn whose facts preflight finds the canonical writer busy (`writer_lock_unavailable`, before any model call) re-queued after 5, 15 and 45 s (`writer_busy_requeued`; the retry skips admission, a pending retry dedups a re-schedule as `already_queued`, shutdown clears pending retries) while a compact segment's busy refusal stays an error the sweep resumes, and error reasons that keep the error's code or `reason` within the 48-char reason-code shape (`operationerror:writer_lock_unavailable`), the first failure of each reason logged to stderr once per serve run — pinned by `test/checkpoint-harvest.serial.test.ts`. `hook-heartbeat.ts` — the hooks telemetry JSONL extracted from hook.ts (hook.ts re-exports; serve-side writers never import the command module); allowlist carries the checkpoint `segment`/`inserted`/`duplicate`/`links` count-only fields. `session-state.ts` also carries the v132 `checkpoint_manifest` helpers (`getCheckpointManifest`/`appendCheckpointManifest`: newest-first, dedup-by-slug, cap 20, seg-hash completion key, fail-open on pre-v132 schema) — pinned by `test/checkpoint-manifest.test.ts`. `sensitivity-scan.ts` + `compile-view.ts` — the compile-context stack: composed detector (secret-scan + ordered `PII_PATTERNS` + path/blocklist families + operator pattern file; uniform `.gbrain-scan-allow` fingerprint escape hatch; CONTENT hits drop an entry, CONFIG/loader failures THROW so the caller aborts without writing) and the deterministic compiled-view builder (recency decay anchored to the newest candidate `updated_at`, never wall-clock; total-order (score desc, slug asc); source-scoped listPages/getPage reads that skip op-layer write-backs and pass `excludePrivate: true` on every arm, so private pages never reach the compiled file; whole-file `packToBudget` math that never passes a <=0 budget) — pinned by `test/sensitivity-scan.test.ts` + `test/compile-view.test.ts` + `test/e2e/compile-context-pglite.test.ts`; the CLI shell is `src/commands/compile-context.ts` (targets claude-code|codex|openclaw, AGENTS.md managed-marker splice that throws on damaged markers, atomic writes, `--check` recompile-and-compare exit codes; the guide is `docs/guides/checkpoint-compaction.md`). It also owns the whole Memorable seam's engine-free plumbing: the session-receipt JSONL (`session-receipts.jsonl`, `appendSessionReceipt` — dedup by post-redaction `content_hash` so a resumed session neither duplicates its receipt nor re-fires the relay; tail-rewrite compaction triggered by the 32 MB byte ceiling alone — the read fires exactly when the pass will act, with the 2000-line budget enforced inside the pass — and a `skipCompaction` seam the openclaw compact() lane sets unconditionally: the hook lane is the ONE receipts compactor, so two processes can never race the read-filter-rename rewrite); ONE bounded adaptive `readJsonlTail` reader shared by `lastReceiptMatches`, `lastRelayResult` and `readSessionReceiptsTail` (a receipt line can exceed the 1 MB window — the window doubles rather than reading "empty"); `maybeTrimRelayResults` (BOTH capture lanes trim the child-appended `memorable-relay.jsonl` — an openclaw-only host has no hook lane, and converging newest-keeping trims make concurrent trims safe: mtime-stale preferred, hard 8 MB force backstop, line-boundary cut keeping the newest lines — the child appends open-by-path, so the residual loss window is one in-flight write); the CONSENT STAMP (`memorable-consent.json`, 0600, written ONLY by config-set's disclosure flow — deliberately outside config.json, which the external CLI full-file-rewrites; scope-bound to the disclosure sha256 + `MEMORABLE_CAPTURE_HARNESSES`, so widening the capture surface invalidates old stamps); `memorableGateAllowed(cfg)` ({allowed, reason: kill_switch|disabled|disclosure_missing} — one reason vocabulary for hook, context-engine and doctor); `memorableConsentEvidence()` (the CLI-side opt-in read fail-closed from ~/.memorable/config.json, dated provisional spec note, GBRAIN_MEMORABLE_CONFIG test seam); `redactedToolCallsJson` (the security-load-bearing span-filter + highEntropy redaction, ONE implementation for both capture lanes; string LEAVES are redacted raw before serialization — scanning the serialized JSON would let quoted secrets through via \" escaping — with a post-serialization re-scan as belt-and-braces); `recordAndRelayReceipt` (per-receipt harness scope-binding first — a harness outside `MEMORABLE_CAPTURE_HARNESSES` is refused with `memorable_harness_undisclosed` → receipt → prior-run outcome surfacing with the child's reason clamped via the shared `clampRelayCause` (32 chars, so the 16-char prefix keeps composites inside the 48-char reason bound) and appended LAST → consent evidence → `resolveMemorableBin` → detached spawn; never throws; `spawnFn` test seam); and `priorRelayFailure`, which surfaces the PREVIOUS relay run's self-reported exit status so a relay that records nothing is never reported healthy. `resolveMemorableBin` does the pre-spawn PATH/`MEMORABLE_BIN` resolution so a missing CLI is a named heartbeat reason rather than a silent async ENOENT. #6195: `entity-salience.extractCandidates` also emits lowercase 2-3-word weak n-grams (`multiToken`, own budget `MAX_WEAK_NGRAM_CANDIDATES` = 16, never across punctuation, never all stopwords/common words) that ride the exact weak-alias fold, and `retrieval-reflex` arm 2.6 (`weak-title`, 0.72, behind `lexicalArms`, private pages hidden by default) matches them to the exact title of a person/company/organization page whose title is globally unique; single lowercase words stay alias-only.+- `src/core/context/` — Retrieval Reflex (Layer 1). `entity-salience.ts`: pure, zero-LLM, precision-biased `extractCandidates(text)` (capitalized runs + `@handles`, STOPWORDS + soft COMMON_WORDS + sentence-start guard, deterministic, capped; a lowercase weak pass additionally emits `weak: true` candidates — lowercase words ≥3 chars on a separate `MAX_WEAK_CANDIDATES=32` budget that never evicts strong candidates — which downstream may resolve through the alias arm ONLY) + `extractCandidatesFromWindow(turns)` (merges per-turn extraction across the last N turns by normalizeAlias form with occurrence/newest-turn/user-mention metadata; salience-ordered — recency > frequency > user-role — so the cap drops stale assistant chatter first). `retrieval-reflex.ts`: `resolveEntitiesToPointers(engine, sourceId, candidates, opts)` — alias arm (`resolveAliases`, caught per-arm for pre-v110 brains) + exact title/slug-suffix arm (real slugs are namespaced `people/x` but `slugify` drops the prefix) + two lexical identity arms behind `opts.lexicalArms` (kill switch: config `retrieval_reflex_lexical_arms` / env `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`, default on): weak lowercase candidates probe the ALIAS arm ONLY (never title/slug-suffix, where ordinary lowercase words would fabricate pointers) and require GLOBAL uniqueness across all sources in play; the surname arm resolves a strong single capitalized token ≥3 chars via a `lower(title) LIKE '% <token>'` predicate on the same query, with exact-arm precedence and ambiguity counted over ALL person rows carrying the surname — ambiguity in either arm injects nothing; pointers carry `source_id`/`arm`/`confidence`/`matchedNorm` (`ARM_CONFIDENCE` alias 0.9 / title 0.8 / title-surname 0.72 (deliberately above the volunteer layer's 0.70 gate, below title) / slug-suffix 0.6 lives next to the arm definitions; arm-2 provenance classified in JS since the combined OR can't report which predicate matched); opts: `sourceIds?` federated scope (alias a... (line truncated to 2000 chars)- `src/core/context/hook-heartbeat.ts` — the hooks telemetry plane under `<gbrain home>/integrations/hooks/` (`heartbeat.jsonl`, `status.json`, session receipts, the memorable relay log; directories 0700, appends 0600). Entries hold counters, durations and codes only: `HEARTBEAT_ALLOWED_KEYS` is the full key allowlist CI greps the fixture against, and includes `pattern` (scanner pattern name), `fingerprint` (`sha256:<16 hex>`) and `hint` (fixed text) for refusals. `near_duplicate` is the shadow count on the `writeback_dedup` event that `facts/capture-dedup.ts` appends (lane in `reason`, exact drops in `duplicate`). `relayRefusalHeartbeat(hit)` builds the line `context-engine.ts` writes when its high-entropy re-scan refuses a memorable relay (`event: relay`, `outcome: degraded`, `reason: secret_scan_refused`); the receipt and relay are skipped for that compaction window and the checkpoint is kept. `memorableGateAllowed` gates the relay lane; span redaction runs `redactFindings` with `highEntropy: true`. Tests: `test/context-engine-checkpoint.serial.test.ts`.- `src/core/context/seat.ts` — seat identity for captured sessions (#4618), engine-free. `resolveSeat` returns the lowercased `GBRAIN_SEAT` label when it matches `SEAT_LABEL_RE` (`^[a-z0-9][a-z0-9._-]{0,63}$`), else `home-<8 hex>` over the realpath of the harness home (Claude Code: the directory holding `projects/` in the transcript path, then `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `~/.claude`; codex: `CODEX_HOME` or `~/.codex`; OpenClaw: the agent directory holding `sessions/`), so no raw path reaches frontmatter; `GBRAIN_SEAT=off` (the opt-out) resolves to null and nothing is recorded. `writeSeatSidecar` writes `<sessionId>.seat.json` (`{version: 1, seat, seat_source, hook_lane, harness, first_seen}`, 0600, tmp+rename) unless one exists, reporting `seat_conflict` when the existing seat differs; `readSeatSidecar` accepts only a valid v1 record. `SEAT_REASON_HINTS` holds the fixed heartbeat hints. The sidecar name and its GC live in `corpus-segments.ts` (`seatFileName`, `SEAT_SIDECAR_SUFFIX`).- `src/core/context/ipc-path.ts` — engine-free local socket discovery and private Unix fallback when the complete role-specific address exceeds 103 UTF8 bytes. Hashes the physical parent plus basename under a fixed OS temporary root, verifies ownership/0700 directory/0600 client socket without following fallback symlinks, and retains a native binding claim through actual server close. Existing Unix socket accessibility is rechecked even when a runtime reports ENOENT; permission/resource probe failures never authorize stale takeover; on Windows a PGLite data-dir socket (`.gbrain-<kind>.sock`) over afunix's 107 UTF-8 bytes moves to `%USERPROFILE%\.gbrain\run\<kind>-<hash12(canonical data dir, case-folded)>.sock` (`windowsLocalIpcSocketPath`, the Postgres run-dir scheme; the secret stays in the data dir), and `localIpcPathTooLong` reports a resolved path still over the platform budget, which `ipc-path-too-long.ts` turns into the typed `ipc_path_too_long` serve log line and doctor `ipc_socket_path` warning (#6573; `test/ipc-path-windows-fallback-6573.test.ts` on every OS, the native bind and 20-cycle stability probe in `test/windows-ipc-long-path-6573.serial.test.ts` on windows-latest); Windows named pipes retain a native Global mutex through actual close; `windows-ipc.ts` normalizes namespace prefixes while native Windows Unicode casing defines the mutex identity. `test/local-ipc-path.test.ts` covers concurrent real processes, SIGKILL recovery, active-connection shutdown, aliases and unsafe paths. The published CLI smoke also uses a long Unicode datastore path.- `src/core/entities/near-name.ts` — Flag-only near-name matcher for #2942 (never merges, never writes `entity_identities`; `entity-identity.ts` stays manual-only). `classifyNearName` returns `same` (normalized-equal after corporate suffixes, or a strong `name-variants.ts` shape), `typo` (Damerau distance 1 on 3–64 normalized characters) or `acronym` (one word equals a multi-word name's initials, at most one letter different). Candidates come from symmetric one-deletion keys plus initials keys, so recall is complete for those kinds; past `NEAR_NAME_MAX_KEYS_PER_SHARD` the index splits into shards by key hash (a pair shares a key, so it lands whole in one shard). `loadEntityNames` reads one source's fact-entity pages plus the source pack's linkable types, leaving out private pages for callers that exclude them. Pinned by `test/review-lists.test.ts`.-- `src/core/review-lists.ts` — The two lists `extraction_pending` adds beside `pending`: `unattributed` (active facts with no entity, newest first, world-only for remote callers, each with a `remember` + `entity` + `replaces` relink action, never a forget) and opt-in `possible_duplicates` (entity pages created in the last `since_days` whose name is near another entity's name or alias; pairs in `aliases` or `distinct_from` are skipped). The duplicates cursor walks recent pages within a shard, then the next shard, and reports `complete` only after the last shard; index builds are serialized per process. Pinned by `test/review-lists.test.ts` and the Postgres parity file.+- `src/core/review-lists.ts` — The two lists `extraction_pending` adds beside `pending`: `unattributed` (active facts with no entity, newest first, world-only for remote callers, each with a `remember` + `entity` + `replaces` relink action, never a forget) and opt-in `possible_duplicates` (entity pages created in the last `since_days` whose name is near another entity's name or alias; pairs in `aliases` or `distinct_from` are skipped; each row carries `mark_distinct`, the owner's `extraction-review distinct` command). The duplicates cursor walks recent pages within a shard, then the next shard, and reports `complete` only after the last shard; index builds are serialized per process. Pinned by `test/review-lists.test.ts` and the Postgres parity file.+- `src/core/persistence/publication-guard.ts` — GBRA-215: the source-scoped guard (`withPublicationGuard`, a `gbrain_cycle_locks` lease named `review-publication:<source>`) that review decisions take while they re-read a page, re-check it and publish through the page door; ingest undo takes the same guard, so a decision and an undo on one source never interleave between check and write. The wait is bounded (`PUBLICATION_GUARD_WAIT_MS`), then `lock_busy` with a read-only locks fix; the lease TTL frees a dead holder. Pinned by `test/extraction-review-door.serial.test.ts` and `test/e2e/extraction-review-door-postgres.test.ts`.diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex 70e4192579..d4b0b1db1a 100644--- a/docs/architecture/key-files/graph-and-facts.md+++ b/docs/architecture/key-files/graph-and-facts.md@@ -77,16 +77,16 @@ rejection of serve-only flags before a brain opens.- `src/core/context/delta-cursor.ts` — pure helpers for delta's per-arm cursor: the opaque base64url `cursor` (`{v:1, p:[since, slug], f:[created_at, id]}`, validated like `since`), microsecond ISO normalization and the one-microsecond clamp, `nextPagesPos`/`nextFactsPos` (delivered prefix, `now() - 2 s` horizon `DELTA_COMMIT_LAG_MS`, the facts cursor computed from raw rows so a duplicate cluster split by a budget cut loses nothing), `resolveDeltaStart` and `legacyDeltaCursor`. `test/delta-cursor-integrity.test.ts`.- `src/core/facts/question-recall.ts` — recall's `question`: `parseQuestionParam` refuses `supersessions`, `include_expired` and more than 2,000 characters with the corrected call as `fix.mcp`; `rankFactsByQuestion` resolves `entity` per source to pairs and runs `unlinkedNamesakes` on the whole filtered pool before ranking, embeds the question once through `embedQueryBounded` (the gateway's query-embedding cache, so a `query` of the same text shares it; the embedding opt-out, a missing provider or a failed embed rank by term share and set `facts_degraded.reason`), ranks with `search/fact-relevance.ts` under the `recall.question_admission` rule (`reserve` default, or `facts_arm`; pool, uncomparable count and rule read concurrently), hydrates the ranked ids through `rowToFact`, counts uncomparable facts (`facts_degraded.unembedded`, the `facts_unembedded` notice with the `embed --stale --facts` preview), sets `calibration` (recall's informational `facts_calibration: {status: 'unmeasured', model_key}`, #6590) when the cosine arm ran on a model with no row in `FACT_ADMISSION_FLOOR_EVIDENCE` (`search/fact-relevance.ts`, shared with doctor `fact_admission_floors`), with the `facts_calibration_unmeasured` info notice deduped per brain per session by its `dedupe_key` (test `test/recall-facts-calibration-6590.test.ts`), and turns a DB error into `unavailable` (`fix.next: wait`). `recallHintNotice` builds `recall_hint`. Tests: `test/recall-question.test.ts` (both engines), `test/recall-question-cli.test.ts`.-- `src/core/ops/facts.ts` — shared fact/memory operations, including `recall` and the `delta` cursor. Every recall response carries `facts_order` (`newest`, or `relevance` when `question` ranked the facts arm through `facts/question-recall.ts`); a `query` call without `question` or a fact filter emits `recall_hint`. `context_pack` and `delta` `facts[]` carry recall's `fact_id` and `provenance` (the stored `facts.source`), read in one batched `withProvenance` lookup by the delivered ids, so hot memory and MCP `_meta` stay unchanged; remote callers get provenance through the same redaction as the fact text, and it never enters `text` (#6146, `test/context-pack-fact-traceability.test.ts`). `context_pack` `entity_facts[]` carry the packed cards' own facts (#6724, entry in core-services-3.md). Recall keeps source/visibility and fact filters before per-arm candidate limits. Its default/explicit `facts_first` packing preserves the frozen memory-verb contract, including the positive sub-one budget quirk. Optional `query_first` packs the ranked page prefix first only with a nonblank query and positive finite budget; floor-zero and exhausted remainders explicitly return empty arms rather than call the unbounded zero-budget packer. Neither arm skips oversized prefix items or truncates. No-query and inactive-budget paths keep legacy behavior. Only policy-supplied calls add `budget_packing` effective-policy/reason and candidate/kept/dropped/estimated-used accounting. Counter sums match the frozen fields. Do not change the global packer or fact relevance to implement this policy. Delta rejects calendar-invalid ISO dates and years outside 0001-9999 (on the parsed UTC value) before normalization across fractional-second forms, while preserving valid six-digit microsecond cursors. Delta's per-arm cursor (contributor audit wave P0): the start position resolves `cursor` > `since` (whole tuple, slug only when supplied) > the session row; each arm advances through its delivered prefix only (`src/core/context/delta-cursor.ts`), an arm that failed or never finished holds, the conservative legacy `next_cursor.since`/`slug` never passes the oldest undelivered fact, and a legacy caller at an unpageable same-timestamp boundary is refused with `delta_cursor_upgrade_required`. Incomplete wakes emit `delta_incomplete` (`fix.next: wait`, `report` on the third consecutive wake, counted atomically in `session_context_state.degraded_wakes` with an in-process fallback when the store is down); a failed state read refuses with `unavailable`/`session_state` instead of re-initializing at now. `test/recall-budget-policy.test.ts` pins recall behavior; `test/ambient-recall.test.ts` pins delta cursor validation; `test/delta-cursor-integrity.test.ts` (both engines) pins every no-advance path, the facts drain, legacy safety and the commit-visibility bound.+- `src/core/ops/facts.ts` — shared fact/memory operations, including `recall` and the `delta` cursor. Every recall response carries `facts_order` (`newest`, or `relevance` when `question` ranked the facts arm through `facts/question-recall.ts`); a `query` call without `question` or a fact filter emits `recall_hint`. `context_pack` and `delta` `facts[]` carry recall's `fact_id` and `provenance` (the stored `facts.source`), read in one batched `withProvenance` lookup by the delivered ids, so hot memory and MCP `_meta` stay unchanged; remote callers get provenance through the same redaction as the fact text, and it never enters `text` (#6146, `test/context-pack-fact-traceability.test.ts`). `context_pack` `entity_facts[]` carry the packed cards' own facts (#6724, entry in core-services-3.md). Recall keeps source/visibility and fact filters before per-arm candidate limits. Its default/explicit `facts_first` packing preserves the frozen memory-verb contract, including the positive sub-one budget quirk. Optional `query_first` packs the ranked page prefix first only with a nonblank query and positive finite budget; floor-zero and exhausted remainders explicitly return empty arms rather than call the unbounded zero-budget packer. Neither arm skips oversized prefix items or truncates. No-query and inactive-budget paths keep legacy behavior. Only policy-supplied calls add `budget_packing` effective-policy/reason and candidate/kept/dropped/estimated-used accounting. Counter sums match the frozen fields. Do not change the global packer or fact relevance to implement this policy. Delta rejects calendar-invalid ISO dates and years outside 0001-9999 (on the parsed UTC value) before normalization across fractional-second forms, while preserving valid six-digit microsecond cursors. Delta's per-arm cursor (contributor audit wave P0): the start position resolves `cursor` > `since` (whole tuple, slug only when supplied) > the session row; each arm advances through its delivered prefix o... (line truncated to 2000 chars)- `src/core/markdown-code.ts` — `stripCodeBlocks` masks fenced and inline code while preserving every CR/LF and UTF-16 code-unit offset. Citation paragraphs and later link references retain their original boundaries, including after an unclosed fence. `parseTimelineEntries` in `src/core/link-extraction.ts` groups the optional dash with its trailing whitespace so leading whitespace does not trigger overlapping repetition. Existing date and delimiter rules remain unchanged. Standalone backtick and tilde fences require valid closing markers; historical inline triple-backtick spans remain masked. Pinned through real FS/DB link and timeline consumers by `test/timeline-parser-regression.test.ts`; its adversarial whitespace workload runs in a timeout-bounded child process. #6133: inline spans pair backtick runs of equal length (CommonMark), found read-only by `fence-scan.ts` `scanMarkdownCode`/`inlineCodeEndAt` over a view where a bare CR is a space (so a span may still cross one), so a double-backtick span and a span holding a single backtick are masked whole and a backslash-escaped backtick opens nothing; the lint `placeholder-date` rule (`src/commands/lint.ts`) runs over the masked text, so placeholders in inline code no longer fire (`test/lint-3958.test.ts`, `test/timeline-parser-regression.test.ts`).-- `src/core/check-resolvable.ts` — Resolver validation: reachability, MECE overlap, DRY checks, structured fix objects. `CROSS_CUTTING_PATTERNS.conventions` is an array (notability gate accepts `conventions/quality.md` and `_brain-filing-rules.md`). `extractTriggers()` delegates to the shared SKILL.md parser, so MECE gap detection and the trigger index agree on block lists, single-line flow sequences, wrapped flow sequences, and CRLF input. `extractDelegationTargets()` parses `> **Convention:**`, `> **Filing rule:**`, and inline backtick references. DRY suppression is proximity-based via `DRY_PROXIMITY_LINES = 40`. `parseResolverEntries` accepts BOTH the markdown table AND a compact list format (`- **skill-name**: trigger1 | trigger2 | trigger3` or `- skill-name: trigger1 | trigger2`); shapes can mix in one file, folded by the multi-resolver merge. Skill name MUST be kebab-lowercase (regex `[a-z][a-z0-9-]+`) so prose bullets like `- **Note**:`/`- **Convention**:`/`- **TODO**:` don't false-match as skill rows. `skillPath` is ALWAYS derived as `skills/<name>/SKILL.md`: an optional `→ \`skills/path\`` (or ASCII `->`) suffix is stripped from the trigger but NOT honored as the path — two consumers (`routing-eval.ts:skillSlugFromPath`, the manifest lookup) assume the convention; use the table format for non-conventional paths. Multi-trigger rows fan out to one entry per trigger sharing the same `skillPath`; `checkResolvable` dedupes so the reachability count counts each skill once. Pinned by `test/check-resolvable.test.ts` (resolver shapes plus trigger array syntax cases) + `test/check-resolvable-openclaw-compact.test.ts` (8 cases over `test/fixtures/openclaw-compact-resolver/` and `test/fixtures/openclaw-mixed-merge/`). Tutorial: `docs/guides/scaling-skills.md` (three-tier scaling: ~300-skill agent to ~4K tokens/turn from ~25K). `checkResolvable(skillsDir, opts?)` takes an optional `skillsDirSource` (the detection tier from `autoDetectSkillsDir`, threaded by both callers: doctor.ts and the check-resolvable command; an explicit `--skills-dir` passes `null`). An `unreachable` issue downgrades from `error` to `warning` only when ALL hold: the directory was found via the ungated `cwd_walk_up` tier, no resolver file contributes rows (no `RESOLVER.md`; a generic `AGENTS.md` with zero table rows counts as absent), unreachable skills outnumber reachable ones, and no `manifest.json` exists on disk. This keeps a foreign tool's `skills/` dir walked up to from cwd from being scored as a broken gbrain skillpack, while a real skillpack (RESOLVER.md present, higher-confidence tier, dense trigger coverage, or any manifest.json, even a corrupted one) stays strict. A foreign dir with zero `triggers:` and no resolver file still hard-fails via the `missing_file` branch (separate follow-up).+- `src/core/check-resolvable.ts` — Resolver validation: reachability, MECE overlap, DRY checks, structured fix objects. `CROSS_CUTTING_PATTERNS.conventions` is an array (notability gate accepts `conventions/quality.md` and `_brain-filing-rules.md`). `extractTriggers()` delegates to the shared SKILL.md parser, so MECE gap detection and the trigger index agree on block lists, single-line flow sequences, wrapped flow sequences, and CRLF input. `extractDelegationTargets()` parses `> **Convention:**`, `> **Filing rule:**`, and inline backtick references. DRY suppression is proximity-based via `DRY_PROXIMITY_LINES = 40`. `parseResolverEntries` accepts BOTH the markdown table AND a compact list format (`- **skill-name**: trigger1 | trigger2 | trigger3` or `- skill-name: trigger1 | trigger2`); shapes can mix in one file, folded by the multi-resolver merge. Skill name MUST be kebab-lowercase (regex `[a-z][a-z0-9-]+`) so prose bullets like `- **Note**:`/`- **Convention**:`/`- **TODO**:` don't false-match as skill rows. `skillPath` is ALWAYS derived as `skills/<name>/SKILL.md`: an optional `→ \`skills/path\`` (or ASCII `->`) suffix is stripped from the trigger but NOT honored as the path — two consumers (`routing-eval.ts:skillSlugFromPath`, the manifest lookup) assume the convention; use the table format for non-conventional paths. Multi-trigger rows fan out to one entry per trigger sharing the same `skillPath`; `checkResolvable` dedupes so the reachability count counts each skill once. Pinned by `test/check-resolvable.test.ts` (resolver shapes plus trigger array syntax cases) + `test/check-resolvable-openclaw-compact.test.ts` (8 cases over `test/fixtures/openclaw-compact-resolver/` and `test/fixtures/openclaw-mixed-merge/`). Tutorial: `docs/guides/scaling-skills.md` (three-tier scaling: ~300-skill agent to ~4K tokens/turn from ~25K). `checkResolvable(skillsDir, opts?)` takes an optional `skillsDirSource` (the detection tier from `autoDetectSkillsDir`, threaded by both callers... (line truncated to 2000 chars)-- `src/core/entities/resolve.ts` — Free-form entity name → canonical slug resolution. `resolveEntitySlug(engine, source_id, raw)`: exact slug (slug-shaped input via `looksLikeSlug`: lowercase Unicode letters and numbers plus `/`, `_`, `-`, so non-Latin slugs match exactly) → alias-exact (an unambiguous `page_aliases` hit via `resolveAliases`, verified against LIVE pages since `page_aliases` has no FK — a stale alias row can never point at a deleted page; fail-open on pre-v110 brains missing the table; `ResolutionSource` reports `alias_exact`) → unique source-scoped full-basename match for multi-token names across people/companies/hosts/projects/concepts → unambiguous bare-name prefix expansion across `people/<token>-%` + `companies/<token>-%` (when several candidates share one directory, the single page titled exactly the bare name wins: "Acme" over "Acme Labs", gbrain-evals N9-5; cross-directory collisions and duplicate exact titles stay ambiguous) (tagged `prefix_expansion`, not `fuzzy_match`: the sole candidate is chosen by cardinality, so `facts/backstop.ts` appends an unverified-resolution note to the fact's context cell) → fuzzy candidates for multi-token input taken only when `sameEntityName` holds (same name tokens ignoring case, punctuation, order, accents and corporate suffixes), the candidate is an entity page (person/company/fund/org, host, project, concept or deal — never a meeting or note), and it is the only such candidate, so a near-name such as "Alicia Example" never lands on Alice and a person without a page never lands on a meeting page → per-segment holding fallback (`slugify`; `slugifySegment` where `slugify` would delete letters; null if empty). Bare-name collisions never use popularity as confidence. `isIdentityEntity(slug, type)` (person/company/fund/organization types or their directories) and `sameEntityName` are shared with `makeResolver`. The phantom-redirect helper takes a fuzzy hit only at trigram ≥ 0.7 with a 0.1 margin over the runner-up. Two helpers for the phantom-redirect pass: `resolvePhantomCanonical(engine, sourceId, phantomSlug)` SKIPS the exact-slug step (a phantom slug `'alice'` would exact-match itself and no-op the redirect); returns the canonical only when non-null AND contains `/`. `findPrefixCandidates(engine, sourceId, token)` is a standalone SQL query returning ALL candidates across `PREFIX_EXPANSION_DIRS` (hardcoded `['people', 'companies']`) via `slug LIKE ANY($N::text[])` over patterns `dir/token` + `dir/token-%`, cap of 10 ordered by `connection_count DESC, slug ASC` (non-ranking link types never count). Pinned by `test/entity-resolve.test.ts` (explicit, unique, ambiguous-person, and shared-token-company cases) plus `test/phantom-redirect.test.ts` (resolvePhantomCanonical 3 cases + findPrefixCandidates 6 cases incl. multi-dir ambiguity and the `people/aliceberg`-doesn't-match-`alice` false-positive guard). When a name resolves to two or three pages that form one identity-sibling group (`mentions/siblings.ts` `siblingCanonical`), the alias and basename arms of `resolveEntitySlugWithSource` and `resolveStrictEntityReference` return the group's lowest slug instead of an ambiguity or a fallback slug; `resolveStrictEntityReference` also accepts the source pack's linkable entity types (accounts, CRM records) as fact entities. Retired pages (#6898: `canonical: false`, a `superseded_by`/`merged_into` target, or an alias/redirect `status`) never win a guessing arm; exact, basename and alias hits follow `superseded_by` (5 hops, same source, readable, cycle-safe) or stay unresolved. Alias lookup also tries the reference's words joined by space, `-` and `_` (last slug segment, same parent dir). Pinned by `test/entity-resolve-retired-alias-6898.test.ts`.+- `src/core/entities/resolve.ts` — Free-form entity name → canonical slug resolution. `resolveEntitySlug(engine, source_id, raw)`: exact slug (slug-shaped input via `looksLikeSlug`: lowercase Unicode letters and numbers plus `/`, `_`, `-`, so non-Latin slugs match exactly) → alias-exact (an unambiguous `page_aliases` hit via `resolveAliases`, verified against LIVE pages since `page_aliases` has no FK — a stale alias row can never point at a deleted page; fail-open on pre-v110 brains missing the table; `ResolutionSource` reports `alias_exact`) → unique source-scoped full-basename match for multi-token names across people/companies/hosts/projects/concepts → unambiguous bare-name prefix expansion across `people/<token>-%` + `companies/<token>-%` (when several candidates share one directory, the single page titled exactly the bare name wins: "Acme" over "Acme Labs", gbrain-evals N9-5; cross-directory collisions and duplicate exact titles stay ambiguous) (tagged `prefix_expansion`, not `fuzzy_match`: the sole candidate is chosen by cardinality, so `facts/backstop.ts` appends an unverified-resolution note to the fact's context cell) → fuzzy candidates for multi-token input taken only when `sameEntityName` holds (same name tokens ignoring case, punctuation, order, accents and corporate suffixes), the candidate is an entity page (person/company/fund/org, host, project, concept or deal — never a meeting or note), and it is the only such candidate, so a near-name such as "Alicia Example" never lands on Alice and a person without a page never lands on a meeting page → per-segment holding fallback (`slugify`; `slugifySegment` where `slugify` would delete letters; null if empty). Bare-name collisions never use popularity as confidence. `isIdentityEntity(slug, type)` (person/company/fund/organization types or their directories) and `sameEntityName` are shared with `makeResolver`. The phantom-redirect helper takes a fuzzy hit only at trigram ≥ 0.7 with a 0.1 margin over the runner... (line truncated to 2000 chars)-- `src/core/facts/drain.ts` + `drain-scheduler.ts` + `src/core/cycle/facts-drain.ts` + `src/commands/doctor/checks/facts-drain.ts` — the automatic facts drain on PGLite (no job worker there). `runFactsDrain(engine, { owner, signal, wallClockMs })` runs queued `facts-absorb` jobs one at a time through the real handler (`withFactsAbsorbHaltCooldown(makeFactsAbsorbHandler)`), with `authorizeJobExecution`/`withSubmissionAuthority`, lock renewal, a 25 ms yield between jobs and the owner's AbortSignal forwarded into the handler. Spend runs inside one `BudgetTracker` (`facts:drain`) capped at min(`facts.drain_budget_usd` 1.00, the rest of `facts.drain_daily_budget_usd` 5.00 over a rolling 24 h); `capSource` is `user` once either cap is set, so an unpriced model warns and runs under the defaults and refuses with the `gbrain pricing set` fix under a user cap. Before each claim the job's worst case (8,000-char turn + `facts.extraction_max_tokens`) must fit; `facts.drain_max_jobs` (50) bounds a run. Every stop other than an empty queue is a deferral that leaves jobs queued with no attempt counted (`queue.deferJob`): `no_key`, `extraction_unavailable`, `budget_exhausted`, `daily_budget_exhausted`, `job_over_budget`, `no_pricing`, `provider_halted`, shutdown. Run records (newest 20, 48 h) and the first-run marker live in config `facts.drain_state`; `readFactsDrainStatus` feeds doctor `facts_drain` and the readiness capability `facts_drain`. The first run prints the backlog, estimated spend, caps and opt-out on stderr and queues a `facts_drain_first_run` notice; deferrals raise one `facts_drain_deferred` notice per reason per process (`takeFactsDrainNotice`, taken by stdio `dispatch.ts`). Never writes stdout. `startFactsDrainScheduler` owns one unref'd 10-minute timer: it runs when the owner saw no activity since the previous tick or 30 minutes passed since the last run, one run in flight, an owner veto per tick (`canRun`), the timer callback returns the tick's promise (a test awaits it), and `stop()` aborts and waits up to 5 s. Owners: stdio `serve` (`installFactsDrain`, stdin-data activity, delegated-sync veto, stopped first in the shutdown chain), `serve --http` (every tick; stopped before engine disconnect) and the cycle phase `facts_drain` (PGLite only; Postgres skips `not_applicable` for the drain). GBRA-130 C-9: before the drain, on every engine, the phase re-submits dead put_page `facts-absorb` jobs whose failure is retryable (`src/core/facts/dead-absorb-retry.ts`: provider or config class, once extraction is servable, at most hourly per key and `facts.absorb_retry.max_resubmits` times; set in config `facts.absorb_retry.state`); `gbrain facts retry-dead` lists, resets and clears it and doctor `facts_extraction_health` counts it. Test: `test/pathological/c-9-facts-absorb-dead.test.ts`. Opt-out: `facts.extraction_enabled false`. Tests: `test/facts-drain.test.ts`, `test/facts-drain-scheduler.test.ts`, `test/facts-absorb-keyless-deferral.test.ts`, the `facts_drain` row of `test/managed-phase-matrix.test.ts`.-- `src/core/facts/capture-dedup.ts` — the capture-lane (`hook:writeback`, `sweep:corpus`, `hook:compact`) duplicate policy (#5888). `cosineVerdict(source, score, claim, existing)` is the one cosine rule at every fact-write decision point (`backstop.ts` unmanaged loop, `single-prepare.ts` `decideSingleFact` and so `persistence/facts-prepare.ts` under its publication guard): explicit lanes drop at the embedding model's calibrated threshold (`supersession-threshold.ts`; none for an uncalibrated model); capture lanes never drop by cosine and return `near_duplicate` only at 0.92+ when `claimsDiverge` (negation, number, date or amount tokens) is false. `wouldDedupSamePage(ctx, existing, score, claim)` (#6333, shadow only) is the explicit-lane same-page rewording rule the backstop measures but never acts on: the nearest candidate shares the lane, `source_session` and visibility, sits at or above `SAME_PAGE_REWORDING_THRESHOLD` (0.85) and does not `claimsDiverge`; the backstop counts (`would_dedup_same_page`) and logs it, and inserts the fact as before. Its measured false positives (Lisbon→Porto) are pinned in `test/backstop-same-page-shadow-6333.test.ts` and are why no drop path ships. `dedupCapturedFacts` runs before the backstop's managed/unmanaged branch: one indexed read (`(source_id, visibility, gbrain_fact_fingerprint(fact))`, `LIMIT 50`) drops a candidate whose fingerprint matches an active fact on the same entity (or both none) or on an entity whose title/`page_aliases` the claim names (`claimNamesEntity`, whole words), visible where the candidate is (private sees world+private, world sees world), within 15 minutes of `ctx.turnAt` (else now) or written by a capture lane in the same `canonicalConversationKey` conversation (`sweep:corpus:<file>` and `.txt` stripped via `corpusFileSessionId`). Read failure keeps the candidate and warns with the lane; each drop logs lane, matched id and rule on stderr; drops and shadow near-duplicate counts append one `writeback_dedup` heartbeat event. Explicit `remember` never passes through it. `collapseHotFacts` groups hot-memory/delta rows by the SQL `fact_fingerprint` column (`FactListOpts.fingerprint`), merges different entities only when the claim names one, and keeps the newest row with `entity_slugs[]`. `collapseFactReads` (#7043) runs it per source and visibility for recall, entity cards and `saved_facts` before `limit`. The check is best-effort outside the publication transaction (two concurrent capture writers can both insert). Tests: `test/facts/capture-dedup-policy.test.ts`, `test/capture-dedup.test.ts` (unmanaged + coordinator-managed bound source; Postgres via `test/e2e/capture-dedup-postgres.test.ts`).+- `src/core/facts/drain.ts` + `drain-scheduler.ts` + `src/core/cycle/facts-drain.ts` + `src/commands/doctor/checks/facts-drain.ts` — the automatic facts drain on PGLite (no job worker there). `runFactsDrain(engine, { owner, signal, wallClockMs })` runs queued `facts-absorb` jobs one at a time through the real handler (`withFactsAbsorbHaltCooldown(makeFactsAbsorbHandler)`), with `authorizeJobExecution`/`withSubmissionAuthority`, lock renewal, a 25 ms yield between jobs and the owner's AbortSignal forwarded into the handler. Spend runs inside one `BudgetTracker` (`facts:drain`) capped at min(`facts.drain_budget_usd` 1.00, the rest of `facts.drain_daily_budget_usd` 5.00 over a rolling 24 h); `capSource` is `user` once either cap is set, so an unpriced model warns and runs under the defaults and refuses with the `gbrain pricing set` fix under a user cap. Before each claim the job's worst case (8,000-char turn + `facts.extraction_max_tokens`) must fit; `facts.drain_max_jobs` (50) bounds a run. Every stop other than an empty queue is a deferral that leaves jobs queued with no attempt counted (`queue.deferJob`): `no_key`, `extraction_unavailable`, `budget_exhausted`, `daily_budget_exhausted`, `job_over_budget`, `no_pricing`, `provider_halted`, shutdown. Run records (newest 20, 48 h) and the first-run marker live in config `facts.drain_state`; `readFactsDrainStatus` feeds doctor `facts_drain` and the readiness capability `facts_drain`. The first run prints the backlog, estimated spend, caps and opt-out on stderr and queues a `facts_drain_first_run` notice; deferrals raise one `facts_drain_deferred` notice per reason per process (`takeFactsDrainNotice`, taken by stdio `dispatch.ts`). Never writes stdout. `startFactsDrainScheduler` owns one unref'd 10-minute timer: it runs when the owner saw no activity since the previous tick or 30 minutes passed since the last run, one run in flight, an owner veto per tick (`canRun`), the timer callback returns the tick's promise (a test aw... (line truncated to 2000 chars)+- `src/core/facts/capture-dedup.ts` — the capture-lane (`hook:writeback`, `sweep:corpus`, `hook:compact`) duplicate policy (#5888). `cosineVerdict(source, score, claim, existing)` is the one cosine rule at every fact-write decision point (`backstop.ts` unmanaged loop, `single-prepare.ts` `decideSingleFact` and so `persistence/facts-prepare.ts` under its publication guard): explicit lanes drop at the embedding model's calibrated threshold (`supersession-threshold.ts`; none for an uncalibrated model); capture lanes never drop by cosine and return `near_duplicate` only at 0.92+ when `claimsDiverge` (negation, number, date or amount tokens) is false. `wouldDedupSamePage(ctx, existing, score, claim)` (#6333, shadow only) is the explicit-lane same-page rewording rule the backstop measures but never acts on: the nearest candidate shares the lane, `source_session` and visibility, sits at or above `SAME_PAGE_REWORDING_THRESHOLD` (0.85) and does not `claimsDiverge`; the backstop counts (`would_dedup_same_page`) and logs it, and inserts the fact as before. Its measured false positives (Lisbon→Porto) are pinned in `test/backstop-same-page-shadow-6333.test.ts` and are why no drop path ships. `dedupCapturedFacts` runs before the backstop's managed/unmanaged branch: one indexed read (`(source_id, visibility, gbrain_fact_fingerprint(fact))`, `LIMIT 50`) drops a candidate whose fingerprint matches an active fact on the same entity (or both none) or on an entity whose title/`page_aliases` the claim names (`claimNamesEntity`, whole words), visible where the candidate is (private sees world+private, world sees world), within 15 minutes of `ctx.turnAt` (else now) or written by a capture lane in the same `canonicalConversationKey` conversation (`sweep:corpus:<file>` and `.txt` stripped via `corpusFileSessionId`). Read failure keeps the candidate and warns with the lane; each drop logs lane, matched id and rule on stderr; drops and shadow near-duplicate counts append one `writeback_dedup`... (line truncated to 2000 chars)- `src/core/facts/relink.ts` + `relink-publish.ts` + `relink-model.ts` + `relink-reasons.ts` + `relink-schema.ts` — `gbrain facts relink` (`src/commands/facts.ts`, CLI-only, host-only). Candidates are active database-only rows with `entity_slug IS NULL` (fence-owned subjectless rows are only counted), walked by id from `--after-id` over `idx_facts_unlinked_active`. Free tiers via `inferFactSubject`, then the model tier (`facts.extraction_model`, batches of 25, `--max-usd` cap, private facts only with `--include-private`; an answer must quote the fact and pass the strict resolver). Publication is one coordinator request per entity page (`relink_facts`, dispatched from `persistence/service.ts`, managed or not): each fact's whole row is pinned by hash; prepare and the locked validation must classify identically; linked rows take fresh fence positions (row id, embedding and provenance kept, context gains `entity relinked from <tier>`) ahead of the page projection; exact duplicates retire expired and detached; nothing is superseded; withdrawn claims and facts the user didn't say (`not_user_attributed`) are skipped; attempt rows and the `decide_sweep_deferred` handoff (`enqueueRelinked`, when the conflict slot is not off) commit in the same transaction. Write target follows `persistence/fact-write-target.ts` (the remember rule): bound write-through publishes the file, write-through off or connector-database publishes the page body only, an unbound write-through source is refused as `unfenceable` (relink never claims an owner). `fact_relink_attempts` (migration v187) holds `linked`/`deduped` records and model verdict memos (`no_subject`, `ambiguous`, `unverified_match`) stopping paid reruns unless `--retry-model`. `RELINK_REASONS` is the one reason list (code, memoized, fix) for output, memo, guide. Pinned by `test/facts-relink.test.ts` and `test/facts-relink-routing.test.ts` (+ `test/e2e/facts-relink-routing.test.ts`).@@ -94,30 +94,17 @@ rejection of serve-only flags before a brain opens.- `src/core/extract-frontmatter.ts` — `resolveIncludeFrontmatter(engine, explicit?)`: the single answer for "extract `related:`/`sources:` frontmatter link edges too?" (`autopilot.incremental_extract_include_frontmatter`; explicit flag > file plane > DB plane via `isConfigTruthy` > false, fail-closed on an unreadable config table). Resolved INSIDE the shared helpers — `extractLinksForSlugs` and `extractStaleFromDB` default `opts.includeFrontmatter` through it, the same in-helper pattern as `isGlobalBasenameEnabled` — so sync's inline extract, the GitHub/Google source inline extracts, the `extract_stale` minion, `gbrain maintain`, the cycle's extract phase and `gbrain extract --stale` (flag absent → configured knob) all agree; no caller passes a literal `false`. Pinned by `test/extract-include-frontmatter-config.serial.test.ts` (resolver precedence + a source-text guard on the call sites + a PGLite link-row test through `extractLinksForSlugs`).-- `src/core/extract/receipt-writer.ts` + `src/core/extract/rollup-writer.ts` + `src/commands/extract-status.ts` + `src/commands/extract-explain.ts` + `src/commands/extract-benchmark.ts` + `src/core/schema-pack/scaffold-extractable.ts` — unified extract operator surface. Every shipped extractor (deterministic `facts.conversation` in `src/commands/extract-conversation-facts.ts` + three LLM-backed cycle phases at `src/core/cycle/{extract-atoms,synthesize-concepts,propose-takes,extract-facts}.ts`) writes ONE receipt page per run (`writeReceipt`) + UPSERTs a row to `extract_rollup_7d` (`upsertExtractRollup`). Receipt slug `extracts/{date}/{kind}/{source_id}/{run_id_short}/round-{N}.md`; frontmatter stamps BOTH `type: extract_receipt` AND `dream_generated: true` (belt+suspenders against extraction-loop guard drift). `extract_receipt` joins `ALL_PAGE_TYPES` in `src/core/types.ts`; `extracts/` prefix gets a 0.3x source-boost demote in `src/core/search/source-boost.ts`. Migration v104 adds `extract_rollup_7d (kind, source_id, day, cost_usd, halt_count, eval_pass_count, eval_fail_count, round_completed_count, rollup_write_failures, updated_at)` with PK `(kind, source_id, day)` + `idx_extract_rollup_7d_day`. Rollup writes best-effort with process-scoped error-dedup so transient DB failures bump `rollup_write_failures` instead of crashing the cycle. Migration v239 adds `halt_reasons JSONB NOT NULL DEFAULT '{}'` (DDL only, no backfill): `classifyRunStop({ error })` takes `true` (an unclassified halt) or one word of the closed `HALT_REASONS` vocabulary (`provider_auth`, `provider_billing`, `provider_rate_limit`, `provider_model_not_found`, `no_pricing`, `integrity_guard`, `item_error`; a budget or deadline cap is an expected stop, never a reason), and the same UPSERT increments that key with bound parameters (`$N::text`, `jsonb_set`). `unknown` is never stored: the doctor read computes it as `halt_count - sum(halt_reasons)` (`haltReasonsWithUnknown`), so pre-v239 rows and older writers on the same day stay consistent. A brain whose schema is behind v239 loses rollup rows (one stderr line names `migrations_pending` and `gbrain apply-migrations --yes --no-autopilot-install`) and never throws. `extract_health` doctor check reads last 7 days, warns at halt-rate > 10% AND when rollup_write_failures > 0, lists `halt_reasons` and `top_halt_reason` per kind and names the top reason in the warn line (`atoms=42.9%, last halt 1d ago (top reason: item_error ×3)`); pre-v104 brains report `ok`. Pinned by `test/extract-rollup-halt-reasons-5495.test.ts` (both engines). CLI: `gbrain extract status [--source-id ID] [--kind X] [--verbose] [--json]` (7-day rollup, sorted halt_rate desc + cost desc, top-5 + "more rows" hint, stable `schema_version: 1`); `gbrain extract --explain <kind>` (resolution chain pack-declared vs built-in cycle phase, prompt_template + fixture_corpus paths with `✓`/`(missing)`, last 7d rollup); `gbrain extract benchmark --pack X --kind Y` (loads pack fixture corpus through strict path validation — rejects absolute paths, `..` traversal, null bytes, AND symlinks resolving outside pack root; ships as a stub-reporter). `src/core/schema-pack/manifest-v1.ts` widens `extractable` from `z.boolean()` to `z.union([z.boolean(), ExtractableSpecSchema])` (carries `prompt_template`, `fixture_corpus`, `eval_dimensions`, `benchmark_min_recall`, plus reserved `verifier_path` — parses but refuses at runtime); `extractableSpecsFromPack` + `getExtractableSpec` + `refuseVerifierPathInV042` in `src/core/schema-pack/extractable.ts`; `gbrain schema scaffold-extractable <type> --pack <pack>` declares the type extractable, generates 5 placeholder fixtures + a prompt template stub under `packs/<pack>/{fixtures,prompts}/extract/`, refuses to overwrite without `--force`. Pinned by `test/extractable-spec-widening.test.ts` (22), `test/extract/receipt-writer.test.ts` (12, canonical PGLite block R3+R4), `test/extract/benchmark.test.ts` (17), `test/extract/status.test.ts` (15), `test/schema-pack/scaffold-extractable.test.ts` (15, privacy guards), `test/doctor-extract-health.test.ts` (8).+- `src/core/extract/receipt-writer.ts` + `src/core/extract/rollup-writer.ts` + `src/commands/extract-status.ts` + `src/commands/extract-explain.ts` + `src/commands/extract-benchmark.ts` + `src/core/schema-pack/scaffold-extractable.ts` — unified extract operator surface. Every shipped extractor (deterministic `facts.conversation` in `src/commands/extract-conversation-facts.ts` + three LLM-backed cycle phases at `src/core/cycle/{extract-atoms,synthesize-concepts,propose-takes,extract-facts}.ts`) writes ONE receipt page per run (`writeReceipt`) + UPSERTs a row to `extract_rollup_7d` (`upsertExtractRollup`). Receipt slug `extracts/{date}/{kind}/{source_id}/{run_id_short}/round-{N}.md`; frontmatter stamps BOTH `type: extract_receipt` AND `dream_generated: true` (belt+suspenders against extraction-loop guard drift). `extract_receipt` joins `ALL_PAGE_TYPES` in `src/core/types.ts`; `extracts/` prefix gets a 0.3x source-boost demote in `src/core/search/source-boost.ts`. Migration v104 adds `extract_rollup_7d (kind, source_id, day, cost_usd, halt_count, eval_pass_count, eval_fail_count, round_completed_count, rollup_write_failures, updated_at)` with PK `(kind, source_id, day)` + `idx_extract_rollup_7d_day`. Rollup writes best-effort with process-scoped error-dedup so transient DB failures bump `rollup_write_failures` instead of crashing the cycle. Migration v239 adds `halt_reasons JSONB NOT NULL DEFAULT '{}'` (DDL only, no backfill): `classifyRunStop({ error })` takes `true` (an unclassified halt) or one word of the closed `HALT_REASONS` vocabulary (`provider_auth`, `provider_billing`, `provider_rate_limit`, `provider_model_not_found`, `no_pricing`, `integrity_guard`, `item_error`; a budget or deadline cap is an expected stop, never a reason), and the same UPSERT increments that key with bound parameters (`$N::text`, `jsonb_set`). `unknown` is never stored: the doctor read computes it as `halt_count - sum(halt_reasons)` (`haltReasonsWithUnknown`), so pre-v239 rows and older w... (line truncated to 2000 chars)-- `src/core/extraction-review.ts` — Extraction quarantine lane markers, sibling of `src/core/quarantine.ts` / `embed-skip.ts` (frontmatter-key pattern, no schema migration). Auto-extracted stubs from untrusted input carry the PAIR `provenance: 'auto-extracted'` + `status: 'unverified'` (both required — user pages with their own `status`/`provenance` never match). Exports `quarantineMarkers()`, `isUnverifiedExtraction()` (JS predicate) and `unverifiedExtractionFragment(alias)` — the single SQL source of truth consumed by `buildSourceFactorCase` (namespace source-boost guard), both engines' `getUnverifiedExtractionPageIds`, the `extraction_pending` op, and the `unverified_extractions` doctor check, so filter and marker keys can never drift. Consequences: unverified stubs are excluded from the compiled-truth fusion boost + the `people/`/`companies/` source-boost (rank as ordinary content), stamped `unverified: true` in search results (`stampUnverifiedExtractions`, hybrid.ts), listed by `extraction_pending`, promoted (status → `verified`, provenance kept for audit) or rejected (soft-delete) by the owner-only `extraction_review` op. Pinned by `test/extraction-review.test.ts` (PGLite) + `test/e2e/extraction-review-postgres.test.ts` (live Postgres parity).+- `src/core/extraction-review.ts` — Extraction quarantine lane markers, sibling of `src/core/quarantine.ts` / `embed-skip.ts` (frontmatter-key pattern, no schema migration). Auto-extracted stubs from untrusted input carry the PAIR `provenance: 'auto-extracted'` + `status: 'unverified'` (both required — user pages with their own `status`/`provenance` never match). Exports `quarantineMarkers()`, `isUnverifiedExtraction()` (JS predicate) and `unverifiedExtractionFragment(alias)` — the single SQL source of truth consumed by `buildSourceFactorCase` (namespace source-boost guard), both engines' `getUnverifiedExtractionPageIds`, the `extraction_pending` op, and the `unverified_extractions` doctor check, so filter and marker keys can never drift. Consequences: unverified stubs are excluded from the compiled-truth fusion boost + the `people/`/`companies/` source-boost (rank as ordinary content), stamped `unverified: true` in search results (`stampUnverifiedExtractions`, hybrid.ts), listed by `extraction_pending`, promoted (status → `verified`, provenance kept for audit) or rejected (soft-delete) by the owner-only `extraction_review` op, which also records `distinct` decisions (`distinct_from`); every decision publishes through the page door (Git first on a repository source, the database on a repo-less one) under `persistence/publication-guard.ts`, with the revision it read. Pinned by `test/extraction-review.test.ts` (PGLite) + `test/e2e/extraction-review-postgres.test.ts` (live Postgres parity).-- `src/core/facts-fence.ts` — the `## Facts` fence primitives: parse (`parseFactsFence`; #6385: cells are read by the column the header names (`factsHeaderLayout`, `FACTS_FENCE_COLUMNS`), so an unknown, repeated or missing required header column is one `FACTS_TABLE_MALFORMED` and no rows, a header in canonical order keeps the positional typed tail, and `factsRowProblem` lets a row leave off only trailing optional columns and refuses a non-empty cell past the layout; a confidence cell outside 0..1 or not a plain number is `FACTS_TABLE_MALFORMED`, a `claim_value` cell parses strictly (plain/scientific numbers, `1,234,567` separators, a leading currency symbol, a k/M/B suffix that scales; anything else such as `1,5` or `0.9abc` is `FACTS_TABLE_MALFORMED`), `formatFenceDate` writes UTC-midnight dates as `YYYY-MM-DD` and any other instant as a UTC timestamp so TTLs and write-time `valid_from` round-trip, so the page is non-authoritative instead of failing the DB CHECK), render (`renderFactsTable`), and strip (`stripFactsFence({keepVisibility})` — the remote-read privacy boundary `get_page`/`fetch_page`/the chunker apply), plus the remote write-back merge, plus the ONE fence-placement rule: `replaceOrInsertFactsFence(body, fenceBlock)` replaces an existing fence in place or inserts a fresh `## Facts` section ABOVE the timeline sentinel (`timelineSentinelOffset`, #4756 — below it splitBody() files the fence into page.timeline where extract_facts refuses to reconcile it), EOF only when the page has no sentinel; every writer that materializes a fence (`upsertFactRow`, the phantom-redirect canonical append, the importer's hidden-row merge) routes through it, so no writer can re-grow its own EOF append. `upsertFactRow` throws `FenceRewriteRefusal` (fence-shared.ts) when the fence it starts from parses with warnings (#6385 R12): it re-renders the parsed rows, so a rewrite would delete the rows the parser skipped. `restoreHiddenFactRows(incoming, existing)` is the row-level, visibility-aware merge `import-file.ts` applies per fence-bearing column (compiled_truth AND timeline) when a remote caller writes back a page it read with hidden rows stripped — without it, a remote get→edit→put round-trip would silently drop every non-`world` fact row. Rules: only non-`world` rows of the existing fence are restoration candidates (a caller's deletion of a VISIBLE row stays honored — world rows are never restored); a hidden row whose rowNum is absent from the incoming fence is restored at its stable rowNum (cross-page `#F<N>` refs survive); a rowNum collision (a caller-authored addition landing on a hidden number the caller never saw) keeps the hidden row's number and renumbers the CALLER's row onto fresh appended numbers (upsertFactRow's append-only contract); same rowNum + same claim keeps the incoming version (idempotent full-content write-throughs); either side parsing with warnings returns null — re-rendering a fence that didn't fully parse would drop the caller's unparsed rows — and `factsGapWarning` surfaces exactly that residual loss. Pure and side-effect-free. Pinned by `test/facts-fence.test.ts` + the remote write-back describes in `test/privacy-strip-and-forget.test.ts` (row-level merge, world-only deletion honored, timeline-embedded fence round-trip).+- `src/core/facts-fence.ts` — the `## Facts` fence primitives: parse (`parseFactsFence`; #6385: cells are read by the column the header names (`factsHeaderLayout`, `FACTS_FENCE_COLUMNS`), so an unknown, repeated or missing required header column is one `FACTS_TABLE_MALFORMED` and no rows, a header in canonical order keeps the positional typed tail, and `factsRowProblem` lets a row leave off only trailing optional columns and refuses a non-empty cell past the layout; a confidence cell outside 0..1 or not a plain number is `FACTS_TABLE_MALFORMED`, a `claim_value` cell parses strictly (plain/scientific numbers, `1,234,567` separators, a leading currency symbol, a k/M/B suffix that scales; anything else such as `1,5` or `0.9abc` is `FACTS_TABLE_MALFORMED`), `formatFenceDate` writes UTC-midnight dates as `YYYY-MM-DD` and any other instant as a UTC timestamp so TTLs and write-time `valid_from` round-trip, so the page is non-authoritative instead of failing the DB CHECK), render (`renderFactsTable`), and strip (`stripFactsFence({keepVisibility})` — the remote-read privacy boundary `get_page`/`fetch_page`/the chunker apply), plus the remote write-back merge, plus the ONE fence-placement rule: `replaceOrInsertFactsFence(body, fenceBlock)` replaces an existing fence in place or inserts a fresh `## Facts` section ABOVE the timeline sentinel (`timelineSentinelOffset`, #4756 — below it splitBody() files the fence into page.timeline where extract_facts refuses to reconcile it), EOF only when the page has no sentinel; every writer that materializes a fence (`upsertFactRow`, the phantom-redirect canonical append, the importer's hidden-row merge) routes through it, so no writer can re-grow its own EOF append. `upsertFactRow` throws `FenceRewriteRefusal` (fence-shared.ts) when the fence it starts from parses with warnings (#6385 R12): it re-renders the parsed rows, so a rewrite would delete the rows the parser skipped. `restoreHiddenFactRows(incoming, existing)` is the row-level, vis... (line truncated to 2000 chars)- `src/core/facts/attribution.ts` — speaker attribution's one dedup rule: `attributionCompatible(a, b)` is false only for two different known speakers (`user`, `assistant`, `other`); NULL (no recorded speaker) is compatible with either. Every dedup path applies it before candidate limits: `findCandidateDuplicates` (`attributedTo` option, SQL pre-limit), `decideSingleFact` exact and cosine matches, capture exact/near matches, hot-memory collapse (`collapseHotFacts` splits a fingerprint group by speaker when it holds two), fence reindex (`duplicateActiveFenceRows`) and the managed batch key (`facts-prepare.ts`). `facts.attributed_to` (migration v215) is written by the extractor (`facts.attribution`, default on per `docs/eval/decisions/p2-e3-heldout/`; `false` opts out), carried in the fence's 15th cell (only on rows that have it), returned by `recall` and hot memory, rendered `(assistant said)` in context packs, and kept out of `consolidate` (takes are the user's own). Pinned by `test/facts/speaker-attribution.test.ts`.- `src/core/fence-shared.ts` — shared pipe-table primitives for the `## Takes` (`takes-fence.ts`) and `## Facts` (`facts-fence.ts`) fences: `parseRowCells`, `isSeparatorRow`, `stripStrikethrough`, `parseStringCell`, `escapeFenceCell`, and the rewrite guard (#6385 R12) `assertFenceRewritable` / `FenceRewriteRefusal` that `upsertFactRow`, `upsertTakeRow`, `supersedeRow` and `mergePhantomFenceRows` throw when their input fence parses with warnings (the message names the fence only; the warnings, which embed row text, stay on the error). `parseRowCells` is escape-aware: `\|` stays inside its cell and decodes back to a literal `|` (exact inverse of `escapeFenceCell`), while any other backslash passes through verbatim so existing fence text (e.g. Windows paths) is byte-stable across a render → parse cycle. This matters because the fence is canonical and reconcile is wipe-and-reinsert — a pipe inside a cell shifting the column layout would corrupt every row behind it on the next reconcile. `escapeFenceCell` also encodes fence-marker text (`gbrain:facts:begin` and the three siblings) by lengthening the ampersand run before `#58;` (`gbrain:X` → `gbrain:X`, a literal `gbrain:X` → `gbrain&#58;X`), and `decodeFenceCell` (the decoder `parseRowCells` and `fence-repair/raw-rows.ts` share) removes exactly one level, so a claim that quotes a marker never becomes a live marker and a literal entity round-trips byte-identically; the lexical fail-closed privacy rule is unchanged. Pinned by the escape cases in `test/facts-fence.test.ts` + the full render → parse → reconcile round-trip in `test/e2e/facts-fence-reconcile-postgres.test.ts`.-- `src/core/link-extraction.ts` — shared library for the graph layer. `extractEntityRefs` (canonical) matches `[Name](../people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks; `extractPageLinks`, `resolveMarkdownLinkSlug` (one markdown href resolved from a page exactly as `extractPageLinks` resolves it; the writer's link validator, `src/core/output/validators/link.ts`, uses it so its dangling-link verdict matches the graph), `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled`. In `inferLinkType` a per-edge verb counts only when it belongs to the link being typed (`attachedVerb`: a match with another link between it and this one, or written immediately before another link, is that link's), then precedence founded > invested_in > advises > works_at decides; `joined [X] as <role>` reads as works_at. `attendanceEvidenceRanges` accepts an `Attendees:`/`Participants:` line (plain or bold) and a `## Attendees`/`## Participants` link-list section (`Participants` since gbrain-evals N12-6, with a `LINK_EXTRACTOR_VERSION_TS` bump so meeting pages re-extract). Markdown links, bare-slug prose refs, and slash-shaped wikilinks match ANY dir-shaped path (`ANY_DIR_SEGMENT`), not a directory whitelist — nonexistent targets are dropped by the persist paths' page-existence checks (`resolveCandidateSources`, put_page's allSlugs filter, `addLinksBatch` INNER JOINs) and counted as `skippedMissingTarget` in the extract summaries; the `DIR_PATTERN` whitelist is only the typed fast-path for pass-2b wikilinks (non-whitelisted `[[dir/...]]` get an equivalent direct typed candidate in pass 2c, plus the flag-gated suffix rescue for non-exact matches). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. **Opt-in global-basename wikilink resolution** (default off): `WIKILINK_GENERIC_RE` catches bare `[[name]]` wikilinks outside `DIR_PATTERN` (third pass `2c` in `extractEntityRefs`); `EntityRef.needsResolution: true` tags refs from this pass (the ref's `slug` is the wikilink TARGET, `name` the optional display alias). `SlugResolver` gains optional `resolveBasenameMatches(name): Promise<string[]>` (multi-match by design — emits one edge per matching page). The single shared basename matcher is `buildBasenameIndex(slugs)` + `queryBasenameIndex(index, name)` + `normalizeBasename` (keys raw/lower/slugified tail, stable-sorted shorter-first then lexical), used by `makeResolver`, the FS `resolveBasenameMatchesFromSlugs`, AND the doctor check so they cannot drift. `makeResolver` step 1 and the FS resolver try `exactSlugCandidates` (`exact-slug-candidates.ts`: the value, then `slugifyPath`), then `resolveSlugWithAlias` (rename aliases); its fuzzy title step and live keyword step (source-scoped) accept a person/company/fund/organization candidate only under `sameEntityName`, so a near-name stays unresolved instead of linking to a different entity (`test/entity-resolution-near-names.test.ts`). With `link_resolution.global_basename` on, `extractFrontmatterLinks` passes `resolve(name, dirHint, { globalBasename, selfSlug })`, and a unique basename match (self excluded) resolves right after the exact steps and before the fuzzy and live keyword steps, the exact-name-first precedence of `resolveEntitySlug` (#5749, `test/link-resolution-basename-before-search.test.ts`). `makeResolver(engine, {mode, sourceId})` builds the index lazily via `engine.getAllSlugs({sourceId})` — source-scoped so a bare `[[name]]` never resolves to a same-tail page in a different source. `extractPageLinks` gains `opts.globalBasename` (routes `needsResolution` refs through `resolveBasenameMatches` keyed on `ref.slug`, emits candidates tagged `linkType: 'wikilink_basename'` + `linkSource: 'wikilink-resolved'`, skips self-loops) and `opts.skipFrontmatter`. All three surfaces (FS extract, DB extract, `put_page` auto-link) tag provenance with `link_source='wikilink-resolved'`; `put_page` includes it in its reconcilable-edge set so stale basename edges are removed when the wikilink or the flag goes away. Exports `WIKILINK_BASENAME_LINK_TYPE` + `isGlobalBasenameEnabled(engine)` (resolution order: env `GBRAIN_LINK_RESOLUTION_GLOBAL_BASENAME` → DB config `link_resolution.global_basename` → default false). `gbrain doctor`'s `link_resolution_opportunity` check surfaces a paste-ready enable hint when ≥5 bare wikilinks would resolve AND ≥20% match. Migration v113 widens `links_link_source_check` to admit `'wikilink-resolved'`; v114 then opens it to any kebab-case provenance (`^[a-z][a-z0-9]*(-[a-z0-9]+)*$`, ≤64 chars) so external derivers register their own tag (e.g. `citation-graph`) without a migration. `LINK_EXTRACTOR_VERSION_TS` also lives here (bump like `CHUNKER_VERSION` to invalidate prior extract-stale stamps). Pinned by `test/link-extraction.test.ts`, `test/extract-fs.test.ts`, `test/doctor.test.ts`, `test/e2e/global-basename-pglite.test.ts`. #6191: `inferLinkType` applies `link-target-roles.ts` `targetTakesVerb` to every per-edge and fallback verb: `works_at` never types a link to a person, meeting, calendar-event, media, image or transcript target (unknown type: a `people/`, `meetings/`, `calendar/`, `cal/` slug), `founded`/`invested_in` never a temporal or media one; a refused verb keeps scanning lower-precedence rules, then `mentions` (`test/link-type-target-guard.test.ts`).+- `src/core/link-extraction.ts` — shared library for the graph layer. `extractEntityRefs` (canonical) matches `[Name](../people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks; `extractPageLinks`, `resolveMarkdownLinkSlug` (one markdown href resolved from a page exactly as `extractPageLinks` resolves it; the writer's link validator, `src/core/output/validators/link.ts`, uses it so its dangling-link verdict matches the graph), `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled`. In `inferLinkType` a per-edge verb counts only when it belongs to the link being typed (`attachedVerb`: a match with another link between it and this one, or written immediately before another link, is that link's), then precedence founded > invested_in > advises > works_at decides; `joined [X] as <role>` reads as works_at. `attendanceEvidenceRanges` accepts an `Attendees:`/`Participants:` line (plain or bold) and a `## Attendees`/`## Participants` link-list section (`Participants` since gbrain-evals N12-6, with a `LINK_EXTRACTOR_VERSION_TS` bump so meeting pages re-extract). Markdown links, bare-slug prose refs, and slash-shaped wikilinks match ANY dir-shaped path (`ANY_DIR_SEGMENT`), not a directory whitelist — nonexistent targets are dropped by the persist paths' page-existence checks (`resolveCandidateSources`, put_page's allSlugs filter, `addLinksBatch` INNER JOINs) and counted as `skippedMissingTarget` in the extract summaries; the `DIR_PATTERN` whitelist is only the typed fast-path for pass-2b wikilinks (non-whitelisted `[[dir/...]]` get an equivalent direct typed candidate in pass 2c, plus the flag-gated suffix rescue for non-exact matches). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. **Opt-in global-basename wikilink resolution** (default off): `WIKILINK_GENERIC_RE` catches bare `[[name]]` wikilinks outside `DIR_PATTERN` (third pass `2c` in `extractEnti... (line truncated to 2000 chars)- `src/core/timeline-dedup-repair.ts` — schema-drift self-heal for `idx_timeline_dedup`. A master-merge migration renumbering can leave a brain's version counter stamped past the index change while the index keeps an old shape — and every `addTimelineEntry` batch then fails its `ON CONFLICT` inference, silently breaking timeline writes brain-wide. The version counter can't detect this, so the repair is keyed off the actual index SHAPE. Canonical shape is `(page_id, date, md5(summary), source)` — md5-keyed (migration v138) because a raw long/incompressible summary would overflow the btree v4 row cap (~2704 bytes) and abort every timeline insert for that page; both engines' insert sites infer `ON CONFLICT` on the md5 tuple, so `EXPECTED_COLUMNS` MUST carry the md5 form (a raw-shape expectation would make the repair revert v138 on every migrate pass). `checkTimelineDedupIndex(engine)` returns `{tablePresent, indexPresent, columns, needsRepair}` (read-only; powers the `timeline_dedup_index` doctor check; the indexdef column parser is paren-depth-aware so `md5(summary)` — or any future expression column — parses as ONE column instead of flagging a correct index as drifted forever) and `repairTimelineDedupIndex(engine)` dedupes-then-rebuilds to the canonical shape (raw-summary grouping ⟺ md5 grouping modulo negligible collisions). `runMigrations` invokes the repair on every pass (including the no-pending early-return path); idempotent no-op when the index already matches. `gbrain apply-migrations --force-schema` triggers it on demand. Pinned by `test/timeline-dedup-repair.test.ts`.- `src/core/trajectory-format.ts` — shared `formatTrajectoryBlock(points, entitySlug, opts)` consumed by both `gbrain think` (production) and the LongMemEval harness (benchmark). Groups by `(metric ?? event_type)`, per-metric cap 20, total cap 100, knowledge_update intent annotates value-change rows with `(superseded prior)`. Emits a `<trajectory entity="...">` XML envelope — `INJECTION_PATTERNS` in `src/core/think/sanitize.ts` escapes `</trajectory>`, `<trajectory ...>` open tags, and attribute injection so adversarial fact text can't break out. Pinned by `test/trajectory-format.test.ts`.--- `src/core/line-grammar.ts` + `src/core/machine-sections.ts` — the line grammar: `parseLineGrammar` reads list items in a page body as typed relation lines (`- works_at [[companies/x]] (context)`: one type token or quoted phrase, exactly one link, optional `(context)`, optional `@effective[start,end)`, an optional trailing `[Source: ...]` citation) and fact lines (`- [category] claim #tag (context)`). Guards: a category is one letter-led token (timecodes, dates, citations, footnotes, task boxes and bracket phrases never match), `x`/`todo`/`done`/`wip` are refused, and code, blockquotes, HTML comments, frontmatter and the machine-written sections from `rolePriorSuppressedRanges` (now in `machine-sections.ts`, shared with type inference) are skipped. Prose after the link, two links, stoplisted generic words and verbs the active pack does not declare fall back to inference with a diagnostic. `statedRelationTypes` feeds `extractPageLinks` (and the filesystem scan in `commands/extract.ts`): the stated type wins for the link on its line, except an `attended` line on a meeting page, which stays with canonical attendance. `parseEffectiveQualifier` normalizes ISO ranges to half-open `[from, until)` dates and refuses everything else unpeeled (a range with more than one comma is refused with an exactly-one-comma message). Parsing stays linear on adversarial lines: the qualifier's date groups exclude commas, the trailing-citation pattern has no overlapping whitespace quantifiers, and links come from `findLinks`, a scan with precomputed stop positions that returns exactly the old link regex's matches. `lineGrammarOptions` resolves `line_grammar.enabled` (default off: held-out verdict H3 failed its precision bar, and Q2's G1 natural-junk and G3 decoy gates failed again with the guards) and `line_grammar.allow_undeclared_types`. Fact lines are reported (put_page `line_grammar`, `gbrain lint` rule `line-grammar`, `schema detect --fields`), not projected into `facts`. Pinned by `test/line-grammar.test.ts` (incl. a timeout-bounded adversarial input, a 200k-character linear-time ratio check and a `findLinks` equivalence property test), `test/link-extraction-line-grammar.test.ts`, `test/put-page-line-grammar.test.ts`.--- `src/core/wanted-links.ts` + `src/core/wanted-links-store.ts` — wanted pages. `collectWantedLinks` turns an origin's link candidates (each body markdown link / wikilink carries an `authoredRef` from `extractPageLinks`) and unresolved frontmatter names into `wanted_links` rows: a reference is wanted only when every alternative resolution failed with `missing_target`/`cross_source` (an unqualified target existing only in another source is wanted in the origin source; a qualified target in a source the origin may not link to is not). Bare prose paths never become rows. `replaceWantedLinks` runs inside `replaceDerivedLinks` (`opts.wanted`, per producer `body`/`frontmatter`), so every extraction path (managed put_page and stale sweep via `links-preparation.ts`, unmanaged `extract`, the serve sweep, source reconciliation) replaces rows atomically with links; it keeps only `possibleWantedRows` (a slug target `validateSlug` accepts, in the origin's or a registered source read `FOR SHARE`, so a regex literal on a code page or a `[[memory:123]]` citation never reaches the page guard and aborts extraction, #6228/#6225; `links-preparation.ts` filters the receipt preview the same way), locks slug targets and stamps a row `-infinity` when its exact target already exists. `WANTED_ORIGIN_IS_STALE` in `engine-sql/pages.ts` joins the stale-for-extraction predicate: a live target (exact slug, or basename for `ref_kind='name'`) updated after `checked_at` makes the origin stale, so the next sweep creates the edge; restore and rename bump `updated_at`. `listWantedPages` backs the `wanted_pages` op (`gbrain wanted`): source-scoped, private origins excluded before aggregation for remote callers, soft-deleted origins never count, bare-name targets list `existing_matches`. `wanted_pages.enabled` (default on). Migration v214. Pinned by `test/wanted-links.test.ts` + `test/e2e/wanted-links-postgres.test.ts`.--- `src/core/similar-pages.ts` — put_page's similar-pages advisory on creates (`page-advisories.ts`): exact title (`ILIKE`, served by `idx_pages_trgm`), `page_aliases`, same slug basename in another directory (`idx_pages_slug_basename`), and title trigram similarity >= 0.55 in the same top-level directory; up to 3 slugs with their evidence, private pages excluded for callers that may not read them, `semantic: 'not_checked'` (the page's embedding is queued after publication). A question, never a merge. `put_page.similar_pages` (default off: held-out verdict H5b failed its wrong-merge bar). Pinned by `test/put-page-similar-pages.test.ts` + `test/e2e/p5-graph-postgres.test.ts`.--- `src/core/schema-pack/field-usage.ts` — `gbrain schema detect --fields`: per page type (top 50, up to 500 sampled pages each), frontmatter key, fact-category and relation-type usage; share 1 → required, >= 0.25 → optional. Identity and write-provenance keys are ignored. Read-only. Pinned by `test/schema-field-usage.test.ts`.--- `src/core/link-validity.ts` + `src/core/link-relationships.ts` + `src/core/link-temporal-evidence.ts` + `src/core/link-temporal-apply.ts` + `src/core/ops/edge-temporal.ts` — temporal typed edges ([guide](../../guides/temporal-edges.md)). Relation semantics (state / event / reference), `buildRelationshipState` (order-invariant stints from `links` assertions with `assertion_tense` plus dated `link_transitions`; dated beats undated, same-page present beats past), `closeContradiction` (pure date arithmetic, relationship-specific starts only), and `relationshipFilterSql` / `annotateTemporalRow` / `edgeMatchesTemporal` (one liveness rule: a relationship with no `link_relationships` row reads live; `LIVENESS_EXEMPT_LINK_TYPES` (`amends`) never hide outside `ended` reads). `refreshRelationships` recomputes per-scope state (`all`, `world` ignores private-origin evidence) inside the writer's transaction; `replaceDerivedLinks` calls `applyTemporalEvidence`, and the engine link writers refresh touched temporal keys; the extract phase sweeps lagging or orphaned state. Graph ops read live relationships by default; default reads keep the established row shape, history reads (`status`, `as_of`, `during`) return `status`/`stints`/`recorded_at`/`retired_at`; hidden rows emit `former_relationships_hidden` + `gbrain.temporal` meta. `graph.edge_validity off` is a read policy only. `src/core/link-semantics-pack.ts` installs pack-declared `link_types[].temporal` semantics (union of the active and per-source packs, `state` wins) over the built-in table; `replaceDerivedLinks`, `add_link`/`remove_link` and the extract sweep prime it before deriving or refreshing state (lint rule `link_types_temporal`; `test/link-semantics-pack.test.ts`). `src/core/link-relationship-notes.ts` renders the shared relationship note (`now: … ; ended: … ; summary may be stale`) with one batched read for entity cards, `context_pack`, ambient turn-context synopses and compiled context entries. Pinned by `test/link-validity.test.ts`, `test/link-temporal-evidence.test.ts`, `test/link-relationships.test.ts` (+ Postgres twin), `test/link-temporal-put-page.test.ts`, `test/link-temporal-reads.test.ts`.--- `src/core/cycle/edge-contradictions.ts` + `src/commands/edge-proposals.ts` — the `edge_contradictions` dream phase and `gbrain edge-proposals`. Candidates are subjects with ≥2 live same-type state relationships whose pair evidence hash has no proposal; #6953 admission: `entity-types.ts`; one judge call per subject returns only conflict flags; `closeContradiction` picks the ending relationship and date (undated → `undated_unresolved`). Modes propose (default) / apply (certified models in `CERTIFIED_APPLY_MODELS`) / off; applying appends a `gbrain-dream (inferred)` "Ended <type> [[target]]" timeline line through the coordinated `add_timeline_entry` path and re-derives the page; a hand-deleted line becomes `reverted_by_user`. `list` reads `--status` and `--limit` as `--flag value` or `--flag=value`; `--limit` is a positive integer (`intFlagValue`, a bad or missing value is `invalid_params` before any query) capped at 1000 (`test/edge-proposals-list-flags.test.ts`). Budget through the cycle `BudgetMeter`. The CLI's `rows()` normalizes proposal ids at the row boundary (Postgres returns `bigint` as BigInt: a safe integer becomes a number, anything larger an exact string) and `--json` output also passes `bigintToStringReplacer`, so `list/show --json` never crash on Postgres (#6193). Pinned by `test/cycle-edge-contradictions.test.ts`, the managed phase matrix, `test/edge-proposals-json-bigint.test.ts` and `test/e2e/edge-proposals-json-postgres.test.ts`. `edge-proposals <sub> --help` prints usage before any engine read (router help, `src/cli/subcommands.ts`). #6311: a judge failure writes an `error` row whose detail is `attempt N/3; <class>: <message>` (provider keys, connection info and labeled credentials redacted, message ≤ 200 chars); skip-known treats it as known for 24 h (`updated_at`), then the pair is judged again and `recordProposal`'s upsert replaces only an `error` row; after `JUDGE_MAX_ATTEMPTS` (3) the detail reads `held after 3 attempts; …` and the pair is skipped until `gbrain edge-proposals retry <id> | --all-held` deletes the row (or the evidence hash changes). No migration. Pinned by `test/cycle-edge-contradictions.test.ts`.-- `src/core/link-single-value.ts` — declared single-value relations ([guide](../../guides/temporal-edges.md#declared-single-value-relations)). A pack's `cardinality: one_per_from` on a state relation, built in or declared `temporal: state` (manifest-v1 `LinkTypeSchema`; lint rule `link_types_cardinality` rejects it elsewhere) makes `edge_contradictions` close that type's competing live relationships without a model: `planSingleValueClosures` orders members by latest dated start and applies `closeContradiction` to each consecutive pair (undated and same-date members stay open as proposals). `declaredSingleValueTypes` reads the source's resolved pack; `previewSingleValue` backs the read-only `gbrain schema cardinality-preview`. `dream.single_value.mode` propose (default) / apply / off. Pinned by `test/link-single-value.test.ts`.diff --git a/docs/architecture/managed-mutating-writers.tsv b/docs/architecture/managed-mutating-writers.tsvindex e10d0c3641..6771907fa5 100644--- a/docs/architecture/managed-mutating-writers.tsv+++ b/docs/architecture/managed-mutating-writers.tsv@@ -59,7 +59,7 @@ op connector_sync coordinator Managed connector sync admits pages and checkpointop ontology_propose engine_guard mergeOntologyFact inserts into facts; the managed writer trigger refuses it on a managed brain.op chronicle_backfill no_canonical_write Queues chronicle jobs; the chronicle extractor publishes through publishMaintenancePage.op extract_entities coordinator #6262: the stub is a create-only put_page through submitPageMutation; its tier lowering, timeline row and backlink are coordinatedDatabaseWrite transactions. A refusal or pending write returns its envelope and stops the batch.-op extraction_review no_canonical_write Review queue state only.+op extraction_review coordinator Promote, reject and distinct publish through the page-mutation door (edit_page / delete_page).op entity_identity_link no_canonical_write entity_identity side table.op entity_identity_unlink no_canonical_write entity_identity side table.op extract_facts coordinator The facts backstop publishes through the managed facts session on managed brains.diff --git a/docs/guides/entity-detection.md b/docs/guides/entity-detection.mdindex e61d92f654..9e33ae540a 100644--- a/docs/guides/entity-detection.md+++ b/docs/guides/entity-detection.md@@ -190,8 +190,11 @@ to Alice" only works if Alice's page links back to every mention.whose name is one edit, or one acronym letter, away from another entity'sname or alias, whoever wrote them. It only flags: link the pair with`entity-identity-link` (owner, manual), or add the name to the other- page's `aliases` frontmatter, which silences the pair. A page whose- `distinct_from` frontmatter lists the other slug is never flagged. The+ page's `aliases` frontmatter, which silences the pair. If they are+ different entities, `gbrain extraction-review distinct --slugs <new>+ --of <existing>` (owner, on the brain host) records it in the new page's+ `distinct_from` frontmatter, committed to Git on a repository source, and+ the pair is never flagged again. Thesame command lists facts saved without an entity (`unattributed`); relinkone with `remember` plus `entity` and `replaces`, never by forgetting itfirst.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 9d238a5d26..acfb8ff5b4 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: linksrc/core/search/evidence-delivery.ts 1733 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move)src/commands/config.ts 1524 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)src/commands/mcp-expose.ts 1512 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts)-src/core/behavior-change-notice.ts 1519 ratchet +1 GBRA-215 L1: extraction_pending review lists row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2); the behavior-change table split (#7607) retires this row+src/core/behavior-change-notice.ts 1520 ratchet +1 GBRA-215 L2: extraction_review_page_door row; +1 GBRA-215 L1: extraction_pending review lists row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2); the behavior-change table split (#7607) retires this rowdiff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex c356a98ed5..32a0cfdbf6 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -341,6 +341,7 @@ src/core/minions/handlers/subagent-oneshot.ts planOneshotWrites call:serializeMasrc/core/ops/admin.ts get_versions field SEGW lane 1e: segmented versions return metadata onlysrc/core/ops/attribution.ts get_write_attribution field NONE not the page body: timeline entry id paramsrc/core/ops/attribution.ts rowTarget field NONE not the page body: timeline entry id param+src/core/ops/extraction.ts reviewDecision call:serializePageToMarkdown NONE serializes the frontmatter head with an empty body (withoutBody) for an edit_page head edit; the body is never readsrc/core/ops/get-page-body.ts bodyBytes field METAsrc/core/ops/get-page-body.ts editTarget field INLINE inline branch only (a segmented page maps through the window's segment units); regions read whole within the segmented thresholdsrc/core/ops/get-page-body.ts readPartialBody call:serializePageToMarkdown SEGWdiff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 8b0cdf9e21..6ddfef6776 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1321,6 +1321,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;// #7679 / #7685 orphaned worktree refresh. `since` is stamped at the merge slot.{ since: '0.60.472.0', id: 'refresh_orphan_7679', text: 'A managed `gbrain sources refresh` whose process died (for example a container replaced mid-refresh) no longer wedges the checkout: the next plain `gbrain sources refresh` on the owner host finishes the orphaned refresh through the `--resume` path before its own refresh and reports it as `recovered`, and the owner completes an orphaned `syncing` refresh once every member has synced to its target. A refresh whose holder is still running, or is recorded on another host, is never taken over. `gbrain sources writer status` and `gbrain sync status` now name the holder and its `liveness` (`live`, `orphaned`, `unknown`) with a fix naming `--resume`. With `--json`, a refusal that carries a structured fix (`refresh_in_progress`, `refresh_diverged`, a git read failure) now prints `fix` as an object (argv, actor, next) instead of a string; the prose stays in `suggestion`, so read that when a script needs text. A plain refresh of a checkout whose interrupted refresh needs a reset decision now refuses `refresh_recovery_required` (it refused `refresh_in_progress`).' },{ since: 'TBD', id: 'extraction_pending_review_lists', text: '`extraction_pending` (CLI `gbrain extraction-pending`) now also returns `unattributed`: active facts saved without an entity, newest first (world facts only for remote callers), each with the relink action (remember the same claim with `entity` and `replaces`). `pending` and `count` are unchanged; the result adds `include` and `unattributed`. Pass `include` to choose lists, and add `possible_duplicates` to it to list entity pages created in the last 30 days whose name is one edit or one acronym letter away from another entity, for review only (nothing is merged).' },+ { since: 'TBD', id: 'extraction_review_page_door', text: '`extraction_review` (CLI `gbrain extraction-review`) promote and reject now write through the page door instead of changing the database row alone: on a source with a repository the decision is committed to Git (promote rewrites the stub\'s file with `status: verified`, reject removes the file), and on a repo-less source the database is the record. Each decision re-reads the page under a source-scoped guard and writes with the revision it read, so a page that changed in between reports `changed` (run the command again), and two decisions on one stub never both land. The result adds `write_requests` (request id and state per written page). A new `distinct` action (`gbrain extraction-review distinct --slugs <new> --of <existing>`, owner-only) records `distinct_from` the same way, and `possible_duplicates` rows carry it.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex b441be94f8..001a18737d 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -25,13 +25,13 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'backup': ['--accept-pending', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--purge-mirror', '--quiet', '--restore-only', '--source', '--timeout', '--timings', '--wait'],'beliefs': ['--apply', '--archived-at', '--brain', '--from-url-env', '--help', '--json', '--probe', '--purge-mirror', '--since', '--source'],'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],- 'book-mirror': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--asof', '--author', '--background', '--body', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--client', '--context-file', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-turns', '--max-usd', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-follow', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--timeout', '--timeout-ms', '--timings', '--title', '--to', '--updated-after', '--url', '--wait', '--yes'],+ 'book-mirror': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--asof', '--author', '--background', '--body', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--client', '--context-file', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-turns', '--max-usd', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-follow', '--of', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--timeout', '--timeout-ms', '--timings', '--title', '--to', '--updated-after', '--url', '--wait', '--yes'],'bootstrap': ['--abbrev-ref', '--accept-visibility-change-consequences', '--active', '--add', '--adopt', '--all', '--allow-unverified-remote', '--auto', '--autostash', '--batch-check', '--bearer-token-env-var', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--dry-run', '--enable', '--env', '--error-unmatch', '--exclude-standard', '--expect-remote', '--ff-only', '--file', '--force', '--gbrain-bin', '--get', '--get-all', '--git-dir', '--git-path', '--hard', '--harness', '--header', '--heads', '--help', '--home', '--host', '--hostname', '--http', '--id', '--init', '--install', '--is-inside-work-tree', '--issuer-url', '--jq', '--json', '--keep-checkout', '--local', '--local-env-vars', '--mcp-even-if-plugin', '--mcp-only', '--mcp-url', '--minimal', '--name', '--name-only', '--no-autostash', '--no-capture', '--no-cron', '--no-hooks', '--no-seat', '--no-tags', '--no-verify', '--oauth-client-id', '--oauth-client-secret', '--only', '--operations', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pull', '--pure', '--push-only', '--quiet', '--rebase', '--refresh-operations', '--refresh-skills', '--remove', '--repair', '--require-clean', '--resolve', '--scope', '--scopes', '--seat', '--set', '--short', '--show', '--show-toplevel', '--skills', '--skip', '--source', '--sources', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],'brainstorm': ['--admin-intent', '--brain', '--confirm-relocated-root', '--dir', '--expected-epoch', '--expected-state', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--manifest', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--path', '--probe', '--resume', '--save', '--self-transfer', '--source', '--source-id', '--stale', '--strict-budget', '--yes'],'cache': ['--brain', '--help', '--json', '--source', '--yes'],- 'calibration': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--holder', '--http', '--id', '--include-deleted', '--json', '--key-prefix', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--regenerate', '--row', '--scopes', '--scrub-gstack', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--undo-wave', '--updated-after', '--url', '--with-calibration', '--yes'],+ 'calibration': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--holder', '--http', '--id', '--include', '--include-deleted', '--json', '--key-prefix', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--regenerate', '--row', '--scopes', '--scrub-gstack', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--undo-wave', '--updated-after', '--url', '--with-calibration', '--yes'],'call': ['--brain', '--help', '--json', '--source'],- 'capture': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--depth', '--entities', '--expect-tail', '--expected-revision', '--explain', '--federated-read', '--file', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--region', '--request-id', '--row', '--scopes', '--separator', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--stdin', '--surface', '--timeout', '--timings', '--to', '--type', '--updated-after', '--url', '--wait', '--what', '--where', '--who', '--yes'],+ 'capture': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--depth', '--entities', '--expect-tail', '--expected-revision', '--explain', '--federated-read', '--file', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--of', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--region', '--request-id', '--row', '--scopes', '--separator', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--stdin', '--surface', '--timeout', '--timings', '--to', '--type', '--updated-after', '--url', '--wait', '--what', '--where', '--who', '--yes'],'check-backlinks': ['--accept-pending', '--background', '--brain', '--dir', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],'check-resolvable': ['--brain', '--dry-run', '--fix', '--help', '--json', '--skills-dir', '--source', '--strict', '--verbose'],'check-update': ['--brain', '--channel', '--exit-code', '--ff-only', '--force-retry', '--help', '--is-ancestor', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-restart', '--non-interactive', '--quiet', '--refresh-cache', '--refs', '--remediation-plan', '--restart-only', '--source', '--stop-mcp', '--swap-only', '--tags', '--version', '--yes'],@@ -49,15 +49,15 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],'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-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--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', '--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-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-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', '--run', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--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', '--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'],+ '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', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--of', '--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-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--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', '--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-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-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', '--of', '--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', '--run', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--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', '--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'],+ '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', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--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'],'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--client', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--group', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-null-signature', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-facts', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-embed', '--no-embedding', '--no-hooks', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--scopes', '--section', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--timings', '--to', '--wait', '--yes'],'embeddings': ['--accept-pending', '--background', '--brain', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--no-accept-pending', '--no-embedding', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--wait', '--yes'],'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--http', '--json', '--legacy-lock', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],- 'enrich': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--apply', '--asof', '--audit', '--background', '--body', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--conflicts', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--expect', '--explain', '--federated-read', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--non-interactive', '--order', '--output', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--progress-interval', '--progress-json', '--purge', '--quiet', '--rate', '--recent', '--reenrich-after', '--refresh-operations', '--resume', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--timings', '--to', '--trust', '--types', '--updated-after', '--url', '--wait', '--workers', '--yes'],+ 'enrich': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--apply', '--asof', '--audit', '--background', '--body', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--conflicts', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--expect', '--explain', '--federated-read', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--non-interactive', '--of', '--order', '--output', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--progress-interval', '--progress-json', '--purge', '--quiet', '--rate', '--recent', '--reenrich-after', '--refresh-operations', '--resume', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--timings', '--to', '--trust', '--types', '--updated-after', '--url', '--wait', '--workers', '--yes'],'errors': ['--brain', '--changed', '--help', '--json', '--source'],'eval': ['--ab-relational', '--accept-pending', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--call-plan', '--call-plan-gate', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--decide', '--decide-calibration', '--decide-dataset', '--decide-force-on', '--decide-provider', '--decide-threshold', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--error-unmatch', '--eval-pool-depth', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fact-extractor', '--fact-keys', '--fact-keys-max-usd', '--fact-keys-model', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-accept-pending', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--op-expand', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--porcelain', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--request-id', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--synopsis-cache', '--synopsis-concurrency', '--synopsis-max-usd', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--time-scope', '--time-scope-pool', '--timeout', '--timings', '--tool', '--top-k', '--top-regressions', '--until', '--untracked-files', '--update-baseline', '--usefulness-min', '--vectors', '--verbose', '--verify', '--via-operation', '--wait', '--with-code-intel', '--yes'],'export': ['--accept-pending', '--background', '--body', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--timings', '--type', '--wait'],@@ -76,10 +76,10 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--batch-check', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--literal-pathspecs', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers'],- 'init': ['--access', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--of', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],- 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--channel', '--check', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],+ 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--channel', '--check', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'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'],@@ -90,19 +90,19 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],'notability-eval': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--out', '--repo', '--skip-llm', '--source', '--status', '--target-high', '--target-low', '--target-medium'],'notices': ['--brain', '--help', '--json', '--source'],- 'onboard': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--asof', '--auto', '--body', '--bound-slug-prefixes', '--brain', '--check', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-index', '--from-pages', '--full', '--fuzzy', '--group-by', '--help', '--history', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--probe', '--purge', '--recent', '--refresh-operations', '--remediate', '--remediation-plan', '--resume', '--row', '--save', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--target-score', '--to', '--updated-after', '--url', '--yes'],+ 'onboard': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--asof', '--auto', '--body', '--bound-slug-prefixes', '--brain', '--check', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-index', '--from-pages', '--full', '--fuzzy', '--group-by', '--help', '--history', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--probe', '--purge', '--recent', '--refresh-operations', '--remediate', '--remediation-plan', '--resume', '--row', '--save', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--target-score', '--to', '--updated-after', '--url', '--yes'],'orphans': ['--accept-pending', '--all', '--background', '--brain', '--count', '--cursor', '--explain', '--follow', '--force', '--help', '--include-pseudo', '--json', '--limit', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--limit', '--literal-pathspecs', '--name-only', '--older-than', '--quiet', '--retry-parked', '--show-toplevel', '--source', '--source-id', '--state', '--verify', '--yes'],'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--legacy-lock', '--path', '--probe', '--source', '--vectors', '--yes'],'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--value', '--vectors', '--verify', '--version', '--workers', '--yes'],'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],'projections': ['--brain', '--dry-run', '--enable-dcr', '--help', '--http', '--images', '--install', '--json', '--limit', '--now', '--only', '--port', '--public-url', '--remove', '--source', '--stale', '--status', '--surface', '--user'],- 'protocol': ['--access', '--add', '--all', '--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', '--provenance', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--updated-after', '--url', '--yes'],+ 'protocol': ['--access', '--add', '--all', '--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', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--page', '--params', '--path', '--phase', '--prefer', '--provenance', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--updated-after', '--url', '--yes'],'providers': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--model', '--source', '--status', '--touchpoint'],'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],'quarantine': ['--accept-all', '--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--body', '--brain', '--break-lock', '--client', '--confirm-relocated-root', '--db-url', '--dir', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--help', '--http', '--id', '--include-flagged', '--json', '--kind', '--legacy-lock', '--limit', '--manifest', '--no-accept-pending', '--no-embed', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--remove', '--resume', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--timings', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],'questions': ['--brain', '--defer', '--entity', '--fail-fast', '--full', '--help', '--id', '--include-archived', '--json', '--prefix', '--probe', '--publish', '--source', '--tools-json', '--wait-ms', '--yes'],- 'recall': ['--accept-pending', '--access', '--add', '--all', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--continue', '--cursor', '--date', '--dated-since', '--days', '--entities', '--entity', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--grep', '--group-by', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--timings', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],+ 'recall': ['--accept-pending', '--access', '--add', '--all', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--continue', '--cursor', '--date', '--dated-since', '--days', '--entities', '--entity', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--grep', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--of', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--timings', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],'reconcile-links': ['--accept-pending', '--background', '--body', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--all-drifted', '--apply', '--background', '--body', '--brain', '--class', '--close', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--held', '--help', '--include-ambiguous', '--include-cross-entity', '--json', '--keep', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--oversized', '--path', '--plan', '--prefer', '--progress-interval', '--progress-json', '--provenance', '--quiet', '--repo', '--request', '--request-id', '--segmented', '--self-transfer', '--side', '--since', '--skip', '--slug', '--source', '--stale', '--state', '--status', '--supabase', '--timeout', '--timings', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--client', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--id', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--scopes', '--source', '--status', '--timeout', '--timings', '--trust', '--wait', '--workers', '--yes'],@@ -139,7 +139,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--value', '--vectors', '--verify', '--version', '--workers', '--yes'],'waiting': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],- 'whoknows': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--request-id', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--updated-after', '--url', '--yes'],+ 'whoknows': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--of', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--request-id', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--updated-after', '--url', '--yes'],};// Routing flags a fix naming each CLI-only command carries (A1 render-time pin,diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex 47e9a6568b..58ae3acc76 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -5502,12 +5502,12 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["name": "extraction_review","idempotent": false,"outputRedaction": "no_stored_text",- "description": "Promote or reject unverified auto-extracted entity stubs (batch). Promote flips `status` to verified (provenance kept for audit); reject soft-deletes the stub. Owner-only: this op is refused for any non-local caller. (The markers are ordinary frontmatter — the boundary against rewriting them wholesale is put_page write authz, same as for any page.)",+ "description": "Decide on review rows (batch). promote flips an unverified auto-extracted stub's `status` to verified (provenance kept for audit); reject soft-deletes the stub; distinct records that each of slugs is a different entity from of (`distinct_from` frontmatter), so possible_duplicates stops pairing them. Every decision writes through the page door: Git first on a source with a repository, the database on a repo-less source. Owner-only: this op is refused for any non-local caller. (The markers are ordinary frontmatter — the boundary against rewriting them wholesale is put_page write authz, same as for any page.)","params": {"action": {"type": "string","required": true,- "description": "'promote' or 'reject'."+ "description": "'promote', 'reject' or 'distinct'."},"slugs": {"type": "array",@@ -5515,7 +5515,12 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["items": {"type": "string"},- "description": "Stub slugs to act on (batch)."+ "description": "Slugs to act on (batch)."+ },+ "of": {+ "type": "string",+ "required": false,+ "description": "distinct only: the existing entity page each of slugs is not the same as."}},"mutating": true,diff --git a/src/core/ops/extraction.ts b/src/core/ops/extraction.tsindex 506c61c1fe..3e06b40c55 100644--- a/src/core/ops/extraction.ts+++ b/src/core/ops/extraction.ts@@ -9,13 +9,18 @@*/import type { Operation } from './contract.ts';-import { opError, type OperationContext } from './contract.ts';+import { opError, OperationError, type OperationContext } from './contract.ts';import type { Action } from '../agent-output.ts';import { hostOnlyError, paramUse, readFix } from './op-fix.ts';import { sourceScopeOpts } from './context.ts';+import { randomUUID } from 'node:crypto';import { unverifiedExtractionFragment, isUnverifiedExtraction, EXTRACTION_STATUS_KEY, STATUS_VERIFIED } from '../extraction-review.ts';import { buildVisibilityClause } from '../search/sql-ranking.ts';-import { maintenanceTransaction } from '../persistence/attribution.ts';+import { serializePageToMarkdown } from '../markdown.ts';+import { withoutBody } from '../page-body/page-shape.ts';+import type { Page } from '../types.ts';+import { submitPageMutation } from '../persistence/page-mutations.ts';+import { withPublicationGuard } from '../persistence/publication-guard.ts';// ---------------------------------------------------------------------------// Extraction quarantine lane (issue #160)@@ -195,13 +200,18 @@ function pendingFix(): Action {{ argv: ['gbrain', 'extraction-pending'], mcp: { tool: 'extraction_pending', arguments: {} } });}+const REVIEW_ACTIONS = ['promote', 'reject', 'distinct'] as const;+type ReviewDecision = typeof REVIEW_ACTIONS[number];+const isReviewAction = (v: unknown): v is ReviewDecision => typeof v === 'string' && (REVIEW_ACTIONS as readonly string[]).includes(v);+function reviewOwnerOnly(ctx: OperationContext, p: Record<string, unknown>) {- const message = 'extraction_review is owner-only: promote/reject decisions must come from the trusted local CLI.';- const action = p.action === 'promote' || p.action === 'reject' ? p.action : undefined;+ const message = 'extraction_review is owner-only: promote, reject and distinct decisions must come from the trusted local CLI.';+ const action = isReviewAction(p.action) ? p.action : undefined;const slugs = Array.isArray(p.slugs) ? p.slugs : [];- const exact = action && slugs.length > 0 && slugs.every(s => typeof s === 'string' && REVIEW_SLUG.test(s));+ const of = typeof p.of === 'string' && REVIEW_SLUG.test(p.of) ? p.of : undefined;+ const exact = action && slugs.length > 0 && slugs.every(s => typeof s === 'string' && REVIEW_SLUG.test(s)) && (action !== 'distinct' || of);return exact- ? hostOnlyError(ctx, 'permission_denied', message, ['gbrain', 'extraction-review', action, '--slugs', slugs.join(',')],+ ? hostOnlyError(ctx, 'permission_denied', message, ['gbrain', 'extraction-review', action, '--slugs', slugs.join(','), ...(action === 'distinct' ? ['--of', of!] : [])],'The review decision is the quarantine trust gate, so only the brain owner\'s CLI may make it.',{ consent: action === 'reject' ? ['destructive'] : [] }): hostOnlyError(ctx, 'permission_denied', message, ['gbrain', 'extraction-pending'],@@ -212,10 +222,11 @@ const extraction_review: Operation = {name: 'extraction_review',idempotent: false,outputRedaction: 'no_stored_text',- description: 'Promote or reject unverified auto-extracted entity stubs (batch). Promote flips `status` to verified (provenance kept for audit); reject soft-deletes the stub. Owner-only: this op is refused for any non-local caller. (The markers are ordinary frontmatter — the boundary against rewriting them wholesale is put_page write authz, same as for any page.)',+ description: 'Decide on review rows (batch). promote flips an unverified auto-extracted stub\'s `status` to verified (provenance kept for audit); reject soft-deletes the stub; distinct records that each of slugs is a different entity from of (`distinct_from` frontmatter), so possible_duplicates stops pairing them. Every decision writes through the page door: Git first on a source with a repository, the database on a repo-less source. Owner-only: this op is refused for any non-local caller. (The markers are ordinary frontmatter — the boundary against rewriting them wholesale is put_page write authz, same as for any page.)',params: {- action: { type: 'string', required: true, description: "'promote' or 'reject'." },- slugs: { type: 'array', required: true, items: { type: 'string' }, description: 'Stub slugs to act on (batch).' },+ action: { type: 'string', required: true, description: "'promote', 'reject' or 'distinct'." },+ slugs: { type: 'array', required: true, items: { type: 'string' }, description: 'Slugs to act on (batch).' },+ of: { type: 'string', required: false, description: "distinct only: the existing entity page each of slugs is not the same as." },},mutating: true,scope: 'write',@@ -227,10 +238,10 @@ const extraction_review: Operation = {if (ctx.remote !== false) {throw reviewOwnerOnly(ctx, p);}- const action = p.action as string;- if (action !== 'promote' && action !== 'reject') {- throw opError('invalid_params', `extraction_review: action must be 'promote' or 'reject'; got '${action}'.`,- "Nothing changed. Pass 'promote' or 'reject' as the action; fix lists the stubs awaiting review.", { fix: pendingFix() });+ const action = p.action;+ if (!isReviewAction(action)) {+ throw opError('invalid_params', `extraction_review: action must be 'promote', 'reject' or 'distinct'; got '${String(action)}'.`,+ "Nothing changed. Pass 'promote', 'reject' or 'distinct' as the action; fix lists the rows awaiting review.", { fix: pendingFix() });}// CLI passes `--slugs a,b,c` as one string; MCP passes a real array.const slugs = Array.isArray(p.slugs)@@ -243,10 +254,18 @@ const extraction_review: Operation = {`Nothing changed. Pass the stub slugs to act on, for example ${paramUse(ctx, 'slugs', ctx.remote === false ? 'slug1,slug2' : ['slug1', 'slug2'])}; fix lists the stubs awaiting review.`,{ fix: pendingFix() });}- if (ctx.dryRun) return { dry_run: true, action: `extraction_review:${action}`, slugs };+ const of = typeof p.of === 'string' ? p.of.trim() : '';+ if (action === 'distinct' && !REVIEW_SLUG.test(of)) {+ throw opError('invalid_params', 'extraction_review distinct needs of: the existing entity page the slugs are not the same as.',+ 'Nothing changed. Pass of: the existing entity page the slugs are not the same as; the possible_duplicates rows of extraction_pending carry the exact command.',+ { fix: readFix('Lists recently created entity pages flagged as near names, each with its distinct command.',+ { argv: ['gbrain', 'extraction-pending', '--include', 'possible_duplicates'], mcp: { tool: 'extraction_pending', arguments: { include: ['possible_duplicates'] } } }) });+ }+ if (ctx.dryRun) return { dry_run: true, action: `extraction_review:${action}`, slugs, ...(action === 'distinct' ? { of } : {}) };const results: Array<{ slug: string; status: string }> = [];+ const writeRequests: Array<{ slug: string; request_id: unknown; state: unknown }> = [];for (const slug of slugs) {- // First-match read is safe here: BOTH writes below key on the RETURNED+ // First-match read is safe here: every write below keys on the RETURNED// row's page.source_id, so read and write can never target different// rows. gbrain-allow-unscoped-getpage: write follows the returned rowconst page = await ctx.engine.getPage(slug, ctx.sourceId ? { sourceId: ctx.sourceId } : undefined);@@ -254,36 +273,64 @@ const extraction_review: Operation = {results.push({ slug, status: 'not_found' });continue;}- if (!isUnverifiedExtraction(page.frontmatter)) {- results.push({ slug, status: 'not_unverified' });- continue;- }- if (action === 'promote') {- // Frontmatter-only flip via a targeted JSONB merge — NOT putPage,- // whose upsert would reset non-carried columns (page_kind →- // 'markdown', content_hash, …) for a change that only touches one- // frontmatter key. provenance stays 'auto-extracted' as the audit- // trail of HOW the page came to exist; status → 'verified' records- // the owner's call. jsonb_build_object binds as text (no- // JSON.stringify-into-::jsonb hazard); identical on both engines.- await maintenanceTransaction(ctx.engine, tx => tx.executeRaw(- `UPDATE pages- SET frontmatter = COALESCE(frontmatter, '{}'::jsonb) || jsonb_build_object($1::text, $2::text),- updated_at = now()- WHERE slug = $3 AND source_id = $4`,- [EXTRACTION_STATUS_KEY, STATUS_VERIFIED, slug, page.source_id],- ));- results.push({ slug, status: 'promoted' });- } else {- await maintenanceTransaction(ctx.engine, tx => tx.softDeletePage(slug, { sourceId: page.source_id }));- results.push({ slug, status: 'rejected' });- }+ const decided = await reviewDecision(ctx, action, slug, page.source_id, of);+ results.push({ slug, status: decided.status });+ if (decided.response) writeRequests.push({ slug, request_id: decided.response.request_id, state: decided.response.state });}- return { status: 'ok', action, results };+ return { status: 'ok', action, results, ...(writeRequests.length ? { write_requests: writeRequests } : {}) };},cliHints: { name: 'extraction-review', positional: ['action'] },};+/**+ * One review decision under the source's publication guard: re-read the page, re-check that the decision+ * still applies, and publish it through the page door with the revision it read (a page that moved in+ * between reports `changed`; run the command again).+ */+async function reviewDecision(ctx: OperationContext, action: ReviewDecision, slug: string, sourceId: string, of: string):+ Promise<{ status: string; response?: Record<string, unknown> }> {+ return withPublicationGuard(ctx.engine, sourceId, async () => {+ const snapshot = await ctx.engine.readPageSnapshot(slug, { sourceId });+ if (!snapshot || snapshot.page.deleted_at) return { status: 'not_found' };+ const fm = (snapshot.page.frontmatter ?? {}) as Record<string, unknown>;+ // Frontmatter-only decisions edit the page's head (serialized with an empty body, as edit_page lays it out), so+ // the body is never read or rewritten and a segmented page keeps its segments.+ const head = (frontmatter: Record<string, unknown>) =>+ serializePageToMarkdown({ ...withoutBody(snapshot.page), frontmatter, compiled_truth: '', timeline: '' } as Page, snapshot.tags).slice(0, -1);+ const editHead = (frontmatter: Record<string, unknown>) =>+ ({ operation: 'edit_page' as const, params: { slug, source_id: sourceId, edits: [{ old_text: head(fm), new_text: head(frontmatter) }] } });+ let mutation: { operation: 'edit_page' | 'delete_page'; params: Record<string, unknown> };+ let status: string;+ if (action === 'distinct') {+ if (of === slug) return { status: 'same_page' };+ const other = await ctx.engine.getPage(of, { sourceId });+ if (!other) return { status: 'of_not_found' };+ const prior = Array.isArray(fm.distinct_from) ? fm.distinct_from.filter((x): x is string => typeof x === 'string') : typeof fm.distinct_from === 'string' ? [fm.distinct_from] : [];+ if (prior.includes(of)) return { status: 'already_distinct' };+ mutation = editHead({ ...fm, distinct_from: [...prior, of] });+ status = 'distinct';+ } else if (!isUnverifiedExtraction(fm)) {+ return { status: 'not_unverified' };+ } else if (action === 'promote') {+ // provenance stays 'auto-extracted' as the audit trail of HOW the page came to exist; status → 'verified'+ // records the owner's call.+ mutation = editHead({ ...fm, [EXTRACTION_STATUS_KEY]: STATUS_VERIFIED });+ status = 'promoted';+ } else {+ mutation = { operation: 'delete_page', params: { slug, source_id: sourceId } };+ status = 'rejected';+ }+ try {+ const response = await submitPageMutation(ctx, { operation: mutation.operation,+ params: { ...mutation.params, expected_revision: snapshot.revision, request_id: randomUUID() } });+ return { status, response };+ } catch (error) {+ if (error instanceof OperationError && ['revision_conflict', 'changed_since_preview'].includes(error.code)) return { status: 'changed' };+ throw error;+ }+ });+}+export const extractionOperations: Operation[] = [extract_entities, extraction_pending, extraction_review,];diff --git a/src/core/persistence/publication-guard.ts b/src/core/persistence/publication-guard.tsnew file mode 100644index 0000000000..094a7e6085--- /dev/null+++ b/src/core/persistence/publication-guard.ts@@ -0,0 +1,40 @@+/**+ * GBRA-215: the source-scoped guard that review decisions (extraction_review promote, reject and distinct)+ * and ingest undo take while they re-read a page, re-check its eligibility and publish the decision. Two+ * decisions on one source never interleave between the check and the write, so an undo that previewed a+ * proposed page cannot delete it after a promotion landed, and a promotion cannot flip a page an undo is+ * retracting. The write itself still carries its expected revision; the guard orders the decisions.+ *+ * Built on the gbrain_cycle_locks lease (tryAcquireDbLock), so it holds across processes on both engines.+ * The wait is bounded and the lease is short: a holder that dies frees it when its TTL lapses.+ */+import type { BrainEngine } from '../engine.ts';+import { tryAcquireDbLock } from '../db-lock.ts';+import { opError, type OperationError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';++export const PUBLICATION_GUARD_WAIT_MS = 15_000;+const PUBLICATION_GUARD_TTL_MINUTES = 5;++export function publicationGuardId(sourceId: string): string {+ return `review-publication:${sourceId}`;+}++function guardBusy(sourceId: string, waitMs: number): OperationError {+ return opError('lock_busy', `Another review decision or undo on source ${sourceId} held the publication guard for the whole wait.`,+ `Nothing was written. Another review decision or ingest undo on this source held the guard for ${Math.round(waitMs / 1000)}s; retry the same command once it finishes.`,+ { fix: readFix('Shows the gbrain_cycle_locks rows, the review-publication guard included, with holder and expiry, read-only.', { argv: ['gbrain', 'status', '--section', 'locks', '--json'] }) });+}++/** Runs `work` holding the source's publication guard; throws `lock_busy` when another holder keeps it past `waitMs`. */+export async function withPublicationGuard<T>(engine: BrainEngine, sourceId: string, work: () => Promise<T>, waitMs = PUBLICATION_GUARD_WAIT_MS): Promise<T> {+ const deadline = performance.now() + waitMs;+ for (;;) {+ const handle = await tryAcquireDbLock(engine, publicationGuardId(sourceId), PUBLICATION_GUARD_TTL_MINUTES);+ if (handle) {+ try { return await work(); } finally { await handle.release().catch(() => {}); }+ }+ if (performance.now() >= deadline) throw guardBusy(sourceId, waitMs);+ await new Promise(resolve => setTimeout(resolve, 100));+ }+}diff --git a/src/core/review-lists.ts b/src/core/review-lists.tsindex 82d83ff412..b486611141 100644--- a/src/core/review-lists.ts+++ b/src/core/review-lists.ts@@ -110,6 +110,8 @@ export async function listPossibleDuplicates(engine: BrainEngine, ctx: Operation{ kind: 'add_alias', run_by: 'caller', argv: ['gbrain', 'get', first.slug],mcp: { tool: 'edit_page', arguments: { slug: first.slug, expected_revision: '<from get_page>', edits: [] } },why: `If "${own[0]!.name}" is another name for ${first.slug}, add it to that page's aliases frontmatter; the pair is then no longer flagged.` },+ { kind: 'mark_distinct', run_by: local ? 'caller' : 'owner', argv: ['gbrain', 'extraction-review', 'distinct', '--slugs', slug, '--of', first.slug],+ why: `If ${slug} and ${first.slug} are different entities, records it in ${slug}'s distinct_from frontmatter (through the page door); the pair is then no longer flagged.` },],});}diff --git a/test/e2e/extraction-review-door-postgres.test.ts b/test/e2e/extraction-review-door-postgres.test.tsnew file mode 100644index 0000000000..5a28d61ebd--- /dev/null+++ b/test/e2e/extraction-review-door-postgres.test.ts@@ -0,0 +1,72 @@+/**+ * GBRA-215 L2 on live Postgres: extraction_review promote, reject and distinct through the page door, on a+ * repository-backed source and on a repo-less one. PGLite runs the same scenarios in+ * test/extraction-review-door.serial.test.ts.+ *+ * Gated by DATABASE_URL via hasDatabase(); skips cleanly when unset.+ *+ * Run: DATABASE_URL=... bun test test/e2e/extraction-review-door-postgres.test.ts+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { dropPreadmitCache } from '../../src/core/persistence/preadmit-cache.ts';+import {+ distinctScenario, promoteScenario, racedDecisionsScenario, rejectScenario, reviewDoorFixture,+ type ReviewDoorFixture, type ReviewStorage,+} from '../helpers/review-door-scenarios.ts';++const RUN = hasDatabase();+const d = RUN ? describe : describe.skip;++let engine: PostgresEngine;+let fx: ReviewDoorFixture | null = null;+let home: string;+let priorHome: string | undefined;++// setupDB does not truncate the persistence bindings: release the claim so no later test or file inherits it.+// The worktree row stays: the write requests this file journaled still reference it.+const releaseClaim = () => engine.executeRaw(`DELETE FROM persistence_source_bindings WHERE source_id = 'default';+ DELETE FROM persistence_host_bindings h WHERE NOT EXISTS (SELECT 1 FROM persistence_source_bindings s WHERE s.worktree_id = h.worktree_id);+ UPDATE sources SET local_path = NULL WHERE id = 'default'`);++/** On Postgres a repository-backed source writes through its canonical owner, so the git fixture claims the checkout for this host. */+async function fixture(storage: ReviewStorage): Promise<ReviewDoorFixture> {+ await releaseClaim();+ // The raw release bypasses admission, so drop the 30 s pre-admission cache of the source row it changed.+ dropPreadmitCache(engine);+ const made = await reviewDoorFixture(engine, storage);+ if (!made.repo) return made;+ await engine.executeRaw(`UPDATE sources SET local_path = $1 WHERE id = 'default'`, [made.repo]);+ await claimWorktree(engine, 'default', made.repo);+ return made;+}++d('extraction_review through the page door (live Postgres)', () => {+ beforeAll(async () => { engine = await setupDB(); }, 60_000);+ afterAll(async () => { await releaseClaim(); await engine.unsetConfig('sync.repo_path'); await teardownDB(); }, 60_000);+ beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-review-door-home-'));+ priorHome = process.env.GBRAIN_HOME;+ process.env.GBRAIN_HOME = home;+ });+ afterEach(async () => {+ await disposePersistenceConsumer(engine);+ fx?.cleanup(); fx = null;+ if (priorHome === undefined) delete process.env.GBRAIN_HOME; else process.env.GBRAIN_HOME = priorHome;+ rmSync(home, { recursive: true, force: true });+ });++ for (const storage of ['git', 'database'] as ReviewStorage[]) {+ const label = storage === 'git' ? 'repository-backed' : 'repo-less';+ test(`promote (${label})`, async () => { fx = await fixture(storage); await promoteScenario(engine, fx); }, 30_000);+ test(`reject (${label})`, async () => { fx = await fixture(storage); await rejectScenario(engine, fx); }, 30_000);+ test(`distinct (${label})`, async () => { fx = await fixture(storage); await distinctScenario(engine, fx); }, 30_000);+ test(`raced promote and reject (${label})`, async () => { fx = await fixture(storage); await racedDecisionsScenario(engine, fx); }, 30_000);+ }+});diff --git a/test/extraction-review-door.serial.test.ts b/test/extraction-review-door.serial.test.tsnew file mode 100644index 0000000000..cb15bd3a88--- /dev/null+++ b/test/extraction-review-door.serial.test.ts@@ -0,0 +1,122 @@+/**+ * GBRA-215 L2: extraction_review promote, reject and distinct write through the page door on PGLite, on a+ * repository-backed source (Git commit first) and on a repo-less one (the database is the record), under+ * the source's publication guard. Postgres runs the same scenarios in+ * test/e2e/extraction-review-door-postgres.test.ts.+ *+ * .serial: real git subprocesses against tmp repos and a GBRAIN_HOME swap.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { tryAcquireDbLock } from '../src/core/db-lock.ts';+import { publicationGuardId, withPublicationGuard } from '../src/core/persistence/publication-guard.ts';+import { operationsByName, OperationError } from '../src/core/operations.ts';+import {+ distinctScenario, promoteScenario, racedDecisionsScenario, rejectScenario, reviewCtx, reviewDoorFixture, seedStub,+ type ReviewDoorFixture, type ReviewStorage,+} from './helpers/review-door-scenarios.ts';++let engine: PGLiteEngine;+let fx: ReviewDoorFixture | null = null;+let home: string;+let priorHome: string | undefined;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);+afterAll(async () => { await engine.disconnect(); }, 60_000);+beforeEach(async () => {+ await resetPgliteState(engine);+ home = mkdtempSync(join(tmpdir(), 'gbrain-review-door-home-'));+ priorHome = process.env.GBRAIN_HOME;+ process.env.GBRAIN_HOME = home;+});+afterEach(async () => {+ await disposePersistenceConsumer(engine);+ fx?.cleanup(); fx = null;+ if (priorHome === undefined) delete process.env.GBRAIN_HOME; else process.env.GBRAIN_HOME = priorHome;+ rmSync(home, { recursive: true, force: true });+});++for (const storage of ['git', 'database'] as ReviewStorage[]) {+ describe(`extraction_review through the page door (${storage === 'git' ? 'repository-backed' : 'repo-less'} source)`, () => {+ test('promote flips status to verified through the door', async () => {+ fx = await reviewDoorFixture(engine, storage);+ await promoteScenario(engine, fx);+ }, 30_000);+ test('reject soft-deletes through the door', async () => {+ fx = await reviewDoorFixture(engine, storage);+ await rejectScenario(engine, fx);+ }, 30_000);+ test('distinct records distinct_from and silences the pair', async () => {+ fx = await reviewDoorFixture(engine, storage);+ await distinctScenario(engine, fx);+ }, 30_000);+ test('a raced promote and reject land exactly one decision', async () => {+ fx = await reviewDoorFixture(engine, storage);+ await racedDecisionsScenario(engine, fx);+ }, 30_000);+ });+}++describe('publication guard', () => {+ test('a review decision waits for the guard and runs once it is released', async () => {+ fx = await reviewDoorFixture(engine, 'database');+ const slug = 'people/guarded-example';+ await seedStub(engine, slug, 'Guarded Example');+ const held = (await tryAcquireDbLock(engine, publicationGuardId('default'), 1))!;+ let released = 0;+ const decision = operationsByName.extraction_review!.handler(reviewCtx(engine), { action: 'promote', slugs: [slug] });+ await new Promise(resolve => setTimeout(resolve, 400));+ expect((await engine.getPage(slug))!.frontmatter.status).toBe('unverified');+ released = performance.now();+ await held.release();+ const out = await decision as { results: Array<{ status: string }> };+ expect(performance.now()).toBeGreaterThanOrEqual(released);+ expect(out.results[0]!.status).toBe('promoted');+ }, 30_000);++ test('a guard held past the wait refuses with lock_busy and writes nothing', async () => {+ const held = (await tryAcquireDbLock(engine, publicationGuardId('default'), 1))!;+ let ran = false;+ try {+ const err = await withPublicationGuard(engine, 'default', async () => { ran = true; }, 250).then(() => null, (e: unknown) => e);+ expect(err).toBeInstanceOf(OperationError);+ expect((err as OperationError).code).toBe('lock_busy');+ expect((err as OperationError).fix?.argv).toEqual(['gbrain', 'status', '--section', 'locks', '--json']);+ expect(ran).toBe(false);+ } finally { await held.release(); }+ });++ test('guards are per source: another source decides while one is held', async () => {+ const held = (await tryAcquireDbLock(engine, publicationGuardId('source-a'), 1))!;+ try {+ expect(await withPublicationGuard(engine, 'default', async () => 'ran', 250)).toBe('ran');+ } finally { await held.release(); }+ });+});++describe('extraction_review distinct refusals', () => {+ test('a remote caller is told the exact owner command, of included', async () => {+ const err = await operationsByName.extraction_review!.handler(reviewCtx(engine, { remote: true }),+ { action: 'distinct', slugs: ['companies/acmi-example'], of: 'companies/acme-example' }).then(() => null, (e: unknown) => e) as OperationError;+ expect(err.code).toBe('permission_denied');+ expect(err.fix?.actor).not.toBe('agent');+ expect(err.fix?.user_message).toBeTruthy();+ expect(err.fix?.argv).toEqual(['gbrain', 'extraction-review', 'distinct', '--slugs', 'companies/acmi-example', '--of', 'companies/acme-example']);+ });++ test('distinct without of is invalid_params and writes nothing', async () => {+ const err = await operationsByName.extraction_review!.handler(reviewCtx(engine), { action: 'distinct', slugs: ['companies/acmi-example'] })+ .then(() => null, (e: unknown) => e) as OperationError;+ expect(err.code).toBe('invalid_params');+ expect(err.fix?.argv).toEqual(['gbrain', 'extraction-pending', '--include', 'possible_duplicates']);+ });+});diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 293362e44e..1ec61e4d65 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 265643,- "stdoutSha256": "a3193f5bf16f3f06caa9c6a96be44a89434f470729fbb1ca70230d83803cc63c",+ "stdoutBytes": 266092,+ "stdoutSha256": "2c3bfc071a1de8087f8d53fe42d76b52bf26cd5f40cfdfdec034997461f63366","toolNames": ["remember","entity",@@ -6456,24 +6456,29 @@"scope": "read"},{- "description": "Promote or reject unverified auto-extracted entity stubs (batch). Promote flips `status` to verified (provenance kept for audit); reject soft-deletes the stub. Owner-only: this op is refused for any non-local caller. (The markers are ordinary frontmatter — the boundary against rewriting them wholesale is put_page write authz, same as for any page.)",+ "description": "Decide on review rows (batch). promote flips an unverified auto-extracted stub's `status` to verified (provenance kept for audit); reject soft-deletes the stub; distinct records that each of slugs is a different entity from of (`distinct_from` frontmatter), so possible_duplicates stops pairing them. Every decision writes through the page door: Git first on a source with a repository, the database on a repo-less source. Owner-only: this op is refused for any non-local caller. (The markers are ordinary frontmatter — the boundary against rewriting them wholesale is put_page write authz, same as for any page.)","idempotent": false,"local_only": true,"mutating": true,"name": "extraction_review","parameters": {"action": "string",+ "of": "string?","slugs": "array"},"required_scopes": [],"schema": {"properties": {"action": {- "description": "'promote' or 'reject'.",+ "description": "'promote', 'reject' or 'distinct'.",+ "type": "string"+ },+ "of": {+ "description": "distinct only: the existing entity page each of slugs is not the same as.","type": "string"},"slugs": {- "description": "Stub slugs to act on (batch).",+ "description": "Slugs to act on (batch).","items": {"type": "string"},diff --git a/test/helpers/review-door-scenarios.ts b/test/helpers/review-door-scenarios.tsnew file mode 100644index 0000000000..d271a28c54--- /dev/null+++ b/test/helpers/review-door-scenarios.ts@@ -0,0 +1,160 @@+/**+ * GBRA-215 L2: extraction_review decisions through the page door, as scenarios both engines run on a+ * repository-backed source and on a repo-less one (test/extraction-review-door.serial.test.ts on PGLite,+ * test/e2e/extraction-review-door-postgres.test.ts on Postgres).+ */+import { expect } from 'bun:test';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import { operationsByName, type OperationContext } from '../../src/core/operations.ts';+import { runPersistenceEffects } from '../../src/core/persistence/effects.ts';+import { localHostId } from '../../src/core/persistence/identity.ts';+import { parseMarkdown } from '../../src/core/markdown.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';+import { git } from './git-publication.ts';++export type ReviewStorage = 'git' | 'database';++export interface ReviewDoorFixture { storage: ReviewStorage; repo: string | null; cleanup: () => void }++export function reviewCtx(engine: BrainEngine, over: Partial<OperationContext> = {}): OperationContext {+ return {+ engine,+ config: { engine: engine.kind } as OperationContext['config'],+ logger: { info() {}, warn() {}, error() {} },+ dryRun: false,+ remote: false,+ sourceId: 'default',+ ...over,+ } as OperationContext;+}++/** A durability-hardened repo with no remote (Git effects commit for real), or no repository at all. */+export async function reviewDoorFixture(engine: BrainEngine, storage: ReviewStorage): Promise<ReviewDoorFixture> {+ _resetWriteThroughCacheForTest();+ if (storage === 'database') {+ await engine.unsetConfig('sync.repo_path');+ return { storage, repo: null, cleanup: () => {} };+ }+ const repo = mkdtempSync(join(tmpdir(), 'gbrain-review-door-'));+ git(repo, 'init', '-q', '-b', 'main');+ git(repo, 'config', 'user.name', 'Example Writer');+ git(repo, 'config', 'user.email', '[email protected]');+ writeFileSync(join(repo, 'seed.md'), 'seed\n');+ git(repo, 'add', 'seed.md'); git(repo, 'commit', '-q', '-m', 'Initial');+ mkdirSync(join(repo, '.git', 'hooks'), { recursive: true });+ writeFileSync(join(repo, '.git', 'hooks', 'post-commit'), '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\nexit 0\n');+ chmodSync(join(repo, '.git', 'hooks', 'post-commit'), 0o755);+ await engine.setConfig('sync.repo_path', repo);+ return { storage, repo, cleanup: () => rmSync(repo, { recursive: true, force: true }) };+}++async function drain(engine: BrainEngine): Promise<void> {+ await runPersistenceEffects(engine, { engine: engine.kind, embedding_disabled: true } as never, { hostId: localHostId(), limit: 16 });+}++/** The file Git's HEAD holds for a slug, or null when HEAD has none. */+export function committedFile(repo: string, slug: string): string | null {+ try { return git(repo, 'show', `HEAD:${slug}.md`); } catch { return null; }+}++/** An unverified auto-extracted stub, written through the page door like any other page. */+export async function seedStub(engine: BrainEngine, slug: string, title: string): Promise<void> {+ const put = operationsByName.put_page!;+ await put.handler(reviewCtx(engine), { slug,+ content: `---\ntype: ${slug.startsWith('companies/') ? 'company' : 'person'}\ntitle: ${title}\nprovenance: auto-extracted\nstatus: unverified\n---\n\n${title} came up in a call.\n` });+ await drain(engine);+}++async function review(engine: BrainEngine, params: Record<string, unknown>): Promise<{ results: Array<{ slug: string; status: string }>; write_requests?: Array<{ slug: string; request_id: string; state: string }> }> {+ const out = await operationsByName.extraction_review!.handler(reviewCtx(engine), params) as never;+ await drain(engine);+ return out;+}++export async function promoteScenario(engine: BrainEngine, fx: ReviewDoorFixture): Promise<void> {+ const slug = `people/promote-${fx.storage}-example`;+ await seedStub(engine, slug, 'Promote Example');+ const head = fx.repo ? git(fx.repo, 'rev-parse', 'HEAD').trim() : null;+ const out = await review(engine, { action: 'promote', slugs: [slug] });+ expect(out.results).toEqual([{ slug, status: 'promoted' }]);+ expect(out.write_requests?.[0]).toMatchObject({ slug, state: 'committed' });+ const page = await engine.getPage(slug);+ expect(page!.frontmatter.status).toBe('verified');+ expect(page!.frontmatter.provenance).toBe('auto-extracted');+ expect(page!.compiled_truth).toContain('came up in a call');+ if (fx.repo) {+ expect(git(fx.repo, 'rev-parse', 'HEAD').trim()).not.toBe(head);+ const file = committedFile(fx.repo, slug)!;+ const parsed = parseMarkdown(file, `${slug}.md`);+ expect(parsed.frontmatter.status).toBe('verified');+ expect(parsed.frontmatter.provenance).toBe('auto-extracted');+ expect(file).toContain('came up in a call');+ // Rebuild from Git: drop the row and import the committed file; the owner's decision survives.+ await engine.executeRaw('DELETE FROM pages WHERE slug = $1', [slug]);+ await importFromContent(engine, slug, file);+ expect((await engine.getPage(slug))!.frontmatter.status).toBe('verified');+ }+}++export async function rejectScenario(engine: BrainEngine, fx: ReviewDoorFixture): Promise<void> {+ const slug = `people/reject-${fx.storage}-example`;+ await seedStub(engine, slug, 'Reject Example');+ if (fx.repo) expect(committedFile(fx.repo, slug)).not.toBeNull();+ const out = await review(engine, { action: 'reject', slugs: slug });+ expect(out.results).toEqual([{ slug, status: 'rejected' }]);+ expect(out.write_requests?.[0]).toMatchObject({ slug, state: 'committed' });+ expect(await engine.getPage(slug)).toBeNull();+ expect((await engine.getPage(slug, { includeDeleted: true }))?.deleted_at).toBeTruthy();+ if (fx.repo) {+ expect(committedFile(fx.repo, slug)).toBeNull();+ expect(existsSync(join(fx.repo, `${slug}.md`))).toBe(false);+ }+}++export async function distinctScenario(engine: BrainEngine, fx: ReviewDoorFixture): Promise<void> {+ const existing = `companies/acme-${fx.storage}`;+ const fresh = `companies/acmi-${fx.storage}`;+ await operationsByName.put_page!.handler(reviewCtx(engine), { slug: existing, content: `---\ntype: company\ntitle: Acme ${fx.storage}\n---\n\nAn existing company.\n` });+ await operationsByName.put_page!.handler(reviewCtx(engine), { slug: fresh, content: `---\ntype: company\ntitle: Acmi ${fx.storage}\n---\n\nA different company.\n` });+ await drain(engine);+ const pending = operationsByName.extraction_pending!;+ const before = await pending.handler(reviewCtx(engine), { include: ['possible_duplicates'] }) as { possible_duplicates: { rows: Array<{ slug: string; actions: Array<{ kind: string; argv: string[] }> }> } };+ const row = before.possible_duplicates.rows.find(r => r.slug === fresh || r.slug === existing)!;+ const mark = row.actions.find(a => a.kind === 'mark_distinct')!;+ expect(mark.argv.slice(0, 3)).toEqual(['gbrain', 'extraction-review', 'distinct']);+ const [newSlug, ofSlug] = [mark.argv[4]!, mark.argv[6]!];+ const out = await review(engine, { action: 'distinct', slugs: [newSlug], of: ofSlug });+ expect(out.results).toEqual([{ slug: newSlug, status: 'distinct' }]);+ expect((await engine.getPage(newSlug))!.frontmatter.distinct_from).toEqual([ofSlug]);+ const again = await review(engine, { action: 'distinct', slugs: [newSlug], of: ofSlug });+ expect(again.results).toEqual([{ slug: newSlug, status: 'already_distinct' }]);+ expect(again.write_requests).toBeUndefined();+ const after = await pending.handler(reviewCtx(engine), { include: ['possible_duplicates'] }) as { possible_duplicates: { rows: Array<{ slug: string }> } };+ expect(after.possible_duplicates.rows.map(r => r.slug)).not.toContain(newSlug);+ expect(after.possible_duplicates.rows.map(r => r.slug)).not.toContain(ofSlug);+ if (fx.repo) expect(parseMarkdown(committedFile(fx.repo, newSlug)!, `${newSlug}.md`).frontmatter.distinct_from).toEqual([ofSlug]);+}++/** Promote and reject of one stub raced: the guard orders them, so exactly one decision lands. */+export async function racedDecisionsScenario(engine: BrainEngine, fx: ReviewDoorFixture): Promise<void> {+ const slug = `people/race-${fx.storage}-example`;+ await seedStub(engine, slug, 'Race Example');+ const [a, b] = await Promise.all([+ review(engine, { action: 'promote', slugs: [slug] }),+ review(engine, { action: 'reject', slugs: [slug] }),+ ]);+ const statuses = [a.results[0]!.status, b.results[0]!.status].sort();+ expect([['not_found', 'rejected'], ['not_unverified', 'promoted']]).toContainEqual(statuses);+ const page = await engine.getPage(slug);+ if (statuses.includes('promoted')) expect(page!.frontmatter.status).toBe('verified');+ else expect(page).toBeNull();+ if (fx.repo) {+ const file = committedFile(fx.repo, slug);+ if (statuses.includes('promoted')) expect(parseMarkdown(file!, `${slug}.md`).frontmatter.status).toBe('verified');+ else expect(file).toBeNull();+ }+}