Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
56.1 KB
Raw Blame

Key files: Core Services (2/3)

Subsystem index. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG. Fact and page purge modules (src/core/facts/purge*.ts, deletion-inventory.ts): memory purge.

  • src/core/conversation-parser/ — 19-pattern built-in chat-format registry + opt-in LLM fallback. Modules: types.ts (PatternEntry + ParseResult + DateContext + CaptureMap + TimezonePolicy), builtins.ts (19 hand-vetted patterns sourced from public format docs — iMessage/Slack, Telegram bracket + text-export, bold-paren-time, bold-time-dash, bold-name-no-time, chatgpt-export-you-chatgpt, Discord classic + export, WhatsApp ISO + US, Signal, Matrix/Element, IRC classic + weechat, Teams export, markdown-heading-turn; module-load validation runs every test_positive[] + test_negative[] sample at startup so a typo in any built-in regex makes gbrain refuse to start; DEFAULT_SPEAKER_CLEAN exported as a module-level default), parse.ts (orchestrator with pattern-priority scoring across the first 10 lines + date derivation chain explicit > frontmatter.date > effective_date > '1970-01-01' + multi-line continuation + timezone warning; #5430 (W14 P1.9): a valid frontmatter.timezone (IANA) converts every built timestamp from that zone's wall clock to UTC through localToUtcIso(date, hour, minute, tz) (Intl longOffset, no dependency, host-TZ independent; a DST fold takes the first occurrence, a gap the pre-transition offset), an invalid zone is reported as DateContext.invalid_timezone and the warning names it while timestamps stay UTC (test/conversation-parser/timezone.test.ts); also populates ParseResult.unrecognized_headings — when the WINNING pattern is heading-anchored, heading-shaped lines whose label is outside the pattern's speaker set FOLD into the previous turn's body (or drop before the first anchor) while the parse still returns regex_match, silently crediting one speaker with another's words; detection is diagnostic-only and unconditional (not behind opts.diagnostic — the extractor's decline gate depends on it), fence-aware (a fence closes only on ITS OWN marker; an unclosed fence suppresses detection below it), labels deduped/capped at 10 entries ≤48 chars, undefined when empty so healthy-page JSON stays byte-identical; gbrain conversation-parser scan surfaces the field in both human and JSON output; applyPattern never DROPS a matched anchor whose date it cannot reconstruct (a localized month name, malformed digits) — dropping it would fold that speaker's body into the previous turn on a multi_line pattern, so the message opens anyway, inheriting the previous anchor's timestamp (page fallback date at midnight for the first), and the count surfaces as ParseResult.date_fallback_count, undefined when zero), llm-base.ts (shared runLlmCall<T> with content-hash cache in-process + DB-persistent via migration v97 + 4-strategy JSON repair + Anthropic-key probe; fallback is a thin wrapper), llm-fallback.ts (opt-IN; NO regex inference + NO persistence), eval.ts (scoreFixture + aggregateScores + parseFixtureJsonl for the fixture-corpus CI gate), nightly-probe.ts (DI-stubbed; mode-gated default tokenmax=ON, conservative/balanced opt-in; adversarial false-positive detection; an unreadable fixture returns skipped with fixture_unavailable, which the autopilot wiring audits, and the wiring reads the embedded fixtures from cycle/nightly-probe-fixtures.ts). Pattern bold-name-no-time (regex /^\*\*(?!\[)(.+?):\*\*\s*(.*)$/, ordered after the time-bearing bold patterns) parses **Speaker:** text with NO per-line timestamp (Circleback/Granola/Zoom), anchoring every message at T00:00:00Z of the frontmatter date (line order preserves sequence, same no-time convention as irc-classic); the (?!\[) lookahead rejects telegram-bracket **[18:37] Name:**; non-shadow is the colon-INSIDE-bold regex (NOT declaration order — parse.ts scores every candidate independently, order is only the tie-break). Because **Label:** text is a common prose idiom, the pattern sets optional PatternEntry.score_full_body: true so parse.ts recomputes the winner's acceptance score over the FULL body before the SCORING_MIN_ACCEPTANCE floor, keeping a bold-label notes page at no_match. Pattern chatgpt-export-you-chatgpt (regex /^\*\*(You|ChatGPT):\*\*\s*(.*)$/, declared just before bold-name-no-time so it wins the score tie on the two literal ChatGPT-export labels) parses ChatGPT's web-export → Markdown shape, where each turn's **You:** / **ChatGPT:** anchor is followed by a blank line and a multi-paragraph reply; bold-name-no-time alone cannot absorb that shape (multi_line: false scores a long reply's density near zero and falls below SCORING_MIN_ACCEPTANCE), so this pattern sets multi_line: true + score_continuations_as_body: true (excludes non-**-prefixed reply lines from the density denominator) + score_full_body: true. The speaker capture is a closed two-value enumeration (You or ChatGPT exactly, never an arbitrary (.+?) label), so it cannot reopen bold-name-no-time's BROAD-REGEX GUARD against notes pages. Because a bare **You:**/**ChatGPT:** heading is plausible in prose ABOUT ChatGPT, the pattern also sets the optional PatternEntry.score_continuations_min_distinct_speakers: 2: scoreFromLines only grants the continuation-density-exclusion score when the anchor lines that fully match regex collectively capture at least that many DISTINCT speaker_group values, so a page with only one role falls back to the ordinary flat-density score. It ALSO sets PatternEntry.score_continuations_max_preamble_lines: 5, because one genuine pair embedded deep in an unrelated long document would otherwise pass: scoreFromLines tracks the index of the FIRST fully-matching anchor line and only grants the immunity when that index is at or before the bound (a short title preamble is tolerated). Pattern bold-paren-time parses **Speaker** (HH:MM): text and (HH:MM:SS) (date_source: frontmatter). Fallback gates: SCORING_HEAD_TRIGGER_THRESHOLD = 0.3 triggers a full-body re-score when the head pass scores below that; SCORING_MIN_ACCEPTANCE = 0.05 blocks essay false-positives. Exported scorePatternFull(body, entry); private getNonBlankLines(body, headCap?) + scoreFromLines(lines, entry) DRY the quick_reject+regex loop. CLI surfaces at src/commands/eval-conversation-parser.ts (gbrain eval conversation-parser <fixture.jsonl> exit 0/1/2, wired into bun run verify via check:conversation-parser) and src/commands/conversation-parser.ts (scan <slug> debug, list-builtins, validate <file>). Doctor checks: conversation_format_coverage, progressive_batch_audit_health, conversation_parser_probe_health. Pinned by test/conversation-parser/{parse,llm-base,llm-fallback,nightly-probe}.test.ts + the 27-case baseline at test/extract-conversation-facts.test.ts (back-compat invariant). Migration v97 (conversation_parser_llm_cache_table). Fixtures at test/fixtures/conversation-formats/{imessage,imessage-time-only-12h,telegram-bracket,whatsapp-iso,whatsapp-us,signal-export,irc-classic,irc-weechat,matrix-element,teams-export,all,adversarial,bold-name-no-time,bold-time-dash,chatgpt-export-you-chatgpt}.jsonl with scripts/check-fixture-privacy.sh banning real-name leaks. Maintainer guidance: conversation parser patterns.

  • src/core/facts/conversation-windows.ts — conversation windowing for extract-conversation-facts (#6267, wave 15 P2.5): splitIntoSegments(messages, { gapMinutes, maxMessages, sinceIso, maxChars, pageTitle }) cuts gap groups, keeps only groups with MIN_SEGMENT_MESSAGES (2) original messages, then packs each eligible group into windows bounded by DEFAULT_SEGMENT_MAX_MESSAGES (30) and SEGMENT_TEXT_CHAR_LIMIT (6,500 rendered chars, header included). Every eligible turn lands in exactly one window; a turn whose own line overflows is split by splitTurnText at sentence, then whitespace, then code-point boundaries (never inside a surrogate pair; pieces.join('') is the original) with the speaker (timestamp): prefix on every piece; an original singleton stays ineligible; a header that leaves fewer than 32 chars of room throws before any window exists. renderSegmentForExtraction(pageTitle, segment) renders the unchanged prompt shape and throws on an over-budget hand-built segment instead of clipping it. Owns the tunables the command re-exports (DEFAULT_SEGMENT_GAP_MINUTES, MAX_PAGE_SEGMENT_GAP_MINUTES). Pinned by test/conversation-windows-6267.test.ts.

  • src/core/facts/conversation-types.ts — single-source conversation-type allowlist (ALLOWED_TYPES: conversation, meeting, slack, email, imessage, imessage-daily + AllowedType). It also owns the granular collector aliases (ALLOWED_TYPE_ALIASES, pageTypesForAllowed) and the one eligibility rule (#5330): isConversationFactsEligiblePage and its SQL twin conversationFactsEligibleSql admit an allowed concrete type unless frontmatter says conversation_parseable: false; with cycle.conversation_facts_backfill.require_parseable_flag on, only type: conversation or conversation_parseable: true. The extractor (slug, batch and enumeration paths), the doctor backlog SQL and its in-process verifier, and the format-coverage sample all use it, so the backlog can drain. Every consumer derives from this frozen leaf module — extract-conversation-facts.ts (which re-exports both names verbatim for its existing importers), the cycle backfill phase, doctor.ts + doctor/checks/search-eval.ts, sources.ts, jobs.ts — so no hand-copied list can drift. It lives under src/core/facts/ (not src/commands/) because scripts/generate-flag-registry.ts scans option-shaped literals one relative-import level deep — importing the constant straight from extract-conversation-facts.ts would transitively attribute that command's whole option surface to doctor/jobs/sources in the generated CLI_ONLY registry. Drift-guarded by test/conversation-facts-type-allowlist-drift.test.ts. isFrontmatterFlagOff (the same off spellings) is shared with facts/eligibility.ts. Since #6267 it also owns the ConversationMessage, ConversationSegment and SplitSegmentsOpts types the windowing module and the command share.

  • src/core/facts/eligibility.ts — isFactsBackstopEligible, the one automatic facts-extraction predicate (page-write outbox, its body_unchanged check, sync's post-import hook, the facts-absorb job's re-check). Skips wiki/agents/, dream_generated: true, facts_backstop set off (opted_out, #6232: a writer's opt-out for a page whose facts another page carries, such as a meeting's raw transcript; removing it re-offers the page even with an unchanged body), bodies under 80 characters, and types outside ELIGIBLE_TYPES unless the slug is under a rescue prefix (conversation-pipeline types, CONVERSATION_PIPELINE_TYPES, skip as conversation_pipeline, #6557: the opt-in conversation facts backfill owns them; doctor facts_extraction_health names the opt-in and its caps when such pages exist and the backfill is off). Receipt reasons are documented under facts_backstop_skipped in the error registry. Pinned by test/facts-eligibility.test.ts, test/persistence-facts-backstop.test.ts. #6259: a quarantined page (the gate's quarantine marker) is ineligible with reason quarantined, which the page-write receipt reports as facts_backstop.skipped (registered in facts_backstop_skipped).

  • src/core/facts/extract.ts — the LLM facts extractor (extractFactsFromTurnWithOutcome and friends; the output cap, truncation retry, and salvage behavior are described under the trajectory entry). The first call and the truncation retry send cacheSystem: true (the system prompt is identical across calls; per-call data rides in the user message), so bulk extraction reads it from the provider's prompt cache; the malformed-output retry, whose system prompt differs, does not. Model: resolveFactsExtractionModel(engine) returns the model and the setting that chose it (facts.extraction_model, then the resolveModelDetailed chain on the reasoning tier); when nothing chose one and the tier's key-aware default resolved through Anthropic, FACTS_EXTRACTION_MEASURED_DEFAULTS substitutes anthropic:claude-haiku-5-5 (source measured_default; the facts-absorb quality gate, gbrain-evals docs/benchmarks/2026-10-08-facts-extraction-model.md), and gbrain models reports that row through the same resolver. getFactsExtractionModel is its string wrapper. Deterministic junk gate: isJunkFact(text, kind?) tests JUNK_FACT_PATTERNS — assistant plan/offer narration, meta-narration about the conversation itself, provider billing/rate-limit strings captured verbatim — and is kind-aware: a candidate the extractor classified commitment is exempt from the plan-narration arm ONLY ("I'll send the deck by Friday" is a genuine commitment); meta-narration and provider-error strings are junk for every kind. isJunkFilterEnabled(engine) is the config kill switch (fail-open on a config read error); getFactsExtractionPromptAppendix supplies the config-driven prompt appendix. Entity gate at the candidate loop (the ONE seam where LLM-emitted entity tokens become entity_slug): isUnknownSpeakerLabel (anonymous diarizer labels — Speaker A, SPEAKER_00, spk_0, other|unknown|guest) and isNullLikeEntity (placeholder STRINGS "null"/"None"/"n/a" where the prompt asked for JSON null; shared with write-single.ts) both null the attribution and KEEP the fact, so no consumer can mint entity_slug='null' through the resolver's fallback slugify. The provider-error arm is start-anchored (^\W*, optional error/status token or a <step> stopped|failed because … prefix, then (spend|rate) (limit|cap) … (hit|exceeded|reached)), so a genuine fact that merely mentions a spend limit or rate limit mid-sentence survives; the verbatim provider strings still match. Two config keys: facts.extraction_prompt_appendix (non-empty text is appended to the extraction prompt) and facts.extraction_junk_filter (false disables the deterministic junk gate; default on), plus the opt-in facts.extraction_missing_confidence (stored when confidence is missing, null or non-numeric; unset keeps 1.0). A numeric-string confidence ("0.3") is read as the stated value; unknown kinds are still stored as fact but counted in a stderr warning. Every extractor chat() call (first attempt, the #2113 truncation retry, the malformed-output retry) carries responseSchema: FACTS_EXTRACTION_SCHEMA (mirrors RawExtracted: facts[] of {fact, kind ∈ ALL_EXTRACT_KINDS} plus entity/confidence/notability/metric/value/unit/period — EVERY property in required, the optional ones nullable via type unions, additionalProperties: false at both levels, so the schema is OpenAI-strict-safe for proxies that honor the SDK's default strict: true); the gateway honors it only on openai-compatible recipes that declare structured outputs (Ollama's server-side grammar), so small local models cannot emit malformed JSON, while parseExtractorJsonDetailed still validates the reply text on every lane. The typed-claim examples keep a bare $ as USD (series compare by (metric, unit, period), so nulling it would split them) and, since wave 15 (PR #6274 by @jordanschwartz-js), show two explicit non-USD examples (EUR, CAD) with the rule to preserve a stated currency as the unit and never convert; pinned by test/facts-extract-currency-examples-6274.test.ts. Pinned by test/facts-extract-structured-output.test.ts.

  • src/core/facts/forget.ts — forgetFactInFence(engine, id, {reason?, sourceId?, worldOnly?, supersededBy?}) checks source and visibility before inspecting state, then commits a durable withdrawal through facts/withdrawal.ts. With supersededBy: { rowNum } (the writeSingleFact supersession path) it only expires the row and strikes it with a page-local #N supersession reference: no withdrawal, so the old claim stays rememberable and no other page is invalidated. A writable source fence is atomically struck with a date and reason; otherwise the DB-body mirror is best-effort. Both paths remain withdrawn on stale reimport while the withdrawal database is preserved. The file resolver and per-page lock match fence writes. The body-only mirror deliberately leaves a hash mismatch so the next import re-chunks. Forget is retraction, not deletion of original prose, files or backups. strikeFenceRow and supersededFact are exported for the S9 checked supersede (facts/proposal-supersede.ts). strikeFenceRow returns null for a fence that parses with warnings (#6385 R12), so forget falls back to the DB-only expire and the file keeps the rows the parser could not read. Pinned by test/forget-reconcile-durability.test.ts, test/privacy-strip-and-forget.test.ts, and test/e2e/delegated-grants-withdrawal.test.ts. A segmented page's row is struck in the segment holding its fence (rewriteLiveSegmentedFences), on the DB-only and the file-mirror paths, with strikeFenceRow's whole-string semantics: only the first facts fence is a candidate (of the compiled truth for the DB body, of truth then timeline for the mirror), and a first fence without the row strikes nothing.

  • src/core/facts/phantom-audit.ts — JSONL audit at ${resolveAuditDir()}/phantoms-YYYY-Www.jsonl. Pattern copy of src/core/audit-slug-fallback.ts (ISO-week rotation, honors GBRAIN_AUDIT_DIR). Exports logPhantomEvent(record) + readRecentPhantomEvents(days) + computePhantomAuditFilename(now?). Records every outcome: redirected | ambiguous | drift | no_canonical | not_phantom_has_residue | pass_skipped_lock_busy. Best-effort writes — stderr warn on failure, never throws. Separate file from stub-guard-audit.ts (distinct consumer + lifecycle: stub-guard logs PREVENTIVE blocks; phantom-audit logs CLEANUP decisions, to be read by a future phantoms_pending doctor check).

  • src/core/facts/queue.ts:FactsQueue.drainPending — method drainPending({timeout?: number}): Promise<{drained, unfinished}>. Semantically distinct from shutdown() (which calls this.internalAbort.abort() and would abort the very facts:absorb worker trying to log its post-completion event). Drain lets in-flight finish; only the wait is bounded. Default timeout 1000ms so commands that don't enqueue facts pay one fast 0ms check before exit. src/cli.ts op-dispatch finally block awaits getFactsQueue().drainPending({timeout: 1000}) BEFORE engine.disconnect(). Lazy-import keeps the facts-queue module off the hot path for ops that never touch it. Prevents a trailing 'No database connection' line after gbrain capture (a post-page-write facts:absorb outliving the CLI process). Pinned by test/facts-queue-drain-pending.test.ts (4 cases: empty fast-path, in-flight settled without abort, unfinished count on timeout, default timeout = 1000ms).

  • src/core/facts/withdrawal.ts + withdrawal-schema.ts + withdrawal-discovery.ts — durable withdrawal key is (source_id, visibility, subject, SHA256(normalized claim)). subject is the forgotten row's entity_slug; '' (all subjects) covers subjectless facts and rows recorded before v169. A withdrawal matches when subject = '*' OR subject = entity_slug, so forgetting one entity's claim never touches the same claim about another entity. GBRA-574 A1: a fact on an unbacked name key (unbackedEntitySql: a bare slug with no live page at it in the source) counts as subject '': forgetting or purging it writes '*' (factWithdrawalSubjectSql, planFactPurge), and the guards (gbrain_preserve_fact_withdrawal, gbrain_guard_inserted_facts, gbrain_refuse_purged_fact, migration v321), the forget-time expiry, the purge plan and the conversation purge pre-filter match such a row under a withdrawal or tombstone of any subject. Fence rows belong to their page's entity: the import overlay, prepared-import check (preserveWithdrawnFenceRows / assertPreparedFactWithdrawals), snapshot overlay and Markdown export match on the page slug. updateSlug (both engines, via moveSlugBindings) and the phantom-redirect merge move subjects to the new slug (MOVE_WITHDRAWAL_SUBJECT_SQL), so rename and index recreation do not restore a claim. Normalization (gbrain_fact_normalize, mirrored in JS by normalizeLoweredClaim) folds case, whitespace and an explicit punctuation set, not meaning (migration v174); +, # and in-word dots are kept ("C++" ≠ "C"); pre-v174 ledger rows keep their exact gbrain_fact_fingerprint_v1 hash and every ledger match checks both. v174 adds a folded row wherever a fact row still holds the claim text, expires facts that became matching, and builds idx_facts_withdrawal_fingerprint (the fingerprint inlines normalization: index builds use a restricted search_path). Discovery (withdrawal-discovery.ts) is keyed on claim, subject and fingerprint: SQL shortlists pages and chunks whose lowercased text contains every normalized token of the claim (one lower(text) LIKE ALL(patterns) fold per text with %, _ and \ escaped, #6270; necessary for any match; nothing is normalized in SQL), streams them by keyset, then verifies exactly; a subject-scoped claim reads only its entity's page plus provenance of that entity's facts. There is no source-inventory limit (#5674): refusals come from the matched set (>256 pages, reported with the count and sample slugs), the 10s scan budget, per-batch input limits or matching malformed evidence. One facts fence a forced cut splits is checked as one batch; over 16,384 rows or 8 MiB it refuses with reason split_fence_rows, naming the page and the fence (test/pathological/lp-f-split-fence-withdrawal-capacity.test.ts). Only an existing withdrawal covering the same subject skips discovery. Only affected page revisions/chunks are invalidated. The source row lock serializes withdrawal with the facts triggers (per row, or once per statement for the bulk fence insert, v264); they prevent reactivating a matching claim. Import and snapshot overlays cover every complete legacy fence, including inactive rows; withdrawal markers precede preserved context and retain earlier expiry dates before hashing/chunking; malformed fences retain their existing diagnostics and the DB trigger still protects derived facts. writeSingleFact refuses an identical withdrawn claim for the resolved entity before embedding, using the protocol error envelope. writeFactsToFence rechecks each input under the page lock and drops claims withdrawn for the page's entity (reporting withdrawnSkipped), and the backstop skips them in phase 1, so a withdrawn claim is never appended to Markdown as an active row (audit B-10). TTL/supersession expiry creates no withdrawal; backfill trusts only explicit forgotten: markers; Markdown-only copies do not preserve DB-only withdrawals. Pinned by test/facts-withdrawal-subject.test.ts, test/fact-withdrawal-normalized.test.ts, test/withdrawal-bounded-safety.test.ts (both engines) and the Postgres scale gate test/e2e/fact-withdrawal-scope-postgres.test.ts. recordFactWithdrawal(…, { semanticReview }) also queues a withdraw review row in decide_review_queue inside the same transaction when decide.slots.conflict.review_withdraw is on (unset counts as on; reviewWithdrawOn) and the caller did not opt out, and runs every registerWithdrawalInvalidation hook in that transaction for projections beyond pages and chunks. src/core/facts/similar-active.ts — similarActiveAfterForget: after a committed forget, up to five active facts with the same source, entity and visibility (world only for remote callers other than the brain owner, worldOnlyFacts, GST-2951) at cosine >= 0.80 to the withdrawn fact's stored embedding, returned as ids and scores with the overnight review state and a next line (zero model calls; pinned by test/decide/review-withdraw.serial.test.ts). Segmented affected pages are struck segment by segment through rewriteLiveSegmentedFences (a new generation whose flip replaces only the rewritten occurrences' chunks); discovery also scans live manifest rows with facts_slots, reading only each slot's bytes, and joins a fence a forced cut split from its slots' bytes (splitFactsFences; above PAGE_MAX_BYTES it refuses with page_body_segmented), so a private row, which never reaches chunks, is found wherever the cut falls.

  • src/core/facts/write-single.ts — writeSingleFact(fact, ctx): the zero-LLM single-fact seam behind remember. runFactsPipeline is extraction-first (LLM-gated) and cannot back a pre-formed fact; this reuses the pipeline's post-extraction stages directly: resolve → embedding-cosine dedup (per-model threshold) → fence-first write with the same legacy DB-only fallbacks (thin-client, unparented, stub-guard). Supersession: deterministic rule — same entity_slug + same kind + similarity ≥ threshold + DIFFERENT text ⇒ the new fact supersedes (fence path: append new + forgetFactInFence(old, { supersededBy }), which strikes the old row with a page-local #N supersession reference and records no withdrawal, + superseded_by link; DB path: engine insertFact supersedeId). Pinned by test/facts-supersede-not-withdrawal.test.ts. Provenance lands on NewFact.source verbatim (no FactsBackstopCtx). No embedding provider ⇒ degraded_dedup: true (near-duplicates may insert — documented). isNullLikeEntity(entity) (exported) normalizes null-like entity tokens ("null", "undefined", "none", "n/a", "nil", "-", empty/whitespace) to ABSENT before resolution — applied here rather than only at the verb boundary so EVERY writeSingleFact caller gets the guard and the resolved?.slug ?? entityRef fallback can never adopt "null" as a slug. On a managed brain, after the withdrawal check and embedding, the fact publishes through publishManagedEntityFacts (src/core/facts/managed-fact-write.ts, the managed_facts_entity intent: fence row, index row and file together, dedup at publication, and the same-kind near-duplicate supersession rule via the intent's supersede flag, which strikes the old fence row and expires and links the old fact in the same transaction; an explicit per-fact context is kept; an entity without a live page lands database-only on memory/unattributed and, through the intent's opt-in attribute_fallback flag, which only writeSingleFact sets, keeps the resolver's fallback slug as entity_slug with no row number, so dedup and withdrawal checks stay per entity; the facts backstop never sets it and keeps those rows unattributed). writeFactsToFence (fence-write.ts) takes the same path on a managed brain, after dropping withdrawn claims. A fence append refused because the page's facts fence does not parse cleanly rethrows the typed fenceRefusal (invalid_fence / target_fence_malformed). On an unmanaged brain, #6398 (fix wave 13): when the page's file is missing but a source-scoped row exists (live, with a vanished source_path file, or tombstoned), writeFactsToFence returns stubGuardBlocked with audit reason db_only_page and the caller records the facts DB-only, so no stub overwrites the DB body or resurrects a deleted page; an unreadable row returns fenceWriteFailed; the #4872 page mirror runs only for a body read from a real file. Doctor stub_guard_24h (commands/doctor/checks/local-audits.ts) counts unprefixed, fallback_resolution and db_only_page separately; db_only_page never feeds the WARN threshold. Tests: test/fence-write-db-only.test.ts, test/doctor-stub-guard.test.ts.

  • src/core/facts/managed-fact-write.ts — publishManagedEntityFacts(engine, sourceId, entity, facts) builds one managed facts session per visibility (request identity derived from the write, so a retried job replays its receipt; attributeFallback sets the intent's attribute_fallback), keeps a caller's vector only when it matches the brain's facts embedding signature, and returns ids in input order; managedFactWritePreflight runs the same session checks before a caller's model call.

  • src/core/interaction.ts — the one interaction primitive (agent operator wave A5). isInteractive(probe?) needs two TTYs and no GBRAIN_NON_INTERACTIVE, CI or agent-process marker (agentProcessMarker(): CLAUDECODE, CLAUDE_CODE_ENTRYPOINT, CODEX_SANDBOX, CODEX_CI, OPENCODE, OPENCODE_PID; never CODEX_HOME); GBRAIN_INTERACTIVE=1 overrides on two TTYs only, and a marker or CI forcing prompts off prints one stderr line per process naming it and the override. Neither variable implies consent. readLine is the prompt read (stderr prompt; EOF/timeout = decline; {kind:'eof'} without reading when non-interactive; bytes after the newline are pushed back for the next prompt). readStdinBounded is the payload read: 30 s first-byte deadline (GBRAIN_STDIN_TIMEOUT_MS overrides; stderr notice at 5 s), 60 s inactivity reset per chunk, no total cap, 5 MB default byte cap; data/empty/timeout{phase}/cancelled/error are distinct and partial input is never data. Every reader removes its listeners and pauses the stream so the process can exit; a failed read of process stdin also destroys it. Also hosts the legacy promptLine (now '' on EOF), promptLineStderr and promptYesNo, re-exported by cli-util.ts / confirm-prompt.ts for one release; src/cli.ts keeps a legacy readStdinBounded(): string | null shim. Pinned by test/interaction.test.ts (decision table, injected streams) and test/interaction-stdin.test.ts (real stdin, PTY, natural exit).

  • src/core/ops/ — the operations contract's module directory (the meat behind the operations.ts façade). contract.ts is the foundation contract: the error envelope (ErrorCode/OperationError/verbError), the shared param/logger/auth/context types, and the Operation interface — re-exported wholesale by the façade. context.ts carries the context validators + scope resolvers: the upload/slug/filename validators, the subagent and bound-client slug fences, and the source-scope resolution ladder (some internal helpers are exported only here and deliberately NOT re-exported from the façade — import those from context.ts directly). The remaining modules are one-per-op-domain (pages.ts, search.ts, takes.ts, tags.ts, links.ts, timeline.ts, admin.ts, skills-catalog.ts, sync-status.ts, raw-data.ts, chunks.ts, ingest-log.ts, files.ts, jobs.ts, orphans.ts, calibration.ts, salience.ts, facts.ts, sources.ts, transcripts.ts, insights.ts, image.ts, extraction.ts, code-intel.ts, chronicle.ts, embedding-migration.ts, request-tools.ts, schema-packs.ts, skillopt.ts), each exporting a <domain>Operations map that the façade spreads into the single operations export. Add a new op in the matching domain module — an existing domain needs no façade change; a brand-new domain module gets one spread line in operations.ts. facadeExpansion in scripts/generate-flag-registry.ts maps the façade to this whole directory so every module's --flag text stays on the command flag-scan surface.

  • src/core/ops/read-paging.ts — paging for the two by-slug row reads that would otherwise return everything: get_chunks (chunks.ts: from_index default 0, limit default 50, MCP cap 500; the engine's getChunkPage returns the chunk_index range [from_index, from_index + limit) plus total_chunks and the highest index) and get_versions (admin.ts: default 20, MCP cap 100). Both keep a bare-array result; pagingLimit resolves the limit (trusted local CLI honors any explicit value; a non-positive-integer is invalid_params), and reportChunkPage / reportVersionPage emit _meta.pagination (from_index, limit, returned, total_chunks, next_from_index / limit, truncated, clamped_from), the model-visible listing_truncated notice for remote callers when rows remain (its fix is the next call), and one stderr line for a local call with no limit. Tests: test/get-chunks-paging.test.ts, test/get-versions-defaults.test.ts.

  • src/core/ops/admin.ts — the admin/diagnostics domain module (get_stats, get_health, get_brain_identity, …). get_health adds embedding_column, the registry-active vector column its coverage counts were measured on (legacy embedding when the registry is unreadable), on both engines (test/get-health-embedding-column.test.ts + its Postgres arm). get_versions reads an explicit column list (PAGE_VERSION_COLUMNS in engine-sql/pages.ts), so the write attribution columns never reach a plain read caller; trusted local callers and admin holders (canReadWriteAttribution) also get written_by and archived_by from attributeVersions. It filters protected facts/takes from both canonical body and timeline, preserves legacy missing timeline fields, and retains engine-side current/historical page privacy predicates for every snapshot field. By default it returns metadata only (no compiled_truth/timeline) for the newest 20 versions; include_body: true adds the bodies (remote-sanitized), and limit (a positive safe integer; any other explicit value is invalid_params without echoing it) takes the newest N, capped at 100 for every caller but the trusted local CLI. The handler probes one row past the limit and reports a cut history through read-paging.ts. The bound and the projection run in engine-sql/pages.ts getVersions (one query, scope and privacy predicates in WHERE before LIMIT, ORDER BY pv.snapshot_at DESC, pv.id DESC, metadata mode selects no body columns, typed PageVersionRows), so hidden versions never shift the prefix; trusted and admin callers keep written_by/archived_by (test/get-versions-response-bounds.test.ts). All three aggregate ops confine remote callers via the same ladder reads use: ctx.remote === false keeps the trusted brain-wide view; every other caller gets sourceScopeOpts(ctx) (federated array > scalar > the unmatchable __all__ sentinel, which fail-closes to zeros) threaded into engine.getStats(scope)/getHealth(scope) — aggregates leak by subtraction, so they scope exactly like reads, and read-scope get_brain_identity is confined the same way. get_health's migrations {pending, pending_fresh_install, partial, wedged, declined, skipped_future} block (declined since #6466: versions the brain's config turns off, read through declinedMigrations(engine)) stays GLOBAL for scoped callers by decision: it is a host filesystem ledger with no per-source semantics, a wedged host migration is exactly what a remote agent needs to see to explain degraded behavior, and it is composed at the op layer (not in BrainEngine.getHealth — growing the engine interface would force both engines to duplicate a file read). get_health serves repeat calls from src/core/health-memo.ts and returns computed_at, the time its counters were read.

  • src/core/ops/attribution.ts — write attribution reads (Foundations 1, F1b). resolveWriteAttributions turns stored (request id, principal kind, principal id) snapshots into WriteAttributionViews (types.ts), joining persistence_requests (operation, completed_at, agent_label), oauth_clients.client_name, access_tokens.name and the persistence_local_writers lane at read time, one query each; origin is request, maintenance (principal without request) or unrecorded (all NULL). get_write_attribution (scope admin, localOnly: false, CLI gbrain attribution <slug> [--fact <id>] [--take <row>] [--timeline <id>] [--versions]) returns { target, created, last, live_revision, versions? }; a page's created is the origin of its oldest version snapshot. The page lookup uses readPolicyOpts, so remote admins stay inside their source grant; remote fact targets are world only except for a credential bound to the brain owner (worldOnlyFacts, GST-2951), and take targets follow readHolders. Tests: test/write-attribution-read.test.ts (PGLite), test/access-owner-fact-ops-gst2951.test.ts (owner reads, both engines) and test/e2e/write-attribution-read-parity.test.ts (Postgres and PgBouncer).

  • src/core/ops/trust.ts — confirm_memory (#5575 A4, CEO-9, DX-20): the one MCP-visible owner action. Raises a fact, take or page to user_confirmed through trust/owner-actions.ts after requireOwnerConfirmation (a memory_confirm connection, or the local CLI's typed-token TTY prompt); agent tokens get insufficient_scope with a tell_user_to_run fix naming gbrain trust confirm <ref>. Trust proposals and holds are not reachable here; the other owner actions are CLI or resident-owner administration only (trust/owner-ipc.ts). It also holds promote_guest_note (GBRA-504), whose logic is guests/promote.ts.

  • src/core/guests/{promote,owner-credentials}.ts, src/commands/doctor/checks/guest-source.ts — GBRA-504 slice 4. promote.ts is promote_guest_note (CLI gbrain guests promote): isGuestPromotionOwner admits the trusted local CLI (not under GBRAIN_ENFORCED_MEMBER, not --as) and a remote or stdio caller whose CallerAccess.owner is set with no attested actor, anyone else is guest_promotion_owner_only; it writes the owner page with submitPageMutation put_page (git first where the target has a repo), carrying the note's type, title, body and readable_by plus promoted_from: <guest source>:<slug>, then inserts guest_promotions, which marker.ts loadGuestMarks reads as guest.promoted and admission.ts refuseRemoteGuestDelete reads to refuse a remote delete guest_page_promoted; it also refuses permission_denied when the note's guest mark names a writer other than the caller (both at submission in page-mutations.ts, again in the delete's publication in page-prepare.ts). owner-credentials.ts lists tokens and OAuth clients bound to access.owner_member with their read lists, the exact gbrain auth rescope ... --if-version command and whether min_trust hides guest notes; grantOwnerCredentials (gbrain guests grant-owner-clients --yes) adds the guest source as a compare-and-set on the grant revision. The doctor check guest_source reads both and changes nothing. Tests: test/guest-notes-promotion.test.ts, test/doctor-guest-source.test.ts, test/guests-grant-owner-clients.test.ts.

  • src/core/guests/{schema,sources}.ts — GBRA-504 guest sources. schema.ts is the guest-notes migration's DDL (number: guests/migration.ts): guest_sources (the authority for which sources are guest sources, their writer list of <kind>:<id> attribution principals and their tier ceiling), guest_marks (immutable: gbrain_guard_guest_records refuses UPDATE; rows leave only with their page) and guest_promotions, RLS on, and the guard that keeps a guest source database-only (no local_path). The trust trigger (trust/schema.ts GUEST_AWARE_STAMP_TIER_FUNCTION, installed by that migration; v226 keeps its own body) clamps a guest page to the ceiling on every exit, refuses a page INSERT or content change (any content column but deleted_at) unless gbrain.write_principal_kind:gbrain.write_principal_id is on the writer list, and refuses facts, takes and timeline rows there. sources.ts holds the reads and writes behind gbrain guests init and gbrain sources writers.

  • src/core/guests/{marker,stamp}.ts, src/core/access/page-items.ts, src/cli/guest-lines.ts — GBRA-504 slice 3: the guest warning on every read. marker.ts holds the GuestStamp object (sender, from guest_marks.sender_label; group, audience_member, saved_at day, promoted, writer for owner callers only, unattributed), the warning line, the quote-fence label, think's fixed Uses outside-guest notes: line, loadGuestMarks (one batched guest_marks read; a failed read leaves rows unattributed, never bare) and withGuestMarks, which operation-load.ts finalizeOperation wraps around every op whose outputRedaction is not no_stored_text. stamp.ts stampGuestNotes finds page items with page-items.ts collectPageItems (the walker shared with access/room.ts; it also reads fetch rows by their gbrain://page/ url), skips the trust load only when marker.ts brainHasGuestSource (one read of sources and guest_sources, yes when it fails) finds no guest source, reads guest rows through eligibility/stamp.ts loadPageTrust (a source is a guest source when its config says so or guest_sources lists it, guestSourceSql), and stamps a copy with origin: guest, external_untrusted and the guest object; a failed load fails the read. eligibility/labels.ts prints the warning line before the origin="guest" envelope, eligibility/activation.ts and context/turn-context.ts carry the stamp on delta, and the CLI prints it through search-row-format.ts, page-render.ts and guest-lines.ts. Publication refuses a plain write that lands after its source became a guest source (guests/admission.ts assertNoGuestSourceAtPublication). Servers list capability guest_marker_v1. Tests: test/guest-notes-warning.test.ts, test/guest-notes-contract.test.ts (every op that returns stored text, as owner over HTTP and stdio and as the audience member), test/guest-notes-shortcut.test.ts (a source marked guest without gbrain guests init is still marked).

  • src/core/health-memo.ts — in-process memo for the get_health op only (O-ENG-13). An entry is reused when engine object, scope key (all, scalar:<id>, set:<sorted unique ids>, empty for an empty or no-sources grant; derived from the exact scope handed to engine.getHealth, so no scope reads another's entry), config generation (hash of the orphan exclusions, embedding column registry keys and schema pack setting), page clock (page_generation_clock_seq.last_value plus the persistence_brain id) and TTL all match. TTL: GBRAIN_HEALTH_CACHE_TTL_MS, else config health.cache_ttl_ms, else 30000 ms; 0 disables. The TTL bounds staleness from writes that do not touch pages (links, timeline rows, chunks). A failed clock/config read computes uncached. engine.getHealth stays uncached, so doctor, remediation, maintain, embedding migration and repair verification always read fresh numbers; gbrain repair --apply and gbrain doctor --remediate call clearHealthMemo. Pinned by test/health-memo.test.ts.

  • src/core/ops/context.ts (source-id confinement helpers) — assertSourceInCallerScope(ctx, id) is the READ-scope confinement for an explicitly named source id (sources_status): untrusted callers may only name an id inside the sourceScopeOpts ladder. assertSourceInCallerWriteScope(ctx, id) is its WRITE-authority twin for destructive source ops (sources_remove): federation (ctx.auth.allowedSources) is read authority and confers no removal right, so a bound untrusted caller (write source ctx.auth.sourceId ?? ctx.sourceId, and/or any federated grant) may name only its own write source; a bound caller with no write source (or the __all__ sentinel) may name nothing; an unbound untrusted caller keeps full authority; trusted local passes. Both answer OperationError('not_found', 'Unknown source: <id>'). resolveRequestedScope(ctx, sourceId, allSources, explicitReads?) takes an optional explicit-read admission set (#5081) that only federatedSearchScope passes: a granted token admits nothing extra, a stdio connection bound by GBRAIN_SOURCE/.gbrain-source admits ctx.explicitReadBinding.sourceIds, and an unbound connection admits its own localFederatedSourceIds; its denial hint names why (token grant, binding, opted-out source) with docs/guides/multi-source-brains.md#explicit-reads-from-a-bound-agent-connection. Image, loops and code-intel pass nothing and keep the original denial (test/explicit-read-admission-5081.test.ts, test/serve-stdio-bound-explicit-read.test.ts). enforceSubagentSlugFence stays fail-closed on a missing subagentId; its one exception (#5994) is a failed-writes replay whose replayAuthority is restricted and whose allow-list equals the stored non-empty delegatedPrefixes exactly, and the slug must still match it. isOpPageSlug is the validatePageSlug grammar as a predicate; page-prepare's prepareFileTarget returns no file for a slug outside it, so an admitted legacy row publishes database-only and never removes a file its stale source_uri/source_path names (#6212).

  • src/core/ops/insights.ts — find_contradictions (filtered, takes min_trust) returns the stored report as written only to explicitly trusted, unscoped, unfloored local callers. Remote, source-scoped and floored callers get eval-contradictions/scoped-read.ts findings (both sides re-read live, total_visible instead of the run total); a remote context with no source scope gets an empty list and a note. Expert search threads page and holder policy and performs final authorized-page admission after enrichment.

  • src/core/ops/links.ts — the link-domain op module (add_link, remove_link, get_links, get_backlinks, list_link_sources, traverse_graph); get_backlinks' type/group/limit/cursor live in backlinks-paged.ts. Three load-bearing behaviors. (1) Pack vocabulary at the write surface: an EXPLICIT link_type on add_link must be declared by the active schema pack when one resolves (schema-pack/write-vocabulary.ts; no resolvable pack = no enforcement; omitted/empty link_type is the untyped-edge default and stays unchecked; the check runs before the dry-run return so dry runs preview the rejection). (2) traverse_graph output shape: trusted local no-filter callers (ctx.remote === false, no link_type/direction) keep the legacy GraphNode[] shape that gbrain graph renders; remote callers default to direction: 'both' and always receive explicit GraphPath[] edges, so a page whose typed edges are all inbound does not read as edge absence. An explicit direction param wins for every caller. Depth: default 5 (DEFAULT_TRAVERSE_DEPTH), except a remote call that let direction default to both ALSO defaults depth to REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH (2) — bidirectional path enumeration is combinatorial on entity hubs and this is the per-agent-turn path; a link_type-only remote call still takes both/2; an explicit depth is honored up to TRAVERSE_DEPTH_CAP (10, clamped with a warn). The edge walk runs through engine.traversePathsDetailed, and a hit on TRAVERSE_PATH_ROW_CAP (engine-constants.ts) surfaces as a stderr warn naming the cap (shallowest edges kept) — the GraphPath[] wire shape stays unchanged. Pinned by test/traverse-graph-op-default.test.ts + test/traverse-paths-row-cap.test.ts. (3) Link-read source scope: the three read ops take source_id (parseSourceIdParam, __all__ admitted) and all_sources (equivalent to __all__; both together is invalid_params). resolveLinkReadScope composes federatedSearchScope (grant check, #5081 admission, unqualified no-grant widening to localFederatedSourceIds; a grant never widens), then assertExplicitSourceLive (so an archived source outside the caller's admission answers permission_denied, not unknown_source), then linkReadScopeOpts (remote scalar promoted to sourceIds[] for the engine's all-endpoints branch), then readPolicyOpts. A trusted local unqualified read that comes back as the federated sourceIds[] runs the scalar read once per federated source (set order, resolved source first) and merges de-duplicated on link identity, keeping the scalar branch's cross-source far endpoints; traverse_graph walks the federated set in one query because its scalar walk already scopes every node. A trusted local unqualified link read that returns nothing prints a stderr rerun hint naming sources outside the read that hold links for the slug (quiet under json, never for remote callers). CLI names: links (alias get_links), backlinks, graph. (4) Row paging (#6876): rows are keyset-paged by ops/link-paging.ts (cap after the source/identity merge; see its header). Pinned by test/link-read-paging.test.ts. Pinned by test/federated-link-reads-5827.test.ts, test/link-reads-thin-client-5827.serial.test.ts and test/e2e/federated-link-reads-postgres.test.ts. traverse_graph hops (1-3 {link_type, toward}) runs a typed chain through runRelationalChain under the op's read scope, returns {anchor, answers, paths, diagnostics} with evidence edges (remote context sanitized), sets depth/link_type/direction aside (set_aside), refuses bad hops as invalid_params naming the parameter path, and emits a relational_chain notice with the next call when the chain finds nothing. Pinned by test/traverse-graph-hops.test.ts. all_sources is full-surface-only (starter passes source_id: '__all__').

  • src/core/ops/pages.ts — page operations share source validation and the persistence coordinator. Replacements require expected_revision or explicit force; omitted preconditions permit creation only. The put_page description keeps Keep a request_id UUID; retry with identical arguments within its schema budget (pinned by test/mcp-schema-budget.test.ts minimum guidance; the description and the content param keep the get_page include_content:true read that test/mcp-tool-defs.test.ts pins). get_page and fetch use page-state/snapshot.ts for exact/alias resolution, content, tags, revision and withdrawal overlays in one SQL snapshot; fuzzy fallback uses a short repeatable-read transaction with the same visibility and source ceilings. get_page content_only (ops/get-page-projection.ts) returns slug, source_id, type, title, revision, tags, content and chars (keys pinned by test/get-page-content-roundtrip-2225.test.ts). A put_page revision_conflict (ops/put-page-revision-source.ts) whose expected_revision is the current revision of the same slug in another source the caller may read (grant via federatedSearchScope, private pages excluded for untrusted readers) names that source and gets a re-read fix; otherwise the refusal is unchanged. get_page adds file_held when sync holds the page's newer file (persistence/held-reads.ts; path for trusted local callers only). Missing migration dependencies and connection errors propagate. Capture freezes target/type/timestamp/provenance before admission and resolves same-ID replay first. persistence/links-preparation.ts prepares trusted automatic graph reconciliation outside locks, then installs it with canonical projections and the receipt; delayed oneshot reconciliation validates its originating revision. persistence/page-advisories.ts prepares bounded, content-free lint findings. Tests: source/alias ownership, concurrent graph replacements, stale delayed reconciliation, private fences, durable retries. list_pages passes listColumnsOnly so engine-sql/pages.ts:listPages projects identity, type, title and dates without reading page bodies or frontmatter (list-pages-columns-5154.test.ts). delete_page accepts a strict boolean purge only from trusted local callers. Immediate purge uses the same durable journal, observed revision (or explicit force), stored/current authority and exact request-ID replay as other page mutations. Owner preparation resolves the recorded file from a coherent snapshot, including tombstones; file removal precedes hard deletion and receipt commitment in the guarded publication transaction. Failed publication preserves the prior active row or existing tombstone and never overwrites unexpected file bytes. The receipt reports the filesystem/database persistence outcome and warns that repository history, synced copies, exports and derived artifacts may retain content. The gbrain delete <slug> --purge flag derives from the operation contract. list_pages probes limit + 1 rows: a local CLI caller gets a stderr truncation notice; every dispatched caller gets _meta.pagination (truncated, limit, clamped_from?, next?) and a truncated remote page also gets the model-visible listing_truncated notice (fix.mcp: the next-page call) (ops/list-pages-pagination.ts; next is the updated_asc keyset or an offset). Test: test/list-pages-truncation.test.ts. An unused type adds an empty_retrieval notice naming visible types (GBRA-449). An updated_after the database cannot cast (SQLSTATE 22007/22008, the shared isDatetimeInputError in core/utils.ts) is invalid_params with a read-only list_pages fix, never echoing the value; other SQLSTATEs pass through (test/list-pages-timestamp-input.test.ts). put_page (dry runs included) refuses a new .md/.mdx-suffixed slug (persistence/suffixed-slug.ts). #6212: delete_page and restore_page (dry runs included) go through persistence/page-mutations.ts:validateMutationSlug, which admits a legacy stored slug (ops/context.ts:isLegacyStoredPageSlug: refused by today's grammar, still accepted by validateSlug) only when an existing row in the target source holds it; every other operation keeps validatePageSlug, and remote purge stays denied by assertPurgeParams. Large pages: get_page resolves its body mode first (parseBodyRequest, ops/get-page-body.ts) and returns readPartialBody for none/outline/window/auto-above-256 KB, assertFullReadFits guarding whole remote reads; fetch of a page over the inline size returns fetchWindowResult (window around the id's chunk anchor, metadata.next_id); remote put_page runs assertLargePageAdmission before queueing. A committed segmented write's outcome records searchable (true, 'pending' when its projection runs after commit, false when quarantined); persistence/searchable.ts:liveSearchable re-reads a pending one whenever the receipt is served (the put_page reply in page-mutations.ts, get_write_request) and adds searchable_retry_after_ms and a searchable_fix that reads the receipt again (test/large-pages/segmented-create-searchable.test.ts). Only writes load page-mutations.ts (test/cold-read-module-graph.test.ts). The starter list leaves out (fullSurfaceOnly, still accepted) get_page fuzzy/content_only/include_deleted/include_timeline_entries/include_quarantined, list_pages offset/include_deleted, put_page allow_empty/drop_timeline (refusals name them), the write ops' reason and the server-set provenance params, and capture expected_revision/force/local_file.

  • src/core/persistence/large-page-guard.ts — put_page against a page over 256 KB: assertLargePageAdmission (remote, before queueing) refuses force without expected_revision (revision_required) and content under half the stored body (page_shrink_refused) unless allow_shrink; assertLargePageReplacement re-checks the parsed body against the locked snapshot in preparation (page-prepare.ts).

  • src/core/ops/page-edit.ts — the edit_page operation (write scope, starter surface, client slug-fence allowlist): validates edits and the optional within range (full surface only), then submits through submitPageMutation like put_page; matching and the diff live in persistence/page-edit.ts.

  • src/core/ops/persistence.ts — get/list/cancel own-write receipt controls, all requiring write scope and an explicit current operation grant. SQL principal/source/incarnation plus current operation and prefix predicates precede list pagination; original accepted authority and current source/slug grants remain the final guard. Public output selects receipt fields and target metadata only; a failed receipt adds write_error_message, the same allowlisted writeFailureDiagnostic message managed sync prints, never raw journal error text (test/sync-frontmatter-slug-conflict.test.ts). A terminal or recovery-holding receipt also returns write_error_reason, suggestion and a diagnosis from classifyTerminal with a rendered fix (#6650, test/write-request-diagnosis-6650.test.ts). Cancellation rechecks receipt permission under the same transaction grant locks as the original write. Starter/full expose the helpers (list_write_requests limit is full-surface-only); frozen verbs stay unchanged, and existing operation snapshots require explicit regrant. Tests: test/persistence-receipt-operations.test.ts, test/client-grants.test.ts, test/mcp-surface.test.ts.

  • src/core/ops/raw-data.ts — put_raw_data / get_raw_data. get_raw_data follows the page soft-delete (a tombstoned page reads as [], restore_page brings the rows back; there is no remote include_deleted param — get_page include_deleted: true verifies the tombstone) and, per #4352, a visibility: private page's raw data reads exactly like a missing page's for untrusted callers. Scope comes from readPolicyOpts(ctx), never from MCP parameters.

Continued in Core Services (2/3, more).