Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Agent bootstrap cluster (the paste-in desktop-agent install) (continued)
Subsystem index · Previous entries.
src/core/wsl-paths.ts— WSL Windows-drive path translation shared by the doctor asset checks (src/commands/doctor-asset-paths.ts) and hook-transcript confinement (confineTranscriptPathabove). ExportsWINDOWS_DRIVE_PATH_RE,translateWindowsPath(p, mountRoot)(C:\Users\x\file→<mountRoot>/c/Users/x/file; null for non-drive input so callers keep the original untouched),parseWslAutomountRoot(conf)(the/etc/wsl.conf[automount] rootvalue, default/mnt), anddetectWslMountRoot()(null off-WSL). Mechanical detection + translation only — POLICY stays with callers (skip vs stat vs confine): the hook lane confines the translated path to the known Claude config tree, doctor decides skip-vs-stat. Pinned by the WSL cases intest/claude-code-jsonl.test.ts.src/core/context/turn-context.ts— server-side per-turn assembly: reflex pointers + volunteered pages (≤3) + hot facts (visibility=['world']except for the brain owner over MCP,worldOnlyFacts; the IPC path never widens what MCP would return) under a "data, not instructions" envelope, trimmed to ≤8KB (the harness caps hook output at 10,000 chars). The ambientcontext_packanddeltamodes are world-only across every arm by default; only an explicit trusted-localinclude_privatewidens entity cards, changed pages, threads, and facts together. The result exposespointersAND post-trimvolunteered— exactly what the rendered text carries — so the IPC delivery point can log the feedback loop without ever counting a trimmed-out page. Reuses the hot-memory cache keyed by typed sessionId. Engine-agnostic. Hot facts render through the sharedrenderFactLine(speaker prefix, trust label or data envelope), and a fact whose rendered line or unlabeled line (without the drifting confidence) already appears inpriorContextTextis not re-injected, the same cross-turn contract as volunteered pages (#5591, #7023). In turn mode, System One S6 (recall_needed,src/core/context/recall-needed.ts) runs concurrently with the reflex arms; the reflex block is rendered first and S6 may only replace its pointer/volunteer window (fire or suppress) when it finishes inside its own deadline, reported asdecide.recall_neededon the result only when the slot is not off.src/core/context/resolve-ipc.ts(IPC v2) — discriminated-union requests (absentkind= legacy resolve;turn_contextcarriesprotocol: 2+ a shared secret from a 0600 file in the data dir, plus an additivechannelfor feedback-loop attribution — wire channel claims are validated to the harness channels at the logging site, anything else logs as the default hook channel), handler map, named response types, per-kind timeouts/size caps, socket + parent dir permissions set before exposure, server-side source binding (cross-source requests rejected), protocol echo (a response without it = stale serve → loud degradation). Bind policy:startResolveIpcServerconnect-probes the path first — a live owner makes it return null (that serve stays the IPC provider; a transient serve never unlinks a live socket), only a dead/absent owner's entry is unlinked (unconditionally, since Bun on win32 cannot stat the AF_UNIX socket file it leaves behind) before listen. The connection handler processes exactly ONE request per connection (trailing bytes mid-await never double-process a line or double-log a delivery); the client clamps a too-big request below the message cap by dropping the advisorypriorContextTextBEFORE any conversation turn. Delivery seams:onDelivered(resolve kind) andonTurnContextDelivered(turn_context kind) both fire ONLY after the response write succeeds — a block abandoned before the serve responded is never counted (serve's callback logs the delivered block's volunteered pages + pointers tocontext_volunteer_eventsunder the request channel); write-accept still isn't proof of injection (the client can trim/drop after receipt), which is why thevolunteer_channelsdoctor check reconciles counts against the hook heartbeat. v1 clients and servers interoperate untouched. Serve-delegated sync rides the same socket as three additive secret-gated kinds (sync_start/sync_status/sync_abort, wire shapes + fail-closed option validation insrc/core/context/sync-ipc.ts): start+poll, one line per connection, O(1) handlers with no server budget race; a pre-delegation serve answersunknown_kind:*without the protocol echo and the client degrades to the typed stale-serve refusal.src/core/context/turn-context.ts— server-side per-turn assembly: reflex pointers + volunteered pages (≤3) + hot facts (visibility=['world']except for the brain owner over MCP,worldOnlyFacts; the IPC path never widens what MCP would return) under a "data, not instructions" envelope, trimmed to ≤8KB (the harness caps hook output at 10,000 chars).deltapages carryupdated_atfromPage.updated_at_iso(the column's microseconds, projected bylistPages), sonext_cursor.sinceand the sessionlast_wake_at(read back viato_charinsession-state.ts) resume from the exact row — a millisecond-rounded cursor re-delivers same-millisecond pages on the next wake; thedeltaop keeps an already-canonical 6-digit ISOsinceverbatim instead of re-rounding it through a JS Date. The ambientcontext_packanddeltamodes are world-only across every arm by default; only an explicit trusted-localinclude_privatewidens entity cards, changed pages, threads, and facts together. The result exposespointersAND post-trimvolunteered— exactly what the rendered text carries — so the IPC delivery point can log the feedback loop without ever counting a trimmed-out page. Reuses the hot-memory cache keyed by typed sessionId;sessionOnly(from the IPC handlers) reaches both hot-fact reads (turn mode andfetchHotFactsfor pack), so a session with no facts of its own gets none. Engine-agnostic. In turn mode, System One S6 (recall_needed,src/core/context/recall-needed.ts) runs concurrently with the reflex arms; the reflex block is rendered first and S6 may only replace its pointer/volunteer window (fire or suppress) when it finishes inside its own deadline, reported asdecide.recall_neededon the result only when the slot is not off. Pack cards resolve oversources(home first) plus source-qualifiedentityRefs, are deduplicated by(source_id, slug), and each card's activation verdict and newer mentions read its OWN source, never a same-slug page in another source; a card outside the home source renders(source <id>). delta's arms publish their results in one assignment each and the verb readsdeltaArms(ok/failed/unknown) from the same snapshot as the arrays, so a deadline can never pair a stale flag with a half-filled arm; the facts arm readslistFactsKeyset(ascending(created_at, id), limit+1 probe) and returns the raw rows with their collapsed representative (deltaFactsRaw); a thread-builder throw marksthreadsfailed.session-state.tsdistinguishes absent, loaded and unavailable (readDeltaSessionState), stores the facts keyset and the degraded-wake counter (migration v208), and binds timestamps as$n::text::timestamptzso postgres.js cannot truncate them to milliseconds.src/core/context/resolve-ipc.ts(IPC v2) — discriminated-union requests (absentkind= legacy resolve;turn_contextcarriesprotocol: 2+ a shared secret from a 0600 file in the data dir, plus an additivechannelfor feedback-loop attribution — wire channel claims are validated to the harness channels at the logging site, anything else logs as the default hook channel), handler map, named response types, per-kind timeouts/size caps, socket + parent dir permissions set before exposure, server-side source binding (cross-source requests rejected), protocol echo (a response without it = stale serve → loud degradation). The connection handler processes exactly ONE request per connection (trailing bytes mid-await never double-process a line or double-log a delivery); the client clamps a too-big request below the message cap by dropping the advisorypriorContextTextBEFORE any conversation turn. Delivery seams:onDelivered(resolve kind) andonTurnContextDelivered(turn_context kind) both fire ONLY after the response write succeeds — a block abandoned before the serve responded is never counted (serve's callback logs the delivered block's volunteered pages + pointers tocontext_volunteer_eventsunder the request channel); write-accept still isn't proof of injection (the client can trim/drop after receipt), which is why thevolunteer_channelsdoctor check reconciles counts against the hook heartbeat. v1 clients and servers interoperate untouched. Serve-delegated sync rides the same socket as three additive secret-gated kinds (sync_start/sync_status/sync_abort, wire shapes + fail-closed option validation insrc/core/context/sync-ipc.ts): start+poll, one line per connection, O(1) handlers with no server budget race; a pre-delegation serve answersunknown_kind:*without the protocol echo and the client degrades to the typed stale-serve refusal.src/core/facts/visibility.ts—resolveDefaultVisibility(engine)/resolveVisibilityParam: the ONE resolver behind all four facts-visibility default sites (facts.default_visibilityconfig key; explicit caller value always wins; invalid values fail closed to private). Bootstrap sets the workspace brain's default toworldso the principal's own sessions can recall their facts — a documented, security-relevant knob. NOTE the deliberate asymmetry with the ambient-writeback TEMPLATE resolver (writeback-config.ts below): this READ/extract default fail-closes UNSET to private; write GUIDANCE treats unset as world (therememberverb's own default) because telling agents to write private-by-default on a default install makes their facts invisible to their own later remote sessions.- Ambient memory writeback cluster (opt-in,
memory.auto_writeback = off|salient|all, default off; guidedocs/guides/ambient-writeback.md):src/core/facts/ttl-parse.ts— dependency-free TTL grammar leaf (parseTtlShorthandnon-throwing typed results;validateTtlConfig— duration-shorthand-only, positive, ≤365d for the transient-TTL config).ops/facts.ts'sparseTtlParamwraps it with the byte-identical frozen verbError copy; the engine-free hook child shares the grammar without touching the gateway-reaching ops graph.src/core/facts/writeback-config.ts— config resolution, fail-closed OFF.gbrain config set memory.*DUAL-WRITES (file mirror first for the engine-free readers, then the AUTHORITATIVE DB plane;src/commands/config.tsMEMORY_DUAL_PLANE_KEYS branch, which also stamps the resolvedmemory.visibility_posturefile mirror for the engine-free harness renderer — and afacts.default_visibilityset/unset RE-STAMPS that mirror so installed blocks can always converge; a DB-write/delete failure on these keys exits NON-ZERO naming the unchanged runtime value, andconfig getreports them DB-first with a drift warn). MOUNT RULE: when the selected brain is not the host (--brain/GBRAIN_BRAIN_ID/.gbrain-mount), every dual-plane lane (set, unset,unset --pattern, the posture re-stamp) writes the DB row ONLY and says so — the machine-local mirror gates the HOST's Stop hook, and enabling a team mount must never opt the host's conversations into banking; an unresolvable brain selection also skips the mirror (fail toward not mutating host state). The engine path resolves mode/ttl from the DB ONLY — the machine-global file mirror never enables a per-brain gap (a mounted/selected brain can't inherit another brain's opt-in); a provided fileCfg serves drift detection (plane_drift: DB row ABSENT + file enabled; explicit DB 'off' is intent, never drift) and the LKG override (a file-mirror explicit 'off' beats a cached ENABLED bundle on read failure).resolveWritebackConfigcaches a per-engine LAST-KNOWN-GOOD bundle ATOMICALLY (mode+ttl+visibility together; no LKG + read failure = OFF+read_error).ambientOptsFrom(wb, {remember, extractFacts})gates the section on the caller's ACTUAL callable set — noremember⇒ no section (bound-client fences, clamped surfaces).visibilityPostureFromRawowns the rule: unset → world, only explicit non-world → private.- Capture gate (#6091): see Ambient capture consent gate.
src/core/facts/writeback-settings.ts— GBRA-219: the DB-onlymemory.agent_writebackoverride (inherit | off | salient | all) of the mode AGENTS are told to follow.resolveAgentWritebackwraps the operator resolver and is what the three initialize transports render; an unreadable or invalid override, or an operator read failure with no last-known-good, fails closed to off (never inherits a wider mode). It never feedscaptureGateDecision, so the capture lanes stay onmemory.auto_writeback.writeAgentWritebackwrites the setting and amemory_setting_changerequest-log row in one transaction under an advisory lock. Kept out of writeback-config.ts because the engine-free hook children import that file.src/core/ops/memory-settings.ts—get_memory_settings(read),set_memory_writeback(admin scope +mcp.publish_memory_settingspublish gate; writes only the override),memory_conversation_mode(write scope, callable whererememberis; stores nothing; no enum auto-repair becausemutatingis unset). Guide:docs/guides/ambient-writeback.md#reading-and-changing-it-remotely.src/core/facts/writeback-instructions.ts— the ONE ~15-line instruction-section builder feeding BOTH the MCPinstructionscomposition and the bootstrap-managed harness blocks (surfaces structurally cannot drift). Mode-conditional candidate policy, literal resolved TTL, surface-honest extract_facts mention, visibility posture with the "world = agents on this brain, not the public internet / never widen" rule; the private posture states its consequence to the agent (it and every other MCP/HTTP session cannot recall or forget a fact it saves as private).src/core/facts/writeback-gate.ts— the engine-free zero-LLM Stop-hook salience gate: frozen skip-reason vocabulary (empty/too_short[CJK-aware 20→10 floor]/ack_or_greeting/slash_command/question_only/quoted_or_tool_output/bulk_paste>8KB/pasted_content), first hit wins; after the length checks every Claude Code paste block is stripped (pasted-content.ts) and the remaining rules plus the banked text see only the user's own words (a paste-only turn ispasted_content); an accepted turn banks without its>quote lines outside backtick or tilde fences (#8410); ok returns the NFC/collapsed normalized text + sha256-hash24 — the turn's idempotency key (same turn ⇒ same.wb-filename ⇒ embedding-free dedup that works keyless).src/core/facts/writeback-audience.ts— personal-vs-shared classifier for the consent nudge. Declaration (brain.audience, stamped by company-brainify's Phase-5 handoff, the bootstrap interview's SURFACE_MULTIUSER answer — applied the momentinterview --setrecords it, BEFORE the agent runs init — or the operator) BEATS the conservative heuristic (≥3 distinct non-automation MCP clients active 30d viamcp-usage.ts,likely_automationexcluded);reasons[]always names the evidence. The machine-global file-mirror declaration speaks for the HOST brain only — a mounted/selected brain falls through to its own DB row or heuristic. Fail directions: config read failure →unknown(nudge stays silent), usage-read failure with a reachable DB →personal(missing multi-client infra is personal-shaped). Never enables anything.src/core/onboard/writeback-nudge.ts— the fire-once consent ASK (init epilogue +runPostUpgrade): double gate (sentinelmemory.auto_writeback_notice_shown+ setting unset), personal-audience only, suppressed on mounts/thin-clients/env bypass,[AGENT]-relayed disclosure + ask (non-TTY IS the relay path — deliberately unlike runInitNudge), sentinel stamped AFTER printing (a decline is permanent; a shared classification does NOT burn the sentinel), whole body try/caught (init/upgrade must survive a crashing nudge). The recurring reminder issrc/core/advisor/collect-writeback-consent.ts(info,ask_user, NO dispatch_id — consent is never--apply-able; local-only; fires only AFTER the sentinel so the advisor is never the first ask).src/core/bootstrap/instructions-block.ts— the managed harness block (<!-- gbrain:ambient-writeback:begin/end -->): spliceCompiledBlock discipline verbatim (idempotent replace-interior, THROW on damaged markers, marker-equal body lines neutralized), header names mode + serve endpoint (multi-brain last-wins stays visible), remove/strip helpers never delete a user file. Harness lane (src/core/bootstrap/harness.ts):kind:'instructions'targets (additive under receipt version 1 — old binaries won't unwire them, documented) for user-scope CLAUDE.md +$CODEX_HOME/AGENTS.md(paths + the AGENTS.override.md exclusivity probe are dated PROVISIONAL spec entries inhost-specs.ts); enabled ⇒ install, disabled ⇒ CONVERGE (strip blocks + receipt targets + advisory line; a strip FAILURE is recorded as a failedinstructionsreceipt target so --status/--remove/the next converge keep tracking the orphan); registrar mode (non-loopback --url) NEVER installs blocks — the local mirror speaks for the local brain, and the remote brain's own MCP instructions carry the contract when its operator opts in; a block installs only when the SAME host's MCP target confirmed (both lanes — a foreign-registration refusal or failed write must not leave a block directing saves at a server this run never registered), and a failed final smoke STRIPS the blocks this run installed (targets marked failed) so no block outlives its rolled-back registration;--remove/--statuswired.- Stop-hook backstop lane:
hookStopinsrc/commands/hook.ts(own 2s deadline inside Stop's 10s cap, fail-open exit 0, file-plane gate, a gbrain claude-cli scratch session [transcript path or payload cwd fingerprint, the SessionEnd guard's] is the by-design skipself_capturebefore any parse, 128KB-tail transcript parse selecting the newest structurally genuine user turn viagenuineUserTurnIndexes[a paste-only turn is not genuine], with ONE 2MB-cap retry when the cheap tail contains none — turn OFFSET from EOF ≠ turn size, and Claude's user-role tool-result placeholders neither shadow the prompt nor suppress the retry — then gate → secret-scannedbankWritebackTurn[corpus-segments.ts:<session>.wb-<hash24>[.src-<sourceId>].txt— the source segment lets the SWEEP fallback file the turn into the session's own source; scanner-unavailable = fail-closed skip] →requestContextPack(bankOnly, flushCorpusFile, trigger:'writeback-bank', sourceId from GBRAIN_SOURCE); every outcome a typedwriteback-bankheartbeat reason — by-design skips [gate reasons, no_user_turn, flush_skip_*] rideoutcome:'ok', 'degraded' is INFRA faults only) →src/mcp/context-pack-handler.tstags.wb-basenameslane:'writeback'→checkpoint-harvest.ts's writeback lane (a self-capture session [isClaudeCliSelfSessionId] is the terminal.ingested {skipped:'self_capture'}before any gate or extraction; both lanes extractcorpusTextForExtractiontext; AUTHORITATIVE serve-sidememory.auto_writebackre-check with{gate:true}+ loadConfig drift input — off ⇒ terminal.ingested {skipped:'writeback_off'};plane_drift/invalid mode/read_error/non-transport extraction skip [extract_skipped_*: refusal/content_filter/malformed_output class] ⇒ NO sidecar, file survives for the sweep; salient ⇒notabilityFilter:'medium-and-up';source:'hook:writeback'; NO manifest publish; per-session prompt-harvest capWRITEBACK_SESSION_CAP=30in a true-LRU counter map [delete-before-set on increment], budget burned only on real enqueues, overflow = ACK-only skip the sweep batch-extracts; heartbeats underevent:'writeback'with PERSISTED inserted/duplicate/superseded). The sweep's corpus pass recognizes.wb-files, applies the same gate semantics, routes to the FILENAME-banked source (isValidSourceId-checked, pass source as fallback), and recordsskipped_reasonin its terminal sidecar (src/core/sweep.ts) — leftover banked turns never bypass the OFF gate and never silently zero out. wb-file state machine: ack-only skips leave the file for the sweep;writeback_offis the one terminal skip sidecar. - Read-time TTL validity (there is no sweeper): ACTIVE fact reads in BOTH engines (
listFactsByEntity/Since/BySession, everyfindCandidateDuplicatesarm,countUnconsolidatedFacts,getFactsHealthactive buckets) carryAND (valid_until IS NULL OR valid_until > now())—valid_untilis temporal validity, not retention; history paths (listSupersessions,findTrajectory,--asof) deliberately still see lapsed rows; a re-stated expired fact re-inserts fresh. Pinned bytest/facts/ttl-validity.test.ts+ engine-parity additions. - Diagnostics:
src/commands/doctor/checks/memory-writeback.ts(memory_writeback, BRAIN category) — quiet-ok when off, but the OFF branch still probes receipt + canonical instruction paths and WARNS on a lingering block (off-but-still-instructing) with the converge command; plane-compare warns when the file mirror disagrees with the DB row (the Stop hook acting on the wrong truth) naming the re-sync; a read_error reports the state as UNKNOWN, never "off (default)"; resolved bundle + BOTH visibility postures + audience/reasons; on both branches an explicit privatefacts.default_visibilityon a non-shared brain with remote readers (a harness receipt, or HTTP MCP clients active in 30d; listed inprivate_default_remote_readers) warns with the sharedPRIVATE_DEFAULT_REMOTE_CONSEQUENCEtext (writeback-config.ts), the same textbootstrap harnessprints before consent; instruction blocks receipt-vs-live-probe-vs-drift compare (drift fix names theconfig set+bootstrap harnesscombo — the config set re-stamps the posture mirror so the re-render converges even after an out-of-band visibility flip) + AGENTS.override.md detection — and a receipt target in statefailedis a STANDING warn regardless of the live probe (the one physical-survival path — a smoke-rollback strip that itself threw — leaves a current-looking block directing sessions at a rolled-back endpoint, and only the receipt state knows) naming thebootstrap harness --yes/--removeconverge; validity-lapsed count; 7d counters (verbs usage sidecar's additiveremember_status[stamped insrc/mcp/dispatch.ts, ALL-MCP-callers semantics labeled honestly] +writeback/writeback-bankheartbeat events;turns_bankedcounts flush_skip_* — banked, enqueue declined); when at least 10 serve-side harvests finished (ok + error; awriter_busy_requeuedretry is not finished) in those 7d and more than 20% failed, a warn names the failure count, the top error reason and thegbrain sweep --oncerecovery;details.corpus_backlogcounts corpus files with no.ingestedsidecar (pending, oldest age, past retention, deletion day) and, with writeback on, warns once one is past plain retention (E-N1) with the local/lossy disclosure. Null-engine runs report the file mirror honestly.cross_lane_duplicates_7d/near_duplicates_shadow_7dsum thewriteback_dedupheartbeat events in both the on and off branches. - Tests:
test/writeback-config.test.ts,test/mcp-instructions-writeback.test.ts,test/facts/writeback-gate.test.ts,test/hook-writeback-stop.serial.test.ts, writeback-lane cases intest/checkpoint-harvest.serial.test.ts,test/bootstrap-instructions-block.test.ts+ harness serial additions,test/writeback-nudge.serial.test.ts,test/doctor-memory-writeback.test.ts, the hermetic 5-steptest/ambient-writeback-lifecycle.serial.test.ts, and the NON-GATING real-codex door (test/e2e/bootstrap-real-codex.serial.test.ts, ambient-writeback describe).
src/core/sweep.ts+src/commands/sweep.ts— the serve-resident maintenance sweep (the lock owner closes the persistence loop): facts-fence reconciliation (zero-LLM, reuses the cycle extractor with a slug subset), deterministic link/timeline extraction over recent workspace pages (the same cores asgbrain extract— remote put_page deliberately skips these, the sweep is where the graph compounds), and spend-gated corpus ingest (skipped keyless; turn-boundary windows throughsrc/core/context/corpus-windows.ts, at mostCORPUS_WINDOWS_PER_SWEEP(8) per file andCORPUS_WINDOWS_PER_SWEEP_TOTAL(32, envGBRAIN_CORPUS_WINDOWS_PER_SWEEP) per sweep, each windowed file reported incorpus_files[]as{file, windows_done, windows_remaining};.ingestedis written when the last window of the current snapshot finishes, and a finished file re-enters when its stat no longer matches its.progress; writeback.wb-turn files stay one call; dream outputs and claude-cli self-captures classified byisClaudeCliSelfSessionIdget a terminal.ingestedsidecar withskipped: dream_output/self_capture(the sharedselfCaptureSidecarJsonwriter) and are never extracted; the extractor input iscorpusTextForExtraction, so pasted blocks never reach it). Bounded, fail-soft, never throws; the wall-clock budget stops the corpus pass between files and windows, never mid-extraction (an in-flight extraction finishes and writes its sidecar, E-N2, pinned bytest/sweep-budget-between-items.test.ts); armed at serve startup (3s, best-effort) and on 10-min idle ticks through the injectable timer seam, everything unref'd;serve --httparmsarmCorpusDraininstead (X8: everyCORPUS_DRAIN_INTERVAL_MS, 10 min, one sweep on aCORPUS_DRAIN_BUDGET_MS60 s budget while a corpus.txthas no final.ingestedsidecar; never overlaps itself; its sweep diagnostics and thrown ticks reach stderr, each distinct line once per run, plus the skip reasons whenever their set changes (#6785); pinned bytest/serve-http-corpus-drain.test.ts);GBRAIN_SWEEP=0kills both.bootstrap verifyruns the sweep in-process withcorpus: false(#6786: its engine has no configured gateway, so every window answeredchat_unavailable). Before any model call the corpus pass runs the facts-absorb owner-readiness preflight per source (assertSourceLegacyWriterinpersistence/filesystem-guard.ts): a claimed, not activated canonical worktree skips the file aswriter_coordinator_requiredand logsgbrain sources writer status <id>(#6785; the compact and writeback harvest lanes do the same). Achat_unavailableresult is not terminal: the windowed file or.wb-turn keeps no sidecar, nothing is recorded, and the pass stops (corpus_chat_unavailable). Failures thrown after a chat call are counted per window (<file>.failures.json, seecorpus-windows.ts) and skipped ascorpus_window_backoff/corpus_window_dead_lettered;gbrain sweep --retry-failed [--apply]previews or clears them (doctormemory_writebacknames the paid retry as its fix). Pinned bytest/sweep-corpus-chat-unavailable-6786.test.tsandtest/sweep-corpus-failure-cap-6785.test.ts.gbrain sweep --onceis the trusted CLI seam for operator catch-up runs (CLI-only, never over MCP). The link pass threads the samelink_resolution.cross_sourceopt-in and configuredsources.defaultthe CLI extract lanes pass intoresolveCandidateSources, so an edge into another source is created (flag on) or counted ascross_source_linkinskipped(flag off) — never silently dropped, and the reconcile never deletes a cross-source edgeextract links --source dbcreated. A corpus window's facts batch is keyed by its text (the sweep passesreAdmitFileRefusals), so when the canonical file check refused some of its entity requests,resumeManagedFactsadmits their retained facts as a follow-up batch once every refused page passes that check again: no new extraction, the page's current revision, never wider than the current default visibility, committed requests reported rather than re-admitted, the stored and current writer grants re-checked, at most three follow-ups. Pinned bytest/managed-sweep-refused-window-retry.test.ts.src/core/context/corpus-windows.ts— windowed fact extraction of session-corpus files (#5887).retireCorpusFile/retireCorpusTurns(#6091) record a file or its off-period turns as finished without extracting (skipped_reason; a retire overrides another extractor's lease, and a later rewrite extracts only unrecorded turns).parseCorpusTurns(defined in the provider-freecorpus-turns.ts, re-exported here) splits only at the exact\n\n[user]\n/\n\n[assistant]\nmarkerstoCorpusTextemits (text before the first marker is a header-less preamble); each user turn is paste-stripped whole before windowing;planCorpusWindowspacks whole turns into windows of at mostMAX_TURN_TEXT_CHARS(exported fromfacts/extract.ts) and splits a turn that cannot fit a fresh window at a newline or space, never inside a surrogate pair, repeating its[role]header on every piece.<file>.progress(suffix constants incorpus-segments.ts, GC'd by the session-end hook with the.txt, never deleted by its resume rewrite) holds{version, generation, turns[{start,end,sha256}], continuation{turn_sha256, stripped_offset}|null, windows_done, finished(stat)|null, totals, entity_slugs, skipped_reason?, lease}:resumePointresumes at the first turn whose hash is unrecorded (appends, compaction remainders and same-size or shorter rewrites cost only their new turns). Every write is compare-and-set under the O_EXCL<file>.progress.lock(stale after 30 s): a window commits only when generation, last turn hash and lease owner still match and progress grows; the lease (stale after an hour, like the claim) stops a sweep whose.in-progressclaim the hook deleted from extracting a window another extractor holds.runCorpusWindowsreturnscomplete/partial/aborted/contended/changed/source_changed/unavailable/backoff/dead_letteredwith cumulative counts; an aborted orunavailablewindow records nothing, and a progress a pre-#6786 build finished withskipped_reason: chat_unavailableis rewound under the lease CAS to its retired turns (source binding, totals and links kept). Transport and write errors release the lease and throw; one thrown after a chat call (extractUnderFailureCount, observed through the AI invocation preflight) counts against the window's start key (<turn sha256>@<offset>) and source incarnation in<file>.failures.json: retried on the next sweep, then after 10, 20 and 40 minutes (CORPUS_WINDOW_RETRY_BASE_MS), stopped atCORPUS_WINDOW_FAILURE_CAP(5); tail growth and error labels never reset it, a commit of that window removes it, and one change ofextractionConfigFingerprint(model, provider, key presence) re-arms a stopped window once (#6785). #9279: a failure code retrying cannot change (CORPUS_DETERMINISTIC_FAILURE_CODESincorpus-segments.ts,page_body_segmented) stops the window after that one paid attempt, stamped with the build (build); the first sweep on another gbrain build runs it once, retention GC keeps its file past the un-ingested ceiling (corpusFailureHeld), and doctormemory_writebackcounts it (held);facts/subject-infer-write.tsreads an inferred target's fence as its writer does, so a segmented page no longer throws that code. Pinned bytest/sweep-segmented-entity-9279.test.ts.corpusFileCompletionincorpus-segments.tsis the one completion classifier (selection, the under-claim re-check, retention GC;corpusSidecarStatefor the drain and the doctor backlog): achat_unavailablesidecar is pending, and onlydone/legacyfiles get the plain retention (#6786);adoptFinishedCorpusFilerecords a pre-window.ingestedfile at its current turns once (only when the sidecar is newer than the file).checkpoint-harvest.ts(hook:compact) extracts window 1 only: when more remains it publishes window 1's links, releases the receipt and leaves.progressfor the sweep; an existing.progressmeans window 1 is done. Pinned bytest/corpus-windows.test.ts,test/sweep-corpus-windows.test.tsandtest/managed-sweep-corpus-windows.test.ts(managed coordinator, PGLite and Postgres).src/core/context/corpus-source.ts— #6268, the session's source for every corpus file. Writers (hook.tscompact/stop/session-end, the OpenClawcompact()) callopenSessionCorpus, which freezes one source per session at first use (GBRAIN_SOURCE, then the.gbrain-sourcedotfile, else unresolved) into<sid>.source.jsonin thesourced/spool and stamps it into the file name (.src-<id>,defaultincluded;_unresolvedcannot collide with a real id). Pre-stamp sweepers never list the spool.resolveCorpusFileSourceis the sweep/harvest/serve and dream-synthesize/extract_atoms read: the stamp or frozen record, else tier 4 alone (resolveRegisteredLocalPathSourceinsource-resolver.ts: a registered source whose local_path contains the recorded cwd, active over archived; frozen, tierengine), else on a single-source brain that source unfrozen (sole_source), else heldcorpus_source_unresolved, never a fallback tier (#7868);{ readOnly: true }(dry runs, the synthesis child re-check) freezes and binds nothing; legacy top-level files are held (corpus_legacy_unstamped) unless a legacy wb stamp, a frozen record or a single-source brain proves the source, never assigned the pass source. The first engine resolution binds the source incarnation; a recreated source holds the session (corpus_source_incarnation_changed).gbrain sweep --assign-corpus <source>is the operator mapping (preview, then--apply; it lists what routing holds,.txtand.mdfiles in nested folders included, and sessions the sweep already extracted, because dream synthesis and extract_atoms hold those until their source is mapped, #7805, #7846, #7849); it releases onlycorpus_legacy_unstampedandcorpus_source_unresolvedholds, and the phases print each other reason's own fix (corpusHoldReleaseinsynthesize-source-routing.ts); doctormemory_writebackreports the same listing asdetails.corpus_source_holds. Tests:test/corpus-source-stamp.test.ts.src/core/context/sync-ipc.ts+src/core/serve-sync-runner.ts+src/commands/sync-delegate.ts— serve-delegated sync.sync-ipc.tsis the LEAF wire module:DELEGATED_SYNC_OPTION_FIELDS(the fieldsSYNC_FLAGSinsrc/core/sync-flags.tsforwards through the serve, plussourceId,embedDeferred,timeoutSecondsandorigin) drives the validator, the CLI wire-builder, and the serve-side SyncOpts builder;validateDelegatedSyncOptionsrejects unknown keys fail-closed (repoPath/skipLock/lockId/concurrency are unreachable from the socket), requirestimeoutSeconds(0 = the explicit--no-hard-deadlineunbounded encoding; everything else clamps to 24h), andtoWireSyncResulttruncatespagesAffectedto 50 + a true total under the 256KB message cap.serve-sync-runner.tsis the serve-side module singleton: one job at a time (correctness still rests on thegbrain-sync:<source>row lock inside performSync), clientToken attach (a lost-ack retry finds its own running OR retained-terminal job instead of duplicate-running), per-job deadline timer,[serve-sync]lifecycle stderr lines, an idempotent sharedshutdownDelegatedSync()both serve shutdown paths await BEFOREengine.disconnect()(the disconnect-mode drain is allowAbort:false after_dbis nulled, so settle writes need the live engine; a registered drainer remains as backstop), andmaybeDrainDeferredEmbeds(delegated jobs always run noEmbed — the cost gate lives in runSync — and the serve drains stale embeds afterwards viarunEmbedCore, keyless-safe, cleared only when a drain finds nothing left; wirenoEmbedrecords that the USER declined embeds and suppresses the drain).sync-delegate.tsis the CLI half: read-only holder probe (probeLivePgliteHolder), DEFAULT-DENY argv gate (any unclassified token refuses by name — a silently dropped--excludewould perform the wrong sync), engine-free source tiers (resolveSourceIdEngineFree), 1s poll loop tolerant of event-loop-blocked serves with a PID-probe backstop,unknown_job→ serve-restarted resume hint, Ctrl-C →sync_abort(second Ctrl-C exits 130), and runSync'spull_failedverdict mirroring. Mounts never delegate; opt-outs--no-delegate/GBRAIN_SYNC_NO_DELEGATE=1(client) andGBRAIN_SERVE_SYNC_IPC=0(serve). #6317 (D1 a′), managed Postgres brains:maybeDelegateManagedSyncToServe(engine, args, opts)runs post-connect fromrunSingleSourceSyncright beforeperformSync; it probes the host's live fullserveconsumer throughpersistence_consumers(consumer-heartbeat.ts, the database, never a socket), admits the catch-up's flags (--no-bulk,--lanes/--no-lanes,--json, the processing flags), sends the CLI's durablecliregistration insync_start, prints the drain's own numbered lines fromsync_status(managed,lines,drain,next) and returns the SyncResult to the in-process printers, so exit codes and the JSON envelope do not change. The serve verifies the registration (withVerifiedLocalRegistration) and runsperformSync({ drain: true })as that writer underwithHumanLineSink; the shared-secret lane stays underwithLegacySyncDelegationand is still refused on a managed brain; a denied, revoked or stdio registration answerssync_startwithpermission_deniedand the envelope (refusal), which the CLI rethrows. Every other rung (no owner, a non-serve owner, an unsupported flag, no socket, the kill switch,stale_serve/unsupported_kindfrom an older serve,source_mismatch, a serve lost mid-drain) runs without the serve with one actionable line; only the opt-out, a serve not answering its socket and astale_serveserve callforceOwnConsumer(#6543), the rest admit writes the serve consumes underpersistence.single_consumer. #6712 PR 1: neither builder sendsexplicitProcessingany more; the serve validates one from an older CLI by shape and drops it (WIRE_SKEW_WINDOWSinsrc/core/wire-skew.ts), and a resume inherits the cursor's processing opt-outs. #6712 PR 2:WIRE_BOOL_FLAGS/VALUE_FLAGS/IGNORED_FLAGSand the managed pick list are views ofSYNC_FLAGS; a retired field the validator drops comes back asignored, and the serve logsretiredWireNoticeand streams it to the older client as a progress line (test/sync-flag-table-6712.test.ts). The serve's delegated run follows the source's drain lease as holderserve(followDrainLease,drainHolder). WireembedDeferred(sent only when true) carries the cost gate's runtime deferral, so adopting a cursor that storesnoEmbed=falsenever embeds in that run.maybeDelegateManagedSyncToServerefuses--skip-failed/--include-gitignoredon a managed source withmanaged_sync_flag_refusedbefore any probe or socket call (test/sync-delegated-options-6696.serial.test.ts,test/sync-managed-forbidden-flags-6696.test.ts). Pinned bytest/context/sync-ipc-validation.test.ts,test/sync-delegate-ladder.test.ts,test/serve-sync-runner.serial.test.ts,test/serve-sync-handoff.serial.test.ts,test/context/resolve-ipc-sync-kinds.test.ts,test/e2e/sync-delegation-under-serve.serial.test.ts(gating tier1 step) andtest/e2e/serve-delegated-managed-sync.serial.test.ts(Postgres, spawned serve, MCP latency printed). GBRA-133 2b.3: the deferred-embed drain re-arms itself until the backlog is gone: a pass that left work retries afterGBRAIN_DEFERRED_EMBED_RETRY_MS(default 5000), a failing provider backs off 1x/3x/12x/60x, a running delegated sync defers it at mostDEFERRED_EMBED_BUSY_MAX(3) times before it drains beside the sync, and a keyless brain keeps the backlog with no provider call or timer;deferredEmbedDecisionsrecords each decision. #7243:startDelegatedSync's in-processlogLinesoption (never on the wire) also writes a verified job's human lines to the serve log, for the resident notifier's runs that nobody polls.src/core/capability.ts— config-plane keyless/keyed detection + the honest capability report (per-provider keyless banner: OpenAI = semantic search + auto-extraction, Voyage = semantic search, Anthropic = auto-extraction) rendered by verify and the runbook. The extraction probe resolves through the SAME sharedresolveEffectiveChatModelthe gateway's reconfigure fallback uses (GBRAIN_MODEL> servable file pin > key-aware tier default), so a stale unservable pin degrades identically in the report and at runtime. Key/env fold comes frommergedProviderEnv(src/core/ai/provider-env.ts). Accepted limitation (documented in the module): DB-plane overrides (models.default,facts.extraction_model) are invisible to this engine-less probe; the runtime gate infacts/extract.tsand the engine-aware pre-enqueue gate infacts/backstop.tsare the backstops.src/core/readiness.ts— capability readiness (agent operator contract A7):ReadinessEntry {capability, state, reason, why, fix, tier, asset?, http_visible}for embeddings, chat_llm, writeback, tool_surface, sync, harness_wiring (config tier) and worker, backup per asset, migrations, sync (probed tier); each capability's reasons are a closed exported const (EMBEDDINGS_REASONS, …).configReadiness(cfg, {transport})is synchronous and memoized per (config object, transport); its only file read is one memoizedpeekLock()(none when this process holds the lock, viaheldLockFor), plus one process-wide gbrain-binary PATH lookup on the CLI transport only. The HTTP view dropshttp_visible:falseentries and passes the rest throughredactForTransport.probedReadiness(engine, {cache})never callsgetStats/getHealth; 60 s cache (createReadinessCache()per ServeHttpContext, process-wide otherwise), single-flight, 2 s per-probe bound, stale-while-revalidate;readinessTailis MCP initialize's best-effort 250 ms tail.embeddingEnablement(cfg)is the one "turn on embeddings" fix: resolves the datastore (PGLite path, Postgres, a mount from--brain/GBRAIN_BRAIN_ID) and the column width, picks a keyed provider that fits (or asks for a key withinputs), and emits in-placeinit --force --embedding-model … --embedding-dimensions … [--path …]or, for a mount,embeddings enable --brain …; it never rebuilds a column.exclusiveFixturns an exclusive fix into a two-step plan (actoruserstops the owning serve named bylock_owner,thenthe command) unless the command delegates to the owner. A live status-onlyserve --httpmarker (liveStatusMarkers, config plane) makes CLIharness_wiringserve_status_onlywithtransport: 'http'and the status reason's fix (httpStatusServerEntry, shared with doctor), never "startgbrain serve --http" on the port it holds.harnessWiringEntrybuilds harness-native stdio registration (absolute binary,stdioServeArgvwithREGISTRATION_SURFACE=starter, orinput.surfacefromgbrain init --surface;configReadiness(cfg, {transport, surface})skips the memo when a surface is passed), shared-HTTPbootstrap harness, or the MEMORY_VERBS install anchor, with effects and destinations disclosed. Consumers never coach ondisabled_by_choice. Tests:test/readiness.test.ts,test/readiness-http-cost.test.ts,test/readiness-advice-lint.test.ts(no hand-written enablement advice outside this module; shrink-only baseline),test/readiness-embedding-enablement.serial.test.ts(the E2E matrix).- Secret and sensitivity scanning (
src/core/secret-scan.ts,src/core/secret-scan-allowlist.ts,src/core/secret-scan-stream.ts,src/core/secret-scan-work.ts,src/core/context/sensitivity-scan.ts): see secret-scan.md. src/core/transcripts/render.ts— session → conversation page(s) forgbrain transcripts ingest.redactSessionis two-phase over message text, speaker labels, title and every raw-meta string, BEFORE any engine write:planRedaction(…, { highEntropy: true, echoValues })on every field into ONE session-wide echo dictionary, thenapplyRedactionper field, so a bearer or high-entropy value claimed in one message is scrubbed where it recurs bare in any other field, in either order; echoes add nothing toredactionCount(fail-closed: a scanner/pattern throw aborts the session), then the operator pattern file; nested raw-meta values are dropped. This is the only lane that opts into the entropy heuristic (pasted.envlines are most likely here). Rendering shares the imessage-slack anchor regex with the parser and escapes body lines that would forge it; long sessions split into-pNparts at message boundaries once a part would passPART_TARGET_BYTES(45,000 bytes, 0.9 × the content-sanity warn lineDEFAULT_BYTES_WARN;renderSessionParts(…, { partTargetBytes })overrides it for measurement and refuses a non-positive or non-integer target). No message is truncated (#6388; the former 4,000-characterMESSAGE_CHAR_CAPis gone): a message whose block would not fit a part becomes continuation blocks that repeat its speaker and timestamp anchor, cut at line breaks or, inside an over-long line, at a code-point boundary (a cut piece always lands on the generated anchor line, so every body line was escaped whole); overlap repeats only whole messages, never continuation blocks, and is trimmed so no part body passes the target (test/transcript-long-message-render.test.ts).scripts/measure-transcript-split-cost.tsimports one deterministic synthetic 1 MB session through the real redact → render →importFromContentpath into in-memory PGLite with a token-counting stub embedder at the former 300,000-byte target and the current one: 4 → 27 pages (×6.75), 380 → 424 chunks (×1.116), 199,614 → 217,057 embed input tokens (×1.087); the extra tokens are the part headers and the two overlap messages repeated at each boundary. EachRenderedPartcarries thefrontmatterit owns and itsbody; on re-ingestrunTranscriptsIngestcarries any other key already on the page (a review flag another tool added) onto the re-rendered part, except the re-derived safety and atom-scan markers (#5431,test/transcripts-retitle.test.ts).redactSessionplans every field withTRANSCRIPT_LANE_SCAN_OPTS(highEntropy,labeledCredentialsand the transcript-onlytranscriptRules:cookie_header,.netrc, key-label join) and passes each message the label form the previous message left dangling (trailingDanglingLabel→ScanOpts.leadingDangling), so a value alone on the first line of the next message is claimed (GST-2768,test/transcripts-secret-cross-message.test.ts).src/core/backup/status-file.ts— ENGINE-FREE core of the monthly backup-coverage check: the cached verdict (~/.gbrain/backup-status.json, schemagbrain-backup-status-v2, which includes theconnectorasset kind; a cache with any other schema reads as absent and is recomputed; fail-open load, atomic tmp+rename write,invalidateBackupStatus()fired by the fix paths —bootstrap reporeceipt write,sources harden,workspacePushfinish on ok when the cache carried a warn or failing/unpushed totals (a routine healthy push leaves an ok cache alone, preserving the monthly throttle)), the notice renderer (backupNoticeText(s, 'human'|'aggregate')— human ≤300 chars names assets, aggregate is counts-only for remote surfaces; the remote-privacy pin), and the bounded nag gate shared by every render channel (backupNagGate(channel, s)onbackup-nag-state.json, OWN schemagbrain-backup-nag-v1— skillpackloadNagStatewould drop the extra fields on round-trip, so only the pure policy fnsdecideNagAction/recordNagDisplayare reused). Budget = AND of: 24h cross-channel dampener (last_shown_at), per-channel ceiling 3 per pseudo-version (YYYY-MM(checked_at)+ no-remote fingerprint — month rollover or a changed verdict re-surfaces; a same-month recompute with an unchanged verdict stays quiet), and a global cap of 3 recorded impressions per month (global_shown_count/global_month).backupNagReadOnlyConsultis the OpenClaw context-engine's never-writes variant;backupSpawnDue/recordBackupSpawndebounce the session-end detached spawn (no sidecar file);maybeEmitBackupNagis the cli.ts startup rail body (skip set incl. serve/call/jobs;BACKUP_LOCAL_ONLY <n>machine marker + human line). Off switches:GBRAIN_BACKUP_CHECK=0, configbackup.check_enabled; interval envGBRAIN_BACKUP_CHECK_DAYS> configbackup.check_interval_days> 30; values <1 or non-numeric fall back to the 30-day default (DAYS=0never means "always stale";config setrejects <1 outright). Tests:test/backup-status-file.serial.test.ts. Remote evidence is identity-bound and one-hour-limited; absent, stale, future-dated or inconsistent evidence cannot produce verified recovery counts, and failed refresh does not overwrite cache.- Workspace push and backup coverage (
src/core/workspace-push.ts,src/core/backup/{coverage,repository}.ts): see workspace-push-and-backup.md. src/core/gbrain-home.ts— the single GBRAIN_HOME resolution choke point (delegates to config's parent-dir semantics; 0700 on create) — durability, push, hooks, and bootstrap all route through it so home semantics cannot drift.src/core/bootstrap/verify.ts+status.ts— verify is the definition of done: fail-soft check suite over the REAL write path (put_page op, waiting as long as a CLI write:resolveCliWriteWaitMs, soGBRAIN_WRITE_WAIT_MS/persistence.write_wait_ms, default 30 s; a write still pending after that names its request andgbrain write-requestpoll command → write-through file underbrain/→ in-process sweep → graph floor via link tables → recall), the keyless magic-moment check (## Factsfence → zero-LLM reconciliation → world-visibility read-back), source_id collision resolution (as the one bootstrap subcommand holding an engine: a manifestsource_idalready registered to a DIFFERENT checkout → derives a stableworkspace-<8char-path-hash>, persists it to agent.json, names the re-register steps — every consumer readsmanifest.source_id), theembedding_planecheck (keyed installs live-embed ONE probe string and compare the RETURNED width to the actualcontent_chunks.embeddingwidth — a plane split is a named FAIL with the recovery command, keyless passes, a dead probe warns; runs BEFORE the roundtrip so a keyless-passing roundtrip can never certify a brain whose keyed writes all fail), token sweep, byte floors, secret scan, deny globs, repo privacy, hooks smoke (in-process IPC), capability report, first-run tour; snapshots kept last-5 under<home>/bootstrap/. The roundtrip's probe section runs under one try/finally, so both fixed-slug probes are removed on every exit, early failure returns included (#6001; pinned by the early-exit case intest/bootstrap-verify.serial.test.ts). On a managed brain each probe is purged through the coordinator and its purge tombstones (page, plus the fact/take purges of that request) are then cleared with the host-onlyunpurgePage, also on every sweep, so the constant probe bodies are never refusedpurged_contenton the next run andpage_purgesdoes not grow (#6634). status owns the ordered PHASES list (the runbook defers to it), artifact-first detection, install.jsonl, the runbook version-stamp skew check, and the support blob doctor/agents relay verbatim.src/core/bootstrap/template-repo.ts+scripts/generate-template-repo.ts— deterministic public-template generation (render--minimal+ placeholder manifest + stamped README); published only by the release workflow after diffing against the vendored tree.scripts/check-bootstrap-tag.sh/scripts/check-bootstrap-templates.sh— CI guards: sanctioned distribution ref only (stable; promote-stable moves it to a published release whose exact tree passed the soak;latest-stable, the alpha line, is refused) + runbook stamp == VERSION; template↔question-bank token bijection + placeholder-only assertion + offline generator↔vendored byte-diff + runbook-phase↔status.ts consistency. Both skip gracefully when their subjects are absent.src/core/cycle/synthesize-concepts.tsconcept-quality addendum — aconcepts/<x>page whose frontmatter lackssynthesized_by: synthesize_concepts-*belongs to a human or another writer: the phase checks it before any LLM spend, never rewrites it, and reports it indetails.skipped_human_owned(pinned bytest/cycle/synthesize-concepts-human-owned.test.ts). Concept refs are normalized before grouping (conceptStemFor: last path segment throughslugifySegment, validated byvalidatePageSlug; one atom counts once per concept), so case and spacing variants share one page and no slug carries a space; punctuation variants (network-effects/networkeffects) fold per run throughcycle/concept-redirects.tsaddSpellingRedirects(#5965; documented withconcept-publication.tsincore-cycle-continued.md). Each page recordsmember_hash(member atom slugs, titles and bodies without their## Facts/## Takessections, which the prompt also omits, plus the synthesis model; a page still carrying the full-body hash whose inputs are unchanged is rehashed without a model call,details.rehashed; a narrative achat_fallback_chainmodel wrote is hashed under that model, so the next cycle re-synthesizes it); an unchanged hash on anllmordeterministic_tierpage is skipped without spend (details.skipped_unchanged), and when its concept-provenance edges no longer reach every member they are banked again at its current revision without a publication (details.provenance_restored,test/cycle/synthesize-concepts-provenance-restore.test.ts), and a budget or error fallback never replaces an existingllmnarrative (details.kept_existing_narrative); fallback pages retry next cycle. Pinned bytest/cycle/synthesize-concepts-identity.test.ts. Eligible groups are processed deterministically by tier, descending atom count, then concept slug so the fixed LLM budget reaches the strongest evidence first regardless of database row order. Every page and phase receipt distinguishesllm, intendeddeterministic_tier,budget_fallback, anderror_fallbacksynthesis modes. The narrative call's output cap is sized from the resolvedmodels.dream.synthesizemodel viaresolveSynthMaxOutputTokens: 500 for non-thinking models, the gateway'sTHINKING_MODEL_MAX_OUTPUT_TOKENS(no phase-private number — DeepSeek v4 truncates at 8192-class caps) when the gateway's sharedisThinkingModelmatches (name-matched Claude 5 or recipe-declaredthinking_by_default; unknown providers count as non-thinking), so a tier-reasoningthinking model no longer spends the whole budget on reasoning and persists a template stub or truncated chain-of-thought as the concept narrative. Pinned bytest/cycle/synthesize-concepts-token-cap.test.ts. Right after each concept page write the phase banks concept<->member-atom provenance edges throughengine.addLinksBatch(link_source: 'concept-provenance';synthesized_fromconcept->atom,synthesizesatom->concept; audit sitecycle.synthesize_concepts.provenance), both endpoints scoped to the cycle's source, so the concept pages are graph-reachable (backlinks, relational recall, doctorgraph_signals_coverage/orphans) even though the prompt forbids enumerating atoms in the body. The dedicatedlink_sourcekeeps reconcile passes from pruning them;ON CONFLICT DO NOTHINGmakes re-runs the backfill; a failed or zero-row edge write lands inlink_warnings[](phasewarn) — NOT infailures[], which means "LLM-failed → template fallback" downstream and drives the rollup'shalt_delta/round_completed_delta— and never aborts the page write. Atom discovery (thetype = 'atom'scan) is scoped to the cycle source (opts.sourceId ?? 'default') so same-slug atoms from other sources are never grouped into this source's concepts. Pinned by the#4589describe intest/cycle/extract-atoms-synthesize-concepts.test.tsandtest/cycle/synthesize-concepts-source-scope.test.ts. The phase budget iscycle.synthesize_concepts.budget_usd(finite USD above 0, default 1.5;config setrefuses other values, a stored invalid value keeps the default with a named-key warning, specs insrc/core/cycle/phase-config-values.ts); groups refused at the cap are counted in the summary anddetails.warnings. Pinned bytest/cycle-synthesize-concepts-budget-config.test.ts. A narrative whose stop reason islength,refusalorcontent_filteris a failure (template fallback for a new concept; an existingllmpage and itsmember_hashstay), and failed narratives are bounded per concept and member hash bycycle/concept-retry-bound.ts(ConceptRetryBound, DB-only config keydream.concepts.failed_attempts,MAX_CONCEPT_ATTEMPTS= 3): a bounded concept is skipped before any spend intodetails.skipped_retry_bounduntil its members change, a narrative succeeds, or the key is unset (test/cycle/synthesize-concepts-stop-reason.test.ts). #7986:opts.signal(cycle.ts passes the cycle signal, as for extract_atoms) goes to the narrative model call and is checked before each concept, again right before eachwriter.queue/publish(after the reads that prepare it) and before the final managed flush. On abort the phase saves the retry counters and a rollup row with the finished calls' spend (no completed round), then throwsAbortError(uncontained): nothing more is published, an aborted call is never written aserror_fallback, and queued but unflushed managed concepts are dropped and redone next run (test/cycle/synthesize-concepts-abort-7986.test.ts).src/core/bootstrap/harness-cleanup.ts— #6743 shared-skills cleanup convergence for the harness apply (step 10),--statusand doctor'sbootstrap_harness_health.convergeHarnessCleanupleaves stale enrollments (a working prior enrollment stays until the current one is ready; one whose credential is already revoked always leaves) and then revokes each carriedprevious_idsentry that no not-yet-left enrollment holds, one id at a time.leaveRevokedEnrollmentruns the adapter's local leave with a caller that never contacts the host and records the entry left with reasoncredential_revoked: a revoked principal cannot authenticateleave_brain, so its membership is inert.harnessCleanupItemsreports what stays pending per id (revoke_pending,leave_pending,enrollment_retained,credential_unreadable, with the token-row state from the read-onlytokenStatesWithlookup); the apply and--statusexitbootstrap_cleanup_pending(14) with afixthat re-runs the same command when every id converges and otherwise names the owner's revoke or restore step. Pinned bytest/bootstrap-harness-cleanup-6743.test.ts.