Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(minions): deterministic refusals end jobs at once; dream synthesize no longer cancels every child over one bad payload (#7239, #7240)

garrytanbd54c5451762
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.md
index 0887ef07a1..05a1184c9d 100644
--- a/docs/architecture/key-files/commands-1.md
+++ b/docs/architecture/key-files/commands-1.md
@@ -22,7 +22,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; it also adds `global_maintenance`, the daemon's latest stall verdict (`readGlobalMaintenanceVerdict` in `src/core/minions/global-maintenance-stall.ts`, null when absent or older than a day), and a non-ok verdict turns exit 0 into 1 (`autopilotStatusExitCode(state, stalled)`); 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. The queued drain's `window` and `timeout_ms` are co-stamped by `resolveAutopilotAutoDrainBounds` (`autopilot-timeout.ts`): the deadline is at least the window plus twice the gateway's `AI_CHAT_TIMEOUT_MS` plus 60 s, because the drain hard-stops at its job deadline (#5809) and checks the window only between items; the window is clamped (to at least 1 s) so that deadline fits the full-cycle anchor (1140 s at the default chat timeout), and a longer interval-derived deadline still wins. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`, `test/autopilot-auto-drain-dispatch.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`. `--install` without `--repo` uses `sync.repo_path`, else the default source's `local_path` (`src/commands/autopilot/install-repo.ts`), and refuses when neither is set; pinned by `test/autopilot-install-repo-fallback-6755.test.ts`. Pinned by `test/autopilot-install-id.test.ts` and `test/e2e/autopilot-multi-brain.serial.test.ts`. GBRA-133 PR 2a additions: [commit-notifier.md](commit-notifier.md#autopilot-and-the-jobs-worker).
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, --retry-global; 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. After the brain-wide maintenance dispatch on the full-cycle branch it writes the stall verdict file (`recordGlobalMaintenanceStallStatus`, GBRA-130 C-6) that `autopilot --status` reads; a failed write is logged (`global_maintenance_verdict_failed` under `--json`) and leaves the previous verdict to expire. 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`. GBRA-133 PR 2a additions: [commit-notifier.md](commit-notifier.md#autopilot-and-the-jobs-worker).
+- `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. After the brain-wide maintenance dispatch on the full-cycle branch it writes the stall verdict file (`recordGlobalMaintenanceStallStatus`, GBRA-130 C-6) that `autopilot --status` reads; a failed write is logged (`global_maintenance_verdict_failed` under `--json`) and leaves the previous verdict to expire. 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`. GBRA-133 PR 2a additions: [commit-notifier.md](commit-notifier.md#autopilot-and-the-jobs-worker). #7239: `readSyncRefusalHolds` holds a source's freshness sync after a refused sync job for the failure cooldown of its refusal count (`freshness_sync_refused`).
- `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-cycle-patterns.md b/docs/architecture/key-files/core-cycle-patterns.md
index 957ba9eec0..e7895d0f92 100644
--- a/docs/architecture/key-files/core-cycle-patterns.md
+++ b/docs/architecture/key-files/core-cycle-patterns.md
@@ -15,7 +15,7 @@ Patterns, drift reports and the cycle modules listed after them.
- `src/core/cycle/attribution-checks.ts` — #5425 [UC4]: `dream.attribution_checks` (`ATTRIBUTION_CHECKS_KEY`, registered in `KNOWN_CONFIG_KEYS`; `config set` takes a boolean word through `CYCLE_GUARDED_KEYS` in `cycle/config-guards.ts`), the one default-off switch for the two mechanical attribution checks: the propose_takes holder downgrade (`propose-takes-attribution.ts`) and the synthesis `superseded_in_source` quarantine (`synthesize-verify.ts`). `attributionChecksEnabled(engine)` is `isConfigTruthy` over the stored value and false on any read error. The default flips only on a held-out gbrain-evals receipt, the same bar as the prompt rules `dream.synthesize.attribution_rules` / `dream.propose_takes.attribution_rules`.
- `src/core/cycle/propose-takes-attribution.ts` — #5425 [UC4]: `downgradeAssistantOnlyHolders(proposals, pageBody)`, called once from `propose-takes.ts` right after the extractor returns when `dream.attribution_checks` is on. `claimContentTokens` takes a claim's numeric keys (`numericClaims`: currency, scaled amounts, percents, dates, 4+ digit numbers; bare years dropped) and its quoted phrases (`extractQuoteSpans`, normalized); `statedBySpeaker` credits each token to the speakers whose turns state it, plus a speaker who explicitly accepted the previous turn. A `people/<slug>` proposal every one of whose stated tokens was stated only by `assistant` is returned with holder `brain`; a token the user stated or accepted, a claim with no tokens, tokens no turn states, a page without speaker turns, and non-person holders leave the proposal untouched. Pure: returns the input array when nothing changes. Pinned by `test/propose-takes-attribution.test.ts` (standalone) and `test/propose-takes-attribution-callsite.test.ts` (the call, `test.todo` until the wave 13 hunk lands).
- `src/core/cycle/synthesize-verify-epochs.ts` — the scope side of dream-page verification, peeled move-only from `synthesize-verify.ts` (module-size ratchet) and re-exported from it: `readVerifyEpoch`, `loadChildWriteEpochs`, `loadPreRunRevision`, `isDreamOwnedPage`, `resolveVerifyPrior`, exactly as described under `synthesize-verify.ts` above. Pure database reads; no claim check lives here.
-- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached as verdicts: `triage-backoff.ts` upserts a score-NULL backoff marker instead and the next passes report the file `deferred` with `code: 'triage_unreliable_backoff'` (counted in `details.triage.unreliable_backoff`, not in `deferred`, so the cooldown and autopilot's maintenance stamp are not held) without a judge call until the backoff ends; nor is a verdict a `chat_fallback_chain` model gave (`TriageResult.answeredBy`, from the judge client's `answered_by` marker): it decides the run and the next cycle re-judges on the configured model. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the... (line truncated to 2000 chars)
+- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached as verdicts: `triage-backoff.ts` upserts a score-NULL backoff marker instead and the next passes report the file `deferred` with `code: 'triage_unreliable_backoff'` (counted in `details.triage.unreliable_backoff`, not in `deferred`, so the cooldown and autopilot's maintenance stamp are not held) without a judge call until the backoff ends; nor is a verdict a `chat_fallback_chain` model gave (`TriageResult.answeredBy`, from the judge client's `answered_by` marker): it decides the run and the next cycle re-judges on the configured model. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the... (line truncated to 2000 chars) #7240: a transcript whose child cannot be queued (any error but a lost connection or cancellation) is skipped `submit_failed (<code>)` with its own fresh chunks rolled back, and the fan-out continues instead of failing the phase, whose private-queue cleanup would cancel every child already queued (`test/dream-synthesize-submit-failure-7240.test.ts`).
- `src/core/cycle/transcript-discovery.ts` — Pure filesystem walk for synthesize. `discoverTranscripts(opts)` filters `.txt` files by date range, min_chars, and word-boundary regex `excludePatterns` (`medical` matches "medical advice" but NOT "comedical"; power users may pass full regex). `readSingleTranscript(path)` is the `gbrain dream --input <file>` ad-hoc path. Self-consumption guard: `DREAM_OUTPUT_MARKER_RE` (anchored at frontmatter open `---\n`, optional BOM + CRLF tolerance, scans first 2000 chars for `dream_generated: true` with case-insensitive value and word boundary on `true`) drives `isDreamOutput(content, bypass=false)`. Both functions skip matching files and emit a `[dream] skipped <basename>: dream_generated marker` stderr log (no silent skips). An `excludePatterns` hit is never logged per file (the matching files are sensitive by definition); instead both functions emit ONE `[dream] excluded N transcript(s) matching exclude_patterns (<label>: n, ...)` stderr line at the end of discovery, naming only the count and the configured pattern labels that fired, never a path, basename, or content. `DEFAULT_EXCLUDE_PATTERNS` is unchanged (`medical`, `therapy`). `bypassGuard?: boolean` on `DiscoverOpts` and `readSingleTranscript`'s opts disables the guard for the explicit `--unsafe-bypass-dream-guard` escape hatch only — never auto-applied for `--input`. Two path-level guards run before the content read: `selfCaptureSessionIds` (from `claudeCliSelfSessionIds`) skips a `.txt` corpus file (session-end, checkpoint segment or writeback form, via `corpusFileSessionId`) captured from gbrain's own claude-cli call, and `excludeDirs` (synthesize passes the reflections, originals, patterns-output and cycle-summary directories under `brainDir`, empty under `--unsafe-bypass-dream-guard`) skips any file whose resolved path sits inside one, so an output a failed postprocess left unmarked is never re-synthesized while a transcript that merely names such a path is still disc... (line truncated to 2000 chars)
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.md
index 986e328d42..36d9eeac8e 100644
--- a/docs/architecture/key-files/core-cycle.md
+++ b/docs/architecture/key-files/core-cycle.md
@@ -30,7 +30,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/cycle/extract-facts.ts` — source-scoped `## Facts` fence reconciliation. Rows are keyed by fence row number, never by claim text: a DB row whose `(row_num, claim)` is still in the fence keeps its id and has its other cells updated in place (ids from recall stay valid for forget; `source_session`, `created_at`, consolidation state and vectors survive), a row whose number left the fence or whose claim was rewritten is expired and detached (`row_num` NULL), never deleted, and only new row numbers insert. Duplicate ACTIVE rows with the same claim and source index once; a struck history row never collapses onto an active row with the same text, so a claim that reverts (NYC → SF → NYC) stays active. `superseded by #N` links resolve on every hop of a chain (`supersede-resolve.ts`; forgotten targets and cycles still resolve to NULL with a warning). Each run first fences the source's unfenced rows (`row_num IS NULL`, live entity page, never ontology observations: `dimension IS NULL`, #6264) through `facts/unfenced-facts.ts` and adds those pages to the run's reconcile set (`unfencedRowsFenced`); rows it cannot fence this run (canonical file not on this host, malformed fence, held page lock, a claim the fence codec cannot render) are named as `FACTS_FENCE_FAILED: <slug> (<reason>)` and keep their own page out of the destructive reconcile (the empty-fence guard, per page since #6278: `pendingLegacyRows` lists the pages, `legacyRowsPending` and `legacyPages` report them, and every other page of the source still reconciles; the page keeps its fact index because reconciliation would classify its `row_num IS NULL` rows as stale and expire them). The phantom-redirect pass moves rows by fence position and so still waits until the source has no unfenced rows. `runPhaseExtractFacts` (`cycle.ts`) then reports the reconcile counts of the pages that did reconcile and names the skipped pages in its summary. Rows with no backing page or checkout, and ontology observations, never gate. It then expires (without detaching) the active fence-owned rows of soft-deleted pages in the source; restoring the page re-activates them on its next reconcile. Previously embedded fact rows and their text/provenance remain intact when a full valid replacement embedding batch is unavailable; old vectors are never transplanted to changed text/model. Restrictive fence changes still expire removed/withdrawn claims and tighten visibility before deferral. Provider cancellation within database writes rolls back rather than publishing half a replacement. Keyless initial fact insertion remains supported; conversation-origin facts without a fence are not wiped by fence reconciliation. Each page reconciles in isolation: a page whose writes the database rejects rolls back, is reported as `<slug>: FACTS_RECONCILE_FAILED: …` (counted in `pagesFailed`, booked as a halt in the rollup), and later pages still reconcile. `facts.superseded_by` is `ON DELETE SET NULL`. On an unmanaged brain each reconcile records its outcome in `page_facts_reconcile` (`src/core/facts/reconcile-watermark.ts`): a complete reconcile (including a no-op) stamps the page's `knowledge_revision` inside the write transaction, after a `FOR SHARE` lock and a revision recheck (a moved page writes nothing and stays due); `deferred` (lock, stale cache, embedding deferral, rejected write), `invalid` (malformed or misplaced fence, not retried until the page changes) and `cancelled` leave it due. The dream cycle passes `drain`, so an incremental run also reconciles up to 250 due pages within 60 s, never-attempted first then oldest attempt, after settling in bulk the due pages with no fence marker and no fence rows; a fence imported by a standalone sync or removed from a page is therefore reconciled even when the cycle's own sync changed nothing. A direct call with `slugs: []` and no `drain` still reconciles nothing. Doctor's `extract_health` names unreconciled fence pages and unreadable fences on unmanaged brains. Tests: `test/extract-facts-reconcile-drain.test.ts` (Postgres race through `test/e2e/extract-facts-reconcile-drain-postgres.test.ts`), `test/e2e/fact-vector-repair-parity.test.ts`, `test/extract-facts-phase.test.ts`, `test/extract-facts-unfenced-rows.test.ts` (a mixed page, on PGLite and through the Postgres E2E), `test/extract-facts-poison-page.test.ts`, `test/extract-facts-stable-identity.test.ts`. On a managed brain the same reconcile runs after `managedDerivedFactsPreflight` (local writer, active source, before any embedding call): each page transaction and the deleted-page expiry commit inside `withDerivedFactsWrite` (coordinator source capability, page key locked); the facts receipt page is skipped, the rollup is still booked. Each deleted page's expiry is one item (ItemRun site `extract_facts.expire_deleted`, src/core/item-failure.ts): a refused expiry is a `FACTS_EXPIRE_FAILED: <slug>: <code>: …` warning (the phase warns) retried by the next run, a page the refusal breaker holds back is a `FACTS_EXPIRE_SKIPPED` warning, and run-scoped errors or most pages failing (`item_failures_systemic`) still fail the phase; test `test/pathological/a21-facts-expire-deleted.test.ts`. It is distinct from the coordinated `extract_facts` operation and durable page backstop. Tests: `test/managed-facts-writers.test.ts`. Wave B PR 2 (lane 2e2): a segmented page reconciles like an inline one, its fences read from its marker segments (`segmentedFactsFenceView`), its write guarded by content hash and size, and its stale-cache check streamed against the canonical file (`segmentedBodyMatchesFile`, page-body/segment-facts.ts); test `test/large-pages/segmented-facts-reconcile.test.ts`. #6259: it and `extract-takes.ts` (both the DB walk and the file walk, which checks the stored page) skip a quarantined page, leaving rows projected before it was quarantined as they are. Test: `test/quarantine-fence-projection.test.ts`. #6946: a gbrain-owned `--url` clone on an unmanaged brain never gates the empty-fence guard (its facts are database-only by design).
-- `src/core/cycle/inline-drain.ts` — the dream cycle's private-queue drain. `runSubagentsInline(engine, queue, queueName, yieldDuringPhase?, handler?, lockMs?, concurrency?)` runs N independent `drainLoop`s (`dream.synthesize.inline_concurrency`, clamp [1,8], PGLite forced serial at the callsite) sharing the queue via the same SKIP-LOCKED claim fencing workers use — everything job-scoped (lockToken, abort, timeout timer, keepalive, renewTimer, outcome recording) stays loop-local. Pool hygiene: global housekeeping sweeps are leader-only (loop 0) while `promoteDelayed` runs in every loop; idle claim-poll backs off 1s→5s; a NON-retryable loop-level failure aborts siblings after their current child (a failing child is a job outcome, never a drain crash). Exit only when the queue holds no active/waiting/delayed child (a lease-full bounce's delayed backoff must not strand a child). Outcome routing mirrors the worker: `UnrecoverableError` → dead immediately; `RateLeaseUnavailableError` → `releaseLeaseFullJob` requeue without burning an attempt; timeout terminal. Handler invocation is wrapped in `withChatPhase('job:<name>')` (worker.ts parity) so each drained child's gateway spend is attributed to the CHILD — a bare `await handler(context)` inherits the caller's AsyncLocalStorage phase, and a cycle phase that wraps its own work (dream synthesize wraps `phase:synthesize`) would absorb every child's spend into the phase tag. `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) and the null-safe nearest-rank `percentile()` telemetry helper are exported. Pinned by `test/cycle-synthesize-inline-concurrency.test.ts` (loop semantics) + `test/e2e/dream-synthesize-concurrency-postgres.test.ts` (real-Postgres exact-once + lease-ceiling).
+- `src/core/cycle/inline-drain.ts` — the dream cycle's private-queue drain. `runSubagentsInline(engine, queue, queueName, yieldDuringPhase?, handler?, lockMs?, concurrency?)` runs N independent `drainLoop`s (`dream.synthesize.inline_concurrency`, clamp [1,8], PGLite forced serial at the callsite) sharing the queue via the same SKIP-LOCKED claim fencing workers use — everything job-scoped (lockToken, abort, timeout timer, keepalive, renewTimer, outcome recording) stays loop-local. Pool hygiene: global housekeeping sweeps are leader-only (loop 0) while `promoteDelayed` runs in every loop; idle claim-poll backs off 1s→5s; a NON-retryable loop-level failure aborts siblings after their current child (a failing child is a job outcome, never a drain crash). Exit only when the queue holds no active/waiting/delayed child (a lease-full bounce's delayed backoff must not strand a child). Outcome routing mirrors the worker: `UnrecoverableError` → dead immediately; `RateLeaseUnavailableError` → `releaseLeaseFullJob` requeue without burning an attempt; timeout terminal. Handler invocation is wrapped in `withChatPhase('job:<name>')` (worker.ts parity) so each drained child's gateway spend is attributed to the CHILD — a bare `await handler(context)` inherits the caller's AsyncLocalStorage phase, and a cycle phase that wraps its own work (dream synthesize wraps `phase:synthesize`) would absorb every child's spend into the phase tag. `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) and the null-safe nearest-rank `percentile()` telemetry helper are exported. Pinned by `test/cycle-synthesize-inline-concurrency.test.ts` (loop semantics) + `test/e2e/dream-synthesize-concurrency-postgres.test.ts` (real-Postgres exact-once + lease-ceiling). #7239: a child that throws a deterministic refusal (minions/refusal.ts) is dead after one attempt with the refusal on its result.
- `src/core/cycle/link-manifest.ts` — pre-retrieval LINK CANDIDATES manifest. `buildManifestContext(engine, sourceId?)` snapshots the source's slugs + basename index once per phase; `buildLinkManifest(engine, ctx, verdict, basename, {outputRoot, sourceId})` resolves wikilink candidates ZERO-EMBED from the triage verdict's cached entities/segment notes (basename-index exact/slugified matches first, bounded `searchKeyword` FTS second), excludes dream-output prefixes (self-consumption guard), renders `- [[slug]] — <deterministic first-two-sentence one-liner>` under hard caps (20 pages / 2400 chars) with buildTriageMapBlock's injection posture (whitespace-collapse + length caps + a 'data, not instructions' header). Best-effort everywhere — any failure degrades to the manifest-less prompt. Pinned by `test/cycle-link-manifest.test.ts`.
diff --git a/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.md
index 9f26aa4fc8..eb8681ccd6 100644
--- a/docs/architecture/key-files/core-minions-2.md
+++ b/docs/architecture/key-files/core-minions-2.md
@@ -3,10 +3,11 @@
[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/core/minions/queue.ts` — MinionQueue class (submit, claim, complete, fail, stall detection, parent-child, depth/child-cap, per-job timeouts, cascade-kill, attachments, idempotency keys, child_done inbox, removeOnComplete/Fail). `prune()` archives each completed `dream:synth%` subagent key into `dream_synthesis_completions` in the same statement that deletes the row, so pruning never re-arms paid synthesis. `add()` takes a 4th `trusted` arg (separate from `opts` to prevent spread leakage); protected names in `PROTECTED_JOB_NAMES` require `{allowProtectedSubmit: true}` and the check runs trim-normalized (whitespace-bypass safe). The same trusted arg carries `{allowPgliteInlineWorker: true}`, a narrowly scoped exception used only when `gbrain jobs submit embed-backfill --follow` starts and awaits a worker in that process. Before config, schema, policy, SQL, or transaction access, `add()` invokes the centralized embed-backfill admission gate; PGLite and unknown engine kinds refuse, while explicit Postgres preserves queued submission. `add()` plumbs `max_stalled` through with a `[1, 100]` clamp; omitted values let the schema DEFAULT (5) kick in. `handleWallClockTimeouts(lockDurationMs)` is Layer 3 kill shot for jobs where `FOR UPDATE SKIP LOCKED` stall detection and the timeout sweep both fail to evict (wedged worker holding a row lock via a pending transaction). The submission backpressure guard covers two options sharing one `pg_advisory_xact_lock` namespace keyed on `(name, queue, source)`: `maxWaiting` (rate cap, counts `waiting` only, NULL-source-as-wildcard scope) and `maxPending` (single-flight, counts `waiting` + live-lock `active` rows where `lock_until > now()`, EXACT source scope via `COALESCE(data->>'sourceId', data->>'source_id')` — an expired-lock active never suppresses, keeping the waitingClaimable wedge detectors fed). All three coalesce return paths (idempotency fast-path, cap-hit, ON CONFLICT race fallback) stamp non-persisted `coalesced: true` metadata on the returned job. Both filter on `queue` in addition to `name` so cross-queue same-name jobs don't suppress each other. `claim` and `renewLock` issue their UPDATE via `engine.executeRawDirect` (not `executeRaw`) so the lock heartbeat runs on the direct session-mode pool that the transaction pooler won't recycle mid-hold; on PGLite this is identical to `executeRaw`. The two terminal dead-letter paths (`handleWallClockTimeouts` wall-clock kill and the stall dead-letter CTE in the stall sweep) BOTH increment `attempts_made` so a long job killed there reads as an honest attempt instead of `attempts 0 / started N`; the stall path also bumps `stalled_counter`, surfaced by `gbrain jobs get` as `Attempts: M/N (started: X, stalled: S/MaxS)`. At submit, `add()` stamps a default `timeout_ms` via `defaultTimeoutMsFor(jobName)` (from `handler-timeouts.ts`) when the caller passed none, and `claim()` COALESCEs a still-NULL `timeout_ms` from `HANDLER_DEFAULT_TIMEOUT_MS` (raw-object jsonb bind) deriving `timeout_at` from the coalesced value — the durable invariant covering rows that predate submit-time stamping; an explicit `opts.timeout_ms` always wins. The lock lease follows the identical three-layer shape: `add()` stamps `opts.lock_duration_ms` (clamped [5s,1h] via the shared `clampLockDurationMs`; INSERT-only — an idempotency-key re-submit never mutates the first submitter's lease) else `defaultLockDurationMsFor(jobName)`; `claim()` derives `lock_until` from `COALESCE(lock_duration_ms, map, worker default)` and stamps the resolved lease, SQL-clamping the row/map-resolved value to [5s,1h] (the worker-default fallback passes through unclamped — operator-configured, and tests legitimately use sub-5s leases) so a bypass-written out-of-range row can't produce a pathological lease; `handleWallClockTimeouts`' null-timeout fallback uses `COALESCE(lock_duration_ms, worker default)`. `handleStalled(graceMsOverride?)` applies the stall-sweep reclaim grace (`GBRAIN_MINION_STALL_RECLAIM_GRACE_MS`, default 15s, 0 = legacy predicate, capped at 600s with a warn-once clamp so an oversized value can't disable stalled-job recovery) to all three sweep predicates — a lease that lapsed within the grace is a starved owner's head start, not a steal candidate. Guarded by `test/queue-lock-retry.test.ts` (claim never falls back to `executeRaw`), `test/postgres-execute-raw-direct.test.ts` (routing decision matrix), and `test/minions.test.ts` (attempt accounting + default-timeout stamping). `MinionQueue.add()` gates `subagent` jobs on capability, not provider: `data.model` is classified via `classifyCapabilities()` (lazy-imported from `src/core/ai/capabilities.ts` to keep queue's eager-load surface small) and rejected only when the model cannot run a tool loop (`unusable:no_tools`) or names an unknown provider; degraded verdicts pass through with a gateway cost warning. Layer 1 of the three-layer subagent capability enforcement (layers 2+3: `model-config.ts:enforceSubagentCapable` runtime fallback + `src/commands/doctor/checks/search-eval.ts` `subagent_capability` check). Pinned by `test/agent-cli.test.ts`. All three terminal reaper paths (stall dead-letter, wall-clock kill, cascade) route through the ONE private `killJobs(tx, rows, cause, message)` tail: it emits `child_done(outcome)` to each non-terminal parent's inbox and flips any `waiting-children` parent whose last open child just died back to `waiting` — so a dead-lettered child can never strand its aggregator parent. Callers lock parents FIRST via `lockParentsOrdered` (ascending-id row locks, matching `failJob`'s parent-before-child order) so the reapers and `failJob` can never deadlock on parent/child lock acquisition. An idempotent stranded-parent sweep runs once per stall tick (~30s): any `waiting-children` parent with zero non-terminal children flips back to `waiting` (single UPDATE, NOT EXISTS on an indexed FK) — self-heals every stranding class, including parents stranded before the sweep existed. Every automatic re-run path clears `started_at` (`failJob`'s delayed retry branch, the stall requeue, lease release, `promoteDelayed`, and the parent-unblock flips) so the per-attempt wall clock measures execution, not backoff/queue wait — a retried job can't be dead-lettered by the wall-clock sweep before executing a line. Pinned by `test/queue-stall-parent-unblock.test.ts` + `test/queue-started-at-retry.test.ts`. `renewLock` accepts optional `{signal}` forwarded to executeRawDirect so the renewal tick's timeout race CANCELS a hung UPDATE instead of orphaning a checked-out pool slot (best-effort — the token fence is the correctness authority; a late-landing renewal can only extend a lease nobody else claimed). Re-submitting an idempotency key held by a dead or cancelled row nulls that row's key and records it as `data.__released_idempotency_key`, so the dream paid-loop breaker and daily cap still see the death. The trusted arg's `spendAuthorization` stores a consent-gated producer's record in `spend_authorization` (never job data); a coalesced live row with no record or a `legacy_default` record adopts it by compare-and-set, an `authorized` row keeps its own. `claim()` sets `spend_claim_token = claim_generation + 1` (the fence the protocol trigger requires for spend-authorized rows, so older workers cannot claim them) and stamps NULL rows of `book-mirror:`/`enrich:`/`cli:enrich:` keys `legacy_default` in the same UPDATE. `claim(..., { excludeWatchdogSuspects })` skips jobs carrying `WATCHDOG_SUSPECT_MARK` (re-exported from `watchdog-attribution.ts`) for a worker with jobs in flight; `releaseWatchdogClaim` is the token-fenced uncharged release; `handleStalled` first passes its candidates to `requeueCoRunnerStalls`.
+- `src/core/minions/queue.ts` — MinionQueue class (submit, claim, complete, fail, stall detection, parent-child, depth/child-cap, per-job timeouts, cascade-kill, attachments, idempotency keys, child_done inbox, removeOnComplete/Fail). `prune()` archives each completed `dream:synth%` subagent key into `dream_synthesis_completions` in the same statement that deletes the row, so pruning never re-arms paid synthesis. `add()` takes a 4th `trusted` arg (separate from `opts` to prevent spread leakage); protected names in `PROTECTED_JOB_NAMES` require `{allowProtectedSubmit: true}` and the check runs trim-normalized (whitespace-bypass safe). The same trusted arg carries `{allowPgliteInlineWorker: true}`, a narrowly scoped exception used only when `gbrain jobs submit embed-backfill --follow` starts and awaits a worker in that process. Before config, schema, policy, SQL, or transaction access, `add()` invokes the centralized embed-backfill admission gate; PGLite and unknown engine kinds refuse, while explicit Postgres preserves queued submission. `add()` plumbs `max_stalled` through with a `[1, 100]` clamp; omitted values let the schema DEFAULT (5) kick in. `handleWallClockTimeouts(lockDurationMs)` is Layer 3 kill shot for jobs where `FOR UPDATE SKIP LOCKED` stall detection and the timeout sweep both fail to evict (wedged worker holding a row lock via a pending transaction). The submission backpressure guard covers two options sharing one `pg_advisory_xact_lock` namespace keyed on `(name, queue, source)`: `maxWaiting` (rate cap, counts `waiting` only, NULL-source-as-wildcard scope) and `maxPending` (single-flight, counts `waiting` + live-lock `active` rows where `lock_until > now()`, EXACT source scope via `COALESCE(data->>'sourceId', data->>'source_id')` — an expired-lock active never suppresses, keeping the waitingClaimable wedge detectors fed). All three coalesce return paths (idempotency fast-path, cap-hit, ON CONFLICT race fallback) stamp non-persisted `coalesced: true` metadata on the returned job. Both filter on `queue` in addition to `name` so cross-queue same-name jobs don't suppress each other. `claim` and `renewLock` issue their UPDATE via `engine.executeRawDirect` (not `executeRaw`) so the lock heartbeat runs on the direct session-mode pool that the transaction pooler won't recycle mid-hold; on PGLite this is identical to `executeRaw`. The two terminal dead-letter paths (`handleWallClockTimeouts` wall-clock kill and the stall dead-letter CTE in the stall sweep) BOTH increment `attempts_made` so a long job killed there reads as an honest attempt instead of `attempts 0 / started N`; the stall path also bumps `stalled_counter`, surfaced by `gbrain jobs get` as `Attempts: M/N (started: X, stalled: S/MaxS)`. At submit, `add()` stamps a default `timeout_ms` via `defaultTimeoutMsFor(jobName)` (from `handler-timeouts.ts`) when the caller passed none, and `claim()` COALESCEs a still-NULL `timeout_ms` from `HANDLER_DEFAULT_TIMEOUT_MS` (raw-object jsonb bind) deriving `timeout_at` from the coalesced value — the durable invariant covering rows that predate submit-time stamping; an explicit `opts.timeout_ms` always wins. The lock lease follows the identical three-layer shape: `add()` stamps `opts.lock_duration_ms` (clamped [5s,1h] via the shared `clampLockDurationMs`; INSERT-only — an idempotency-key re-submit never mutates the first submitter's lease) else `defaultLockDurationMsFor(jobName)`; `claim()` derives `lock_until` from `COALESCE(lock_duration_ms, map, worker default)` and stamps the resolved lease, SQL-clamping the row/map-resolved value to [5s,1h] (the worker-default fallback passes through unclamped — operator-configured, and tests legitimately use sub-5s leases) so a bypass-written out-of-range row can't produce a pathological lease; `handleWallClockTimeouts`' null-timeout fallback uses `COALESCE(lock_duration_ms, worker default)`. `handleStalled(graceMsOverride?)` applies the stall-sweep reclaim grace (`GBRAIN_MINION_STALL_RECLAIM_GRACE_MS`, default 15s, 0 = legacy predicate, capped at 600s with a warn-once clamp so an oversized value can't disable stalled-job recovery) to all three sweep predicates — a lease that lapsed within the grace is a starved owner's head start, not a steal candidate. Guarded by `test/queue-lock-retry.test.ts` (claim never falls back to `executeRaw`), `test/postgres-execute-raw-direct.test.ts` (routing decision matrix), and `test/minions.test.ts` (attempt accounting + default-timeout stamping). `MinionQueue.add()` gates `subagent` jobs on capability, not provider: `data.model` is classified via `classifyCapabilities()` (lazy-imported from `src/core/ai/capabilities.ts` to keep queue's eager-load surface small) and rejected only when the model cannot run a tool loop (`unusable:no_tools`) or names an unknown provider; degraded verdicts pass through with a gateway cost warning. Layer 1 of the three-layer subagent capability enforcement (layers 2+3: `model-config.ts:enforceSubagentCapable` runtime fallback + `src/commands/doctor/checks/search-eval.ts` `subagent_capability` check). Pinned by `test/agent-cli.test.ts`. All three terminal reaper paths (stall dead-letter, wall-clock kill, cascade) route through the ONE private `killJobs(tx, rows, cause, message)` tail: it emits `child_done(outcome)` to each non-terminal parent's inbox and flips any `waiting-children` parent whose last open child just died back to `waiting` — so a dead-lettered child can never strand its aggregator parent. Callers lock parents FIRST via `lockParentsOrdered` (ascending-id row locks, matching `failJob`'s parent-before-child order) so the reapers and `failJob` can never deadlock on parent/child lock acquisition. An idempotent stranded-parent sweep runs once per stall tick (~30s): any `waiting-children` parent with zero non-terminal children flips back to `waiting` (single UPDATE, NOT EXISTS on an indexed FK) — self-heals every stranding class, including parents stranded before the sweep existed. Every automatic re-run path clears `started_at` (`failJob`'s delayed retry branch, the stall requeue, lease release, `promoteDelayed`, and the parent-unblock flips) so the per-attempt wall clock measures execution, not backoff/queue wait — a retried job can't be dead-lettered by the wall-clock sweep before executing a line. Pinned by `test/queue-stall-parent-unblock.test.ts` + `test/queue-started-at-retry.test.ts`. `renewLock` accepts optional `{signal}` forwarded to executeRawDirect so the renewal tick's timeout race CANCELS a hung UPDATE instead of orphaning a checked-out pool slot (best-effort — the token fence is the correctness authority; a late-landing renewal can only extend a lease nobody else claimed). Re-submitting an idempotency key held by a dead or cancelled row nulls that row's key and records it as `data.__released_idempotency_key`, so the dream paid-loop breaker and daily cap still see the death. The trusted arg's `spendAuthorization` stores a consent-gated producer's record in `spend_authorization` (never job data); a coalesced live row with no record or a `legacy_default` record adopts it by compare-and-set, an `authorized` row keeps its own. `claim()` sets `spend_claim_token = claim_generation + 1` (the fence the protocol trigger requires for spend-authorized rows, so older workers cannot claim them) and stamps NULL rows of `book-mirror:`/`enrich:`/`cli:enrich:` keys `legacy_default` in the same UPDATE. `claim(..., { excludeWatchdogSuspects })` skips jobs carrying `WATCHDOG_SUSPECT_MARK` (re-exported from `watchdog-attribution.ts`) for a worker with jobs in flight; `releaseWatchdogClaim` is the token-fenced uncharged release; `handleStalled` first passes its candidates to `requeueCoRunnerStalls`. #7240: `add` passes job data through `jsonbSafeJson` (text-safe.ts: lone UTF-16 surrogates and U+0000 become U+FFFD), because Postgres refuses either inside a JSONB value (22P02/22P05) and one such character refused the whole insert; `failJob` takes an optional `result` (a refused job's `refusal`, #7239).
- `src/core/minions/rate-leases.ts` — lease-based concurrency cap for outbound providers (default key `anthropic:messages`, max via `GBRAIN_ANTHROPIC_MAX_INFLIGHT`). Owner-tagged rows with `expires_at` auto-prune on acquire; `pg_advisory_xact_lock` guards check-then-insert; CASCADE on owning job deletion. `renewLeaseWithBackoff` retries 3x (250/500/1000ms). Canonical home of `RateLeaseUnavailableError` (thrown when acquire finds no slot; the worker and the inline dream drain both recognize it and requeue WITHOUT burning an attempt — lease-full is a scheduling condition, not a failure; `subagent.ts` re-exports it for compatibility) and `leaseFullBackoffMs()` (the shared 1–3s jittered lease-full requeue backoff `worker.ts` and `inline-drain.ts` both use, so the two curves cannot silently desync).
+- `src/core/minions/refusal.ts` — #7239: `jobRefusal(err)` decides whether a handler error is a deterministic refusal from its error-registry code: a site `retryable` wins, else a caller/consent/host_only code the registry does not mark retryable, except the concurrency codes (`revision_conflict`, `page_identity_changed`, `concurrent_write`); classes retryable/server/unavailable, unregistered codes and code-less errors are not (a code-less error is looked through to its `cause`; other `UnrecoverableError`s keep their own path). The worker's executeJob catch and the dream inline drain end such a job `dead` after one attempt with `refusedJobResult` (`job_outcome: 'refused'`, `refusal: {code, reason, message, fix, docs_cmd}`); the suggestion prose is never stored (job rows are served remotely). Across the per-job child boundary it travels as errorKind `refused` and is rebuilt as `JobRefusedError` (errors.ts). Tests: `test/minions-refusal-7239.test.ts`.
- `src/core/minions/rss-default.ts` — cgroup-aware auto-sized default for the worker RSS watchdog cap. `resolveDefaultMaxRssMb(opts?)` / `describeDefaultMaxRss(opts?)` (provenance for the startup log) / `readCgroupMemLimitBytes(readFile?)`. Used at every spawn site (`jobs work`, `jobs supervisor`, autopilot, `MinionSupervisor`). Formula `clamp(round(0.5 × basisMB), 4096, 16384)` where `basis = min(cgroupLimit, totalmem)`. LOAD-BEARING NUANCE: plain `os.totalmem()` reports HOST RAM, so in a 4GB cgroup on a 126GB host it would pick 16GB, the watchdog would never fire, and the kernel OOM-killer would SIGKILL at 4GB. The cap MUST sit below the real ceiling so the graceful drain (distinct exit code, loud log) beats the kernel's silent kill; the 4096 floor applies only when it stays below the basis. Reads cgroup v2 `/sys/fs/cgroup/memory.max` (literal `max` = unlimited) then v1 `/sys/fs/cgroup/memory/memory.limit_in_bytes`. Explicit `--max-rss` (including `0` to disable) always wins. Pinned by `test/rss-default.test.ts`.
- `src/core/minions/run-child.ts` — `runChildJobEntry(engine, opts, injectables)`: the `jobs run-child` core. Re-reads the job row and validates status+token (exit 14 on mismatch, handler never runs), builds the shared token-fenced context against the CHILD's engine, runs the handler under `runWithJobSpend` (the job's spend authorization), writes ONE atomic outcome file (handler failure = reported outcome = exit 0; only write-failure exits 15). Installs a SIGTERM→shutdownSignal-ONLY handler (inline signal-separation parity: ctx.signal stays live so cooperative handlers finish + report inside the drain window; the parent's group SIGKILL at drain end is the backstop) and a parent-liveness watchdog polling `process.kill(parentPid, 0)` (ppid checks are dead code under tini) that aborts BOTH signals on parent death with a hard exit after grace. No worker machinery (parent owns liveness). Pinned by `test/run-child-entry.test.ts`.
diff --git a/scripts/bench-minions-load.ts b/scripts/bench-minions-load.ts
new file mode 100644
index 0000000000..0f1ecbab97
--- /dev/null
+++ b/scripts/bench-minions-load.ts
@@ -0,0 +1,126 @@
+#!/usr/bin/env bun
+/**
+ * Synthetic minions job-load fixture (#7239, #7240). In-memory PGLite, no network, no model calls. Run it on two trees
+ * to compare (`bun scripts/bench-minions-load.ts --json`):
+ *
+ * retry_burn: autopilot's freshness dispatch for SOURCES sources whose sync is deterministically refused (a managed
+ * refusal, `writer_coordinator_required`), one dispatch per 5-minute slot for a simulated day, a real MinionWorker
+ * draining each slot. History is aged by one slot between slots, so the dispatch's cooldowns see real elapsed time.
+ * Reports sync jobs created, handler attempts and deaths per source-day.
+ *
+ * cancel_churn: a dream-style private queue: CHILDREN subagent children submitted up front, an inline drain with a
+ * parent deadline that fits only some of them, then the phase's cleanup. Reports completed vs cancelled children.
+ */
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { MinionWorker } from '../src/core/minions/worker.ts';
+import { dispatchFreshnessSyncs } from '../src/commands/autopilot-dispatch.ts';
+import { opError } from '../src/core/ops/contract.ts';
+import { createHash } from 'node:crypto';
+import { writeFileSync } from 'node:fs';
+import { runPhaseSynthesize, TRIAGE_VERSION } from '../src/core/cycle/synthesize.ts';
+import { TIER_DEFAULTS } from '../src/core/model-config.ts';
+
+const json = process.argv.includes('--json');
+const SOURCES = 3;
+const SLOT_MIN = 5;
+const SLOTS = (24 * 60) / SLOT_MIN;
+
+process.env.GBRAIN_HOME = mkdtempSync(join(tmpdir(), 'gbrain-minions-load-'));
+const engine = new PGLiteEngine();
+await engine.connect({});
+await engine.initSchema();
+const queue = new MinionQueue(engine);
+
+const quiet = async <T,>(fn: () => Promise<T>): Promise<T> => {
+ const write = process.stderr.write.bind(process.stderr);
+ const log = console.log, warn = console.warn;
+ (process.stderr as { write: unknown }).write = () => true;
+ console.log = () => {}; console.warn = () => {};
+ try { return await fn(); } finally { (process.stderr as { write: unknown }).write = write; console.log = log; console.warn = warn; }
+};
+
+async function drain(): Promise<void> {
+ const worker = new MinionWorker(engine, { pollInterval: 10 });
+ worker.register('sync', async () => {
+ attempts++;
+ throw opError('writer_coordinator_required', 'Managed sync requires skipping the Git pull.', 'Sync with --no-pull.');
+ });
+ const running = worker.start();
+ for (let i = 0; i < 500; i++) {
+ await engine.executeRaw(`UPDATE minion_jobs SET delay_until = now() WHERE status = 'delayed'`);
+ const [{ n }] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM minion_jobs WHERE name='sync' AND status IN ('waiting','active','delayed')`);
+ if (n === 0) break;
+ await new Promise(r => setTimeout(r, 15));
+ }
+ worker.stop();
+ await running;
+}
+
+let attempts = 0;
+for (let i = 0; i < SOURCES; i++) {
+ const id = `source-${String.fromCharCode(97 + i)}`;
+ const dir = join(process.env.GBRAIN_HOME!, id);
+ mkdirSync(dir, { recursive: true });
+ execFileSync('git', ['-C', dir, 'init', '-q']);
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)', [id, dir, '{}']);
+}
+await quiet(async () => {
+ for (let slot = 0; slot < SLOTS; slot++) {
+ await dispatchFreshnessSyncs(engine, queue, { baseInterval: SLOT_MIN * 60, slot: `slot-${slot}`, timeoutMs: 60_000, jsonMode: true });
+ await drain();
+ await engine.executeRaw(`UPDATE minion_jobs SET created_at = created_at - interval '${SLOT_MIN} minutes',
+ finished_at = finished_at - interval '${SLOT_MIN} minutes', updated_at = updated_at - interval '${SLOT_MIN} minutes'`);
+ }
+});
+const [burn] = await engine.executeRaw<{ jobs: number; dead: number }>(`SELECT count(*)::int AS jobs, count(*) FILTER (WHERE status='dead')::int AS dead FROM minion_jobs WHERE name='sync'`);
+const retryBurn = { sources: SOURCES, slots: SLOTS, sync_jobs: burn.jobs, handler_attempts: attempts, deaths: burn.dead,
+ deaths_per_source_day: +(burn.dead / SOURCES).toFixed(1), attempts_per_job: +(attempts / Math.max(1, burn.jobs)).toFixed(2) };
+
+// cancel_churn: TRANSCRIPTS passing transcripts; the payload of one (BAD_AT) carries a lone UTF-16 surrogate, the shape
+// a large deployment's synthesize payloads hit. The drain is replaced by a seam that marks every waiting child as run,
+// so the numbers count children that reached the drain vs children cancelled before running.
+const TRANSCRIPTS = 10, BAD_AT = 5;
+await engine.executeRaw('DELETE FROM minion_jobs');
+const corpusDir = mkdtempSync(join(tmpdir(), 'gbrain-minions-load-corpus-'));
+await engine.setConfig('dream.synthesize.enabled', 'true');
+await engine.setConfig('dream.synthesize.session_corpus_dir', corpusDir);
+for (let i = 0; i < TRANSCRIPTS; i++) {
+ const name = `2026-08-${String(i + 1).padStart(2, '0')}-t${i}.txt`;
+ const content = `conversation ${i}\n`.repeat(200);
+ writeFileSync(join(corpusDir, name), content);
+ await engine.putDreamVerdict(join(corpusDir, name), createHash('sha256').update(content, 'utf8').digest('hex'), {
+ worth_processing: true, reasons: ['seed'], score: 0.9, content_type: null, segments: [], entities: [], model: TIER_DEFAULTS.utility, triage_version: TRIAGE_VERSION,
+ });
+}
+const realAdd = MinionQueue.prototype.add, realClaim = MinionQueue.prototype.claim;
+MinionQueue.prototype.add = async function (this: MinionQueue, ...args: Parameters<typeof realAdd>) {
+ const data = args[1] as { prompt?: string } | undefined;
+ if (typeof data?.prompt === 'string' && data.prompt.includes(`-t${BAD_AT}.txt`)) args[1] = { ...data, prompt: data.prompt + ' \ud83d' };
+ return realAdd.apply(this, args);
+};
+MinionQueue.prototype.claim = async function () {
+ await engine.executeRaw(`UPDATE minion_jobs SET status = 'completed', started_at = now(), finished_at = now() WHERE name = 'subagent' AND status = 'waiting'`);
+ return null;
+};
+let phase: Awaited<ReturnType<typeof runPhaseSynthesize>>;
+try {
+ phase = await quiet(() => runPhaseSynthesize(engine, { brainDir: mkdtempSync(join(tmpdir(), 'gbrain-minions-load-brain-')), dryRun: false }));
+} finally {
+ MinionQueue.prototype.add = realAdd;
+ MinionQueue.prototype.claim = realClaim;
+}
+const [churn] = await engine.executeRaw<{ created: number; ran: number; cancelled: number }>(
+ `SELECT count(*)::int AS created, count(*) FILTER (WHERE started_at IS NOT NULL)::int AS ran,
+ count(*) FILTER (WHERE status = 'cancelled' AND started_at IS NULL)::int AS cancelled FROM minion_jobs WHERE name = 'subagent'`);
+const cancelChurn = { transcripts: TRANSCRIPTS, children_created: churn.created, children_reached_drain: churn.ran,
+ children_cancelled_unrun: churn.cancelled, phase_error: phase.error?.code ?? null };
+
+const out = { retry_burn: retryBurn, cancel_churn: cancelChurn };
+await engine.disconnect();
+if (json) console.log(JSON.stringify(out, null, 2));
+else console.log(`cancel_churn: ${cancelChurn.children_created} children, ${cancelChurn.children_reached_drain} reached the drain, ${cancelChurn.children_cancelled_unrun} cancelled unrun (phase error ${cancelChurn.phase_error})`), console.log(`retry_burn: ${retryBurn.sync_jobs} sync jobs, ${retryBurn.handler_attempts} handler attempts, ${retryBurn.deaths} deaths (${retryBurn.deaths_per_source_day}/source-day, ${retryBurn.attempts_per_job} attempts/job)`);
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 0a8ba48c66..3fd5ef5bd1 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -24,12 +24,12 @@ src/core/pglite-engine.ts 3087 ratchet +5 agent operator gate fixes: repair-fail
src/core/postgres-engine.ts 3114 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107); +3 #7159: the frontmatter where clause in the two keyword typesClause sites and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (3114 measured)
src/core/search/hybrid.ts 1562 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook); lowered to 1562: LHF wave 2 item 3 peeled cosineReScore into search/cosine-rescore.ts
src/core/types.ts 2345 ratchet +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts); +4 wave 18b lane 2 (#6495): SearchOpts.keywordTimeoutCache, the skipped_after_timeout degraded reason and the useCache doc line; integrated at wave 18b: master 2319 + 4; +2 LHF wave 2 item 3: retrieval meta cosine_rescore field (js_fallback disclosure; logic in search/cosine-rescore.ts); +14 GBRA-154 ranking wave (#4612 #7153 #7156 #7162 #7164): SearchResult collapsed/redirect_to/image_page/rank_prior/rank_score/fused_score stamps and HybridSearchMeta.collapse (interface fields; logic in search/collapse.ts, rank-priors.ts, score-contract.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (2343 measured); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (2345 measured)
-src/core/minions/queue.ts 2533 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts); +5 GBRA-130 A-30: claim excludeWatchdogSuspects option (signature, doc and the mark parameter), the releaseWatchdogClaim delegate, and the co-runner stall call site in handleStalled (logic in minions/watchdog-attribution.ts)
+src/core/minions/queue.ts 2538 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts); +5 GBRA-130 A-30: claim excludeWatchdogSuspects option (signature, doc and the mark parameter), the releaseWatchdogClaim delegate, and the co-runner stall call site in handleStalled (logic in minions/watchdog-attribution.ts); +5 GBRA-158 #7239/#7240: failJob result parameter (the #7216 hunk), jsonbSafeJson import and its call in add (sanitizer in text-safe.ts)
src/commands/init.ts 1884 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts); +4 GBRA-81 item 1: --search-mode value flag, its parse line, module-level choice, help line (picker logic lives in init-mode-picker.ts); +2 D8 funnel: a fresh init counts one clean_install when the opt-in funnel is on (core/funnel.ts)
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
src/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)
src/commands/bootstrap.ts 2147 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts)
-src/core/minions/worker.ts 1788 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler); +3 watchdog: gracefulShutdown records its reason and launchJob aborts a claim committed before it fired; +5 GBRA-130 A-30: watchdog-attribution import, InFlightJob.shared (interface field), the suspect-alone claim gate and option, and the watchdog settle call in the executeJob catch (logic in minions/watchdog-attribution.ts); +6 GBRA-133 2a.4 sync-queue wake: IdleWaiter import and field, claimStarted before each claim, the idle poll through it, and stop/requestShutdown ending its wait (logic in minions/idle-wait.ts)
+src/core/minions/worker.ts 1789 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler); +3 watchdog: gracefulShutdown records its reason and launchJob aborts a claim committed before it fired; +5 GBRA-130 A-30: watchdog-attribution import, InFlightJob.shared (interface field), the suspect-alone claim gate and option, and the watchdog settle call in the executeJob catch (logic in minions/watchdog-attribution.ts); +6 GBRA-133 2a.4 sync-queue wake: IdleWaiter import and field, claimStarted before each claim, the idle poll through it, and stop/requestShutdown ending its wait (logic in minions/idle-wait.ts); +1 GBRA-158 #7239: refusal.ts import (a deterministic refusal ends the job at once; classification in minions/refusal.ts)
src/commands/sources.ts 2065 ratchet +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts)
src/core/link-extraction.ts 2421 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass); +21 fix wave 13 P4.10 #6266: resolveSameDirSlug + exported resolveMarkdownLinkSlug, shared with the link validator; +41 Wave B PR 2 lane 2e: extractPageLinks split into extractBodyLinks (window-scoped, offset-shifted, pass-tagged candidates) and frontmatterLinks, plus entityRefPasses, candidateKey, rolePriorPhrases and the roleText/regexBudget/window options, so a segmented page streams through the same extractor (window and merge logic in core/page-body/segment-links.ts); +1 at the #6869 gate-ahead merge: the #6803 wave EXTRACTOR_BUMP_NOTES comment composed with lane 2e (2420 + 1)
src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budget
diff --git a/src/commands/autopilot-dispatch.ts b/src/commands/autopilot-dispatch.ts
index abe2dd5254..9f4a48009e 100644
--- a/src/commands/autopilot-dispatch.ts
+++ b/src/commands/autopilot-dispatch.ts
@@ -25,6 +25,7 @@ import { logError } from './autopilot.ts';
import { readCheckoutHead } from '../core/checkout-head.ts';
import { SYNC_ON_COMMIT_KEY } from '../core/sync-config-keys.ts';
import { autopilotPaused } from '../core/autopilot-paths.ts';
+import { cooldownMinForCount, resolveFailureCooldownOpts } from './autopilot-fanout.ts';
/** Returns cycleOk: false only when the dispatch itself threw. */
export async function dispatchAutopilotTick(
@@ -300,6 +301,59 @@ async function checkoutFreshness(engine: BrainEngine, src: SourceRow, root: stri
* A HEAD-driven job is keyed on its HEAD, never the wall-clock slot, so a new commit cannot coalesce into the slot's
* completed job. A source with a live sync job keeps its HEAD undecided; the next tick or probe dispatches it.
*/
+/** #7239: a source whose automatic sync keeps being refused, and until when its freshness sync waits. */
+export interface SyncRefusalHold { code: string; job_id: number; count: number; retry_at: number }
+
+const REFUSAL_LOOKBACK_MS = 24 * 60 * 60 * 1000;
+const reportedRefusalJobs = new Set<number>();
+
+/**
+ * #7239: a refused sync job (`job_outcome: 'refused'`, refusal.ts) fails the same way until someone fixes its cause, so
+ * the freshness dispatch stops queueing a new one per slot and per commit. A source's refusals since its last completed
+ * sync job (looking back a day) hold it for the autopilot failure cooldown of that count (10 minutes doubling to the
+ * 2-hour cap; `autopilot.failure_cooldown_min` / `_cap_min`, 0 disables), counted from the newest refusal. A completed
+ * sync job clears the hold; an explicit `gbrain sync --source <id>` is never held. Fails open (no holds) on a read error.
+ */
+export async function readSyncRefusalHolds(engine: BrainEngine, now = Date.now()): Promise<Map<string, SyncRefusalHold>> {
+ const holds = new Map<string, SyncRefusalHold>();
+ const opts = await resolveFailureCooldownOpts(engine);
+ if (opts.baseMin <= 0) return holds;
+ const rows = await engine.executeRaw<{ source_id: string | null; n: number; last_at: string | Date; job_id: number; code: string | null }>(
+ `SELECT COALESCE(j.data->>'sourceId', j.data->>'source_id', 'default') AS source_id, count(*)::int AS n, max(j.finished_at) AS last_at,
+ (array_agg(j.id ORDER BY j.finished_at DESC))[1] AS job_id,
+ (array_agg(j.result->'refusal'->>'code' ORDER BY j.finished_at DESC))[1] AS code
+ FROM minion_jobs j
+ WHERE j.name = 'sync' AND j.status = 'dead' AND j.result->>'job_outcome' = 'refused' AND j.finished_at > $1
+ AND NOT EXISTS (SELECT 1 FROM minion_jobs c
+ WHERE c.name = 'sync' AND c.status = 'completed' AND c.finished_at > j.finished_at
+ AND COALESCE(c.data->>'sourceId', c.data->>'source_id', 'default') = COALESCE(j.data->>'sourceId', j.data->>'source_id', 'default'))
+ GROUP BY 1`,
+ [new Date(now - REFUSAL_LOOKBACK_MS).toISOString()],
+ );
+ for (const r of rows) {
+ const last = r.last_at instanceof Date ? r.last_at.getTime() : new Date(r.last_at).getTime();
+ if (!r.source_id || !Number.isFinite(last)) continue;
+ const retryAt = last + cooldownMinForCount(Number(r.n), opts) * 60_000;
+ if (retryAt > now) holds.set(r.source_id, { code: r.code ?? 'refused', job_id: Number(r.job_id), count: Number(r.n), retry_at: retryAt });
+ }
+ return holds;
+}
+
+/** Whether a refusal hold skips this source's freshness sync now; reports the hold once per refused job. */
+function skipRefusedSync(holds: ReadonlyMap<string, SyncRefusalHold>, sourceId: string, jsonMode: boolean): boolean {
+ const hold = holds.get(sourceId);
+ if (!hold) return false;
+ if (!reportedRefusalJobs.has(hold.job_id)) {
+ reportedRefusalJobs.add(hold.job_id);
+ const retryAt = new Date(hold.retry_at).toISOString();
+ process.stderr.write((jsonMode
+ ? JSON.stringify({ event: 'freshness_sync_refused', source_id: sourceId, job_id: hold.job_id, code: hold.code, refusals: hold.count, retry_at: retryAt })
+ : `[dispatch] sync of ${sourceId} waits until ${retryAt}: its last sync job #${hold.job_id} was refused (${hold.code}) and would be refused again. `
+ + `gbrain jobs get ${hold.job_id} --json shows the fix; after fixing it, gbrain sync --source ${sourceId} runs now.`) + '\n');
+ }
+ return true;
+}
+
export async function dispatchFreshnessSyncs(
engine: BrainEngine,
queue: MinionQueue,
@@ -328,8 +382,10 @@ export async function dispatchFreshnessSyncs(
const activationPending = await loadActivationPendingSourceIds(engine);
const intervalMs = baseInterval * 1000;
const now = Date.now();
+ const refusalHolds = await readSyncRefusalHolds(engine, now).catch(() => new Map<string, SyncRefusalHold>());
for (const src of sources) {
if (onlySourceIds && !onlySourceIds.has(src.id)) continue;
+ if (skipRefusedSync(refusalHolds, src.id, jsonMode)) { decisions.push({ source_id: src.id, outcome: 'skipped' }); continue; }
if (isConnectorSourceKind(parseSourceConfig(src.config).kind)) {
await dispatchConnectorFreshnessSync(queue, src, attempted, activationPending, mismatched, { intervalMs, now, slot, timeoutMs, jsonMode });
continue;
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index cda8c94855..559a963f70 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1053,6 +1053,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.338.0', text: 'On Postgres, a keyword search whose words match more than 50,000 chunks now ranks the first 50,000 matches that pass its filters instead of all of them, so a common-word query on a large brain returns ranked rows in about a second instead of running into the keyword statement timeout and returning none; hybrid search reports `keyword_candidates_incomplete` when the bound applies. Its any-word retry (after an all-words match finds nothing) now matches only the words the planner statistics say fit about 20,000 chunks, still ranking with every word, and also reports `keyword_candidates_incomplete` when it drops a word.' },
{ since: '0.60.338.0', text: 'The keyword arm keeps one chunk per page in its candidate pool (Postgres and PGLite), so a page with hundreds of matching chunks no longer pushes every other matching page out of the results.' },
{ since: '0.60.338.0', text: 'The title arm\'s any-word retry (after an all-words title match finds nothing) now matches page titles only, as remote callers already did, and drops repeated words (#7135): a date in a question no longer pulls every dated timeline into ranking, which cut a 3-5 s title arm to well under a second on a large brain. A local all-words title match is unchanged.' },
+ // GBRA-158 minions wave (#7239).
+ { since: 'TBD', text: 'A background job that fails with a deterministic refusal (an error whose code is a caller, consent or host-only refusal the error registry does not mark retryable, or one its site marks `retryable: false`, such as `writer_coordinator_required`, `connector_account_changed`, `not_connected` or an `owner_unavailable` on a host that does not own the checkout) now ends at once as `dead` after one attempt instead of retrying until its attempts run out. Its result carries `job_outcome: "refused"` and `refusal` with the code, reason, message, fix and `gbrain errors <code>`; failures that can pass on retry (rate limits, timeouts, server and unavailable errors, write conflicts, a write still pending) retry as before. Autopilot\'s freshness dispatch then holds that source\'s automatic sync for the failure cooldown of its refusal count (10 minutes doubling to 2 hours, `autopilot.failure_cooldown_min` / `autopilot.failure_cooldown_cap_min`, 0 disables) instead of queueing a sync that is refused again every slot and every commit; it says so once per refused job (`freshness_sync_refused`), a completed sync job clears the hold, and `gbrain sync --source <id>` is never held.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cycle/inline-drain.ts b/src/core/cycle/inline-drain.ts
index f24d805dd0..fbac9f0887 100644
--- a/src/core/cycle/inline-drain.ts
+++ b/src/core/cycle/inline-drain.ts
@@ -36,8 +36,9 @@
import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
import { MinionQueue } from '../minions/queue.ts';
-import type { MinionHandler, MinionJobContext } from '../minions/types.ts';
+import type { MinionHandler, MinionJob, MinionJobContext } from '../minions/types.ts';
import { UnrecoverableError } from '../minions/types.ts';
+import { jobRefusal, refusedJobResult } from '../minions/refusal.ts';
import { makeSubagentHandler } from '../minions/handlers/subagent.ts';
import { RateLeaseUnavailableError, leaseFullBackoffMs } from '../minions/rate-leases.ts';
import { reconnectAfterConnectionError } from '../minions/reconnect.ts';
@@ -396,17 +397,7 @@ async function drainLoop(
// Lock-token mismatch (stall sweep won) — fall through to failJob,
// which no-ops under the same fence.
}
- const timedOut = abort.signal.aborted;
- const errorText = timedOut ? 'timeout exceeded' : (handlerErr instanceof Error ? handlerErr.message : String(handlerErr));
- const isUnrecoverable = handlerErr instanceof UnrecoverableError;
- const attemptsExhausted = job.attempts_made + 1 >= job.max_attempts;
- await queue.failJob(
- job.id,
- lockToken,
- errorText,
- timedOut || isUnrecoverable || attemptsExhausted ? 'dead' : 'delayed',
- 0,
- );
+ await failChild(queue, job, lockToken, handlerErr, abort.signal.aborted);
};
try {
// #4077: external cancellation outranks outcome recording — a child
@@ -450,3 +441,16 @@ async function drainLoop(
throw e;
}
}
+
+/**
+ * Record a failed child: a timeout or an UnrecoverableError is dead; a deterministic refusal (#7239) is dead with its
+ * code and fix on the result; anything else is retried (delayed, no backoff) until its attempts run out.
+ */
+async function failChild(queue: MinionQueue, job: MinionJob, lockToken: string, handlerErr: unknown, timedOut: boolean): Promise<void> {
+ const errorText = timedOut ? 'timeout exceeded' : (handlerErr instanceof Error ? handlerErr.message : String(handlerErr));
+ const refusal = timedOut ? null : jobRefusal(handlerErr);
+ const isUnrecoverable = refusal !== null || handlerErr instanceof UnrecoverableError;
+ const attemptsExhausted = job.attempts_made + 1 >= job.max_attempts;
+ await queue.failJob(job.id, lockToken, errorText, timedOut || isUnrecoverable || attemptsExhausted ? 'dead' : 'delayed', 0,
+ refusal ? refusedJobResult(refusal) : undefined);
+}
diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.ts
index da81ef8148..103005af45 100644
--- a/src/core/cycle/synthesize.ts
+++ b/src/core/cycle/synthesize.ts
@@ -96,6 +96,7 @@ import { verifyAndRepairDreamPages, normForGrounding, readVerifyEpoch, loadChild
import { dreamBreakerRefusal, loadDreamBreaker } from './dream-breaker.ts';
import { resolveTriageDecide, type TriageDecide, type TriageDecideStats } from './triage-decide.ts';
import { OperationError } from '../ops/contract.ts';
+import { isRetryableConnError } from '../retry-matcher.ts';
import { backoffUntil, recordUnreliableTriage, responseDiagnostic, triageBackoffDetails, TRIAGE_UNRELIABLE_BACKOFF, VerdictCacheWrites, type TriageDiagnostic, type VerdictCacheFailure } from './triage-backoff.ts';
import { resolveGroundingDecide } from './grounding-decide.ts';
import { passesTriageGate, rescueConfigOf, DEFAULT_RESCUE_FLOOR, DEFAULT_RESCUE_MIN_SEGMENTS, DEFAULT_RESCUE_CONTENT_TYPES, DEFAULT_RESCUE_CONFIG, type RescueConfig, type RescueVerdictLike } from './triage-rescue.ts';
@@ -247,6 +248,12 @@ function warnUnknownModelOnce(model: string): void {
*
* Pure function. Tested by `test/cycle/synthesize-chunker.test.ts`.
*/
+/** #7240: the skip reason for a transcript whose child could not be queued: `submit_failed (<code>): <message>`. */
+function submitFailedReason(e: unknown): string {
+ const code = e instanceof OperationError ? e.code : (e as { code?: unknown } | null)?.code;
+ return `submit_failed${typeof code === 'string' ? ` (${code})` : ''}: ${e instanceof Error ? e.message : String(e)}`;
+}
+
export function splitTranscriptByBudget(
content: string,
contentHash: string,
@@ -866,6 +873,14 @@ async function runPhaseSynthesizeInner(
// (adversarial finding). Coalesced rows are another run's bookkeeping
// and must not be cancelled.
const transcriptFreshIds: number[] = [];
+ const rollbackTranscriptChunks = async (): Promise<void> => {
+ for (const id of transcriptFreshIds) {
+ try { await queue.cancelJob(id); } catch { /* best-effort rollback */ }
+ if (childIds.includes(id)) childIds.splice(childIds.indexOf(id), 1);
+ jobRawSource.delete(id);
+ chunkInfo.delete(id);
+ }
+ };
const prompts = chunks.map((chunk, i) => buildSynthesisPrompt(
t, chunk, i, chunks.length, priorContradictionsBlock, config.outputRoot,
buildTriageMapBlock(triageVerdict, chunk, chunks.length),
@@ -961,18 +976,17 @@ async function runPhaseSynthesizeInner(
// partial chunk set would write partial pages for a transcript the
// skip report says was skipped.
if (isQueueQuotaExceededError(e)) {
- for (const id of transcriptFreshIds) {
- try { await queue.cancelJob(id); } catch { /* best-effort rollback */ }
- const idx = childIds.indexOf(id);
- if (idx >= 0) childIds.splice(idx, 1);
- jobRawSource.delete(id);
- chunkInfo.delete(id);
- }
+ await rollbackTranscriptChunks();
skipReports.push({ filePath: t.filePath, reason: `admission_quota: ${e.message}` });
quotaHit = true;
break;
}
- throw e;
+ // #7240: one transcript whose child cannot be queued is skipped, never the phase: rethrowing cancelled every
+ // child already queued for the other transcripts. A lost connection or a cancellation still ends the phase.
+ if (opts.signal?.aborted || isRetryableConnError(e)) throw e;
+ await rollbackTranscriptChunks();
+ skipReports.push({ filePath: t.filePath, reason: submitFailedReason(e) });
+ break;
}
// Self-heal (#4152 C1): an idempotency-coalesced row still `waiting`
// in a FOREIGN dream-inline-* queue was stranded by a previously
diff --git a/src/core/minions/errors.ts b/src/core/minions/errors.ts
index 61a586d4b8..a3602d54ca 100644
--- a/src/core/minions/errors.ts
+++ b/src/core/minions/errors.ts
@@ -20,3 +20,24 @@ export class JobDeferredError extends Error {
this.name = 'JobDeferredError';
}
}
+
+/**
+ * #7239: a deterministic refusal, recorded on the job's result as `refusal` (job_outcome `refused`). `fix` is the
+ * error's rendered next step and `docs_cmd` explains the code offline; the suggestion prose is never kept, because job
+ * rows are served to remote callers and a suggestion may name an account or a local path.
+ */
+export interface JobRefusal {
+ code: string;
+ reason?: string;
+ message: string;
+ fix?: unknown;
+ docs_cmd: string[];
+}
+
+/** A refusal rebuilt on the worker side of a per-job child (job-isolation.ts); terminal like any UnrecoverableError. */
+export class JobRefusedError extends UnrecoverableError {
+ constructor(readonly refusal: JobRefusal) {
+ super(refusal.message);
+ this.name = 'JobRefusedError';
+ }
+}
diff --git a/src/core/minions/job-isolation.ts b/src/core/minions/job-isolation.ts
index b3ba1fe019..263585f9d5 100644
--- a/src/core/minions/job-isolation.ts
+++ b/src/core/minions/job-isolation.ts
@@ -37,6 +37,8 @@ import { accessSync, constants, readdirSync, readFileSync, writeFileSync, rename
import { readFile, stat } from 'node:fs/promises';
import { spawnSync } from '../spawn.ts';
import { JobDeferredError, UnrecoverableError } from './types.ts';
+import { JobRefusedError, type JobRefusal } from './errors.ts';
+import { jobRefusal } from './refusal.ts';
import { RateLeaseUnavailableError } from './handlers/subagent.ts';
import { SpendGroupRefusedError, type SpendRefusalEnvelope } from './spend-authorization.ts';
import { LocalConfigurationError, isLocalConfigurationError } from './configuration-error.ts';
@@ -91,7 +93,7 @@ export function childConfigurationError(reason: typeof CHILD_CONFIGURATION_REASO
return new LocalConfigurationError(reason, `${messages[reason]} Verify worker and child readiness, then restart. See docs/guides/minions-fix.md#configuration-blocked.`);
}
-export type ChildErrorKind = 'unrecoverable' | 'rate_lease' | 'deferred' | 'generic' | 'local_configuration';
+export type ChildErrorKind = 'unrecoverable' | 'refused' | 'rate_lease' | 'deferred' | 'generic' | 'local_configuration';
export type ChildOutcome =
| { outcome: 'success'; result: unknown }
@@ -104,6 +106,8 @@ export type ChildOutcome =
/** A group spend refusal's envelope (code, fix, group amounts). */
spend?: SpendRefusalEnvelope;
deferral?: { reason: string; retryInMs: number };
+ /** #7239: a deterministic refusal (refusal.ts), rebuilt as JobRefusedError on the worker side. */
+ refusal?: JobRefusal;
protocolVersion?: number;
reasonCode?: typeof CHILD_CONFIGURATION_REASONS[number];
};
@@ -129,6 +133,7 @@ export function encodeHandlerError(err: unknown): ChildOutcome {
if (err instanceof JobDeferredError) {
return { outcome: 'error', errorKind: 'deferred', message: err.message, deferral: { reason: err.reason, retryInMs: err.retryInMs } };
}
+ if (err instanceof JobRefusedError) return { outcome: 'error', errorKind: 'refused', message: err.message, refusal: err.refusal };
if (err instanceof UnrecoverableError) {
return {
outcome: 'error',
@@ -138,6 +143,8 @@ export function encodeHandlerError(err: unknown): ChildOutcome {
...(err instanceof SpendGroupRefusedError ? { spend: err.envelope } : {}),
};
}
+ const refusal = jobRefusal(err);
+ if (refusal) return { outcome: 'error', errorKind: 'refused', message: refusal.message, refusal };
const message = err instanceof Error ? err.message : String(err);
const stack = err instanceof Error ? err.stack : undefined;
return { outcome: 'error', errorKind: 'generic', message, ...(stack ? { stack } : {}) };
@@ -156,6 +163,7 @@ export function reconstructHandlerError(o: Extract<ChildOutcome, { outcome: 'err
if (o.errorKind === 'rate_lease' && o.lease) {
return new RateLeaseUnavailableError(o.lease.key, o.lease.active, o.lease.max, o.lease.retryInMs);
}
+ if (o.errorKind === 'refused' && o.refusal) return new JobRefusedError(o.refusal);
if (o.errorKind === 'unrecoverable') {
return o.spend ? new SpendGroupRefusedError(o.spend) : new UnrecoverableError(o.message);
}
@@ -221,8 +229,13 @@ export function parseChildOutcome(raw: string, size: number, maxBytes = CHILD_OU
// policy as the errorKind whitelist.
const rawDeferral = (o as { deferral?: unknown }).deferral as { reason?: unknown; retryInMs?: unknown } | undefined;
const deferralValid = rawDeferral != null && typeof rawDeferral.reason === 'string' && Number.isFinite(rawDeferral.retryInMs as number);
+ const rawRefusal = (o as { refusal?: unknown }).refusal as { code?: unknown; reason?: unknown; message?: unknown; fix?: unknown; docs_cmd?: unknown } | undefined;
+ const refusalValid = rawRefusal != null && typeof rawRefusal === 'object' && typeof rawRefusal.code === 'string' && typeof rawRefusal.message === 'string'
+ && (rawRefusal.reason === undefined || typeof rawRefusal.reason === 'string')
+ && Array.isArray(rawRefusal.docs_cmd) && rawRefusal.docs_cmd.every(a => typeof a === 'string');
const errorKind =
kind === 'unrecoverable' ? 'unrecoverable'
+ : kind === 'refused' && refusalValid ? 'refused'
: kind === 'rate_lease' && leaseValid ? 'rate_lease'
: kind === 'deferred' && deferralValid ? 'deferred'
: 'generic';
@@ -238,6 +251,7 @@ export function parseChildOutcome(raw: string, size: number, maxBytes = CHILD_OU
...(Number.isFinite(rawLease.retryInMs as number) && (rawLease.retryInMs as number) >= 0 ? { retryInMs: rawLease.retryInMs as number } : {}) } }
: {}),
...(errorKind === 'unrecoverable' && spendValid ? { spend: rawSpend as SpendRefusalEnvelope } : {}),
+ ...(errorKind === 'refused' && refusalValid ? { refusal: rawRefusal as JobRefusal } : {}),
...(errorKind === 'deferred' && deferralValid
? { deferral: { reason: rawDeferral.reason as string, retryInMs: rawDeferral.retryInMs as number } }
: {}),
diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.ts
index 05f871fa16..277981dbe7 100644
--- a/src/core/minions/queue.ts
+++ b/src/core/minions/queue.ts
@@ -21,6 +21,7 @@ import { coalesceOnIdempotencyKey, decideCoalesce, insertOrCoalesce } from './id
import { adoptSpendAuthorization, legacyDefaultClaimSetSql, legacyDefaultClaimParams, type SpendAuthorization } from './spend-authorization.ts';
import { validateAttachment } from './attachments.ts';
import { isProtectedJobName } from './protected-names.ts';
+import { jsonbSafeJson } from '../text-safe.ts';
import { assertEmbedBackfillQueueAdmission } from './embed-backfill-admission.ts';
import { lockDelegatedSubmission, checkDelegatedCapacity, prepareDelegatedReplay, admitDelegatedRetry } from './delegated-admission.ts';
import {
@@ -225,6 +226,8 @@ export class MinionQueue {
// canonical form. Without the trim-before-check, `queue.add(' shell ', ...)`
// would evade the guard and insert a job literally named 'shell'.
if (currentSubmissionAuthority() && currentSubmissionAuthority()!.kind !== 'application') throw new Error('Remote jobs cannot submit descendant jobs');
+ // #7240: Postgres refuses a lone UTF-16 surrogate or U+0000 anywhere in a JSONB value, which failed the whole insert.
+ if (data !== undefined) data = jsonbSafeJson(data);
const authority = parseSubmissionAuthority(trusted?.submissionAuthority ?? APPLICATION_AUTHORITY);
if (!authority) throw new Error('Unsupported submission authority');
const delegatedClientId = authority.kind === 'remote_agent' ? authority.principal.id : trusted?.delegatedClientId;
@@ -1802,7 +1805,7 @@ export class MinionQueue {
/**
* Fail a job (token-fenced). All side effects atomic in one transaction:
- * 1. UPDATE child to 'delayed' (retry) | 'failed' | 'dead'
+ * 1. UPDATE child to 'delayed' (retry) | 'failed' | 'dead'; `result` (a handler result that reported a failure, #7188) is kept
* 2. If terminal AND parent_job_id, run on_child_fail policy:
* - 'fail_parent' → mark parent 'failed' (via failParent SQL)
* - 'remove_dep' → null out parent_job_id (via removeChildDependency SQL)
@@ -1819,7 +1822,8 @@ export class MinionQueue {
lockToken: string,
errorText: string,
newStatus: 'delayed' | 'failed' | 'dead',
- backoffMs?: number
+ backoffMs?: number,
+ result?: Record<string, unknown>,
): Promise<MinionJob | null> {
return this.engine.transaction(async (tx) => {
// Lock the parent row first so concurrent sibling completions/failures
@@ -1843,10 +1847,11 @@ export class MinionQueue {
delay_until = CASE WHEN $1 = 'delayed' THEN now() + ($4::double precision * interval '1 millisecond') ELSE NULL END,
finished_at = CASE WHEN $1 IN ('failed', 'dead') THEN now() ELSE NULL END,
started_at = CASE WHEN $1 = 'delayed' THEN NULL ELSE started_at END,
+ result = COALESCE($7::jsonb, result),
lock_token = NULL, lock_until = NULL, updated_at = now()
WHERE id = $5 AND status = 'active' AND lock_token = $6
RETURNING *`,
- [newStatus, errorText, errorText, backoffMs ?? 0, id, lockToken]
+ [newStatus, errorText, errorText, backoffMs ?? 0, id, lockToken, result ?? null]
);
if (rows.length === 0) return null;
diff --git a/src/core/minions/refusal.ts b/src/core/minions/refusal.ts
new file mode 100644
index 0000000000..ee0c877566
--- /dev/null
+++ b/src/core/minions/refusal.ts
@@ -0,0 +1,40 @@
+/**
+ * #7239: is a handler's error a deterministic refusal, one that fails the same way on every retry? The worker and the
+ * dream inline drain end such a job at once (dead, one attempt) with the refusal on its result instead of burning its
+ * retries; autopilot's freshness dispatch then backs off the source (autopilot-dispatch.ts).
+ *
+ * The error's registry code decides (error-registry.ts): a site that set `retryable` wins; otherwise a code whose class
+ * is caller, consent or host_only and that the registry does not mark retryable is a refusal. Classes retryable, server
+ * and unavailable stay retryable (a dependency can come back), so do the concurrency codes a re-read can clear, codes the
+ * registry does not know, and errors with no code. An error with no code is looked through to its `cause`.
+ */
+import { JobRefusedError, UnrecoverableError, type JobRefusal } from './errors.ts';
+import { OperationError } from '../ops/contract.ts';
+import { codeClass, codeRetryable, isRegistryCode } from '../error-catalogue.ts';
+
+const DETERMINISTIC_CLASSES = new Set(['caller', 'consent', 'host_only']);
+const CONCURRENCY_CODES = new Set(['revision_conflict', 'page_identity_changed', 'concurrent_write']);
+
+export function jobRefusal(err: unknown): JobRefusal | null {
+ let e: unknown = err;
+ for (let depth = 0; e instanceof Error && depth < 4; depth++, e = e.cause) {
+ if (e instanceof JobRefusedError) return e.refusal;
+ if (e instanceof UnrecoverableError) return null;
+ const fields = e as { code?: unknown; reason?: unknown; retryable?: unknown };
+ const code = e instanceof OperationError ? e.canonicalCode : fields.code;
+ if (typeof code !== 'string') continue;
+ const reason = typeof fields.reason === 'string' ? fields.reason : undefined;
+ if (!isRegistryCode(code) || fields.retryable === true) return null;
+ const refused = fields.retryable === false
+ || (DETERMINISTIC_CLASSES.has(codeClass(code, reason)) && !codeRetryable(code, reason) && !CONCURRENCY_CODES.has(code));
+ if (!refused) return null;
+ const fix = e instanceof OperationError && e.fix ? e.toJSON().fix : undefined;
+ return { code, ...(reason !== undefined ? { reason } : {}), message: e.message, ...(fix !== undefined ? { fix } : {}), docs_cmd: ['gbrain', 'errors', code] };
+ }
+ return null;
+}
+
+/** The result a refused job stores. */
+export function refusedJobResult(refusal: JobRefusal): Record<string, unknown> {
+ return { job_outcome: 'refused', refusal };
+}
diff --git a/src/core/minions/worker.ts b/src/core/minions/worker.ts
index 8b0e1108dd..8973bfab61 100644
--- a/src/core/minions/worker.ts
+++ b/src/core/minions/worker.ts
@@ -89,6 +89,7 @@ import { evaluateQuietHours, type QuietHoursConfig } from './quiet-hours.ts';
import { endedByShutdown, releaseUndrainedClaims, settleShutdownInterruptedJob } from './worker-shutdown.ts';
import { isWatchdogSuspect, settleWatchdogAbort } from './watchdog-attribution.ts';
import { IdleWaiter } from './idle-wait.ts';
+import { jobRefusal, refusedJobResult } from './refusal.ts';
import { readFileSync } from 'fs';
/**
@@ -1720,7 +1721,7 @@ export class MinionWorker extends EventEmitter {
return;
}
- const isUnrecoverable = err instanceof UnrecoverableError;
+ const refusal = jobRefusal(err), isUnrecoverable = refusal !== null || err instanceof UnrecoverableError; // #7239: refusals end now
const attemptsExhausted = job.attempts_made + 1 >= job.max_attempts;
let newStatus: 'delayed' | 'failed' | 'dead';
@@ -1746,7 +1747,7 @@ export class MinionWorker extends EventEmitter {
// so handleStalled requeues it cleanly on a live pool (the D8a path).
let failed: MinionJob | null;
try {
- failed = await this.queue.failJob(job.id, lockToken, errorText, newStatus, backoffMs);
+ failed = await this.queue.failJob(job.id, lockToken, errorText, newStatus, backoffMs, refusal ? refusedJobResult(refusal) : undefined);
} catch (recordErr) {
const recordMsg = recordErr instanceof Error ? recordErr.message : String(recordErr);
console.error(
@@ -1755,7 +1756,7 @@ export class MinionWorker extends EventEmitter {
if (!isRetryableConnError(recordErr)) throw recordErr;
await this.reconnectAfterConnectionError('failJob', recordErr);
try {
- failed = await this.queue.failJob(job.id, lockToken, errorText, newStatus, backoffMs);
+ failed = await this.queue.failJob(job.id, lockToken, errorText, newStatus, backoffMs, refusal ? refusedJobResult(refusal) : undefined);
} catch (retryErr) {
if (isLocalConfigurationError(retryErr)) {
this.blockForConfiguration(retryErr);
@@ -1781,7 +1782,7 @@ export class MinionWorker extends EventEmitter {
if (newStatus === 'delayed') {
console.log(`Job ${job.id} (${job.name}) failed, retrying in ${Math.round(backoffMs)}ms (attempt ${job.attempts_made + 1}/${job.max_attempts})`);
} else {
- console.log(`Job ${job.id} (${job.name}) permanently failed: ${errorText}`);
+ console.log(`Job ${job.id} (${job.name}) ${refusal ? `refused (${refusal.code}), not retried` : 'permanently failed'}: ${errorText}`);
}
}
}
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index b1cdf17ae6..098f269b70 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -20,6 +20,7 @@ import { isWriteTargetContained } from '../path-confine.ts';
import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
import { unboundBindCommand } from './unbound-source.ts';
import { localHostId } from './identity.ts';
+import { ownerUnavailableReason } from './owner-refusal.ts';
import { sha256 } from './digest.ts';
import { isWindowsColonTarget } from './native-file-target.ts';
import { ERROR_CATALOGUE } from '../error-catalogue.ts';
@@ -231,12 +232,17 @@ export async function resolveManagedSyncContext(engine: BrainEngine, opts: SyncO
binding.owner_host_id !== localHostId() || binding.state !== 'active' || !binding.local_path) {
// #6449: a rooted source with no owner at all is the database-only one activation listed; the exit is a deliberate claim.
const unbound = source && !source.archived && !binding && source.local_path && source.config?.kind == null;
+ // #7239: a missing, archived or re-registered source, or a checkout another host id owns, refuses the same way on every
+ // retry from this host, so a sync job ends at once; a transfer or clone in progress can finish, so it stays retryable.
+ const reason = source && !source.archived ? ownerUnavailableReason(binding, source.incarnation, localHostId()) : null;
+ const deterministic = !source || source.archived || (reason !== null && reason !== 'transfer_in_progress' && reason !== 'clone_in_progress');
throw opError('owner_unavailable', 'Sync must run on the active registered worktree owner.',
unbound
? `Source ${sourceId} has a checkout path (${source.local_path}) but no canonical owner, so it is database-only and there is no checkout to sync; nothing changed. `
+ `To make this host its owner (a brain-wide change: ask the user first), preview with gbrain sources writer claim ${sourceId} --path ${source.local_path} --dry-run --json, then ${unboundBindCommand(sourceId, source.local_path)}; afterwards run gbrain sync --no-pull --source ${sourceId}.`
: `Source ${sourceId} is archived, re-registered, or not bound to an active worktree owned by this host. Run its sync on the owner host that gbrain sources writer status --source ${sourceId} --json names; do not claim or transfer the source to make this host the owner.`,
- { fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'], consent: [], actor: 'agent', requires_exclusive: false,
+ { ...(reason ? { reason } : {}), ...(deterministic ? { retryable: false } : {}),
+ fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'], consent: [], actor: 'agent', requires_exclusive: false,
why: 'Shows the owning host, binding state and incarnation of the source.' } });
}
const registeredRoot = resolve(binding.local_path, binding.relative_path);
diff --git a/src/core/text-safe.ts b/src/core/text-safe.ts
index 5d0d32f7eb..36d0735150 100644
--- a/src/core/text-safe.ts
+++ b/src/core/text-safe.ts
@@ -57,6 +57,20 @@ export function wellFormedJson<T>(value: T): T {
return value;
}
+/**
+ * #7240: `wellFormedJson` plus U+0000 → U+FFFD in every string and key, the other input Postgres refuses inside a
+ * JSONB value (22P05). One such character in a job payload refused the whole insert, so the phase that submitted it
+ * failed and cancelled every child it had queued.
+ */
+export function jsonbSafeJson<T>(value: T): T {
+ if (typeof value === 'string') return ensureWellFormed(value).replaceAll('\u0000', '\uFFFD') as T;
+ if (Array.isArray(value)) return value.map(jsonbSafeJson) as T;
+ if (value && typeof value === 'object') {
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [jsonbSafeJson(key), jsonbSafeJson(item)])) as T;
+ }
+ return value;
+}
+
function isHighSurrogate(code: number): boolean {
return code >= 0xd800 && code <= 0xdbff;
}
diff --git a/test/autopilot-sync-refusal-hold-7239.test.ts b/test/autopilot-sync-refusal-hold-7239.test.ts
new file mode 100644
index 0000000000..e640c1d434
--- /dev/null
+++ b/test/autopilot-sync-refusal-hold-7239.test.ts
@@ -0,0 +1,99 @@
+/**
+ * #7239: a sync job refused by a deterministic refusal (job_outcome 'refused') is refused again until its cause is
+ * fixed, so autopilot's freshness dispatch stops queueing one per slot: the source waits out the failure cooldown for
+ * its refusal count, the hold is stated once per refused job, and a completed sync job clears it.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { LATEST_VERSION } from '../src/core/migrate.ts';
+import { dispatchFreshnessSyncs, readSyncRefusalHolds } from '../src/commands/autopilot-dispatch.ts';
+
+let engine: PGLiteEngine;
+let home: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.setConfig('version', String(LATEST_VERSION));
+ home = mkdtempSync(join(tmpdir(), 'gbrain-7239-'));
+});
+
+const inHome = <T,>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: home }, fn);
+async function checkoutSource(id: string): Promise<void> {
+ const dir = join(home, id);
+ mkdirSync(dir, { recursive: true });
+ execFileSync('git', ['-C', dir, 'init', '-q']);
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)', [id, dir, '{}']);
+}
+async function settledSync(sourceId: string, outcome: 'refused' | 'completed', minutesAgo = 0): Promise<number> {
+ const result = outcome === 'refused' ? { job_outcome: 'refused', refusal: { code: 'writer_coordinator_required', message: 'm', docs_cmd: ['gbrain', 'errors', 'writer_coordinator_required'] } } : { ok: true };
+ const [row] = await engine.executeRaw<{ id: number }>(
+ `INSERT INTO minion_jobs (name, queue, status, data, result, finished_at, submission_authority)
+ VALUES ('sync', 'default', $1, $2::text::jsonb, $3::text::jsonb, now() - ($4::int * interval '1 minute'), '{"kind":"trusted_local","version":1}'::jsonb) RETURNING id`,
+ [outcome === 'refused' ? 'dead' : 'completed', JSON.stringify({ sourceId }), JSON.stringify(result), minutesAgo],
+ );
+ return row.id;
+}
+const waitingSyncs = async () => (await engine.executeRaw<{ src: string }>("SELECT data->>'sourceId' AS src FROM minion_jobs WHERE name='sync' AND status='waiting' ORDER BY id")).map(r => r.src);
+
+async function tick(): Promise<Array<Record<string, unknown>>> {
+ const lines: string[] = [];
+ const write = process.stderr.write.bind(process.stderr);
+ const log = console.log;
+ (process.stderr as { write: unknown }).write = (chunk: unknown) => { lines.push(String(chunk)); return true; };
+ console.log = () => {};
+ try {
+ await dispatchFreshnessSyncs(engine, new MinionQueue(engine), { baseInterval: 60, slot: `slot-${Math.random()}`, timeoutMs: 60_000, jsonMode: true });
+ } finally {
+ (process.stderr as { write: unknown }).write = write;
+ console.log = log;
+ }
+ return lines.flatMap(l => l.split('\n')).filter(Boolean).map(l => JSON.parse(l));
+}
+
+describe('#7239 refused automatic syncs back off', () => {
+ test('a source whose last sync job was refused gets no new sync job this slot; its neighbour still does', () => inHome(async () => {
+ await checkoutSource('source-a');
+ await checkoutSource('source-b');
+ const refused = await settledSync('source-a', 'refused');
+ const first = await tick();
+ const second = await tick();
+ expect(await waitingSyncs()).toEqual(['source-b']);
+ const holds = [...first, ...second].filter(e => e.event === 'freshness_sync_refused');
+ expect(holds).toEqual([expect.objectContaining({ source_id: 'source-a', job_id: refused, code: 'writer_coordinator_required', refusals: 1 })]);
+ }));
+
+ test('the hold grows with consecutive refusals and lapses after its cooldown', () => inHome(async () => {
+ await settledSync('source-a', 'refused', 11);
+ expect((await readSyncRefusalHolds(engine)).has('source-a')).toBe(false);
+ await settledSync('source-a', 'refused', 5);
+ const hold = (await readSyncRefusalHolds(engine)).get('source-a');
+ expect(hold?.count).toBe(2);
+ expect(hold!.retry_at - Date.now()).toBeGreaterThan(14 * 60_000);
+ }));
+
+ test('a completed sync job after the refusal clears the hold, and the cooldown knob at 0 disables it', () => inHome(async () => {
+ await checkoutSource('source-a');
+ await settledSync('source-a', 'refused', 2);
+ expect((await readSyncRefusalHolds(engine)).has('source-a')).toBe(true);
+ await engine.setConfig('autopilot.failure_cooldown_min', '0');
+ expect((await readSyncRefusalHolds(engine)).size).toBe(0);
+ await engine.setConfig('autopilot.failure_cooldown_min', '10');
+ await settledSync('source-a', 'completed', 1);
+ expect((await readSyncRefusalHolds(engine)).size).toBe(0);
+ await tick();
+ expect(await waitingSyncs()).toEqual(['source-a']);
+ }));
+});
diff --git a/test/dream-synthesize-submit-failure-7240.test.ts b/test/dream-synthesize-submit-failure-7240.test.ts
new file mode 100644
index 0000000000..83a3c6b3d3
--- /dev/null
+++ b/test/dream-synthesize-submit-failure-7240.test.ts
@@ -0,0 +1,92 @@
+/**
+ * #7240: in a large deployment every dream synthesize run failed right after fan-out with Postgres 22P02 ("invalid
+ * input syntax for type json") and its private-queue cleanup cancelled every child it had queued, so synthesize
+ * children were cancelled ~17 s after creation and none ever ran. Two causes, two fixes:
+ * - a child payload with a lone UTF-16 surrogate (or U+0000) was refused by the JSONB insert: queue.add now stores
+ * such strings well-formed (U+FFFD), for every submitter;
+ * - one transcript whose child could not be queued failed the whole phase: it is now skipped (submit_failed) with
+ * its own chunks rolled back, and every other transcript's children still run.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { createHash } from 'node:crypto';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { runPhaseSynthesize, TRIAGE_VERSION } from '../src/core/cycle/synthesize.ts';
+import { TIER_DEFAULTS } from '../src/core/model-config.ts';
+
+let engine: PGLiteEngine;
+let schemaVersion: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+ schemaVersion = (await engine.getConfig('version')) ?? '7';
+}, 60_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.setConfig('version', schemaVersion);
+});
+
+describe('#7240 queue.add stores JSONB-unsafe strings well-formed', () => {
+ test('a lone surrogate or U+0000 in job data no longer refuses the insert', async () => {
+ const queue = new MinionQueue(engine);
+ const job = await queue.add('subagent', { prompt: 'split emoji \ud83d here', note: 'nul \u0000 byte', nested: [{ k: '\udc00' }] },
+ { queue: 'dream-inline-1-abcdef12' }, { allowProtectedSubmit: true });
+ const row = (await queue.getJob(job.id))!;
+ expect(row.data).toMatchObject({ prompt: 'split emoji \uFFFD here', note: 'nul \uFFFD byte', nested: [{ k: '\uFFFD' }] });
+ });
+});
+
+describe('#7240 one transcript that cannot be queued does not cancel the run', () => {
+ test('the failing transcript is skipped submit_failed; the others are queued and not reconciled away', async () => {
+ const brainDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gbrain-7240-brain-'));
+ const corpusDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gbrain-7240-corpus-'));
+ const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'gbrain-7240-home-'));
+ await engine.setConfig('dream.synthesize.enabled', 'true');
+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpusDir);
+ for (const name of ['2026-08-01-a.txt', '2026-08-02-b.txt', '2026-08-03-c.txt']) {
+ const content = `conversation in ${name}\n`.repeat(200);
+ const filePath = path.join(corpusDir, name);
+ fs.writeFileSync(filePath, content);
+ await engine.putDreamVerdict(filePath, createHash('sha256').update(content, 'utf8').digest('hex'), {
+ worth_processing: true, reasons: ['seed'], score: 0.9, content_type: null, segments: [], entities: [],
+ model: TIER_DEFAULTS.utility, triage_version: TRIAGE_VERSION,
+ });
+ }
+ const realAdd = MinionQueue.prototype.add;
+ MinionQueue.prototype.add = async function (this: MinionQueue, ...args: Parameters<typeof realAdd>) {
+ if (String((args[1] as { prompt?: unknown } | undefined)?.prompt ?? '').includes('2026-08-02-b.txt')) {
+ throw Object.assign(new Error('invalid input syntax for type json'), { code: '22P02' });
+ }
+ return realAdd.apply(this, args);
+ };
+ let result: Awaited<ReturnType<typeof runPhaseSynthesize>>;
+ let cancelledAtDrain: Array<{ status: string; error_text: string | null }> = [];
+ const drainSeam = MinionQueue.prototype.claim;
+ MinionQueue.prototype.claim = async function (this: MinionQueue, ...args: Parameters<typeof drainSeam>) {
+ cancelledAtDrain = await engine.executeRaw(`SELECT status, error_text FROM minion_jobs WHERE name = 'subagent'`);
+ await engine.executeRaw(`UPDATE minion_jobs SET status = 'cancelled', finished_at = now(), error_text = 'test: stop before run' WHERE name = 'subagent' AND status = 'waiting'`);
+ return null;
+ };
+ try {
+ result = await withEnv({ ANTHROPIC_API_KEY: undefined, GBRAIN_HOME: tmpHome }, () =>
+ runPhaseSynthesize(engine, { brainDir, dryRun: false }));
+ } finally {
+ MinionQueue.prototype.add = realAdd;
+ MinionQueue.prototype.claim = drainSeam;
+ for (const d of [brainDir, corpusDir, tmpHome]) fs.rmSync(d, { recursive: true, force: true });
+ }
+ expect(String(result.error?.code ?? '')).not.toBe('SYNTH_PHASE_FAIL');
+ // The drain saw both healthy transcripts' children still waiting (not reconciled away by a phase failure).
+ expect(cancelledAtDrain.map(r => r.status)).toEqual(['waiting', 'waiting']);
+ const skips = (result.details as { skips?: Array<{ filePath: string; reason: string }> }).skips ?? [];
+ expect(skips).toEqual([expect.objectContaining({ filePath: expect.stringContaining('2026-08-02-b.txt'), reason: 'submit_failed (22P02): invalid input syntax for type json' })]);
+ }, 60_000);
+});
diff --git a/test/minions-refusal-7239.test.ts b/test/minions-refusal-7239.test.ts
new file mode 100644
index 0000000000..e52c17a9e9
--- /dev/null
+++ b/test/minions-refusal-7239.test.ts
@@ -0,0 +1,132 @@
+/**
+ * #7239: a deterministic refusal (an error whose registry code says the same request fails the same way again)
+ * ends its job at once: one attempt, status dead, and the result names the refusal's code, reason and fix
+ * (`job_outcome: 'refused'`). A transient failure (class retryable, server or unavailable, or a concurrency code)
+ * still retries with backoff as before.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { MinionWorker } from '../src/core/minions/worker.ts';
+import { JobRefusedError, UnrecoverableError } from '../src/core/minions/errors.ts';
+import { jobRefusal } from '../src/core/minions/refusal.ts';
+import { encodeHandlerError, reconstructHandlerError } from '../src/core/minions/job-isolation.ts';
+import { opError, OperationError } from '../src/core/ops/contract.ts';
+import { CredentialError } from '../src/core/creds/errors.ts';
+import { waitFor } from './helpers/wait-for.ts';
+import { runSubagentsInline } from '../src/core/cycle/inline-drain.ts';
+
+const writerStatusFix = { argv: ['gbrain', 'sources', 'writer', 'status', '--source', 'source-a', '--json'], consent: [], actor: 'agent' as const, requires_exclusive: false, why: 'Read-only.' };
+const managedRefusal = () => opError('writer_coordinator_required', 'Managed sync requires skipping the Git pull.', 'Sync with --no-pull.', { fix: writerStatusFix });
+
+describe('#7239 jobRefusal', () => {
+ test('a caller, consent or host_only code that is not retryable is a refusal, with its code and fix', () => {
+ const r = jobRefusal(managedRefusal());
+ expect(r).toMatchObject({ code: 'writer_coordinator_required', message: 'Managed sync requires skipping the Git pull.', docs_cmd: ['gbrain', 'errors', 'writer_coordinator_required'] });
+ expect((r!.fix as { command?: string; argv?: string[] }).argv ?? (r!.fix as { command?: string }).command).toBeTruthy();
+ expect(jobRefusal(opError('connector_account_changed', 'Connector source source-a is pinned to a different account.', 'x'))?.code).toBe('connector_account_changed');
+ expect(jobRefusal(new CredentialError('not_connected', ' for alice-example'))?.code).toBe('not_connected');
+ });
+
+ test('the suggestion never rides the refusal: job rows are served remotely and a suggestion may name an account', () => {
+ const r = jobRefusal(opError('connector_account_changed', 'Connector source source-a is pinned to a different account.', 'pinned to [email protected]'));
+ expect(JSON.stringify(r)).not.toContain('[email protected]');
+ });
+
+ test('a site that marks its error retryable: false is a refusal whatever the class; retryable: true never is', () => {
+ expect(jobRefusal(opError('owner_unavailable', 'Sync must run on the active registered worktree owner.', 'x', { reason: 'host_mismatch', retryable: false }))).toMatchObject({ code: 'owner_unavailable', reason: 'host_mismatch' });
+ expect(jobRefusal(opError('writer_coordinator_required', 'm', 's', { retryable: true }))).toBeNull();
+ });
+
+ test('transient classes, concurrency codes, unregistered codes and plain errors are not refusals', () => {
+ expect(jobRefusal(opError('owner_unavailable', 'Sync must run on the active registered worktree owner.', 'x'))).toBeNull();
+ expect(jobRefusal(opError('write_pending', 'The write is accepted and is still pending.', 'x'))).toBeNull();
+ expect(jobRefusal(opError('storage_error', 'disk', 'x'))).toBeNull();
+ expect(jobRefusal(opError('unavailable', 'no key', 'x'))).toBeNull();
+ expect(jobRefusal(opError('revision_conflict', 'moved', 'x'))).toBeNull();
+ expect(jobRefusal(opError('concurrent_write', 'moved', 'x'))).toBeNull();
+ expect(jobRefusal(new OperationError('not_a_registered_code_7239', 'm'))).toBeNull();
+ expect(jobRefusal(new Error('boom'))).toBeNull();
+ expect(jobRefusal(new UnrecoverableError('dead anyway'))).toBeNull();
+ });
+
+ test('a refusal wrapped as an error cause is still found', () => {
+ expect(jobRefusal(new Error('sync failed', { cause: managedRefusal() }))?.code).toBe('writer_coordinator_required');
+ });
+
+ test('a refusal crosses the per-job child boundary intact (process isolation)', () => {
+ const encoded = encodeHandlerError(managedRefusal());
+ expect(encoded).toMatchObject({ outcome: 'error', errorKind: 'refused' });
+ const rebuilt = reconstructHandlerError(JSON.parse(JSON.stringify(encoded)));
+ expect(rebuilt).toBeInstanceOf(JobRefusedError);
+ expect(jobRefusal(rebuilt)).toEqual(jobRefusal(managedRefusal()));
+ });
+});
+
+describe('#7239 worker ends a refused job at once', () => {
+ let engine: PGLiteEngine;
+ let queue: MinionQueue;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+ queue = new MinionQueue(engine);
+ });
+ afterAll(async () => { await engine.disconnect(); });
+ beforeEach(async () => { await engine.executeRaw('DELETE FROM minion_jobs'); });
+
+ async function runOne(name: string, fail: () => Error, until: (status: string) => boolean) {
+ const job = await queue.add(name, {}, { max_attempts: 3, backoff_type: 'fixed', backoff_delay: 60_000 });
+ const worker = new MinionWorker(engine, { pollInterval: 25 });
+ let calls = 0;
+ worker.register(name, async () => { calls++; throw fail(); });
+ const running = worker.start();
+ try {
+ await waitFor(async () => until((await queue.getJob(job.id))?.status ?? ''), { timeoutMs: 10_000, label: `${name} settled` });
+ } finally {
+ worker.stop();
+ await running;
+ }
+ return { job: (await queue.getJob(job.id))!, calls };
+ }
+
+ test('a deterministic refusal is dead after one attempt, with the refusal on the result', async () => {
+ const { job, calls } = await runOne('sync', managedRefusal, s => s === 'dead');
+ expect(calls).toBe(1);
+ expect(job.attempts_made).toBe(1);
+ expect(job.error_text).toBe('Managed sync requires skipping the Git pull.');
+ expect(job.result).toMatchObject({ job_outcome: 'refused', refusal: { code: 'writer_coordinator_required', docs_cmd: ['gbrain', 'errors', 'writer_coordinator_required'] } });
+ });
+
+ test('a transient failure still retries with backoff (not dead after one attempt)', async () => {
+ const { job, calls } = await runOne('sync', () => opError('write_pending', 'The write is accepted and is still pending.', 'x'), s => s === 'delayed');
+ expect(calls).toBe(1);
+ expect(job.status).toBe('delayed');
+ expect(job.attempts_made).toBe(1);
+ expect(job.result).toBeNull();
+ });
+});
+
+describe('#7239 the dream inline drain ends a refused child at once', () => {
+ let engine: PGLiteEngine;
+ let queue: MinionQueue;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+ queue = new MinionQueue(engine);
+ });
+ afterAll(async () => { await engine.disconnect(); });
+
+ test('one handler call, dead, refusal on the result', async () => {
+ const child = await queue.add('subagent', { prompt: 'p' }, { queue: 'dream-inline-7239-a', max_attempts: 3 }, { allowProtectedSubmit: true });
+ let calls = 0;
+ await runSubagentsInline(engine, queue, 'dream-inline-7239-a', undefined, async () => { calls++; throw managedRefusal(); });
+ const row = (await queue.getJob(child.id))!;
+ expect(calls).toBe(1);
+ expect(row.status).toBe('dead');
+ expect(row.result).toMatchObject({ job_outcome: 'refused', refusal: { code: 'writer_coordinator_required' } });
+ });
+});