Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge capy/w9f-lane-j (wave 9 follow-ups lane J: judge thinking capability table, judge cost preflights, round-2 TODOS)

garrytana3176ee65605
diff --cc TODOS.md
index 0d6c3f96a2,9c0f01fefd..6ac922d76b
--- a/TODOS.md
+++ b/TODOS.md
@@@ -1,41 -1,16 +1,52 @@@
# TODOS
+## Fix wave 12 follow-ups (filed 2026-10-07, GBRA-57)
+
+- [ ] **P2 — Free relabel for a legacy bare `embedding_model` row (#6113, carried from wave 11 W4.7).** **What:** wave 12 ships the refusal that names `gbrain migrate embeddings --to <provider:model> --dry-run`; the zero-cost relabel is not built. **Fix:** a restamp-only branch taken only when bare row, recipe, unambiguous model, dimensions, gateway config and every stored chunk/fact/take stamp agree (a NULL stamp on a non-null vector refuses), translating the model-bound chunk input hashes (`embedding-input-hash.ts`) and recording prior labels; doctor `embedding_identity_unqualified`. Needs a concurrent old-model worker test on Postgres. **Effort:** M-L. **Priority:** P2.
+- [ ] **P2 — Hard ceiling for a stuck managed write (W3.3b, #6176).** **What:** still detection only. **Fix:** reuse `persistence.max_claim_ms` as a ceiling during preparation, fail as `write_stalled` after 3 releases, keep publication detection-only; it needs two `consumer.ts` hunks, so it lands after GBRA-45's sync-feeder rework. **Effort:** M. **Priority:** P2.
+- [ ] **P3 — Transcript budget for dream patterns children (#6236).** **What:** wave 12 de-duplicates claim records and counts deaths per source; a per-job transcript budget and subagent tool wrapper are not built. **Effort:** M. **Priority:** P3.
+- [ ] **P3 — Quarantine junk classifier masks code (#6259).** **What:** fenced and inline code still trip junk patterns; wave 12 ships the override only. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — Restore image pages' text projection after managed activation (#6223).** **What:** activation clears every page's projection marker; only `embed --stale --images` restores image pages. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — `type: code` pages skip body link extraction (#6228).** **What:** code pages no longer abort extraction but still add noise rows to `gbrain wanted`. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — Cyrillic-aware slug folding (#6235's bug).** **What:** `Сергей` slugs to `сергеи` because й loses its breve; #6235 was declined (undisclosed changes, a self-granting migration). Needs its own designed wave covering aliases and in-place upgrade. **Effort:** L. **Priority:** P3.
+- [ ] **P3 — `extract all --source db` keeps finished pages on an abort (#6228 S4).** **What:** only the stale sweep stamps finished pages; the `all` path runs links then timeline, so stamping on a links abort would mark pages timeline-fresh. **Fix:** per-phase stamps. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — Postgres vector arm without Materialize (#6039, second half).** **What:** `enable_material=off` was moved out of wave 12 because one scale run can't show no regression. **Fix:** a retrieval-latency eval at several brain sizes before changing the default. **Effort:** M. **Priority:** P3.
+- [ ] **P3 — Wave 12 CSO lows (GBRA-57 review of v0.60.106.0).** Each fails closed or needs a trusted path today. (T1) `quarantine_override`'s body hash isn't keyed, so a file synced on a trusted path (an upstream repo behind a read-only mirror source) can compute its own and bypass the content-quality gate: key it with a brain-local secret. (G1) The hardened-Git blocklist misses Git's option abbreviations (`--textc`, `--filt` ran textconv and clean): switch to an exact allow-list of full options. (G2) `hardenedPathDirty` passes paths as pathspecs, so `[ab].md` and `*.md` glob: use `:(literal)`. (G3) A `.git` planted in a world-writable ancestor (`/tmp`) parks Git effects as `git_unavailable`: stop discovery at an ownership change. (G4, pre-existing) an inherited `GIT_DIR` makes a plain directory report durable. (L1) The skill-lint paid-consent check is lexical and bypassable; treat it as a tripwire, not a gate. Plus the review's hardening notes (quote `pollCommand` arguments, return the parsed `LLMS_REPO_BASE` URL). **Effort:** S each. **Priority:** P3.
+- [ ] **P3 — Batch `remember` accepts a non-UUID top-level `request_id`.** **What:** wave 12's agent smoke saw a batch `remember` (with `items`) accept `7c1e2a9e-5b3f-4d0a-9e61-qul1-20260915`; single-fact `remember`, `edit_page` and `add_timeline_entry` refuse non-UUID ids. **Fix:** validate the top-level `request_id` on the batch path the same way, with a test. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — `forget` caveat inside Claude Code's 2,048-character head (wave 11 CSO E4).** **What:** wave 12 moved it next to the "facts saved with remember" sentence and Opus 5.5 write-back fell 20/20 -> 15/20 (attribution 19/20 with the old text; gbrain-evals branch `capy/w12-agent-smoke`), so it was reverted. Any added clause before clause 7 pushes "Answering from the brain" further past the cap on the full surfaces. **Fix:** a net-zero-length rewrite of clauses 1-6 that fits the caveat, then 20 Opus write-back cells (about $4.50) before shipping. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — Connector tests asserting a complete run under the 1.5 s fixture budget.** **What:** `test/helpers/connector-fixture.ts` cuts every connector wait to `testWaitMs(1_500)`; a cold consumer start on a loaded VM can exceed it, so a healthy-owner run returns `writer_pending` (root-caused in wave 12 for `connector-wave3`, fixed with `withHealthyOwnerBudget`). About 30 other files using `createConnectorFixture` assert `not.toBe('partial')` the same way (e.g. `connector-holds`, `persistence-connectors`). **Fix:** wrap their healthy-owner runs in `withHealthyOwnerBudget`. **Effort:** S. **Priority:** P3.
+
+## Fix wave 11 follow-ups (filed 2026-10-07, GBRA-55)
+
+- [ ] **P2 — Ceiling for a stuck managed publication (W3.3b, #6176).** **What:** a publication that hangs inside a live consumer keeps renewing its claim; wave 11 ships detection only (`claim_phase`, doctor `persistence_write_stall` past `persistence.max_claim_ms`). **Fix:** a phase-split ceiling: a statement timeout inside `publishMutation`, a recovery handoff that releases the root, and a bounded abandonment counter, written against the consumer/coordinator after GBRA-45's sync-feeder work lands. **Effort:** M. **Priority:** P2.
+- [ ] **P2 — Free relabel for a legacy bare `embedding_model` row (W4.7, #6113).** **What:** brains seeded before the qualified default store `text-embedding-3-large` without a provider, and the managed facts resolver refuses it. **Fix:** a restamp-only branch in `gbrain migrate embeddings --to <provider:model>` taken only for a positively established legacy identity (known seed default, every chunk/fact/take stamp equal to the bare value, known provider recipe, equal dimensions), then a resolver refusal and doctor finding that name it. **Effort:** M. **Priority:** P2.
+- [ ] **P3 — Run the keyword and vector arms concurrently on Postgres (#5989).** **What:** the CJK keyword arm's time adds to every hybrid search. **Fix:** start both arms together in `hybrid.ts`, with a retrieval eval before the default changes. **Effort:** M. **Priority:** P3.
+- [ ] **P3 — CJK relevance judgments and a pg_trgm decision (W6.2, D11).** **What:** the capped keyword retry and the OR fallback are covered by invariant tests, not relevance judgments; a trigram index on `chunk_text` was deferred. **Effort:** M. **Priority:** P3.
+- [ ] **P3 — `extract.ts` rebuilds the basename index per lookup.** **What:** `resolveBasenameMatchesFromSlugs` rebuilds the whole index on every call (O(N) per wikilink on the filesystem path); this, not Unicode normalization, is the cost #6178 targeted. **Fix:** build once per run in the caller. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — `--json` BigInt ratchet.** **What:** about 223 `JSON.stringify(…, null, 2)` command sites can crash on Postgres BigInt values (#6193 was one). **Fix:** a lint that `--json` paths use `writeJsonDocument` or the BigInt replacer, then convert the sites. **Effort:** M. **Priority:** P3.
+- [ ] **P3 — Agent-operator conformance suite in CI.** **What:** run every bundled skill's headless command in dry/offline mode plus every command's `--help` and `--json` on a seeded brain. Subsumes the help gate, the skill-command lint and the BigInt ratchet. **Effort:** M. **Priority:** P3.
+- [ ] **P3 — `schema remove-*` read the type name from the first non-flag token.** **What:** `schema remove-type --pack mine people` reads `mine` as the type (fails loudly); the same class W1.6 fixed for `add-type`. **Fix:** parse the name as the first positional that isn't a flag value. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — `search modes --reset --source <mode>` should be `--mode`.** **What:** `--source` means a brain source everywhere else. **Fix:** add `--mode`, keep `--source` as a deprecated alias with a notice. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — Per-source `pages purge-deleted`.** **What:** the purge is brain-wide; wave 11 refuses `--source` instead of silently purging everything. **Fix:** scope the purge by source when asked. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — Doctor warning for harnesses with an instruction cap (#6170).** **What:** wave 11 moved the writeback contract inside Claude Code's 2,048-character cap; other harnesses with caps aren't detected. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — Expire capture-lane facts created after an explicit writeback `off`.** **What:** wave 11 stops new capture under `off`; facts captured before the fix stay. **Fix:** record the off time, then a preview/apply repair that retires facts captured after it. **Effort:** M. **Priority:** P3.
+- [ ] **P3 — Workspace-lane (`bootstrap-v1`) hook marker durability.** **What:** the same lost-marker problem W2.2 fixed for the harness lane. **Fix:** stamp the lane first, then match by command shape. **Effort:** M. **Priority:** P3.
+- [ ] **P3 — `remember` replay hitting `source_changed` stalls `repair failed-writes` (#5994 side note).** **Fix:** classify it in the preview as `file_database_drift` with the reconcile command. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — `waiting` follow-ups (#6174).** **What:** the 500-row fetch cap and the unbounded count term in the score. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — Measure dream patterns sizing on a real paid run (W5.11).** **What:** `planPatternsRun` assumes cost is linear in reflections; it's unmeasured. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — Deferred product calls from the wave 11 plan.** Coordinated type cleanup on managed brains (#6196 C), #6122 (b)/(c) and a managed commit path for agreed git-dirty bytes (#6138), connector contact pages yielding mentions to their main-brain twin (#6158), coordinated raw-file uploads (#5963 part B). Each needs a decision before code. **Priority:** P3.
+- [ ] **P3 — #6131 Darwin export publication.** **What:** not reproduced on macOS 26 (800k publications, arm64 and x64); the report is from macOS 27. **Fix:** rerun the C loop when a macOS 27 runner is available; ship our own fix and rebuilt prebuilds only if it reproduces. **Priority:** P3.
+ ## Fix wave 9 follow-ups, round 2 (filed 2026-10-07, GBRA-41)
+
+ Context: the wave 9 follow-up wave (plan reviewed 2026-10-06; Garry approved every recommended decision on 2026-10-07). These are the items that wave deliberately leaves out.
+
+ - [ ] **P3 — Stall detection for subagent turns, both transports.** **What:** `ai.chat.per_turn_timeout_ms` bounds a whole subagent turn (default 30 min) because neither transport streams, so a hung provider holds the turn for the full budget. Deferred from the wave 9 follow-ups (Decision 1) until GBRA-52 (#6066, which edits the Google instantiation in `ai/gateway.ts`) lands. **Fix:** cover both transports, never only one: (1) the default Anthropic-direct path (`makeSubagentHandler` in `src/core/minions/handlers/subagent.ts` calls `messages.create` on the Anthropic SDK client) moves to `messages.stream` with an idle timer; (2) the gateway path (non-Anthropic routes through `toolLoop`) moves to `streamText` with execute-less tools and `timeout.chunkMs`, raising the `ai` floor in `package.json` to `^6.0.174`. Measure first-chunk and between-chunk windows on current frontier routes before picking defaults (thinking routes can stay silent for minutes; a 120-300 s window kills legitimate reasoning). Add a stall error code with `fix.next`, an error-catalogue entry and a config override (for example `ai.chat.stall_timeout_ms`). **Effort:** M. **Priority:** P3.
+ - [ ] **P2 — Receipts for the pages, timeline and alias derived writers.** **What:** the wave 9 follow-ups put admitted persistence requests (receipts) on the managed-brain facts and takes writers it touches and add a coverage test that names every other guarded-table writer; the derived writers in `src/core/page-state/materialize.ts`, `src/core/timeline-extract.ts`, `src/commands/reindex-aliases.ts` and `src/core/mentions/pass.ts` still write on managed brains without one and are listed there with a TODO. **Fix:** admit a persistence request per derived batch (page revision as the CAS), then drop their TODO rows from the coverage table. **Effort:** M. **Priority:** P2.
+ - [ ] **P2 — Production fail-closed receipt guard.** **What:** the receipt requirement (`gbrain.write_request` for facts and takes writes on managed brains) is enforced only in the contract-test harness plus the coverage table (Decision 10). **Fix:** once the coverage table lists no unreceipted writer, enforce it in the production guard function as well (fail closed; a function-only replace, no table lock), behind a `BEHAVIOR_CHANGES` row. **Effort:** S. **Priority:** P2.
+ - [ ] **P3 — Owner delegation for every `gbrain repair` kind under a live serve.** **What:** while `gbrain serve` owns a PGLite brain, repair kinds that open the engine wait on its lock or refuse with stop, repair, restart. **Fix:** delegate each repair kind's preview and apply through the owner (as `takes remove` does), keeping preview hashes and `--expect` consent identical to the local path. **Effort:** M. **Priority:** P3.
+ - [ ] **P3 — Typed `ShutdownInterruptedError` for cooperative handlers.** **What:** during worker shutdown only `UnrecoverableError` now burns an attempt (Decision 7); every other error from an in-process handler is still treated as a shutdown interruption, because cooperative handlers throw plain `Error`s (`subagent.ts`, `shell.ts`). **Fix:** have every cooperating handler throw a typed `ShutdownInterruptedError` on the shutdown abort, then take the requeue path only for that type so ordinary failures during a deploy burn an attempt. **Effort:** M. **Priority:** P3.
+ - [ ] **P2 — Judge-panel refresh to current frontier models.** **What:** the takes-quality panel (`openai:gpt-5.2`, `anthropic:claude-opus-4-7`, `google:gemini-2.5-flash`) and the cross-modal slots (`openai:gpt-5.2`, `anthropic:claude-opus-4-7`, `deepseek:deepseek-v4-pro`) predate the project's newest-model-per-family eval rule. **Fix:** an eval-owned, preregistered panel change in gbrain-evals first (keep at most one older model as the link to previous results), then update the defaults, their recipe listings and the default-panel tests together. **Effort:** M. **Priority:** P2.
+ - [ ] **P3 — gpt-6 judges cannot lower reasoning effort.** **What:** the pinned `@ai-sdk/openai` (3.0.58) does not recognise gpt-6 ids as reasoning models and drops `reasoningEffort` with a warning, so `thinking: 'off'` on gpt-6-sol/-luna cannot send `none` and on gpt-6-astra/6.1-sol cannot send the `low` floor; `thinking-off.ts` gives those routes headroom only. **Fix:** bump `@ai-sdk/openai` to a release that knows gpt-6 (or set `forceReasoning`), verify the request live, and add the gpt-6 rows to the capability table. **Effort:** S. **Priority:** P3.
## Fix wave 10 lane H follow-ups (filed 2026-10-06, GBRA-51)
@@@ -54,18 -29,16 +65,6 @@@ Context: `docs/guides/core-memory.md`,
- [ ] **P3 — Per-turn context drops core slugs.** **What:** the per-turn context (hook `turn_context`, OpenClaw reflex) still volunteers core pages that are already in the session. **Fix:** pass the core slugs as already-delivered. **Effort:** S.
- [ ] **P3 — Pressure notice record-after-write.** **What:** the once-per-segment state is written before the hook's stdout lands; a deadline-expired turn loses that segment's notice. **Fix:** commit the state after the write, like the session-start deferred records. **Effort:** S.
--## Fix wave 9 follow-ups (filed 2026-10-05, follow-up from v0.60.74.0)
--
--- [ ] **P2 — Receipted publication for managed conversation facts.** **What:** `extract-conversation-facts` replaces a page's derived fact batch through `replaceDerivedFactsForPage` (`src/core/persistence/derived-facts.ts`), a coordinated transaction with no persistence request. On a managed brain a multi-message email thread is therefore skipped without writing and retried every run (`src/core/facts/conversation-skip.ts`), as are the single-email and prose outcomes; `test/helpers/managed-connector-job-contract.ts` case `extract_conversation_facts_thread` pins it. **Fix:** admit a persistence request for the derived batch (delete-by-prefix plus insert, page revision as the CAS) in the same transaction, so the write carries a receipt; then drop the managed gate and record the single-email/prose outcomes durably there too. **Effort:** M. **Priority:** P2.
--- [ ] **P2 — Re-extract conversation facts misattributed to meeting-note labels.** **What:** before v0.60.74.0 the conversation parser read `**Date:**`, `**Attendees:**` and similar labels as speakers, so conversation facts were written with entity "Date" and an epoch date. The parser fix stops new ones; existing rows stay. **Fix:** a `gbrain` command that finds conversation facts whose provenance is a metadata-label speaker, previews them by default, and on `--apply` re-extracts the source pages under an explicit cost cap (never an automatic spend). **Effort:** M. **Priority:** P2.
--- [ ] **P2 — Concept publication can overwrite a narrative edited in the file mid-cycle.** **What:** `src/core/cycle/concept-publication.ts` rechecks the database row against the synthesis baseline but not the markdown file it then rewrites; a file edit made after the cycle's sync and before the concept publishes is lost. **Fix:** when the file exists, also require its fence-stripped body to equal the baseline and defer with `revision_conflict` otherwise, with a test that proves no perpetual deferral on formatting-only differences. **Effort:** S. **Priority:** P2.
--- [ ] **P2 — `takes remove` can free a row number for reuse.** **What:** row allocation is max(fence)+1 (`src/core/takes-fence.ts`), so removing the highest row lets the next `takes add` reuse its number; `take_proposals.promoted_row_num` and agents caching row numbers then point at a different claim. **Fix:** keep a per-page high-water mark (or a struck tombstone row) so numbers are never reused, or clear `promoted_row_num` for proposals that pointed at the removed row. **Effort:** S. **Priority:** P2.
- - [ ] **P3 — Judge cost estimates ignore thinking headroom.** **What:** with `thinking: 'off'`, a thinking-by-default route without a per-call switch (GLM, claude-cli Claude 5) gets a 32,000-token output cap, but the takes-quality projection and cross-modal `--max-usd` preflight still price 2,000/4,000 output tokens. Google judges (`gemini-2.5-flash` on the default takes-quality panel) get no thinking switch at all. **Fix:** size both estimates with `thinkingOffMaxOutputTokens`, and map Google to `thinkingConfig.thinkingBudget: 0` after a live check. **Effort:** S. **Priority:** P3.
--- [ ] **P3 — In-process job errors during shutdown are always treated as shutdown interruptions.** **What:** `src/core/minions/worker.ts` re-queues any in-process job that throws while shutdown is in progress (no attempt burned, `error_text` overwritten), including an `UnrecoverableError` from a handler that ignores `shutdownSignal`. **Fix:** take the shutdown path only when the error is the shutdown abort's reason (or the shell handler's shutdown kill). **Effort:** S. **Priority:** P3.
--- [ ] **P3 — `jobs supervisor stop` liveness check can hit a recycled worker PID.** **What:** it checks every `worker_spawned` pid of the supervisor in this week's audit file, including workers that already exited; a recycled pid makes a clean drain exit 1 with `worker_still_running`. **Fix:** check only spawns without a later `worker_exited`, or record the last worker pid on the `stopped` event. **Effort:** S. **Priority:** P3.
--- [ ] **P3 — `gbrain takes rebuild` while `gbrain serve` owns a PGLite brain.** **What:** `takes remove` delegates through the owner, but `takes rebuild` (the recovery its refusal names) opens the engine and waits on the serve's lock. **Fix:** an IPC-delegated rebuild op, or route the refusal's hint through the owner. **Effort:** M. **Priority:** P3.
- - [ ] **P3 — Stall detection for subagent turns.** **What:** `ai.chat.per_turn_timeout_ms` bounds a whole turn (default 30 min) because gateway chat calls are not streamed, so a hung provider holds the turn for the full budget. **Fix:** once chat streams, abort a turn that produces no tokens for a shorter stall window. **Effort:** M. **Priority:** P3.
--
## Dependency hygiene (filed 2026-10-06, GBRA-40)
diff --cc scripts/module-size-limits.tsv
index f9faaafbd3,ae2bcbf3dc..6a4ca9429b
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@@ -8,13 -8,13 +8,13 @@@ src/commands/autopilot.ts 1642 ratchet
src/commands/doctor.ts 667 ratchet +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts
src/commands/embed.ts 2227 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts)
src/commands/extract-conversation-facts.ts 2213 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch); +2 fix wave 10 (#6037, issue #6033): explicit-slug page failures are contained per page through one bounded failure logger (recordPageFailure) shared with the pooled path; +4 fix wave 10 (#5120): facts.default_visibility resolved once per run (resolveDefaultVisibility) and applied to extracted rows only; 2 P2 segmentObservationDate + segmentValidFrom helpers (date-grounding observation time per segment; extractor event date wins over segment start)
-src/commands/extract.ts 2567 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan
+src/commands/extract.ts 2580 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 12 W2.1 S4 (#6228): extract --stale flushes and stamps the pages a batch finished before an aborting page
src/commands/jobs.ts 666 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codes
src/commands/serve-http.ts 926 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts)
- src/core/ai/gateway.ts 4425 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts)
+ src/core/ai/gateway.ts 4427 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts)
src/commands/sync.ts 512 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field
-src/core/cycle.ts 3254 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts)
-src/core/cycle/synthesize.ts 3207 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg)
+src/core/cycle.ts 3283 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts)
+src/core/cycle/synthesize.ts 3227 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import)
src/core/cycle/extract-atoms.ts 1650 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt
src/core/engine.ts 2721 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract
src/core/import-file.ts 2200 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts)
diff --cc src/core/fence-repair/llm.ts
index a4b0f3f886,0000000000..7ec86120ac
mode 100644,000000..100644
--- a/src/core/fence-repair/llm.ts
+++ b/src/core/fence-repair/llm.ts
@@@ -1,295 -1,0 +1,295 @@@
+/**
+ * Tier 3 fence repair (#6188): the configured chat model realigns the rows a
+ * fence's residual issues name, and nothing else.
+ *
+ * What the model sees: the fence kind and section, the page's visibility,
+ * the canonical header, the schema vocabulary, the residual reason codes
+ * with row numbers, and the header line plus the residual rows exactly as
+ * written. For a fence-level issue (`no_header`, `header_unmapped`, or an
+ * issue that names no row) that is every row of that fence; otherwise only
+ * the named rows. Never the valid rows of a row-level issue, never the rest
+ * of the page, never tools.
+ *
+ * What it must return: one markdown table (the canonical header, the
+ * separator, one row per input row in order) and nothing else. A single
+ * wrapping code fence is tolerated; any other text outside the table is
+ * `llm_malformed`. Failure classes: `llm_unavailable` (the provider threw:
+ * timeout, rate limit, server error; transient, the attempt memo is not
+ * consumed), `llm_empty`, `llm_refused` (refusal or content-filter stop, or a
+ * prose refusal), `llm_malformed` (no single table, wrong header, prose),
+ * `llm_truncated` (any stop other than a normal end, rejected even if the
+ * text parses), `llm_declined` (the single word HOLD: a row has more than one
+ * reasonable reading, so the model declines instead of guessing). A table
+ * with the wrong number of rows is a gate (e) failure.
+ *
+ * The corrective re-ask (only after a structural failure, gate (a) or (e))
+ * repeats the conversation with the model's own answer and names the failed
+ * gate letter and row numbers only.
+ *
+ * The output ceiling is the table's size plus, for a model whose reasoning a
+ * call cannot switch off, a reasoning allowance; the cost estimate uses the
+ * ceiling the gateway will actually send, so the caps reserve the worst case.
+ *
+ * Pure helpers (`tier3Requests`, `buildTier3Prompt`, `extractSingleTable`,
+ * `spliceTier3`) do no I/O; `callTier3` is the one gateway call, testable
+ * through the gateway's chat transport seam (`__setChatTransportForTests`).
+ */
+import { chat, isThinkingModel, THINKING_MODEL_MAX_OUTPUT_TOKENS, type ChatMessage, type ChatResult } from '../ai/gateway.ts';
- import { thinkingOffMaxOutputTokens, thinkingOffNamespace } from '../ai/thinking-off.ts';
++import { thinkingOffControl, thinkingOffMaxOutputTokens } from '../ai/thinking-off.ts';
+import { isSeparatorRow, parseRowCells } from '../fence-shared.ts';
+import { sectionsOf } from './page-checks.ts';
+import { extractRawRows, primaryFence, type RawFence, type RawRow } from './raw-rows.ts';
+import { ALLOWED, BASE_WIDTH, CANONICAL_HEADER, COLUMNS, COLUMN_DEFAULTS } from './schema.ts';
+import { FENCE_REASON_CODES, FENCE_REASONS, GATE_REASONS } from './reasons.ts';
+import type { FenceIssue, FenceKind, FencePage, FenceReason, FenceSection, GateLetter } from './types.ts';
+
+/** Bump when the prompt text changes: it is part of the attempt-memo key, so a new prompt retries rejected pages. */
+export const FENCE_REPAIR_PROMPT_VERSION = 2;
+
+/** Residual reasons a model may clear: the screen reasons whose tier is `llm` (everything else is manual or the resolver's). */
+export const TIER3_REASONS: ReadonlySet<FenceReason> = new Set(FENCE_REASON_CODES.filter(reason => FENCE_REASONS[reason].stage === 'screen' && FENCE_REASONS[reason].tier === 'llm'));
+const FENCE_LEVEL: ReadonlySet<FenceReason> = new Set(['header_unmapped', 'no_header']);
+
+export type Tier3Failure = 'llm_unavailable' | 'llm_empty' | 'llm_refused' | 'llm_malformed' | 'llm_truncated' | 'llm_declined';
+
+/** The whole answer a model gives to decline (prompt rule 8). */
+export const TIER3_DECLINE = 'HOLD';
+/** Output tokens a reasoning model may spend thinking before it writes the table. */
+export const TIER3_REASONING_TOKENS = 2048;
+
+/** One fence the model is asked to repair. */
+export interface Tier3Request {
+ kind: FenceKind;
+ section: FenceSection;
+ pageVisibility: 'private' | 'world';
+ layout: 'narrow' | 'wide';
+ /** The header line as written, or null when the fence has none. */
+ header: string | null;
+ /** The rows sent, as written, in fence order, with their data-row ordinal. */
+ rows: Array<{ occurrence: number; text: string }>;
+ /** Residual reasons with the row numbers they name (location only). */
+ issues: Array<{ reason: FenceReason; rows: number[] }>;
+}
+
+/** Why a fence cannot go to the model (it stays held with its own reason). */
+export type Tier3Ineligible = { kind: FenceKind; section: FenceSection; why: 'no_fence' | 'stray_lines' | 'no_end_marker' };
+
+/**
+ * The model requests for a page's residual issues, one per fence, or why a
+ * fence is not eligible. Callers send only issues whose reason is in
+ * TIER3_REASONS.
+ */
+export function tier3Requests(page: FencePage, issues: readonly FenceIssue[], pageVisibility: 'private' | 'world'): { requests: Tier3Request[]; ineligible: Tier3Ineligible[] } {
+ const requests: Tier3Request[] = [];
+ const ineligible: Tier3Ineligible[] = [];
+ const texts = new Map(sectionsOf(page));
+ const groups = new Map<string, FenceIssue[]>();
+ for (const issue of issues) {
+ const key = `${issue.section}\u0000${issue.fence}`;
+ groups.set(key, [...(groups.get(key) ?? []), issue]);
+ }
+ for (const group of groups.values()) {
+ const { section, fence: kind } = group[0]!;
+ const text = texts.get(section) ?? '';
+ const fence = primaryFence(extractRawRows(text, section), kind);
+ if (!fence) { ineligible.push({ kind, section, why: 'no_fence' }); continue; }
+ if (!fence.end) { ineligible.push({ kind, section, why: 'no_end_marker' }); continue; }
+ if (strayLines(text, fence)) { ineligible.push({ kind, section, why: 'stray_lines' }); continue; }
+ const named = new Set(group.flatMap(issue => fence.rows.filter(row => row.line === issue.line).map(row => row.occurrence)));
+ const fenceLevel = group.some(issue => FENCE_LEVEL.has(issue.reason) || issue.line === null || !fence.rows.some(row => row.line === issue.line));
+ const sent = fence.rows.filter(row => fenceLevel || named.has(row.occurrence));
+ const byReason = new Map<FenceReason, Set<number>>();
+ for (const issue of group) {
+ const rows = byReason.get(issue.reason) ?? new Set<number>();
+ if (issue.row !== null) rows.add(issue.row);
+ byReason.set(issue.reason, rows);
+ }
+ requests.push({ kind, section, pageVisibility, layout: wideLayout(kind, fence) ? 'wide' : 'narrow',
+ header: fence.header ? text.slice(fence.header.start, fence.header.end) : null,
+ rows: sent.map(row => ({ occurrence: row.occurrence, text: text.slice(row.start, row.end) })),
+ issues: [...byReason].map(([reason, rows]) => ({ reason, rows: [...rows].sort((a, b) => a - b) })) });
+ }
+ return { requests, ineligible };
+}
+
+/** Wide when the header names a wide-layout column, or (no header) when a row as written has more cells than the narrow width. */
+function wideLayout(kind: FenceKind, fence: RawFence): boolean {
+ const base = BASE_WIDTH[kind];
+ if (fence.header) return fence.columns.some(column => column !== null && COLUMNS[kind].indexOf(column) >= base);
+ return fence.rows.some(row => row.cells.length > base);
+}
+
+/** Non-blank lines inside the fence that are neither the header, a separator nor a data row: rebuilding the table would drop them. */
+function strayLines(text: string, fence: RawFence): boolean {
+ const region = text.slice(fence.begin.end, fence.end!.start);
+ const tableLines = (fence.header ? 1 : 0) + fence.separators.length + fence.rows.length;
+ return region.split('\n').filter(line => line.trim()).length !== tableLines;
+}
+
+function headerOf(req: Pick<Tier3Request, 'kind' | 'layout'>): { header: string; separator: string } {
+ const h = CANONICAL_HEADER[req.kind];
+ return req.layout === 'wide' ? { header: h.wide, separator: h.wideSep } : { header: h.narrow, separator: h.narrowSep };
+}
+
+function vocabulary(kind: FenceKind): string {
+ return Object.entries(ALLOWED[kind]).filter(([column]) => column !== '#').map(([column, values]) => `- ${column}: ${values.join(', ')}`).join('\n');
+}
+
+const GATE_TEXT: Record<GateLetter, string> = {
+ a: 'it still does not parse as a valid fence table',
+ b: 'a claim cell changed',
+ c: 'an existing row number changed',
+ d: 'a row became more visible than the input allows',
+ e: 'rows were added, dropped, merged, split or reordered',
+ f: "a cell's text changed, or a valid cell moved out of its column",
+ g: 'it would expose text that sat outside the table',
+};
+
+/** The system and first user message. Location and the rows as written; no other page text. */
+export function buildTier3Prompt(req: Tier3Request): { system: string; user: string } {
+ const { header, separator } = headerOf(req);
+ const defaults = Object.entries(COLUMN_DEFAULTS[req.kind]);
+ const system = [
+ `You repair one malformed markdown table from a gbrain ${req.kind} fence. You move cells into the right columns and supply the canonical header; you never change what a cell says.`,
+ '',
+ `Return exactly one markdown table and nothing else (or the single word ${TIER3_DECLINE}, rule 8): no prose, no explanation, no code fence.`,
+ 'The table starts with this header and separator, unchanged:',
+ header,
+ separator,
+ 'Then one row per input row, in the same order. Do not add, drop, merge, split or reorder rows.',
+ '',
+ 'Rules:',
+ '1. Copy every cell exactly as written: same words, spelling, case, punctuation, links, numbers, dates and ~~strikethrough~~. Only its column may change.',
+ '2. The claim cell of each output row is the claim of the matching input row, unchanged.',
+ '3. Keep each row number in the # column. If an input row has none, leave # empty.',
+ `4. Put each cell in the column its content belongs to. A column with no matching input cell stays empty${defaults.length
+ ? `, except a column the input header lacks entirely, which takes its default: ${defaults.map(([column, value]) => `${column} ${value}`).join(', ')}` : ''}.`,
+ '5. Never invent, translate, summarize or correct a value. A cell you cannot place goes in the column it was written under.',
+ `6. This page is ${req.pageVisibility}-visible. A row's visibility may be world only when that row already says world or public and the page is world-visible; otherwise keep what the row says or leave it empty.`,
+ '7. Write a literal | inside a cell as \\|.',
+ `8. If any row has more than one reasonable reading (two values for one column, or a cell that fits more than one column), return only the single word ${TIER3_DECLINE} instead of a table.`,
+ '',
+ 'Allowed values per column:',
+ vocabulary(req.kind),
+ ].join('\n');
+ const user = [
+ `Fence: ${req.kind} (${req.section} section). Page visibility: ${req.pageVisibility}.`,
+ 'Problems found (reason codes, with row numbers where known):',
+ ...req.issues.map(issue => `- ${issue.reason}${issue.rows.length ? `: row(s) ${issue.rows.join(', ')}` : ''}`),
+ '',
+ 'Header as written:',
+ req.header ?? '(none)',
+ '',
+ `Rows as written (${req.rows.length}):`,
+ ...req.rows.map(row => row.text),
+ ].join('\n');
+ return { system, user };
+}
+
+/** The follow-up after a structural gate rejection: the gate letter, its reason code and row numbers only. */
+export function correctionMessage(gate: GateLetter, rows: readonly number[]): string {
+ return `Your table was rejected by validation gate (${gate}) ${GATE_REASONS[gate]}${rows.length ? ` at row(s) ${rows.join(', ')}` : ''}: ${GATE_TEXT[gate]}. `
+ + `Return the corrected full table following every rule above, or ${TIER3_DECLINE} if a row has more than one reasonable reading. Output only the table or ${TIER3_DECLINE}.`;
+}
+
- /** The model may reason whatever the call asks: a thinking-by-default model, or a route with no per-call thinking switch. */
++/** The model may reason whatever the call asks: a thinking-by-default model, or a route whose thinking-off option does not turn reasoning fully off. */
+function mayReason(model: string): boolean {
- return isThinkingModel(model) || !thinkingOffNamespace(model);
++ return isThinkingModel(model) || !thinkingOffControl(model)?.disables;
+}
+
+/**
+ * Token bounds for one call: the prompt's size, and the output ceiling the
+ * gateway will send: the table's size (from the rows sent), plus
+ * TIER3_REASONING_TOKENS for a model that may reason, raised to the
+ * gateway's thinking headroom where a thinking model's route cannot switch
+ * thinking off. Estimates and the caps use this ceiling, so they reserve the
+ * worst case.
+ */
+export function tier3TokenBudget(req: Tier3Request, model: string, prior?: { answer: string }): { inputTokens: number; maxOutputTokens: number } {
+ const prompt = buildTier3Prompt(req);
+ const rowChars = req.rows.reduce((sum, row) => sum + row.text.length, 0) + headerOf(req).header.length * 2;
+ const inputChars = prompt.system.length + prompt.user.length + (prior ? prior.answer.length + 400 : 0);
+ const table = Math.min(4096, Math.max(512, Math.ceil(rowChars * 1.5 / 3) + 256));
+ const requested = table + (mayReason(model) ? TIER3_REASONING_TOKENS : 0);
+ return { inputTokens: Math.ceil(inputChars / 3) + 64, maxOutputTokens: thinkingOffMaxOutputTokens(model, requested, isThinkingModel(model), THINKING_MODEL_MAX_OUTPUT_TOKENS) };
+}
+
+export interface Tier3Table { header: string; separator: string; rows: string[] }
+
+const REFUSAL = /\b(cannot|can['’]t|unable to|won['’]t|will not|refuse|not able to)\b/i;
+
+/**
+ * The single table in a model answer, or why there is none. A single
+ * wrapping code fence is stripped; any other non-table line is prose.
+ */
+export function extractSingleTable(text: string, req: Pick<Tier3Request, 'kind' | 'layout'>): { ok: true; table: Tier3Table } | { ok: false; reason: 'llm_empty' | 'llm_refused' | 'llm_malformed' | 'llm_declined' } {
+ let body = text.trim();
+ if (!body) return { ok: false, reason: 'llm_empty' };
+ const fenced = /^```[\w-]*\n([\s\S]*?)\n```$/.exec(body);
+ if (fenced) body = fenced[1]!.trim();
+ if (body.replace(/[.*_`]/g, '').trim() === TIER3_DECLINE) return { ok: false, reason: 'llm_declined' };
+ const lines = body.split('\n').map(line => line.trim()).filter(Boolean);
+ if (!lines.some(line => line.startsWith('|'))) return { ok: false, reason: REFUSAL.test(body) ? 'llm_refused' : 'llm_malformed' };
+ if (lines.some(line => !line.startsWith('|')) || lines.length < 2) return { ok: false, reason: 'llm_malformed' };
+ const headerCells = parseRowCells(lines[0]!)?.map(cell => cell.trim().toLowerCase()).join('|');
+ const sepCells = parseRowCells(lines[1]!);
+ const layout = (['narrow', 'wide'] as const).find(width => headerCells === COLUMNS[req.kind].slice(0, width === 'wide' ? COLUMNS[req.kind].length : BASE_WIDTH[req.kind]).join('|'));
+ if (!layout || !sepCells || !isSeparatorRow(sepCells)) return { ok: false, reason: 'llm_malformed' };
+ const rows = lines.slice(2);
+ if (rows.some(row => parseRowCells(row) === null || isSeparatorRow(parseRowCells(row)!))) return { ok: false, reason: 'llm_malformed' };
+ const { header, separator } = headerOf({ kind: req.kind, layout });
+ return { ok: true, table: { header, separator, rows } };
+}
+
+/**
+ * The page with one request's fence rebuilt from the model's table: the
+ * canonical header and separator, then every data row in fence order, the
+ * sent rows replaced by the answer's rows in order. Everything outside the
+ * fence region is unchanged. Null when the answer's row count differs.
+ */
+export function spliceTier3<T extends FencePage>(page: T, req: Tier3Request, table: Tier3Table): T | null {
+ if (table.rows.length !== req.rows.length) return null;
+ const field = req.section === 'body' ? 'compiled_truth' : 'timeline';
+ const text = (page[field] ?? '') as string;
+ const fence = primaryFence(extractRawRows(text, req.section), req.kind);
+ if (!fence?.end) return null;
+ const answers = new Map(req.rows.map((row, i) => [row.occurrence, table.rows[i]!]));
+ const lines = [table.header, table.separator, ...fence.rows.map((row: RawRow) => answers.get(row.occurrence) ?? text.slice(row.start, row.end))];
+ const rebuilt = `${text.slice(0, fence.begin.end)}\n${lines.join('\n')}\n${text.slice(fence.end.start)}`;
+ return { ...page, [field]: rebuilt };
+}
+
+export type Tier3Answer =
+ | { ok: true; table: Tier3Table; text: string; result: ChatResult }
+ | { ok: false; reason: Tier3Failure; text?: string; result?: ChatResult; error?: string }
+ /** The answer parsed but has the wrong number of rows: a gate (e) failure, eligible for the corrective re-ask. */
+ | { ok: false; reason: 'row_count_changed'; text: string; result: ChatResult; table: Tier3Table };
+
+export interface Tier3CallOptions {
+ model: string;
+ /** The first attempt's answer and the gate it failed, for the corrective re-ask. */
+ correction?: { answer: string; gate: GateLetter; rows: readonly number[] };
+ timeoutMs?: number;
+ signal?: AbortSignal;
+}
+
+/** One gateway call (no tools, no fallback model, thinking off where the route allows; no temperature, which reasoning models refuse), classified. */
+export async function callTier3(req: Tier3Request, opts: Tier3CallOptions): Promise<Tier3Answer> {
+ const prompt = buildTier3Prompt(req);
+ const messages: ChatMessage[] = [{ role: 'user', content: prompt.user }];
+ if (opts.correction) messages.push({ role: 'assistant', content: opts.correction.answer }, { role: 'user', content: correctionMessage(opts.correction.gate, opts.correction.rows) });
+ const budget = tier3TokenBudget(req, opts.model, opts.correction ? { answer: opts.correction.answer } : undefined);
+ let result: ChatResult;
+ try {
+ result = await chat({ model: opts.model, system: prompt.system, messages, maxTokens: budget.maxOutputTokens, allowFallback: false,
+ thinking: 'off', purpose: 'fence_repair', ...(opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}), ...(opts.signal ? { abortSignal: opts.signal } : {}) });
+ } catch (error) {
+ return { ok: false, reason: 'llm_unavailable', error: error instanceof Error ? error.name : 'Error' };
+ }
+ if (result.stopReason === 'refusal' || result.stopReason === 'content_filter') return { ok: false, reason: 'llm_refused', text: result.text, result };
+ if (result.stopReason !== 'end') return { ok: false, reason: result.text.trim() ? 'llm_truncated' : 'llm_empty', text: result.text, result };
+ const extracted = extractSingleTable(result.text, req);
+ if (!extracted.ok) return { ok: false, reason: extracted.reason, text: result.text, result };
+ if (extracted.table.rows.length !== req.rows.length) return { ok: false, reason: 'row_count_changed', text: result.text, result, table: extracted.table };
+ return { ok: true, table: extracted.table, text: result.text, result };
+}
diff --cc test/fence-repair-llm.test.ts
index 91e99777cc,0000000000..3d8eb7247d
mode 100644,000000..100644
--- a/test/fence-repair-llm.test.ts
+++ b/test/fence-repair-llm.test.ts
@@@ -1,252 -1,0 +1,257 @@@
+/**
+ * #6188 PR4: Tier 3 fence repair, the model call (src/core/fence-repair/llm.ts).
+ *
+ * Protects: the model sees only the fence header and the residual rows a
+ * row-level issue names (never the valid rows, never the rest of the page),
+ * no tools and no fallback model; every failure class is distinct
+ * (llm_unavailable, llm_empty, llm_refused, llm_malformed, llm_truncated) and
+ * a truncated answer is rejected even when it parses; a wrong row count is a
+ * gate (e) failure; the corrective re-ask carries the model's own answer plus
+ * the gate letter and row numbers only, and runs only after a structural
+ * failure (gate (a) or (e)), never after gate (f); a HOLD answer is
+ * `llm_declined` and consumes the attempt memo; a headerless fence of typed
+ * rows gets the wide header; the output ceiling leaves a reasoning model room
+ * to think and the estimate reserves the ceiling the gateway sends; the splice
+ * rebuilds only the fence; the prompt bytes are pinned (a change must bump
+ * FENCE_REPAIR_PROMPT_VERSION).
+ * Fails when: valid rows or page prose leak into the prompt, a tool or a
+ * fallback chain reaches the call, a refusal or truncation is treated as an
+ * answer, the re-ask quotes anything beyond its own answer or follows a gate
+ * (f) rejection, a decline is retried or written, or the budget starves a
+ * reasoning model.
+ * Why new: the Tier 3 module is new in PR4.
+ * Seams: the gateway's chat transport seam (__setChatTransportForTests).
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
- import { __setChatTransportForTests, configureGateway, resetGateway, type ChatOpts, type ChatResult } from '../src/core/ai/gateway.ts';
++import { __setChatTransportForTests, configureGateway, resetGateway, thinkingOffOutputCap, type ChatOpts, type ChatResult } from '../src/core/ai/gateway.ts';
+import { dailyLedger, FENCE_REPAIR_LEDGER } from '../src/core/budget/daily-ledger.ts';
+import { attemptStore } from '../src/core/fence-repair/attempts.ts';
+import { buildTier3Prompt, callTier3, correctionMessage, extractSingleTable, FENCE_REPAIR_PROMPT_VERSION, spliceTier3, tier3Requests, tier3TokenBudget, TIER3_REASONING_TOKENS } from '../src/core/fence-repair/llm.ts';
+import { pageSha, type FenceTarget } from '../src/core/fence-repair/repair-io.ts';
+import { analyzeFences, runTier3, type FenceAnalysis } from '../src/core/fence-repair/repair-tiers.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { safeNormalizeFences } from '../src/core/fence-repair/normalize.ts';
+import { validateFenceRepair } from '../src/core/fence-repair/validate.ts';
+
+const FB = '<!--- gbrain:facts:begin -->', FBE = '<!--- gbrain:facts:end -->';
+const FH = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|';
+const NARROW = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |';
+const SEP = '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|';
+const VALID = 'Validrowclaimzq9 stays private';
+const PROSE = 'Pageproseqz9 is never sent';
+const BROKEN = 'Brokenrowclaimzq9 ships';
+/** One valid row and one row missing its trailing cells (short_row, row-level). */
+const rowLevel = `${PROSE}\n\n${FB}\n${FH}\n| 1 | ${VALID} | fact | 0.9 | private | high | 2026-01-01 | | chat | ctx |\n| 2 | ${BROKEN} | fact | 0.8 | private | low | 2026-02-01 |\n${FBE}\n`;
+/** A fence with rows but no header (no_header, fence-level). */
+const noHeader = `${PROSE}\n\n${FB}\n| 1 | ${BROKEN} | fact | 0.9 | private | high | 2026-01-01 | | chat | ctx |\n${FBE}\n`;
+
+const result = (text: string, stopReason: ChatResult['stopReason'] = 'end'): ChatResult => ({ text, blocks: [], stopReason,
+ usage: { input_tokens: 400, output_tokens: 80, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'anthropic:claude-opus-4-7', providerId: 'anthropic' });
+
+function stub(answers: Array<ChatResult | Error>) {
+ const calls: ChatOpts[] = [];
+ __setChatTransportForTests(async opts => {
+ calls.push(opts);
+ const next = answers.shift()!;
+ if (next instanceof Error) throw next;
+ return next;
+ });
+ return calls;
+}
+
+function residualOf(text: string) {
+ const page = { compiled_truth: text, timeline: '' };
+ const normalized = safeNormalizeFences(page, { pageVisibility: 'private' });
+ return { page, normalized, ...tier3Requests(normalized.page, normalized.residual, 'private') };
+}
+
+afterEach(() => __setChatTransportForTests(null));
+afterAll(() => resetGateway());
+
+describe('Tier 3 requests and prompt', () => {
+ test('a row-level issue sends the header and that row only; a fence-level issue sends every row; page prose never', () => {
+ const row = residualOf(rowLevel);
+ expect(row.normalized.residual.map(i => i.reason)).toEqual(['short_row']);
+ expect(row.requests).toHaveLength(1);
+ const req = row.requests[0]!;
+ expect(req.rows.map(r => r.occurrence)).toEqual([1]);
+ const prompt = buildTier3Prompt(req);
+ const all = `${prompt.system}\n${prompt.user}`;
+ expect(all).toContain(BROKEN);
+ expect(all).not.toContain(VALID);
+ expect(all).not.toContain(PROSE);
+ expect(prompt.user).toContain('short_row: row(s) 2');
+ const fence = residualOf(noHeader);
+ expect(fence.requests[0]!.header).toBeNull();
+ expect(fence.requests[0]!.rows).toHaveLength(1);
+ expect(buildTier3Prompt(fence.requests[0]!).user).not.toContain(PROSE);
+ });
+
+ test('prompt bytes are pinned; a prompt change must bump FENCE_REPAIR_PROMPT_VERSION', () => {
+ const prompt = buildTier3Prompt(residualOf(noHeader).requests[0]!);
+ const digest = createHash('sha256').update(`${prompt.system}\u0000${prompt.user}`).digest('hex');
+ expect({ version: FENCE_REPAIR_PROMPT_VERSION, digest }).toEqual({ version: 2, digest: PROMPT_DIGEST });
+ expect(prompt.system).toContain('return only the single word HOLD instead of a table');
+ });
+
+ test('a headerless fence of typed 14-cell rows is sent with the wide header', () => {
+ const typed = `${FB}\n| 1 | Typedrowzq9 revenue | fact | 0.9 | private | high | 2026-05-01 | | deck | | revenue | 120k | USD | monthly |\n${FBE}\n`;
+ const req = residualOf(typed).requests[0]!;
+ expect(req.layout).toBe('wide');
+ expect(buildTier3Prompt(req).system).toContain('| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context | claim_metric | claim_value | claim_unit | claim_period |');
+ expect(residualOf(noHeader).requests[0]!.layout).toBe('narrow');
+ });
+
+ test('the output ceiling adds room to reason only where the call cannot turn reasoning off, and reserves what the gateway sends', () => {
+ const req = residualOf(rowLevel).requests[0]!;
+ const table = tier3TokenBudget(req, 'anthropic:claude-opus-4-7').maxOutputTokens;
+ expect(tier3TokenBudget(req, 'anthropic:claude-fable-5-1').maxOutputTokens).toBe(table + TIER3_REASONING_TOKENS);
- expect(tier3TokenBudget(req, 'openai:gpt-6.1-sol').maxOutputTokens).toBe(table + TIER3_REASONING_TOKENS);
++ expect(tier3TokenBudget(req, 'openai:gpt-6.1-sol').maxOutputTokens).toBe(32000);
++ expect(tier3TokenBudget(req, 'google:gemini-2.5-flash').maxOutputTokens).toBe(table);
++ expect(tier3TokenBudget(req, 'google:gemini-3.8-flash').maxOutputTokens).toBe(32000);
++ for (const model of ['anthropic:claude-fable-5-1', 'openai:gpt-6.1-sol', 'google:gemini-2.5-flash', 'google:gemini-3.8-flash']) {
++ expect(tier3TokenBudget(req, model).maxOutputTokens).toBe(thinkingOffOutputCap(model, tier3TokenBudget(req, model).maxOutputTokens));
++ }
+ expect(tier3TokenBudget(req, 'claude-cli:claude-fable-5-1').maxOutputTokens).toBe(32000);
+ });
+
+ test('a fence with a stray text line inside is not eligible (rebuilding the table would drop it)', () => {
+ const stray = `${FB}\n| 1 | ${BROKEN} | fact | 0.9 | private | high | 2026-01-01 | | chat | ctx |\na stray note\n${FBE}\n`;
+ const out = residualOf(stray);
+ expect(out.requests).toEqual([]);
+ expect(out.ineligible.map(i => i.why)).toEqual(['stray_lines']);
+ });
+});
+
+describe('extracting the answer', () => {
+ const req = { kind: 'facts' as const, layout: 'narrow' as const };
+ test('a single table (optionally in one code fence) is accepted; prose, a wrong header or nothing is not', () => {
+ expect(extractSingleTable(`${NARROW}\n${SEP}\n| 1 | x | fact | 1 | private | high | | | | |`, req)).toMatchObject({ ok: true });
+ expect(extractSingleTable('```markdown\n' + `${NARROW}\n${SEP}\n| 1 | x | fact | 1 | private | high | | | | |` + '\n```', req)).toMatchObject({ ok: true });
+ expect(extractSingleTable(`Here is the table:\n${NARROW}\n${SEP}\n| 1 | x |`, req)).toEqual({ ok: false, reason: 'llm_malformed' });
+ expect(extractSingleTable('| # | claim | type |\n|---|---|---|\n| 1 | x | fact |', req)).toEqual({ ok: false, reason: 'llm_malformed' });
+ expect(extractSingleTable(' ', req)).toEqual({ ok: false, reason: 'llm_empty' });
+ expect(extractSingleTable("I can't help rewrite that table.", req)).toEqual({ ok: false, reason: 'llm_refused' });
+ });
+
+ test('the single word HOLD (plain, bold or in a code fence) is a decline', () => {
+ for (const text of ['HOLD', ' **HOLD** ', '```\nHOLD\n```', 'HOLD.']) expect(extractSingleTable(text, req)).toEqual({ ok: false, reason: 'llm_declined' });
+ expect(extractSingleTable('HOLD: row 2 has two kinds', req)).toEqual({ ok: false, reason: 'llm_malformed' });
+ });
+});
+
+describe('the gateway call', () => {
+ const realigned = `${NARROW}\n${SEP}\n| 2 | ${BROKEN} | fact | 0.8 | private | low | 2026-02-01 | | | |`;
+
+ test('no tools, no fallback, the configured model; a realigned answer splices into a page that passes every gate', async () => {
+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', chat_fallback_chain: ['openai:gpt-6-luna'] } as never);
+ const calls = stub([result(realigned)]);
+ const { page, normalized, requests } = residualOf(rowLevel);
+ const answer = await callTier3(requests[0]!, { model: 'anthropic:claude-fable-5' });
+ expect(answer.ok).toBe(true);
+ expect(calls).toHaveLength(1);
+ expect(calls[0]!.tools).toBeUndefined();
+ expect(calls[0]!.allowFallback).toBe(false);
+ expect(calls[0]!.model).toBe('anthropic:claude-fable-5');
+ expect(calls[0]!.thinking).toBe('off');
+ expect(calls[0]!.maxTokens).toBe(tier3TokenBudget(requests[0]!, 'anthropic:claude-fable-5').maxOutputTokens);
+ const spliced = spliceTier3(normalized.page, requests[0]!, (answer as Extract<typeof answer, { ok: true }>).table)!;
+ expect(spliced.compiled_truth.startsWith(`${PROSE}\n\n${FB}\n${NARROW}\n${SEP}\n| 1 | ${VALID} |`)).toBe(true);
+ const final = safeNormalizeFences(spliced, { pageVisibility: 'private' });
+ expect(final.residual).toEqual([]);
+ expect(validateFenceRepair(page, final.page, { pageVisibility: 'private', tier: 'llm', issues: [...normalized.fixes, ...normalized.residual] })).toEqual({ ok: true });
+ });
+
+ test('each failure class is distinct; a truncated answer that parses is still rejected; a wrong row count is a gate (e) failure', async () => {
+ const req = residualOf(rowLevel).requests[0]!;
+ const cases: Array<[ChatResult | Error, string]> = [
+ [Object.assign(new Error('rate limited'), { status: 429 }), 'llm_unavailable'],
+ [result(''), 'llm_empty'],
+ [result('', 'refusal'), 'llm_refused'],
+ [result(realigned, 'content_filter'), 'llm_refused'],
+ [result('Sure! I fixed it.'), 'llm_malformed'],
+ [result(realigned, 'length'), 'llm_truncated'],
+ [result('HOLD'), 'llm_declined'],
+ [result(`${realigned}\n| 3 | Extra row | fact | 1 | private | high | | | | |`), 'row_count_changed'],
+ ];
+ for (const [answer, reason] of cases) expect(await reasonOf(req, answer)).toBe(reason);
+ });
+
+ test('the corrective re-ask repeats the model\'s own answer and names only the gate letter and rows', async () => {
+ const req = residualOf(rowLevel).requests[0]!;
+ const calls = stub([result(realigned)]);
+ await callTier3(req, { model: 'anthropic:claude-opus-4-7', correction: { answer: 'PRIOR-ANSWER', gate: 'f', rows: [2] } });
+ const messages = calls[0]!.messages;
+ expect(messages.map(m => m.role)).toEqual(['user', 'assistant', 'user']);
+ expect(messages[1]!.content).toBe('PRIOR-ANSWER');
+ expect(messages[2]!.content).toBe(correctionMessage('f', [2]));
+ expect(String(messages[2]!.content)).toBe("Your table was rejected by validation gate (f) cell_changed at row(s) 2: a cell's text changed, or a valid cell moved out of its column. Return the corrected full table following every rule above, or HOLD if a row has more than one reasonable reading. Output only the table or HOLD.");
+ });
+});
+
+describe('runTier3: the re-ask and the decline', () => {
+ let engine: PGLiteEngine;
+ let incarnation: string;
+ const model = 'anthropic:claude-opus-4-7';
+ const fixed = `${NARROW}\n${SEP}\n| 2 | ${BROKEN} | fact | 0.8 | private | low | 2026-02-01 | | | |`;
+ const cellChanged = `${NARROW}\n${SEP}\n| 2 | ${BROKEN} | fact | 0.8 | private | low | 2026-02-02 | | | |`;
+ const extraRow = `${fixed}\n| 3 | Inventedrowzq9 | fact | 1.0 | private | low | | | | |`;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ const [src] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");
+ incarnation = src!.incarnation;
+ });
+ afterAll(async () => { await engine.disconnect(); });
+
+ async function attempt(slug: string, answers: ChatResult[]) {
+ const page = { compiled_truth: rowLevel, timeline: '' };
+ const target: FenceTarget = { mode: 'db', sourceId: 'default', key: slug, slug, path: null, sourcePath: null, page, content: null, before: pageSha(page), snapshot: null, hold: null,
+ ctx: { pageVisibility: 'private' } } as FenceTarget;
+ const analysis = await analyzeFences(engine, target, { pageId: null });
+ expect(analysis.status).toBe('llm');
+ const calls = stub(answers);
+ const out = await runTier3(target, analysis as Extract<FenceAnalysis, { status: 'llm' }>, incarnation, { ledger: dailyLedger(engine, FENCE_REPAIR_LEDGER), store: attemptStore(engine),
+ model, capSource: 'default', perPageUsd: 1, perDayUsd: 10, timeoutMs: 30_000, now: () => new Date() });
+ return { out, calls };
+ }
+
+ test('a gate (f) rejection is final: no re-ask, so the gates cannot steer the model to an allowed but wrong placement', async () => {
+ const { out, calls } = await attempt('t3/cell', [result(cellChanged), result(fixed)]);
+ expect(calls).toHaveLength(1);
+ expect(out).toMatchObject({ ok: false, reason: 'cell_changed', gate: 'f' });
+ });
+
+ test('a structural failure (wrong row count, gate e) still earns one re-ask', async () => {
+ const { out, calls } = await attempt('t3/rows', [result(extraRow), result(fixed)]);
+ expect(calls).toHaveLength(2);
+ expect(out.ok).toBe(true);
+ });
+
+ test('a headerless row whose claim an unescaped pipe cut in two is held before any model call', async () => {
+ const page = { compiled_truth: `${FB}\n| 1 | Headerlesszq9 revenue grew | mostly from enterprise renewals, per the memo | fact | 0.9 | private | high | 2026-06-30 | | memo | |\n${FBE}\n`, timeline: '' };
+ const target = { mode: 'db', sourceId: 'default', key: 't3/split', slug: 't3/split', path: null, sourcePath: null, page, content: null, before: pageSha(page), snapshot: null, hold: null,
+ ctx: { pageVisibility: 'private' } } as FenceTarget;
+ expect(await analyzeFences(engine, target, { pageId: null })).toMatchObject({ status: 'manual', reason: 'claim_split' });
+ });
+
+ test('HOLD is held as llm_declined and consumes the memo: the same bytes are never sent again', async () => {
+ const first = await attempt('t3/hold', [result('HOLD')]);
+ expect(first.calls).toHaveLength(1);
+ expect(first.out).toMatchObject({ ok: false, reason: 'llm_declined' });
+ const again = await attempt('t3/hold', [result(fixed)]);
+ expect(again.calls).toHaveLength(0);
+ expect(again.out).toMatchObject({ ok: false, reason: 'llm_declined', memoHit: true, spentUsd: 0 });
+ });
+});
+
+async function reasonOf(req: Parameters<typeof callTier3>[0], answer: ChatResult | Error): Promise<string> {
+ stub([answer]);
+ const out = await callTier3(req, { model: 'anthropic:claude-opus-4-7' });
+ return out.ok ? 'ok' : out.reason;
+}
+
+const PROMPT_DIGEST = '71cf09e5a19efc76b1c8b2b02d20074fcc3cfed172f43ba654de124d202dba3e';