Garry's Opinionated OpenClaw/Hermes Agent Brain
Key files: Core Cycle
Subsystem index · More entries. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
src/core/cycle/dream-provenance.ts—summaryProvenanceLines(#6642) writes the cycle summary's provenance section:dream_cycle_dateis first-write provenance, so it reports the count the recovery query returns and, separately, the pages this cycle rewrote that keep an earlier cycle's date.stampDreamProvenance, the unmanaged dream-output identity stamp shared by synthesize and patterns: setsdream_generated, a stabledream_cycle_date/dream_created_cycle_dateand an optionalraw_sourcein page frontmatter, and leaves a page that existed before the child's first write to it (first_write_at) unstamped. Managed brains stamp through maintenance writes instead. A ref's optionalseatis stamped besideraw_source(the capturing agent seat, #4618). #5575 I2: a ref carryingderivationis stamped inderivedMaintenanceTransactionat the child's derived tier, and the page is lowered to it and gets itsderivation_inputsedges even when it is not dream-owned (the child wrote it from that prompt). Pinned bytest/trust-taint-dream.test.ts.src/core/cycle/dream-taint.ts— #5575 I2 taint for the dream derivers (ENG-3):transcriptDerivationgives a synthesis transcript's tier (agbrain-page://conversation page = that page's stored tier, with an edge to it; a file underdream.synthesize.meeting_transcripts_dir= external_untrusted; any other corpus file = the cap its frontmatter names, else agent_written);transcriptsDerivationtakes the least trusted of several;withTranscriptTaintattaches it to unmanaged output refs;summaryDerivationgives the dream summary the tier of the pages it indexes (written as adream_summarysingle-page generation, GBRA-161 PR 5);patternsDerivationis one patterns pass's tier over the reflections in its prompt. The tier is read when outputs are stamped (a page can only be lowered meanwhile). Pinned bytest/trust-taint-dream.test.ts. #6982 (GBRA-131 D-9): the summary write keeps a live body it replaces with a different one in page_versions first and stores the tags the summary file declares, so a same-date rerun finds its own file replaceable.src/core/cycle/extract-atoms-schema.ts— shared atom-type vocabulary and the extraction response schema. The private model prompt requests an object containingatoms; the schema uses closed objects and nullable optional metadata.extract-atoms.tspasses it through the gateway's capability gate and existing schema-rejection fallback, while its tolerant parser still accepts legacy bare arrays. Schema submission does not replace grounding or malformed-output checks. Covered bytest/cycle/extract-atoms-structured-output.test.tsusing a local HTTP protocol fixture and isolated PGLite, without live model inference.src/core/cycle/extract-atoms-parse.ts— extract_atoms response parsing, re-exported byextract-atoms.ts.parseAtomsOutcomereturns a typed outcome (ok: falsewith a stable reason string for malformed output,ok: true, atoms: []for an honest zero-yield), retrying once with reasoning blocks stripped.parseAtomsOutcome(text, stopReason)takes the gateway stop reason:length/refusal/content_filterare never parsed, and an empty answer underother/tool_callsis not taken as complete; both returnok: false, stopped: true, whichextract-atoms.tscounts indetails.stopped_outputsand fails like malformed output (unmanaged: the bounded streak; managed: a failure receipt that never retires earlier atoms;test/cycle/extract-atoms-stop-reason.test.ts,test/managed-atoms-stop-reason.test.ts). A bounded anchor scan (MAX_ARRAY_ANCHOR_CANDIDATES) tries successive[offsets; each candidate ends at its own closing bracket (matchingCloseBracketinllm-json.ts), the first array yielding an atom-shaped element wins, a literal[]is zero-yield only when no earlier[is still open at its offset (an atom's own"concepts": []inside a clipped or malformed array is malformed output,test/extract-atoms-nested-empty-array.test.ts), and failure reasons always describe the first bracket.atomsFromParsedArrayis the single atom shape gate.src/core/cycle/anomaly.ts— Pure stats helpers forfind_anomalies.meanStddevreturns sample stddev (n-1 denominator) and (0,0) for empty input.computeAnomaliesFromBuckets(baseline, today, sigma, limit)takes densified daily-count buckets + today's counts per cohort, returnsAnomalyResult[]. Zero-stddev fallback: cohort fires whencount > mean + 1, withsigma_observed = count - meanas a finite sort proxy (no NaN). Brand-new cohorts (no baseline) havemean=0, stddev=0so the fallback fires at count >= 2. Sorted bysigma_observeddesc, toplimit(default 20).page_slugscapped at 50 per cohort.src/core/cycle/cycle-date.ts— the dream-cycle calendar-date policy (runCycleresolves it once and threadscycleDateinto synthesize, patterns and drift, so one cycle never splits across days;test/cycle-date-consistency.test.tsalso lintssrc/core/cycle*for the UTC-daytoISOString().slice(0, 10)pattern;shiftCalendarDatedoes lookback arithmetic on the date string):resolveCycleDateresolves explicit--date>cycle.timezoneconfig > host IANA timezone > UTC, so a run after local midnight buckets into the day the user actually lived instead of rewriting yesterday's UTC-day summary.isValidTimeZonegates configured values (config.ts also validates atgbrain config settime); an invalid configured timezone falls back loudly instead of killing the cycle.utcDateis retained for source-date fallbacks and legacy pages.src/core/cycle/emotional-weight.ts— Pure functioncomputeEmotionalWeight({tags, takes}, {highEmotionTags?, userHolder?}). Deterministic 0..1 score: tag-emotion boost (max 0.5, case-insensitive match againstHIGH_EMOTION_TAGSseed list), take density (0.1/take, capped at 0.3), take avg weight (0..0.1), user-holder ratio (0..0.1 over active takes; default holder'garry'). Total clamped to [0..1]. Anglocentric / personal-life-biased seed list intentional; override via configemotional_weight.high_tags(JSON array).userHolderoverridable viaemotional_weight.user_holder.src/core/cycle/extract-atoms-cost-gate.ts— cost-gate decision for the extract_atomsBudgetTracker, shared with the Life Chroniclechroniclephase throughsettleExtractAtomsCostGate'starget(phase name, refusal key prefixchronicle.no_pricing., no rollup).resolveExtractAtomsCostGate(extractModel, embedModel, overrides?, {explicitBudget?})(pure) returns{enforceCap, unpricedModel?, unpricedKind?, refusal?}: the cap is enforceable only when EVERY model billed under the phase's tracker is priceable — the extraction chat model AND the embedding model the atom import (importFromContent, inside the samewithBudgetTrackerscope) calls — with operatorpricing.overridesconsulted first, matchingBudgetTracker.reserve().resolveEmbedModelForCostGate()mirrors the write site'sisAvailable('embedding')gate (null when embedding is unavailable). A DEFAULT cap is dropped for an unpriced route (warn and run). When the operator SETcycle.extract_atoms.budget_usd(explicitBudget), an unpriced chat model or embed route yieldsrefusal(the sharedno_pricingguidance).settleExtractAtomsCostGateacts before any work item: it warns on a dropped cap; on a refusal it returns the phase'swarnresult (details.reason: 'no_pricing',details.no_pricing, no model call), records the guidance atcycle.extract_atoms.no_pricing.<source>and upserts the rollup as an expected limit, not a halt; any run past the gate clears the source's record (dry runs record nothing).readExtractAtomsNoPricing+withExtractAtomsNoPricingoverlay doctor'sextract_health(wired indoctor/checks/local-audits.ts) with awarnnaming the model andregister_command. Pinned bytest/extract-atoms-embed-cost-gate.test.tsandtest/extract-atoms-explicit-cap-no-pricing.test.ts.src/core/cycle/extract-atoms-drain.ts— pure single-hold bounded drain for the silent lens-phase backlog.runExtractAtomsDrain(deps, opts)over injected deps (withLock,runBatch,countRemaining,now, optionalonBatch) loops bounded batches under ONE lock hold, rediscovering eligibility each batch (idempotent NOT-EXISTS-on-source_hash; no cross-window cursor), until the backlog is empty or the window ends. Two stop signals: HARD (jobsignal+ the lock's lease-loss signal +deadlineAtMs) reaches the chat call, the pacing pause and every backlog count; SOFT (hard + the window timer) is checked only between batches and items, so the item in flight finishes. Counts are cancellable and bounded (countTimeoutMs, capped by the remaining deadline).stoppedis aDrainStop(drained|window|deadline|lock_lost|aborted|no_progress|max_batches|provider_failure|budget);budget(#6425) stops after the first batch that reportsbudgetSkipped > 0(the attempt's one tracker is spent) and carriesspent_usd/budget_usd, whichdream --drainrenders as the spend, the cap and anatom_drain_budgetnotice whose paid fix raisescycle.extract_atoms.budget_usd; the Minion handler completes it normally; a hard stop skipsonBatchand the recount and reports the last count asremaining, and the lease losswithRefreshingLockrethrows becomeslock_lostwith the partial counters. Backsgbrain dream --phase extract_atoms --drainunder the SAMEcycleLockIdFor(sourceId)the routine cycle takes (a concurrent tick defers withcycle_already_running).runExtractAtomsDrainForSource(engine, {sourceId, windowSeconds, brainDir?, maxBatches?, onBatch?, signal?, deadlineAtMs?})owns the lock+batch+count wiring for all three callers —dream --drain, theextract-atoms-drainMinion handler, autopilot auto-drain.sourceId: undefined→ legacygbrain-cyclelock +'default'; a real id →gbrain-cycle:<id>.LockUnavailableErrorpropagates. OnerunExtractAtomsDrainForSourcecall is one drain attempt: its batches share oneBudgetTracker(the per-runcycle.extract_atoms.budget_usdcap is the attempt's cap) and oneMaintenanceWriteWait(persistence/maintenance-wait.ts, bounded bydeadlineAtMs).structuralAtomRefusalmaps anowner_unavailable/permission_deniedrefusal from the atom session preflight toSTRUCTURAL_REFUSAL_PREFIXtext; theextract-atoms-drainMinion handler (src/core/minions/handlers/extract-atoms-drain.ts) throws it asUnrecoverableError, so the job dead-letters once with no model call and the auto-drain cap does not count it.last_errorand the typed failure records pass throughsanitizeFailureText(secret/DSN redaction, bounded). #7514: a record whose write did not commit also carriesrequest_idandcode; the adapter leaves such items out ofproviderFailureand its class (they never reached a provider), a batch that extracted nothing (whatever it skipped, #8445) is recounted and stopsno_progresswhen the backlog did not shrink, and a batch whose only progress is write-failure strikes (writeStrikes) is notno_progress(nor is a 0/0 batch started after the window closed: that iswindow), so the drain moves on and the strikes reach their hold in the same window. Aprovider_failureresult carriesprovider_failure_class(batchProviderFailureClass: the phase'saborted_global_errorhalt classauth/billing/model_not_found/rate_limit,content_blockwhen every failure is a provider content block, elsetransient).formatDrainProviderFailure(result, {final?})renders the handler'sprovider_failurethrow; the handler throwsUnrecoverableErrorondeadline, on a provider failuredrainOutcomemarks not retryable, or any failure at/pastdeadlineAtMs, the job's abort reason onaborted, and a retryable error onlock_lost. Tests:test/extract-atoms-drain*.test.ts.src/core/cycle/extract-atoms-drain-outcome.ts— #6817:drainOutcome(result), the one mapping from a drain stop to exit code, JSONstatus(neverokfor an incomplete stop),retryable,codeandreason, read from the error registry (atom_drain_incompleteexit 11,atom_drain_provider_failureexit 1 withrate_limit/transientoverridden to retryable exit 11,atom_drain_no_progressexit 1; a null count is alwaysatom_drain_incomplete/count_unavailable). Used bydream --drainand theextract-atoms-drainMinion handler; type-only import of the drain module. Tests:test/extract-atoms-drain-outcome.test.ts,test/dream-drain-failure-summary.serial.test.ts,test/extract-atoms-drain-handler.test.ts.src/core/cycle/extract-atoms-budget-notice.ts— #6425:drainBudgetNotice(result)renders theatom_drain_budgetnotice abudget-stopped drain carries ingbrain dream --drain --json(spend, per-run cap, pages left; paid fixgbrain config set cycle.extract_atoms.budget_usd <USD>, verifygbrain config get), andusdformats the amounts for the stderr stop line. Dynamically imported bydream.tsso its notice-rendering imports stay out of the CLI flag scan. Tests:test/dream-drain-failure-summary.serial.test.ts.src/core/cycle/extract-atoms-input.ts— #6503 the input cap and the partial disposition.resolveExtractAtomsInputCapreadscycle.extract_atoms.max_input_chars(floor 1000; the oldermax_source_chars, floor 500, loses when both are set; default 50 000) before discovery.extractAtomsInput(item, cap)binds the cut once: paste-stripped for a transcript (#5812), UTF-8-safe, withtruncatedmeasured on the text the cap applied to. A page item also takes its storedextract_atomswatermark (src/core/extraction-watermark.ts, large pages A7): when the body still starts with the watermarked prefix the model reads only the appended text (its newestcapcharacters when longer), which is still partial input, so the same disposition below applies;inputTruncatedLineis null for a complete tail read (not counted, no stderr) and names the window otherwise, and the phase commits the plan once the item's writes committed (a pending managed batch keeps the old watermark). A cut item is extracted once from its head and gets a partial disposition instead of a completion:input_truncatedcounts it on the phase result (and the drain sums it intoinput_truncated, with one[drain]line),inputTruncatedLineis written to stderr naming the knob, the head atoms publish, no completion stamp is written and nothing is retired.recordPartialDispositionstores the cap under (content hash, cap) inextract_atoms_page_state/extract_atoms_transcript_state.partial_input_chars(migration v240; the page row is pinned to the identity discovery read), and on a managed brain the origin carriespartialInputChars, which enters the run key, keeps the completion's checkpointpartial, skips the page-state stamp and the retirement, and marks the completion outcomestatus: 'partial'. Discovery and the backlog count skip a partial row like a tombstone (PAGE_SCAN_STATE_EXCLUSION_SQL,tombstonedTranscriptsForHashes, the partial checkpoint);releasePartialDispositionsruns before discovery with the current cap and clears the rows and checkpoints a raised cap supersedes, so the item is eligible again with zero model calls in between;countExtractAtomsBacklogreads the same cap and counts a page whose partial row or checkpoint sits below it (pageScanStateExclusionSql/managedAtomDiscoverySqlwith the cap; #7391), so a drain, doctor and autopilot see it before any phase has released it, while counting itself writes nothing (test/extract-atoms-raised-cap-drain-7391.test.ts); a content change is a new row. Resumed and budget-skipped items are not counted.stampTranscriptTombstone(v146) lives here too. Tests:test/extract-atoms-input-truncated-6503.test.ts(PGLite and Postgres, page and transcript, managed and unmanaged). A page is read as a world reader sees it (publicBodyfrommentions/aliases.ts: facts rows other than world and the takes fence removed) before the cap and the watermark apply, so the prompt, the atoms and a verifiedsource_quotenever hold a row a remote read of the page hides; test:test/extract-atoms-world-fence-rows.test.ts(unmanaged and managed, PGLite and Postgres).src/core/cycle/extract-atoms.ts— the extract_atoms lens phase: mines eligible pages (shelf excluded) intoatoms/<date>/<stem>-<hash>pages. The input cap, the cut and the partial disposition of a cut item are inextract-atoms-input.ts(#6503). Transcript input is paste-stripped before the cut (#5812); discovery skips self-captures (#5820) and keeps only the session-corpus fileskeepSessionSourceTranscripts(synthesize-source-routing.ts, shared with synthesize; a file is a corpus file by its spelled or real path, an unreadable real path is heldcorpus_path_unresolvable, #7871) resolves to the run's source, read-only in a dry run, reporting the rest indetails.source_routing(#7846); a resumed generation member whose transcript no longer resolves to the run's source (transcriptSourceHold) is held, not resubmitted, and counted indetails.source_routing.generation_members_held(#7870); the meeting transcripts dir is read only fordefault. Discovery and the backlog count appendconnectorAtomExclusionSql(connector-atoms.ts), so connectoremail/meetingpages stay out only whencycle.extract_atoms.connector_pagesis false. The type allowlist isunionExtractableTypes(packExtractable, packExcluded): the legacy floor (meeting, source, article, video, book, original) minus the floor types the active pack declares not extractable (nonExtractableTypesFromPack, #5756; a declared type withoutextractable: trueis a pack decision, an undeclared type keeps the floor), plus the pack'sextractable: truetypes, minus synthesis outputs; gbrain-base is unchanged, gbrain-recommended'ssource: falsenow holds for atoms as it did for facts. Pinned bytest/pack-extractable-floor-5756.test.ts. A drain attempt passesopts.attempt(budgetTracker,writeWait) so its batches share one budget and one maintenance publish wait. Eligibility reads source-incarnation/page/full-hash-keyed derived scan state; scan and failure markers do not mutate canonical frontmatter. Managed extraction checks source-wide local authority and owner readiness before provider work, admits outputs plus a completion request together, and replays retained output without another model call. A failed managed batch is retried by the next run instead (#6325,resumeManagedAtomsinpersistence/atom-maintenance.ts); an origin held afterMAX_DETERMINISTIC_FAILURES(now defined inextract-atoms-page-state.ts, re-exported here) is skipped with no model call and counted indetails.held_failed, never infailures. Managed atom files keep provisional source hashes; only the source-incarnation/page/full-hash durable completion receipt excludes an item from discovery and backlog counts. Unmanaged atom completion flips and their cardinality check share a transaction after provenance links persist, so a partial match rolls back and stays retryable. A page-derived atom upserts at its locator-folded slug, else a compatible legacy title-only slug; when both miss, the source page's live bound atoms are loaded once per page per run and exactly one JS-lowercased title match is adopted (a case-only title change never mints a duplicate; zero or several matches mint the new slug). Response parsing lives inextract-atoms-parse.ts. Atoms of one item that resolve to one slug (a repeated title) publish once, the first kept (#7514: two items at one key failed the generation, managedgeneration_live_conflict, unmanaged a primary-key violation). A managed item whose atom write did not commit is a write failure (atomWriteFailure,persistence/atom-maintenance.ts): itsfailuresentry carriesrequest_id,code, and its strike, never a provider classification. An undated source dates its atoms by the source page's creation date (undatedfor transcripts), never the run date. A page-derived atom's frontmatterdateis the source page's content date (atom-source-date.ts: the storedeffective_date, elsecomputeEffectiveDate), read with the input before the model call, so classic import and managed publication store thateffective_date(sourcedate) andextracted_atstays the processing stamp; transcript-derived atoms carry nodate. After an unmanaged item completes (completeUnmanagedItem),retireStaleAtomssoft-deletes that source's atoms from earlier extractions (other or provisionalsource_hash) that this extraction did not re-produce; a cut item neither completes nor retires. Hardopts.signal(chat call, pacing, checks before each item and commit) leaves no strike, receipt or rollup; softopts.stopSignalstops before the next item. Managed completion admits revision-pinnedmanaged_atom_deletechildren alongside replacement pages, removes canonical files through the page deletion path, and commits its checkpoint only after every publication and retirement commits. Both paths prevent LLM-chosen titles that drift between extractions from piling up. Atom identity: page-derived atoms fold the source-page slug into the slug hash (8 chars, NUL-separated) so two same-date pages emitting the same title get DISTINCT slugs; the source CONTENT hash is deliberately NOT folded (a reworded source still upserts rather than duping); transcript atoms keep the legacy title-only 6-char hash.resolvePageAtomSlugadopts a legacy-slug atom with a compatible binding in place on re-extraction (upgrade idempotency — no migration, no duplicate), whileassertAtomImportBindingfail-closed refuses to reuse a slug bound to a DIFFERENT source locator. Both shareisCompatibleAtomBinding(frontmatter, sourcePageSlug)— the ONE definition of compatible: bound to THIS source page, or carrying nosource_slug/source_pathat all (pre-binding-era adoption, not a clobber); asource_path-bound legacy transcript atom or a differentsource_slugis a different origin, and a non-atom page squatting on the slug is refused.source_quoteis verified at extraction time against the exacttruncateUtf8prompt prefix the model saw (locateQuoteadvances by full code points): located quotes persist original characters + [start,end) offsets +source_quote_verified; unlocatable quotes are dropped with the atom kept. Edges write before the completion flip; per-item drain failures stay typed (bounded, sanitized, reconcilable). Transcript items carry the same failure-count/tombstone machinery as pages, in theextract_atoms_transcript_statetable (keyed(source_id, file_path, content_hash), 16-char hash prefix, so an edit is a new row):recordItemFailureCountcounts a transcript's malformed output or prompt-level provider block (providerContentBlockReason; never feeds the outage halt) towardMAX_DETERMINISTIC_FAILURES, a zero-yield transcript tombstones immediately (as pages do), andtombstonedTranscriptsForHashesis the batch read-side gate mirroringatomsExistingForHashes(fail-open on error). Reported astombstoned_transcripts(paths), separate from the page-slugtombstoned_for_failures. Malformed managed output requires a newly approved protected-job retry identity; publication retry reuses retained output and original/current grants.src/core/cycle/extract-facts.ts— source-scoped## Factsfence reconciliation. Rows are keyed by fence row number, never by claim text: a DB row whose(row_num, claim)is still in the fence keeps its id and has its other cells updated in place (ids from recall stay valid for forget;source_session,created_at, consolidation state and vectors survive), a row whose number left the fence or whose claim was rewritten is expired and detached (row_numNULL), never deleted, and only new row numbers insert. Duplicate ACTIVE rows with the same claim and source index once; a struck history row never collapses onto an active row with the same text, so a claim that reverts (NYC → SF → NYC) stays active.superseded by #Nlinks resolve on every hop of a chain (supersede-resolve.ts; forgotten targets and cycles still resolve to NULL with a warning). Each run first fences the source's unfenced rows (row_num IS NULL, live entity page, never ontology observations:dimension IS NULL, #6264) throughfacts/unfenced-facts.tsand adds those pages to the run's reconcile set (unfencedRowsFenced); rows it cannot fence this run (canonical file not on this host, malformed fence, held page lock, a claim the fence codec cannot render) are named asFACTS_FENCE_FAILED: <slug> (<reason>)and keep their own page out of the destructive reconcile (the empty-fence guard, per page since #6278:pendingLegacyRowslists the pages,legacyRowsPendingandlegacyPagesreport them, and every other page of the source still reconciles; the page keeps its fact index because reconciliation would classify itsrow_num IS NULLrows as stale and expire them). The phantom-redirect pass moves rows by fence position and so still waits until the source has no unfenced rows.runPhaseExtractFacts(cycle.ts) then reports the reconcile counts of the pages that did reconcile and names the skipped pages in its summary. Rows with no backing page or checkout, and ontology observations, never gate. It then expires (without detaching) the active fence-owned rows of soft-deleted pages in the source; restoring the page re-activates them on its next reconcile. Previously embedded fact rows and their text/provenance remain intact when a full valid replacement embedding batch is unavailable; old vectors are never transplanted to changed text/model. Restrictive fence changes still expire removed/withdrawn claims and tighten visibility before deferral. Provider cancellation within database writes rolls back rather than publishing half a replacement. Keyless initial fact insertion remains supported; conversation-origin facts without a fence are not wiped by fence reconciliation. Each page reconciles in isolation: a page whose writes the database rejects rolls back, is reported as<slug>: FACTS_RECONCILE_FAILED: …(counted inpagesFailed, booked as a halt in the rollup), and later pages still reconcile.facts.superseded_byisON DELETE SET NULL. On an unmanaged brain each reconcile records its outcome inpage_facts_reconcile(src/core/facts/reconcile-watermark.ts): a complete reconcile (including a no-op) stamps the page'sknowledge_revisioninside the write transaction, after aFOR SHARElock and a revision recheck (a moved page writes nothing and stays due);deferred(lock, stale cache, embedding deferral, rejected write),invalid(malformed or misplaced fence, not retried until the page changes) andcancelledleave it due. The dream cycle passesdrain, so an incremental run also reconciles up to 250 due pages within 60 s, never-attempted first then oldest attempt, after settling in bulk the due pages with no fence marker and no fence rows; a fence imported by a standalone sync or removed from a page is therefore reconciled even when the cycle's own sync changed nothing. A direct call withslugs: []and nodrainstill reconciles nothing. Doctor'sextract_healthnames unreconciled fence pages and unreadable fences on unmanaged brains. Tests:test/extract-facts-reconcile-drain.test.ts(Postgres race throughtest/e2e/extract-facts-reconcile-drain-postgres.test.ts),test/e2e/fact-vector-repair-parity.test.ts,test/extract-facts-phase.test.ts,test/extract-facts-unfenced-rows.test.ts(a mixed page, on PGLite and through the Postgres E2E),test/extract-facts-poison-page.test.ts,test/extract-facts-stable-identity.test.ts. On a managed brain the same reconcile runs aftermanagedDerivedFactsPreflight(local writer, active source, before any embedding call): each page transaction and the deleted-page expiry commit insidewithDerivedFactsWrite(coordinator source capability, page key locked); the facts receipt page is skipped, the rollup is still booked. Each deleted page's expiry is one item (ItemRun siteextract_facts.expire_deleted, src/core/item-failure.ts): a refused expiry is aFACTS_EXPIRE_FAILED: <slug>: <code>: …warning (the phase warns) retried by the next run, a page the refusal breaker holds back is aFACTS_EXPIRE_SKIPPEDwarning, and run-scoped errors or most pages failing (item_failures_systemic) still fail the phase; testtest/pathological/a21-facts-expire-deleted.test.ts. It is distinct from the coordinatedextract_factsoperation and durable page backstop. Tests:test/managed-facts-writers.test.ts. Wave B PR 2 (lane 2e2): a segmented page reconciles like an inline one, its fences read from its marker segments (segmentedFactsFenceView), its write guarded by content hash and size, and its stale-cache check streamed against the canonical file (segmentedBodyMatchesFile, page-body/segment-facts.ts); testtest/large-pages/segmented-facts-reconcile.test.ts. #6259: it andextract-takes.ts(both the DB walk and the file walk, which checks the stored page) skip a quarantined page, leaving rows projected before it was quarantined as they are. Test:test/quarantine-fence-projection.test.ts. #6946: a gbrain-owned--urlclone on an unmanaged brain never gates the empty-fence guard (its facts are database-only by design). #8819: on a managed brainplanFenceReconcilekeeps stale positioned rows no fence of the page held (generations/fence-evidence.ts) and whose claim the fence does not state out of the retirements (kept), andwriteFenceReconcilemoves one whose number a new fence row needs (moveKeptRows); an unmanaged brain's reconcile still retires rows its fence lacks as drift.src/core/cycle/inline-drain.ts— the dream cycle's private-queue drain.runSubagentsInline(engine, queue, queueName, yieldDuringPhase?, handler?, lockMs?, concurrency?)runs N independentdrainLoops (dream.synthesize.inline_concurrency, clamp [1,8], PGLite forced serial at the callsite) sharing the queue via the same SKIP-LOCKED claim fencing workers use — everything job-scoped (lockToken, abort, timeout timer, keepalive, renewTimer, outcome recording) stays loop-local. Pool hygiene: global housekeeping sweeps are leader-only (loop 0) whilepromoteDelayedruns in every loop; idle claim-poll backs off 1s→5s; a NON-retryable loop-level failure aborts siblings after their current child (a failing child is a job outcome, never a drain crash). Exit only when the queue holds no active/waiting/delayed child (a lease-full bounce's delayed backoff must not strand a child). Outcome routing mirrors the worker:UnrecoverableError→ dead immediately;RateLeaseUnavailableError→releaseLeaseFullJobrequeue without burning an attempt; timeout terminal. Handler invocation is wrapped inwithChatPhase('job:<name>')(worker.ts parity) so each drained child's gateway spend is attributed to the CHILD — a bareawait handler(context)inherits the caller's AsyncLocalStorage phase, and a cycle phase that wraps its own work (dream synthesize wrapsphase:synthesize) would absorb every child's spend into the phase tag.runDrainRenewalTick(per-call AbortSignal + timeout + re-entrancy guard) and the null-safe nearest-rankpercentile()telemetry helper are exported. Pinned bytest/cycle-synthesize-inline-concurrency.test.ts(loop semantics) +test/e2e/dream-synthesize-concurrency-postgres.test.ts(real-Postgres exact-once + lease-ceiling). #7239: a child that throws a deterministic refusal (minions/refusal.ts) is dead after one attempt with the refusal on its result.src/core/cycle/link-manifest.ts— pre-retrieval LINK CANDIDATES manifest.buildManifestContext(engine, sourceId?)snapshots the source's slugs + basename index once per phase;buildLinkManifest(engine, ctx, verdict, basename, {outputRoot, sourceId})resolves wikilink candidates ZERO-EMBED from the triage verdict's cached entities/segment notes (basename-index exact/slugified matches first, boundedsearchKeywordFTS second), excludes dream-output prefixes (self-consumption guard), renders- [[slug]] — <deterministic first-two-sentence one-liner>under hard caps (20 pages / 2400 chars) with buildTriageMapBlock's injection posture (whitespace-collapse + length caps + a 'data, not instructions' header). Best-effort everywhere — any failure degrades to the manifest-less prompt. Pinned bytest/cycle-link-manifest.test.ts.src/core/cycle/nightly-probe-adapters.ts— bridges the autopilot's object-shapeNightlyProbeDepsto the argv-shaperunEvalLongMemEval+runEvalCrossModalCLI functions. Cross-modal adapter argv MUST include--output summaryPath(without it the summary lands at the default receipt path and the adapter reads nothing fromsummaryPath) and--concurrent 1: judge calls reserve worst cases against the run cap until they settle, so questions run one at a time, each with its judges in parallel (test/nightly-probe-sequential-questions-7534.test.ts). In-process invocation (NOT subprocess) avoids gbrain-version-drift for source-tree CI. The LongMemEval adapter passes--reader-mode direct(#6627: the probe's judge grades DIRECTNESS, and the notes reader's notes-plus-reasoning text would be the whole hypothesis; the shared reader prompts are untouched;test/nightly-probe-reader-mode.test.ts) andexitOnError: false: failures throw into the nightly audit/rate-limit boundary instead of exiting the host process, with resolved chat providers checked before embedding work. The LongMemEval argv always carries--no-embed-cache(C-N5: the eval cache swaps the gateway's process-global embed transport, which inside the daemon would catch every other embed call). The pure buildersbuildLongMemEvalProbeCall/buildCrossModalProbeCallcarry the brain-resolvedmodelRoutes: the reader as--model, the extractor asRunOpts.extractorModel, each set judge slot as--slot-<x>-model, and{ useConfiguredGateway: true }so the batch keeps the daemon's gateway; with no routes both calls are the pre-routing ones. The summary parse keepstotal,malformed_count,judge_models(slot order),panel(with per-slotslot_scored_questions) and every non-passing question asfailures: scores come from the batch's slot-indexedslot_scores, a failing dimension outsidePROBE_QA_DIMENSIONSis recorded asunrecognized, error text is cut at the--- raw ---model-output marker, redacted and cut to 200 characters, and a malformed entry yields what can be read instead of a throw. Pinned bytest/cycle/nightly-probe-adapters.test.ts(incl. the argv-shape guard for the--outputrequirement, the builder cases with and without routes, and the summary parse over a canned summary) andtest/nightly-probe-gateway-isolation.test.ts(the real adapters leave the daemon's embed transport, chat model, provider chat options and env unchanged).src/core/cycle/nightly-probe-fixtures.ts—NIGHTLY_PROBE_FIXTURES: the LongMemEval nightly fixture and the conversation-parser probe's two fixture files, embedded withimport ... with { type: 'file' }(types insrc/types/jsonl-assets.d.ts). A source checkout resolves them totest/fixtures/..., a compiled binary to a/$bunfs/pathreadFileSyncreads, so both installs run the probes (#5187, C-N6). Pinned bytest/nightly-probe-compiled-binary.serial.test.ts(abun build --compileharness copied to an empty dir runs both autopilot probe steps on a hermetic provider, plus a source-mode run).src/core/cycle/nightly-probe-routes.ts— the nightly probe's model routes, resolved against the live brain by the caller that holds the engine (the search-config-snapshot shape).resolveNightlyProbeModelRoutes(engine): reader throughNIGHTLY_PROBE_READER_ROUTE(models.eval.longmemeval→models.tier.reasoning→models.default→GBRAIN_MODEL→ key-aware default, the chaingbrain modelsreports for that key), extractor throughNIGHTLY_PROBE_EXTRACTOR_ROUTE(utility tier), and the optionalmodels.eval.cross_modal.slot_{a,b,c}keys (NIGHTLY_PROBE_SLOT_KEYS; alias-expanded, blank = unset). Any read failure rethrows asNightlyProbeModelRoutesError, whose message names the routes. Consumed byautopilot-probes.ts(after a gateway refresh) andgbrain models. Pinned bytest/cycle/nightly-probe-routes.test.ts.readCrossModalSlotConfig(reader)is the one slot-pin reader (#6486), shared withgbrain eval cross-modal: the CLI resolves each judge slot as--slot-<x>-modelflag →models.eval.cross_modal.slot_<x>→DEFAULT_SLOTS(resolveSlotModelsinsrc/commands/eval-cross-modal.ts; a config pin counts as explicit for the #4636 substitution), reading the pins throughreadCrossModalSlotConfigFrom(connect)only when some slot has no flag;src/cli/main.tspasses a probe-only connect (no migrations, closed after the read) and a reader that throws (no brain, brain busy) leaves the defaults, so the command stays usable beforegbrain init. Pinned bytest/cross-modal-slot-config-6486.test.ts.src/core/cycle/nightly-quality-probe.ts+src/core/audit-quality-probe.ts+test/fixtures/longmemeval-nightly.jsonl+test/nightly-quality-probe.test.ts— opt-in nightly cross-modal quality probe. The phase runsgbrain eval longmemeval --by-typeagainst the committed 10-question placeholder fixture, pipes output throughgbrain eval cross-modal --batch --max-usd 5 --yes, and writes one event per run to~/.gbrain/audit/quality-probe-YYYY-Www.jsonl(ISO-week-rotated, mirrorsaudit-slug-fallback.ts; honorsGBRAIN_AUDIT_DIR). Default DISABLED — opt-in viagbrain config set autopilot.nightly_quality_probe.enabled true(prevents surprise API spend). 24h rate limit (pureshouldRunNightly(now, recentEvents, windowMs?)) skips without an audit row. An unreadable fixture writesoutcome: skippedwithreason: fixture_unavailable(exit 0, no model call; the row also holds the 24h gate). Embedding-key short-circuit: longmemeval needsgateway.embedQuery(), so the phase exits early withoutcome: no_embedding_key+ stderr warn when no provider configured. Full DI surface viaNightlyProbeDeps(isEnabled,hasEmbeddingProvider,resolveMaxUsd, optionalresolveBudgetPolicy,resolveFixturePath(wins) /resolveRepoRoot,resolveSearchConfigSnapshotandresolveModelRoutes,runLongMemEval,runCrossModalBatch,now) so the unit test stubs every external effect.resolveModelRoutesruns inside the run'strybefore LongMemEval and its routes reach both adapters; a rejection becomes anerroraudit row naming the model routes and LongMemEval never starts. Rows also carry the evidence behind the verdict (#5506), every field optional so older rows read unchanged (logQualityProbeEventcopies them from one explicit list):reader_model/extractor_modelonce the routes resolved;judge_modelsin slot order,judge_scored_questionsper slot, anddistinct_judge_models/distinct_judge_providersover the slots that scored, from a completed batch; on a non-pass row, up to 10failures(failing dimensions with mean, slot-indexed scores and fail reason, or redacted error text) and a one-line digestdetailcounting every question that did not pass, malformed rows included, and naming a slot that scored none. One pricingwithChatCallMetermeter wraps LongMemEval and the batch, so every row of a run that reached its model calls, a part-way failure included, recordschat_calls,chat_cost_usd(reader, extractor and judges) andunpriced_chat_calls;est_cost_usdstays the batch's pre-flight estimate for its judge calls only, 0 without a summary. Run-level budget (CEO B4): oneBudgetTracker(withBudgetTracker) wraps both stages withmax_usdas the cap (resolveProbeCap: a configured value is ausercap, else the $5default;pricing.overridesfrom the brain), so every gateway chat/embed call of LongMemEval and the judges reserves first. A refusal is kept by theProbeBudgetTrackersubclass even when LongMemEval records it as a per-question error: exhausted after LongMemEval →budget_exceeded, no judge call; exhausted while judging →budget_exceededwhatever the batch said; a user cap refuses an unpriced model with the shared no_pricing text (reason: no_pricing), a default cap warns and runs it. Rows carrycap_usd/cap_source. A pass or fail from a collapsed panel (one model holding two judged slots, or fewer than two models judged) becomesinconclusivewithreason: panel_collapsed, the batch verdict and the slot-key remedy indetail(D12). A non-pass run copiessummary.json/lme-output.jsonlto<audit dir>/nightly-probe/<ts>/(newest 7) and names it inreceipt_dir. Thenightly_quality_probe_healthdoctor check (computeNightlyQualityProbeHealthCheckinsrc/commands/doctor/checks/search-eval.ts, registered right afterslug_fallback_auditbysrc/commands/doctor/checks/local-audits.ts) reads last 7 days: SKIPPED when flag off (with enable command); OK when enabled + all PASS; WARN on any non-PASS outcome with per-outcome counts (skipped=Nappended when a run skipped), so a skipped run is never OK. OK and WARN append the latest row's judge panel and name a slot that scored no question; among the slots that scored, a model holding two or more gets the remedy (three different models inmodels.eval.cross_modal.slot_a/slot_b/slot_c), fewer than three providers get the not-cross-modal information; a row without valid panel fields keeps the plain message. Pinned bytest/nightly-quality-probe.test.ts.src/core/cycle/dream-breaker.ts— dream paid-loop circuit breaker.countDeadDreamSubmissionsis the one counting rule shared by synthesize, patterns,gbrain dream reset-keyand thedream_paid_loopdoctor check: deadsubagentrows finished in the last 24 h (partial indexidx_minion_jobs_dead_subagent_finished, migration 173), keyed by the live or released idempotency key with the:c<i>of<n>chunk suffix stripped, counted as distinct queues (one per run), ignoring deaths before the key's persisted reset (dream.breaker.resetsconfig JSON, database clock). A key atdream.breaker.max_dead_submissions(default 3; 0 disables) is refused before synthesis submission; a failed count leaves the breaker off for that run with a warning. Completed jobs, including legitimate zero-write completions, never count. Synthesize deaths also count per transcript underdream:synth-v2:@file:<source id>:<encoded file>(dreamSynthFileKey) once they span two content keys, so a growing transcript trips too (W3, #6753), andgbrain dream reset-keyaccepts every key--listprints (DREAM_RESETTABLE_KEY_PREFIXES, #7505); unkeyed patterns runs are not covered. Contained cycle-phase failures after paid model calls (recordContainedPaidFailure,dream.breaker.contained_failuresconfig JSON, 24 h window, database clock) are counted underdream:phase:<phase>:<source>keys; the breaker never refuses those phases, doctor reports them andgbrain dream reset-keyclears them. Tests:test/dream-breaker.test.ts,test/cycle-synthesize-breaker.test.ts,test/e2e/dream-breaker-postgres.test.ts. Patterns rows count under the per-source keydream:patterns:source:<data.source_id or default>(never their content key), and a patterns childcancelledwith recorded tokens counts as a death;patternsBreakerSkipreturns the phase skip (dream_breaker_tripped, paid resetfix, read-only--list --jsonverify) andclearPatternsSourceDeathsresets the source after a completed child (test/dream-breaker-patterns-source.test.ts).src/core/cycle/phantom-redirect.ts— Phantom-redirect orchestrator. ExportsrunPhantomRedirectPass(engine, brainDir, sourceId, dryRun): Promise<PhantomPassResult>(per-cycle wrapper acquiring thegbrain-syncwriter lock once for the whole pass, 30s bounded retry, walks up toGBRAIN_PHANTOM_REDIRECT_LIMITunprefixed phantoms) +tryRedirectPhantom(engine, page, sourceId, brainDir, dryRun): Promise<RedirectResult>+stripFenceAndFrontmatterAndLeadingH1(pure body-shape gate helper — strips facts fence incl. preceding## Factsheading and the leading H1). Only fence rows migrate, so the residue gate also counts the page's timeline text, anytimeline_entriesrow, and frontmatter keys beyondtitle/type/tags; any residue = not a phantom. Handler order: body-shape gate →resolvePhantomCanonical(bypasses exact-self-match; a fuzzy hit needs a 0.1 margin over the runner-up) →findPrefixCandidatesambiguity check (a canonical that is not the single prefix candidate is ambiguous too) →fenceDbDriftbi-directional check → a phantom fence that parses with warnings isdrift(its skipped rows would go with the deleted phantom, #6385 R12) → dry-run early exit → canonical file resolved throughresolvePageWriteTarget(recordedsource_path, own-local_pathroots; only a brain with no configured root falls back tobrainDir) → materialize canonical viaserializeMarkdownif DB-only → append phantom fence rows to that file with(claim, valid_from)dedup-guard, numbering past both the file's and the DB's highest row number and rewritingsuperseded by #Nto the new numbers →engine.refreshPageBody→ move the phantom's fact withdrawals to the canonical subject → move every phantom fact row by id (a row takes its on-disk canonical row number unless the canonical index already holds it; history, duplicates and rows absent from the fence move expired and detached, never deleted) → move the phantom's links to the canonical page id (skipping duplicates and self-links) →recordRenameAlias(phantom → canonical inslug_aliases) →engine.softDeletePage+ unlink.RedirectResult.canonicalpopulated on'redirected'(incl. dry-run preview) so the caller buildstouched_canonicals. Idempotent on re-run: phantom soft-deleted → predicate fails (deleted_at IS NULL); migrate UPDATE matches no rows; dedup-guard prevents double-append.mergePhantomFenceRows(pure body merge; throwsFenceRewriteRefusalon a canonical fence that parses with warnings, which the pass records asdrift),movePhantomFacts(row move inside the caller's transaction) andmergePhantomLinksare shared withphantom-redirect-managed.ts, which a managed brain uses instead of the file-first commit phase. GBRA-130 A-24: the pass resumes after the last slug it examined (slug > cursor, op_checkpoints opPHANTOM_REDIRECT_CURSOR_OP=phantom-redirect-cursor, fingerprint the source id, viarotationAfter/saveRotation), so root prose notes that are not phantoms no longer starve later phantoms; the cursor resets to''after a full pass and stays put on a dry run, an abort or a stop. Phantoms run asItemRunitems (extract_facts.phantom_redirect): an item error is afailures[]entry (key,code,message,fixgbrain dream --phase extract_facts --source <id>) and the next phantom still runs; a run-scoped error rethrows anditem_failures_systemicsetsstopped.extract-facts.tsturns them intophantom_redirect_failed: <slug> (<code>); retry: <fix>andphantom_redirect_stopped: …warnings. Pinned bytest/pathological/a24-phantom-redirect-cursor.test.ts(both engines). #6982 (GBRA-131 D-5/D-6): withsync.write_throughoff the phantom's rows merge into the canonical's database body under a row lock (prior body in page_versions) and no file is written or removed. With it on, the phantom's file is removed only whenreplaceableFilefinds nothing in it its row lacks (re-read right before the unlink; a changed file is kept and reported), and the canonical file takes the rows only when its body and timeline equal the canonical's database body; the mirror then runs under the row lock (mirrorFileBody, prior body in page_versions, importer hash), the file is re-read immediately before the.tmpis renamed last, and a body that moved, or a file that moved (which rolls the transaction back), holds the phantom. Holds aredriftoutcomes listed inPhantomPassResult.held(<slug> (file_database_drift: …)with its fix), which extract_facts turns intophantom_redirect_held:warnings. Pinned bytest/pathological/d5-phantom-canonical-overwrite.test.tsandtest/pathological/d6-phantom-file-unlink.test.ts(both engines).src/core/cycle/phantom-redirect-managed.ts— managed-brain phantom redirect (#5280). After the same gates,redirectManagedPhantomrunsmaintenancePreflight, renders the canonical body with the phantom's fence rows appended and submitsmanaged_maintenance_phantom_mergeon the canonical page (keyed by its intent):preparePhantomMergerechecks the phantom's id and revision, and its publication moves withdrawals, the phantom's fact rows by id, links and the rename alias in the canonical page's publication transaction. It then submitsmanaged_maintenance_phantom_deleteon the phantom, bound to the merged revision:preparePhantomDeleteholds both page keys, moves any edge added to the phantom since the merge, defers if timeline rows appeared, then soft-deletes and removes the file. A missing canonical page or a changed phantom is reported asdrift. Tests:test/managed-facts-writers.test.ts.src/core/cycle/lock-set.ts— Cycle lease set (#6242).acquireLeaseSet(required, acquire, optional)takes the required lease ids, then the optional ones, without waiting, in that order with duplicates dropped: a busy required lease or any acquire that throws releases what was taken (busy →{status:'busy', busyId}, throw → rethrow), a busy optional lease returns the held set withbusyOptional.combineLeasesrefreshes in order and returns false at the first lease it no longer owns, and releases every lease in reverse, rethrowing the first failure.cycle.tsuses it so a source-scoped cycle with brain-wide phases holdsgbrain-cycle:<source>plusgbrain-cycle(PGLite still takes its file lock first);maintenanceLockBusySkip(phase, holder)builds themaintenance_lock_busyskipped result (details:reason,code,phase_scope,lock_id,lock_holder,why,fix=gbrain dream --phase <p>withpaidconsent and a read-onlygbrain status --section locks --jsonverify). Pinned bytest/cycle-lock-set.test.ts,test/cycle-pglite-lock-ordering.serial.test.tsandtest/e2e/cycle-maintenance-lock.test.ts.src/core/cycle/phase-scope.ts— the phase-scope taxonomy:PHASE_SCOPE: Record<CyclePhase, 'source'|'mixed'|'global'>maps everyALL_PHASESentry (source: safe to parallelize per source; global: must serialize across the brain, sofence_repairand the other brain-wide phases run once in the global maintenance job and never in a per-source payload; mixed: brain-wide read + page write, so it stays in the default/global-maintenance lane until decomposed), plusSOURCE_FRESHNESS_PHASES— the deterministic, non-LLM subset (lint, backlinks, sync, extract, extract_facts, recompute_emotional_weight) that alone defines source freshness, so LLM-backed enrichment can never hold a freshness stamp hostage. cycle.ts re-exports both and derives the scheduling lists from them (see the cycle.ts entry). Consumed byrunCycle'sresolveCyclePhasesboundary, the autopilot fanout's per-source enqueue (src/commands/autopilot-fanout.ts), the jobs global-maintenance handler, and doctor's routing-federation phase-scope surface (src/commands/doctor/checks/routing-federation.ts). Pinned bytest/autopilot-global-maintenance.test.ts(SOURCE ∪ MIXED ∪ GLOBAL == ALL_PHASES with no overlap; FRESHNESS ∪ BACKGROUND == SOURCE; resolveCyclePhases boundary semantics).src/core/cycle/recompute-emotional-weight.ts— Cycle phase orchestrator. One read plus bounded writes:engine.batchLoadEmotionalInputs(slugs?)→computeEmotionalWeight(per-row pure function) →engine.setEmotionalWeightBatch(slice)in slices of 1000 rows. Between slices it checksopts.signal(throws →fail), awaitsopts.yieldDuringPhase(cycle-lock refresh / steal detection), firesopts.onProgress, and yields a macrotask (setTimeout(0)) so PGLite's synchronous statement execution never wedges the main thread for a whole-brain pass;runCyclewires these exactly like consolidate (racedTimePhase+buildYieldDuringPhase+cycleSignal+progress.tick). Both engines'setEmotionalWeightBatchrewrite only rows whose weight changes (IS DISTINCT FROMin the WHERE — no trigger fan-out on same-value rows) and return rows CHANGED;details.pages_recomputed= pages evaluated (feeds the cycle totals),details.pages_updated= rows changed. Reads configemotional_weight.high_tags(JSON array, falls back to default seed list on parse error) andemotional_weight.user_holder. EmptyaffectedSlugsshort-circuits with zero-work success. dry-run reports the would-write count without touching the DB. Engine throw bubbles intostatus: 'fail'with codeRECOMPUTE_EMOTIONAL_WEIGHT_FAILso the cycle continues.src/core/cycle/phase-containment.ts—timeContainedPhaseis the timer everyrunCyclephase runs under: a phase runner that throws returns afailphase result carrying{ class, code, message }anddetails.contained, so later phases in the job still run while the report stays partial/failed (global freshness is not stamped;gbrain dreamexits non-zero). Cancellation (an aborted cycle signal orAbortError),LockStolenErrorandBudgetExhaustedare never contained. Successfulgateway.chatcalls inside the phase are counted throughwithChatCallMeter(ai/chat-usage.ts); a contained failure after at least one paid call is recorded underdream:phase:<phase>:<source>fordream_paid_loop. Tests:test/cycle-phase-containment.test.ts. Each phase also runs underwithAIAttribution({ phase: 'cycle:<phase>' }), so model calls it makes carry the phase in invocation observers andGBRAIN_AI_CALL_LOG.src/core/cycle/fence-repair.ts— thefence_repairmaintenance phase:runFenceRepairPhase(engine, { dryRun, signal?, deadlineAtMs?, registry?, now? })runs thefencesrepair kind (src/core/repair/fences.ts) once through the trustedrepairRunner(apply; a preview on a dry run) over every active source, with no rule logic of its own: the kind plans from its census, skips sources this host may not write (an owner reason such ashost_mismatch,owner_unavailableas the fallback) and the candidates a running sync still names (sync_in_progress; the rest of a syncing source is repaired), readsfences.repair.llmand the daily USD ledger, and re-plans on the next run.fences.repair.enabledfalse skips it without calling the kind (the summary namesgbrain config set fences.repair.enabled true). The run's deadline is min(FENCE_REPAIR_PHASE_BUDGET_MS= 300 s, a third of the maintenance job's remaining time), 300 s without a job deadline; past itrunRepairstops before the next item withtime_budget(status ok, resumed by the next run). Details read the kind'sFenceRepairVerification:candidates,repaired,repaired_by_tier,held_by_reason,llm_usd,llm_usd_per_repair,oldest_hold_at/oldest_hold_age_hours,llm_enabled,scan_partial,time_budget_ms,stopped_reason; the summary says when Tier 3 is off and how many fences need a manual edit (fix:gbrain repair fences). Any other stop reportswarnwith the kind's fix; an internal error reportswarnwith its code only (no message, which could carry fence content) unless the cycle is aborted. Brain-global, aftersyncinALL_PHASES, classifiedwrites. Test:test/cycle-fence-repair.test.ts.src/core/cycle/content-repair.ts— thecontent_repairmaintenance phase (#6377):runContentRepairPhase(engine, { dryRun, signal?, deadlineAtMs?, kinds?, registry?, now? })runs the content-repair lane (src/core/repair/content-lane.ts) minusfences, whichfence_repairjust ran (contentRepairPhaseKinds(); withCONTENT_REPAIR_KINDSholding onlyfencesthe phase runs nothing and reportsskipped/no_kinds), through the shared trustedrepairRunnerover every active source: an apply, or a preview on a dry run. Gated onfences.repair.enabled(one switch for the whole lane; the summary namesgbrain config set fences.repair.enabled trueandgbrain repair content). Deadline min(CONTENT_REPAIR_PHASE_BUDGET_MS= 120 s, a third of the maintenance job's remaining time); past it the lane's kind stopstime_budget(status ok, the next run resumes). Details:kinds,candidates,repaired,held_by_reason(each kind'sremaining, else its per-item outcome reasons),by_kind(mode, counts by outcome, spend, oldest hold, stop),llm_usd,oldest_hold_at/oldest_hold_age_hours,time_budget_ms,stopped_reason; the summary counts holds that wait for a person (merge_recommended,content_repair_needs_human) and points atgbrain sync status. Any stop other than the time budget reportswarnwith the kind's fix; an internal error reportswarnwith its code only unless the cycle is aborted. Brain-global, right afterfence_repairinALL_PHASES, classifiedwrites. Test:test/cycle-content-repair.test.ts.src/core/cycle/unindexed-files.ts— theunindexed_filesmaintenance phase (#6865, global, right aftercontent_repairthrough theREPAIR_LANE_PHASESdispatch helper): on a managed brain,runUnindexedFilesPhase(engine, { dryRun, signal?, deadlineAtMs?, now? })runs one detector pass (persistence/unindexed-files.ts) per managed Git source this host owns, least recently scanned first (#7149: no stored result first, then the oldest, so one large source cannot starve the others), under one deadline of min(5 min, a third of the maintenance job's remaining time), each source also stopping at its own budget (unindexedScanBudgetMs: 60 s per started 100k live pages); a source the budget stops continues from its stored cursor next run. A real run stores each result and schedules the found files for a re-screen on the next sync (requestGitHoldRetry, at most 5,000 per run); a dry run reports without writing. Company-brain sources and sources this host does not own are skipped with a reason; an error on one source iswarnand the others still run, anddetails.completeis true only when no source stopped at its budget or errored (#8887). Details are counts by source and code, never a path; it never runs on the per-sync path. Classifiedno_coordinated_write(phase-table.ts). Tests:test/unindexed-files.test.ts,test/unindexed-files-convergence-7149.test.ts,test/managed-phase-matrix.test.ts.src/core/cycle/phase-table.ts—MANAGED_PHASE_TABLEclassifies everyALL_PHASESentry for managed brains aswrites(publishes through the coordinator),no_coordinated_write(derived projections, side tables, audit-only) ormanaged_skip, each with its reason;isManagedBrainis whatrunPhaseLintuses to report issues without rewriting managed canonical files. The managed phase matrix test fails for an unclassified phase. Each entry has atierthat upkeep's step list is checked against.