Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(write-inference): observe every model call, attribute it, and guard the zero-generative write path
garrytanec18878dd7ee
diff --git a/docs/TESTING.md b/docs/TESTING.mdindex 845c3ce8a0..6e772230ce 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -1080,18 +1080,55 @@ of every script, workflow, helper and doc that names a split file is#### Layering guard`scripts/check-layering.ts` (`bun run check:layering`, in `bun run verify`)-parses every file under `src/core/engine-sql/` and `src/core/schema-migrations/`-and fails on any import, type-only included, of an engine façade-(`pglite-engine.ts`, `postgres-engine.ts`, `engine-factory.ts`) from-engine-sql, or of `src/core/migrate.ts` from schema-migrations. Those-directories are loaded by the engines and by `migrate.ts`, so an import back-up is an ESM cycle that can fail with a temporal-dead-zone error at module-load. Take the executor as a parameter and import types from-`src/core/engine.ts`; migration helpers live in `schema-migrations/helpers.ts`-and the `Migration` type in `schema-migrations/types.ts`. Fixtures:+parses every file under `src/core/engine-sql/`, `src/core/schema-migrations/`+and `src/core/persistence/` and fails on any import, type-only included, of an+engine façade (`pglite-engine.ts`, `postgres-engine.ts`, `engine-factory.ts`)+from engine-sql, of `src/core/migrate.ts` from schema-migrations, or of+`src/core/ai/gateway.ts` from persistence. The first two directories are loaded+by the engines and by `migrate.ts`, so an import back up is an ESM cycle that+can fail with a temporal-dead-zone error at module load. Take the executor as a+parameter and import types from `src/core/engine.ts`; migration helpers live in+`schema-migrations/helpers.ts` and the `Migration` type in+`schema-migrations/types.ts`. Persistence is the write commit path, which never+calls a generative model: it embeds through `src/core/embedding.ts` and queues+derived model work as effects or jobs. Fixtures:`test/fixtures/guards/check-layering.ts/`; forms are driven in`test/scripts/layering.test.ts`.+#### AI SDK importer guard++`scripts/check-ai-sdk-importers.ts` (`bun run check:ai-sdk-importers`, in+`bun run verify`) fails when a file under `src/` or `scripts/` outside+`scripts/ai-sdk-importers.allowlist` imports a provider SDK (`ai`, `@ai-sdk/*`,+`@anthropic-ai/sdk`, `openai`) as a runtime value, in any import form.+Type-only imports pass. An allowlist line whose file no longer imports an SDK+fails, so the list only shrinks. Every model call then routes through+`invokeAI` (`src/core/ai/invocation-guard.ts`), which admission guards, the+write-inference tests and `GBRAIN_AI_CALL_LOG` observe. Fixtures:+`test/fixtures/guards/check-ai-sdk-importers.ts/`; forms are driven in+`test/scripts/ai-sdk-importers.test.ts`.++#### Write-inference tests++Every mutating operation has a write-inference class+(`src/core/ops/write-inference.ts`: inline `writeInference`, else+`OP_WRITE_INFERENCE`, else `none`). `test/write-path-zero-llm.serial.test.ts`+runs each covered write surface (MCP `put_page` local and remote, `capture`,+`edit_page`, links, tags, timeline, takes, `remember`, `forget`, delete/restore,+`importFromContent`) on PGLite with chat and embedding keys configured and+asserts zero generative model calls before commit, keyword-queryability at+commit, zero generative calls after commit with `facts.extraction_enabled`+false, and, with it true, that every generative call is attributed to facts+extraction for the originating write request. It prints the zero-generative+operations that have no runtime case. `test/write-path-no-egress.serial.test.ts`+runs real CLI writes (`put`, `remember`, `link`, `timeline-add`, `import`, a+git-source `sync`) on a keyless brain with `HTTP(S)_PROXY` pointed at a local+recorder and asserts zero connections; its first case proves the recorder sees+a child process that does reach for the network. Helper:+`test/helpers/ai-tripwire.ts` (records every model call and blocks outbound+fetches; tests assert on the records, since best-effort catch blocks would+swallow a throw).+#### Durable-flush guard`scripts/check-durable-flush.ts` (`bun run check:durable-flush`, indiff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.mdindex 63f17a6ab4..128428f17a 100644--- a/docs/architecture/key-files/core-ai.md+++ b/docs/architecture/key-files/core-ai.md@@ -5,6 +5,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/ai/build-gateway-config.ts` — `buildGatewayConfig(c: GBrainConfig): AIGatewayConfig`, re-exported by `src/cli.ts`. Lets core modules (`init-embed-check.ts`) reuse it without importing the CLI entrypoint. Delegates the file-plane API-key fold + env merge to `mergedProviderEnv` (`src/core/ai/provider-env.ts`); keeps ownership of threading local-server `*_BASE_URL` env vars into base_urls. `process.env` wins EXCEPT empty-string / undefined values are dropped before the merge, so an injected empty `ANTHROPIC_API_KEY=''` (Claude Code neuters subprocess LLM calls this way) can't clobber a valid config-plane key; `'0'` / `'false'` are preserved. Pinned by `test/ai/build-gateway-config.test.ts`.+- `src/core/ai/call-log.ts` + the observer half of `src/core/ai/invocation-guard.ts` — invocation observers and attribution. `observeAIInvocations(observer)` registers a process-level observer that `invokeAI` notifies once per call (guarded or not) with `{ call, outcome: ok | error | refused, usage, startedAt, ms, attribution }`; the unguarded branch of `guarded-generation.ts` routes through `invokeAI` only while an observer is installed and passes the caller's transport options unchanged, so observation never alters retries, token defaults or admission (pinned by `test/ai-invocation-observer.test.ts`). Observer throws are swallowed and counted (`aiInvocationObserverFailures`); adding the same function twice is a no-op. `withAIAttribution({ request_id, effect, job_id, job_name, phase }, fn)` merges into an async-local attribution read by observers: the persistence effect dispatcher (`effects.ts`), the in-process facts queue (`facts/queue.ts`, captured per entry at enqueue), the `facts-absorb` job handler (internal write-request id from `persistence_request_id`) and `timeContainedPhase` (`cycle:<phase>`) set it. `installAICallLogFromEnv` (called by `configureGateway`, idempotent per path) appends one JSON line per call to `GBRAIN_AI_CALL_LOG` (kind with multimodal counted as embedding, operation, model, outcome, ms, input/output/cache tokens or `unknown`, attribution; never prompt or response text; one warning on write failure). Pinned by `test/ai-call-log.test.ts`.+- `src/core/ai/chat-usage.ts` + `src/core/ops/usage.ts` — durable per-call chat usage accounting. `gateway.chat()` calls `recordChatUsage` at its SUCCESS boundary (production provider path AND test-transport path) with the answering model + token usage; the record lands in the `chat_usage_log` table (migration v140) via an injected sink (`setChatUsageSink` — no engine import here, so the gateway imports this leaf statically without deepening a cycle). Phase attribution is best-effort via AsyncLocalStorage (`withChatPhase`): the minion worker AND the cycle's inline drain (`inline-drain.ts`) both wrap handler execution in `job:<name>`, a cycle phase that meters its own spend wraps itself in `phase:<name>` (dream synthesize does), and direct callers record phase NULL. The innermost wrap wins, which is the point — a child drained INSIDE a wrapped phase must carry its own `job:` tag or the phase tag absorbs every child's spend and the ledger double-counts (one ledger per surface: `minion_jobs` stays the child-spend authority, the phase row is the orchestrator's own calls). Pricing resolves through `CANONICAL_PRICING` (`estimateChatCostUsd`, cache_read/cache_write at provider cache rates when the table carries them); unknown models record `cost_usd = NULL`, never a fake 0. Accounting is strictly fail-open + fire-and-forget: a sink error must never break a chat call. The `get_usage` op (admin scope, NOT read — `chat_usage_log` has no source dimension, so a source-restricted/federated token must not see brain-wide spend telemetry) returns per-model/per-phase aggregates only, plus an explicit `coverage` block stating what the ledger does NOT capture (subagent raw-SDK path, embeddings, pre-sink/pre-v140 calls, failed calls); `budget-tracker.ts` remains the pessimistic in-flight spend gate — this table is the after-the-fact ledger.- `src/core/ai/defaults.ts` — leaf module for canonical embedding and reranker defaults, without a gateway import. Voyage `voyage:voyage-4` at 1024 dimensions is the new-install embedding default; `voyage:rerank-2.5` is the runtime/mode-bundle reranker default. `renderCanonicalMigrationCommands` supplies an explicit-target cost preview and an OpenAI keep-width alternative where supported. These constants do not establish the identity of vectors in an existing database and must never authorize automatic provider conversion. Init preserves explicit choices, writes no reranker row when the Voyage key is available, disables reranking for keyed installs without that key, and preserves keyless setup.diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex 8389ad7bb7..410e536f15 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -42,6 +42,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cycle/recompute-emotional-weight.ts` — Cycle phase orchestrator. One read plus bounded writes: `engine.batchLoadEmotionalInputs(slugs?)` → `computeEmotionalWeight` (per-row pure function) → `engine.setEmotionalWeightBatch(slice)` in slices of 1000 rows. Between slices it checks `opts.signal` (throws → `fail`), awaits `opts.yieldDuringPhase` (cycle-lock refresh / steal detection), fires `opts.onProgress`, and yields a macrotask (`setTimeout(0)`) so PGLite's synchronous statement execution never wedges the main thread for a whole-brain pass; `runCycle` wires these exactly like consolidate (`racedTimePhase` + `buildYieldDuringPhase` + `cycleSignal` + `progress.tick`). Both engines' `setEmotionalWeightBatch` rewrite only rows whose weight changes (`IS DISTINCT FROM` in the WHERE — no trigger fan-out on same-value rows) and return rows CHANGED; `details.pages_recomputed` = pages evaluated (feeds the cycle totals), `details.pages_updated` = rows changed. Reads config `emotional_weight.high_tags` (JSON array, falls back to default seed list on parse error) and `emotional_weight.user_holder`. Empty `affectedSlugs` short-circuits with zero-work success. dry-run reports the would-write count without touching the DB. Engine throw bubbles into `status: 'fail'` with code `RECOMPUTE_EMOTIONAL_WEIGHT_FAIL` so the cycle continues.-- `src/core/cycle/phase-containment.ts` — `timeContainedPhase` is the timer every `runCycle` phase runs under: a phase runner that throws returns a `fail` phase result carrying `{ class, code, message }` and `details.contained`, so later phases in the job still run while the report stays partial/failed (global freshness is not stamped; `gbrain dream` exits non-zero). Cancellation (an aborted cycle signal or `AbortError`), `LockStolenError` and `BudgetExhausted` are never contained. Successful `gateway.chat` calls inside the phase are counted through `withChatCallMeter` (`ai/chat-usage.ts`); a contained failure after at least one paid call is recorded under `dream:phase:<phase>:<source>` for `dream_paid_loop`. Tests: `test/cycle-phase-containment.test.ts`.+- `src/core/cycle/phase-containment.ts` — `timeContainedPhase` is the timer every `runCycle` phase runs under: a phase runner that throws returns a `fail` phase result carrying `{ class, code, message }` and `details.contained`, so later phases in the job still run while the report stays partial/failed (global freshness is not stamped; `gbrain dream` exits non-zero). Cancellation (an aborted cycle signal or `AbortError`), `LockStolenError` and `BudgetExhausted` are never contained. Successful `gateway.chat` calls inside the phase are counted through `withChatCallMeter` (`ai/chat-usage.ts`); a contained failure after at least one paid call is recorded under `dream:phase:<phase>:<source>` for `dream_paid_loop`. Tests: `test/cycle-phase-containment.test.ts`. Each phase also runs under `withAIAttribution({ phase: 'cycle:<phase>' })`, so model calls it makes carry the phase in invocation observers and `GBRAIN_AI_CALL_LOG`.- `src/core/cycle/phase-table.ts` — `MANAGED_PHASE_TABLE` classifies every `ALL_PHASES` entry for managed brains as `writes` (publishes through the coordinator), `no_coordinated_write` (derived projections, side tables, audit-only) or `managed_skip`, each with its reason; `isManagedBrain` is what `runPhaseLint` uses to report issues without rewriting managed canonical files. The managed phase matrix test fails for an unclassified phase.diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex f782df7447..2f408de698 100644--- a/docs/architecture/key-files/core-utilities-1.md+++ b/docs/architecture/key-files/core-utilities-1.md@@ -55,6 +55,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/operations.ts` — Contract-first operation contract, served through a ~300-line assembly façade: the op definitions live in the domain modules under `src/core/ops/` (next entry) and are spread into the single exported `operations` array here; the registration loop replaces each handler with `withOutputRedaction(op)`, so a `'retrieval'` op's output is redacted on every dispatch path (see `src/core/ops/contract.ts`); the shared contract types (`src/core/ops/contract.ts`) and the security/scope layer (`src/core/ops/context.ts`) are re-exported through this file, so every import path below resolves through the façade unchanged. The rest of this entry describes the surface as consumers see it. Fresh same-source graph mutations (`add_link`, `add_timeline_entry`) preflight each endpoint against the scalar write source via `requireWritablePage` (`ops/context.ts`); `add_timeline_entry` resolves an authorized stored request before that fresh-write preflight so exact replay retains its outcome after page purge or recreation: a page readable only from another granted source returns endpoint-specific `permission_denied` naming the boundary, pages outside the caller's `get_page` visibility scope stay `page_not_found` (a soft-deleted foreign page is indistinguishable from absence), and a mutation-time engine miss — the typed `PageMissingError` from `src/core/engine-errors.ts`, thrown by both engines' single-statement endpoint resolution — is reclassified into the same envelope by `instanceof`, never message matching. Exports upload validators `validateUploadPath`, `validatePageSlug`, `validateFilename`, plus `matchesSlugAllowList(slug, prefixes)` (glob matcher: `<prefix>/*` matches recursive children; bare `<prefix>` matches exact only). `OperationContext.remote` is a REQUIRED field flagging untrusted callers; `OperationContext.allowedSlugPrefixes` is the trusted-workspace allow-list set by the dream cycle; `OperationContext.auth?: AuthInfo` is threaded through HTTP dispatch for scope enforcement in `serve-http.ts` before the op runs. OAuth `whoami` exposes the authenticated `AuthInfo.sourceId` and `AuthInfo.allowedSources` grants as `source_id` and `federated_read`; absent grants serialize fail-closed as `null` and `[]`, while local, legacy, and stdio response shapes stay unchanged. `enforceSubagentSlugFence(ctx, slug, opName)` is the shared fail-closed subagent write fence: when `viaSubagent` and `allowedSlugPrefixes` is set, the slug must match the allow-list; else the legacy `wiki/agents/<id>/...` namespace check applies. Both `put_page` and `add_timeline_entry` (subagent-allowlisted) route through it. Auto-link/timeline hooks are skipped for remote-owned subagents even with explicit prefixes; only local subagents qualify as trusted workspaces. `enforceClientSlugFence(ctx, slug, opName)` is the OAuth-client write fence: when `ctx.auth.boundSlugPrefixes` is present (threaded from `oauth_clients.bound_slug_prefixes` at token-verification time), every direct slug-mutating write op — `put_page`, `delete_page`, `restore_page`, `add_tag`, `remove_tag`, `add_link`/`remove_link` (`from` endpoint only; linking TO a readable page is a reference), `add_timeline_entry`, `revert_version`, `put_raw_data` — rejects out-of-prefix slugs with `permission_denied`, BEFORE each op's dry-run short-circuit. Direct writes use the shared boundary-aware prefix rules; empty-array binding is deny-all (fail-closed); no auth / no binding = no fence. The match rule itself lives in the exported `slugUnderBoundPrefixes(prefixes, slug)` so non-op write surfaces reuse it verbatim. It is BOUNDARY-AWARE (a prefix matches whole segments, so `emp-alice` does not admit `emp-alice-2/…`), lowercases both sides (stored slugs are lowercased by `validateSlug`, so comparing the caller's raw string would let a mixed-case slug commit and only then trip the resolved-slug re-check), accepts BOTH the trailing-slash and the `<prefix>/*` glob spelling via `normalizeSlugPrefix` (direct and delegated fences share normalization while storing independently reviewed spans), and ignores empty-string prefixes. `assertValidSlugPrefixes` (`oauth-provider.ts`) rejects empty, whitespace-bearing, non-lowercase, and boundary-less entries at registration and rescope. `submit_agent` validates tools and namespaces against the independently stored `bound_tools`, `delegated_slug_prefixes`, and `delegated_namespace` grants. It normalizes accepted prefixes for `matchesSlugAllowList` and rejects explicit empty remote tool or prefix overrides. Workers interpret explicit empty tool lists as no tools, with defaults reserved for absent trusted-local bindings. `put_page` deduplication may resolve another slug by content hash or `frontmatter.id`, but returns an authorized read-only `duplicate` outcome. The original target's revision never authorizes publication to that other page. Preparation and guarded validation recheck the duplicate's current authority, readability, concrete page identity and revision; neither its canonical fields nor its file are written. OAuth and delegated subagent fences still apply, and denials do not name an inaccessible duplicate. Pinned by `test/put-page-dedup-fence.test.ts`. `CLIENT_FENCED_WRITE_OPS` + `enforceBoundClientOpAllowList(auth, op)` are the fail-closed companion, applied once in `src/mcp/dispatch.ts` (the choke point both MCP transports share): a slug-bound client calling ANY `write`/`admin` op not on the allow-list gets `permission_denied`. This covers the ops that write by a key other than a slug and therefore cannot be fenced — `extract_entities`/`extract_facts` (mutate `people/*`, `companies/*`), `forget_fact` (numeric fact id, crosses sources), `ontology_propose` — and makes a write op added later denied-by-default instead of silently unfenced. `think` is on the allow-list because remote callers cannot persist from it. Pinned by `test/client-slug-fence.test.ts` and over-the-wire by `test/qm-provisioning.test.ts`. Every `Operation` carries `scope?: 'read' | 'write' | 'admin'` + `localOnly?: boolean`; `think` is read-scoped for OAuth/MCP because remote callers have `save`/`take` forced off before persistence, while local CLI can still persist via `remote:false`; `sync_brain`, `file_upload`, `file_list`, `file_url` are `admin + localOnly` (rejected over HTTP). Four trust-boundary call sites (`put_page` allowlist, file_upload trust-narrowing, submit_job protected-name guard, auto-link skip) use FAIL-CLOSED semantics: `ctx.remote === false` for trusted-only sites, `ctx.remote !== false` for "untrust unless explicit-false" — anything not strictly `false` is treated as remote (so a read+write OAuth token over HTTP MCP cannot submit `shell` jobs). `sourceScopeOpts(ctx)` encodes the source-scoped read precedence ladder — federated array (`ctx.auth.allowedSources`) wins over scalar (`ctx.sourceId`/`ctx.auth.sourceId`) over nothing; every read-side op handler routes through it so a source-bound OAuth client can't see neighboring sources via `search`/`query`/`list_pages`/`get_page`/`find_experts`/query's image path, plus the by-slug reads `get_tags`/`get_links`/`get_backlinks`/`get_timeline`/`get_chunks` (chunks follow the same ladder as `get_page`, so a federated grant that can open a page can read its chunks — and the chunk payload never carries embedding vectors) (and `get_page`'s tag fetch, which resolves against the concrete page's own `source_id`). `get_tags` resolves `readPolicyOpts`, so an untrusted caller gets no tags for a `visibility: private` page (unless the operator's private-pages opt-out is on) or a soft-deleted page. `assertExplicitSourceLive(ctx, sourceIdParam)` is the async companion for the ops that accept a per-call `source_id` (`get_page`, `list_pages`, `search`, `query`): called right after `federatedSearchScope` (so the grant check has already run and it can only name a granted source), an explicit id with no live unarchived `sources` row throws `unknown_source` instead of silently scoping the read to an empty source — the CLI's `--source` existence rule applied to the op path; `__all__` and an omitted param skip it. `linkReadScopeOpts(ctx, scope?)` is the link-read sibling for `get_links`/`get_backlinks`/`traverse_graph` (`scope` defaults to `sourceScopeOpts(ctx)`; the link ops pass their resolved per-call `federatedSearchScope`): a link row references three pages (from/to/origin), and the engine's federated (`sourceIds[]`) branch scopes ALL THREE while its scalar (`sourceId`) branch scopes only the near endpoint (by design — trusted internal callers like `reconcileLinks` and back-link validators call the engine with a scalar scope and need the cross-source view). For an UNTRUSTED remote caller (`ctx.remote !== false`) carrying only a scalar scope it promotes that scope to a single-element `sourceIds:[id]`, routing them through the all-endpoint branch so a far/origin slug from outside the grant isn't disclosed; a federated array passes through unchanged and trusted local CLI (`ctx.remote === false`) keeps the scalar cross-source view. `thinkSourceScopeOpts(ctx)` maps the same precedence ladder onto `runThink`'s public options (`allowedSources`/`sourceId`) so the `think` op's gather and trajectory stages inherit the caller's source grant. `put_page` submits through `submitPageMutation` to the durable journal. Existing-page replacements require `expected_revision` or explicit `force`; omission is create-only. The designated owner publishes under native root and database guards, with recoverable file replacement and a terminal receipt committed with canonical state. Accepted contention returns `write_pending` after the synchronous wait; admission failure does not fabricate a queued receipt. Git and embeddings report separate effect outcomes. Trusted-local `delete_page` with `purge: true` uses the same journal, revision and recovery protocol: artifact-removal failure preserves the prior row, and exact replay retains the original terminal outcome after deletion. Link provenance surface: `add_link` (`gbrain link`/`link-add`) + `remove_link` (`gbrain unlink`/`link-rm`) expose `link_source`/`link_type`; `add_link` rejects the reconciliation-managed built-ins via `MANAGED_LINK_SOURCES` (`markdown`/`frontmatter`/`mentions`/`wikilink-resolved`) and defaults omitted provenance to `'manual'` (the engine's own default stays `'markdown'` for internal callers); `list_link_sources` (`gbrain link-sources`, read) lists provenances via `sourceScopeOpts`. CLI aliases register through `cliHints.aliases` (collision-guarded in `src/cli.ts`).- `src/core/ops/contract.ts` — the shared operation types (`Operation`, `OperationContext`, `ParamDef`, `OperationError`). `Operation.outputRedaction: OutputRedactionPolicy` is REQUIRED, so typecheck forces every op to say how its response treats stored text: `'retrieval'` (the whole response passes `redactRetrievalOutput`, uncapped, assignment rule on), `{ retrieval: { localVerbatim: [...] } }` (same, but the named top-level keys stay raw for the trusted local CLI, `ctx.remote === false`; the memory verbs' `facts`), `{ exempt: reason }` (deliberately raw with a one-line reason: page reads `get_page`/`fetch`/`get_chunks`/`get_raw_data`/`get_versions`, skill-catalog files, admin job ops) or `'no_stored_text'` (returns no page, chunk, fact, take or transcript text). `operations.ts` applies the policy at registration (`withOutputRedaction` in `src/core/search/output-redaction.ts`); `test/retrieval-op-redaction.test.ts` sweeps every classified op with a planted secret. `whoami` and the HTTP `gbrain://capabilities` resource choose `oauth` vs `legacy` through `authTransport`, which trusts the verifier-set `AuthInfo.principal` and falls back to the `gbrain_cl_` id prefix only when no principal is present.+- `src/core/ops/write-inference.ts` — the write-inference contract: what model work a write may do and when. `WriteInference` = `none` (no model call before commit) | `embedding` (may embed before commit, never generative) | `async_derived` (none/embedding before commit; may queue generative work after commit, e.g. facts extraction) | `opt_in_media` (generative before commit only under a user opt-in, image OCR) | `explicit_llm` (the op is a model call: think, extract_facts, submit_agent) | `non_content` (admin state). `writeInferenceOf(op)` resolves the inline `Operation.writeInference`, then `OP_WRITE_INFERENCE`, then `none`, so an unclassified op is held to the strictest promise and never breaks the build. `CLI_WRITE_INFERENCE` lists CLI writers that are not ops. `ZERO_GENERATIVE_BEFORE_COMMIT` = none/embedding/async_derived. Pinned by `test/op-write-inference.test.ts` and checked at runtime by `test/write-path-zero-llm.serial.test.ts` + `test/write-path-no-egress.serial.test.ts` (docs/TESTING.md#write-inference-tests).- `src/core/pg-access-classify.ts` — Postgres ACCESS-error classifier, the reason/remediation layer of the db-availability loop (detect → `GBRAIN_DB_ACCESS` marker → skills/db-repair → `gbrain db-repair`). `RESIDENT_POOL_FLOOR` (6) is the documented minimum `GBRAIN_POOL_SIZE` for a long-running process; `pool_exhausted` recommends it plus fewer processes (docs/ENGINES.md#pool-sizing), and `serve`'s boot-deadline line uses it. Two entry points, one diagnosis type: `classifyPgAccessError(err, ctx?)` for thrown errors (data-driven ordered `REASON_ROWS` table, first match wins — specific rows before general ones) and `diagnoseDbConfig(ctx)` for errorless config-plane reasons (`no_url`, `env_shadowed` — there is no error object at connectEngine's no-config exit or under an env shadow; never fake one). The `PgAccessReason` union (16 reasons) is APPEND-ONLY — a compatibility surface once the bundled skills are in the wild, like progress phase names; consumers switch exhaustively with a `never` sentinel. Invariants: `message`/`remediation` are ALWAYS pre-redacted (safe for transcripts/receipts/issues); every `fix` descriptor is hardcoded or derived from the CURRENT config URL (`deriveSessionPoolerUrl`/`deriveDirectUrl`), never from anything parsed out of error text, and `run_command` argv[0] is always `gbrain`; **remediation copy has exactly ONE home: this module** — db-repair, doctor, and MCP dispatch all render `diagnosis.remediation`, skills reference the command and never duplicate recipe text. TWO-AXIS design note (mirrored in `retry-matcher.ts`'s header — do not "fix" one side to match the other): retry-matcher answers "should I retry?" and deliberately treats `password authentication failed` as retryable (auth race during DNS failover); this module answers "what went wrong?" and reports the same error `auth_failed` + `transient: false` — both correct on their own axis; unknown reasons defer `transient` to `isRetryableConnError`. Also exports `DB_ACCESS_MARKER_PREFIX`/`formatDbAccessMarker` (the single source of the marker literal that skills/db-repair pins in both `description:` and `triggers:`; the action a reader takes is ALWAYS the hardcoded `gbrain db-repair`, never a command parsed from the marker), `isDbAccessFailure` (the ACCESS-class subset fail-open recall arms use to tell "one arm degraded" from "the DB is down"), and Supabase enrichment `{pooler, projectRef, pausedSuspect}` (paused projects aren't a distinct wire error — modeled as a suspicion flag on dns/timeout/tenant reasons). Pinned by `test/pg-access-classify.test.ts`.diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.mdindex 9f88e3bf36..58b7ed930c 100644--- a/docs/architecture/key-files/providers.md+++ b/docs/architecture/key-files/providers.md@@ -59,4 +59,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/spend-posture.ts` — spend-control surface. `resolveSpendPosture(engine): 'gated'|'tokenmax'` (DB-plane `spend.posture`, fail-open `gated`); `tokenmax` makes every cost gate informational across sync/reindex/enrich/onboard (spend still ledgered — removes the ceiling, not the accounting). `parseUsdLimit(raw, def, {allowZero?})` accepts `off`/`unlimited`/`none` → `Infinity`; `formatUsdLimit(n)` renders `Infinity` as the string `'unlimited'` (never raw — `JSON.stringify(Infinity)` is `null`); `usdLimitToCap(n)` maps `Infinity` → `undefined` at the BudgetTracker boundary so ledger rows never serialize null. `normalizeSpendPosture`/`isValidSpendPosture` back the `config set` validation. Doc: `docs/operations/spend-controls.md`. Pinned by `test/sync-cost-preview.test.ts` + `test/spend-off-switch.test.ts`.-- `src/core/transcription.ts` — Audio transcription: Groq Whisper (default), OpenAI fallback, ffmpeg segmentation for >25MB.+- `src/core/transcription.ts` — Audio transcription: Groq Whisper (default), OpenAI fallback, ffmpeg segmentation for >25MB. Each provider request routes through `invokeAI` with kind `transcription`, so admission guards and invocation observers see it.diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.mdindex 65eb12a0ce..566e153921 100644--- a/docs/guides/memory-boundaries.md+++ b/docs/guides/memory-boundaries.md@@ -26,6 +26,20 @@ saved facts do not expire just because they describe a temporary situation.`forget` withdraws a fact from active recall, not from all source material,history, or private backups. See [ambient writeback](ambient-writeback.md).+## What a write costs++Saving text or a fact never waits on a generative model: a write is+acknowledged and keyword-queryable without one. Embeddings are the configured+feature (`remember` embeds before saving to detect near-duplicates; pages embed+just after the save). With default settings each saved page of an+extraction-eligible type (note, meeting, email and similar) also gets one facts+extraction call after it is saved; it runs as a queued job, is attributed to the+write that caused it, and stops with `gbrain config set facts.extraction_enabled+false`. Image OCR, when turned on (`embedding_image_ocr`), runs before the save.+Set `GBRAIN_AI_CALL_LOG=<path>` to record every model call a process makes (kind,+model, tokens, duration, and the write request, job or cycle phase it served; no+prompt or response text).+## Page writes and the graph are separate outcomes| Write path | Graph behavior |diff --git a/package.json b/package.jsonindex a91018fb95..10bff72205 100644--- a/package.json+++ b/package.json@@ -139,6 +139,7 @@"check:module-size": "bash scripts/check-module-size.sh","check:function-size": "bun scripts/check-function-size.ts","check:layering": "bun scripts/check-layering.ts",+ "check:ai-sdk-importers": "bun scripts/check-ai-sdk-importers.ts","check:durable-flush": "bun scripts/check-durable-flush.ts","check:engine-sql-ratchet": "bun scripts/check-engine-sql-ratchet.ts","check:engine-sql-dynamic": "bun scripts/check-engine-sql-dynamic.ts",diff --git a/scripts/ai-sdk-importers.allowlist b/scripts/ai-sdk-importers.allowlistnew file mode 100644index 0000000000..87382736c6--- /dev/null+++ b/scripts/ai-sdk-importers.allowlist@@ -0,0 +1,6 @@+# Files allowed to import a provider SDK as a runtime value. Shrink-only.+# Each routes its provider calls through invokeAI (src/core/ai/invocation-guard.ts).+src/core/ai/gateway.ts+src/core/minions/handlers/subagent.ts+# Eval harness embedding cache (not a write path); its calls are not observed.+src/eval/shared/embed-cache.tsdiff --git a/scripts/check-ai-sdk-importers.ts b/scripts/check-ai-sdk-importers.tsnew file mode 100644index 0000000000..bea128dead--- /dev/null+++ b/scripts/check-ai-sdk-importers.ts@@ -0,0 +1,82 @@+#!/usr/bin/env bun+/**+ * Model-call routing guard (docs/TESTING.md#ai-sdk-importer-guard).+ *+ * Every model provider call must stay observable through `invokeAI`+ * (src/core/ai/invocation-guard.ts): admission guards, the write-inference+ * tripwire and GBRAIN_AI_CALL_LOG all rely on it. This guard fails when a file+ * outside the allowlist imports a provider SDK as a runtime value (`ai`,+ * `@ai-sdk/*`, `@anthropic-ai/sdk`, `openai`). Type-only imports are fine.+ * The allowlist only shrinks.+ *+ * Seam: GBRAIN_GUARD_ROOT (fixture tree root).+ */+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';+import { join, relative } from 'node:path';+import ts from 'typescript';++const ROOT = process.env.GBRAIN_GUARD_ROOT ?? join(import.meta.dir, '..');+const ANCHOR = 'docs/TESTING.md#ai-sdk-importer-guard';+const ALLOWLIST_PATH = join(ROOT, 'scripts', 'ai-sdk-importers.allowlist');+const SDK = /^(ai|openai|@anthropic-ai\/sdk(\/.*)?|@ai-sdk\/.+)$/;++function tsFiles(dir: string): string[] {+ if (!existsSync(dir)) return [];+ const out: string[] = [];+ for (const entry of readdirSync(dir).sort()) {+ const full = join(dir, entry);+ if (statSync(full).isDirectory()) { if (entry !== 'node_modules') out.push(...tsFiles(full)); }+ else if (entry.endsWith('.ts') && !entry.endsWith('.d.ts')) out.push(full);+ }+ return out;+}++function runtimeSdkImports(sf: ts.SourceFile): { spec: string; line: number }[] {+ const out: { spec: string; line: number }[] = [];+ const at = (node: ts.Node) => sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;+ const visit = (node: ts.Node): void => {+ if (ts.isImportDeclaration(node) && ts.isStringLiteralLike(node.moduleSpecifier) && SDK.test(node.moduleSpecifier.text)) {+ const clause = node.importClause;+ const typeOnly = clause?.isTypeOnly+ || (!!clause && !clause.name && !!clause.namedBindings && ts.isNamedImports(clause.namedBindings)+ && clause.namedBindings.elements.length > 0 && clause.namedBindings.elements.every(e => e.isTypeOnly));+ if (!typeOnly) out.push({ spec: node.moduleSpecifier.text, line: at(node) });+ } else if (ts.isExportDeclaration(node) && !node.isTypeOnly && node.moduleSpecifier+ && ts.isStringLiteralLike(node.moduleSpecifier) && SDK.test(node.moduleSpecifier.text)) {+ out.push({ spec: node.moduleSpecifier.text, line: at(node) });+ } else if (ts.isCallExpression(node)) {+ const isImport = node.expression.kind === ts.SyntaxKind.ImportKeyword;+ const isRequire = ts.isIdentifier(node.expression) && node.expression.text === 'require';+ const arg = node.arguments[0];+ if ((isImport || isRequire) && arg && ts.isStringLiteralLike(arg) && SDK.test(arg.text)) out.push({ spec: arg.text, line: at(node) });+ }+ ts.forEachChild(node, visit);+ };+ visit(sf);+ return out;+}++const allowlist = new Set(existsSync(ALLOWLIST_PATH)+ ? readFileSync(ALLOWLIST_PATH, 'utf8').split('\n').map(l => l.replace(/#.*/, '').trim()).filter(Boolean)+ : []);+const violations: string[] = [];+const importers = new Set<string>();+for (const abs of [...tsFiles(join(ROOT, 'src')), ...tsFiles(join(ROOT, 'scripts'))]) {+ const rel = relative(ROOT, abs).replace(/\\/g, '/');+ const sf = ts.createSourceFile(abs, readFileSync(abs, 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);+ for (const { spec, line } of runtimeSdkImports(sf)) {+ importers.add(rel);+ if (!allowlist.has(rel)) violations.push(`FAIL: ${rel}:${line} imports the provider SDK '${spec}' as a runtime value`);+ }+}+const stale = [...allowlist].filter(f => !importers.has(f));++if (violations.length || stale.length) {+ for (const v of violations) console.error(v);+ for (const f of stale) console.error(`FAIL: scripts/ai-sdk-importers.allowlist lists ${f}, which no longer imports a provider SDK; remove the line (the allowlist only shrinks)`);+ if (violations.length) console.error('Fix: call the model through src/core/ai/gateway.ts (chat, embed, generate) so the call routes through invokeAI; use `import type` for SDK types.');+ console.error('Why: admission guards, the write-inference tripwire and GBRAIN_AI_CALL_LOG observe model calls only through invokeAI.');+ console.error(`See: ${ANCHOR}`);+ process.exit(1);+}+console.log(`check-ai-sdk-importers: ok (${importers.size} allowlisted importer(s))`);diff --git a/scripts/check-layering.ts b/scripts/check-layering.tsindex a8eef3c158..5fecaa1b16 100644--- a/scripts/check-layering.ts+++ b/scripts/check-layering.ts@@ -12,6 +12,8 @@* src/core/schema-migrations/** imports no src/core/migrate.ts; shared* helpers live in schema-migrations/helpers.ts* and the Migration type in schema-migrations/types.ts+ * src/core/persistence/** imports no src/core/ai/gateway.ts: the write+ * commit path makes no generative model call** Every import form counts, type-only included: static import/export-from,* dynamic import() and require() with a literal relative specifier.@@ -42,6 +44,11 @@ const RULES: Rule[] = [banned: ['src/core/migrate.ts'],fix: 'import shared helpers from ./helpers.ts and the Migration type from ./types.ts',},+ {+ dir: 'src/core/persistence',+ banned: ['src/core/ai/gateway.ts'],+ fix: 'the write commit path never calls a generative model: embed through src/core/embedding.ts, and queue derived model work as an effect or job',+ },];function tsFiles(dir: string): string[] {@@ -91,7 +98,7 @@ for (const rule of RULES) {if (violations.length) {for (const v of violations) console.error(v);- console.error('Why: engine-sql/ and schema-migrations/ are loaded BY the engines and migrate.ts; an import back up is an ESM cycle (TDZ at load).');+ console.error('Why: engine-sql/ and schema-migrations/ are loaded BY the engines and migrate.ts (an import back up is an ESM cycle, TDZ at load); persistence/ is the write commit path, which stays free of generative model calls.');console.error(`See: ${ANCHOR}`);console.error(`check-layering: ${violations.length} violation(s)`);process.exit(1);diff --git a/scripts/guards-manifest.tsv b/scripts/guards-manifest.tsvindex bb21180917..be512e365d 100644--- a/scripts/guards-manifest.tsv+++ b/scripts/guards-manifest.tsv@@ -69,7 +69,8 @@ check-engine-sql-ratchet.ts scanner yes goal (a) engine-sql ratchet (TS AST): SQcheck-engine-sql-dynamic.ts scanner yes CQ3/EO17 dynamic SQL in src/core/engine-sql/** (TS AST; fragment.ts exempt as the renderer): trustedSql args and composed .query/.unsafe/.executeRaw/executeRawJsonb SQL splice only literals, as-const/allowlisted constants, VETTED_BUILDERS calls or Number.isFinite-checked numbers; no $<digit> in composed strings; no expanded IN listscheck-engine-sql-brands.ts scanner yes EO4/AR2 RLS read brands (TS AST + text): brand-key mentions outside engine-sql/brands.ts; casts onto ScopedRead/LegacyUnscopedRead or `as unknown as` executor types in src/; unscopedExecutor/LegacyUnscopedRead/scopedRead imports outside their allowlists, src/core/ops/** always deniedcheck-sync-run-state.ts scanner yes A17 (W4 sync): SyncRun mutable fields (non-readonly members of interface SyncRun) are never destructured or aliased into locals under src/commands/sync/; @checkpoint fields are assigned only in sync-run.ts (single owner); fixtures cover destructuring, aliasing, a parameter pattern in a nested dir, and an out-of-owner checkpoint write-check-layering.ts scanner yes EO10 layering (TS AST, every import form): src/core/engine-sql/** imports no engine façade; src/core/schema-migrations/** imports no migrate.ts+check-layering.ts scanner yes EO10 layering (TS AST, every import form): src/core/engine-sql/** imports no engine façade; src/core/schema-migrations/** imports no migrate.ts; src/core/persistence/** imports no ai/gateway.ts (P8 write-inference contract)+check-ai-sdk-importers.ts scanner yes P8: provider SDKs (ai, @ai-sdk/*, @anthropic-ai/sdk, openai) imported as runtime values only by scripts/ai-sdk-importers.allowlist (shrink-only), so every model call is observable through invokeAIcheck-durable-flush.ts scanner yes #5595/#5475 Windows durability (TS AST, scope-resolved): fsyncSync of a descriptor from a read-only or unreadable-flags openSync in src/ outside src/core/fs-durable.ts fails, file or directory; write-fd flushes pass; reasoned ALLOWLIST, stale entries fail; bad-directory fixture covers an O_RDONLY directory flushcheck-schema-migrations-fresh.sh buildfresh exempt regenerates src/core/schema-migrations/registry.generated.ts + diffs; generator enforces filename/version/name cross-check and duplicate versions (unit: test/scripts/build-schema-migrations.test.ts)check-schema-fresh.sh buildfresh exempt W2: regenerates the schema chain (fragments -> schema.sql regions -> schema-embedded -> PGLite template) into a temp dir and diffs every output; names the source to edit (unit: test/scripts/build-schema.test.ts)diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex c8d143f471..4bb277515f 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -11,7 +11,7 @@ src/commands/extract-conversation-facts.ts 2182 ratchet grown v0.46.x per-providsrc/commands/extract.ts 2528 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)src/commands/jobs.ts 660 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)src/commands/serve-http.ts 919 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)-src/core/ai/gateway.ts 4393 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)+src/core/ai/gateway.ts 4395 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); +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts)src/commands/sync.ts 510 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)src/core/cycle.ts 3224 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)src/core/cycle/synthesize.ts 3297 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)diff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.shindex ef451d1f6d..54ef22c451 100755--- a/scripts/run-verify-parallel.sh+++ b/scripts/run-verify-parallel.sh@@ -135,6 +135,9 @@ CHECKS=(# EO10 (refactor wave 1): engine-sql/ and schema-migrations/ never import# back up into the engine façades or migrate.ts (ESM TDZ cycles)."check:layering"+ # P8: provider SDKs are imported only by allowlisted modules, so every model+ # call stays observable through invokeAI (write-inference guard, call log).+ "check:ai-sdk-importers"# #5595/#5475: no fsync of a read-only descriptor outside src/core/fs-durable.ts# (Windows refuses it with EPERM)."check:durable-flush"diff --git a/src/core/ai/call-log.ts b/src/core/ai/call-log.tsnew file mode 100644index 0000000000..6297fbd4d9--- /dev/null+++ b/src/core/ai/call-log.ts@@ -0,0 +1,54 @@+/**+ * `GBRAIN_AI_CALL_LOG=<path>`: append one JSON line per model call made by this+ * process (and by child processes, which inherit the variable). The ledger+ * records what was called, by which write request, effect, job or cycle phase,+ * how many tokens the provider reported and how long it took. It never records+ * prompt or response text. Observation does not change how calls execute.+ * Used by write-cost measurements; off unless the variable is set.+ */+import { appendFileSync } from 'node:fs';+import { observeAIInvocations, type AIInvocationEvent } from './invocation-guard.ts';++let installed: { path: string; dispose: () => void } | null = null;+let warned = false;++export function callLogLine(event: AIInvocationEvent): Record<string, unknown> {+ const u = event.usage;+ return {+ ts: new Date(event.startedAt).toISOString(),+ pid: process.pid,+ kind: event.call.kind === 'multimodal' ? 'embedding' : event.call.kind,+ raw_kind: event.call.kind,+ operation: event.call.operation,+ model: event.call.model,+ outcome: event.outcome,+ ms: event.ms,+ input_tokens: u ? u.inputTokens : 'unknown',+ output_tokens: u ? u.outputTokens : 'unknown',+ cache_read_tokens: u ? u.cacheReadTokens ?? 0 : 'unknown',+ cache_write_tokens: u ? u.cacheWriteTokens ?? 0 : 'unknown',+ ...(event.attribution ?? {}),+ };+}++/** Idempotent: re-running with the same path keeps one observer. */+export function installAICallLogFromEnv(env: NodeJS.ProcessEnv = process.env): void {+ const path = env.GBRAIN_AI_CALL_LOG?.trim();+ if (!path) {+ installed?.dispose();+ installed = null;+ return;+ }+ if (installed?.path === path) return;+ installed?.dispose();+ const dispose = observeAIInvocations(event => {+ try { appendFileSync(path, JSON.stringify(callLogLine(event)) + '\n'); }+ catch (error) {+ if (!warned) {+ warned = true;+ process.stderr.write(`[gbrain] GBRAIN_AI_CALL_LOG: cannot write ${path} (${error instanceof Error ? error.message : String(error)}); model-call lines are being dropped. Fix the path or unset the variable.\n`);+ }+ }+ });+ installed = { path, dispose };+}diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.tsindex 8c11167cdb..b2d268ff4b 100644--- a/src/core/ai/gateway.ts+++ b/src/core/ai/gateway.ts@@ -69,6 +69,7 @@ import { redactProviderKeys } from './key-redact.ts';import { reportEmbeddingAuthFailure } from './key-warnings.ts';import { buildGatewayConfig, foldNativeBaseUrlsFromFilePlane } from './build-gateway-config.ts';import { invokeAI, sdkInvocationUsage, responseInvocationUsage, hasAIInvocationGuard, isAIInvocationPolicyError } from './invocation-guard.ts';+import { installAICallLogFromEnv } from './call-log.ts';import { createGuardedGeneration, chatInvocation } from './guarded-generation.ts';installAiSdkWarningWriter();const guardedGeneration = createGuardedGeneration(() => DEFAULT_MAX_OUTPUT_TOKENS);@@ -462,6 +463,7 @@ export function configureGateway(config: AIGatewayConfig): void {// since the last no_key audit row deserves a fresh once-per-process row._noKeyNoticed.clear();warnRecipesMissingBatchTokens();+ installAICallLogFromEnv();}/**diff --git a/src/core/ai/guarded-generation.ts b/src/core/ai/guarded-generation.tsindex d9b32af5da..ac9f55a9ff 100644--- a/src/core/ai/guarded-generation.ts+++ b/src/core/ai/guarded-generation.ts@@ -1,4 +1,4 @@-import { invokeAI, sdkInvocationUsage, hasAIInvocationGuard, type AIInvocation } from './invocation-guard.ts';+import { invokeAI, sdkInvocationUsage, hasAIInvocationGuard, hasAIInvocationObservers, type AIInvocation } from './invocation-guard.ts';import { resolveChatContextTokens } from './model-resolver.ts';export function chatInvocation(operation: string, model: string, maxOutputTokens: number): AIInvocation {@@ -10,7 +10,12 @@ export function chatInvocation(operation: string, model: string, maxOutputTokens/** Each SDK attempt has its own durable hold; local calls keep SDK retries. */export function createGuardedGeneration(defaultMaxOutputTokens: () => number) {return async function guardedGeneration<T>(model: string, transport: (opts: any) => Promise<T>, opts: any): Promise<T> {- if (!hasAIInvocationGuard()) return transport(opts);+ if (!hasAIInvocationGuard()) {+ if (!hasAIInvocationObservers()) return transport(opts);+ // Observed but unguarded: the transport sees the caller's options unchanged (SDK retries, token defaults).+ return invokeAI({ ...chatInvocation('gateway.generate', model, opts.maxOutputTokens ?? defaultMaxOutputTokens()) },+ () => transport(opts), sdkInvocationUsage);+ }const maxOutputTokens = opts.maxOutputTokens ?? defaultMaxOutputTokens();return invokeAI({ ...chatInvocation('gateway.generate', model, maxOutputTokens),cacheWriteTtl: opts.providerOptions?.anthropic?.cacheControl?.ttl ?? '5m' },diff --git a/src/core/ai/invocation-guard.ts b/src/core/ai/invocation-guard.tsindex c5c80520a6..ac0bfc5fc0 100644--- a/src/core/ai/invocation-guard.ts+++ b/src/core/ai/invocation-guard.ts@@ -3,7 +3,7 @@ import { AsyncLocalStorage } from 'node:async_hooks';export interface AIInvocation {operation: string;model: string;- kind: 'chat' | 'embedding' | 'rerank' | 'multimodal' | 'decide';+ kind: 'chat' | 'embedding' | 'rerank' | 'multimodal' | 'decide' | 'transcription';maxInputTokens?: number;maxOutputTokens?: number;cacheWriteTtl?: '5m' | '1h';@@ -45,12 +45,83 @@ export function withAIInvocationPreflight<T>(preflight: (call: AIInvocation) =>}export function hasAIInvocationGuard(): boolean { return guards.getStore() !== undefined; }+/**+ * Who a model call is for: the write request, effect, job or cycle phase that+ * caused it. Set by the persistence effect dispatcher, the facts queue, the job+ * worker and the cycle runner; read by invocation observers.+ */+export interface AIAttribution {+ request_id?: string;+ effect?: string;+ job_id?: number | string;+ job_name?: string;+ phase?: string;+}+const attributions = new AsyncLocalStorage<AIAttribution>();++/** Run `fn` with `patch` merged over the current attribution. */+export function withAIAttribution<T>(patch: AIAttribution, fn: () => T): T {+ return attributions.run({ ...attributions.getStore(), ...patch }, fn);+}+export function currentAIAttribution(): AIAttribution | null { return attributions.getStore() ?? null; }++/**+ * One observed model call. Observation never changes execution: retries,+ * token defaults and admission behave exactly as with no observer installed.+ * Usage is the provider-reported usage of the call's final attempt.+ */+export interface AIInvocationEvent {+ call: AIInvocation;+ outcome: 'ok' | 'error' | 'refused';+ usage: AIInvocationUsage | null;+ startedAt: number;+ ms: number;+ attribution: AIAttribution | null;+}+export type AIInvocationObserver = (event: AIInvocationEvent) => void;+const observers = new Set<AIInvocationObserver>();+let observerFailures = 0;++/** Register an observer of every model call in this process. Returns its disposer; adding the same function twice is a no-op. */+export function observeAIInvocations(observer: AIInvocationObserver): () => void {+ observers.add(observer);+ return () => { observers.delete(observer); };+}+export function hasAIInvocationObservers(): boolean { return observers.size > 0; }+/** Observer throws are swallowed and counted here, never surfaced to the call. */+export function aiInvocationObserverFailures(): number { return observerFailures; }++function notifyObservers(event: AIInvocationEvent): void {+ for (const observer of observers) {+ try { observer(event); } catch { observerFailures += 1; }+ }+}+/*** One provider attempt. No guessed usage, no release on an ambiguous failure:* a failed attempt settles null (keep the maximum) unless `rejected` proves the* provider refused the request unbilled.*/export async function invokeAI<T>(call: AIInvocation, run: () => Promise<T>, usage: (result: T) => AIInvocationUsage | null | Promise<AIInvocationUsage | null>,+ rejected?: (error: unknown) => AIInvocationUsage | null): Promise<T> {+ if (observers.size === 0) return admitAndRun(call, run, usage, rejected);+ const startedAt = Date.now();+ let outcome: AIInvocationEvent['outcome'] = 'error';+ let measured: AIInvocationUsage | null = null;+ try {+ const result = await admitAndRun(call, run, usage, rejected);+ outcome = 'ok';+ try { measured = await usage(result); } catch { measured = null; }+ return result;+ } catch (error) {+ if (isAIInvocationPolicyError(error)) outcome = 'refused';+ throw error;+ } finally {+ notifyObservers({ call, outcome, usage: measured, startedAt, ms: Date.now() - startedAt, attribution: currentAIAttribution() });+ }+}++async function admitAndRun<T>(call: AIInvocation, run: () => Promise<T>, usage: (result: T) => AIInvocationUsage | null | Promise<AIInvocationUsage | null>,rejected?: (error: unknown) => AIInvocationUsage | null): Promise<T> {const guard = guards.getStore();if (!guard) return run();diff --git a/src/core/cycle/phase-containment.ts b/src/core/cycle/phase-containment.tsindex 4ddbb23069..a46a38ce35 100644--- a/src/core/cycle/phase-containment.ts+++ b/src/core/cycle/phase-containment.ts@@ -13,6 +13,7 @@ import type { CyclePhase, PhaseResult } from '../cycle.ts';import { LockStolenError } from '../db-lock.ts';import { BudgetExhausted } from '../budget/budget-tracker.ts';import { withChatCallMeter } from '../ai/chat-usage.ts';+import { withAIAttribution } from '../ai/invocation-guard.ts';import { recordContainedPaidFailure } from './dream-breaker.ts';import { cliRenderContext, toAgentError, type RenderedAction } from '../agent-output.ts';@@ -39,7 +40,7 @@ export async function timeContainedPhase<T extends PhaseResult>(containment: Phaconst start = performance.now();const meter = { calls: 0 };try {- const result = await withChatCallMeter(meter, fn);+ const result = await withAIAttribution({ phase: `cycle:${phase}` }, () => withChatCallMeter(meter, fn));return { result, duration_ms: Math.round(performance.now() - start) };} catch (error) {if (isUncontainedPhaseError(error, containment.signal)) throw error;diff --git a/src/core/facts/queue.ts b/src/core/facts/queue.tsindex 723a0fc279..4c6b284a66 100644--- a/src/core/facts/queue.ts+++ b/src/core/facts/queue.ts@@ -18,6 +18,7 @@* concurrency + dropping under load.*/+import { currentAIAttribution, withAIAttribution, type AIAttribution } from '../ai/invocation-guard.ts';import { registerBackgroundWorkDrainer } from '../background-work.ts';export interface FactsQueueCounters {@@ -46,6 +47,8 @@ interface QueueEntry {job: FactsJob;sessionId: string;enqueuedAt: number;+ /** Model calls the job makes are attributed to whoever enqueued it. */+ attribution: AIAttribution;}export class FactsQueue {@@ -100,7 +103,7 @@ export class FactsQueue {this.pending.shift();this.counters.dropped_overflow += 1;}- this.pending.push({ job, sessionId, enqueuedAt: Date.now() });+ this.pending.push({ job, sessionId, enqueuedAt: Date.now(), attribution: { ...currentAIAttribution(), effect: 'facts-queue' } });this.counters.enqueued += 1;// Non-blocking pump: schedule on microtask so callers stay sync.queueMicrotask(() => { void this.pump(); });@@ -214,7 +217,7 @@ export class FactsQueue {private async runEntry(entry: QueueEntry): Promise<void> {try {- await entry.job(this.internalAbort.signal);+ await withAIAttribution(entry.attribution, () => entry.job(this.internalAbort.signal));this.counters.completed += 1;} catch (err) {// Don't propagate; caller sees nothing — the queue surface is fire-and-diff --git a/src/core/minions/handlers/facts-absorb.ts b/src/core/minions/handlers/facts-absorb.tsindex 7a806de085..4520c336e9 100644--- a/src/core/minions/handlers/facts-absorb.ts+++ b/src/core/minions/handlers/facts-absorb.ts@@ -1,6 +1,7 @@/*** `facts-absorb` Minion job handler (built-in; registered by registerBuiltinHandlers in src/commands/jobs.ts).*/+import { withAIAttribution } from '../../ai/invocation-guard.ts';import type { BrainEngine } from '../../engine.ts';import type { MinionHandler } from '../types.ts';import { loadConfig, loadConfigWithEngine } from '../../config.ts';@@ -43,7 +44,7 @@ export function factsAbsorbShouldRetry(* (llm-halt-cooldown.ts) — a globally-broken provider defers the queue.*/export function makeFactsAbsorbHandler(engine: BrainEngine): MinionHandler {- return async (job) => {+ const handle: MinionHandler = async (job) => {const slug = typeof job.data.slug === 'string' ? job.data.slug : '';if (!slug) throw new Error('facts-absorb job requires data.slug');const sourceId = typeof job.data.sourceId === 'string' ? job.data.sourceId : 'default';@@ -116,4 +117,6 @@ export function makeFactsAbsorbHandler(engine: BrainEngine): MinionHandler {}return result;};+ return job => withAIAttribution({ effect: 'facts-absorb', job_id: job.id, job_name: job.name,+ ...(typeof job.data.persistence_request_id === 'string' ? { request_id: job.data.persistence_request_id } : {}) }, () => handle(job));}diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.tsindex 4669544033..ff31fad402 100644--- a/src/core/persistence/effects.ts+++ b/src/core/persistence/effects.ts@@ -1,3 +1,4 @@+import { withAIAttribution } from '../ai/invocation-guard.ts';import { randomUUID } from 'node:crypto';import { targetedWithdrawalEffect, upgradeWithdrawalEffect } from './effect-targets.ts';import { existsSync, statSync } from 'node:fs';@@ -504,8 +505,9 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainCeffect = await upgradeWithdrawalEffect(engine, effect, opts.hostId);if (effect.kind === 'withdrawal-mirror') await mirrorPage(engine, effect, binding, opts, attempt);else if (effect.kind === 'git') await gitPage(engine, effect, binding, opts, attempt, hardened);- else if (effect.kind === 'facts-backstop') await dispatchFactsBackstopEffect(engine, effect, opts.hostId);- else await embedPage(engine, config, effect, opts);+ else await withAIAttribution({ request_id: effect.request_id, effect: effect.kind }, () => effect.kind === 'facts-backstop'+ ? dispatchFactsBackstopEffect(engine, effect, opts.hostId)+ : embedPage(engine, config, effect, opts));} catch (error) { await recordFailure(engine, effect, error, opts.signal, attempt.target); }finally { await lock?.release(); }};diff --git a/src/core/transcription.ts b/src/core/transcription.tsindex e87efdbb44..24cf4e3c96 100644--- a/src/core/transcription.ts+++ b/src/core/transcription.ts@@ -8,6 +8,7 @@import { statSync, readFileSync, rmSync } from 'fs';import { basename, extname, join } from 'path';+import { invokeAI } from './ai/invocation-guard.ts';// ---------------------------------------------------------------------------// Types@@ -124,11 +125,12 @@ async function transcribeFile(formData.append('response_format', 'verbose_json');if (config.language) formData.append('language', config.language);- const response = await fetch(`${baseUrl}/audio/transcriptions`, {- method: 'POST',- headers: { 'Authorization': `Bearer ${apiKey}` },- body: formData,- });+ const response = await invokeAI({ operation: 'transcription', kind: 'transcription', model: `${provider}:${model}` },+ () => fetch(`${baseUrl}/audio/transcriptions`, {+ method: 'POST',+ headers: { 'Authorization': `Bearer ${apiKey}` },+ body: formData,+ }), () => null);if (!response.ok) {const errorText = await response.text();diff --git a/test/ai-call-log.test.ts b/test/ai-call-log.test.tsnew file mode 100644index 0000000000..d9db98a019--- /dev/null+++ b/test/ai-call-log.test.ts@@ -0,0 +1,57 @@+import { afterEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, readFileSync, rmSync, existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { installAICallLogFromEnv } from '../src/core/ai/call-log.ts';+import { invokeAI, sdkInvocationUsage, withAIAttribution } from '../src/core/ai/invocation-guard.ts';++const dirs: string[] = [];+afterEach(() => {+ installAICallLogFromEnv({});+ while (dirs.length) rmSync(dirs.pop()!, { recursive: true, force: true });+});++function tempPath(): string {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-call-log-'));+ dirs.push(dir);+ return join(dir, 'calls.jsonl');+}++describe('GBRAIN_AI_CALL_LOG', () => {+ test('one JSON line per call with kind, usage and attribution, never prompt text', async () => {+ const path = tempPath();+ installAICallLogFromEnv({ GBRAIN_AI_CALL_LOG: path });+ installAICallLogFromEnv({ GBRAIN_AI_CALL_LOG: path });+ await withAIAttribution({ request_id: 'req-1', effect: 'facts-absorb', job_id: 3 }, () =>+ invokeAI({ operation: 'gateway.chat', kind: 'chat', model: 'anthropic:claude-sonnet-4-6' },+ async () => ({ text: 'SECRET PROMPT ECHO', usage: { inputTokens: 100, outputTokens: 20 } }), sdkInvocationUsage));+ await invokeAI({ operation: 'gateway.multimodal', kind: 'multimodal', model: 'voyage:voyage-multimodal-3' }, async () => ({}), () => null);+ const raw = readFileSync(path, 'utf8');+ expect(raw).not.toContain('SECRET');+ const lines = raw.trim().split('\n').map(l => JSON.parse(l));+ expect(lines).toHaveLength(2);+ expect(lines[0]).toMatchObject({ kind: 'chat', operation: 'gateway.chat', outcome: 'ok', input_tokens: 100, output_tokens: 20,+ request_id: 'req-1', effect: 'facts-absorb', job_id: 3 });+ expect(lines[1]).toMatchObject({ kind: 'embedding', raw_kind: 'multimodal', input_tokens: 'unknown' });+ });++ test('unset disposes the observer', async () => {+ const path = tempPath();+ installAICallLogFromEnv({ GBRAIN_AI_CALL_LOG: path });+ installAICallLogFromEnv({});+ await invokeAI({ operation: 'gateway.chat', kind: 'chat', model: 'm' }, async () => 1, () => null);+ expect(existsSync(path)).toBe(false);+ });++ test('an unwritable path warns once and never fails the call', async () => {+ const writes: string[] = [];+ const orig = process.stderr.write.bind(process.stderr);+ process.stderr.write = ((c: string) => { writes.push(String(c)); return true; }) as typeof process.stderr.write;+ try {+ installAICallLogFromEnv({ GBRAIN_AI_CALL_LOG: join(tempPath(), 'missing-dir', 'x.jsonl') });+ await expect(invokeAI({ operation: 'gateway.chat', kind: 'chat', model: 'm' }, async () => 'ok', () => null)).resolves.toBe('ok');+ await invokeAI({ operation: 'gateway.chat', kind: 'chat', model: 'm' }, async () => 'ok', () => null);+ } finally { process.stderr.write = orig; }+ expect(writes.filter(w => w.includes('GBRAIN_AI_CALL_LOG')).length).toBeLessThanOrEqual(1);+ });+});diff --git a/test/ai-invocation-observer.test.ts b/test/ai-invocation-observer.test.tsnew file mode 100644index 0000000000..4391bb6ca7--- /dev/null+++ b/test/ai-invocation-observer.test.ts@@ -0,0 +1,92 @@+import { afterEach, describe, expect, test } from 'bun:test';+import {+ aiInvocationObserverFailures,+ currentAIAttribution,+ invokeAI,+ observeAIInvocations,+ sdkInvocationUsage,+ withAIAttribution,+ withAIInvocationGuard,+ type AIInvocationEvent,+} from '../src/core/ai/invocation-guard.ts';+import { createGuardedGeneration } from '../src/core/ai/guarded-generation.ts';++const disposers: Array<() => void> = [];+afterEach(() => { while (disposers.length) disposers.pop()!(); });++function observe(): AIInvocationEvent[] {+ const events: AIInvocationEvent[] = [];+ disposers.push(observeAIInvocations(e => { events.push(e); }));+ return events;+}++const chat = { operation: 'test.chat', kind: 'chat' as const, model: 'anthropic:claude-sonnet-4-6' };++describe('invocation observers', () => {+ test('an unguarded call is observed with its usage and outcome', async () => {+ const events = observe();+ await invokeAI(chat, async () => ({ usage: { inputTokens: 10, outputTokens: 3 } }), sdkInvocationUsage);+ await expect(invokeAI(chat, async () => { throw new Error('boom'); }, sdkInvocationUsage)).rejects.toThrow('boom');+ expect(events.map(e => e.outcome)).toEqual(['ok', 'error']);+ expect(events[0]!.usage).toEqual({ inputTokens: 10, outputTokens: 3, cacheReadTokens: 0, cacheWriteTokens: 0 });+ expect(events[1]!.usage).toBeNull();+ });++ test('a guard refusal is observed as refused and still throws', async () => {+ const events = observe();+ await expect(withAIInvocationGuard(async () => { throw new Error('over budget'); },+ () => invokeAI(chat, async () => 'never', () => null))).rejects.toThrow('over budget');+ expect(events.map(e => e.outcome)).toEqual(['refused']);+ });++ test('observation leaves generation options untouched; a guard still pins its own', async () => {+ const seen: any[] = [];+ const generate = createGuardedGeneration(() => 4096);+ const transport = async (opts: any) => { seen.push(opts); return { usage: { inputTokens: 1, outputTokens: 1 } }; };+ const events = observe();+ await generate('anthropic:claude-sonnet-4-6', transport, { prompt: 'x' });+ expect(seen[0]).toEqual({ prompt: 'x' });+ expect(events).toHaveLength(1);+ await withAIInvocationGuard(async () => ({ settle: async () => {} }),+ () => generate('anthropic:claude-sonnet-4-6', transport, { prompt: 'y' }));+ expect(seen[1]).toMatchObject({ prompt: 'y', maxRetries: 0, maxOutputTokens: 4096 });+ });++ test('without observers the transport is called directly with the caller options', async () => {+ const seen: any[] = [];+ await createGuardedGeneration(() => 4096)('m', async (opts: any) => { seen.push(opts); return {}; }, { prompt: 'z' });+ expect(seen[0]).toEqual({ prompt: 'z' });+ });++ test('a throwing observer never reaches the call; failures are counted', async () => {+ const before = aiInvocationObserverFailures();+ disposers.push(observeAIInvocations(() => { throw new Error('observer bug'); }));+ const events = observe();+ await expect(invokeAI(chat, async () => 'ok', () => null)).resolves.toBe('ok');+ expect(aiInvocationObserverFailures()).toBe(before + 1);+ expect(events).toHaveLength(1);+ });++ test('adding the same observer twice registers it once; dispose removes it', async () => {+ const events: AIInvocationEvent[] = [];+ const fn = (e: AIInvocationEvent) => { events.push(e); };+ const d1 = observeAIInvocations(fn);+ observeAIInvocations(fn);+ await invokeAI(chat, async () => 1, () => null);+ expect(events).toHaveLength(1);+ d1();+ await invokeAI(chat, async () => 1, () => null);+ expect(events).toHaveLength(1);+ });++ test('attribution nests by merging and rides on observed events', async () => {+ const events = observe();+ await withAIAttribution({ request_id: 'r1', effect: 'facts-backstop' }, () =>+ withAIAttribution({ job_id: 7 }, async () => {+ expect(currentAIAttribution()).toEqual({ request_id: 'r1', effect: 'facts-backstop', job_id: 7 });+ await invokeAI(chat, async () => 1, () => null);+ }));+ expect(events[0]!.attribution).toEqual({ request_id: 'r1', effect: 'facts-backstop', job_id: 7 });+ expect(currentAIAttribution()).toBeNull();+ });+});diff --git a/test/fixtures/guards/check-ai-sdk-importers.ts/bad/scripts/ai-sdk-importers.allowlist b/test/fixtures/guards/check-ai-sdk-importers.ts/bad/scripts/ai-sdk-importers.allowlistnew file mode 100644index 0000000000..326803c037--- /dev/null+++ b/test/fixtures/guards/check-ai-sdk-importers.ts/bad/scripts/ai-sdk-importers.allowlist@@ -0,0 +1 @@+src/core/ai/gateway.tsdiff --git a/test/fixtures/guards/check-ai-sdk-importers.ts/bad/src/core/ai/gateway.ts b/test/fixtures/guards/check-ai-sdk-importers.ts/bad/src/core/ai/gateway.tsnew file mode 100644index 0000000000..98bd4843d4--- /dev/null+++ b/test/fixtures/guards/check-ai-sdk-importers.ts/bad/src/core/ai/gateway.ts@@ -0,0 +1,2 @@+import { generateText } from 'ai';+export const g = generateText;diff --git a/test/fixtures/guards/check-ai-sdk-importers.ts/bad/src/core/writer.ts b/test/fixtures/guards/check-ai-sdk-importers.ts/bad/src/core/writer.tsnew file mode 100644index 0000000000..1b26e70d5c--- /dev/null+++ b/test/fixtures/guards/check-ai-sdk-importers.ts/bad/src/core/writer.ts@@ -0,0 +1,2 @@+import Anthropic from '@anthropic-ai/sdk';+export const client = () => new Anthropic();diff --git a/test/fixtures/guards/check-ai-sdk-importers.ts/good/scripts/ai-sdk-importers.allowlist b/test/fixtures/guards/check-ai-sdk-importers.ts/good/scripts/ai-sdk-importers.allowlistnew file mode 100644index 0000000000..326803c037--- /dev/null+++ b/test/fixtures/guards/check-ai-sdk-importers.ts/good/scripts/ai-sdk-importers.allowlist@@ -0,0 +1 @@+src/core/ai/gateway.tsdiff --git a/test/fixtures/guards/check-ai-sdk-importers.ts/good/src/core/ai/gateway.ts b/test/fixtures/guards/check-ai-sdk-importers.ts/good/src/core/ai/gateway.tsnew file mode 100644index 0000000000..98bd4843d4--- /dev/null+++ b/test/fixtures/guards/check-ai-sdk-importers.ts/good/src/core/ai/gateway.ts@@ -0,0 +1,2 @@+import { generateText } from 'ai';+export const g = generateText;diff --git a/test/fixtures/guards/check-ai-sdk-importers.ts/good/src/core/ai/providers/cli.ts b/test/fixtures/guards/check-ai-sdk-importers.ts/good/src/core/ai/providers/cli.tsnew file mode 100644index 0000000000..94e13c732b--- /dev/null+++ b/test/fixtures/guards/check-ai-sdk-importers.ts/good/src/core/ai/providers/cli.ts@@ -0,0 +1,2 @@+import type { LanguageModelV2 } from '@ai-sdk/provider';+export type M = LanguageModelV2;diff --git a/test/fixtures/guards/check-layering.ts/bad-persistence/src/core/ai/gateway.ts b/test/fixtures/guards/check-layering.ts/bad-persistence/src/core/ai/gateway.tsnew file mode 100644index 0000000000..19ca95a7e9--- /dev/null+++ b/test/fixtures/guards/check-layering.ts/bad-persistence/src/core/ai/gateway.ts@@ -0,0 +1 @@+export const chat = () => 'model';diff --git a/test/fixtures/guards/check-layering.ts/bad-persistence/src/core/persistence/page-prepare.ts b/test/fixtures/guards/check-layering.ts/bad-persistence/src/core/persistence/page-prepare.tsnew file mode 100644index 0000000000..b23f8c319a--- /dev/null+++ b/test/fixtures/guards/check-layering.ts/bad-persistence/src/core/persistence/page-prepare.ts@@ -0,0 +1,2 @@+import { chat } from '../ai/gateway.ts';+export const prepare = () => chat();diff --git a/test/fixtures/guards/check-layering.ts/good/src/core/embedding.ts b/test/fixtures/guards/check-layering.ts/good/src/core/embedding.tsnew file mode 100644index 0000000000..7e5085403a--- /dev/null+++ b/test/fixtures/guards/check-layering.ts/good/src/core/embedding.ts@@ -0,0 +1 @@+export const embedBatch = () => [];diff --git a/test/fixtures/guards/check-layering.ts/good/src/core/persistence/page-prepare.ts b/test/fixtures/guards/check-layering.ts/good/src/core/persistence/page-prepare.tsnew file mode 100644index 0000000000..b00a1c0afb--- /dev/null+++ b/test/fixtures/guards/check-layering.ts/good/src/core/persistence/page-prepare.ts@@ -0,0 +1,2 @@+import { embedBatch } from '../embedding.ts';+export const prepare = () => embedBatch;diff --git a/test/helpers/ai-tripwire.ts b/test/helpers/ai-tripwire.tsnew file mode 100644index 0000000000..8e572eb289--- /dev/null+++ b/test/helpers/ai-tripwire.ts@@ -0,0 +1,49 @@+/**+ * Records every model call and every outbound network request a test makes.+ *+ * The invocation observer is the proof: every provider call routes through+ * `invokeAI` (scripts/check-ai-sdk-importers.sh keeps it that way), including+ * subprocess providers. The fetch wrapper is a second net for anything that+ * bypasses it; it records the request and then fails it, so nothing leaves the+ * machine. Tests assert on the records, never on a thrown error, because+ * best-effort catch blocks on write paths would swallow the throw.+ */+import { observeAIInvocations, type AIInvocationEvent } from '../../src/core/ai/invocation-guard.ts';++export const EMBEDDING_KINDS = new Set(['embedding', 'multimodal']);++export interface Tripwire {+ events: AIInvocationEvent[];+ egress: string[];+ /** Model calls that are not embeddings (chat, generate, rerank, decide, transcription). */+ generative(): AIInvocationEvent[];+ reset(): void;+ dispose(): void;+}++export function installTripwire(opts: { allowHosts?: string[] } = {}): Tripwire {+ const events: AIInvocationEvent[] = [];+ const egress: string[] = [];+ const disposeObserver = observeAIInvocations(event => { events.push(event); });+ const originalFetch = globalThis.fetch;+ const allow = new Set(opts.allowHosts ?? []);+ const wrapped = (async (input: string | URL | Request, init?: RequestInit) => {+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;+ let host = '';+ try { host = new URL(url).host; } catch { host = url; }+ if (allow.has(host)) return originalFetch(input as never, init);+ egress.push(url);+ throw new Error(`tripwire: outbound request to ${url} blocked in a hermetic test`);+ }) as typeof fetch;+ globalThis.fetch = wrapped;+ return {+ events,+ egress,+ generative: () => events.filter(e => !EMBEDDING_KINDS.has(e.call.kind)),+ reset() { events.length = 0; egress.length = 0; },+ dispose() {+ disposeObserver();+ if (globalThis.fetch === wrapped) globalThis.fetch = originalFetch;+ },+ };+}diff --git a/test/op-write-inference.test.ts b/test/op-write-inference.test.tsnew file mode 100644index 0000000000..bd2050fa8c--- /dev/null+++ b/test/op-write-inference.test.ts@@ -0,0 +1,37 @@+import { describe, expect, test } from 'bun:test';+import { operations, operationsByName } from '../src/core/operations.ts';+import {+ CLI_WRITE_INFERENCE,+ OP_WRITE_INFERENCE,+ WRITE_INFERENCE_CLASSES,+ writeInferenceOf,+} from '../src/core/ops/write-inference.ts';++describe('write-inference classes', () => {+ test('every map entry names an existing mutating op with a known class', () => {+ for (const [name, cls] of Object.entries(OP_WRITE_INFERENCE)) {+ expect(WRITE_INFERENCE_CLASSES).toContain(cls);+ expect(operationsByName[name]).toBeDefined();+ expect(operationsByName[name]!.mutating).toBe(true);+ }+ for (const cls of Object.values(CLI_WRITE_INFERENCE)) expect(WRITE_INFERENCE_CLASSES).toContain(cls);+ });++ test('an unclassified op resolves to the strictest class; inline wins over the map', () => {+ expect(writeInferenceOf({ name: 'some_future_write' })).toBe('none');+ expect(writeInferenceOf({ name: 'think' })).toBe('explicit_llm');+ expect(writeInferenceOf({ name: 'think', writeInference: 'none' })).toBe('none');+ });++ test('inline classes on ops are valid', () => {+ for (const op of operations) {+ if (op.writeInference !== undefined) expect(WRITE_INFERENCE_CLASSES).toContain(op.writeInference);+ }+ });++ test('the memory write verbs keep their promises', () => {+ expect(writeInferenceOf(operationsByName.remember!)).toBe('embedding');+ expect(writeInferenceOf(operationsByName.forget!)).toBe('none');+ expect(writeInferenceOf(operationsByName.put_page!)).toBe('async_derived');+ });+});diff --git a/test/scripts/ai-sdk-importers.test.ts b/test/scripts/ai-sdk-importers.test.tsnew file mode 100644index 0000000000..765387e605--- /dev/null+++ b/test/scripts/ai-sdk-importers.test.ts@@ -0,0 +1,56 @@+/**+ * scripts/check-ai-sdk-importers.ts keeps provider SDK imports inside the+ * allowlist, so every model call stays observable through invokeAI.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';++const REPO = resolve(import.meta.dir, '..', '..');+const GUARD = join(REPO, 'scripts', 'check-ai-sdk-importers.ts');+const dirs: string[] = [];+afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); });++function run(files: Record<string, string>) {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-sdk-guard-'));+ dirs.push(root);+ for (const [rel, body] of Object.entries(files)) {+ mkdirSync(join(root, rel, '..'), { recursive: true });+ writeFileSync(join(root, rel), body);+ }+ const r = spawnSync('bun', [GUARD], { encoding: 'utf8', env: { ...process.env, GBRAIN_GUARD_ROOT: root } });+ return { code: r.status, out: `${r.stdout}\n${r.stderr}` };+}++describe('check-ai-sdk-importers.ts', () => {+ test.each([+ ['named import', "import { generateText } from 'ai';"],+ ['default import', "import Anthropic from '@anthropic-ai/sdk';"],+ ['provider package', "import { createOpenAI } from '@ai-sdk/openai';"],+ ['dynamic import', "export const f = () => import('openai');"],+ ['require', "export const f = () => require('ai');"],+ ['multi-line import', "import {\n embedMany,\n} from 'ai';"],+ ])('%s outside the allowlist fails with FAIL/Fix/Why/See', (_label, line) => {+ const r = run({ 'scripts/ai-sdk-importers.allowlist': 'src/core/ai/gateway.ts\n', 'src/core/ai/gateway.ts': "import { generateText } from 'ai';\n", 'src/core/new-writer.ts': line + '\n' });+ expect(r.code).toBe(1);+ expect(r.out).toContain('FAIL: src/core/new-writer.ts');+ for (const label of ['Fix:', 'Why:', 'See: docs/TESTING.md#ai-sdk-importer-guard']) expect(r.out).toContain(label);+ });++ test('type-only imports and allowlisted importers pass', () => {+ const r = run({+ 'scripts/ai-sdk-importers.allowlist': '# comment\nsrc/core/ai/gateway.ts\n',+ 'src/core/ai/gateway.ts': "import { generateText } from 'ai';\n",+ 'src/core/ai/providers/cli.ts': "import type { LanguageModelV2 } from '@ai-sdk/provider';\nimport { type JSONSchema7 } from 'ai';\n",+ });+ expect(r.code).toBe(0);+ });++ test('a stale allowlist line fails', () => {+ const r = run({ 'scripts/ai-sdk-importers.allowlist': 'src/core/ai/gateway.ts\nsrc/core/old.ts\n', 'src/core/ai/gateway.ts': "import { generateText } from 'ai';\n" });+ expect(r.code).toBe(1);+ expect(r.out).toContain('lists src/core/old.ts');+ });+});diff --git a/test/scripts/layering.test.ts b/test/scripts/layering.test.tsindex 94344a5879..6ad8605039 100644--- a/test/scripts/layering.test.ts+++ b/test/scripts/layering.test.ts@@ -1,7 +1,9 @@/*** T-G9 (refactor wave 1, EO10): scripts/check-layering.ts keeps* src/core/engine-sql/ from importing an engine façade and- * src/core/schema-migrations/ from importing migrate.ts, in every import form.+ * src/core/schema-migrations/ from importing migrate.ts, and the write commit+ * path in src/core/persistence/ from importing the model gateway, in every+ * import form.*/import { afterEach, describe, expect, test } from 'bun:test';import { spawnSync } from 'node:child_process';@@ -47,6 +49,12 @@ describe('check-layering.ts', () => {expect(r.out).toContain('imports src/core/migrate.ts');});+ test('persistence: importing the model gateway fails', () => {+ const r = run({ 'src/core/persistence/page-prepare.ts': "export const f = () => import('../ai/gateway.ts');\n" });+ expect(r.code).toBe(1);+ expect(r.out).toContain('imports src/core/ai/gateway.ts');+ });+test('allowed edges pass: engine.ts types, sql-query.ts, sibling helpers, packages', () => {const r = run({'src/core/engine-sql/facts.ts': "import type { BrainEngine } from '../engine.ts';\nimport { executeRawJsonb } from '../sql-query.ts';\nimport ts from 'typescript';\n",diff --git a/test/write-path-no-egress.serial.test.ts b/test/write-path-no-egress.serial.test.tsnew file mode 100644index 0000000000..07c56c6d7f--- /dev/null+++ b/test/write-path-no-egress.serial.test.ts@@ -0,0 +1,105 @@+/**+ * Real CLI writes on a keyless brain leave the machine for nothing.+ *+ * Each write runs as its own `gbrain` process (and any child process it+ * starts inherits the environment) with HTTP_PROXY / HTTPS_PROXY pointed at a+ * local recorder that logs every connection and refuses it. Chat keys are+ * present, so key-gated model paths are live. The commit must succeed, and+ * the recorder must see zero connections. This catches transports the+ * in-process tripwire cannot see. The first case proves the recorder is live.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';+import { createServer, type Server } from 'node:net';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { makeGitFixture } from './helpers/git-fixture.ts';++const REPO = resolve(import.meta.dir, '..');+const CLI = join(REPO, 'src', 'cli.ts');+let home: string;+let proxy: Server;+let proxyUrl = '';+const connections: string[] = [];++function env(extra: Record<string, string> = {}): Record<string, string> {+ return {+ ...process.env as Record<string, string>,+ GBRAIN_HOME: home, ANTHROPIC_API_KEY: 'sk-ant-test', OPENAI_API_KEY: 'sk-test-fake',+ HTTP_PROXY: proxyUrl, HTTPS_PROXY: proxyUrl, http_proxy: proxyUrl, https_proxy: proxyUrl, NO_PROXY: '', no_proxy: '',+ DATABASE_URL: '', GBRAIN_DATABASE_URL: '', ...extra,+ };+}++/** Async spawn: the recorder lives in this process, so the event loop must stay free. */+async function run(cmd: string[], input?: string): Promise<{ code: number; out: string }> {+ const proc = Bun.spawn(cmd, { env: env(), stdin: input === undefined ? 'ignore' : new TextEncoder().encode(input), stdout: 'pipe', stderr: 'pipe' });+ const timer = setTimeout(() => proc.kill(), 120_000);+ const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);+ clearTimeout(timer);+ return { code, out: `${stdout}\n${stderr}` };+}++const gbrain = (args: string[], input?: string) => run(['bun', CLI, ...args], input);++beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-no-egress-'));+ proxy = createServer(socket => {+ socket.once('data', chunk => {+ connections.push(chunk.toString('latin1').split('\r\n')[0] ?? '');+ socket.end('HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n');+ });+ });+ await new Promise<void>(r => proxy.listen(0, '127.0.0.1', r));+ const addr = proxy.address();+ proxyUrl = `http://127.0.0.1:${typeof addr === 'object' && addr ? addr.port : 0}`;+ const init = await gbrain(['init', '--pglite', '--no-embedding']);+ if (init.code !== 0) throw new Error(`init failed: ${init.out}`);+}, 180_000);++afterAll(() => {+ proxy?.close();+ rmSync(home, { recursive: true, force: true });+});++const NOTE = '---\ntype: meeting\ntitle: Roadmap\n---\nA substantive meeting note about the quarterly roadmap with acme-example. '.padEnd(400, 'More detail. ');++describe('CLI writes make no network connection', () => {+ test('the recorder sees a child process that does reach for the network', async () => {+ connections.length = 0;+ await run(['bun', '-e', "await fetch('https://api.anthropic.com/v1/messages').catch(() => {})"]);+ expect(connections.some(c => c.includes('api.anthropic.com'))).toBe(true);+ }, 60_000);++ test('put, remember, link, timeline-add, import, sync', async () => {+ connections.length = 0;+ const steps: Array<[string[], string | undefined]> = [+ [['put', 'meetings/roadmap'], NOTE],+ [['put', 'companies/acme-example'], '---\ntype: company\ntitle: Acme Example\n---\nA company.'],+ [['remember', 'Alice Example prefers async standups.', '--provenance', 'test', '--entity', 'companies/acme-example'], undefined],+ [['link', 'meetings/roadmap', 'companies/acme-example'], undefined],+ [['timeline-add', 'companies/acme-example', '2026-09-01', 'Signed the pilot.'], undefined],+ ];+ for (const [args, input] of steps) {+ const r = await gbrain(args, input);+ if (r.code !== 0) throw new Error(`gbrain ${args.join(' ')} exited ${r.code}: ${r.out}`);+ }+ const dir = join(home, 'notes');+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'imported.md'), NOTE);+ const imp = await gbrain(['import', dir, '--no-embed']);+ if (imp.code !== 0) throw new Error(`gbrain import exited ${imp.code}: ${imp.out}`);+ const repo = join(home, 'repo');+ mkdirSync(repo, { recursive: true });+ const fixture = await makeGitFixture(repo);+ writeFileSync(join(repo, 'synced.md'), NOTE.replace('title: Roadmap', 'title: Synced'));+ fixture.commitAll('add synced note');+ for (const args of [['sources', 'add', 'synced', '--path', repo], ['sync', '--source', 'synced', '--no-pull', '--no-embed']]) {+ const r = await gbrain(args);+ if (r.code !== 0) throw new Error(`gbrain ${args.join(' ')} exited ${r.code}: ${r.out}`);+ }+ expect(connections).toEqual([]);+ const search = await gbrain(['search', 'quarterly roadmap']);+ expect(search.out).toContain('meetings/roadmap');+ }, 600_000);+});diff --git a/test/write-path-zero-llm.serial.test.ts b/test/write-path-zero-llm.serial.test.tsnew file mode 100644index 0000000000..cc008acc36--- /dev/null+++ b/test/write-path-zero-llm.serial.test.ts@@ -0,0 +1,216 @@+/**+ * The write-inference contract, checked at runtime.+ *+ * Saving text or a fact never waits on a generative model: every write+ * surface commits and is keyword-queryable with zero generative model calls.+ * Embeddings are allowed. Generative work a write triggers (facts extraction)+ * runs after commit, attributed to the job that ran it, and stops when+ * `facts.extraction_enabled` is false.+ *+ * Keys are configured for chat and embeddings so gated paths are live; the+ * chat transport answers with no facts, the embed transport is deterministic, and+ * any outbound request is recorded and blocked.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { operations } from '../src/core/operations.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';+import { localHostId } from '../src/core/persistence/identity.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { registerBuiltinHandlers } from '../src/commands/jobs.ts';+import type { MinionHandler } from '../src/core/minions/types.ts';+import { writeInferenceOf, ZERO_GENERATIVE_BEFORE_COMMIT } from '../src/core/ops/write-inference.ts';+import { installTripwire, type Tripwire } from './helpers/ai-tripwire.ts';++let engine: PGLiteEngine;+let wire: Tripwire;+const PINNED = ['ANTHROPIC_API_KEY', 'OPENAI_API_KEY'] as const;+const saved: Record<string, string | undefined> = {};+const BODY = 'A substantive meeting note about the quarterly roadmap with acme-example. '.repeat(4);++function body(r: { isError?: boolean; content: Array<{ text?: string }> }): Record<string, any> {+ const parsed = JSON.parse(r.content[0]?.text ?? '{}');+ if (r.isError) throw new Error(`tool error: ${JSON.stringify(parsed)}`);+ return parsed;+}++async function call(name: string, params: Record<string, unknown>, remote = false) {+ return body(await dispatchToolCall(engine, name, params, remote+ ? { remote: true, takesHoldersAllowList: ['world'], sourceId: 'default' }+ : { remote: false }));+}++async function drainEffects(): Promise<void> {+ for (let i = 0; i < 5; i++) {+ const n = await runPersistenceEffects(engine, { engine: 'pglite' }, { hostId: localHostId(), limit: 32 });+ if (!n) break;+ }+}++async function runFactsJobs(): Promise<number> {+ const handlers = new Map<string, MinionHandler>();+ await registerBuiltinHandlers({ register: (name: string, handler: MinionHandler) => handlers.set(name, handler) } as never, engine, { quiet: true });+ const jobs = await engine.executeRaw<{ id: number; data: Record<string, unknown> }>(+ "SELECT id,data FROM minion_jobs WHERE name='facts-absorb' AND status IN ('waiting','active','delayed')");+ for (const job of jobs) {+ await handlers.get('facts-absorb')!({+ ...job, name: 'facts-absorb', attempts_made: 0, signal: new AbortController().signal,+ deadlineAtMs: null, shutdownSignal: new AbortController().signal, updateProgress: async () => {},+ updateTokens: async () => {}, log: async () => {}, isActive: async () => true, readInbox: async () => [],+ } as never).catch(() => {});+ await engine.executeRaw("UPDATE minion_jobs SET status='completed' WHERE id=$1", [job.id]);+ }+ return jobs.length;+}++function expectNoGenerative(label: string): void {+ const gen = wire.generative();+ if (gen.length) throw new Error(`${label}: ${gen.length} generative model call(s) before commit: ${gen.map(e => e.call.operation).join(', ')}`);+ expect(wire.egress).toEqual([]);+}++beforeAll(async () => {+ for (const k of PINNED) saved[k] = process.env[k];+ process.env.ANTHROPIC_API_KEY = 'sk-ant-test';+ process.env.OPENAI_API_KEY = 'sk-test-fake';+ configureGateway({+ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536,+ chat_model: 'anthropic:claude-sonnet-4-6',+ env: { ANTHROPIC_API_KEY: 'sk-ant-test', OPENAI_API_KEY: 'sk-test-fake' },+ });+ __setEmbedTransportForTests(async ({ values }: { values: string[] }) => ({+ embeddings: values.map((v, i) => Array.from({ length: 1536 }, (_, j) => ((v.length + i + j) % 7) / 7 + 0.01)),+ usage: { tokens: values.length * 4 },+ }) as never);+ __setChatTransportForTests(async () => ({+ text: '{"facts":[]}', blocks: [{ type: 'text', text: '{"facts":[]}' }], stopReason: 'end',+ usage: { input_tokens: 40, output_tokens: 4, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic',+ }) as never);+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.setConfig('facts.extraction_model', 'anthropic:claude-sonnet-4-6');+ wire = installTripwire();+}, 60_000);++beforeEach(() => { wire.reset(); });+afterEach(async () => { await disposePersistenceConsumer(engine); });++afterAll(async () => {+ wire.dispose();+ __setChatTransportForTests(null);+ __setEmbedTransportForTests(null);+ resetGateway();+ await engine.disconnect();+ for (const k of PINNED) { if (saved[k] === undefined) delete process.env[k]; else process.env[k] = saved[k]; }+});++const COVERED = new Set<string>();++describe('writes commit with zero generative model calls', () => {+ test('put_page (local and remote), keyword-queryable at commit', async () => {+ COVERED.add('put_page');+ await call('put_page', { slug: 'meetings/roadmap-local', content: `---\ntype: meeting\ntitle: Roadmap local\n---\n${BODY}` });+ await call('put_page', { slug: 'meetings/roadmap-remote', content: `---\ntype: meeting\ntitle: Roadmap remote\n---\n${BODY} See [[meetings/roadmap-local]].` }, true);+ expectNoGenerative('put_page');+ const hits = await engine.searchKeyword('quarterly roadmap');+ expect(hits.map(h => h.slug)).toEqual(expect.arrayContaining(['meetings/roadmap-local', 'meetings/roadmap-remote']));+ });++ test('capture and edit_page', async () => {+ COVERED.add('capture'); COVERED.add('edit_page');+ await call('capture', { slug: 'notes/captured', content: `Captured thought about pricing tiers. ${BODY}` });+ const page = await call('get_page', { slug: 'meetings/roadmap-local', include_content: true });+ await call('edit_page', { slug: 'meetings/roadmap-local', expected_revision: page.revision,+ edits: [{ old_text: 'Roadmap local', new_text: 'Roadmap local (edited)' }] });+ expectNoGenerative('capture/edit_page');+ });++ test('graph, tags, timeline and takes', async () => {+ for (const n of ['add_link', 'remove_link', 'add_tag', 'remove_tag', 'add_timeline_entry', 'takes_add']) COVERED.add(n);+ await call('put_page', { slug: 'companies/acme-example', content: `---\ntype: company\ntitle: Acme Example\n---\nA company.` });+ await call('add_link', { from: 'meetings/roadmap-local', to: 'companies/acme-example', link_type: 'mentions' });+ await call('remove_link', { from: 'meetings/roadmap-local', to: 'companies/acme-example' });+ await call('add_tag', { slug: 'companies/acme-example', tag: 'customer' });+ await call('remove_tag', { slug: 'companies/acme-example', tag: 'customer' });+ await call('add_timeline_entry', { slug: 'companies/acme-example', date: '2026-09-01', summary: 'Signed the pilot.' });+ await call('takes_add', { page_slug: 'companies/acme-example', claim: 'Acme Example will expand the pilot.', kind: 'bet', holder: 'self', weight: 0.6 }).catch(() => undefined);+ expectNoGenerative('graph/tags/timeline/takes');+ });++ test('remember (fresh, duplicate, cosine supersede) and forget', async () => {+ COVERED.add('remember'); COVERED.add('forget');+ const first = await call('remember', { fact: 'Alice Example prefers async standups.', provenance: 'test', entity: 'companies/acme-example' });+ await call('remember', { fact: 'Alice Example prefers async standups.', provenance: 'test', entity: 'companies/acme-example' });+ await call('remember', { fact: 'Alice Example now prefers daily standups.', provenance: 'test', entity: 'companies/acme-example' }, true);+ expect(wire.events.some(e => e.call.kind === 'embedding')).toBe(true);+ await call('forget', { id: String(first.fact_id ?? first.id) });+ expectNoGenerative('remember/forget');+ });++ test('delete_page and restore_page', async () => {+ COVERED.add('delete_page'); COVERED.add('restore_page');+ await call('put_page', { slug: 'notes/temp', content: `---\ntype: note\ntitle: Temp\n---\nTemporary.` });+ const temp = await call('get_page', { slug: 'notes/temp', include_content: true });+ await call('delete_page', { slug: 'notes/temp', expected_revision: temp.revision });+ const deleted = await call('get_page', { slug: 'notes/temp', include_content: true, include_deleted: true }).catch(() => ({} as Record<string, any>));+ await call('restore_page', { slug: 'notes/temp', ...(deleted.revision ? { expected_revision: deleted.revision } : {}) });+ expectNoGenerative('delete/restore');+ });++ test('CLI import (importFromContent)', async () => {+ await importFromContent(engine, 'notes/imported', `---\ntype: note\ntitle: Imported\n---\n${BODY}`, { sourceId: 'default' });+ expectNoGenerative('importFromContent');+ expect((await engine.searchKeyword('roadmap')).some(h => h.slug === 'notes/imported')).toBe(true);+ });+});++describe('generative work a write triggers runs after commit, attributed and switchable', () => {+ test('extraction off: draining effects and jobs makes zero generative calls', async () => {+ await engine.setConfig('facts.extraction_enabled', 'false');+ await call('put_page', { slug: 'meetings/off-arm', content: `---\ntype: meeting\ntitle: Off arm\n---\n${BODY}` });+ await drainEffects();+ await runFactsJobs();+ expectNoGenerative('extraction off');+ });++ test('extraction on: every generative call belongs to facts extraction for the originating request', async () => {+ await engine.setConfig('facts.extraction_enabled', 'true');+ const receipt = await call('put_page', { slug: 'meetings/on-arm', content: `---\ntype: meeting\ntitle: On arm\n---\n${BODY}` });+ expectNoGenerative('commit before drain');+ await drainEffects();+ const ran = await runFactsJobs();+ expect(ran).toBeGreaterThan(0);+ const gen = wire.generative();+ expect(gen.length).toBeGreaterThan(0);+ for (const e of gen) {+ expect(['facts-absorb', 'facts-queue']).toContain(e.attribution?.effect ?? 'unattributed');+ }+ // The receipt carries an opaque public id; attribution uses the internal write-request id.+ const [request] = await engine.executeRaw<{ id: string }>(+ "SELECT id::text AS id FROM persistence_requests WHERE slug='meetings/on-arm' AND operation='put_page' ORDER BY created_at DESC LIMIT 1");+ const requestId = request?.id;+ expect(typeof receipt.request_id).toBe('string');+ expect(typeof requestId).toBe('string');+ expect(gen.some(e => e.attribution?.request_id === requestId)).toBe(true);+ expect(wire.egress).toEqual([]);+ });+});++describe('coverage of the classification', () => {+ test('every mutating op resolves to a class; uncovered zero-generative ops are reported', () => {+ const mutating = operations.filter(op => op.mutating);+ const uncovered = mutating+ .filter(op => ZERO_GENERATIVE_BEFORE_COMMIT.has(writeInferenceOf(op)) && !COVERED.has(op.name))+ .map(op => `${op.name}:${writeInferenceOf(op)}`);+ for (const op of mutating) expect(typeof writeInferenceOf(op)).toBe('string');+ if (uncovered.length) console.info(`[write-inference] zero-generative ops without a runtime case here: ${uncovered.join(', ')}`);+ for (const core of ['put_page', 'capture', 'edit_page', 'remember', 'forget', 'add_link', 'add_timeline_entry']) {+ expect(COVERED.has(core)).toBe(true);+ }+ });+});