Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
docs: key-files entries for the GST-927 refusal fixes and ParamDef fields (ship docs audit)
garrytan0bc523e15c96
diff --git a/docs/architecture/key-files/belief-ledger.md b/docs/architecture/key-files/belief-ledger.mdindex 0ce2fa020d..51201758d0 100644--- a/docs/architecture/key-files/belief-ledger.md+++ b/docs/architecture/key-files/belief-ledger.md@@ -18,7 +18,7 @@ Design: [BELIEF_LEDGER.md](../../designs/BELIEF_LEDGER.md). Operator surface: `g- `src/core/belief/page-at-time.ts` — W2 page-at-time (BELIEF_LEDGER.md section 10): `readPageAtTime` replays a slug's page events of every lifetime into validity intervals under the section 5.3 visibility rule (a straddling write refuses `known_as_of_unproven`), refuses `coverage_from` / `coverage_gap` from `coverageAt`, and pairs each closed interval with the preimage version the next transition wrote (by revision, in order); the open head reads the live page. A body no version holds is disclosed (`body_reason`), never borrowed. Purge-redacted events carry no revision, so a purged lifetime splits only on slug and deleted state. `remoteMayRead` applies history.ts's remote rule per interval.- `src/core/belief/preimages.ts` — the preimage invariant (BELIEF_LEDGER.md section 14 item 8): a revision-moving publication leaves a version of its `revision_before`. `missingPreimages` is the in-batch check `finalizeBeliefEvents` runs under `NODE_ENV=test` (off with `GBRAIN_BELIEF_PREIMAGE_CHECK=0`); `preimageGaps` is doctor's production scan (large and segmented pages exempt).- `src/core/belief/changes.ts` — W4 weekly change diff (BELIEF_LEDGER.md section 15): `beliefChanges` reads the window through `readBeliefHistory` (`recordedAfter`/`recordedUntil`, then `subjectKeys` up to `since` for each subject's value before), nets each subject end to end, reads a subject with no earlier event from the page body at `since` (`before_known: false` when no body answers), lists a page created in the window with its creation body's fence rows, flags a `dream`-inferred link end `upper_bound`, and skips backfill and baseline events. Remote callers get world fence rows only where `remoteMayRead` passes. Served by `delta {beliefs: true}` and `gbrain beliefs changes`.-- `src/core/ops/known-as-of.ts` — the op surface: `get_page {known_as_of}` and `get_versions {known_as_of, diff, source_id}` (full surface only). One target source (explicit, ambient, or the only granted source whose ledger names the slug); remote callers get only readable intervals of a page visible now at their trust floor, with sanitized bodies. `parseKnownAsOf` refuses a bare date `clock_mismatch`. Window selectors, `section`, `grep` and `context` do not combine with known_as_of (`invalid_params`).+- `src/core/ops/known-as-of.ts` — the op surface: `get_page {known_as_of}` and `get_versions {known_as_of, diff, source_id}` (full surface only). One target source (explicit, ambient, or the only granted source whose ledger names the slug); remote callers get only readable intervals of a page visible now at their trust floor, with sanitized bodies. `parseKnownAsOf` refuses a bare date `clock_mismatch`. Window selectors, `section`, `grep` and `context` do not combine with known_as_of (`invalid_params` naming the arguments to drop, with a read `fix` that keeps only what a recorded-time read takes).- `src/core/engine-sql/pages.ts` `updateSlug` — versions the page before the move (the move advances the revision), so page-at-time has the body from before a rename.- `src/commands/beliefs.ts` — `gbrain beliefs enable|disable|status|changes|reconcile|backfill|replay-purges` (`--json`); an unknown source is `invalid_params`. Only `changes` routes on a thin client: `thin-client-routing.ts` calls the host's `delta {beliefs: true}` (so it lists the remote world view) and refuses `--source`; every other subcommand is host-only.- `src/commands/doctor/checks/belief-ledger.ts` — doctor `belief_ledger_coverage`: intervals and certification, baseline progress, drift (sampled; complete under `--tier deep`), orphan lifetimes, unmarked publications, and a restore whose purge replay was partial, unavailable or unverified (`ask_user`). `--fix` reconciles and fills marks; a brain without coverage is information with an `ask_user` enable.diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.mdindex 066561e08a..c10aa2991a 100644--- a/docs/architecture/key-files/core-services-2-continued.md+++ b/docs/architecture/key-files/core-services-2-continued.md@@ -49,4 +49,4 @@ Writes that change part of a page in time proportional to the change (Wave B spe- `src/core/ops/page-append.ts` — the `append_page` operation (write scope, client slug-fence allowlist, `outputRedaction: 'no_stored_text'`): params `{slug, source_id?, text, request_id, expected_revision?, expected_tail_sha256?, region?, separator?}`, returns `{slug, revision, body_bytes, appended_bytes, chunks_new, size_state, receipt}`. get_page's `body: 'none'` returns `tail_sha256` and `tail_region` for inline and segmented pages, and its window reads return `edit_target: {revision, byte_start, byte_end}` in stored coordinates (`ops/get-page-body.ts` `editTarget`), withheld from a remote caller when hidden text precedes the window end (`read-range.ts` `hiddenBefore`).Segmented edit_page (`persistence/page-edit.ts`, entry in [Core Persistence](core-persistence.md)): optional `within: {byte_start, byte_end}` (stored coordinates, as `edit_target` returns them; `parseEditWithin`, `edit_invalid`) limits matching to one range, and a range the page no longer holds refuses `revision_conflict`. A remote caller's `within` refuses `edit_invalid` (one refusal for every range and edit, before any match or fence check) when hidden text starts before `byte_end`: on a segmented page the read projection's hidden units (`read-range.ts` `hiddenBefore`, the predicate `editTarget` withholds `edit_target` by), on an inline page a fence whose remote view differs from its stored text; such a range would measure the hidden text. A segmented page is never materialized: `prepareSegmentedEditMutation` (called first by `page-prepare.ts` `preparePageMutation`) finds each old_text by a streaming scan across segment boundaries (`locateSegmentedEdits`, with applyPageEdits' exactly-once, protected-span and remote-view rules; the scan keeps at most two matches per edit and refuses `edit_ambiguous_match` at the second, counted in `spliceWork.matches`) and splices the touched range; the receipt diff covers the touched range plus 2 KB of context, and only the first replacement past 256 KB (`diff_truncated`); its context never starts at or inside hidden facts or takes text, nor ends inside it, and its hunk lines count the caller's view (`viewNewlinesBefore`: row line counts plus, for a remote caller, each hidden run before the diff rendered as `sanitizeRemoteBody` renders it). With a withdrawal ledger that applies, the scan, the diff and those line counts read the page through its withdrawal overlay (`storedPieces` over `trustedSegments`, rows widened to whole fence blocks), on every path; a match into a block the overlay rewrote is never kept. A segmented page's remote edit view hides withdrawn rows as its remote windows do (`SEGMENTED_REMOTE_VIEW`, also on the whole-body path). A stored fence that does not compile refuses as applyPageEdits refuses it (typed `target_fence_malformed`, same location), at submission (`assertSegmentedEditFences`) and again at preparation: `scanCanonicalFences` runs over the stored fence text alone, each piece at its own line, so only segments holding fence text are read; with `within`, only the fences in the touched segments and those crossing into them. It declines to the whole-body path for an old_text naming the timeline sentinel or also found in the frontmatter head, or a miss without `within` on a page within the single-string ceiling.-- `src/core/ops/get-page-body.ts` — get_page's body modes (`auto|full|none|outline|window`, selectors `lines`/`bytes`/`around_chunk_id`/`cursor`, `view: read|markdown`). `parseBodyRequest` fixes precedence (explicit body; include_content/content_only → full; a selector → window; the thin client and the local CLI → full; else auto) and rejects conflicting selectors. `readPartialBody` never fills compiled_truth/timeline/content: it slices the read projection (`readPageDocument`) or, for `view: markdown`, the round-trip markdown with its sha256; a window is re-measured as the final encoded frame and shrunk until it fits `resultByteCap`. `around_chunk_id` uses the stored span (`anchor: stored_span`), a unique text match (`located`), or returns the chunk alone (`chunk_only`). Cursors are revision-bound; a stale one is `revision_changed` with a same-offset fix. `readFetchWindow` / `fetchWindowResult` serve fetch's windowed shape; `LARGE_PAGES_CAPABILITY` is advertised by `get_brain_identity`. A segmented page (Wave B PR 2, spec 7.2) is never read whole: `full` is `page_body_segmented` for local and MCP callers alike with `segmentedReadFix` (`body: 'auto'`, argv and mcp; local `gbrain get` with no `--body` streams it instead), and `page_too_large_for_inline` only for gbrain's thin client, its paging signal (`segmentedFullReadError`); `grammar_diagnostics` on it is `line_grammar: { state: 'skipped', reason: 'page_body_segmented' }` (`segmentedGrammarSkip`, line-grammar-report.ts); window byte offsets are coordinates of the view's `size.total_bytes`, never `body_bytes`, and an offset past the end is an empty window on both storages; `auto` is the outline plus the first window, and `segmentedWindows` cuts every window, outline page and `around_chunk_id` from `page-window/segmented.ts`. A segmented `around_chunk_id` resolves only from the chunk's live occurrence and segment-relative span (a retired occurrence is `revision_changed`; no text match), and `body: 'none'` reports stored sums plus the tail digest without chunk counts. `section`/`grep`: `ops/get-page-slice.ts` ([continued](core-services-2-continued.md)).+- `src/core/ops/get-page-body.ts` — get_page's body modes (`auto|full|none|outline|window`, selectors `lines`/`bytes`/`around_chunk_id`/`cursor`, `view: read|markdown`). `parseBodyRequest` fixes precedence (explicit body; include_content/content_only → full; a selector → window; the thin client and the local CLI → full; else auto) and rejects conflicting selectors (`invalid_params` naming the selectors to drop; its `fix` is the same call with the first selector alone and `body: 'window'`, kept arguments only, argv and mcp). `readPartialBody` never fills compiled_truth/timeline/content: it slices the read projection (`readPageDocument`) or, for `view: markdown`, the round-trip markdown with its sha256; a window is re-measured as the final encoded frame and shrunk until it fits `resultByteCap`. `around_chunk_id` uses the stored span (`anchor: stored_span`), a unique text match (`located`), or returns the chunk alone (`chunk_only`). Cursors are revision-bound; a stale one is `revision_changed` with a same-offset fix. `readFetchWindow` / `fetchWindowResult` serve fetch's windowed shape; `LARGE_PAGES_CAPABILITY` is advertised by `get_brain_identity`. A segmented page (Wave B PR 2, spec 7.2) is never read whole: `full` is `page_body_segmented` for local and MCP callers alike with `segmentedReadFix` (`body: 'auto'`, argv and mcp; local `gbrain get` with no `--body` streams it instead), and `page_too_large_for_inline` only for gbrain's thin client, its paging signal (`segmentedFullReadError`); `grammar_diagnostics` on it is `line_grammar: { state: 'skipped', reason: 'page_body_segmented' }` (`segmentedGrammarSkip`, line-grammar-report.ts); window byte offsets are coordinates of the view's `size.total_bytes`, never `body_bytes`, and an offset past the end is an empty window on both storages; `auto` is the outline plus the first window, and `segmentedWindows` cuts every window, outline page and `around_chunk_id` from `page-window/segmented.ts`. A segmented `around_chunk_id` resolves only from the chunk's live occurrence and segment-relative span (a retired occurrence is `revision_changed`; no text match), and `body: 'none'` reports stored sums plus the tail digest without chunk counts. `section`/`grep`: `ops/get-page-slice.ts` ([continued](core-services-2-continued.md)).diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex 7f5719bf8a..183570e40e 100644--- a/docs/architecture/key-files/core-utilities-1.md+++ b/docs/architecture/key-files/core-utilities-1.md@@ -69,7 +69,7 @@ The `src/core/cycle.ts` entry is on its own page: [Core Cycle primitive](core-cy- `src/core/operations-descriptions.ts` — Constants module for tool descriptions. Pinned via `test/operations-descriptions.test.ts`. Houses `GET_RECENT_SALIENCE_DESCRIPTION`, `FIND_ANOMALIES_DESCRIPTION`, `GET_RECENT_TRANSCRIPTS_DESCRIPTION` plus `LIST_PAGES_DESCRIPTION`, `QUERY_DESCRIPTION`, `SEARCH_DESCRIPTION`. Stable surface for the Tier-2 LLM routing eval — keeping them here keeps the test from binding to whatever is in `operations.ts` at test-run time. Description-edit checklist for `QUERY_DESCRIPTION` / `SEARCH_DESCRIPTION` (and any other text a starter tool serves): no pre-merge lane carries a provider key, so run the routing eval yourself with `GBRAIN_TEST_KEEP_PROVIDER_KEYS=1 bun test test/e2e/salience-llm-routing.test.ts` (Haiku 4.5 at temperature 0, ≈ $0.04; a `search`/`query` rewrite can move concept phrasings such as "all the people that work on X" from `query` to `search` without any unit test noticing), then `bun test test/mcp-schema-budget.test.ts` (per-tool budget, 25,000-character served starter ceiling and its 200-character headroom floor, `MINIMUM_GUIDANCE` pins), `test/operations-descriptions.test.ts`, `test/mcp-instructions-batching.test.ts`, and regenerate with `bun run build:operation-manifest`, `bun run scripts/generate-tool-catalog.ts` and `GBRAIN_TEST_UPDATE_GOLDENS=1 bun test test/cli-goldens.test.ts`. Both descriptions say that people/companies/projects by topic are `query` work: Haiku 4.5 otherwise reads "all the X that do Y" as a `search` list lookup (measured at temperature 1: 28/80 concept phrasings misrouted without the clause, 1/80 with it).- `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/contract.ts` — the shared operation types (`Operation`, `OperationContext`, `ParamDef`, `OperationError`). `ParamDef` carries `minimum`, `exclusiveMinimum`, `minItems`, `actsWhenTrue` and `appliesWith` (GST-927): only `normalizeOptionalParams` reads them, they travel in the operation manifest and never in the tools/list schema. `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`.