Garry's Opinionated OpenClaw/Hermes Agent Brain
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 everytest_positive[]+test_negative[]sample at startup so a typo in any built-in regex makes gbrain refuse to start;DEFAULT_SPEAKER_CLEANexported as a module-level default),parse.ts(orchestrator with pattern-priority scoring across the first 10 lines + date derivation chainexplicit > frontmatter.date > effective_date > '1970-01-01'+ multi-line continuation + timezone warning; #5430 (W14 P1.9): a validfrontmatter.timezone(IANA) converts every built timestamp from that zone's wall clock to UTC throughlocalToUtcIso(date, hour, minute, tz)(IntllongOffset, no dependency, host-TZ independent; a DST fold takes the first occurrence, a gap the pre-transition offset), an invalid zone is reported asDateContext.invalid_timezoneand the warning names it while timestamps stay UTC (test/conversation-parser/timezone.test.ts); also populatesParseResult.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 returnsregex_match, silently crediting one speaker with another's words; detection is diagnostic-only and unconditional (not behindopts.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 scansurfaces the field in both human and JSON output;applyPatternnever 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 asParseResult.date_fallback_count, undefined when zero),llm-base.ts(sharedrunLlmCall<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+parseFixtureJsonlfor 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 returnsskippedwithfixture_unavailable, which the autopilot wiring audits, and the wiring reads the embedded fixtures fromcycle/nightly-probe-fixtures.ts). Patternbold-name-no-time(regex/^\*\*(?!\[)(.+?):\*\*\s*(.*)$/, ordered after the time-bearing bold patterns) parses**Speaker:** textwith NO per-line timestamp (Circleback/Granola/Zoom), anchoring every message atT00:00:00Zof the frontmatter date (line order preserves sequence, same no-time convention asirc-classic); the(?!\[)lookahead rejects telegram-bracket**[18:37] Name:**; non-shadow is the colon-INSIDE-bold regex (NOT declaration order —parse.tsscores every candidate independently, order is only the tie-break). Because**Label:** textis a common prose idiom, the pattern sets optionalPatternEntry.score_full_body: truesoparse.tsrecomputes the winner's acceptance score over the FULL body before theSCORING_MIN_ACCEPTANCEfloor, keeping a bold-label notes page atno_match. Patternchatgpt-export-you-chatgpt(regex/^\*\*(You|ChatGPT):\*\*\s*(.*)$/, declared just beforebold-name-no-timeso 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-timealone cannot absorb that shape (multi_line: falsescores a long reply's density near zero and falls belowSCORING_MIN_ACCEPTANCE), so this pattern setsmulti_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 (YouorChatGPTexactly, never an arbitrary(.+?)label), so it cannot reopenbold-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 optionalPatternEntry.score_continuations_min_distinct_speakers: 2:scoreFromLinesonly grants the continuation-density-exclusion score when the anchor lines that fully matchregexcollectively capture at least that many DISTINCTspeaker_groupvalues, so a page with only one role falls back to the ordinary flat-density score. It ALSO setsPatternEntry.score_continuations_max_preamble_lines: 5, because one genuine pair embedded deep in an unrelated long document would otherwise pass:scoreFromLinestracks 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). Patternbold-paren-timeparses**Speaker** (HH:MM): textand(HH:MM:SS)(date_source: frontmatter). Fallback gates:SCORING_HEAD_TRIGGER_THRESHOLD = 0.3triggers a full-body re-score when the head pass scores below that;SCORING_MIN_ACCEPTANCE = 0.05blocks essay false-positives. ExportedscorePatternFull(body, entry); privategetNonBlankLines(body, headCap?)+scoreFromLines(lines, entry)DRY the quick_reject+regex loop. CLI surfaces atsrc/commands/eval-conversation-parser.ts(gbrain eval conversation-parser <fixture.jsonl>exit 0/1/2, wired intobun run verifyviacheck:conversation-parser) andsrc/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 bytest/conversation-parser/{parse,llm-base,llm-fallback,nightly-probe}.test.ts+ the 27-case baseline attest/extract-conversation-facts.test.ts(back-compat invariant). Migration v97 (conversation_parser_llm_cache_table). Fixtures attest/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}.jsonlwithscripts/check-fixture-privacy.shbanning real-name leaks. Maintainer guidance: conversation parser patterns.src/core/facts/conversation-windows.ts— conversation windowing forextract-conversation-facts(#6267, wave 15 P2.5):splitIntoSegments(messages, { gapMinutes, maxMessages, sinceIso, maxChars, pageTitle })cuts gap groups, keeps only groups withMIN_SEGMENT_MESSAGES(2) original messages, then packs each eligible group into windows bounded byDEFAULT_SEGMENT_MAX_MESSAGES(30) andSEGMENT_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 bysplitTurnTextat sentence, then whitespace, then code-point boundaries (never inside a surrogate pair;pieces.join('')is the original) with thespeaker (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 bytest/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):isConversationFactsEligiblePageand its SQL twinconversationFactsEligibleSqladmit an allowed concrete type unless frontmatter saysconversation_parseable: false; withcycle.conversation_facts_backfill.require_parseable_flagon, onlytype: conversationorconversation_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 undersrc/core/facts/(notsrc/commands/) becausescripts/generate-flag-registry.tsscans option-shaped literals one relative-import level deep — importing the constant straight fromextract-conversation-facts.tswould transitively attribute that command's whole option surface to doctor/jobs/sources in the generated CLI_ONLY registry. Drift-guarded bytest/conversation-facts-type-allowlist-drift.test.ts.isFrontmatterFlagOff(the same off spellings) is shared withfacts/eligibility.ts. Since #6267 it also owns theConversationMessage,ConversationSegmentandSplitSegmentsOptstypes the windowing module and the command share.src/core/facts/eligibility.ts—isFactsBackstopEligible, the one automatic facts-extraction predicate (page-write outbox, itsbody_unchangedcheck, sync's post-import hook, the facts-absorb job's re-check). Skipswiki/agents/,dream_generated: true,facts_backstopset 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 outsideELIGIBLE_TYPESunless the slug is under a rescue prefix (conversation-pipeline types,CONVERSATION_PIPELINE_TYPES, skip asconversation_pipeline, #6557: the opt-in conversation facts backfill owns them; doctorfacts_extraction_healthnames the opt-in and its caps when such pages exist and the backfill is off). Receipt reasons are documented underfacts_backstop_skippedin the error registry. Pinned bytest/facts-eligibility.test.ts,test/persistence-facts-backstop.test.ts. #6259: a quarantined page (the gate'squarantinemarker) is ineligible with reasonquarantined, which the page-write receipt reports asfacts_backstop.skipped(registered infacts_backstop_skipped).src/core/facts/extract.ts— the LLM facts extractor (extractFactsFromTurnWithOutcomeand friends; the output cap, truncation retry, and salvage behavior are described under the trajectory entry). The first call and the truncation retry sendcacheSystem: 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 theresolveModelDetailedchain on thereasoningtier); when nothing chose one and the tier's key-aware default resolved through Anthropic,FACTS_EXTRACTION_MEASURED_DEFAULTSsubstitutesanthropic:claude-haiku-5-5(sourcemeasured_default; the facts-absorb quality gate, gbrain-evalsdocs/benchmarks/2026-10-08-facts-extraction-model.md), andgbrain modelsreports that row through the same resolver.getFactsExtractionModelis its string wrapper. Deterministic junk gate:isJunkFact(text, kind?)testsJUNK_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 classifiedcommitmentis 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);getFactsExtractionPromptAppendixsupplies the config-driven prompt appendix. Entity gate at the candidate loop (the ONE seam where LLM-emitted entity tokens becomeentity_slug):isUnknownSpeakerLabel(anonymous diarizer labels —Speaker A,SPEAKER_00,spk_0,other|unknown|guest) andisNullLikeEntity(placeholder STRINGS"null"/"None"/"n/a"where the prompt asked for JSON null; shared withwrite-single.ts) both null the attribution and KEEP the fact, so no consumer can mintentity_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) andfacts.extraction_junk_filter(falsedisables the deterministic junk gate; default on), plus the opt-infacts.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 asfactbut counted in a stderr warning. Every extractorchat()call (first attempt, the #2113 truncation retry, the malformed-output retry) carriesresponseSchema: FACTS_EXTRACTION_SCHEMA(mirrorsRawExtracted:facts[]of{fact, kind ∈ ALL_EXTRACT_KINDS}plusentity/confidence/notability/metric/value/unit/period— EVERY property inrequired, the optional ones nullable via type unions,additionalProperties: falseat both levels, so the schema is OpenAI-strict-safe for proxies that honor the SDK's defaultstrict: 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, whileparseExtractorJsonDetailedstill 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 bytest/facts-extract-currency-examples-6274.test.ts. Pinned bytest/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 throughfacts/withdrawal.ts. WithsupersededBy: { rowNum }(thewriteSingleFactsupersession path) it only expires the row and strikes it with a page-local#Nsupersession 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.strikeFenceRowandsupersededFactare exported for the S9 checked supersede (facts/proposal-supersede.ts).strikeFenceRowreturns 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 bytest/forget-reconcile-durability.test.ts,test/privacy-strip-and-forget.test.ts, andtest/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, withstrikeFenceRow'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 ofsrc/core/audit-slug-fallback.ts(ISO-week rotation, honorsGBRAIN_AUDIT_DIR). ExportslogPhantomEvent(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 fromstub-guard-audit.ts(distinct consumer + lifecycle: stub-guard logs PREVENTIVE blocks; phantom-audit logs CLEANUP decisions, to be read by a futurephantoms_pendingdoctor check).src/core/facts/queue.ts:FactsQueue.drainPending— methoddrainPending({timeout?: number}): Promise<{drained, unfinished}>. Semantically distinct fromshutdown()(which callsthis.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 timeout1000msso commands that don't enqueue facts pay one fast 0ms check before exit.src/cli.tsop-dispatch finally block awaitsgetFactsQueue().drainPending({timeout: 1000})BEFOREengine.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 aftergbrain capture(a post-page-write facts:absorb outliving the CLI process). Pinned bytest/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)).subjectis the forgotten row'sentity_slug; '' (all subjects) covers subjectless facts and rows recorded before v169. A withdrawal matches whensubject = '*' 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, viamoveSlugBindings) 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 bynormalizeLoweredClaim) 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 exactgbrain_fact_fingerprint_v1hash 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 buildsidx_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 (onelower(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 reasonsplit_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.writeSingleFactrefuses an identical withdrawn claim for the resolved entity before embedding, using the protocol error envelope.writeFactsToFencerechecks each input under the page lock and drops claims withdrawn for the page's entity (reportingwithdrawnSkipped), 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 explicitforgotten:markers; Markdown-only copies do not preserve DB-only withdrawals. Pinned bytest/facts-withdrawal-subject.test.ts,test/fact-withdrawal-normalized.test.ts,test/withdrawal-bounded-safety.test.ts(both engines) and the Postgres scale gatetest/e2e/fact-withdrawal-scope-postgres.test.ts.recordFactWithdrawal(…, { semanticReview })also queues awithdrawreview row indecide_review_queueinside the same transaction whendecide.slots.conflict.review_withdrawis on (unset counts as on;reviewWithdrawOn) and the caller did not opt out, and runs everyregisterWithdrawalInvalidationhook in that transaction for projections beyond pages and chunks.src/core/facts/similar-active.ts—similarActiveAfterForget: after a committedforget, 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 anextline (zero model calls; pinned bytest/decide/review-withdraw.serial.test.ts). Segmented affected pages are struck segment by segment throughrewriteLiveSegmentedFences(a new generation whose flip replaces only the rewritten occurrences' chunks); discovery also scans live manifest rows withfacts_slots, reading only each slot's bytes, and joins a fence a forced cut split from its slots' bytes (splitFactsFences; abovePAGE_MAX_BYTESit refuses withpage_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 behindremember.runFactsPipelineis 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#Nsupersession reference and records no withdrawal, + superseded_by link; DB path: engine insertFact supersedeId). Pinned bytest/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 theresolved?.slug ?? entityReffallback can never adopt"null"as a slug. On a managed brain, after the withdrawal check and embedding, the fact publishes throughpublishManagedEntityFacts(src/core/facts/managed-fact-write.ts, themanaged_facts_entityintent: fence row, index row and file together, dedup at publication, and the same-kind near-duplicate supersession rule via the intent'ssupersedeflag, 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 onmemory/unattributedand, through the intent's opt-inattribute_fallbackflag, which only writeSingleFact sets, keeps the resolver's fallback slug asentity_slugwith 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 typedfenceRefusal(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 vanishedsource_pathfile, or tombstoned),writeFactsToFencereturnsstubGuardBlockedwith audit reasondb_only_pageand the caller records the facts DB-only, so no stub overwrites the DB body or resurrects a deleted page; an unreadable row returnsfenceWriteFailed; the #4872 page mirror runs only for a body read from a real file. Doctorstub_guard_24h(commands/doctor/checks/local-audits.ts) countsunprefixed,fallback_resolutionanddb_only_pageseparately;db_only_pagenever 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;attributeFallbacksets the intent'sattribute_fallback), keeps a caller's vector only when it matches the brain's facts embedding signature, and returns ids in input order;managedFactWritePreflightruns 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 noGBRAIN_NON_INTERACTIVE,CIor agent-process marker (agentProcessMarker():CLAUDECODE,CLAUDE_CODE_ENTRYPOINT,CODEX_SANDBOX,CODEX_CI,OPENCODE,OPENCODE_PID; neverCODEX_HOME);GBRAIN_INTERACTIVE=1overrides on two TTYs only, and a marker orCIforcing prompts off prints one stderr line per process naming it and the override. Neither variable implies consent.readLineis 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).readStdinBoundedis the payload read: 30 s first-byte deadline (GBRAIN_STDIN_TIMEOUT_MSoverrides; stderr notice at 5 s), 60 s inactivity reset per chunk, no total cap, 5 MB default byte cap;data/empty/timeout{phase}/cancelled/errorare distinct and partial input is neverdata. 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 legacypromptLine(now''on EOF),promptLineStderrandpromptYesNo, re-exported bycli-util.ts/confirm-prompt.tsfor one release;src/cli.tskeeps a legacyreadStdinBounded(): string | nullshim. Pinned bytest/interaction.test.ts(decision table, injected streams) andtest/interaction-stdin.test.ts(real stdin, PTY, natural exit).src/core/ops/— the operations contract's module directory (the meat behind theoperations.tsfaçade).contract.tsis the foundation contract: the error envelope (ErrorCode/OperationError/verbError), the shared param/logger/auth/context types, and theOperationinterface — re-exported wholesale by the façade.context.tscarries 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 fromcontext.tsdirectly). 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>Operationsmap that the façade spreads into the singleoperationsexport. 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 inoperations.ts.facadeExpansioninscripts/generate-flag-registry.tsmaps the façade to this whole directory so every module's--flagtext 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_indexdefault 0,limitdefault 50, MCP cap 500; the engine'sgetChunkPagereturns the chunk_index range [from_index, from_index + limit) plustotal_chunksand the highest index) andget_versions(admin.ts: default 20, MCP cap 100). Both keep a bare-array result;pagingLimitresolves the limit (trusted local CLI honors any explicit value; a non-positive-integer isinvalid_params), andreportChunkPage/reportVersionPageemit_meta.pagination(from_index,limit,returned,total_chunks,next_from_index/limit,truncated,clamped_from), the model-visiblelisting_truncatednotice 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_healthaddsembedding_column, the registry-active vector column its coverage counts were measured on (legacyembeddingwhen the registry is unreadable), on both engines (test/get-health-embedding-column.test.ts+ its Postgres arm).get_versionsreads an explicit column list (PAGE_VERSION_COLUMNSinengine-sql/pages.ts), so the write attribution columns never reach a plainreadcaller; trusted local callers andadminholders (canReadWriteAttribution) also getwritten_byandarchived_byfromattributeVersions. 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 (nocompiled_truth/timeline) for the newest 20 versions;include_body: trueadds the bodies (remote-sanitized), andlimit(a positive safe integer; any other explicit value isinvalid_paramswithout 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 throughread-paging.ts. The bound and the projection run inengine-sql/pages.tsgetVersions(one query, scope and privacy predicates in WHERE beforeLIMIT,ORDER BY pv.snapshot_at DESC, pv.id DESC, metadata mode selects no body columns, typedPageVersionRows), so hidden versions never shift the prefix; trusted and admin callers keepwritten_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 === falsekeeps the trusted brain-wide view; every other caller getssourceScopeOpts(ctx)(federated array > scalar > the unmatchable__all__sentinel, which fail-closes to zeros) threaded intoengine.getStats(scope)/getHealth(scope)— aggregates leak by subtraction, so they scope exactly like reads, and read-scopeget_brain_identityis confined the same way.get_health'smigrations {pending, pending_fresh_install, partial, wedged, declined, skipped_future}block (declinedsince #6466: versions the brain's config turns off, read throughdeclinedMigrations(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 inBrainEngine.getHealth— growing the engine interface would force both engines to duplicate a file read).get_healthserves repeat calls fromsrc/core/health-memo.tsand returnscomputed_at, the time its counters were read.src/core/ops/attribution.ts— write attribution reads (Foundations 1, F1b).resolveWriteAttributionsturns stored (request id, principal kind, principal id) snapshots intoWriteAttributionViews (types.ts), joiningpersistence_requests(operation,completed_at,agent_label),oauth_clients.client_name,access_tokens.nameand thepersistence_local_writerslane at read time, one query each;originisrequest,maintenance(principal without request) orunrecorded(all NULL).get_write_attribution(scopeadmin,localOnly: false, CLIgbrain attribution <slug> [--fact <id>] [--take <row>] [--timeline <id>] [--versions]) returns{ target, created, last, live_revision, versions? }; a page'screatedis the origin of its oldest version snapshot. The page lookup usesreadPolicyOpts, so remote admins stay inside their source grant; remote fact targets areworldonly except for a credential bound to the brain owner (worldOnlyFacts, GST-2951), and take targets followreadHolders. Tests:test/write-attribution-read.test.ts(PGLite),test/access-owner-fact-ops-gst2951.test.ts(owner reads, both engines) andtest/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 touser_confirmedthroughtrust/owner-actions.tsafterrequireOwnerConfirmation(amemory_confirmconnection, or the local CLI's typed-token TTY prompt); agent tokens getinsufficient_scopewith atell_user_to_runfix naminggbrain 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 holdspromote_guest_note(GBRA-504), whose logic isguests/promote.ts.src/core/guests/{promote,owner-credentials}.ts,src/commands/doctor/checks/guest-source.ts— GBRA-504 slice 4.promote.tsispromote_guest_note(CLIgbrain guests promote):isGuestPromotionOwneradmits the trusted local CLI (not underGBRAIN_ENFORCED_MEMBER, not--as) and a remote or stdio caller whoseCallerAccess.owneris set with no attested actor, anyone else isguest_promotion_owner_only; it writes the owner page withsubmitPageMutationput_page (git first where the target has a repo), carrying the note's type, title, body andreadable_bypluspromoted_from: <guest source>:<slug>, then insertsguest_promotions, whichmarker.tsloadGuestMarksreads asguest.promotedandadmission.tsrefuseRemoteGuestDeletereads to refuse a remote deleteguest_page_promoted; it also refusespermission_deniedwhen the note's guest mark names a writer other than the caller (both at submission inpage-mutations.ts, again in the delete's publication inpage-prepare.ts).owner-credentials.tslists tokens and OAuth clients bound toaccess.owner_memberwith their read lists, the exactgbrain auth rescope ... --if-versioncommand and whethermin_trusthides guest notes;grantOwnerCredentials(gbrain guests grant-owner-clients --yes) adds the guest source as a compare-and-set on the grant revision. The doctor checkguest_sourcereads 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.tsis 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_recordsrefuses UPDATE; rows leave only with their page) andguest_promotions, RLS on, and the guard that keeps a guest source database-only (nolocal_path). The trust trigger (trust/schema.tsGUEST_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 butdeleted_at) unlessgbrain.write_principal_kind:gbrain.write_principal_idis on the writer list, and refuses facts, takes and timeline rows there.sources.tsholds the reads and writes behindgbrain guests initandgbrain 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.tsholds theGuestStampobject (sender, fromguest_marks.sender_label;group,audience_member,saved_atday,promoted,writerfor owner callers only,unattributed), the warning line, the quote-fence label, think's fixedUses outside-guest notes:line,loadGuestMarks(one batchedguest_marksread; a failed read leaves rows unattributed, never bare) andwithGuestMarks, whichoperation-load.tsfinalizeOperationwraps around every op whoseoutputRedactionis notno_stored_text.stamp.tsstampGuestNotesfinds page items withpage-items.tscollectPageItems(the walker shared withaccess/room.ts; it also readsfetchrows by theirgbrain://page/url), skips the trust load only whenmarker.tsbrainHasGuestSource(one read ofsourcesandguest_sources, yes when it fails) finds no guest source, reads guest rows througheligibility/stamp.tsloadPageTrust(a source is a guest source when its config says so orguest_sourceslists it,guestSourceSql), and stamps a copy withorigin: guest,external_untrustedand theguestobject; a failed load fails the read.eligibility/labels.tsprints the warning line before theorigin="guest"envelope,eligibility/activation.tsandcontext/turn-context.tscarry the stamp ondelta, and the CLI prints it throughsearch-row-format.ts,page-render.tsandguest-lines.ts. Publication refuses a plain write that lands after its source became a guest source (guests/admission.tsassertNoGuestSourceAtPublication). Servers list capabilityguest_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 withoutgbrain guests initis still marked).src/core/health-memo.ts— in-process memo for theget_healthop only (O-ENG-13). An entry is reused when engine object, scope key (all,scalar:<id>,set:<sorted unique ids>,emptyfor an empty or no-sources grant; derived from the exact scope handed toengine.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_valueplus thepersistence_brainid) and TTL all match. TTL:GBRAIN_HEALTH_CACHE_TTL_MS, else confighealth.cache_ttl_ms, else 30000 ms; 0 disables. The TTL bounds staleness from writes that do not touchpages(links, timeline rows, chunks). A failed clock/config read computes uncached.engine.getHealthstays uncached, so doctor, remediation, maintain, embedding migration and repair verification always read fresh numbers;gbrain repair --applyandgbrain doctor --remediatecallclearHealthMemo. Pinned bytest/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 thesourceScopeOptsladder.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 sourcectx.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 answerOperationError('not_found', 'Unknown source: <id>').resolveRequestedScope(ctx, sourceId, allSources, explicitReads?)takes an optional explicit-read admission set (#5081) that onlyfederatedSearchScopepasses: a granted token admits nothing extra, a stdio connection bound byGBRAIN_SOURCE/.gbrain-sourceadmitsctx.explicitReadBinding.sourceIds, and an unbound connection admits its ownlocalFederatedSourceIds; its denial hint names why (token grant, binding, opted-out source) withdocs/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).enforceSubagentSlugFencestays fail-closed on a missingsubagentId; its one exception (#5994) is a failed-writes replay whosereplayAuthorityis restricted and whose allow-list equals the stored non-emptydelegatedPrefixesexactly, and the slug must still match it.isOpPageSlugis thevalidatePageSluggrammar as a predicate; page-prepare'sprepareFileTargetreturns no file for a slug outside it, so an admitted legacy row publishes database-only and never removes a file its stalesource_uri/source_pathnames (#6212).src/core/ops/insights.ts—find_contradictions(filtered, takesmin_trust) returns the stored report as written only to explicitly trusted, unscoped, unfloored local callers. Remote, source-scoped and floored callers geteval-contradictions/scoped-read.tsfindings (both sides re-read live,total_visibleinstead 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/cursorlive inbacklinks-paged.ts. Three load-bearing behaviors. (1) Pack vocabulary at the write surface: an EXPLICITlink_typeonadd_linkmust 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_graphoutput shape: trusted local no-filter callers (ctx.remote === false, nolink_type/direction) keep the legacyGraphNode[]shape thatgbrain graphrenders; remote callers default todirection: 'both'and always receive explicitGraphPath[]edges, so a page whose typed edges are all inbound does not read as edge absence. An explicitdirectionparam wins for every caller. Depth: default 5 (DEFAULT_TRAVERSE_DEPTH), except a remote call that let direction default tobothALSO defaults depth toREMOTE_BIDIRECTIONAL_DEFAULT_DEPTH(2) — bidirectional path enumeration is combinatorial on entity hubs and this is the per-agent-turn path; alink_type-only remote call still takes both/2; an explicit depth is honored up toTRAVERSE_DEPTH_CAP(10, clamped with a warn). The edge walk runs throughengine.traversePathsDetailed, and a hit onTRAVERSE_PATH_ROW_CAP(engine-constants.ts) surfaces as a stderr warn naming the cap (shallowest edges kept) — theGraphPath[]wire shape stays unchanged. Pinned bytest/traverse-graph-op-default.test.ts+test/traverse-paths-row-cap.test.ts. (3) Link-read source scope: the three read ops takesource_id(parseSourceIdParam,__all__admitted) andall_sources(equivalent to__all__; both together isinvalid_params).resolveLinkReadScopecomposesfederatedSearchScope(grant check, #5081 admission, unqualified no-grant widening tolocalFederatedSourceIds; a grant never widens), thenassertExplicitSourceLive(so an archived source outside the caller's admission answerspermission_denied, notunknown_source), thenlinkReadScopeOpts(remote scalar promoted tosourceIds[]for the engine's all-endpoints branch), thenreadPolicyOpts. A trusted local unqualified read that comes back as the federatedsourceIds[]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_graphwalks 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 underjson, never for remote callers). CLI names:links(aliasget_links),backlinks,graph. (4) Row paging (#6876): rows are keyset-paged byops/link-paging.ts(cap after the source/identity merge; see its header). Pinned bytest/link-read-paging.test.ts. Pinned bytest/federated-link-reads-5827.test.ts,test/link-reads-thin-client-5827.serial.test.tsandtest/e2e/federated-link-reads-postgres.test.ts.traverse_graphhops(1-3{link_type, toward}) runs a typed chain throughrunRelationalChainunder the op's read scope, returns{anchor, answers, paths, diagnostics}with evidence edges (remote context sanitized), setsdepth/link_type/directionaside (set_aside), refuses bad hops asinvalid_paramsnaming the parameter path, and emits arelational_chainnotice with the next call when the chain finds nothing. Pinned bytest/traverse-graph-hops.test.ts.all_sourcesis full-surface-only (starter passessource_id: '__all__').src/core/ops/pages.ts— page operations share source validation and the persistence coordinator. Replacements requireexpected_revisionor explicitforce; omitted preconditions permit creation only. The put_page description keepsKeep a request_id UUID; retry with identical argumentswithin its schema budget (pinned bytest/mcp-schema-budget.test.tsminimum guidance; the description and the content param keep the get_page include_content:true read thattest/mcp-tool-defs.test.tspins).get_pageandfetchusepage-state/snapshot.tsfor 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_pagecontent_only(ops/get-page-projection.ts) returns slug, source_id, type, title, revision, tags, content and chars (keys pinned bytest/get-page-content-roundtrip-2225.test.ts). A put_pagerevision_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 viafederatedSearchScope, private pages excluded for untrusted readers) names that source and gets a re-read fix; otherwise the refusal is unchanged.get_pageaddsfile_heldwhen 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.tsprepares 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.tsprepares bounded, content-free lint findings. Tests: source/alias ownership, concurrent graph replacements, stale delayed reconciliation, private fences, durable retries.list_pagespasseslistColumnsOnlysoengine-sql/pages.ts:listPagesprojects identity, type, title and dates without reading page bodies or frontmatter (list-pages-columns-5154.test.ts).delete_pageaccepts a strict booleanpurgeonly from trusted local callers. Immediate purge uses the same durable journal, observed revision (or explicitforce), 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. Thegbrain delete <slug> --purgeflag derives from the operation contract.list_pagesprobeslimit + 1rows: 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-visiblelisting_truncatednotice (fix.mcp: the next-page call) (ops/list-pages-pagination.ts;nextis theupdated_asckeyset or an offset). Test:test/list-pages-truncation.test.ts. An unusedtypeadds anempty_retrievalnotice naming visible types (GBRA-449). Anupdated_afterthe database cannot cast (SQLSTATE 22007/22008, the sharedisDatetimeInputErrorincore/utils.ts) isinvalid_paramswith 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_pageandrestore_page(dry runs included) go throughpersistence/page-mutations.ts:validateMutationSlug, which admits a legacy stored slug (ops/context.ts:isLegacyStoredPageSlug: refused by today's grammar, still accepted byvalidateSlug) only when an existing row in the target source holds it; every other operation keepsvalidatePageSlug, and remote purge stays denied byassertPurgeParams. Large pages:get_pageresolves its body mode first (parseBodyRequest,ops/get-page-body.ts) and returnsreadPartialBodyfor none/outline/window/auto-above-256 KB,assertFullReadFitsguarding whole remote reads;fetchof a page over the inline size returnsfetchWindowResult(window around the id's chunk anchor,metadata.next_id); remoteput_pagerunsassertLargePageAdmissionbefore queueing. A committed segmented write's outcome recordssearchable(true,'pending'when its projection runs after commit,falsewhen quarantined);persistence/searchable.ts:liveSearchablere-reads a pending one whenever the receipt is served (the put_page reply inpage-mutations.ts,get_write_request) and addssearchable_retry_after_msand asearchable_fixthat reads the receipt again (test/large-pages/segmented-create-searchable.test.ts). Only writes loadpage-mutations.ts(test/cold-read-module-graph.test.ts). The starter list leaves out (fullSurfaceOnly, still accepted) get_pagefuzzy/content_only/include_deleted/include_timeline_entries/include_quarantined, list_pagesoffset/include_deleted, put_pageallow_empty/drop_timeline(refusals name them), the write ops'reasonand the server-set provenance params, and captureexpected_revision/force/local_file.src/core/persistence/large-page-guard.ts— put_page against a page over 256 KB:assertLargePageAdmission(remote, before queueing) refusesforcewithoutexpected_revision(revision_required) and content under half the stored body (page_shrink_refused) unlessallow_shrink;assertLargePageReplacementre-checks the parsed body against the locked snapshot in preparation (page-prepare.ts).src/core/ops/page-edit.ts— theedit_pageoperation (write scope, starter surface, client slug-fence allowlist): validates edits and the optionalwithinrange (full surface only), then submits throughsubmitPageMutationlike put_page; matching and the diff live inpersistence/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 addswrite_error_message, the same allowlistedwriteFailureDiagnosticmessage managed sync prints, never raw journal error text (test/sync-frontmatter-slug-conflict.test.ts). A terminal or recovery-holding receipt also returnswrite_error_reason,suggestionand adiagnosisfromclassifyTerminalwith a renderedfix(#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_requestslimitis 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_datafollows the page soft-delete (a tombstoned page reads as[],restore_pagebrings the rows back; there is no remoteinclude_deletedparam —get_page include_deleted: trueverifies the tombstone) and, per #4352, avisibility: privatepage's raw data reads exactly like a missing page's for untrusted callers. Scope comes fromreadPolicyOpts(ctx), never from MCP parameters.
Continued in Core Services (2/3, more).