Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Keep the user's crontab when crontab -l fails, refuse --schedule for a mounted brain, let a tool call stop idle upkeep's sync, retry parked items each round, and embed from one runner at a time
garrytan49abed10554e
diff --git a/changelog.d/capy-gbra438-upkeep-runners.md b/changelog.d/capy-gbra438-upkeep-runners.mdindex 7e7966404f..1e913e9e86 100644--- a/changelog.d/capy-gbra438-upkeep-runners.md+++ b/changelog.d/capy-gbra438-upkeep-runners.md@@ -1,6 +1,6 @@### Upkeep runs while your agent is connected, and `--schedule` covers the rest-**An open `gbrain serve` now does the free upkeep for you, so a default install needs no service, cron job or second command.** When the agent connected to `gbrain serve` (stdio or HTTP) goes quiet, serve runs `gbrain maintain --unattended` in slices of about 3 seconds, at most one full round a day per brain, and stops a slice the moment a tool call arrives. It writes the same record that `gbrain maintain --status` and doctor read, with runner `serve`. It never deletes a page, and on a keyless brain it never spends anything. When two serves share one brain, only one runs it and the other skips. A source too big to finish within 30 slices is parked: the rest of the round finishes, serve stops doing upkeep until the next round (it tries the parked source once more after each restart), and `gbrain maintain --status` and doctor warn and name it, because `gbrain maintain --unattended` or the schedule below has to finish it. Turn it off with `gbrain config set maintenance.auto false` (or `GBRAIN_SWEEP=0`, which also stops the idle sweep).+**An open `gbrain serve` now does the free upkeep for you, so a default install needs no service, cron job or second command.** When the agent connected to `gbrain serve` (stdio or HTTP) goes quiet, serve runs `gbrain maintain --unattended` in slices of about 3 seconds, at most one full round a day per brain, and stops a slice the moment a tool call arrives. It writes the same record that `gbrain maintain --status` and doctor read, with runner `serve`. It never deletes a page, and on a keyless brain it never spends anything. When two serves share one brain, only one runs it and the other skips. A source too big to finish within 30 slices is parked: the rest of the round finishes, serve stops doing upkeep until the next round (it tries the parked source again each round and after each restart), and `gbrain maintain --status` and doctor warn and name it; `gbrain maintain --unattended` finishes it at once. A tool call that stops a slice never counts toward the 30. Turn it off with `gbrain config set maintenance.auto false` (or `GBRAIN_SWEEP=0`, which also stops the idle sweep).- `gbrain maintain --schedule` is for a brain with no agent session open most days. It installs a job that runs `gbrain maintain --unattended` every 6 hours (launchd on macOS, a systemd user timer on Linux, cron otherwise). It asks before installing, `--dry-run` shows exactly what it would write, and `--unschedule` removes it. Nothing installs it by default. A scheduled run that finds a live `gbrain serve` on the brain exits 0 with `maintenance_owned_by_serve` and leaves the work to serve.- `gbrain init` and `gbrain setup <harness>` now say how upkeep works in their first-run settings block, and how to turn it off.diff --git a/docs/architecture/key-files/commands-4-continued.md b/docs/architecture/key-files/commands-4-continued.mdindex 6d2fd2a206..638121d83d 100644--- a/docs/architecture/key-files/commands-4-continued.md+++ b/docs/architecture/key-files/commands-4-continued.md@@ -35,5 +35,5 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/embedding-migration-cli.ts` — pure, positive migration control contract, shared by the pre-engine CLI boundary and the command parser (re-exported by `commands/migrate-embeddings.ts`). Validates original argv as well as command arguments, so consumed global timeout/progress flags cannot evade validation. Unknown controls, unsupported equals forms, duplicate flags, missing values, invalid numeric ranges and unknown pace modes refuse rather than falling back, truncating, clamping or widening work. Only implemented globals are accepted; no new fact-only or deadline behavior. The flag-registry generator includes this peeled surface; the registry's embed/import unions do not define migration legality.- `test/migrate-embeddings-recovery-cli.serial.test.ts` — real migration CLI subprocesses over isolated synthetic PGLite brains. Pins recovery envelopes and private-safe help/stderr, then exercises unsupported scope/work flags, consumed timeout, malformed numeric controls, supported pacing/globals/status/help, zero dispatch and unchanged DB/config snapshots on both routes. Direct parser cases use the same adversarial matrix. Help directs deferred work back through the migration with the existing total authorization, never standalone/background embedding. The static `EMBEDDING_MIGRATION_RECOVERY` is shared with the local-only admin operation; its unchanged discriminators and restrictions remain covered by `test/migrate-embeddings-op-contract.serial.test.ts`. Archived pending projections still block destructive transitions; no silent restore or source exclusion is introduced.-- `src/core/maintenance/run.ts` + `src/core/maintenance/status.ts` — GBRA-438 free unattended upkeep. `unattendedPlan` is the `--safe` list plus `bookkeeping_gc`, split into one global item (brain-wide phases, once per window under `gbrain-cycle`) and one item per source; cycles run with `stamp: 'none'` and `deferFactEmbedding` on a keyed brain. `runUnattendedMaintenance` never throws: preflight skips (`maintenance_disabled`, `engine_degraded`, `migrations_pending`, `maintenance_owned_by_autopilot` when `autopilot.last_global_at` is under 48h old, `write_capacity_backpressure`, `cycle_already_running`) exit 0; a failed step records its code (exit 1 for `maintain`) and three same-code failures back the step off to once a week. A budgeted run parks an item unfinished after `UPKEEP_PARK_AFTER_SLICES` (30) slices in `parked` (skipped by later budgeted runs, rerun by an unbudgeted run or `retryParked`, a serve's first idle run; `readUpkeepStatus` state `parked` warns); test `test/maintenance-park-gbra438.test.ts`. The embedding step runs under `maintenance.embed_daily_usd` (default $1 per UTC day, 0 = off; spend in `maintenance.embed_spend`). The record is `maintenance.last_run` (database config, so repo-less brains have one). `readUpkeepStatus` is the one view behind `--status` and doctor. Tests: `test/maintenance-unattended.test.ts` (both engines).+- `src/core/maintenance/run.ts` + `src/core/maintenance/status.ts` — GBRA-438 free unattended upkeep. `unattendedPlan` is the `--safe` list plus `bookkeeping_gc`, split into one global item (brain-wide phases, once per window under `gbrain-cycle`) and one item per source; cycles run with `stamp: 'none'` and `deferFactEmbedding` on a keyed brain. `runUnattendedMaintenance` never throws: preflight skips (`maintenance_disabled`, `engine_degraded`, `migrations_pending`, `maintenance_owned_by_autopilot` when `autopilot.last_global_at` is under 48h old, `write_capacity_backpressure`, `cycle_already_running`) exit 0; a failed step records its code (exit 1 for `maintain`) and three same-code failures back the step off to once a week. A budgeted run parks an item its budget stopped `UPKEEP_PARK_AFTER_SLICES` (30) times, in `parked` (a foreground abort never counts; skipped by budgeted runs for the rest of the round, rerun each new round, by an unbudgeted run or by `retryParked`, a serve's first idle run; `readUpkeepStatus` state `parked` warns); test `test/maintenance-park-gbra438.test.ts`. The embedding step runs under `maintenance.embed_daily_usd` (default $1 per UTC day, 0 = off; spend in `maintenance.embed_spend`), one runner at a time (`MAINTENANCE_EMBED_LOCK_ID`; a busy lock skips it as `embed_running`). The record is `maintenance.last_run` (database config, so repo-less brains have one). `readUpkeepStatus` is the one view behind `--status` and doctor. Tests: `test/maintenance-unattended.test.ts` (both engines).- `src/core/maintenance/idle.ts` + `src/commands/maintain-schedule.ts` — GBRA-438 PR 2, the upkeep runners. `runIdleUpkeep` runs `runUnattendedMaintenance` as runner `serve` with `IDLE_UPKEEP_BUDGET_MS` (3 s) when upkeep is on and due (`upkeepDue`); the stdio serve calls it from its idle tick after the sweep, in the same in-flight slot, and stdin data, `onForegroundRequest` or shutdown aborts it. `armIdleUpkeep` is the HTTP serve's idle timer: `mcpForegroundMiddleware` (in `src/core/foreground-activity.ts`, mounted on `/mcp` by `serve-http.ts`) marks each `/mcp` POST foreground, the first tick only opens the window, one run at a time. A finished round on PGLite ends with a `CHECKPOINT` step. `maintain-schedule.ts` is routed engine-free from `src/cli/main.ts`: `--schedule` (consent `persistent_install`, `--dry-run` preview) writes a wrapper and a launchd plist, systemd user service and timer, or a `# gbrain-maintain` crontab line (pure renderers, every 6 hours); Windows and containers refuse `schedule_unsupported`; `--unschedule` removes it. A scheduled `--unattended --runner schedule` run exits 0 `maintenance_owned_by_serve` while a live serve holds the brain (PGLite lock holder, or the CLI socket on Postgres). Tests: `test/serve-idle-upkeep-gbra438.test.ts`, `test/maintenance-idle-gbra438.test.ts` (both engines, two serves on one brain), `test/maintain-schedule-gbra438.test.ts`, `test/e2e/serve-idle-upkeep-keyless-pglite.test.ts`. The cycle hands its signal to the repo-less stale link drain (`extractStaleFromDB` `signal`), so a slice stops between 25-page batches, and `runExtractFacts` yields a macrotask every 50 pages of its walk, so a timer or stdin can trip the abort mid-walk on PGLite. Bench: `scripts/bench/serve-upkeep-latency.ts` (tool-call latency during idle upkeep on a keyless repo-less PGLite brain, against a sweep-only baseline).diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 2da4ee6446..c839fc0ae7 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -4574,9 +4574,9 @@ More: [docs/guides/troubleshooting.md#runtime-build-skew](../../docs/guides/trou| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| gbrain maintain --schedule installed nothing: on Windows and in containers it has no installer. | Windows gets the schtasks line to add by hand (minimal Windows support). In a container an operating-system schedule does not survive a redeploy, so the resident gbrain serve is the upkeep runner there. | On Windows, add the printed schtasks line yourself. In a container, keep gbrain serve running; it runs free upkeep while idle. | agent | `repeat the read that failed` | 1 | no |+| gbrain maintain --schedule installed nothing: on Windows and in containers it has no installer, and it schedules the host brain only. | Windows gets the schtasks line to add by hand (minimal Windows support). In a container an operating-system schedule does not survive a redeploy, so the resident gbrain serve is the upkeep runner there. The scheduled job runs without --brain, so a mounted brain gets no schedule. | On Windows, add the printed schtasks line yourself. In a container, keep gbrain serve running; it runs free upkeep while idle. For a mounted brain, schedule gbrain --brain <id> maintain --unattended yourself. | agent | `repeat the read that failed` | 1 | no |-Reasons: `windows`, `container`.+Reasons: `windows`, `container`, `mount`.### schema_lock_blockeddiff --git a/src/commands/maintain-schedule.ts b/src/commands/maintain-schedule.tsindex 4623cae260..3cf42f04e0 100644--- a/src/commands/maintain-schedule.ts+++ b/src/commands/maintain-schedule.ts@@ -31,6 +31,9 @@ import { isConsentRefusal, printConsentRefusal, requireConsent } from '../core/cimport { setCliExitVerdict } from '../core/cli-force-exit.ts';import { writeCliError } from '../cli/cli-error.ts';import { opError } from '../core/ops/contract.ts';+import { resolveBrainId } from '../core/brain-resolver.ts';+import { HOST_BRAIN_ID } from '../core/brain-registry.ts';+import { getCliOptions } from '../core/cli-options.ts';export const SCHEDULE_INTERVAL_HOURS = 6;/** What the job runs: one unattended upkeep run, recorded with runner `schedule`. */@@ -158,6 +161,8 @@ export interface ScheduleEnv {gbrainCommand: string[];gbrainHome?: string;runtimeDir?: string;+ /** The brain this command selects (--brain, GBRAIN_BRAIN_ID, a mount); the schedule covers the host brain only. */+ brainId?: string;run: CommandRunner;/** `/run/systemd/system` exists (the host booted with systemd); the user manager is probed through `run`. */systemdBooted: boolean;@@ -177,6 +182,7 @@ export function defaultScheduleEnv(): ScheduleEnv {gbrainCommand: resolveServeGbrainCommand(),...(process.env.GBRAIN_HOME ? { gbrainHome: process.env.GBRAIN_HOME } : {}),runtimeDir: runtimeDir === '.' ? '' : runtimeDir,+ brainId: resolveBrainId(getCliOptions().brain),run: defaultCommandRunner,systemdBooted: existsSync('/run/systemd/system'),};@@ -221,9 +227,11 @@ function writeFile(path: string, content: string, mode: number, what: string): vconst describe = (r: { status: number | null; stdout: string; stderr: string }) => (r.stderr || r.stdout).trim() || `exit ${r.status}`;-async function readCrontab(run: CommandRunner): Promise<string> {+async function readCrontab(run: CommandRunner): Promise<{ lines: string[] } | { error: string }> {const r = await run(['crontab', '-l'], { timeoutMs: 15_000 });- return r.status === 0 ? r.stdout : '';+ if (r.status === 0) return { lines: r.stdout ? r.stdout.replace(/\n$/, '').split('\n') : [] };+ if (r.status === 1 && /no crontab|no such file/i.test(`${r.stderr}${r.stdout}`)) return { lines: [] };+ return { error: `crontab -l failed (${describe(r)}), so the crontab was left unchanged` };}async function writeCrontab(env: ScheduleEnv, lines: string[]): Promise<{ status: number | null; stdout: string; stderr: string }> {@@ -258,7 +266,12 @@ export async function installSchedule(target: 'macos' | 'linux-systemd' | 'linuxout.notes.push('The timer runs while your user manager runs; for runs after logout turn on lingering (loginctl enable-linger "$USER", which may need an admin).');return out;}- const kept = (await readCrontab(env.run)).split('\n').filter((l) => l.trim() !== '' && !isScheduleCronLine(l, env.names.cronMarker));+ const current = await readCrontab(env.run);+ if ('error' in current) {+ out.error = current.error;+ return out;+ }+ const kept = current.lines.filter((l) => !isScheduleCronLine(l, env.names.cronMarker));const write = await writeCrontab(env, [...kept, scheduleCronLine({ wrapperPath: paths.wrapper, logPath: paths.log, marker: env.names.cronMarker })]);if (write.status !== 0) out.error = `crontab failed: ${describe(write)}`;else out.written.push('crontab: one gbrain-maintain line');@@ -279,7 +292,9 @@ export async function uninstallSchedule(target: ScheduleTarget, env: ScheduleEnvremove(paths.service);await env.run(['systemctl', '--user', 'daemon-reload'], { timeoutMs: 15_000 });} else if (target === 'linux-cron') {- const lines = (await readCrontab(env.run)).split('\n').filter((l) => l.trim() !== '');+ const current = await readCrontab(env.run);+ const lines = 'error' in current ? [] : current.lines;+ if ('error' in current) out.error = current.error;const kept = lines.filter((l) => !isScheduleCronLine(l, env.names.cronMarker));if (kept.length !== lines.length) {const write = await writeCrontab(env, kept);@@ -324,6 +339,11 @@ export async function runMaintainSchedule(args: string[], env: ScheduleEnv = def'Keep gbrain serve running in the container (gbrain serve --http for a hosted brain): it runs free upkeep on its own while idle.', { reason: 'container' }), 'maintain', { json }));return;}+ if (env.brainId && env.brainId !== HOST_BRAIN_ID && !args.includes('--unschedule')) {+ setCliExitVerdict(writeCliError(opError('schedule_unsupported', `gbrain maintain --schedule covers the host brain only, and this command selects the mounted brain ${env.brainId}, so nothing was installed.`,+ `Run gbrain maintain --schedule without --brain for the host brain. For ${env.brainId}, add gbrain --brain ${env.brainId} maintain --unattended to a scheduler yourself.`, { reason: 'mount', detail: env.brainId }), 'maintain', { json }));+ return;+ }if (args.includes('--unschedule')) {const result = await uninstallSchedule(target, env);if (result.error) setCliExitVerdict(1);diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 34f1d3fd30..cf8e44fd20 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -85,7 +85,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'lint': ['--abbrev-ref', '--accept-pending', '--add', '--admin-intent', '--adopt-slug-path', '--as', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--porcelain', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--readers', '--rebase', '--require-clean', '--resolve', '--scan-secrets', '--scan-timeout', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--stdin', '--timeout', '--timings', '--unset-all', '--untracked-files', '--verify', '--wait', '--yes'],'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],- 'maintain': ['--absolute-git-dir', '--accept-dns', '--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--alert', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--attest-read', '--audit', '--background', '--bg', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--cask', '--catch-up', '--check-only', '--class', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--delete-brain', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--enable-dcr', '--entity', '--exclude', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--https', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-extensions', '--no-extract', '--no-hard-deadline', '--no-instructions', '--no-pull', '--no-renames', '--no-schema-pack', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--operator', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefix', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--public-url', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw-only', '--reader-mode', '--readers', '--reads-unscoped', '--reauth', '--rebase', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repo', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--runner', '--safe', '--scan-secrets', '--schedule', '--scope', '--scopes', '--serves', '--session', '--set-path', '--show-current', '--show-toplevel', '--since', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--to', '--token', '--top-k', '--trust', '--type', '--unattended', '--unindexed', '--unschedule', '--untracked-files', '--url-env', '--user', '--verbose', '--verify', '--version', '--where', '--window', '--workers', '--working-tree', '--workspace', '--yes'],+ 'maintain': ['--absolute-git-dir', '--accept-dns', '--accept-pending', '--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--alert', '--all', '--allow-outside-source-root', '--apply', '--as', '--assign-corpus', '--attest-read', '--audit', '--background', '--bg', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--cask', '--catch-up', '--check-only', '--class', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--db-url', '--delete-brain', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--enable-dcr', '--entity', '--exclude', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--https', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-extensions', '--no-extract', '--no-hard-deadline', '--no-instructions', '--no-pull', '--no-renames', '--no-schema-pack', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--operator', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefix', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--public-url', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw-only', '--reader-mode', '--readers', '--reads-unscoped', '--reauth', '--rebase', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repo', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--runner', '--safe', '--scan-secrets', '--schedule', '--scope', '--scopes', '--serves', '--session', '--set-path', '--show-current', '--show-toplevel', '--since', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--trust', '--type', '--unattended', '--unindexed', '--unschedule', '--untracked-files', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--where', '--window', '--workers', '--working-tree', '--workspace', '--yes'],'mcp': ['--admin-token-file', '--advertise', '--agent', '--all', '--arg', '--attest-actor', '--attest-ops', '--attest-read', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--cursor', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--email', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--groups', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--member', '--name', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--qm', '--queue', '--reason', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],'memory-proposals': ['--all', '--brain', '--dry-run', '--help', '--json', '--limit', '--reason', '--replace', '--source'],'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--as', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--statement-timeout', '--status', '--timeout', '--timings', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex 9f131548e7..d92fdb7e16 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -1301,6 +1301,7 @@ async function runPhaseSync(dryRun: boolean,pull: boolean,willRunExtractPhase: boolean,+ signal?: AbortSignal,): Promise<SyncPhaseResult> {try {const { performSync } = await import('../commands/sync.ts');@@ -1322,6 +1323,7 @@ async function runPhaseSync(// If extract isn't scheduled (e.g. `gbrain dream --phase sync`),// sync's inline extract still runs to preserve prior behavior.drainHolder: { kind: 'cycle', id: null }, // #6712 PR 1: a busy drain lease skips like a busy sync lock+ ...(signal ? { signal } : {}),});const syncedCount = result.added + result.modified;// #3068: a pull_failed partial means the internal git pull failed and the@@ -2278,8 +2280,8 @@ async function runCycleUnscoped(// coverage. Raced like the other five: an abandoned wait is safe —// sync checkpoints its progress, holds its own per-source lock (the// successor's sync phase skips with lock-busy), and its stall- // watchdog bounds the dangling import. Signal threading lands in W6.- const { result, duration_ms } = await racedTimePhase(() => runPhaseSync(engine, brainDir, dryRun, pull, phases.includes('extract')), 'sync');+ // watchdog bounds the dangling import. The cycle signal stops the import between files (GBRA-438).+ const { result, duration_ms } = await racedTimePhase(() => runPhaseSync(engine, brainDir, dryRun, pull, phases.includes('extract'), cycleSignal), 'sync');result.duration_ms = duration_ms;// Capture changed slugs for incremental extract.syncPagesAffected = (result as SyncPhaseResult).pagesAffected;diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex d3ee86c531..1d6d2d3f0a 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -72,7 +72,7 @@ export const CODES = {engine_degraded: { class: 'unavailable', summary: 'The brain database was unreachable (the engine is in degraded mode), so background work such as unattended upkeep skipped this run.', why: 'A degraded engine answers from its last state and reconnects on its own; writing maintenance results then would be lost or refused.', suggestion: 'Run gbrain doctor --json and report the connection problem it names.' },maintenance_disabled: { class: 'caller', exit: 0, summary: 'Free unattended upkeep is off on this brain (maintenance.auto is false), so nothing ran.', why: 'The person turned upkeep off; doctor reads it as off, not stale.', suggestion: 'Turn it back on with gbrain config set maintenance.auto true.' },maintenance_owned_by_serve: { class: 'caller', exit: 0, summary: 'A live gbrain serve owns this brain and runs free upkeep while idle, so the scheduled upkeep run did nothing (serve owns upkeep).', why: 'One runner at a time: the serve holds the brain (the PGLite lock, or the warm CLI socket on Postgres) and runs the same free upkeep on its idle tick.', suggestion: 'Nothing to do; gbrain maintain --status shows the last run and its runner.' },- schedule_unsupported: { class: 'caller', reasons: ['windows', 'container'], summary: 'gbrain maintain --schedule installed nothing: on Windows and in containers it has no installer.', why: 'Windows gets the schtasks line to add by hand (minimal Windows support). In a container an operating-system schedule does not survive a redeploy, so the resident gbrain serve is the upkeep runner there.', suggestion: 'On Windows, add the printed schtasks line yourself. In a container, keep gbrain serve running; it runs free upkeep while idle.' },+ schedule_unsupported: { class: 'caller', reasons: ['windows', 'container', 'mount'], summary: 'gbrain maintain --schedule installed nothing: on Windows and in containers it has no installer, and it schedules the host brain only.', why: 'Windows gets the schtasks line to add by hand (minimal Windows support). In a container an operating-system schedule does not survive a redeploy, so the resident gbrain serve is the upkeep runner there. The scheduled job runs without --brain, so a mounted brain gets no schedule.', suggestion: 'On Windows, add the printed schtasks line yourself. In a container, keep gbrain serve running; it runs free upkeep while idle. For a mounted brain, schedule gbrain --brain <id> maintain --unattended yourself.' },schedule_install_failed: { class: 'host_only', retryable: false, actor: 'user', summary: 'gbrain maintain --schedule wrote its files, but the operating-system scheduler (launchctl, systemctl --user or crontab) refused the job.', why: 'The scheduler belongs to the host: a missing user session bus, a locked crontab or a launchd error stops the job from loading.', suggestion: 'Read the scheduler error in the message, fix it on the host, then run gbrain maintain --schedule --yes again (gbrain maintain --unschedule removes the files).' },maintenance_owned_by_autopilot: { class: 'caller', exit: 0, summary: 'An autopilot keeps this brain maintained (its brain-wide pass stamped autopilot.last_global_at within 48 hours), so free upkeep did nothing.', why: 'One owner per brain: the autopilot already runs the free phases and more, on any host sharing the database.', suggestion: 'Nothing to do; gbrain autopilot --status shows the daemon.' },on_behalf_of_invalid_audience: { class: 'caller', summary: "A shared agent's request named its audience (the X-Gbrain-On-Behalf-Of header or request-level _meta.on_behalf_of) in a form gbrain does not accept: empty, more than 50 entries, an entry that is not a member id, group:<id> or guest, or a header and _meta that name different audiences. Nothing was read.", why: 'The audience decides whose notes the agent may read, so an audience gbrain cannot read exactly is refused instead of guessed.', docs: 'docs/guides/write-refusals.md#on_behalf_of_invalid_audience', suggestion: 'Fix the harness code that sets the audience: 1-50 entries, each a member id, group:<id> or guest, the same in the header and _meta when both are sent.' },diff --git a/src/core/maintenance/run.ts b/src/core/maintenance/run.tsindex a8dc2ebc71..afc86c4645 100644--- a/src/core/maintenance/run.ts+++ b/src/core/maintenance/run.ts@@ -33,6 +33,7 @@ import { readDecideConfig } from '../ai/decide/config.ts';import { hasTypesafeKey } from '../ai/decide/index.ts';import { isEngineDegraded } from '../degraded-marker.ts';import { hasPendingMigrations } from '../migrate-pending.ts';+import { tryAcquireDbLock } from '../db-lock.ts';export const MAINTENANCE_LAST_RUN_KEY = 'maintenance.last_run';export const MAINTENANCE_AUTO_KEY = 'maintenance.auto';@@ -46,11 +47,13 @@ export const UPKEEP_INTERVAL_MS = 24 * 60 * 60 * 1000;export const UPKEEP_BACKOFF_FAILURES = 3;export const UPKEEP_BACKOFF_MS = 7 * 24 * 60 * 60 * 1000;/**- * A budgeted (serve) run parks an item that started and did not finish in this many slices of one round: the round- * settles without it, budgeted runs skip it, and an unbudgeted run (`gbrain maintain --unattended`, the schedule) or a- * serve's first idle run (`retryParked`) runs it again.+ * A budgeted (serve) run parks an item that its budget stopped this many times in one round: the round settles without+ * it and budgeted runs skip it until the next round, an unbudgeted run (`gbrain maintain --unattended`, the schedule) or+ * a serve's first idle run (`retryParked`) runs it again. A foreground request's abort never counts as a slice.*/export const UPKEEP_PARK_AFTER_SLICES = 30;+/** One runner embeds at a time, so two serves finishing a round together never both spend the day's cap. */+export const MAINTENANCE_EMBED_LOCK_ID = 'gbrain-maintenance-embed';/** An autopilot whose global pass is younger than this owns upkeep. */export const AUTOPILOT_OWNS_WITHIN_MS = 48 * 60 * 60 * 1000;@@ -374,8 +377,8 @@ export async function runUnattendedMaintenance(engine: BrainEngine, opts: Upkeepconst sources = (await engine.listAllSources()).sort((a, b) => a.id.localeCompare(b.id));const keys = ['global', ...sources.map((source) => `source:${source.id}`)];const parked = (prior?.parked ?? []).filter((p) => keys.includes(p.key)).map((p) => ({ ...p }));- const retrying = !budgeted || opts.retryParked ? parked.map((p) => p.key) : [];const retryOnly = !upkeepDue(prior, now);+ const retrying = !budgeted || opts.retryParked || (!retryOnly && !prior?.cursor) ? parked.map((p) => p.key) : [];if (retryOnly && retrying.length === 0) {return { status: 'not_due', exit: 0, message: `Upkeep already ran at ${prior!.at}; next due at ${prior!.next_due_at}.`, record: prior! };}@@ -409,7 +412,7 @@ export async function runUnattendedMaintenance(engine: BrainEngine, opts: Upkeepretry.delete(item.key);};const unfinished = (): void => {- if (!budgeted) return;+ if (!budgeted || opts.signal?.aborted) return;const slices = (attempts[item.key] ?? 0) + 1;if (slices < UPKEEP_PARK_AFTER_SLICES) { attempts[item.key] = slices; return; }const entry = parked.find((p) => p.key === item.key);@@ -458,9 +461,17 @@ export async function runUnattendedMaintenance(engine: BrainEngine, opts: Upkeepconst finished = items.every((item) => done.includes(item.key));let embed: UpkeepRecord['embed'];if (finished && plan.embedding && !opts.signal?.aborted) {- const result = await runEmbedStep(engine, now, opts.signal);- steps.push(result.step);- embed = result.embed;+ const lock = await tryAcquireDbLock(engine, MAINTENANCE_EMBED_LOCK_ID);+ if (!lock) steps.push({ name: 'embed', scope: 'global', status: 'skipped', reason: 'embed_running' });+ else {+ try {+ const result = await runEmbedStep(engine, now, opts.signal);+ steps.push(result.step);+ embed = result.embed;+ } finally {+ await lock.release();+ }+ }}if (finished && engine.kind === 'pglite' && !opts.signal?.aborted) steps.push(await checkpointStep(engine));const failed = steps.filter((step) => step.status === 'fail');diff --git a/src/core/maintenance/status.ts b/src/core/maintenance/status.tsindex ab49b0dedb..3a3536f52e 100644--- a/src/core/maintenance/status.ts+++ b/src/core/maintenance/status.ts@@ -120,7 +120,7 @@ export async function readUpkeepStatus(engine: BrainEngine, nowMs: number = Dateif (base.parked.length) {const named = base.parked.map((p) => `${p.key} after ${p.slices} slices`).join(', ');return { ...base, fix, alternative_fix: scheduleFix(), state: 'parked',- message: `Upkeep inside serve parked ${named}; the scheduled run or gbrain maintain --unattended finishes it.${purgeNote}${spendNote}` };+ message: `Upkeep inside serve parked ${named}; serve tries it again next round, and gbrain maintain --unattended finishes it now.${purgeNote}${spendNote}` };}const ran = record.steps.filter((s) => s.status === 'ok' || s.status === 'warn').length;const due = Date.parse(record.next_due_at) - nowMs;diff --git a/test/cycle/cycle-sync-uncommitted-warn.serial.test.ts b/test/cycle/cycle-sync-uncommitted-warn.serial.test.tsindex 882e43688a..4e46ba3715 100644--- a/test/cycle/cycle-sync-uncommitted-warn.serial.test.ts+++ b/test/cycle/cycle-sync-uncommitted-warn.serial.test.ts@@ -14,9 +14,10 @@import { describe, test, expect, mock, beforeAll, afterAll } from 'bun:test';let uncommitted: { added: number; modified: number; deleted: number } | undefined;+let onSync: ((opts: { signal?: AbortSignal }) => void) | undefined;mock.module('../../src/commands/sync.ts', () => ({- performSync: async () => ({+ performSync: async (_engine: unknown, opts: { signal?: AbortSignal }) => (onSync?.(opts), {status: 'synced',fromCommit: 'abcd',toCommit: 'efgh',@@ -69,4 +70,17 @@ describe('runCycle sync phase — uncommitted working-tree drift', () => {expect(dirtyPhase?.summary).toContain('sync.include_working_tree');expect(dirtyPhase?.details.uncommitted).toEqual({ added: 2, modified: 1, deleted: 0 });}, 60_000);++ test('the cycle signal reaches performSync, so a tool call or the idle budget stops the import (GBRA-438)', async () => {+ uncommitted = undefined;+ const controller = new AbortController();+ let seen: boolean | undefined;+ onSync = (opts) => { controller.abort(); seen = opts.signal?.aborted; };+ try {+ await runCycle(engine, { brainDir: '/tmp/brain', phases: ['sync'], signal: controller.signal }).catch(() => null);+ } finally {+ onSync = undefined;+ }+ expect(seen).toBe(true);+ }, 60_000);});diff --git a/test/maintain-schedule-gbra438.test.ts b/test/maintain-schedule-gbra438.test.tsindex b72f7fe5ff..6852b6a6a4 100644--- a/test/maintain-schedule-gbra438.test.ts+++ b/test/maintain-schedule-gbra438.test.ts@@ -176,6 +176,48 @@ describe('gbrain maintain --schedule', () => {expect(existsSync(wrapper)).toBe(false);});+ test('a crontab -l that fails for any reason but "no crontab" leaves the crontab alone: install and --unschedule write nothing', async () => {+ const failing: CommandRunner = async (argv) => {+ calls.push(argv);+ if (argv[0] === 'crontab' && argv[1] === '-l') return { status: 1, stdout: '', stderr: 'crontab: cannot open your crontab: permission denied' };+ return run(argv);+ };+ const before = crontab;+ await runMaintainSchedule(['--schedule', '--yes', '--json'], { ...env('linux'), run: failing });+ expect(currentExitCode()).toBe(exitCodeForCode('schedule_install_failed'));+ expect([...out, ...errOut].join('\n')).toContain('crontab -l failed');+ _resetCliExitVerdictForTests();+ await runMaintainSchedule(['--unschedule', '--json'], { ...env('linux'), run: failing });+ expect(currentExitCode()).toBe(1);+ expect(calls.filter((c) => c[0] === 'crontab' && c[1] !== '-l')).toEqual([]);+ expect(crontab).toBe(before);+ });++ test('"no crontab for user" reads as an empty crontab, and an install keeps the other lines exactly, blank ones included', async () => {+ const none: CommandRunner = async (argv) => {+ if (argv[0] === 'crontab' && argv[1] === '-l') { calls.push(argv); return { status: 1, stdout: '', stderr: 'no crontab for user' }; }+ return run(argv);+ };+ await runMaintainSchedule(['--schedule', '--yes', '--json'], { ...env('linux'), run: none });+ expect(currentExitCode()).toBe(0);+ expect(crontab.split('\n').filter(Boolean)).toHaveLength(1);+ expect(crontab).toEndWith('# gbrain-maintain\n');+ crontab = 'MAILTO=""\n\n0 1 * * * /usr/bin/true\n';+ out.length = 0;+ await runMaintainSchedule(['--schedule', '--yes', '--json'], env('linux'));+ expect(crontab.startsWith('MAILTO=""\n\n0 1 * * * /usr/bin/true\n')).toBe(true);+ });++ test('a mounted brain gets no schedule: --schedule refuses with schedule_unsupported (reason mount) and writes nothing', async () => {+ await runMaintainSchedule(['--schedule', '--yes', '--json'], { ...env('linux'), brainId: 'work' });+ expect(currentExitCode()).toBe(exitCodeForCode('schedule_unsupported'));+ const text = [...out, ...errOut].join('\n');+ expect(text).toContain('mount');+ expect(text).toContain('gbrain --brain work maintain --unattended');+ expect(existsSync(join(root, 'home', '.gbrain', 'maintain-run.sh'))).toBe(false);+ expect(calls.filter((c) => c[0] === 'crontab')).toEqual([]);+ });+test('--yes on a systemd host writes the service and timer and enables the timer', async () => {await runMaintainSchedule(['--schedule', '--yes', '--json'], { ...env('linux'), systemdBooted: true });expect(json()).toMatchObject({ status: 'installed', target: 'linux-systemd' });diff --git a/test/maintenance-idle-gbra438.test.ts b/test/maintenance-idle-gbra438.test.tsindex 7f56190a2c..15ec3a52e3 100644--- a/test/maintenance-idle-gbra438.test.ts+++ b/test/maintenance-idle-gbra438.test.ts@@ -19,7 +19,9 @@ import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { PostgresEngine } from '../src/core/postgres-engine.ts';import { runCycle, type CycleOpts } from '../src/core/cycle.ts';-import { readUpkeepRecord, unattendedPlan, type SafePhaseProviders } from '../src/core/maintenance/run.ts';+import { MAINTENANCE_EMBED_LOCK_ID, readUpkeepRecord, runUnattendedMaintenance, unattendedPlan, type SafePhaseProviders } from '../src/core/maintenance/run.ts';+import { tryAcquireDbLock } from '../src/core/db-lock.ts';+import type { CycleReport } from '../src/core/cycle.ts';import { runIdleUpkeep } from '../src/core/maintenance/idle.ts';import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';import { checkUnattendedMaintenance } from '../src/commands/doctor/checks/unattended-maintenance.ts';@@ -45,6 +47,19 @@ for (const kind of testBackends()) {await engine.executeRaw('DELETE FROM pages');});+ test('one runner embeds at a time: while another holds the embed lock, a finished round skips embed as embed_running and spends nothing', async () => {+ const lock = (await tryAcquireDbLock(engine, MAINTENANCE_EMBED_LOCK_ID))!;+ try {+ const outcome = await runUnattendedMaintenance(engine, {+ runner: 'cli', providers: { ...KEYLESS, embedding: true }, cycle: async () => ({ status: 'ok', phases: [] }) as unknown as CycleReport,+ });+ expect(outcome.record?.steps).toContainEqual({ name: 'embed', scope: 'global', status: 'skipped', reason: 'embed_running' });+ expect(await engine.getConfig('maintenance.embed_spend')).toBeNull();+ } finally {+ await lock.release();+ }+ });+test('maintenance.auto=false: nothing runs and nothing is recorded', async () => {await engine.setConfig('maintenance.auto', 'false');let cycles = 0;diff --git a/test/maintenance-park-gbra438.test.ts b/test/maintenance-park-gbra438.test.tsindex 32bc1dacc3..4412e0bb30 100644--- a/test/maintenance-park-gbra438.test.ts+++ b/test/maintenance-park-gbra438.test.ts@@ -19,7 +19,7 @@import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { runCycle, type CycleOpts } from '../src/core/cycle.ts';+import { runCycle, type CycleOpts, type CycleReport } from '../src/core/cycle.ts';import { UPKEEP_PARK_AFTER_SLICES, readUpkeepRecord, runUnattendedMaintenance, type SafePhaseProviders } from '../src/core/maintenance/run.ts';import { runIdleUpkeep } from '../src/core/maintenance/idle.ts';import { readUpkeepStatus } from '../src/core/maintenance/status.ts';@@ -126,3 +126,56 @@ describe('budgeted upkeep parks an item that cannot finish inside its slices (PGexpect((await readUpkeepStatus(engine)).state).toBe('ok');}, 180_000);});++describe('parking counts only the budget, and a new round tries a parked item again (PGLite, counted fake cycle)', () => {+ let engine: BrainEngine;+ const ok = { status: 'ok', phases: [] } as unknown as CycleReport;++ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite' } as never);+ await engine.initSchema();+ }, 60_000);+ afterAll(async () => { await engine.disconnect(); });++ test('a tool call that stops a slice never counts toward parking', async () => {+ for (let n = 0; n < UPKEEP_PARK_AFTER_SLICES + 5; n++) {+ const foreground = new AbortController();+ await runUnattendedMaintenance(engine, {+ runner: 'serve', budgetMs: 60_000, signal: foreground.signal, providers: KEYLESS,+ cycle: async (_e, o) => {+ if (o.sourceId !== 'default') return ok;+ foreground.abort();+ throw new Error('stopped by a request');+ },+ });+ }+ const record = (await readUpkeepRecord(engine))!;+ expect(record.parked ?? []).toEqual([]);+ expect(record.cursor?.attempts?.['source:default']).toBeUndefined();+ });++ test('a new round gives a parked item a fresh set of slices', async () => {+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'maintenance.%'");+ const calls: string[] = [];+ const slow = async (_e: BrainEngine | null, o: CycleOpts): Promise<CycleReport> => {+ calls.push(o.sourceId ?? 'global');+ if (o.sourceId !== 'default') return ok;+ if (!o.signal!.aborted) await new Promise<void>((resolve) => o.signal!.addEventListener('abort', () => resolve()));+ throw new Error('stopped by the budget');+ };+ const slice = (now?: Date) => runUnattendedMaintenance(engine, {+ runner: 'serve', budgetMs: 5, signal: new AbortController().signal, providers: KEYLESS, cycle: slow, ...(now ? { now: () => now } : {}),+ });+ for (let n = 0; n < UPKEEP_PARK_AFTER_SLICES + 5; n++) {+ await slice();+ if ((await readUpkeepRecord(engine))?.cursor === null) break;+ }+ const parked = (await readUpkeepRecord(engine))!;+ expect(parked.parked).toEqual([{ key: 'source:default', since: expect.any(String), slices: UPKEEP_PARK_AFTER_SLICES }]);+ calls.length = 0;+ await slice(new Date(Date.parse(parked.next_due_at) + 60_000));+ expect(calls).toContain('default');+ expect((await readUpkeepRecord(engine))!.cursor?.attempts?.['source:default']).toBe(1);+ });+});