Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

chore(wave17-lane4): size ratchets, test isolation and manifest after the master merge

time-attack396ad2528918
diff --git a/docs/architecture/key-files/core-minions-1.md b/docs/architecture/key-files/core-minions-1.md
index 87df997df0..3b4b206e0f 100644
--- a/docs/architecture/key-files/core-minions-1.md
+++ b/docs/architecture/key-files/core-minions-1.md
@@ -24,7 +24,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/minions/delegated-policy.ts` — immutable submitted grant ceiling intersected with the current OAuth grant. Tools, explicit operation authority, source-only reads, write prefixes, concurrency and finite budget may narrow but never widen during execution; changed source/brain, revoked clients, archived sources or unusable intersections fail closed. Explicit job namespaces resolve to `wiki/agents/<job-id>/*`. Removing `submit_agent` stops the next execution boundary; explicit operation allowlists also constrain delegated tools, while legacy null operation lists preserve separately bound agent-only tools. Surface controls transport discovery. Empty tools never mean all tools. Legacy running jobs adopt the ceiling frozen in their persisted payload by grant rescope; host/current brain aliases mean the serving brain.
-- `src/core/minions/delegated-spend.ts` + `src/core/ai/invocation-guard.ts` + `guarded-generation.ts` — async-local admission (with `src/core/ai/invocation-guard.ts` available as `gbrain/ai/invocation-guard` for a companion capped evaluator) around each owned provider attempt, including nested paid tool work; unrelated local calls retain their transport behavior. Finite caps require a known price (operator `pricing.overrides` first, loaded once per guarded run, then the shipped tables; a rerank prices only by override or its embedding-table rate) and a declared input ceiling plus enforced output maximum before IO (embedding and rerank calls bill no output, so a missing `maxOutputTokens` counts as 0); unknown pricing/bounds refuse. `runWithJobSpend` uses the same pricing, and `reserveGroup` admits a known-zero call at zero remaining headroom (#6546). Hidden SDK retries are disabled for owned attempts. Actual reported usage is settled with cache categories normalized across SDK/raw responses; absent usage remains explicit unresolved liability. The current grant is checked again under the reservation's client lock. The delegated guard nests inside an outer guard (a job's spend-group guard), so both must admit an attempt.
+- `src/core/minions/delegated-spend.ts` + `src/core/ai/invocation-guard.ts` + `guarded-generation.ts` — async-local admission (with `src/core/ai/invocation-guard.ts` available as `gbrain/ai/invocation-guard` for a companion capped evaluator) around each owned provider attempt, including nested paid tool work; unrelated local calls retain their transport behavior. Finite caps require a known price (`pricing.overrides`, loaded once per run, then the tables; rerank: override or embedding-table rate) and an input ceiling plus output maximum before IO (embed/rerank output defaults to 0); unknown pricing/bounds refuse. `runWithJobSpend` prices the same way (#6546). Hidden SDK retries are disabled for owned attempts. Actual reported usage is settled with cache categories normalized across SDK/raw responses; absent usage remains explicit unresolved liability. The current grant is checked again under the reservation's client lock. The delegated guard nests inside an outer guard (a job's spend-group guard), so both must admit an attempt.
- `src/core/minions/detached-stderr.ts` — durable stderr sink + spawn helper for `gbrain jobs supervisor start --detach`. `openDetachedStderrSink()` opens an append-mode log in the audit dir (`${GBRAIN_AUDIT_DIR:-~/.gbrain/audit}/supervisor-stderr.log`, next to the JSONL lifecycle audit), falling back to the null device, then `'ignore'`; never throws (a sink failure must not block the supervisor start). The detached supervisor gets the fd as `stdio[2]` and its worker inherits it, so ONE durable descriptor covers both processes — not a per-call EPIPE swallow. Prevents the SIGPIPE failure of inheriting the INVOKER's stderr: a short-lived automation runner closing its capture pipe after the start payload would make the worker exit 141 on its next stderr write (and could take the supervisor down writing its own crash event), leaving active jobs and DB locks stale while producers keep enqueueing. Pinned by `test/detached-stderr.test.ts`.
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 3b9a844083..1fc551ed10 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -10,7 +10,7 @@ src/commands/embed.ts 2265 ratchet +2 agent operator wave D2: --json failure env
src/commands/extract-conversation-facts.ts 2087 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); +4: ExtractConversationFactsResult.failed_pages (interface field) and the help text exit-status paragraph; partial-success logic lives in core/facts/conversation-run-status.ts; re-summed at the master 6ccf30c3e merge (2179 master lines + 20 integration lines over base); re-summed at the #6020 merge on actual lines (as rehearsed on capy/mpw-integration-p2); re-summed at the wave 10 merge on actual lines (+1 recordPageFailure fills failed_pages); lowered at the wave-9 follow-ups merge: the three zero-result literals became emptyExtractConversationFactsResult(); lowered to 2075 at wave 15 P2.5 (#6267): segment tunables, splitIntoSegments and renderSegmentForExtraction moved to core/facts/conversation-windows.ts, the message/segment types to core/facts/conversation-types.ts (re-exported here); +12 large pages T2: the oversized-sidecar snapshot and the durable size-skip receipt (skippedForSize; the cap and the bounded sidecar read live in core/conversation-parser/body.ts, the receipt in core/extraction-watermark.ts); merge v0.60.240.0: large pages and master growth compose at 2087
src/commands/extract.ts 2637 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; +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +9 Q2 parser gaps: both DB extract paths read the line-grammar settings once, publish through replaceDerivedLinksUnlessSettingsChanged and report pages a mid-run settings change left stale; +25 GBRA-69: extract --source db reads snapshots and publishes derived links BATCH_SIZE pages at a time (readPageSnapshotsBatch in core/page-snapshot-batch.ts, replay in derived-links.ts replaceDerivedLinksBatchOrReplay); +2 GBRA-75 w7: the --source db links walk refreshes planner statistics (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 13 P2.16 (#6272): both unmanaged DB link drains defer and count a page a concurrent writer moved (skipped_concurrent_write) instead of aborting the run (classifier and skip line in core/derived-links.ts); +3 fix wave 13 P2.18 (S4): extract all --source db stamps the pages both phases completed at one revision, in a finally (stampCompletedIntersection), instead of every links-phase page; +1 fix wave 13 P2.15 (#6273): --from-meetings exits non-zero while managed entity pages are still pending; +7 fix wave 13 PR2: extractFromDB split out of runExtract so runExtract stays under its function-size baseline
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 931 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); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts)
+src/commands/serve-http.ts 932 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); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts); +1 #6589: imports loadServeConfigs (operations see the DB-plane config read once at startup; logic in mcp/serve-config.ts)
src/core/ai/gateway.ts 4523 ratchet +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +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); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same text
src/commands/sync.ts 527 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; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict); +1 fix wave 13 P4.3 #6386: the JSON-output comment names writeJsonDocument for sync status/unblock; +2 fix wave 13 PR2: the transaction-pooler stderr line (P2.2) and the staged catch-up result field (P2.14, loop in commands/sync/perform.ts); +2 fix wave 15 P4.5 (#5459 adjacent): SyncResult.working_tree_kept interface field (the tree-walk keep lives in persistence/sync-discovery.ts); +4 #6643: SyncResult.retryWait / knockOns interface fields (recovery lives in persistence/sync-run.ts, sync-knock-on.ts); +2 #6696 (A7): SyncOpts.capacityPreflight interface field (preflight lives in persistence/sync-capacity-preflight.ts); +2 #6696 C1: SyncOpts.embedDeferred interface field (the cost gate's runtime embed deferral; an interface field cannot move), composed with PR A's SyncOpts.capacityPreflight
src/core/cycle.ts 3314 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); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index 2c13cb8c86..596e99c3db 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -194,6 +194,7 @@ test/fts-cjk-boundary.test.ts one copy of the DDL 2 readFileSync
test/gbrain-owned-page-types.test.ts #5881 gbrain-owned page types are declared by gbrain-base-v2 3 readFileSync
test/get-page-federated-scope.test.ts #2555 get_chunks federated scope 5 source-surface-helper
test/get-page-federated-scope.test.ts #4275 alias hop scope: archived sources, include_deleted, fuzzy precedence, grant precedence 5 source-surface-helper
+test/grant-execution-prerequisites.test.ts execution prerequisite table 1 readFileSync
test/harness-onboarding.test.ts harness identity and private handoff 6 readFileSync
test/hook-command.serial.test.ts user-prompt 17 source-surface-helper
test/hook-push-spawn-env.test.ts spawnDetachedPush env handoff 2 readFileSync
diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.ts
index f096db3b3f..f7d740683e 100644
--- a/src/commands/doctor/checks/extraction-sync.ts
+++ b/src/commands/doctor/checks/extraction-sync.ts
@@ -30,19 +30,12 @@ import { quarantineFilterFragment } from '../../../core/quarantine.ts';
import { persistenceEnabledForHealth } from '../../../core/persistence/ownership.ts';
import { upstreamFreshness } from '../../../core/sync-upstream.ts';
import type { Check } from '../../doctor.ts';
-import { ownedContentFreshness } from '../../../core/shared-skills/content-freshness.ts';
+import { isOwnedContentSchemaMissing, ownedContentFreshness } from '../../../core/shared-skills/content-freshness.ts';
import { connectorAuthorities } from '../../../core/persistence/connector-authority.ts';
import { parseSourceConfig } from '../../../core/sources-load.ts';
import { checkError } from '../check-fix.ts';
import { haltReasonsWithUnknown, readRecordedHaltReasons7d, topHaltReason } from '../../../core/extract/rollup-writer.ts';
-/** Objects ownedContentFreshness reads that an older schema may lack; any other SQL error surfaces (#6599). */
-const OWNED_CONTENT_TABLES = [
- 'persistence_brain', 'persistence_source_bindings', 'persistence_worktrees', 'persistence_host_bindings',
- 'persistence_requests', 'persistence_effects', 'source_ingestion_receipts',
-] as const;
-const OWNED_CONTENT_COLUMNS = ['incarnation', 'source_incarnation', 'recovery', 'owner_host_id'] as const;
-
/** Local aliases; the shared warn-once memo lives in core so it can't fork per module. */
const _resolveEnvNumber = resolveEnvNumber;
const _resolveSyncFreshnessHours = resolveHoursEnv;
@@ -1258,7 +1251,7 @@ export async function checkSyncFreshness(
const issues: string[] = [];
let ownedContent = new Set<string>();
try { ownedContent = new Set((await ownedContentFreshness(engine)).map(source => source.sourceId)); }
- catch (error) { if (!isMissingSchemaObject(error, 'table', OWNED_CONTENT_TABLES) && !isMissingSchemaObject(error, 'column', OWNED_CONTENT_COLUMNS)) throw error; }
+ catch (error) { if (!isOwnedContentSchemaMissing(error)) throw error; }
let writer_owned_count = 0;
// v0.41.27.0: D6 count math. Every source falls into
// EXACTLY ONE bucket per iteration. Invariant pinned by unit test:
diff --git a/src/commands/serve-http.ts b/src/commands/serve-http.ts
index c397660265..fa77b73380 100644
--- a/src/commands/serve-http.ts
+++ b/src/commands/serve-http.ts
@@ -44,8 +44,8 @@ import type { McpSurface } from '../mcp/surface.ts';
import { bindResolveIpcForServe } from '../mcp/resolve-ipc-binding.ts';
import { createPersistenceIpcProvider, residentPersistenceConfig } from '../core/persistence/provider.ts';
import { resolveMcpStdioSourceScope } from '../mcp/server.ts';
-import { loadConfig, loadConfigWithEngine, type GBrainConfig } from '../core/config.ts';
-import { isEngineDegraded } from '../core/degraded-marker.ts';
+import { type GBrainConfig } from '../core/config.ts';
+import { loadServeConfigs } from '../mcp/serve-config.ts';
import { buildError } from '../core/errors.ts';
import * as db from '../core/db.ts';
import { sqlQueryForEngine, type SqlQuery } from '../core/sql-query.ts';
@@ -615,12 +615,7 @@ export async function buildServeHttpApp(app: express.Express, engine: BrainEngin
// a misconfiguration; we WARN to stderr at startup in that case rather
// than silently binding loopback only.
const bind = options.bind ?? '127.0.0.1';
- // #6589: CLI parity. Operations, resources and startup consumers see file + env over the DB plane
- // (`gbrain config set`), read once here: a DB-plane change applies after a serve restart (D18). A degraded
- // engine keeps the file plane, as the bearer transport does.
- const fileConfig = loadConfig();
- const config = (isEngineDegraded(engine) ? fileConfig : await loadConfigWithEngine(engine, fileConfig ?? { engine: engine.kind } as GBrainConfig))
- || { engine: 'pglite' as const };
+ const config = (await loadServeConfigs(engine)).operationConfig || { engine: 'pglite' as const }; // #6589: CLI parity, read once
const skillStatus = await logServeHttpStartup(engine, options, config);
diff --git a/src/core/shared-skills/content-freshness.ts b/src/core/shared-skills/content-freshness.ts
index 1ba7785772..aa02568827 100644
--- a/src/core/shared-skills/content-freshness.ts
+++ b/src/core/shared-skills/content-freshness.ts
@@ -1,6 +1,19 @@
import { isAbsolute, resolve } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { graduationVerifyInheritsPersistence } from '../persistence/ownership.ts';
+import { isMissingSchemaObject } from '../utils.ts';
+
+/** Objects ownedContentFreshness reads that an older schema may lack; any other SQL error surfaces (#6599). */
+const OWNED_CONTENT_TABLES = [
+ 'persistence_brain', 'persistence_source_bindings', 'persistence_worktrees', 'persistence_host_bindings',
+ 'persistence_requests', 'persistence_effects', 'source_ingestion_receipts',
+] as const;
+const OWNED_CONTENT_COLUMNS = ['incarnation', 'source_incarnation', 'recovery', 'owner_host_id'] as const;
+
+/** True only when the error names a table or column ownedContentFreshness reads and the schema predates it. */
+export function isOwnedContentSchemaMissing(error: unknown): boolean {
+ return isMissingSchemaObject(error, 'table', OWNED_CONTENT_TABLES) || isMissingSchemaObject(error, 'column', OWNED_CONTENT_COLUMNS);
+}
export interface OwnedContentFreshness {
sourceId: string;
diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.ts
index 94ca2eee7e..42f198cd0c 100644
--- a/src/mcp/http-transport.ts
+++ b/src/mcp/http-transport.ts
@@ -45,7 +45,7 @@ import { GBRAIN_CLIENT_HEADER, isGbrainThinClient, resolveResultRowsMode, result
import { parseStrictParamsMode } from './validate-params.ts';
import { filterOpsForSurface, clampSurface, advertisedOps, resolveAdvertisedSurface, type McpSurface } from './surface.ts';
import { disabledOpsForPublishGates } from './publish-gates.ts';
-import { loadConfig, loadConfigWithEngine, type GBrainConfig } from '../core/config.ts';
+import { loadServeConfigs } from './serve-config.ts';
import { buildDefaultLimiters, type RateLimiter } from './rate-limit.ts';
import { sqlQueryForEngine } from '../core/sql-query.ts';
import { degradedLastError, isEngineDegraded } from '../core/degraded-marker.ts';
@@ -219,10 +219,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {
// `mcp.strict_params` flip needs a restart here (deliberate; the OAuth
// serve-http path re-reads dual-plane per request). Dispatch-side
// enforcement still resolves per call. mcp.advertised_surface (file plane) narrows the tool list only.
- const fileConfig = loadConfig();
- // #6589: operations see the CLI's effective config (file + env over the DB plane), read once at startup:
- // a DB-plane change (`gbrain config set`) applies after a serve restart. A degraded engine keeps the file plane.
- const operationConfig = isEngineDegraded(engine) ? fileConfig : await loadConfigWithEngine(engine, fileConfig ?? { engine: engine.kind } as GBrainConfig);
+ const { fileConfig, operationConfig } = await loadServeConfigs(engine); // #6589: operations see file + env over the DB plane
const strictParams = parseStrictParamsMode(fileConfig?.mcp?.strict_params) === 'reject';
const tools = buildToolDefs(advertisedOps(surfacedOps, surface, await resolveAdvertisedSurface(null, fileConfig)), { strictParams });
@@ -468,7 +465,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {
if (method === 'resources/list' || method === 'resources/read') {
const resources = createSkillResources(engine, async () => ({ remote: true, transport: 'http',
- auth: auth.auth!, sourceId: auth.sourceId ?? 'default', allowedOps: surfaceAllowedOps, surface, config: operationConfig ?? undefined }));
+ auth: auth.auth!, sourceId: auth.sourceId ?? 'default', allowedOps: surfaceAllowedOps, surface, config: operationConfig }));
try {
const result = method === 'resources/list'
? { resources: [{ uri: CAPABILITIES_URI, name: 'GBrain capabilities', mimeType: 'application/json' }, ...await resources.list()] }
@@ -539,8 +536,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {
}
const result = await dispatchToolCall(engine, toolName, args, {
remote: true,
- admissionOrigin: 'interactive',
- config: operationConfig ?? undefined,
+ admissionOrigin: 'interactive', config: operationConfig,
// WP1/D7: network transport — the dispatch-layer localOnly
// backstop keys off this marker.
transport: 'http',
diff --git a/src/mcp/serve-config.ts b/src/mcp/serve-config.ts
new file mode 100644
index 0000000000..7e363fc2d9
--- /dev/null
+++ b/src/mcp/serve-config.ts
@@ -0,0 +1,16 @@
+import type { BrainEngine } from '../core/engine.ts';
+import { loadConfig, loadConfigWithEngine, type GBrainConfig } from '../core/config.ts';
+import { isEngineDegraded } from '../core/degraded-marker.ts';
+
+/**
+ * #6589: the two config views an HTTP server reads once at startup. `fileConfig` is the file plane
+ * (advertised surface, strict params); `operationConfig` is the CLI's effective config (file + env over
+ * the DB plane) that operations and resources see, so a `gbrain config set` change applies after a
+ * serve restart (D18). A degraded engine keeps the file plane.
+ */
+export async function loadServeConfigs(engine: BrainEngine): Promise<{ fileConfig: GBrainConfig | null; operationConfig: GBrainConfig | undefined }> {
+ const fileConfig = loadConfig();
+ const operationConfig = isEngineDegraded(engine) ? fileConfig
+ : await loadConfigWithEngine(engine, fileConfig ?? { engine: engine.kind } as GBrainConfig);
+ return { fileConfig, operationConfig: operationConfig ?? undefined };
+}
diff --git a/test/extract-rollup-schema-diagnostics.test.ts b/test/extract-rollup-schema-diagnostics.test.ts
index 7cabd53a80..941a9e3e5a 100644
--- a/test/extract-rollup-schema-diagnostics.test.ts
+++ b/test/extract-rollup-schema-diagnostics.test.ts
@@ -3,13 +3,17 @@
* wrapped error without a SQLSTATE is accepted only on the exact PostgreSQL diagnostic.
* Real SQL errors/old schemas are exercised in extract-rollup-schema-errors.test.ts.
*/
-import { expect, test } from 'bun:test';
+import { afterAll, beforeAll, expect, test } from 'bun:test';
import type { BrainEngine } from '../src/core/engine.ts';
import { checkSyncFreshness, computeExtractHealthCheck } from '../src/commands/doctor/checks/extraction-sync.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { readRecordedHaltReasons7d, upsertExtractRollup } from '../src/core/extract/rollup-writer.ts';
import { isMissingSchemaObject } from '../src/core/utils.ts';
+let real: PGLiteEngine;
+beforeAll(async () => { real = new PGLiteEngine(); await real.connect({}); await real.initSchema(); }, 60_000);
+afterAll(async () => { await real.disconnect(); });
+
function throwingEngine(error: unknown): BrainEngine {
return { executeRaw: async () => { throw error; } } as unknown as BrainEngine;
}
@@ -92,27 +96,20 @@ test('isMissingSchemaObject needs the named object and the matching SQLSTATE', (
});
test('sync freshness surfaces real errors from the owned-content probe instead of skipping it', async () => {
- const real = new PGLiteEngine();
- await real.connect({});
- await real.initSchema();
- try {
- await real.executeRaw(`INSERT INTO sources (id, name, local_path, last_sync_at) VALUES ('w17-fresh', 'w17-fresh', '/tmp/w17-fresh', now())`);
- const failing = (error: Error) => new Proxy(real, {
- get(target, prop, receiver) {
- if (prop !== 'executeRaw') return Reflect.get(target, prop, receiver);
- return async (sql: string, params?: unknown[]) => {
- if (sql.includes('persistence_source_bindings')) throw error;
- return target.executeRaw(sql, params as never);
- };
- },
- }) as BrainEngine;
- const denied = Object.assign(new Error('role "gbrain_reader" does not exist'), { code: '42704' });
- const deniedCheck = await checkSyncFreshness(failing(denied));
- expect(deniedCheck.message).toContain('role "gbrain_reader" does not exist');
- const missing = Object.assign(new Error('relation "persistence_worktrees" does not exist'), { code: '42P01' });
- const oldCheck = await checkSyncFreshness(failing(missing));
- expect(oldCheck.message).not.toContain('Could not');
- } finally {
- await real.disconnect();
- }
+ await real.executeRaw(`INSERT INTO sources (id, name, local_path, last_sync_at) VALUES ('w17-fresh', 'w17-fresh', '/tmp/w17-fresh', now())`);
+ const failing = (error: Error) => new Proxy(real, {
+ get(target, prop, receiver) {
+ if (prop !== 'executeRaw') return Reflect.get(target, prop, receiver);
+ return async (sql: string, params?: unknown[]) => {
+ if (sql.includes('persistence_source_bindings')) throw error;
+ return target.executeRaw(sql, params as never);
+ };
+ },
+ }) as BrainEngine;
+ const denied = Object.assign(new Error('role "gbrain_reader" does not exist'), { code: '42704' });
+ const deniedCheck = await checkSyncFreshness(failing(denied));
+ expect(deniedCheck.message).toContain('role "gbrain_reader" does not exist');
+ const missing = Object.assign(new Error('relation "persistence_worktrees" does not exist'), { code: '42P01' });
+ const oldCheck = await checkSyncFreshness(failing(missing));
+ expect(oldCheck.message).not.toContain('Could not');
});