Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
chore(wave11-w5): size ratchets, generated manifests and helper extraction for W5 items
garrytan3b68f9007447
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.mdindex 02aaa001c3..5ed19b80b1 100644--- a/docs/architecture/key-files/agent-bootstrap-continued.md+++ b/docs/architecture/key-files/agent-bootstrap-continued.md@@ -21,7 +21,7 @@- Diagnostics: `src/commands/doctor/checks/memory-writeback.ts` (`memory_writeback`, BRAIN category) — quiet-ok when off, but the OFF branch still probes receipt + canonical instruction paths and WARNS on a lingering block (off-but-still-instructing) with the converge command; plane-compare warns when the file mirror disagrees with the DB row (the Stop hook acting on the wrong truth) naming the re-sync; a read_error reports the state as UNKNOWN, never "off (default)"; resolved bundle + BOTH visibility postures + audience/reasons; on both branches an explicit private `facts.default_visibility` on a non-shared brain with remote readers (a harness receipt, or HTTP MCP clients active in 30d; listed in `private_default_remote_readers`) warns with the shared `PRIVATE_DEFAULT_REMOTE_CONSEQUENCE` text (`writeback-config.ts`), the same text `bootstrap harness` prints before consent; instruction blocks receipt-vs-live-probe-vs-drift compare (drift fix names the `config set` + `bootstrap harness` combo — the config set re-stamps the posture mirror so the re-render converges even after an out-of-band visibility flip) + AGENTS.override.md detection — and a receipt target in state `failed` is a STANDING warn regardless of the live probe (the one physical-survival path — a smoke-rollback strip that itself threw — leaves a current-looking block directing sessions at a rolled-back endpoint, and only the receipt state knows) naming the `bootstrap harness --yes` / `--remove` converge; validity-lapsed count; 7d counters (verbs usage sidecar's additive `remember_status` [stamped in `src/mcp/dispatch.ts`, ALL-MCP-callers semantics labeled honestly] + `writeback`/`writeback-bank` heartbeat events; `turns_banked` counts flush_skip_* — banked, enqueue declined); when at least 10 serve-side harvests finished (ok + error; a `writer_busy_requeued` retry is not finished) in those 7d and more than 20% failed, a warn names the failure count, the top error reason and the `gbrain sweep --once` recovery; `details.corpus_backlog` counts corpus files with no `.ingested` sidecar (pending, oldest age, past retention, deletion day) and, with writeback on, warns once one is past plain retention (E-N1) with the local/lossy disclosure. Null-engine runs report the file mirror honestly. `cross_lane_duplicates_7d` / `near_duplicates_shadow_7d` sum the `writeback_dedup` heartbeat events in both the on and off branches.- Tests: `test/writeback-config.test.ts`, `test/mcp-instructions-writeback.test.ts`, `test/facts/writeback-gate.test.ts`, `test/hook-writeback-stop.serial.test.ts`, writeback-lane cases in `test/checkpoint-harvest.serial.test.ts`, `test/bootstrap-instructions-block.test.ts` + harness serial additions, `test/writeback-nudge.serial.test.ts`, `test/doctor-memory-writeback.test.ts`, the hermetic 5-step `test/ambient-writeback-lifecycle.serial.test.ts`, and the NON-GATING real-codex door (`test/e2e/bootstrap-real-codex.serial.test.ts`, ambient-writeback describe).- `src/core/sweep.ts` + `src/commands/sweep.ts` — the serve-resident maintenance sweep (the lock owner closes the persistence loop): facts-fence reconciliation (zero-LLM, reuses the cycle extractor with a slug subset), deterministic link/timeline extraction over recent workspace pages (the same cores as `gbrain extract` — remote put_page deliberately skips these, the sweep is where the graph compounds), and spend-gated corpus ingest (skipped keyless; turn-boundary windows through `src/core/context/corpus-windows.ts`, at most `CORPUS_WINDOWS_PER_SWEEP` (8) per file and `CORPUS_WINDOWS_PER_SWEEP_TOTAL` (32, env `GBRAIN_CORPUS_WINDOWS_PER_SWEEP`) per sweep, each windowed file reported in `corpus_files[]` as `{file, windows_done, windows_remaining}`; `.ingested` is written when the last window of the current snapshot finishes, and a finished file re-enters when its stat no longer matches its `.progress`; writeback `.wb-` turn files stay one call; dream outputs and claude-cli self-captures classified by `isClaudeCliSelfSessionId` get a terminal `.ingested` sidecar with `skipped: dream_output` / `self_capture` (the shared `selfCaptureSidecarJson` writer) and are never extracted; the extractor input is `corpusTextForExtraction`, so pasted blocks never reach it). Bounded, fail-soft, never throws; the wall-clock budget stops the corpus pass between files and windows, never mid-extraction (an in-flight extraction finishes and writes its sidecar, E-N2, pinned by `test/sweep-budget-between-items.test.ts`); armed at serve startup (3s, best-effort) and on 10-min idle ticks through the injectable timer seam, everything unref'd; `serve --http` arms `armCorpusDrain` instead (X8: every `CORPUS_DRAIN_INTERVAL_MS`, 10 min, one sweep on a `CORPUS_DRAIN_BUDGET_MS` 60 s budget while a corpus `.txt` has no `.ingested` sidecar; never overlaps itself; pinned by `test/serve-http-corpus-drain.test.ts`); `GBRAIN_SWEEP=0` kills both. `gbrain sweep --once` is the trusted CLI seam `bootstrap verify` uses (CLI-only, never over MCP). The link pass threads the same `link_resolution.cross_source` opt-in and configured `sources.default` the CLI extract lanes pass into `resolveCandidateSources`, so an edge into another source is created (flag on) or counted as `cross_source_link` in `skipped` (flag off) — never silently dropped, and the reconcile never deletes a cross-source edge `extract links --source db` created. A corpus window's facts batch is keyed by its text (the sweep passes `reAdmitFileRefusals`), so when the canonical file check refused some of its entity requests, `resumeManagedFacts` admits their retained facts as a follow-up batch once every refused page passes that check again: no new extraction, the page's current revision, never wider than the current default visibility, committed requests reported rather than re-admitted, the stored and current writer grants re-checked, at most three follow-ups. Pinned by `test/managed-sweep-refused-window-retry.test.ts`.-- `src/core/context/corpus-windows.ts` — windowed fact extraction of session-corpus files (#5887). `parseCorpusTurns` splits only at the exact `\n\n[user]\n` / `\n\n[assistant]\n` markers `toCorpusText` emits (text before the first marker is a header-less preamble); each user turn is paste-stripped whole before windowing; `planCorpusWindows` packs whole turns into windows of at most `MAX_TURN_TEXT_CHARS` (exported from `facts/extract.ts`) and splits a turn that cannot fit a fresh window at a newline or space, never inside a surrogate pair, repeating its `[role]` header on every piece. `<file>.progress` (suffix constants in `corpus-segments.ts`, GC'd by the session-end hook with the `.txt`, never deleted by its resume rewrite) holds `{version, generation, turns[{start,end,sha256}], continuation{turn_sha256, stripped_offset}|null, windows_done, finished(stat)|null, totals, entity_slugs, skipped_reason?, lease}`: `resumePoint` resumes at the first turn whose hash is unrecorded (appends, compaction remainders and same-size or shorter rewrites cost only their new turns). Every write is compare-and-set under the O_EXCL `<file>.progress.lock` (stale after 30 s): a window commits only when generation, last turn hash and lease owner still match and progress grows; the lease (stale after an hour, like the claim) stops a sweep whose `.in-progress` claim the hook deleted from extracting a window another extractor holds. `runCorpusWindows` returns `complete`/`partial`/`aborted`/`contended` with cumulative counts; an aborted window records nothing and transport errors release the lease and throw. `finishedCorpusFileState` decides `.ingested` files by stat compare (no rehash); `adoptFinishedCorpusFile` records a pre-window `.ingested` file at its current turns once (only when the sidecar is newer than the file). `checkpoint-harvest.ts` (`hook:compact`) extracts window 1 only: when more remains it publishes window 1's links, releases the receipt and leaves `.progress` for the sweep; an existing `.progress` means window 1 is done. `corpusFactTime(mtimeMs)` (#6159) validates the session file's write time (finite, from 2000, at most 60 s ahead); the sweep passes it as the facts pipeline's `turnAt`, which `facts/event-time.ts` `factEventTime` uses after the extractor's date and `validFrom`, so corpus facts are dated when the session was written and the observation date says so; `turnAt` stays out of the managed batch key, and a rejected time logs why and dates facts at extraction. Pinned by `test/corpus-windows.test.ts`, `test/sweep-corpus-windows.test.ts`, `test/sweep-corpus-fact-time.test.ts` and `test/managed-sweep-corpus-windows.test.ts` (managed coordinator, PGLite and Postgres).+- `src/core/context/corpus-windows.ts` — windowed fact extraction of session-corpus files (#5887). `parseCorpusTurns` splits only at the exact `\n\n[user]\n` / `\n\n[assistant]\n` markers `toCorpusText` emits (text before the first marker is a header-less preamble); each user turn is paste-stripped whole before windowing; `planCorpusWindows` packs whole turns into windows of at most `MAX_TURN_TEXT_CHARS` (exported from `facts/extract.ts`) and splits a turn that cannot fit a fresh window at a newline or space, never inside a surrogate pair, repeating its `[role]` header on every piece. `<file>.progress` (suffix constants in `corpus-segments.ts`, GC'd by the session-end hook with the `.txt`, never deleted by its resume rewrite) holds `{version, generation, turns[{start,end,sha256}], continuation{turn_sha256, stripped_offset}|null, windows_done, finished(stat)|null, totals, entity_slugs, skipped_reason?, lease}`: `resumePoint` resumes at the first turn whose hash is unrecorded (appends, compaction remainders and same-size or shorter rewrites cost only their new turns). Every write is compare-and-set under the O_EXCL `<file>.progress.lock` (stale after 30 s): a window commits only when generation, last turn hash and lease owner still match and progress grows; the lease (stale after an hour, like the claim) stops a sweep whose `.in-progress` claim the hook deleted from extracting a window another extractor holds. `runCorpusWindows` returns `complete`/`partial`/`aborted`/`contended` with cumulative counts; an aborted window records nothing and transport errors release the lease and throw. `finishedCorpusFileState` decides `.ingested` files by stat compare (no rehash); `adoptFinishedCorpusFile` records a pre-window `.ingested` file at its current turns once (only when the sidecar is newer than the file). `checkpoint-harvest.ts` (`hook:compact`) extracts window 1 only: when more remains it publishes window 1's links, releases the receipt and leaves `.progress` for the sweep; an existing `.progress` means window 1 is done. Pinned by `test/corpus-windows.test.ts`, `test/sweep-corpus-windows.test.ts` and `test/managed-sweep-corpus-windows.test.ts` (managed coordinator, PGLite and Postgres).- `src/core/context/sync-ipc.ts` + `src/core/serve-sync-runner.ts` + `src/commands/sync-delegate.ts` — serve-delegated sync. `sync-ipc.ts` is the LEAF wire module: the `DELEGATED_SYNC_OPTION_FIELDS` table is the single source of truth for the validator, the CLI wire-builder, and the serve-side SyncOpts builder; `validateDelegatedSyncOptions` rejects unknown keys fail-closed (repoPath/skipLock/lockId/concurrency are unreachable from the socket), requires `timeoutSeconds` (0 = the explicit `--no-hard-deadline` unbounded encoding; everything else clamps to 24h), and `toWireSyncResult` truncates `pagesAffected` to 50 + a true total under the 256KB message cap. `serve-sync-runner.ts` is the serve-side module singleton: one job at a time (correctness still rests on the `gbrain-sync:<source>` row lock inside performSync), clientToken attach (a lost-ack retry finds its own running OR retained-terminal job instead of duplicate-running), per-job deadline timer, `[serve-sync]` lifecycle stderr lines, an idempotent shared `shutdownDelegatedSync()` both serve shutdown paths await BEFORE `engine.disconnect()` (the disconnect-mode drain is allowAbort:false after `_db` is nulled, so settle writes need the live engine; a registered drainer remains as backstop), and `maybeDrainDeferredEmbeds` (delegated jobs always run noEmbed — the cost gate lives in runSync — and the serve drains stale embeds afterwards via `runEmbedCore`, keyless-safe, cleared only when a drain finds nothing left; wire `noEmbed` records that the USER declined embeds and suppresses the drain). `sync-delegate.ts` is the CLI half: read-only holder probe (`probeLivePgliteHolder`), DEFAULT-DENY argv gate (any unclassified token refuses by name — a silently dropped `--exclude` would perform the wrong sync), engine-free source tiers (`resolveSourceIdEngineFree`), 1s poll loop tolerant of event-loop-blocked serves with a PID-probe backstop, `unknown_job` → serve-restarted resume hint, Ctrl-C → `sync_abort` (second Ctrl-C exits 130), and runSync's `pull_failed` verdict mirroring. Mounts and non-PGLite configs never delegate; opt-outs `--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve). Pinned by `test/context/sync-ipc-validation.test.ts`, `test/sync-delegate-ladder.test.ts`, `test/serve-sync-runner.serial.test.ts`, `test/context/resolve-ipc-sync-kinds.test.ts`, and `test/e2e/sync-delegation-under-serve.serial.test.ts` (gating tier1 step).- `src/core/capability.ts` — config-plane keyless/keyed detection + the honest capability report (per-provider keyless banner: OpenAI = semantic search + auto-extraction, Voyage = semantic search, Anthropic = auto-extraction) rendered by verify and the runbook. The extraction probe resolves through the SAME shared `resolveEffectiveChatModel` the gateway's reconfigure fallback uses (`GBRAIN_MODEL` > servable file pin > key-aware tier default), so a stale unservable pin degrades identically in the report and at runtime. Key/env fold comes from `mergedProviderEnv` (`src/core/ai/provider-env.ts`). Accepted limitation (documented in the module): DB-plane overrides (`models.default`, `facts.extraction_model`) are invisible to this engine-less probe; the runtime gate in `facts/extract.ts` and the engine-aware pre-enqueue gate in `facts/backstop.ts` are the backstops.- `src/core/readiness.ts` — capability readiness (agent operator contract A7): `ReadinessEntry {capability, state, reason, why, fix, tier, asset?, http_visible}` for embeddings, chat_llm, writeback, tool_surface, sync, harness_wiring (config tier) and worker, backup per asset, migrations, sync (probed tier); each capability's reasons are a closed exported const (`EMBEDDINGS_REASONS`, …). `configReadiness(cfg, {transport})` is synchronous and memoized per (config object, transport); its only file read is one memoized `peekLock()` (none when this process holds the lock, via `heldLockFor`), plus one process-wide gbrain-binary PATH lookup on the CLI transport only. The HTTP view drops `http_visible:false` entries and passes the rest through `redactForTransport`. `probedReadiness(engine, {cache})` never calls `getStats`/`getHealth`; 60 s cache (`createReadinessCache()` per ServeHttpContext, process-wide otherwise), single-flight, 2 s per-probe bound, stale-while-revalidate; `readinessTail` is MCP initialize's best-effort 250 ms tail. `embeddingEnablement(cfg)` is the one "turn on embeddings" fix: resolves the datastore (PGLite path, Postgres, a mount from `--brain`/`GBRAIN_BRAIN_ID`) and the column width, picks a keyed provider that fits (or asks for a key with `inputs`), and emits in-place `init --force --embedding-model … --embedding-dimensions … [--path …]` or, for a mount, `embeddings enable --brain …`; it never rebuilds a column. `exclusiveFix` turns an exclusive fix into a two-step plan (actor `user` stops the owning serve named by `lock_owner`, `then` the command) unless the command delegates to the owner. A live status-only `serve --http` marker (`liveStatusMarkers`, config plane) makes CLI `harness_wiring` `serve_status_only` with `transport: 'http'` and the status reason's fix (`httpStatusServerEntry`, shared with doctor), never "start `gbrain serve --http`" on the port it holds. `harnessWiringEntry` builds harness-native stdio registration (absolute binary, `stdioServeArgv` with `REGISTRATION_SURFACE` = `starter`, or `input.surface` from `gbrain init --surface`; `configReadiness(cfg, {transport, surface})` skips the memo when a surface is passed), shared-HTTP `bootstrap harness`, or the MEMORY_VERBS install anchor, with effects and destinations disclosed. Consumers never coach on `disabled_by_choice`. Tests: `test/readiness.test.ts`, `test/readiness-http-cost.test.ts`, `test/readiness-advice-lint.test.ts` (no hand-written enablement advice outside this module; shrink-only baseline), `test/readiness-embedding-enablement.serial.test.ts` (the E2E matrix).diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex a54247f703..5e6baae8e9 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/commands/frontmatter.ts` — `gbrain frontmatter validate|generate|audit|install-hook`. `validate` keeps the producer rule: exit 1 on any `parseMarkdown` validation error, including `YAML_PARSE` that ingestion recovers by quoting (those print "importable but not canonical" with the `--fix` command). `--importable` switches to the ingestion view through `screenImportContent` (exit 1 only for a hold). Inputs: a file or directory, `--stdin`/`-` (with optional `--path <source-relative path>` for the slug check, otherwise reported skipped), or `--staged [paths]` (git index blobs via one `ls-files --stage` and one `cat-file --batch`; a failing blob whose working copy passes says to `git add` it). `--fix` runs `autoFixFrontmatter` then `repairRecoverableFrontmatter` (`brain-writer.ts`: safe `quote` recoveries line by line, CRLF/BOM kept, gated on the strict parse equalling what ingestion read; `--include-ambiguous` adds fold/dup/unclosed proposals and `#`-title quoting), re-validates and exits 1 if errors remain, prints the restage step inside git, and refuses on a managed root with `writer_coordinator_required` whose fix is `gbrain repair frontmatter [--source <id>]`. `audit --json` adds `recoverability_by_code` (imported anyway vs held on import). `runFrontmatter(args, io)` takes stdin-stream and git-cwd test seams. Pinned by `test/frontmatter-cli.test.ts` and `test/frontmatter-validate-producer.test.ts`.+- `src/commands/frontmatter.ts` — `gbrain frontmatter validate|generate|audit|install-hook`. `validate` keeps the producer rule: exit 1 on any `parseMarkdown` validation error, including `YAML_PARSE` that ingestion recovers by quoting (those print "importable but not canonical" with the `--fix` command). `--importable` switches to the ingestion view through `screenImportContent` (exit 1 only for a hold). Inputs: a file or directory, `--stdin`/`-` (with optional `--path <source-relative path>` for the slug check, otherwise reported skipped), or `--staged [paths]` (git index blobs via one `ls-files --stage` and one `cat-file --batch`; a failing blob whose working copy passes says to `git add` it). `--fix` runs `autoFixFrontmatter` then `repairRecoverableFrontmatter` (`brain-writer.ts`: safe `quote` recoveries line by line, CRLF/BOM kept, gated on the strict parse equalling what ingestion read; `--include-ambiguous` adds fold/dup/unclosed proposals and `#`-title quoting), re-validates and exits 1 if errors remain, prints the restage step inside git, and refuses on a managed root with `writer_coordinator_required` whose fix is `gbrain repair frontmatter [--source <id>]`. `audit --json` adds `recoverability_by_code` (imported anyway vs held on import). `runFrontmatter(args, io)` takes stdin-stream and git-cwd test seams. Pinned by `test/frontmatter-cli.test.ts` and `test/frontmatter-validate-producer.test.ts`. #6157: `parseMarkdown` (`markdown.ts` `yamlBlockError`) runs the per-line NESTED_QUOTES heuristic only when the whole block fails to parse, and `brain-writer.ts` `autoFixFrontmatter` skips the NESTED_QUOTES rewrite on a parseable block and keeps a tags/aliases re-quote only when the line reads back as the same value, so `validate`, `--fix`, `lint` and `repair frontmatter` never flag or rewrite valid YAML.- `src/commands/graph-query.ts` — `gbrain graph-query <slug> [--type T] [--depth N] [--direction in|out|both] [--source <id>] [--include-foreign]`: typed-edge relationship traversal (renders indented tree). The local walk is scoped to the resolved source (`--source` / `GBRAIN_SOURCE` / `.gbrain-source` / path match / brain default via `resolveSourceId`, the same scalar scope the `traverse_graph` op gets from `sourceScopeOpts`); an explicit `--source` that fails to resolve throws. `--include-foreign` (or `--source __all__`) drops the scope so the walk spans every source. The foreign-edge footer (`N edges to foreign-source pages hidden; pass --include-foreign`) prints only when the walk was actually scoped, so cross-source edges never disappear silently and the footer never describes a filter that did not apply. The local path uses `engine.traversePathsDetailed` and prints a stderr note when the walk hit `TRAVERSE_PATH_ROW_CAP` (shallowest edges kept; lower `--depth` or narrow with `--type`/`--direction`); the thin-client path goes through the `traverse_graph` op, which has no `source_id` param (the server scopes the walk to the caller's grant): an explicit `--source` there is rejected with exit 1 (same policy + wording as `applyThinClientSourceScope`, never silently dropped) and `--include-foreign` prints a stderr note that it is not forwarded. `--hop <link_type>:<object|subject>` (repeatable, 1-3) runs a typed chain through `runRelationalChain` locally or `traverse_graph` `hops` on a thin client; it is refused with `--type`/`--depth`/`--direction`, a malformed hop names the fix, and a host that ignored `hops` (older gbrain, detected via `ignoredRemoteParams` or a non-chain response) is refused with the upgrade message. Pinned by `test/graph-query.test.ts` (local) + `test/graph-query-thin-client-source-flag.serial.test.ts` (thin client; mocks `isThinClient` + `callRemoteTool`).diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.mdindex afbb7258d3..2f9d213d10 100644--- a/docs/architecture/key-files/files-and-sync-1.md+++ b/docs/architecture/key-files/files-and-sync-1.md@@ -33,7 +33,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/link-source-check-repair.ts` — schema-drift self-heal for the `links_link_source_check` CHECK constraint (third instance of the `timeline-dedup-repair.ts` / `pages-upsert-arbiter.ts` class). Migration v114 opened `link_source` from a closed allowlist to the kebab-case gate; the migrator trusts the version ledger, so a brain stamped >= 114 whose live constraint reverted to the pre-v114 allowlist (drifted restore, manual DDL) rejects every kebab provenance write (`atom-provenance`, `concept-provenance`) while the ledger reads current. `LINK_SOURCE_KEBAB_RE` is the ONE exported copy of the regex (a drift-guard test pins it to the literal in migrate.ts v114, `schema.sql`, `pglite-schema.ts`). `checkLinkSourceCheck(engine)` probes `pg_constraint` (`pg_get_constraintdef` + `convalidated`) and classifies the drift as `absent` / `wrong_def` / `not_validated` (read-only; powers the `links_link_source_check` doctor check in `doctor/checks/core-health.ts`, whose severity follows what writes do: only `wrong_def` rejects kebab writes → fail; `absent` / `not_validated` still accept them → warn). `repairLinkSourceCheck(engine)` first COUNTs rows that fail the gate and returns `reason: 'violations'` WITHOUT any DDL when there are any (the prior constraint survives; rows are never touched; a brain with a bad row never pays for a failing ALTER at every engine open), then restores v114's definition mirroring the migration's engine split: Postgres runs DROP + `ADD ... NOT VALID` in one `engine.transaction` (atomic, no scan) and `VALIDATE CONSTRAINT` as a separate `engine.runMigration` outside it (SHARE UPDATE EXCLUSIVE, never a plain ADD's ACCESS EXCLUSIVE + full-table scan), with a `not_validated` drift getting the VALIDATE only; PGLite keeps the one-shot DROP+ADD transaction. A DDL failure re-counts violators (a row written between probe and ALTER) and rethrows when there are none. `LINK_SOURCE_GATE_MIGRATION_VERSION` (114) is the ledger gate `runMigrations` applies before calling it. Pinned by `test/link-source-check-repair.test.ts` (PGLite, incl. a recording-engine assertion that violators trigger no DDL and that a sub-114 ledger never probes) and the DATABASE_URL-gated `test/e2e/link-source-check-repair-postgres.test.ts` (two-phase DDL sequence on real Postgres).-- `src/core/markdown.ts` — Frontmatter parsing + body splitter. `coerceFrontmatterString(v)` coerces a non-string `title`/`slug`/`type` to a deterministic string at parse time so a YAML-typed value never reaches `.toLowerCase()` and throws (`title: 2024-06-01` parses as a `Date`, `title: 1458` as a number, and a throw would block the sync bookmark from advancing); a `Date` becomes its UTC ISO date (`2024-06-01`, machine-independent and matching the on-disk token, unlike `String(date)`), `null`/`undefined` become `''`, everything else uses `String()`. `splitBody` requires an explicit timeline sentinel (`<!-- timeline -->`, `--- timeline ---`, or `---` immediately before `## Timeline`/`## History`). Plain `---` in body text is a markdown horizontal rule, not a separator. `inferType` auto-types `/wiki/analysis/` → analysis, `/wiki/guides/` → guide, `/wiki/hardware/` → hardware, `/wiki/architecture/` → architecture, `/writing/` → writing (plus existing people/companies/deals/etc heuristics). `resolveSourceLocalFilePath` maps Git-root-relative `pages.source_path` values into a source whose `local_path` scopes a repo subdirectory; it finds the Git root with filesystem checks only, strips the exact root-relative scope, rejects unsafe/non-markdown paths, and when given a slug it tolerates historical basename-relative `source_path` rows by checking the slug directory only after the direct path is absent. It leaves write containment to the caller. After its pre-quote pass, a block the strict parse refuses goes to `recoverFrontmatter`; only `quote` recoveries are applied. Under `validate`, YAML_PARSE stays in `errors` (location-only message, `recoverable` plus a content-free `recovery` record), advisories go to `warnings` (`FRONTMATTER_RECOVERED`, `FRONTMATTER_COMMENT_VALUE`), and `recovery` carries interpretive, protected-key and identity-key findings. `HOLD_CODES` and `classifyImportHold(parsed, ctx)` define the ingestion hold set once; `isFrontmatterHoldMessage` recognizes its exact messages. `yamlBlockError(block)` parses a whole frontmatter block once; the per-line NESTED_QUOTES heuristic runs only when it fails, and `autoFixFrontmatter` (brain-writer.ts) uses it to skip the NESTED_QUOTES rewrite and keeps a tags/aliases re-quote only when the line reads back as the same value, so valid YAML is never rewritten (#6157). Tests: `test/frontmatter-recovery.test.ts`, `test/markdown-validation.test.ts`, `test/brain-writer.test.ts`.+- `src/core/markdown.ts` — Frontmatter parsing + body splitter. `coerceFrontmatterString(v)` coerces a non-string `title`/`slug`/`type` to a deterministic string at parse time so a YAML-typed value never reaches `.toLowerCase()` and throws (`title: 2024-06-01` parses as a `Date`, `title: 1458` as a number, and a throw would block the sync bookmark from advancing); a `Date` becomes its UTC ISO date (`2024-06-01`, machine-independent and matching the on-disk token, unlike `String(date)`), `null`/`undefined` become `''`, everything else uses `String()`. `splitBody` requires an explicit timeline sentinel (`<!-- timeline -->`, `--- timeline ---`, or `---` immediately before `## Timeline`/`## History`). Plain `---` in body text is a markdown horizontal rule, not a separator. `inferType` auto-types `/wiki/analysis/` → analysis, `/wiki/guides/` → guide, `/wiki/hardware/` → hardware, `/wiki/architecture/` → architecture, `/writing/` → writing (plus existing people/companies/deals/etc heuristics). `resolveSourceLocalFilePath` maps Git-root-relative `pages.source_path` values into a source whose `local_path` scopes a repo subdirectory; it finds the Git root with filesystem checks only, strips the exact root-relative scope, rejects unsafe/non-markdown paths, and when given a slug it tolerates historical basename-relative `source_path` rows by checking the slug directory only after the direct path is absent. It leaves write containment to the caller. After its pre-quote pass, a block the strict parse refuses goes to `recoverFrontmatter`; only `quote` recoveries are applied. Under `validate`, YAML_PARSE stays in `errors` (location-only message, `recoverable` plus a content-free `recovery` record), advisories go to `warnings` (`FRONTMATTER_RECOVERED`, `FRONTMATTER_COMMENT_VALUE`), and `recovery` carries interpretive, protected-key and identity-key findings. `HOLD_CODES` and `classifyImportHold(parsed, ctx)` define the ingestion hold set once; `isFrontmatterHoldMessage` recognizes its exact messages. Tests: `test/frontmatter-recovery.test.ts`.- `src/core/quarantine.ts` — the two frontmatter markers the content-quality gate writes, sibling of `src/core/embed-skip.ts` (same marker-as-JSONB-object pattern, same JSONB `?` existence check that works on Postgres AND PGLite; no schema migration — both are frontmatter JSONB keys). `quarantine` (key `QUARANTINE_KEY`) HIDES: set ONLY for high-confidence junk, writes zero chunks, excluded from search via `quarantineFilterFragment(pageAlias)` / `QUARANTINE_FILTER_FRAGMENT` (the `p`-aliased constant), the single source of truth `buildVisibilityClause` calls so the search filter and marker key can't drift. `content_flag` (key `CONTENT_FLAG_KEY`) WARNS, does NOT hide: set for fuzzy markup-heavy / oversize, page stays searchable, marker is READ INTO search/get_page output — deliberately NO SQL filter fragment. Three distinct markers, three reasons (never overloaded): `embed_skip` = oversized-but-clean, `quarantine` = junk hidden, `content_flag` = odd-examine-still-here; a page can carry more than one (oversize → embed_skip + content_flag:oversized) and each clears independently. Exports `buildQuarantineMarker` / `isQuarantined` / `filterOutQuarantined`, `buildContentFlagMarker` / `getContentFlag` / `hasContentFlag`, plus the two key constants. Pinned by `test/quarantine.test.ts`. A quarantined page is skipped by every derived-data scan (stale listing via the engine-sql stale predicate, NER, meeting timeline projection, file walks via `quarantinedSlugs`, DB walks, the managed link derivation) and is not in the `links_extraction_lag` denominator. Pinned by `test/quarantine-extraction.test.ts`.diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex be9c9f1b4f..01461e078f 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -29,7 +29,7 @@- `src/core/facts/withdrawal-overlay.ts` — pure legacy-fence enumeration and withdrawal rendering shared by coherent snapshots, stale imports and physical forget mirrors. The shared snapshot overlay and import pre-publication validator recognize canonical prefixed/inline markers and distinguish malformed live segments. Discovery refuses matching ambiguous claims before mutation. Fingerprints match independently in each fence, including inactive history, against both the folded (v174) and exact legacy hashes; parser-recognized markers precede preserved evidence context and earlier expiry remains intact. Regression: `test/withdrawal-overlay-concurrency.test.ts` on both engines.- **`src/commands/sync-persistence-delegate.ts` + `src/core/persistence/{sync-wire,sync-administration}.ts`** — pre-connect authenticated CLI sync ingress for any resident PGLite owner, including stdio MCP. The CLI JSON renderer shares the direct sync envelope. Strict options preserve source/brain selection and filtering; only current CLI credentials can advance bounded durable cursor slices. Unactivated delegation also forces import-only work and queues the owner embed drain, preserving the inline cost gate; backlogs are per-engine source sets and shutdown waits for actual provider settlement before releasing datastore ownership; the real serve E2E observes a committed receipt before SIGKILL and proves same-ID cursor recovery without breaking locks. The env and default deadlines stay progress-aware across slices (`DelegatedSyncDeadline`): past the deadline the client keeps re-entering while a slice advanced the managed cursor within one progress window, and each slice gets at least one window; `--timeout` and `--hard-deadline` stay strict. Legacy shared-secret sync refuses managed brains. `test/persistence-sync-stdio-owner.test.ts` starts a real stdio owner and exercises CLI import/read/admin, remote-lane denial and revocation without a competing datastore open.-- `src/core/facts/backstop.ts` + `src/core/entities/resolve-on-save.ts` — saved facts retain their content and provenance but use a NULL entity target when resolution falls back to slugification. Legacy extraction uses the shared exact source/entity/visibility fingerprint decision before identity-gated cosine candidates, so old facts without vector provenance still deduplicate identical text without relabeling their vectors. The conversation save caller also clears the target on ordinary resolution errors, preserves diagnostic counters, and propagates abort/budget failures. It never treats an invented slug as a verified page. #5836: `src/core/facts/subject-infer-write.ts` `inferMissingSubjects` links facts with no or fallback-only entity via `inferFactSubject` (remote callers: written page only, readable pages, caller fences, managed grant), never on the unmanaged DB-only branch, marks `entity_inferred` (context note; exact-text dedup only in both writers); `test/facts-backstop-entity-inference.test.ts`, `test/managed-facts-entity-inference.test.ts`. #6159: every writer (both backstop buckets, the fence writes and `persistence/facts-maintenance.ts`) dates a fact with `facts/event-time.ts` `factEventTime` (extractor date, then `validFrom`, then `turnAt`, then now) and the extraction prompt's observation date falls back to `turnAt`.+- `src/core/facts/backstop.ts` + `src/core/entities/resolve-on-save.ts` — saved facts retain their content and provenance but use a NULL entity target when resolution falls back to slugification. Legacy extraction uses the shared exact source/entity/visibility fingerprint decision before identity-gated cosine candidates, so old facts without vector provenance still deduplicate identical text without relabeling their vectors. The conversation save caller also clears the target on ordinary resolution errors, preserves diagnostic counters, and propagates abort/budget failures. It never treats an invented slug as a verified page. #5836: `src/core/facts/subject-infer-write.ts` `inferMissingSubjects` links facts with no or fallback-only entity via `inferFactSubject` (remote callers: written page only, readable pages, caller fences, managed grant), never on the unmanaged DB-only branch, marks `entity_inferred` (context note; exact-text dedup only in both writers); `test/facts-backstop-entity-inference.test.ts`, `test/managed-facts-entity-inference.test.ts`. #6159: every writer (both backstop buckets, the fence writes and `persistence/facts-maintenance.ts`) dates a fact with `facts/event-time.ts` `factEventTime` (extractor date, then `validFrom`, then `turnAt`, then now) and the extraction prompt's observation date falls back to `turnAt`; the sweep's corpus pass sets `turnAt` from the session file's write time, vetted by `context/corpus-windows.ts` `corpusFactTime` (finite, from 2000, at most 60 s ahead; otherwise logged and dated at extraction) (`test/sweep-corpus-fact-time.test.ts`).- `src/commands/migrations/v0_32_2.ts` + `src/core/facts/unfenced-facts.ts` — Phase B is the shared core pass `planUnfencedFacts` / `fenceUnfencedFacts`, which the `extract_facts` cycle phase also runs on every cycle (#5299). It fences live unfenced facts (`row_num IS NULL`) only onto an existing source-scoped page and its recorded canonical file; a managed brain publishes each page as one coordinator `managed_maintenance_adopt_fact_fence` request (database-only pages included), and an unmanaged page is written under the source filesystem lock and page lock (`.tmp` + parse + rename), mirrored into `pages` and stamped in one maintenance transaction, and committed when the checkout is durability-hardened. Missing pages/files are counted as `skipped_no_page` (missing files are also listed in `missing_files`), never materialized as stubs. The migration adds a dirty-tree refusal that stays inside the source subdirectory; fence row allocation respects both database-owned row numbers and the parsed fence, preserving idempotent recovery without collisions. Dry runs use the same eligibility checks, and historical drift remains visible rather than silently repaired.- `src/core/google/loop-catchup.ts` — open-loop recovery passes the Gmail sweep runs (#5867, #5868). Grace holds: `recordGraceVerdict` keeps each thread `detectThreadLoop` grace-held (and `loopExtractionEligibility` passes) in connector state `loop_grace_holds` (cap `GRACE_HOLDS_CAP` 2,000, oldest pruned and logged; prose sanitized for jsonb), separate from connector item holds, so `connector_held_items` and `waiting` coverage never count them. `settleDueGraceHolds` opens a due hold from its stored spec when the page still carries the newest message id it was computed from (no Gmail read), otherwise re-fetches through `processThread` (at most `GRACE_REFETCH_PER_SWEEP` 100 per sweep; a 404 drops the hold, a failure keeps it due). `seedGraceBackfill` seeds holds once for email pages active in the last 14 days with no open deterministic loop, from stored pages only; the sweep sets `loop_grace_backfill_done` after a non-aborted sweep. Catch-up (managed sources only): `runLoopsCatchup` re-candidates email pages whose newest message is in the last 30 days; a page is settled by a revision-bound outcome (`recordLoopsExtractOutcome`, written by the `loops_extract` handler into `op_checkpoints` op `loops-extract-outcomes`, one statement, pruned past the window), not by job completion. It skips pages this sweep or a pending sweep job already queues, checks eligibility on the live thread, enqueues under its own key `loops-catchup:<source>:<slug>:<rev>` inside the waiting-depth ceiling, retries a dead-lettered job once (`:retry`) then settles it, honors the kill switch and chat availability, and sets `loops_catchup.done` only when every candidate is settled. Tests: `test/google-loops-recovery.serial.test.ts` (+ Postgres twin).diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex a8dd5d4657..7605bb92c5 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -29,15 +29,15 @@ src/core/brainstorm/orchestrator.ts _runBrainstormInner 413 seed: W5 baseline, rsrc/core/check-resolvable.ts checkResolvable 419 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/config.ts loadConfigWithEngine 362 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5824: search.vector_legacy_guard DB-plane mergesrc/core/context-engine.ts createGBrainContextEngine 520 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #4618: seat sidecar call before the segment spool (helper recordOpenclawSeat)-src/core/context/retrieval-reflex.ts resolveEntitiesToPointers 355 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)+src/core/context/retrieval-reflex.ts resolveEntitiesToPointers 362 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +7 fix wave 11 #6195: multi-word weak n-gram norms and the weak-title arm call (logic in weakTitleHits)src/core/cycle.ts runCycle 1271 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 #5809: extract_atoms phase gets a real abort signal; +2 #5809: cycle_already_running names the lock holder; +1 #4578: a lock steal during the last selected phase reports lock_stolen (one phase per runCycle call); +4 GBRA-40 F4b: planner-stats refresh after the freshness phases; +14 #5876: Life Chronicle phase dispatch block; +6 GBRA-40 Lane D: facts_drain phase dispatch; +10 GBRA-49: edge_contradictions phase dispatch block (adapter in cycle/edge-contradictions.ts)src/core/cycle/extract-atoms.ts runPhaseExtractAtoms 790 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +12 #5809/#5832: hard/soft stop checks, chat-call signal, abortable pacing, no post-stop writes; +1 #5856: one BudgetTracker per drain attempt (reuse the attempt's tracker); +2 fix wave 9 lane P (#5041): opt-in write-through hook creation and its per-item call (derived-write-through.ts); +1 #5031: per-run page-atom title memo for the case-insensitive adoption fallbacksrc/core/cycle/extract-facts.ts runExtractFacts 505 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/cycle/grade-takes.ts GradeTakesPhase.process 402 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)-src/core/cycle/patterns.ts runPhasePatterns 303 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)+src/core/cycle/patterns.ts runPhasePatterns 310 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +7 fix wave 11 #6177: budget sizing call, submitted-reflection slice and the last_run record (logic in cycle/patterns-plan.ts)src/core/cycle/propose-takes.ts ProposeTakesPhase.process 429 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5958 (issue #5874): call_timeout_ms read and its per-page bound (phaseBoundedCallTimeout)-src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 473 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 #5490 review: a narrative a chat_fallback_chain model wrote is hashed under that model so the next cycle re-synthesizes it; +13 fix wave 9 lane P (D-N3): fence-stripped member hash with legacy-hash grandfathering, and the classic write moved to publishClassicConcept (concept-publication.ts); +3 (#5041): opt-in concept write-through hook and the import callback publishClassicConcept runs under the page lock; +6 #4907 (issue #4906): configured budget read, budget-capped counter, summary clause and details.warnings (message text in budgetWarnings)-src/core/cycle/synthesize.ts runPhaseSynthesizeInner 1046 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #5854: publish_pending from postprocess, a pending summary publish deferred instead of failing the phase+src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 477 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 #5490 review: a narrative a chat_fallback_chain model wrote is hashed under that model so the next cycle re-synthesizes it; +13 fix wave 9 lane P (D-N3): fence-stripped member hash with legacy-hash grandfathering, and the classic write moved to publishClassicConcept (concept-publication.ts); +3 (#5041): opt-in concept write-through hook and the import callback publishClassicConcept runs under the page lock; +6 #4907 (issue #4906): configured budget read, budget-capped counter, summary clause and details.warnings (message text in budgetWarnings); +4 fix wave 11 #6161: concept redirects in grouping and the skipped_deleted pre-check (logic in cycle/concept-redirects.ts)+src/core/cycle/synthesize.ts runPhaseSynthesizeInner 1047 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #5854: publish_pending from postprocess, a pending summary publish deferred instead of failing the phase; +1 fix wave 11 #6160: oneshot_task_prefixes on the child job datasrc/core/facts/backstop.ts runPipelineBodyInner 358 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/import-file.ts importFromContent 812 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 wave 8 lane D1 #5158: key-order fallback equality and legacy-hash ordering; lowered to 807 (#5988: screen and sanity config peeled to core/import-screen.ts); +1 #6007: the prepared apply reports its written page and seal (PreparedImportApplied) so put_page skips a re-read and a second seal; +1 #5333: embed-skip transition defeats the unchanged fast paths (the stale-marker clear stays inside the sanity block); +3 #6188: Tier 1 fence step in place before the hidden-row merge (logic in fence-repair/import-step.ts)src/core/minions/handlers/subagent-oneshot.ts runSubagentOneshot 378 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 fix wave 9 lane B #4921: the oneshot sub-budget is passed as the call timeoutMs so the 300 s gateway backstop cannot cut itdiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 2ccbbfb4b0..b475d62acf 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -14,7 +14,7 @@ src/commands/serve-http.ts 926 ratchet refactor wave 1 W4 split into serve-http-src/core/ai/gateway.ts 4425 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts)src/commands/sync.ts 512 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event fieldsrc/core/cycle.ts 3254 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts)-src/core/cycle/synthesize.ts 3207 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg)+src/core/cycle/synthesize.ts 3208 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job datasrc/core/cycle/extract-atoms.ts 1650 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms promptsrc/core/engine.ts 2721 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contractsrc/core/import-file.ts 2200 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts)diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 10d5f5691b..f8043e2ea5 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -91,6 +91,7 @@ test/cycle-abort.test.ts CycleOpts.signal contract (v0.20.5) 3 readFileSynctest/cycle-abort.test.ts autopilot-cycle handler contract (v0.20.5) 3 readFileSync,source-surface-helpertest/cycle-drain-renewal.test.ts db-lock heartbeat wiring (structural — issue #6 cancellation) 1 readFileSynctest/cycle-drain-renewal.test.ts drain-loop wiring (structural — the shape guard only covers worker.ts) 2 readFileSync+test/cycle-legacy-phases.test.ts cycle.lint_exclude (#6134) 4 readFileSynctest/cycle-patterns-deadline-budget.test.ts deadline plumbing wiring (structural) 7 readFileSync,source-surface-helpertest/cycle-patterns.test.ts patterns private-queue keepalive wiring 1 readFileSynctest/cycle-phase-deadline-drift.test.ts propose_takes deadline < job timeout (#4168) 4 readFileSyncdiff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex cf0ad15f68..bfc7ba4d10 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -88,7 +88,7 @@"functional-area-resolver/routing-eval.jsonl": "f80674d915acdfe229046737a5b171da834be15ac6524b5a3fd18048e9b37028","gbrain-advisor/SKILL.md": "7202baab08775048529f131e694e4fbaa85b1c8ae79e4fa7997fe4fe5ffbfa3d","gbrain-upgrade/SKILL.md": "62735c599c12863a7f1bd2193021d72136cb1210b11592fa95d3ce6aded99cff",- "google-loops/SKILL.md": "5ccdf9ac291cbf5b96d6c10c18476bd39c79bed8c192bfdc789fd4b70bde0138",+ "google-loops/SKILL.md": "7df3363e522cee7c24241b369cb1820b3cade4803ee3afd62b8b5c81b6330e31","idea-ingest/SKILL.md": "b3810543f92cd37cb8488ff30990c60bcedde58dc404a3f60d43ac97016d6e33","idea-lineage/SKILL.md": "3432a9cca1626c7876eb12d7ec0d6cc37feeb8f3c18cf99f08028ef3174ae0e0","idea-lineage/routing-eval.jsonl": "ee2e00704b9accb7dd58bb8f126a3bc04a2c40be499180fa505dbf6d5061cd41",diff --git a/src/commands/config.ts b/src/commands/config.tsindex 924d098e69..6508a58b63 100644--- a/src/commands/config.ts+++ b/src/commands/config.ts@@ -1198,26 +1198,9 @@ export async function runConfig(engine: BrainEngine, args: string[]) {}// #4907: a phase knob the phase would ignore is refused before the write.- const { PHASE_CONFIG_KEYS, parsePhaseConfigValue } = await import('../core/cycle/phase-config-values.ts');- if (PHASE_CONFIG_KEYS.includes(key)) {- try { parsePhaseConfigValue(key, value); }- catch (error) { (await import('../cli/cli-error.ts')).exitCliError(error, 'config'); }- }-- // #6177: dream.patterns.last_run is state the patterns phase records, not a setting.- if (key === 'dream.patterns.last_run') {- const { opError } = await import('../core/ops/contract.ts');- (await import('../cli/cli-error.ts')).exitCliError(opError('invalid_params', 'dream.patterns.last_run is recorded by the patterns phase and cannot be set.',- 'To forget the recorded run cost, unset it: gbrain config unset dream.patterns.last_run', {- why: 'The phase sizes in-cycle runs from the cost of the last child it ran; a hand-written value would mis-size them. Nothing was written.',- fix: { argv: ['gbrain', 'config', 'unset', 'dream.patterns.last_run'], consent: [], actor: 'agent', requires_exclusive: false,- why: 'Unsetting resets the record; the next in-cycle run submits a conservative first batch.', verify: { argv: ['gbrain', 'config', 'get', 'dream.patterns.last_run'] } },- }), 'config');- }-- // #6134: a path in cycle.lint_exclude would never match a basename.- if (key === 'cycle.lint_exclude') {- try { (await import('../core/cycle/lint-fix-setting.ts')).parseCycleLintExclude(value); }+ const [{ PHASE_CONFIG_KEYS, parsePhaseConfigValue }, { CYCLE_GUARDED_KEYS, assertCycleConfigValue }] = await Promise.all([import('../core/cycle/phase-config-values.ts'), import('../core/cycle/config-guards.ts')]);+ if (PHASE_CONFIG_KEYS.includes(key) || CYCLE_GUARDED_KEYS.includes(key)) { // #6134/#6177: lint_exclude paths, the last_run state key+ try { if (PHASE_CONFIG_KEYS.includes(key)) parsePhaseConfigValue(key, value); else assertCycleConfigValue(key, value); }catch (error) { (await import('../cli/cli-error.ts')).exitCliError(error, 'config'); }}diff --git a/src/commands/lint.ts b/src/commands/lint.tsindex af80ca1c6a..1992f02f4c 100644--- a/src/commands/lint.ts+++ b/src/commands/lint.ts@@ -659,7 +659,7 @@ function writeLintFixOrRefusal(page: string, relPath: string, fixed: string): Liconst errno = (e as NodeJS.ErrnoException | null)?.code;if (typeof errno !== 'string' || !UNWRITABLE_CODES.has(errno)) throw e;const envelope = toAgentError(opError('fix_not_writable', `fix not applied: ${relPath} is not writable (${errno}); the file was left unchanged.`,- 'Make the file writable by the user running gbrain, or pass its directory or file name to `gbrain lint --exclude` (for the cycle: `gbrain config set cycle.lint_exclude <name>`), then lint again.', {+ 'Make the file writable by the user running gbrain, or pass its directory or file name to `gbrain lint --exclude` (for the cycle, add it to `cycle.lint_exclude` with `gbrain config set`), then lint again.', {why: 'Lint repairs files in place, and this file refused the write (its permissions or a read-only mount).',fix: { consent: [], actor: 'user', requires_exclusive: false, why: 'Only the file owner can change its permissions or mount.',user_message: `Make ${relPath} writable for gbrain, or exclude it from lint.` },diff --git a/src/core/context/retrieval-reflex.ts b/src/core/context/retrieval-reflex.tsindex 11a57c6f1b..ca018cffda 100644--- a/src/core/context/retrieval-reflex.ts+++ b/src/core/context/retrieval-reflex.ts@@ -54,6 +54,32 @@ const PURE_CJK_RE = new RegExp(`^[${CJK_SLUG_CHARS}]+$`, 'u');/** Which resolution arm produced a pointer (provenance → honest confidence). *//** `recall`: a System One S6 keyword-only retrieval fired by the know-to-ask slot (never produced by the resolver). */+/**+ * #6195 arm 2.6 ('weak-title'): a lowercase 2-3-word weak n-gram may match the+ * exact title of an entity page (person, company, organization) when that+ * title is globally unique across the considered sources and no other arm+ * resolved the n-gram. Concepts and other types are excluded: their titles are+ * common phrases ("open source"). Fail-open: the alias arm already ran.+ */+async function weakTitleHits(engine: BrainEngine, sourceIds: string[], privacySql: string, norms: string[]): Promise<PageRow[]> {+ if (!norms.length) return [];+ try {+ const rows = await engine.executeRaw<PageRow>(+ `SELECT p.slug, p.source_id, p.title, p.type, p.frontmatter, p.compiled_truth+ FROM pages p+ WHERE p.deleted_at IS NULL ${privacySql}+ AND p.source_id = ANY($1::text[])+ AND lower(p.title) = ANY($2::text[])`,+ [sourceIds, norms],+ );+ const byTitle = new Map<string, PageRow[]>();+ for (const r of rows) byTitle.set((r.title ?? '').toLowerCase(), [...(byTitle.get((r.title ?? '').toLowerCase()) ?? []), r]);+ return [...byTitle.values()].filter((list) => list.length === 1 && WEAK_TITLE_ENTITY_TYPES.has(String(list[0].type))).map((list) => list[0]);+ } catch {+ return [];+ }+}+/** #6195: page types whose exact title a lowercase multi-word n-gram may match. */const WEAK_TITLE_ENTITY_TYPES = new Set(['person', 'company', 'organization']);@@ -200,8 +226,7 @@ export async function resolveEntitiesToPointers(// norms are tracked so the alias fold can apply the stricter cross-source// uniqueness rule to them.const weakNorms = new Set<string>();- // #6195: multi-word weak n-grams, also probed against exact entity titles (arm 2.6).- const weakTitleNorms = new Set<string>();+ const weakTitleNorms = new Set<string>(); // #6195: multi-word weak n-grams, also probed against exact entity titles (arm 2.6)// Surname arm inputs: strong single-token capitalized candidates ≥3 chars.const surnamePatterns: string[] = [];const surnameTokens: string[] = []; // lower(token), parallel to patterns@@ -506,38 +531,9 @@ export async function resolveEntitiesToPointers(}}- // Arm 2.6 — lowercase multi-word weak exact-title (#6195, 'weak-title'). A- // 2-3-word weak n-gram may match the exact title of an entity page (person,- // company, organization) when that title is globally unique across the- // considered sources and no other arm resolved the n-gram. Concepts and- // other types are excluded: their titles are common phrases ("open source").- if (lexicalArms && weakTitleNorms.size) {- const armResolvedNorms = new Set(resolved.map((r) => r.matchedNorm).filter(Boolean));- const titleNorms = [...weakTitleNorms].filter((n) => !armResolvedNorms.has(n));- if (titleNorms.length) {- try {- const rows = await engine.executeRaw<PageRow>(- `SELECT p.slug, p.source_id, p.title, p.type, p.frontmatter, p.compiled_truth- FROM pages p- WHERE p.deleted_at IS NULL ${privacySql}- AND p.source_id = ANY($1::text[])- AND lower(p.title) = ANY($2::text[])`,- [sourceIds, titleNorms],- );- const hits = new Map<string, PageRow[]>();- for (const r of rows) {- const n = (r.title ?? '').toLowerCase();- hits.set(n, [...(hits.get(n) ?? []), r]);- }- for (const [n, list] of hits) {- if (list.length !== 1 || !WEAK_TITLE_ENTITY_TYPES.has(String(list[0].type))) continue;- rowByKey.set(keyOf(list[0].source_id, list[0].slug), list[0]);- push(list[0].slug, list[0].source_id, 'weak-title', n);- }- } catch {- /* fail-open — the alias arm already ran */- }- }+ // Arm 2.6 — lowercase multi-word weak exact-title (#6195; see weakTitleHits).+ if (lexicalArms && weakTitleNorms.size) for (const r of await weakTitleHits(engine, sourceIds, privacySql, [...weakTitleNorms].filter((n) => !resolved.some((x) => x.matchedNorm === n)))) {+ rowByKey.set(keyOf(r.source_id, r.slug), r); push(r.slug, r.source_id, 'weak-title', (r.title ?? '').toLowerCase());}// Build pointers in confidence order, applying suppression + cap.diff --git a/src/core/cycle/config-guards.ts b/src/core/cycle/config-guards.tsnew file mode 100644index 0000000000..6db861e81b--- /dev/null+++ b/src/core/cycle/config-guards.ts@@ -0,0 +1,24 @@+/**+ * Fix wave 11 `config set` guards for cycle keys that are not numeric phase+ * knobs (those live in phase-config-values.ts): `cycle.lint_exclude` refuses+ * a path (#6134), and `dream.patterns.last_run` is state the patterns phase+ * records, so it can only be unset (#6177). Each throws an `invalid_params`+ * OperationError whose fix is a real command; nothing is written.+ */+import { opError } from '../ops/contract.ts';+import { CYCLE_LINT_EXCLUDE_KEY, parseCycleLintExclude } from './lint-fix-setting.ts';+import { PATTERNS_LAST_RUN_KEY } from './patterns-plan.ts';++export const CYCLE_GUARDED_KEYS: readonly string[] = [CYCLE_LINT_EXCLUDE_KEY, PATTERNS_LAST_RUN_KEY];++export function assertCycleConfigValue(key: string, value: string): void {+ if (key === CYCLE_LINT_EXCLUDE_KEY) { parseCycleLintExclude(value); return; }+ if (key !== PATTERNS_LAST_RUN_KEY) return;+ throw opError('invalid_params', `${PATTERNS_LAST_RUN_KEY} is recorded by the patterns phase and cannot be set.`,+ `To forget the recorded run cost, unset it: gbrain config unset ${PATTERNS_LAST_RUN_KEY}`, {+ why: 'The phase sizes in-cycle runs from the cost of the last child it ran; a hand-written value would mis-size them. Nothing was written.',+ fix: { argv: ['gbrain', 'config', 'unset', PATTERNS_LAST_RUN_KEY], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Unsetting resets the record; the next in-cycle run submits a conservative first batch.',+ verify: { argv: ['gbrain', 'config', 'get', PATTERNS_LAST_RUN_KEY] } },+ });+}diff --git a/src/core/cycle/patterns-plan.ts b/src/core/cycle/patterns-plan.tsindex 376fe91135..448f098ff9 100644--- a/src/core/cycle/patterns-plan.ts+++ b/src/core/cycle/patterns-plan.ts@@ -10,6 +10,7 @@*/import type { BrainEngine } from '../engine.ts';import type { Action } from '../agent-output.ts';+import type { PhaseResult } from '../cycle.ts';export const PATTERNS_LAST_RUN_KEY = 'dream.patterns.last_run';/** Reflections a first in-cycle run submits with no history (or min_evidence, if larger). */@@ -74,8 +75,11 @@ export async function readPatternsLastRun(engine: BrainEngine): Promise<Patterns}}-export async function recordPatternsLastRun(engine: BrainEngine, run: Omit<PatternsLastRun, 'budget_skips'>): Promise<void> {- await engine.setConfig(PATTERNS_LAST_RUN_KEY, JSON.stringify({ ...run, budget_skips: 0 })).catch(() => undefined);+/** Record a child's cost; any end other than completed or timeout is `failed`. */+export async function recordPatternsLastRun(engine: BrainEngine, run: { duration_ms: number; reflections: number; outcome: string }): Promise<void> {+ const outcome: PatternsLastRun['outcome'] = run.outcome === 'completed' || run.outcome === 'timeout' ? run.outcome : 'failed';+ const record: PatternsLastRun = { duration_ms: run.duration_ms, reflections: run.reflections, at: new Date().toISOString(), outcome, budget_skips: 0 };+ await engine.setConfig(PATTERNS_LAST_RUN_KEY, JSON.stringify(record)).catch(() => undefined);}export async function recordPatternsBudgetSkip(engine: BrainEngine, lastRun: PatternsLastRun): Promise<void> {@@ -90,3 +94,22 @@ export function patternsBudgetSkipFix(): Action {docs: 'docs/guides/dream-patterns.md#budget-sizing',};}++/**+ * The phase's sizing step: plan from the recorded last run, or the budget+ * skip result (the skip is counted toward the probe, nothing is submitted).+ */+export async function sizePatternsRun(engine: BrainEngine, input: { budgetMs: number | null; reflections: number; minEvidence: number }):+ Promise<{ kind: 'submit'; plan: Extract<PatternsPlan, { kind: 'submit' }> } | { kind: 'skip'; result: PhaseResult }> {+ const lastRun = await readPatternsLastRun(engine);+ const plan = planPatternsRun({ ...input, lastRun, nowMs: Date.now() });+ if (plan.kind === 'submit') return { kind: 'submit', plan };+ if (lastRun) await recordPatternsBudgetSkip(engine, lastRun);+ const budgetMs = input.budgetMs ?? 0;+ return { kind: 'skip', result: { phase: 'patterns', status: 'skipped', duration_ms: 0,+ summary: `patterns: the ${Math.round(budgetMs / 1000)}s cycle budget fits ${plan.n} of ${input.reflections} reflections ` ++ `at the recorded runtime (need ≥${input.minEvidence}); nothing was submitted. Run it outside the cycle: gbrain dream --phase patterns`,+ details: { reason: 'insufficient_cycle_budget', cause: plan.reason, reflections_selected: input.reflections,+ reflections_submitted: 0, reflections_fit: plan.n, budget_ms: budgetMs, last_run: lastRun,+ fix: patternsBudgetSkipFix(), reset_command: `gbrain config unset ${PATTERNS_LAST_RUN_KEY}` } } };+}diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.tsindex 46d12cefb3..7a187823e3 100644--- a/src/core/cycle/patterns.ts+++ b/src/core/cycle/patterns.ts@@ -102,7 +102,7 @@ export interface PatternsPhaseOpts {* working.*/import { CYCLE_DEADLINE_RESERVE_MS } from './base-phase.ts';-import { patternsBudgetSkipFix, planPatternsRun, readPatternsLastRun, recordPatternsBudgetSkip, recordPatternsLastRun } from './patterns-plan.ts';+import { recordPatternsLastRun, sizePatternsRun } from './patterns-plan.ts';export { CYCLE_DEADLINE_RESERVE_MS };/**@@ -243,21 +243,10 @@ export async function runPhasePatterns();}- // #6177: size an in-cycle run to its budget from the recorded cost of recent runs; skip before any spend.- const lastRun = await readPatternsLastRun(engine);- const plan = planPatternsRun({ budgetMs: opts.deadlineAtMs == null ? null : budgets.timeoutMs, lastRun,- reflections: reflections.length, minEvidence: config.minEvidence, nowMs: Date.now() });- if (plan.kind === 'skip') {- if (lastRun) await recordPatternsBudgetSkip(engine, lastRun);- return { phase: 'patterns', status: 'skipped', duration_ms: 0,- summary: `patterns: the ${Math.round(budgets.timeoutMs / 1000)}s cycle budget fits ${plan.n} of ${reflections.length} reflections ` +- `at the recorded runtime (need ≥${config.minEvidence}); nothing was submitted. Run it outside the cycle: gbrain dream --phase patterns`,- details: { reason: 'insufficient_cycle_budget', cause: 'budget_below_recent_runtime', reflections_selected: reflections.length,- reflections_submitted: 0, reflections_fit: plan.n, budget_ms: budgets.timeoutMs, last_run: lastRun,- fix: patternsBudgetSkipFix(), reset_command: 'gbrain config unset dream.patterns.last_run' } };- }- const selected = reflections.length;- const submitted = reflections.slice(0, plan.n);+ // #6177: size an in-cycle run from the recorded cost of recent runs; a run that cannot fit is skipped before any spend.+ const sized = await sizePatternsRun(engine, { budgetMs: opts.deadlineAtMs == null ? null : budgets.timeoutMs, reflections: reflections.length, minEvidence: config.minEvidence });+ if (sized.kind === 'skip') return sized.result;+ const { plan } = sized, selected = reflections.length, submitted = reflections.slice(0, plan.n);const queue = new MinionQueue(engine);// #2050: children drain inline on BOTH engines (see runSubagentsInline),@@ -364,9 +353,7 @@ export async function runPhasePatterns(}}- // #6177: every child records its cost, timed-out and failed ones included.- await recordPatternsLastRun(engine, { duration_ms: Date.now() - submittedAt, reflections: submitted.length, at: new Date().toISOString(),- outcome: outcome === 'completed' ? 'completed' : outcome === 'timeout' ? 'timeout' : 'failed' });+ await recordPatternsLastRun(engine, { duration_ms: Date.now() - submittedAt, reflections: submitted.length, outcome }); // #6177: every child, timed out or failed tooif (opts.yieldDuringPhase) {try { await opts.yieldDuringPhase(); } catch { /* best-effort */ }diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.tsindex db4c500a29..5aebbb31d8 100644--- a/src/core/cycle/synthesize-concepts.ts+++ b/src/core/cycle/synthesize-concepts.ts@@ -215,13 +215,11 @@ export async function runPhaseSynthesizeConcepts(};}- // 2. Group atoms by normalized concept slug; one atom counts once per concept.- // #6161: a concept merged into another (merged_into / a canonical alias) groups under the canonical one.+ // 2. Group atoms by normalized concept slug (#6161: a merged concept groups under its canonical one); one atom counts once per concept.const redirects = await loadConceptRedirects(engine, opts.sourceId ?? 'default', conceptStemFor).catch(() => new Map<string, string>());const groups = new Map<string, { slugs: string[]; titles: string[]; bodies: string[]; visibilities: Visibility[] }>();for (const atom of atoms) {- const conceptSlugs = new Set(atom.concept_refs.map(conceptStemFor).filter((s): s is string => s !== null)- .map((stem) => canonicalConceptStem(stem, redirects)));+ const conceptSlugs = new Set(atom.concept_refs.map(conceptStemFor).filter((s): s is string => s !== null).map((stem) => canonicalConceptStem(stem, redirects)));for (const conceptSlug of conceptSlugs) {const existing = groups.get(conceptSlug) ?? { slugs: [], titles: [], bodies: [], visibilities: [] };existing.slugs.push(atom.slug);@@ -345,11 +343,7 @@ export async function runPhaseSynthesizeConcepts(// A concept page this phase did not write belongs to a human (or another// writer). Check before any spend; never replace its body.const existingSnapshot = await engine.readPageSnapshot(conceptSlug, { sourceId: opts.sourceId ?? 'default', includeDeleted: true });- // #6161: a concept page someone deleted (with no merge redirect) is never resurrected.- if (existingSnapshot?.page.deleted_at) {- skippedDeleted.push(conceptSlug);- continue;- }+ if (existingSnapshot?.page.deleted_at) { skippedDeleted.push(conceptSlug); continue; } // #6161: a deleted concept is never resurrectedconst existing = existingSnapshot?.page ?? null;if (existing && !String(existing.frontmatter?.synthesized_by ?? '').startsWith('synthesize_concepts')) {skippedHumanOwned.push(conceptSlug);diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.tsindex 2301dcf1f8..64df00eeab 100644--- a/src/core/cycle/synthesize.ts+++ b/src/core/cycle/synthesize.ts@@ -909,8 +909,7 @@ async function runPhaseSynthesizeInner(oneshot_slug_suffix: chunks.length > 1? `${t.contentHash.slice(0, 6)}-c${i}`: t.contentHash.slice(0, 6),- // #6160: the task shapes oneshot validation enforces, from the resolved namespaces.- oneshot_task_prefixes: [config.reflectionsPrefix, config.originalsPrefix],+ oneshot_task_prefixes: [config.reflectionsPrefix, config.originalsPrefix], // #6160: oneshot task shapesrequire_writes: true,// #1586: scope every child tool call to the cycle's resolved source// so put_page writes land there instead of the hardcoded 'default'.diff --git a/src/core/sweep.ts b/src/core/sweep.tsindex d72a67cc7c..343f696b44 100644--- a/src/core/sweep.ts+++ b/src/core/sweep.ts@@ -49,6 +49,7 @@ import { lineGrammarOptions } from './line-grammar.ts';import { join } from 'node:path';import { readdir, readFile, writeFile, rm, stat } from 'node:fs/promises';+import type { CorpusFactTime } from './context/corpus-windows.ts';import type { BrainEngine, LinkBatchInput, TimelineBatchInput } from './engine.ts';import type { FactsBackstopCtx } from './facts/backstop.ts';import type { CapabilityReport } from './capability.ts';@@ -129,6 +130,17 @@ export interface SweepReport {durationMs: number;}+/**+ * #6159: the session file's write time as its facts' time (`turnAt`), or+ * undefined when the file time is not trusted (logged; the facts are then+ * dated at extraction).+ */+function corpusTurnAt(name: string, factTime: CorpusFactTime, log: (line: string) => void): Date | undefined {+ if ('at' in factTime) return factTime.at;+ log(`[sweep] ${name}: file time not trusted (${factTime.rejected}); its facts are dated at extraction time.`);+ return undefined;+}+/*** Run one bounded maintenance sweep. Never throws — failures land in* report.skipped with a per-pass reason.@@ -756,11 +768,6 @@ async function runCorpusIngestPass(const wbSourceId = wbMeta?.sourceId && isValidSourceId(wbMeta.sourceId)? wbMeta.sourceId: sourceId;- // #6159: facts happened when the session file was written, not when this (possibly late) sweep runs.- const factTime = windows.corpusFactTime(fileStat.mtime_ms);- if ('rejected' in factTime) {- log(`[sweep] ${name}: file time not trusted (${factTime.rejected}); its facts are dated at extraction time.`);- }const pipelineCtx: FactsBackstopCtx = {engine,sourceId: wbMeta ? wbSourceId : sourceId,@@ -774,9 +781,8 @@ async function runCorpusIngestPass(mode: 'inline',remote: false,abortSignal: signal,- // #5888/#6159: the file's write time anchors the capture dedup window and dates the facts- // (turnAt, never validFrom: validFrom is part of the managed batch key).- turnAt: 'at' in factTime ? factTime.at : undefined,+ // #5888/#6159: the file's write time anchors the dedup window and dates the facts (never validFrom: a batch-key input).+ turnAt: corpusTurnAt(name, windows.corpusFactTime(fileStat.mtime_ms), log),reAdmitFileRefusals: true,...(wbMeta && wbCfg.mode === 'salient' ? { notabilityFilter: 'medium-and-up' as const } : {}),// visibility deliberately unset → resolveDefaultVisibility [ENG-8]