Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
58.6 KB
Raw Blame

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_date is 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: sets dream_generated, a stable dream_cycle_date / dream_created_cycle_date and an optional raw_source in 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 optional seat is stamped beside raw_source (the capturing agent seat, #4618). #5575 I2: a ref carrying derivation is stamped in derivedMaintenanceTransaction at the child's derived tier, and the page is lowered to it and gets its derivation_inputs edges even when it is not dream-owned (the child wrote it from that prompt). Pinned by test/trust-taint-dream.test.ts.

  • src/core/cycle/dream-taint.ts — #5575 I2 taint for the dream derivers (ENG-3): transcriptDerivation gives a synthesis transcript's tier (a gbrain-page:// conversation page = that page's stored tier, with an edge to it; a file under dream.synthesize.meeting_transcripts_dir = external_untrusted; any other corpus file = the cap its frontmatter names, else agent_written); transcriptsDerivation takes the least trusted of several; withTranscriptTaint attaches it to unmanaged output refs; summaryDerivation gives the dream summary the tier of the pages it indexes (written as a dream_summary single-page generation, GBRA-161 PR 5); patternsDerivation is 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 by test/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 containing atoms; the schema uses closed objects and nullable optional metadata. extract-atoms.ts passes 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 by test/cycle/extract-atoms-structured-output.test.ts using 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 by extract-atoms.ts. parseAtomsOutcome returns a typed outcome (ok: false with 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_filter are never parsed, and an empty answer under other/tool_calls is not taken as complete; both return ok: false, stopped: true, which extract-atoms.ts counts in details.stopped_outputs and 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 (matchingCloseBracket in llm-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. atomsFromParsedArray is the single atom shape gate.

  • src/core/cycle/anomaly.ts — Pure stats helpers for find_anomalies. meanStddev returns 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, returns AnomalyResult[]. Zero-stddev fallback: cohort fires when count > mean + 1, with sigma_observed = count - mean as a finite sort proxy (no NaN). Brand-new cohorts (no baseline) have mean=0, stddev=0 so the fallback fires at count >= 2. Sorted by sigma_observed desc, top limit (default 20). page_slugs capped at 50 per cohort.

  • src/core/cycle/cycle-date.ts — the dream-cycle calendar-date policy (runCycle resolves it once and threads cycleDate into synthesize, patterns and drift, so one cycle never splits across days; test/cycle-date-consistency.test.ts also lints src/core/cycle* for the UTC-day toISOString().slice(0, 10) pattern; shiftCalendarDate does lookback arithmetic on the date string): resolveCycleDate resolves explicit --date > cycle.timezone config > 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. isValidTimeZone gates configured values (config.ts also validates at gbrain config set time); an invalid configured timezone falls back loudly instead of killing the cycle. utcDate is retained for source-date fallbacks and legacy pages.

  • src/core/cycle/emotional-weight.ts — Pure function computeEmotionalWeight({tags, takes}, {highEmotionTags?, userHolder?}). Deterministic 0..1 score: tag-emotion boost (max 0.5, case-insensitive match against HIGH_EMOTION_TAGS seed 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 config emotional_weight.high_tags (JSON array). userHolder overridable via emotional_weight.user_holder.

  • src/core/cycle/extract-atoms-cost-gate.ts — cost-gate decision for the extract_atoms BudgetTracker, shared with the Life Chronicle chronicle phase through settleExtractAtomsCostGate's target (phase name, refusal key prefix chronicle.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 same withBudgetTracker scope) calls — with operator pricing.overrides consulted first, matching BudgetTracker.reserve(). resolveEmbedModelForCostGate() mirrors the write site's isAvailable('embedding') gate (null when embedding is unavailable). A DEFAULT cap is dropped for an unpriced route (warn and run). When the operator SET cycle.extract_atoms.budget_usd (explicitBudget), an unpriced chat model or embed route yields refusal (the shared no_pricing guidance). settleExtractAtomsCostGate acts before any work item: it warns on a dropped cap; on a refusal it returns the phase's warn result (details.reason: 'no_pricing', details.no_pricing, no model call), records the guidance at cycle.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 + withExtractAtomsNoPricing overlay doctor's extract_health (wired in doctor/checks/local-audits.ts) with a warn naming the model and register_command. Pinned by test/extract-atoms-embed-cost-gate.test.ts and test/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, optional onBatch) 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 (job signal + 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). stopped is a DrainStop (drained|window|deadline|lock_lost|aborted|no_progress|max_batches|provider_failure|budget); budget (#6425) stops after the first batch that reports budgetSkipped > 0 (the attempt's one tracker is spent) and carries spent_usd/budget_usd, which dream --drain renders as the spend, the cap and an atom_drain_budget notice whose paid fix raises cycle.extract_atoms.budget_usd; the Minion handler completes it normally; a hard stop skips onBatch and the recount and reports the last count as remaining, and the lease loss withRefreshingLock rethrows becomes lock_lost with the partial counters. Backs gbrain dream --phase extract_atoms --drain under the SAME cycleLockIdFor(sourceId) the routine cycle takes (a concurrent tick defers with cycle_already_running). runExtractAtomsDrainForSource(engine, {sourceId, windowSeconds, brainDir?, maxBatches?, onBatch?, signal?, deadlineAtMs?}) owns the lock+batch+count wiring for all three callers — dream --drain, the extract-atoms-drain Minion handler, autopilot auto-drain. sourceId: undefined → legacy gbrain-cycle lock + 'default'; a real id → gbrain-cycle:<id>. LockUnavailableError propagates. One runExtractAtomsDrainForSource call is one drain attempt: its batches share one BudgetTracker (the per-run cycle.extract_atoms.budget_usd cap is the attempt's cap) and one MaintenanceWriteWait (persistence/maintenance-wait.ts, bounded by deadlineAtMs). structuralAtomRefusal maps an owner_unavailable/permission_denied refusal from the atom session preflight to STRUCTURAL_REFUSAL_PREFIX text; the extract-atoms-drain Minion handler (src/core/minions/handlers/extract-atoms-drain.ts) throws it as UnrecoverableError, so the job dead-letters once with no model call and the auto-drain cap does not count it. last_error and the typed failure records pass through sanitizeFailureText (secret/DSN redaction, bounded). #7514: a record whose write did not commit also carries request_id and code; the adapter leaves such items out of providerFailure and its class (they never reached a provider), a batch that extracted nothing (whatever it skipped, #8445) is recounted and stops no_progress when the backlog did not shrink, and a batch whose only progress is write-failure strikes (writeStrikes) is not no_progress (nor is a 0/0 batch started after the window closed: that is window), so the drain moves on and the strikes reach their hold in the same window. A provider_failure result carries provider_failure_class (batchProviderFailureClass: the phase's aborted_global_error halt class auth/billing/model_not_found/rate_limit, content_block when every failure is a provider content block, else transient). formatDrainProviderFailure(result, {final?}) renders the handler's provider_failure throw; the handler throws UnrecoverableError on deadline, on a provider failure drainOutcome marks not retryable, or any failure at/past deadlineAtMs, the job's abort reason on aborted, and a retryable error on lock_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, JSON status (never ok for an incomplete stop), retryable, code and reason, read from the error registry (atom_drain_incomplete exit 11, atom_drain_provider_failure exit 1 with rate_limit/transient overridden to retryable exit 11, atom_drain_no_progress exit 1; a null count is always atom_drain_incomplete/count_unavailable). Used by dream --drain and the extract-atoms-drain Minion 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 the atom_drain_budget notice a budget-stopped drain carries in gbrain dream --drain --json (spend, per-run cap, pages left; paid fix gbrain config set cycle.extract_atoms.budget_usd <USD>, verify gbrain config get), and usd formats the amounts for the stderr stop line. Dynamically imported by dream.ts so 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. resolveExtractAtomsInputCap reads cycle.extract_atoms.max_input_chars (floor 1000; the older max_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, with truncated measured on the text the cap applied to. A page item also takes its stored extract_atoms watermark (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 newest cap characters when longer), which is still partial input, so the same disposition below applies; inputTruncatedLine is 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_truncated counts it on the phase result (and the drain sums it into input_truncated, with one [drain] line), inputTruncatedLine is written to stderr naming the knob, the head atoms publish, no completion stamp is written and nothing is retired. recordPartialDisposition stores the cap under (content hash, cap) in extract_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 carries partialInputChars, which enters the run key, keeps the completion's checkpoint partial, skips the page-state stamp and the retirement, and marks the completion outcome status: 'partial'. Discovery and the backlog count skip a partial row like a tombstone (PAGE_SCAN_STATE_EXCLUSION_SQL, tombstonedTranscriptsForHashes, the partial checkpoint); releasePartialDispositions runs 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; countExtractAtomsBacklog reads the same cap and counts a page whose partial row or checkpoint sits below it (pageScanStateExclusionSql / managedAtomDiscoverySql with 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 (publicBody from mentions/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 verified source_quote never 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) into atoms/<date>/<stem>-<hash> pages. The input cap, the cut and the partial disposition of a cut item are in extract-atoms-input.ts (#6503). Transcript input is paste-stripped before the cut (#5812); discovery skips self-captures (#5820) and keeps only the session-corpus files keepSessionSourceTranscripts (synthesize-source-routing.ts, shared with synthesize; a file is a corpus file by its spelled or real path, an unreadable real path is held corpus_path_unresolvable, #7871) resolves to the run's source, read-only in a dry run, reporting the rest in details.source_routing (#7846); a resumed generation member whose transcript no longer resolves to the run's source (transcriptSourceHold) is held, not resubmitted, and counted in details.source_routing.generation_members_held (#7870); the meeting transcripts dir is read only for default. Discovery and the backlog count append connectorAtomExclusionSql (connector-atoms.ts), so connector email/meeting pages stay out only when cycle.extract_atoms.connector_pages is false. The type allowlist is unionExtractableTypes(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 without extractable: true is a pack decision, an undeclared type keeps the floor), plus the pack's extractable: true types, minus synthesis outputs; gbrain-base is unchanged, gbrain-recommended's source: false now holds for atoms as it did for facts. Pinned by test/pack-extractable-floor-5756.test.ts. A drain attempt passes opts.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, resumeManagedAtoms in persistence/atom-maintenance.ts); an origin held after MAX_DETERMINISTIC_FAILURES (now defined in extract-atoms-page-state.ts, re-exported here) is skipped with no model call and counted in details.held_failed, never in failures. 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 in extract-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, managed generation_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): its failures entry carries request_id, code, and its strike, never a provider classification. An undated source dates its atoms by the source page's creation date (undated for transcripts), never the run date. A page-derived atom's frontmatter date is the source page's content date (atom-source-date.ts: the stored effective_date, else computeEffectiveDate), read with the input before the model call, so classic import and managed publication store that effective_date (source date) and extracted_at stays the processing stamp; transcript-derived atoms carry no date. After an unmanaged item completes (completeUnmanagedItem), retireStaleAtoms soft-deletes that source's atoms from earlier extractions (other or provisional source_hash) that this extraction did not re-produce; a cut item neither completes nor retires. Hard opts.signal (chat call, pacing, checks before each item and commit) leaves no strike, receipt or rollup; soft opts.stopSignal stops before the next item. Managed completion admits revision-pinned managed_atom_delete children 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. resolvePageAtomSlug adopts a legacy-slug atom with a compatible binding in place on re-extraction (upgrade idempotency — no migration, no duplicate), while assertAtomImportBinding fail-closed refuses to reuse a slug bound to a DIFFERENT source locator. Both share isCompatibleAtomBinding(frontmatter, sourcePageSlug) — the ONE definition of compatible: bound to THIS source page, or carrying no source_slug/source_path at all (pre-binding-era adoption, not a clobber); a source_path-bound legacy transcript atom or a different source_slug is a different origin, and a non-atom page squatting on the slug is refused. source_quote is verified at extraction time against the exact truncateUtf8 prompt prefix the model saw (locateQuote advances 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 the extract_atoms_transcript_state table (keyed (source_id, file_path, content_hash), 16-char hash prefix, so an edit is a new row): recordItemFailureCount counts a transcript's malformed output or prompt-level provider block (providerContentBlockReason; never feeds the outage halt) toward MAX_DETERMINISTIC_FAILURES, a zero-yield transcript tombstones immediately (as pages do), and tombstonedTranscriptsForHashes is the batch read-side gate mirroring atomsExistingForHashes (fail-open on error). Reported as tombstoned_transcripts (paths), separate from the page-slug tombstoned_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 ## Facts fence 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_num NULL), 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 #N links 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) through facts/unfenced-facts.ts and 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 as FACTS_FENCE_FAILED: <slug> (<reason>) and keep their own page out of the destructive reconcile (the empty-fence guard, per page since #6278: pendingLegacyRows lists the pages, legacyRowsPending and legacyPages report them, and every other page of the source still reconciles; the page keeps its fact index because reconciliation would classify its row_num IS NULL rows 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 in pagesFailed, booked as a halt in the rollup), and later pages still reconcile. facts.superseded_by is ON DELETE SET NULL. On an unmanaged brain each reconcile records its outcome in page_facts_reconcile (src/core/facts/reconcile-watermark.ts): a complete reconcile (including a no-op) stamps the page's knowledge_revision inside the write transaction, after a FOR SHARE lock 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) and cancelled leave it due. The dream cycle passes drain, 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 with slugs: [] and no drain still reconciles nothing. Doctor's extract_health names unreconciled fence pages and unreadable fences on unmanaged brains. Tests: test/extract-facts-reconcile-drain.test.ts (Postgres race through test/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 after managedDerivedFactsPreflight (local writer, active source, before any embedding call): each page transaction and the deleted-page expiry commit inside withDerivedFactsWrite (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 site extract_facts.expire_deleted, src/core/item-failure.ts): a refused expiry is a FACTS_EXPIRE_FAILED: <slug>: <code>: … warning (the phase warns) retried by the next run, a page the refusal breaker holds back is a FACTS_EXPIRE_SKIPPED warning, and run-scoped errors or most pages failing (item_failures_systemic) still fail the phase; test test/pathological/a21-facts-expire-deleted.test.ts. It is distinct from the coordinated extract_facts operation 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); test test/large-pages/segmented-facts-reconcile.test.ts. #6259: it and extract-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 --url clone on an unmanaged brain never gates the empty-fence guard (its facts are database-only by design). #8819: on a managed brain planFenceReconcile keeps 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), and writeFenceReconcile moves 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 independent drainLoops (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) while promoteDelayed runs 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 → releaseLeaseFullJob requeue without burning an attempt; timeout terminal. Handler invocation is wrapped in withChatPhase('job:<name>') (worker.ts parity) so each drained child's gateway spend is attributed to the CHILD — a bare await handler(context) inherits the caller's AsyncLocalStorage phase, and a cycle phase that wraps its own work (dream synthesize wraps phase:synthesize) would absorb every child's spend into the phase tag. runDrainRenewalTick (per-call AbortSignal + timeout + re-entrancy guard) and the null-safe nearest-rank percentile() telemetry helper are exported. Pinned by test/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, bounded searchKeyword FTS 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 by test/cycle-link-manifest.test.ts.

  • src/core/cycle/nightly-probe-adapters.ts — bridges the autopilot's object-shape NightlyProbeDeps to the argv-shape runEvalLongMemEval + runEvalCrossModal CLI functions. Cross-modal adapter argv MUST include --output summaryPath (without it the summary lands at the default receipt path and the adapter reads nothing from summaryPath) 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) and exitOnError: 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 builders buildLongMemEvalProbeCall / buildCrossModalProbeCall carry the brain-resolved modelRoutes: the reader as --model, the extractor as RunOpts.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 keeps total, malformed_count, judge_models (slot order), panel (with per-slot slot_scored_questions) and every non-passing question as failures: scores come from the batch's slot-indexed slot_scores, a failing dimension outside PROBE_QA_DIMENSIONS is recorded as unrecognized, 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 by test/cycle/nightly-probe-adapters.test.ts (incl. the argv-shape guard for the --output requirement, the builder cases with and without routes, and the summary parse over a canned summary) and test/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 with import ... with { type: 'file' } (types in src/types/jsonl-assets.d.ts). A source checkout resolves them to test/fixtures/..., a compiled binary to a /$bunfs/ path readFileSync reads, so both installs run the probes (#5187, C-N6). Pinned by test/nightly-probe-compiled-binary.serial.test.ts (a bun build --compile harness 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 through NIGHTLY_PROBE_READER_ROUTE (models.eval.longmemeval → models.tier.reasoning → models.default → GBRAIN_MODEL → key-aware default, the chain gbrain models reports for that key), extractor through NIGHTLY_PROBE_EXTRACTOR_ROUTE (utility tier), and the optional models.eval.cross_modal.slot_{a,b,c} keys (NIGHTLY_PROBE_SLOT_KEYS; alias-expanded, blank = unset). Any read failure rethrows as NightlyProbeModelRoutesError, whose message names the routes. Consumed by autopilot-probes.ts (after a gateway refresh) and gbrain models. Pinned by test/cycle/nightly-probe-routes.test.ts. readCrossModalSlotConfig(reader) is the one slot-pin reader (#6486), shared with gbrain eval cross-modal: the CLI resolves each judge slot as --slot-<x>-model flag → models.eval.cross_modal.slot_<x> → DEFAULT_SLOTS (resolveSlotModels in src/commands/eval-cross-modal.ts; a config pin counts as explicit for the #4636 substitution), reading the pins through readCrossModalSlotConfigFrom(connect) only when some slot has no flag; src/cli/main.ts passes 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 before gbrain init. Pinned by test/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 runs gbrain eval longmemeval --by-type against the committed 10-question placeholder fixture, pipes output through gbrain 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, mirrors audit-slug-fallback.ts; honors GBRAIN_AUDIT_DIR). Default DISABLED — opt-in via gbrain config set autopilot.nightly_quality_probe.enabled true (prevents surprise API spend). 24h rate limit (pure shouldRunNightly(now, recentEvents, windowMs?)) skips without an audit row. An unreadable fixture writes outcome: skipped with reason: fixture_unavailable (exit 0, no model call; the row also holds the 24h gate). Embedding-key short-circuit: longmemeval needs gateway.embedQuery(), so the phase exits early with outcome: no_embedding_key + stderr warn when no provider configured. Full DI surface via NightlyProbeDeps (isEnabled, hasEmbeddingProvider, resolveMaxUsd, optional resolveBudgetPolicy, resolveFixturePath (wins) / resolveRepoRoot, resolveSearchConfigSnapshot and resolveModelRoutes, runLongMemEval, runCrossModalBatch, now) so the unit test stubs every external effect. resolveModelRoutes runs inside the run's try before LongMemEval and its routes reach both adapters; a rejection becomes an error audit 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 (logQualityProbeEvent copies them from one explicit list): reader_model / extractor_model once the routes resolved; judge_models in slot order, judge_scored_questions per slot, and distinct_judge_models / distinct_judge_providers over the slots that scored, from a completed batch; on a non-pass row, up to 10 failures (failing dimensions with mean, slot-indexed scores and fail reason, or redacted error text) and a one-line digest detail counting every question that did not pass, malformed rows included, and naming a slot that scored none. One pricing withChatCallMeter meter wraps LongMemEval and the batch, so every row of a run that reached its model calls, a part-way failure included, records chat_calls, chat_cost_usd (reader, extractor and judges) and unpriced_chat_calls; est_cost_usd stays the batch's pre-flight estimate for its judge calls only, 0 without a summary. Run-level budget (CEO B4): one BudgetTracker (withBudgetTracker) wraps both stages with max_usd as the cap (resolveProbeCap: a configured value is a user cap, else the $5 default; pricing.overrides from the brain), so every gateway chat/embed call of LongMemEval and the judges reserves first. A refusal is kept by the ProbeBudgetTracker subclass even when LongMemEval records it as a per-question error: exhausted after LongMemEval → budget_exceeded, no judge call; exhausted while judging → budget_exceeded whatever 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 carry cap_usd / cap_source. A pass or fail from a collapsed panel (one model holding two judged slots, or fewer than two models judged) becomes inconclusive with reason: panel_collapsed, the batch verdict and the slot-key remedy in detail (D12). A non-pass run copies summary.json / lme-output.jsonl to <audit dir>/nightly-probe/<ts>/ (newest 7) and names it in receipt_dir. The nightly_quality_probe_health doctor check (computeNightlyQualityProbeHealthCheck in src/commands/doctor/checks/search-eval.ts, registered right after slug_fallback_audit by src/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=N appended 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 in models.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 by test/nightly-quality-probe.test.ts.

  • src/core/cycle/dream-breaker.ts — dream paid-loop circuit breaker. countDeadDreamSubmissions is the one counting rule shared by synthesize, patterns, gbrain dream reset-key and the dream_paid_loop doctor check: dead subagent rows finished in the last 24 h (partial index idx_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.resets config JSON, database clock). A key at dream.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 under dream:synth-v2:@file:<source id>:<encoded file> (dreamSynthFileKey) once they span two content keys, so a growing transcript trips too (W3, #6753), and gbrain dream reset-key accepts every key --list prints (DREAM_RESETTABLE_KEY_PREFIXES, #7505); unkeyed patterns runs are not covered. Contained cycle-phase failures after paid model calls (recordContainedPaidFailure, dream.breaker.contained_failures config JSON, 24 h window, database clock) are counted under dream:phase:<phase>:<source> keys; the breaker never refuses those phases, doctor reports them and gbrain dream reset-key clears 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 key dream:patterns:source:<data.source_id or default> (never their content key), and a patterns child cancelled with recorded tokens counts as a death; patternsBreakerSkip returns the phase skip (dream_breaker_tripped, paid reset fix, read-only --list --json verify) and clearPatternsSourceDeaths resets the source after a completed child (test/dream-breaker-patterns-source.test.ts).

  • src/core/cycle/phantom-redirect.ts — Phantom-redirect orchestrator. Exports runPhantomRedirectPass(engine, brainDir, sourceId, dryRun): Promise<PhantomPassResult> (per-cycle wrapper acquiring the gbrain-sync writer lock once for the whole pass, 30s bounded retry, walks up to GBRAIN_PHANTOM_REDIRECT_LIMIT unprefixed phantoms) + tryRedirectPhantom(engine, page, sourceId, brainDir, dryRun): Promise<RedirectResult> + stripFenceAndFrontmatterAndLeadingH1 (pure body-shape gate helper — strips facts fence incl. preceding ## Facts heading and the leading H1). Only fence rows migrate, so the residue gate also counts the page's timeline text, any timeline_entries row, and frontmatter keys beyond title/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) → findPrefixCandidates ambiguity check (a canonical that is not the single prefix candidate is ambiguous too) → fenceDbDrift bi-directional check → a phantom fence that parses with warnings is drift (its skipped rows would go with the deleted phantom, #6385 R12) → dry-run early exit → canonical file resolved through resolvePageWriteTarget (recorded source_path, own-local_path roots; only a brain with no configured root falls back to brainDir) → materialize canonical via serializeMarkdown if 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 rewriting superseded by #N to 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 in slug_aliases) → engine.softDeletePage + unlink. RedirectResult.canonical populated on 'redirected' (incl. dry-run preview) so the caller builds touched_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; throws FenceRewriteRefusal on a canonical fence that parses with warnings, which the pass records as drift), movePhantomFacts (row move inside the caller's transaction) and mergePhantomLinks are shared with phantom-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 op PHANTOM_REDIRECT_CURSOR_OP = phantom-redirect-cursor, fingerprint the source id, via rotationAfter/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 as ItemRun items (extract_facts.phantom_redirect): an item error is a failures[] entry (key, code, message, fix gbrain dream --phase extract_facts --source <id>) and the next phantom still runs; a run-scoped error rethrows and item_failures_systemic sets stopped. extract-facts.ts turns them into phantom_redirect_failed: <slug> (<code>); retry: <fix> and phantom_redirect_stopped: … warnings. Pinned by test/pathological/a24-phantom-redirect-cursor.test.ts (both engines). #6982 (GBRA-131 D-5/D-6): with sync.write_through off 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 when replaceableFile finds 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 .tmp is renamed last, and a body that moved, or a file that moved (which rolls the transaction back), holds the phantom. Holds are drift outcomes listed in PhantomPassResult.held (<slug> (file_database_drift: …) with its fix), which extract_facts turns into phantom_redirect_held: warnings. Pinned by test/pathological/d5-phantom-canonical-overwrite.test.ts and test/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, redirectManagedPhantom runs maintenancePreflight, renders the canonical body with the phantom's fence rows appended and submits managed_maintenance_phantom_merge on the canonical page (keyed by its intent): preparePhantomMerge rechecks 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 submits managed_maintenance_phantom_delete on the phantom, bound to the merged revision: preparePhantomDelete holds 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 as drift. 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 with busyOptional. combineLeases refreshes in order and returns false at the first lease it no longer owns, and releases every lease in reverse, rethrowing the first failure. cycle.ts uses it so a source-scoped cycle with brain-wide phases holds gbrain-cycle:<source> plus gbrain-cycle (PGLite still takes its file lock first); maintenanceLockBusySkip(phase, holder) builds the maintenance_lock_busy skipped result (details: reason, code, phase_scope, lock_id, lock_holder, why, fix = gbrain dream --phase <p> with paid consent and a read-only gbrain status --section locks --json verify). Pinned by test/cycle-lock-set.test.ts, test/cycle-pglite-lock-ordering.serial.test.ts and test/e2e/cycle-maintenance-lock.test.ts.

  • src/core/cycle/phase-scope.ts — the phase-scope taxonomy: PHASE_SCOPE: Record<CyclePhase, 'source'|'mixed'|'global'> maps every ALL_PHASES entry (source: safe to parallelize per source; global: must serialize across the brain, so fence_repair and 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), plus SOURCE_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 by runCycle's resolveCyclePhases boundary, 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 by test/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 checks opts.signal (throws → fail), awaits opts.yieldDuringPhase (cycle-lock refresh / steal detection), fires opts.onProgress, and yields a macrotask (setTimeout(0)) so PGLite's synchronous statement execution never wedges the main thread for a whole-brain pass; runCycle wires these exactly like consolidate (racedTimePhase + buildYieldDuringPhase + cycleSignal + progress.tick). Both engines' setEmotionalWeightBatch rewrite only rows whose weight changes (IS DISTINCT FROM in 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 config emotional_weight.high_tags (JSON array, falls back to default seed list on parse error) and emotional_weight.user_holder. Empty affectedSlugs short-circuits with zero-work success. dry-run reports the would-write count without touching the DB. Engine throw bubbles into status: 'fail' with code RECOMPUTE_EMOTIONAL_WEIGHT_FAIL so the cycle continues.

  • src/core/cycle/phase-containment.ts — timeContainedPhase is the timer every runCycle phase runs under: a phase runner that throws returns a fail phase result carrying { class, code, message } and details.contained, so later phases in the job still run while the report stays partial/failed (global freshness is not stamped; gbrain dream exits non-zero). Cancellation (an aborted cycle signal or AbortError), LockStolenError and BudgetExhausted are never contained. Successful gateway.chat calls inside the phase are counted through withChatCallMeter (ai/chat-usage.ts); a contained failure after at least one paid call is recorded under dream:phase:<phase>:<source> for dream_paid_loop. Tests: test/cycle-phase-containment.test.ts. Each phase also runs under withAIAttribution({ phase: 'cycle:<phase>' }), so model calls it makes carry the phase in invocation observers and GBRAIN_AI_CALL_LOG.

  • src/core/cycle/fence-repair.ts — the fence_repair maintenance phase: runFenceRepairPhase(engine, { dryRun, signal?, deadlineAtMs?, registry?, now? }) runs the fences repair kind (src/core/repair/fences.ts) once through the trusted repairRunner (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 as host_mismatch, owner_unavailable as the fallback) and the candidates a running sync still names (sync_in_progress; the rest of a syncing source is repaired), reads fences.repair.llm and the daily USD ledger, and re-plans on the next run. fences.repair.enabled false skips it without calling the kind (the summary names gbrain 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 it runRepair stops before the next item with time_budget (status ok, resumed by the next run). Details read the kind's FenceRepairVerification: 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 reports warn with the kind's fix; an internal error reports warn with its code only (no message, which could carry fence content) unless the cycle is aborted. Brain-global, after sync in ALL_PHASES, classified writes. Test: test/cycle-fence-repair.test.ts.

  • src/core/cycle/content-repair.ts — the content_repair maintenance phase (#6377): runContentRepairPhase(engine, { dryRun, signal?, deadlineAtMs?, kinds?, registry?, now? }) runs the content-repair lane (src/core/repair/content-lane.ts) minus fences, which fence_repair just ran (contentRepairPhaseKinds(); with CONTENT_REPAIR_KINDS holding only fences the phase runs nothing and reports skipped / no_kinds), through the shared trusted repairRunner over every active source: an apply, or a preview on a dry run. Gated on fences.repair.enabled (one switch for the whole lane; the summary names gbrain config set fences.repair.enabled true and gbrain 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 stops time_budget (status ok, the next run resumes). Details: kinds, candidates, repaired, held_by_reason (each kind's remaining, 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 at gbrain sync status. Any stop other than the time budget reports warn with the kind's fix; an internal error reports warn with its code only unless the cycle is aborted. Brain-global, right after fence_repair in ALL_PHASES, classified writes. Test: test/cycle-content-repair.test.ts.

  • src/core/cycle/unindexed-files.ts — the unindexed_files maintenance phase (#6865, global, right after content_repair through the REPAIR_LANE_PHASES dispatch 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 is warn and the others still run, and details.complete is 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. Classified no_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_TABLE classifies every ALL_PHASES entry for managed brains as writes (publishes through the coordinator), no_coordinated_write (derived projections, side tables, audit-only) or managed_skip, each with its reason; isManagedBrain is what runPhaseLint uses to report issues without rewriting managed canonical files. The managed phase matrix test fails for an unclassified phase. Each entry has a tier that upkeep's step list is checked against.