Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wave 15 G7: regenerate artifacts and goldens, satisfy the verify guards
garrytan2df73816b2b4
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.mdindex 716d08817d..e29e7b4d41 100644--- a/docs/architecture/key-files/commands-1.md+++ b/docs/architecture/key-files/commands-1.md@@ -20,7 +20,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value from `automaticSyncPull` (`src/core/persistence/automatic-sync-policy.ts`): a parsed `remote_url` on an unmanaged, unbound source, so local-only and managed sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn with `--max-rss 2048` and soft `maxCrashes: 5`, preferring the current source/compiled CLI over PATH. The child worker performs private-queue recovery only after its driver/selected-child readiness and schema check; autopilot does not duplicate that recovery before spawn. A configuration-blocked child leaves the owning daemon alive and heartbeating but gates dispatch, worker restarts and engine work until explicit owner restart after repair. `--status --json` adds processing readiness, reason and runtime identities without replacing existing freshness/exit semantics; see [the owner-specific repair guide](../../guides/minions-fix.md). `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` lists `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`; a `provider_failure` result throws `formatDrainProviderFailure(result)` — batches/remaining plus the drain's sanitized `last_error` — so the dead-lettered job's `error_text` names the cause, e.g. a missing provider key); `src/core/config.ts` carries the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID; `src/core/autopilot-lock.ts` checks liveness and the process command before takeover. `looksLikeGbrainAutopilotCommand` recognizes quoted or unquoted `cli.ts` / `cli.js` / `cli.mjs` paths, including spaces and normalized Windows separators, so a live matching autopilot retains even an old lock. Synthetic command-line and lock-decision cases are pinned by `test/autopilot-lock.test.ts`; they are not native Windows process-probe validation. (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector. daemon env lane: `writeWrapperScript` additively sources `<gbrainDir>/env` (honors `GBRAIN_HOME`) after the shell profiles with a `set -a` wrap so dotenv-style `KEY=value` lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes `GBRAIN_HOME` — the wrapper bakes it AFTER sourcing). Exported pure `chatBootWarning(chatAvailable, gbrainDir)` derives both remediation paths from the passed dir and prints via `console.log` at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model `isAvailable('chat')` probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run-`--install` remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd `try-restart`s after `enable --now`, cron/container print a residual-process notice instead of auto-killing. Pinned by `test/autopilot-install.test.ts` (16 cases incl. real-bash wrapper execution). Once processing is configuration-blocked, `guardAutopilotEngine` refuses new engine calls (except disconnect), guards transaction callback engines, and rolls back a transaction whose callback finishes after the block; already committed work is not revoked. Pinned by `test/autopilot-transaction-fence.test.ts`. #5195: install, status and uninstall act on one brain's job, named by `resolveAutopilotJob()` in `src/core/autopilot-paths.ts` (default brain: the shared names; any other brain: `<name>-<suffix>` from the random install id in `<brain>/.gbrain/autopilot-install-id`, with move/copy semantics); crontab lines carry `# gbrain-autopilot:<suffix>`; every log sink writes under the brain's home; a pre-#5195 shared job that runs this brain is replaced on install and reported by `--status` as `needs_reinstall: legacy_shared_job`; replacing or removing a job whose wrapper runs another live brain is refused (`autopilot_job_owned_by_other_brain`). Job-definition reads, legacy replacement and the `--status` job report live in `src/commands/autopilot/jobs.ts`. Pinned by `test/autopilot-install-id.test.ts` and `test/e2e/autopilot-multi-brain.serial.test.ts`.Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers launchd/systemd/cron/container install and reload paths, the wrapper script with its env-file lane and exec guard, status and the self-upgrade channel. `runAutopilot` is a mode table (`AUTOPILOT_MODES`: --install, --uninstall, --status, --pause/--resume; first match wins) that otherwise lazily imports the daemon: `autopilot-daemon.ts` (`runAutopilotDaemon`: boot, lock, managed worker, shutdown and the tick loop over an explicit `AutopilotDaemonState`; steps `probeDatabaseOrReconnect`, `probeNoWorkerPeer`, `runInlineCycle`, `adaptiveInterval`), `autopilot-dispatch.ts` (`dispatchAutopilotTick`: freshness syncs, extract_atoms auto-drain, remediation plan, full-cycle fan-out or targeted submits; targeted submits go through `autopilotTargetedSteps` in `autopilot-remediation-policy.ts`, which drops manual-only steps) and `autopilot-probes.ts` (nightly quality and conversation-parser probes; the quality probe's `resolveNightlyProbeModelRoutesForDaemon` runs `refreshGatewayForJob`'s two gateway calls (inlined: importing `jobs.ts` would grant its flags to `autopilot` in the flag registry) and then reads the probe's model routes from the brain, only on a run past the 24h gate; both probes take their fixtures from `NIGHTLY_PROBE_FIXTURES`, the embedded assets, and the quality probe passes its cap source and `pricing.overrides` as `resolveBudgetPolicy`). No injectable single-tick function exists yet (TODOS: testable autopilot tick), so the wiring guards read these modules as source.-- `src/commands/autopilot-dispatch.ts` — one autopilot tick's submissions (`dispatchAutopilotTick`): freshness syncs, the extract_atoms auto-drain, the remediation plan, and full-cycle fan-out or targeted submits. The auto-drain (`dispatchAutoDrain` → `submitAutoDrains`) runs on Postgres only, unless `autopilot.auto_drain.enabled` is `false`, and only when the active pack does not run extract_atoms in the routine cycle. It submits a bounded, protected `extract-atoms-drain` job per source with a backlog under a per-source UTC-day idempotency key, so a structural refusal costs at most one dead job per source per day. The daily cap (`autopilot.auto_drain.max_usd_per_day` / the per-attempt `cycle.extract_atoms.budget_usd` estimate) counts attempts, not jobs (`autoDrainUnitsToday`: a waiting job one, a retried job one per started attempt), and excludes a job whose only attempt dead-lettered with `structural_refusal:`. Checkout-backed and connector sources alternate for free slots, with the next kind persisted in `AUTO_DRAIN_NEXT_KIND_KEY` (`autopilot.auto_drain.next_kind`) across ticks and days; a source whose writer preflight would refuse (`atomDrainOwnerRefusal`) is skipped with a logged reason; connector sources need no `local_path` and submit no `repoPath`. Tests: `test/autopilot-auto-drain*.test.ts`, `test/e2e/autopilot-auto-drain-dispatch.test.ts`. #5028: the auto-drain no longer skips when the active pack declares extract_atoms (the daemon's per-source cycles run only SOURCE_FRESHNESS_PHASES, so the declaration never made the routine cycle drain it); extract_atoms runs stamp `sources.config.last_extract_atoms_at` (`stampExtractAtomsRun` in `src/core/cycle/extract-atoms-stamp.ts`, which also builds the doctor warning), and the `extract_atoms_backlog` doctor check's declared branch warns when a backlog source's stamp is missing or older than 48h even though cycles run.+- `src/commands/autopilot-dispatch.ts` — one autopilot tick's submissions (`dispatchAutopilotTick`): freshness syncs, the extract_atoms auto-drain, the remediation plan, and full-cycle fan-out or targeted submits. The auto-drain (`dispatchAutoDrain` → `submitAutoDrains`) runs on Postgres only, unless `autopilot.auto_drain.enabled` is `false`, and only when the active pack does not run extract_atoms in the routine cycle. It submits a bounded, protected `extract-atoms-drain` job per source with a backlog under a per-source UTC-day idempotency key, so a structural refusal costs at most one dead job per source per day. The daily cap (`autopilot.auto_drain.max_usd_per_day` / the per-attempt `cycle.extract_atoms.budget_usd` estimate) counts attempts, not jobs (`autoDrainUnitsToday`: a waiting job one, a retried job one per started attempt), and excludes a job whose only attempt dead-lettered with `structural_refusal:`. Checkout-backed and connector sources alternate for free slots, with the next kind persisted in `AUTO_DRAIN_NEXT_KIND_KEY` (`autopilot.auto_drain.next_kind`) across ticks and days; a source whose writer preflight would refuse (`atomDrainOwnerRefusal`) is skipped with a logged reason; connector sources need no `local_path` and submit no `repoPath`. Tests: `test/autopilot-auto-drain*.test.ts`, `test/e2e/autopilot-auto-drain-dispatch.test.ts`. #5028: the auto-drain no longer skips when the active pack declares extract_atoms (the daemon's per-source cycles run only SOURCE_FRESHNESS_PHASES, so the declaration never made the routine cycle drain it); extract_atoms runs stamp `sources.config.last_extract_atoms_at` (`stampExtractAtomsRun` in `src/core/cycle/extract-atoms-stamp.ts`, which also builds the doctor warning), and the `extract_atoms_backlog` doctor check's declared branch warns when a backlog source's stamp is missing or older than 48h even though cycles run. `autopilot.git_pull` (#6451, wave 15 P7.2): `automaticGitPullDisabled` in `core/persistence/automatic-sync-policy.ts` is read first by `automaticSyncPull`, so a non-truthy value queues every remote source's sync with `pull: false` before any persistence read; `dispatchFreshnessSyncs` prints one `git_pull: off` line (`git_pull_disabled` NDJSON event under `--json`) per tick while it is off. Pinned by `test/autopilot-git-pull-optout-6451.test.ts`.- `src/commands/backup.ts` — trusted local `gbrain backup status|check`: status may reuse a recent warning; check forces a bounded remote readback sweep. Enabled missing/locked/degraded evidence does not return an all-clear. Quiet and disabled modes retain explicit zero-exit behavior. JSON separates configured repos from fresh verified recoverable repos and describes committed-file-only recovery. Remote MCP doctor never invokes this local Git path; see `docs/operations/backup-check.md` and `test/backup-cli.serial.test.ts`. `backup create|restore` failures render the agent-operator contract (`storage_error`, fix `gbrain doctor --json`) with the legacy `ok`/`reason`/`message`/`retryable` JSON keys; a message-less thrown value is described only by its bounded name/code/errno (`backupFailureMessage`), never `String(object)`.diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.mdindex f0fef1dcc4..177f870aa1 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -46,7 +46,7 @@ Managed connector ingestion, connector item holds, sync checkpoint validation an- `src/core/persistence/graduation-drain.ts` — engine graduation drain. `graduationBlockers` lists what keeps a brain from copying, each with its structured action: requests this host owns (drained), requests and host bindings owned by another host, recovering topology changes and effects, the writer admin lock, and OAuth clients bound to a missing source (an FK only Postgres enforces; never cleared silently, since unbinding widens access). `drainForGraduation` refuses up front on anything the drain cannot clear, then publishes this host's queued, running and recovering requests with a `requestsOnly` `PersistenceConsumer` bounded by the timeout and always runs its stop barrier before returning; the `graduation_drain_timeout` refusal is built by `graduation-errors.ts`. `freezeSource` stops the resident consumer and sets the PGLite connection to read-only transactions; `withSourceWritable` runs one read-write transaction for custody writes. Tests: `test/graduation-drain.test.ts`.- `src/core/persistence/graduation-copy.ts` — engine graduation copier (in process). `copyTable` reads source rows through the digest's own plan (`digestPlan` with inventory transforms, `rowFilter`, `::text` values, COLLATE "C" keyset batches) and writes them in one target transaction per table that sets `gbrain.graduation_run`, bypasses user triggers (`session_replication_role = replica`, or DISABLE/ENABLE TRIGGER by name in the same transaction, never the `gbrain_graduation_fence` triggers), deletes the target's rows (seed rows included) and inserts byte-sized batches as one `$1::text::jsonb` array cast back per column type. The per-column contract (`columnContract`) refuses missing, retyped, target-only or differently generated columns outside the entry's `columnAllowlist`; generated columns are never inserted. Self-FKs take a second update pass under DISABLE TRIGGER. `copySequences` applies each source sequence's exact position, raised to the target column maximum. `deferIndexes`/`buildDeferredIndexes` drop and rebuild HNSW (through `buildDeferredAnnIndexes`) and GIN indexes, keeping the pending list in the target-owned `graduation.deferred_indexes` config row. Tests: `test/graduation-copy.test.ts`, `test/e2e/graduation-copy.test.ts`.- `src/core/persistence/root-metadata.ts` — engine-free ownership-marker names. `isPhysicalRootMetadata` matches `.gbrain-owner.json`, `.gbrain-owner-<sha256>.json` (reservation) and `.gbrain-owner.json.<uuid>.tmp` (`physical-root-record.ts` re-exports it and `PHYSICAL_ROOT_MARKER`). `OWNERSHIP_MARKER_GLOBS` (#5186) are those names in gitignore dialect: `physical-root-record.ts` `excludeOwnershipMarkers` appends them to `<gitdir>/info/exclude` (`git rev-parse --git-path`, idempotent, best effort) after `writePhysicalRootStamp` / `adoptTransferredRootStamp`, for the stamped directory, the root and the reservation's parent. `PUSH_DENY_GLOBS` denies them with `.gbrain-bootstrap.lock/**`; the bootstrap `.gitignore` template has them; doctor `tracked_ownership_marker` warns when a source checkout's index has one. `withoutPhysicalRootMetadata` drops `git status --porcelain` entries made only of such metadata (doctor `bootstrap_push_health`, stop-hook dirty probes): a stamp-only tree is clean, a real change beside the stamp, a rename across it and a quoted path still count. Test: `test/persistence-root-metadata.test.ts`.-- `src/core/persistence/automatic-sync-policy.ts` — `automaticSyncPull(engine, source)`: whether an automatic sync (autopilot freshness `sync` job, per-source fanout cycle) may request a Git pull. It needs a parsed `remote_url`, exactly one boolean `persistence_brain` state that is off, and no worktree binding; a managed brain or claimed source syncs local HEAD with `pull: false`. Missing, duplicated or non-boolean persistence metadata throws `storage_error` (why, read-only `gbrain sources writer status --probe --json` fix) instead of granting a pull, so the caller queues nothing. Clone, immutable and federation flags grant nothing. `autopilot.git_pull` (#6451; `AUTOPILOT_GIT_PULL_KEY`, `automaticGitPullDisabled`) is the brain-wide opt-out read first: an explicit non-truthy value returns `false` before any persistence read, unset or unreadable keeps the default; `dispatchFreshnessSyncs` prints one `git_pull: off` line (`git_pull_disabled` NDJSON event under `--json`) per tick while it is off. Pinned by `test/automatic-sync-pull-policy.test.ts` and `test/autopilot-git-pull-optout-6451.test.ts`.+- `src/core/persistence/automatic-sync-policy.ts` — `automaticSyncPull(engine, source)`: whether an automatic sync (autopilot freshness `sync` job, per-source fanout cycle) may request a Git pull. It needs a parsed `remote_url`, exactly one boolean `persistence_brain` state that is off, and no worktree binding; a managed brain or claimed source syncs local HEAD with `pull: false`. Missing, duplicated or non-boolean persistence metadata throws `storage_error` (why, read-only `gbrain sources writer status --probe --json` fix) instead of granting a pull, so the caller queues nothing. Clone, immutable and federation flags grant nothing. Pinned by `test/automatic-sync-pull-policy.test.ts`.- `src/core/persistence/native-lock.ts` + `native/locks/` — lazy portable Node-API v3 kernel locks (`flock` / `LockFileEx`) with opaque handles, retained stable lock files, cancellable asynchronous waiting and fail-closed capability errors. Eight vendored prebuilds support script-disabled source installs; pinned Zig recipes and source/artifact hashes live in `scripts/native/`. Actual competing-process, crash-handoff and compiled-executable tests run across eight platform/architecture targets and Bun 1.4.0 / 1.4.2. The compiled smoke waits for child exit before cleanup; `scripts/native/compiled-smoke-cleanup.ts` bounds retries to transient Windows `EBUSY` errors, with persistent and permission failures pinned by `test/scripts/native-compiled-cleanup.test.ts`. Windows-only `windows-ipc.h` supplies opaque Global mutex claims (same-thread recursion refused, abandoned owner handoff) and exact-handle stale AF_UNIX deletion after a verified reparse tag under a retained binding claim. CNG hashing and native casing make pipe identities independent of homes and logon sessions. Build and ownership contract: `native/locks/README.md`. `native/locks/package.json` (private, no entry points, outside `buildInputs` and `prebuilds/`) is a package boundary so plugin hosts that namespace native addons by the nearest package.json do not treat the whole checkout as one package (#6026; guard `test/native-locks-package-boundary.test.ts`). #6305: a failure to create or open the lock file is a `NativeLockUnavailableError` with `stage: 'open'` and `osError` (node:fs code, or the addon's `(OS error N)` as its errno name); `isLockOpenFailure` matches only that typed shape, never message text. `publishMutation` (`coordinator.ts`) and the Postgres single-write group path (`group-publish.ts` `publishGroup`, falling through to `publishMutation`) release such a write as `queued` / `writer_lock_unavailable` instead of the terminal owner-exception path; the consumer holds that root for `INSPECT_OWNER_RETRY_MS` (30 s, `health.ts`) so it doesn't re-prepare every poll; `ownerExceptionFailure` reports `osError` as the owner-only errno; a Git effect counts it as a dependency wait and never parks on it. An EISDIR or EACCES on the brain path itself stays terminal (`persistence-lock-open-failure.test.ts`, both engines).- `src/core/persistence/switches.ts` + `preadmit-cache.ts` + `config-snapshot.ts` — the single-write fast path for foreground page writes on Postgres. `switches.ts` reads every write-path kill switch (`persistence.single_write_group` / `GBRAIN_SINGLE_WRITE_GROUP`, `persistence.preadmit_cache` / `GBRAIN_PREADMIT_CACHE`, `sync.waive_batch` / `GBRAIN_SYNC_WAIVE_BATCH`, `sync.foreground_priority` / `GBRAIN_SYNC_FOREGROUND_PRIORITY`, and `persistence.preparation_deadlines` / `GBRAIN_PREPARATION_DEADLINES` (#6278: off restores the old preparation predicate, see persistence-stalls.md); on by default, `0`/`false` off, env over config) in one `SELECT key,value FROM config WHERE key = ANY(...)` per engine, kept 5 s (the consumer tick reads it under its phase deadline), together with the four preparation budget keys (`readWriteSwitchSnapshot` returns `{ switches, preparation }`; `readPreparationPolicy` is the budgets alone); read-through views register their engine (`registerEngineView`) to share it. With `single_write_group` on: the consumer publishes an eligible single page write (put_page, capture, edit/delete/restore/revert without an internal `intent.kind` or group key) as a group of one through `publishGroup` (`publishSingleWrite`; its intent carries no group marker, its effects queue without `deferBatchReconcile`, and a group that does not commit falls back to `publishMutation`, reclaiming a claim its file restoration released); PGLite and refused shapes keep `publishMutation`. The waiter's own wake (`wake(true)`) claims without the periodic scans (recovery records still block the claim through `claimableWriteSql`); preparation reads the config table once (`config-snapshot.ts`) and sends its independent reads together; the coordinated (`coordinated: true`) put_page apply reuses the publisher's locked read as the import base, pipelines its follow-up statements and reads the page once after its last write for the read-back check, seal, core notice and receipt. Publication, the own admission and the recovery transactions run on the consumer's reserved lane (`onLane`: the idle-probe connection, taken while two other pool connections stay free and kept across writes; never lent while an idle probe runs on it, and probes skip it while lent), so their prepared statements stay warm; the waiter is told of the commit before the recovery record is cleared. `preadmit-cache.ts` (with `preadmit_cache` on, Postgres) answers the brain id, source row, worktree binding and local-writer reads of `submitPageMutation` from a per-engine cache (30 s, keyed by brain id; absences never cached); admission rechecks each under lock and the brain id against its protocol statement, and a refusal the cache could explain (`source_changed`, `permission_denied`, a changed brain) drops the cache and runs the whole preparation once more uncached. Pinned by `test/e2e/single-write-fast-path-postgres.test.ts` (switches, cache rechecks, replay, restoration after a failure past the file rename, the recovery-blocked direct claim) and `test/single-write-group-parity.test.ts` + `test/e2e/single-write-group-parity-postgres.test.ts` (row-for-row parity with the switches off); measured by `scripts/bench/foreground-put-page.ts`.diff --git a/docs/guides/skill-reference.md b/docs/guides/skill-reference.mdindex da283ac149..7195dcf4f1 100644--- a/docs/guides/skill-reference.md+++ b/docs/guides/skill-reference.md@@ -28,8 +28,8 @@ ranking, not a model call, so it is free and instant, and the same callwithout `query` returns the whole catalog exactly as before. On a brain thatserves a shared catalog (`schema_version: 2`, or shared skills activated)`query` is refused with `invalid_params` instead of being ignored; narrow with-`section` there. **Say to your agent:** *"Which of my brain's skills should I-use to prepare for this meeting?"*+`section` there. **Say to your agent:** *"Which of my brain's skills fit+preparing for this meeting?"***Brain-resident skillpacks + advisor:** A brain repo can carry itsown publishable skillpack (`brain_resident: true` in `skillpack.json` + `schema_pack`);diff --git a/llms-full.txt b/llms-full.txtindex a5b7c3428f..cc7409901b 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -6808,6 +6808,26 @@ vars — incident-time escape hatches, not everyday knobs.**Say to your agent:** *"Bring my notes source up to date with its remote."*+9. **Turn automatic pulls off for every source.** On an unmanaged brain,+ autopilot's freshness sync and its per-source cycle run `git pull` for a+ source that has a remote URL. A checkout you keep current yourself (a+ deploy script, a mirror, a branch you rebase by hand) should not be+ pulled behind your back:++ ```bash+ gbrain config set autopilot.git_pull false # default: true+ ```++ Automatic syncs then index the local checkout as it is (`pull: false` on+ every queued sync job), and the daemon prints `git_pull: off+ (autopilot.git_pull=false)` once per tick (`{"event":"git_pull_disabled"}`+ under `--json`). Per-source `syncEnabled: false` still removes a source from+ automatic sync entirely; an explicit `gbrain sync --source <id>` keeps its+ own `--pull`/`--no-pull` choice. Managed brains never pull automatically+ whatever this key says (item 8).++ **Say to your agent:** *"Stop autopilot from git-pulling my sources; I update the checkouts myself."*+## How to Verify1. **Edit a file and search for the change.** Edit a brain markdown file,@@ -7253,6 +7273,15 @@ per-transcript synthesis subagents. The dials:Pages that already existed are checked only on the sentences this runadded. The off switch is the incident escape hatch; telemetry lands in`details.synthesis.quote_verify`.+- `cycle.propose_takes.types` (default unset = every page type) — a JSON array+ of page types the `propose_takes` phase may scan, for example+ `gbrain config set cycle.propose_takes.types '["meeting","analysis"]'`.+ Pages of other types (machine-written lanes, `note` scratch pages) are+ never sent to the model, so the phase spends only on the lanes you name.+ The built-in exclusions (receipts, atoms, the dream cycle's own output)+ still apply; a value that is not a JSON array is ignored with one stderr+ line and the phase scans every type. Note that a page with no `type` has+ no type to match, so it is excluded whenever the list is set.- `dream.synthesize.attribution_rules` and `dream.propose_takes.attribution_rules`(default off) — extra prompt rules from #5425: keep who proposed what andlater corrections explicit; an assistant-authored judgment is not the@@ -8975,6 +9004,36 @@ purpose, no dedicated status); a `max_tokens`-cut envelope parses as`output_truncated` (warning `LLM_OUTPUT_TRUNCATED`) so a too-small outputbudget is distinguishable from malformed model output.+#### synthesize evidence budget and provenance (additive, #5461)++The pages the model reads are excerpts, not whole pages. Each gathered page+gets `min(ceiling, floor(total / pages_gathered))` characters, never fewer+than 600, with `total` from `think.pages_budget_chars` (4 000-200 000,+default 12 000) and `ceiling` from `think.excerpt_ceiling_chars`+(600-200 000, default 2 400), both set with `gbrain config set` on the brain+host (the verb surface stays frozen: no new parameter). The total is a SOFT+bound: the 600-character floor wins, so 40 pages at the default read 24 000+characters. Raising the total alone never delivers whole pages while the+ceiling holds, and even with both raised the unit shown is the gathered+chunk or compiled text, so full pages are not promised. A value outside its+range is refused at set time; a stored bad value is ignored for the call,+the default applies and `warnings` carries+`THINK_BUDGET_CONFIG_IGNORED:<key>`. Conversation-type pages (meetings,+chats, transcripts) travel through evidence delivery instead, under+`think.return_unit` and its token budget; the character budget does not+apply to them.++Two optional response fields report what happened:++- `evidence_truncated: boolean` — true when at least one gathered page+ reached the model in part (an excerpt cut at either end, or a delivered+ block cut to its window). False means every gathered unit was shown whole.+- `citations: [{ slug, source_id, row_num }]` — `sources[]` with+ provenance, same order and length: `source_id` is the source the cited+ page was gathered from (the highest-ranked gathered page with that slug);+ `null` when the model cited a slug outside the gather (the response also+ warns `CITATION_NOT_IN_GATHER:<slug>`). `sources: string[]` is unchanged.+#### Answer feedback fields (additive)`recall` (when its `query` arm searched pages on the hybrid path) anddiff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex a62336ad6e..cb31b8ca81 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -8,7 +8,7 @@path name lines justificationsrc/commands/bootstrap.ts runHooks 600 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #4618: --seat/--no-seat parse + refusal/note (logic in core/bootstrap/hooks.ts parseSeatFlags)src/commands/bootstrap.ts runHooks>withLock(#1) 449 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)-src/commands/config.ts runConfig 776 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5232: persistence.write_wait_ms dispatch line (logic in setFileWriteWait); wave 10 collector: master and the #4907/#5958 config-set range refusals compose at 775; re-summed at the #6015 merge (767 master baseline + 4 integration lines); re-summed at the wave 10 merge on actual lines; +1 C4: dream.auto_think.* replacement note (logic in questions/auto-think-migration.ts)+src/commands/config.ts runConfig 781 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5232: persistence.write_wait_ms dispatch line (logic in setFileWriteWait); wave 10 collector: master and the #4907/#5958 config-set range refusals compose at 775; re-summed at the #6015 merge (767 master baseline + 4 integration lines); re-summed at the wave 10 merge on actual lines; +1 C4: dream.auto_think.* replacement note (logic in questions/auto-think-migration.ts); +5 wave 15 P7.4 #5461: set-time refusal of think.pages_budget_chars / think.excerpt_ceiling_chars (range text from think/pages-budget.ts pagesBudgetConfigError)src/commands/doctor/bootstrap-checks.ts bootstrapDoctorChecks 476 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/commands/doctor/checks/extraction-sync.ts checkSyncFreshness 333 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/commands/doctor/report-remote.ts doctorReportRemote 416 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 982303d901..dfbe20f372 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -44,4 +44,4 @@ src/core/search/mode.ts 1594 ratchet +10 System One v1: decide.* snapshot subsetsrc/commands/eval-longmemeval.ts 1519 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts)src/commands/doctor/checks/extraction-sync.ts 1512 ratchet +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import)src/core/search/evidence-delivery.ts 1512 ratchet new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8)-src/commands/config.ts 1511 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook+src/commands/config.ts 1507 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hookdiff --git a/src/commands/autopilot-dispatch.ts b/src/commands/autopilot-dispatch.tsindex 3ad6cde84f..7ff3c3c0f6 100644--- a/src/commands/autopilot-dispatch.ts+++ b/src/commands/autopilot-dispatch.ts@@ -262,15 +262,15 @@ export async function dispatchFreshnessSyncs(if (await isFederatedV2Enabled(engine)) {const attempted = await attemptedConnectorSourceIds(engine).catch(() => null);const sources = await loadAllSources(engine);- const activationPending = await loadActivationPendingSourceIds(engine);- const intervalMs = baseInterval * 1000;- const now = Date.now();// #6451: one status line per tick when the operator turned automatic pulls off.if (await automaticGitPullDisabled(engine)) {process.stderr.write((jsonMode? JSON.stringify({ event: 'git_pull_disabled', key: AUTOPILOT_GIT_PULL_KEY }): `[autopilot] git_pull: off (${AUTOPILOT_GIT_PULL_KEY}=false); remote sources sync their local checkout without pulling`) + '\n');}+ const activationPending = await loadActivationPendingSourceIds(engine);+ const intervalMs = baseInterval * 1000;+ const now = Date.now();for (const src of sources) {if (isConnectorSourceKind(parseSourceConfig(src.config).kind)) {await dispatchConnectorFreshnessSync(queue, src, attempted, activationPending, { intervalMs, now, slot, timeoutMs, jsonMode });diff --git a/src/commands/config.ts b/src/commands/config.tsindex 125fa5a95d..a13db21e91 100644--- a/src/commands/config.ts+++ b/src/commands/config.ts@@ -1264,15 +1264,11 @@ export async function runConfig(engine: BrainEngine, args: string[]) {catch (error) { console.error(`[config] ${(error as Error).message}`); process.exit(1); }}- // #5461: think falls back to the default budget on a malformed value- // (and warns); refuse it here, where the operator can fix it.+ // #5461: think falls back to the default budget on a malformed value (and warns); refuse it here.if (key === 'think.pages_budget_chars' || key === 'think.excerpt_ceiling_chars') {- const { parsePagesBudgetValue, THINK_PAGES_BUDGET_BOUNDS } = await import('../core/think/pages-budget.ts');- if (parsePagesBudgetValue(key, value) === null) {- const { min, max } = THINK_PAGES_BUDGET_BOUNDS[key];- console.error(`[config] ${key} must be an integer between ${min} and ${max} (characters); got ${JSON.stringify(value)}`);- process.exit(1);- }+ const { pagesBudgetConfigError } = await import('../core/think/pages-budget.ts');+ const error = pagesBudgetConfigError(key, value);+ if (error) { console.error(`[config] ${error}`); process.exit(1); }}// Validate sources.default at set time. This key is read bydiff --git a/src/core/cycle/propose-takes.ts b/src/core/cycle/propose-takes.tsindex 642011b477..27f1c66aad 100644--- a/src/core/cycle/propose-takes.ts+++ b/src/core/cycle/propose-takes.ts@@ -916,8 +916,7 @@ class ProposeTakesPhase extends BaseCyclePhase {};}- // Load pages eligible for proposal. Source-scoped per BaseCyclePhase;- // #5213 `cycle.propose_takes.types` narrows the types.+ // Load pages eligible for proposal. Source-scoped per BaseCyclePhase; #5213 types narrow it.const pages = await listCandidatePages(engine, scope, pageLimit, await proposeTakesTypes(engine));if (opts.reporter) {diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex 3843788e86..ec70b0be6e 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -2081,7 +2081,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [},"limit": {"type": "number",- "description": "Version 2 page size (1-100)."+ "description": "Page size or ranked count (1-100)."},"cursor": {"type": "string",@@ -2094,6 +2094,11 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["section": {"type": "string","description": "Only this routing section."+ },+ "query": {+ "type": "string",+ "description": "Version 1 host catalog: rank skills by word overlap with this task (name, triggers, description), drop the rest, cap at limit (default 10). Refused on a shared catalog.",+ "fullSurfaceOnly": true}},"scope": "read",diff --git a/src/core/think/index.ts b/src/core/think/index.tsindex 996a849adc..ed90f1abd4 100644--- a/src/core/think/index.ts+++ b/src/core/think/index.ts@@ -536,6 +536,13 @@ async function persistCitations(* the renderer passes through whole instead of cutting its own excerpts;* auto's unchanged chunks keep the usual excerpts.*/+/** #5461: source-qualify each citation from the gather (the highest-ranked gathered page with that slug; null outside the gather). */+function stampCitationSources(citations: ParsedCitation[], pages: SearchResult[]): void {+ const sourceOfSlug = new Map<string, string>();+ for (const pg of pages) if (!sourceOfSlug.has(pg.slug)) sourceOfSlug.set(pg.slug, pg.source_id ?? 'default');+ for (const c of citations) c.source_id = sourceOfSlug.get(c.page_slug) ?? null;+}+async function renderThinkPages(engine: BrainEngine, opts: RunThinkOpts, pages: SearchResult[], timeZone: string, warnings: string[]): Promise<{ pagesBlock: string; evidenceTruncated: boolean; evidenceDelivery?: DeliveryMeta }> {const [plan, budget] = await Promise.all([resolveEvidencePlan(engine, {@@ -985,10 +992,7 @@ export async function runThink(for (const slug of new Set(resolved.citations.map(c => c.page_slug))) {if (!gatheredSlugs.has(slug)) warnings.push(`CITATION_NOT_IN_GATHER:${slug}`);}- // #5461: source-qualify each citation from the gather (highest-ranked page with that slug).- const sourceOfSlug = new Map<string, string>();- for (const pg of gather.pages) if (!sourceOfSlug.has(pg.slug)) sourceOfSlug.set(pg.slug, pg.source_id ?? 'default');- for (const c of resolved.citations) c.source_id = sourceOfSlug.get(c.page_slug) ?? null;+ stampCitationSources(resolved.citations, gather.pages);// Round-loop scaffolding (rounds > 1 currently re-runs without gap-driven retrieval).// The loop is in place so the v0.29 gap-fill heuristic doesn't change the call site.diff --git a/src/core/think/pages-budget.ts b/src/core/think/pages-budget.tsindex 535737c5fd..7d7b042558 100644--- a/src/core/think/pages-budget.ts+++ b/src/core/think/pages-budget.ts@@ -67,3 +67,10 @@ export async function readThinkPagesBudget(engine: Pick<BrainEngine, 'getConfig'const [totalChars, ceilingChars] = await Promise.all([read(THINK_PAGES_BUDGET_KEY), read(THINK_EXCERPT_CEILING_KEY)]);return { totalChars, ceilingChars };}++/** `gbrain config set` validation: the refusal text for a bad value, or null when it is acceptable. */+export function pagesBudgetConfigError(key: keyof typeof THINK_PAGES_BUDGET_BOUNDS, value: string): string | null {+ if (parsePagesBudgetValue(key, value) !== null) return null;+ const { min, max } = THINK_PAGES_BUDGET_BOUNDS[key];+ return `${key} must be an integer between ${min} and ${max} (characters); got ${JSON.stringify(value)}`;+}diff --git a/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json b/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.jsonindex 9cae80d835..8b99474b3a 100644--- a/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json+++ b/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json@@ -84,8 +84,10 @@"getCalibrationCurve#default": {},"getCalibrationCurve#sourceId": {},"getCalleesOf#bareFallback": {},+ "getCalleesOf#chunkId": {},"getCalleesOf#default": {},"getCalleesOf#sourceId": {},+ "getCallersOf#chunkId": {},"getCallersOf#default": {},"getCallersOf#sourceId": {},"getChunkWindows#default": {},diff --git a/test/fixtures/goldens/rls-scope-inventory.json b/test/fixtures/goldens/rls-scope-inventory.jsonindex a43d472317..d8fb40bdf3 100644--- a/test/fixtures/goldens/rls-scope-inventory.json+++ b/test/fixtures/goldens/rls-scope-inventory.json@@ -734,6 +734,17 @@],"flagOnScopes": []},+ "getCalleesOf#chunkId": {+ "flagOffLanes": [+ "pool"+ ],+ "flagOffOpensTransaction": false,+ "flagOn": "unscoped",+ "flagOnLanes": [+ "pool"+ ],+ "flagOnScopes": []+ },"getCalleesOf#default": {"flagOffLanes": ["pool"@@ -756,6 +767,17 @@],"flagOnScopes": []},+ "getCallersOf#chunkId": {+ "flagOffLanes": [+ "pool"+ ],+ "flagOffOpensTransaction": false,+ "flagOn": "unscoped",+ "flagOnLanes": [+ "pool"+ ],+ "flagOnScopes": []+ },"getCallersOf#default": {"flagOffLanes": ["pool"