Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(upgrade): load the post-swap tail statically so a successful upgrade exits 0 (#6604)
time-attackb2844d3a0f89
diff --git a/docs/architecture/key-files/commands-6.md b/docs/architecture/key-files/commands-6.mdindex dfb69d9d53..981fc6a86c 100644--- a/docs/architecture/key-files/commands-6.md+++ b/docs/architecture/key-files/commands-6.md@@ -12,7 +12,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/transcripts.ts` — the transcripts command family, all local-only (`ctx.remote=false` by construction). `recent`: raw `.txt` corpus reads via `listRecentTranscripts` (same library as the gated `get_recent_transcripts` op). `ingest <path-or-glob>`: the cross-harness session importer — resolves ONE source id (6-tier chain), threads activePack once, streams progress (phase `transcripts.ingest`), and calls `runTranscriptsIngest` with the CLI's `makeContext` context, so on a writer-claimed brain each rendered part is submitted as a `put_page` write request naming the page's current revision (unmanaged brains and dry runs keep the direct importer; `recover codex --apply` passes the same context; pinned by `test/transcripts-managed-ingest.test.ts`); embedding is OFF by default (embed backfill is the catch-up lane; the embed flag opts in); the max-bytes flag (validated size string, e.g. `4gb`) overrides the per-format file/store byte caps for oversized stores while omission preserves each adapter's native default; the since-last watermark is an op-checkpoint (op `transcripts-ingest`, fingerprint = source + pathspec + format + adapter version + any explicit byte cap via `ingestCheckpointFingerprintInput` — a checkpoint written under one cap is never silently reused under another, so a capped run's skipped tail can't read as scanned; the pathspec binds the user-stated paths resolved + sorted, and the no-arg/all lane substitutes hostname + sorted harness roots so DB-backed checkpoints shared across a brain's machines never let one machine inherit another's watermark and skip sessions it never scanned) advanced ONLY after a clean, untruncated, non-dry scan; no-arg = confined discovery table, the all flag imports the discovered set. `status`: found-vs-imported gap table (disk scan vs ONE conversation-pages frontmatter query — `executeRaw`, both engines — in `src/core/transcripts/discover.ts`) — the correctness surface that catches late-arriving sessions no watermark can. The facts flag hands EVERY touched slug (including hash-skipped) to `src/core/transcripts/ingest-facts.ts`; a page that fails extraction counts in `facts.pagesFailed`, stays unfinished, and makes the command exit 1. Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + SELF_HELP_WITHOUT_ENGINE (engine-free help). `expandTilde(raw)` (bare `~`, leading `~/` or `~\\` → home dir; `~user` forms and a mid-string `~` stay literal) is the one tilde expansion `expandPaths` applies to every path spec. `recover codex` (`src/commands/transcripts-recover.ts`, logic `src/core/transcripts/recover.ts`; D15 for #5163): finds codex conversation pages in one source with no `**User**` anchor, re-parses the retained rollouts (discovery root + archived store, or given paths) and classifies each session recoverable / still userless / unrecoverable (rollout gone); preview by default, `--apply` re-imports only the recoverable rollouts through `runTranscriptsIngest` (content-hash dedup, no facts, no watermark write). Pinned by `test/transcripts-recover-codex.test.ts`. `audit-secrets [--source-id S] [--json]` (`src/commands/transcripts-audit.ts`, logic `src/core/transcripts/secret-audit.ts`): the read-only installed-base audit that streams imported conversation pages (`type = 'conversation'` with `transcript_import` frontmatter) in id-keyset batches of 25, scans title and body with the transcript-lane detectors, lists slug, source, hit counts per pattern and up to 20 line numbers (never values or previews), and caches the summary without slugs in config row `transcripts.secret_audit` for the doctor check `transcript_secret_exposure` (`src/commands/doctor/checks/transcript-secrets.ts`, brain category), which counts imported conversation pages and reads that summary (never scans): no audit, an older `TRANSCRIPT_SECRET_AUDIT_VERSION` or a source-scoped audit warns with the audit as fix; hits warn with the audit's age; a clean full audit is ok. Pinned by `test/transcripts-secret-audit.test.ts`.-- `src/commands/upgrade.ts` — self-update CLI. It sets `GBRAIN_UPGRADE_OWNS_MIGRATIONS=1` for the install step, so package postinstall (`scripts/postinstall.ts`) skips `apply-migrations`; post-upgrade owns them. An install step that fails or times out after `gbrain --version` already reports a newer version counts as installed. The run ends with a `Binary:` line (installed version, or upgrade failed) and a `Migrations:` line: complete; running, with the lock holder's host and pid when post-upgrade exits 75; or failed, with the recovery command (`--force-retry <v>` for wedged versions). `runPostUpgrade()` enumerates migrations from the TS registry (`src/commands/migrations/index.ts`) and tail-calls `runApplyMigrations(['--yes', '--non-interactive'])` so the mechanical side of every outstanding migration runs unconditionally. After schema apply it prints the one-shot auto_chronicle default-on `[AGENT]` notice (`core/chronicle/upgrade-notice.ts`). Before the swap of a bun-link, package or ClawHub install it refuses (exit 78, nothing changed) a target whose Bun floor is above the host's Bun or unreadable (`--no-bun-floor-check` overrides, manual only; `src/core/bun-floor.ts`); after the swap it runs `gbrain --help` as a smoke that passes the startup Bun check and, on failure, exits 1 with per-method recovery (#5855). Tests: `upgrade-migration-outcome.test.ts`, `upgrade-no-autopilot.serial.test.ts`, `upgrade-bun-link-arc.serial.test.ts`. `post-upgrade --json` (D2, `json: 'document'`): human lines go to stderr and stdout is one report `{status, apply_migrations:{exit_code}, schema, warnings[]}`; it calls `applyMigrations()` and still ends on any status apply-migrations returns (a failure is one envelope leading with the report).+- `src/commands/upgrade.ts` — self-update CLI. It sets `GBRAIN_UPGRADE_OWNS_MIGRATIONS=1` for the install step, so package postinstall (`scripts/postinstall.ts`) skips `apply-migrations`; post-upgrade owns them. An install step that fails or times out after `gbrain --version` already reports a newer version counts as installed. The run ends with a `Binary:` line (installed version, or upgrade failed) and a `Migrations:` line: complete; running, with the lock holder's host and pid when post-upgrade exits 75; or failed, with the recovery command (`--force-retry <v>` for wedged versions). `runPostUpgrade()` enumerates migrations from the TS registry (`src/commands/migrations/index.ts`) and tail-calls `runApplyMigrations(['--yes', '--non-interactive'])` so the mechanical side of every outstanding migration runs unconditionally. After schema apply it prints the one-shot auto_chronicle default-on `[AGENT]` notice (`core/chronicle/upgrade-notice.ts`). Before the swap of a bun-link, package or ClawHub install it refuses (exit 78, nothing changed) a target whose Bun floor is above the host's Bun or unreadable (`--no-bun-floor-check` overrides, manual only; `src/core/bun-floor.ts`); after the swap it runs `gbrain --help` as a smoke that passes the startup Bun check and, on failure, exits 1 with per-method recovery (#5855). Everything the post-swap tail needs is imported statically, so the old process never loads new-release modules into its cached graph (#6604; the supervisor step constant lives in the import-free leaf `src/commands/movement-step.ts`; guard: `test/upgrade-post-swap-imports.test.ts`). Tests: `upgrade-migration-outcome.test.ts`, `upgrade-no-autopilot.serial.test.ts`, `upgrade-bun-link-arc.serial.test.ts`. `post-upgrade --json` (D2, `json: 'document'`): human lines go to stderr and stdout is one report `{status, apply_migrations:{exit_code}, schema, warnings[]}`; it calls `applyMigrations()` and still ends on any status apply-migrations returns (a failure is one envelope leading with the report).- `src/commands/watch.ts` — `gbrain watch`: the push transport. Reads turns from stdin as they arrive (`user:`/`assistant:` prefixes; unprefixed = user turn), keeps a rolling in-process window (`--window-turns`, default 4), calls `volunteerContext` per turn, streams pointers to stdout (`--json` for JSONL with turn attribution), logs `channel: 'watch'` events with a per-session id. Session dedupe feeds already-pushed slugs back as priorContext so the core's slug-only suppression dedupes. Blocks in the stdin iteration (interactive alive until Ctrl-C/Ctrl-D; piped ends at EOF) — deliberately NOT in DAEMON_COMMANDS; SIGINT closes the stream so teardown flows through finishCliTeardown. Per-turn resolution failures are fail-open. Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + THIN_CLIENT_REFUSED_COMMANDS (thin clients use the `volunteer_context` MCP op). Pinned by `test/watch-command.test.ts`.diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.mdindex 8ccf4d82e5..231db8d8b0 100644--- a/docs/architecture/key-files/persistence-stalls.md+++ b/docs/architecture/key-files/persistence-stalls.md@@ -30,7 +30,7 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor- `src/core/persistence/consumer-heartbeat.ts` — #6317 (B1a, B3): the probe and heartbeat behind one full consumer per host. `consumerIdentity()` is this process's `{pid, nonce, pid_ns}` (a random per-process nonce, the `/proc/self/ns/pid` inode where readable), so a reused pid after a container restart is a new row; every `owner_pid === process.pid` check compares the nonce too. `startConsumerHeartbeat(engine, row, opts)` renews this process's `persistence_consumers` row every 10 s on its own single-flight timer through `executeRawDirect` (independent of claim renewal: an idle `serve` holds no claim), carrying kind (`claimOwner().kind`), mode (`probing|full|waiter_only|promoted`), `restart_required`, the age of the oldest abandoned root barrier, the pool gauge `{checked_out, max, waiters}`, `host_json_path`, `persistence_home`, `minted_under` and the build; each renewal deletes rows not renewed for 90 s in the same CTE, and a failed write is logged once and never stops the consumer. #6650: rows carry `boot_id`, `process_start` (v243); the probe and `electOwner` skip rows `consumerRowProvablyDead` proves dead (Linux: same boot and pid ns, pid gone/reused). `probeLiveFullConsumer(engine, hostId, self)` is the database-only probe (never a socket: the persistence IPC socket exists only on PGLite): a row of a resident kind (`serve`, `sync`, `jobs`, `autopilot`, `mcp`), mode `full`, not this process, renewed within 30 s, not `restart_required` and not wedged (no root barrier older than `persistence.preparation_ceiling_ms`), on an `active` binding. `listHostConsumers(engine, hostId)` feeds `writer status --json` `host.consumers` and doctor. The consumer mode machine in `consumer.ts` (`probing` → `full` or `waiter_only` → `promoted` → back to `waiter_only` after three healthy owner ticks) consumes the probe on every tick; `startPersistenceConsumer` in `service.ts` stays synchronous and returns the waiter-only seam (`WaiterOnlyConsumer` behind `PersistenceConsumerLike`: `wake()` no-op, settlement listeners kept, `holds()` false, `status()` `waiter_only` with the owner pid) when the probe finds an owner and `persistence.single_consumer` is on. A `serve` always starts full; short-lived kinds (`put`, `import`, `dream`, `cycle`, `sources`, `cli`) keep their own consumer; PGLite is inert.- `src/core/schema-migrations/v222-persistence-consumers.ts` — #6317 (T-01): the `persistence_consumers` table, primary key `(host_id, pid, nonce)`, columns `pid_ns`, `kind`, `mode`, `started_at`, `renewed_at`, `restart_required`, `root_barrier_age_ms`, `pool` jsonb, `host_json_path`, `persistence_home`, `minted_under` jsonb, `version`; plus the partial index `persistence_requests (worktree_id, completed_at DESC) WHERE state = 'committed'` that the movement watermark reads (the baseline indexes cover pending, recovery and principal reads only). Both objects are also in `src/schema.sql` for fresh installs (PGLite and Postgres parity, goldens). The number is taken at the merge slot by `bun run release:restamp`.- `src/commands/doctor/checks/managed-sync-movement.ts` + `src/core/persistence/sync-movement.ts` — #6317 (B4, I2): the movement reader and its doctor check. `readManagedSyncMovement` snapshots, per active managed source, the newest `completed_at` of committed `managed_sync_*` receipts in the current source incarnation (the watermark, one probe of the partial index `persistence_requests_sync_watermark`, v223, whose predicate repeats the read's kind test; a count would shrink under compaction), the head claim's `step_since`, the `managed-sync` cursor (`index/total`, `held`) and `sources.last_sync_at`/`last_commit`, and whether a drain or full consumer is live on the owner host. `data_moving` is false when an unfinished cursor has had neither a committed receipt nor a head step advance for longer than `persistence.preparation_ceiling_ms` while a consumer is live; with none live the state is `parked` (informational). `sources status --json` and `writer status --json` print `data_moving`, `not_moving_since` and `movement_state` beside `sync_running`, and `sources status` prints the exact `gbrain sources writer status --source <id> --json` beside `data_moving: false`; doctor `managed_sync_not_moving` (warn; counts against the score for `not_moving`, never for `parked`) uses the same rule with that command as its structured fix; `serve` prints one `[gbrain notice]` when a source flips. `/health` stays liveness-only.-- `src/commands/sources-writer-movement.ts` — #6317 (I2): `gbrain sources writer movement [<source>] [--wait <dur>] [--warn-only] [--json]`, the deploy gate `gbrain upgrade` and `post-upgrade` end by printing (bare, so it inherits the default window; neither runs it, because neither restarts the resident processes). Same source selection as `writer status` (`persistence-admin.ts`). It snapshots through `sync-movement.ts`, waits `max(300 s, preparation budget + 60 s)` (printed as the effective budget; `--wait <dur>` takes sync's duration syntax) and judges each source: `moved` (a new committed publication; a cursor advanced only by holds or a `last_sync_at` touched by an up-to-date check is not movement) and `current` exit 0; `held` exits 0 with a warning and the hold kind's route (`gbrain repair fences --source <id>`; `preparation_stalled` → writer status, then `gbrain sources retry-held <id>`); `within_allowance` (the head's step advanced inside the window) exits 0 with `retry_after_ms`; `not_moving` exits 1 with `managed_sync_not_moving` (`reason: movement_check`, `fix.argv` the writer-status command, `fix.verify` this command); `unknown` carries the read failure's own code with `fix.next: report`. `--warn-only` prints the same envelopes and exits 0. Flags are regenerated into `src/core/cli-flag-registry.generated.ts` with `bun run build:flag-registry`.+- `src/commands/sources-writer-movement.ts` — #6317 (I2): `gbrain sources writer movement [<source>] [--wait <dur>] [--warn-only] [--json]`, the deploy gate `gbrain upgrade` and `post-upgrade` end by printing (bare, so it inherits the default window; neither runs it, because neither restarts the resident processes). The printed step is `MOVEMENT_SUPERVISOR_STEP` from the import-free leaf `src/commands/movement-step.ts` (re-exported here), so upgrade loads it before the swap (#6604). Same source selection as `writer status` (`persistence-admin.ts`). It snapshots through `sync-movement.ts`, waits `max(300 s, preparation budget + 60 s)` (printed as the effective budget; `--wait <dur>` takes sync's duration syntax) and judges each source: `moved` (a new committed publication; a cursor advanced only by holds or a `last_sync_at` touched by an up-to-date check is not movement) and `current` exit 0; `held` exits 0 with a warning and the hold kind's route (`gbrain repair fences --source <id>`; `preparation_stalled` → writer status, then `gbrain sources retry-held <id>`); `within_allowance` (the head's step advanced inside the window) exits 0 with `retry_after_ms`; `not_moving` exits 1 with `managed_sync_not_moving` (`reason: movement_check`, `fix.argv` the writer-status command, `fix.verify` this command); `unknown` carries the read failure's own code with `fix.next: report`. `--warn-only` prints the same envelopes and exits 0. Flags are regenerated into `src/core/cli-flag-registry.generated.ts` with `bun run build:flag-registry`.- `src/core/persistence/journal.ts` — the request journal SQL: admission, claims, renewals, releases and completion. #6278: the claim statements stamp a `preparing` phase of their own token at claim time and return the previous claim's stamp with the row (`previous_claim_phase`), so a stalled receipt names the last recorded step; a follower's stamp has only its token and owner (#6650) until its wave dispatches it (`markDispatched`), so a kill charges exactly the members that were preparing; `renewGroupClaims` stamps each member's own phase; `releaseUnpublishedClaim` charges one `preparation_attempts` only for `preparation_deadline` (`claim_lost`, `consumer_stopping` and `group_member_waiting` never do); `chargePreparationAttempt` charges a claim this owner still holds before it is finished `preparation_stalled`; `floorPreparationAttempts` pins the counter at the limit after a ceiling overrun; completing a request as committed resets the counter (`completeWrite`, `completeGroup`). An older owner ignores the counter and its renewals overwrite the stamp with the old shape (writer status shows each owner's version); every statement keeps `PERSISTENCE_PROTOCOL_PREDICATE`. Tests: `test/persistence-preparation-kill-accounting.test.ts`, `test/e2e/persistence-preparation-attempts-postgres.test.ts`.- `src/core/persistence/diagnostics.ts` — trusted administrator counts for owners/epochs, queued bytes/age, outbox recovery, configured quota usage and actionable capacity warnings; bigint values are transport-safe strings and diagnostics exclude intent, credentials and private paths. Writer status's blockers also carry each request's `operation`, `intent_kind` and `preparation_attempts`; a running blocker's `claim` adds the preparation `step`, `step_age_ms`, `waiting_on`, the owner process (kind, pid, gbrain build, from the live claim's stamp), `budget_ms` and, past the budget, `stall: { reason: 'preparation_overdue', step, step_age_ms, waiting_on, budget_ms }` (`claimStall`; `WRITE_HEALTH_REASONS`, the wire enum, is unchanged). `WRITER_NEXT_ACTIONS` has entries for `preparation_deadline` (keep the request id: the owner will claim it again) and `preparation_stalled` (do not resubmit under the same id; retry-held after the fix), and the result carries `preparation_policy` (the budgets, ceiling, attempt limit and switch in effect). Doctor `persistence_write_stall` prints the same fields. Tests: `test/persistence-writer-status-stall.test.ts`.- `src/core/schema-migrations/v220-persistence-request-preparation-attempts.ts` — #6278: `persistence_requests.preparation_attempts integer NOT NULL DEFAULT 0 CHECK (preparation_attempts >= 0)`, the count of cut-offs of a request's preparation. Existing rows start at 0; a commit resets it. It is a migration-created column (also in the `persistence_requests` CREATE TABLE of `src/schema.sql`, with no index) so a fresh install and an upgraded brain keep the same column order. Tests: `test/persistence-preparation-attempts-migration.test.ts`, `test/e2e/persistence-preparation-attempts-postgres.test.ts`.diff --git a/src/commands/movement-step.ts b/src/commands/movement-step.tsnew file mode 100644index 0000000000..b84612dbed--- /dev/null+++ b/src/commands/movement-step.ts@@ -0,0 +1,6 @@+/**+ * #6604: the step `gbrain upgrade` and `gbrain post-upgrade` print for the supervisor. A leaf with no imports, so+ * upgrade.ts loads it statically before the swap instead of pulling the movement command graph into the old process.+ * Bare command (no flags), so it inherits the default window.+ */+export const MOVEMENT_SUPERVISOR_STEP = 'after restarting serve and the workers, run: gbrain sources writer movement';diff --git a/src/commands/sources-writer-movement.ts b/src/commands/sources-writer-movement.tsindex 9ee6d91578..84cf4c690f 100644--- a/src/commands/sources-writer-movement.ts+++ b/src/commands/sources-writer-movement.ts@@ -55,8 +55,7 @@ normally), held (advanced only by holds; the hold kind's repair route is printedExit 1 with code managed_sync_not_moving for not_moving and parked; 0 otherwise.Run it after restarting serve and the workers: gbrain sources writer movement`;-/** The bare command `gbrain upgrade` and `gbrain post-upgrade` print for the supervisor's step (no flags, so it inherits the default window). */-export const MOVEMENT_SUPERVISOR_STEP = 'after restarting serve and the workers, run: gbrain sources writer movement';+export { MOVEMENT_SUPERVISOR_STEP } from './movement-step.ts';export const MOVEMENT_DEFAULT_MIN_MS = 300_000;export const MOVEMENT_BUDGET_GRACE_MS = 60_000;diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.tsindex 22e25f4f69..039f61ade4 100644--- a/src/commands/upgrade.ts+++ b/src/commands/upgrade.ts@@ -11,6 +11,9 @@ import type { InteractiveProbe } from '../core/interaction.ts';import { forwardProgressPast, migrationLedgerSummary } from '../core/migration-ledger.ts';import { loadCompletedMigrations } from '../core/preferences.ts';import { MIGRATIONS_RUNNING_EXIT_CODE, readMigrationLockHolder } from '../core/migration-orchestration-lock.ts';+import { loadConfig } from '../core/config.ts';+import { clearSnooze, clearUpdateCache, pendingUpgradeVersion, writeJustUpgraded } from '../core/self-upgrade.ts';+import { MOVEMENT_SUPERVISOR_STEP } from './movement-step.ts';import {BUN_FLOOR_EXIT_CODE,evaluateBunFloor,@@ -212,7 +215,6 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: stringif (!target && method === 'bun' && newVersion && newVersion === oldVersion) {const pin = bunGlobalExactTagPin(resolveBunGlobalRoot());if (pin) {- const { pendingUpgradeVersion } = await import('../core/self-upgrade.ts');const latest = pendingUpgradeVersion(oldVersion);const reinstall = bunReinstallCommand(latest ? `#v${latest}` : '');console.error(`Upgrade did not take effect: still running ${newVersion}, because the global install is pinned to ${pin} and \`bun update\` keeps a pinned tag.`);@@ -241,10 +243,9 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: string// - clear the update-check cache + snooze so a now-stale "upgrade// available" marker doesn't keep nudging after we've already applied it.try {- const su = await import('../core/self-upgrade.ts');- su.writeJustUpgraded(oldVersion);- su.clearUpdateCache();- su.clearSnooze();+ writeJustUpgraded(oldVersion);+ clearUpdateCache();+ clearSnooze();} catch {/* best-effort: never block the upgrade on confirmation bookkeeping */}@@ -292,7 +293,7 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: stringconsole.log(`Binary: installed ${newVersion || 'a new version (could not verify)'}`);console.log(migrationsLine);// #6317 (I2): upgrade owns no relaunch, so the supervisor proves data movement after it restarts serve and the workers.- console.log(`Next: ${(await import('./sources-writer-movement.ts')).MOVEMENT_SUPERVISOR_STEP}`);+ console.log(`Next: ${MOVEMENT_SUPERVISOR_STEP}`);}/**@@ -378,7 +379,6 @@ function installedDespiteFailure(oldVersion: string): boolean {export async function describeMigrationFailure(error: unknown, newVersion: string): Promise<string> {if ((error as { status?: number }).status === MIGRATIONS_RUNNING_EXIT_CODE) {- const { loadConfig } = await import('../core/config.ts');const config = loadConfig();const holder = config ? await readMigrationLockHolder(config) : null;return `Migrations: running (host ${holder?.host ?? 'unknown'}, pid ${holder?.pid ?? 'unknown'}) in another apply-migrations. `@@ -897,7 +897,7 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {// Fail-open per A18: never crash post-upgrade from the banner.}// #6317 (I2): the supervisor's step; bare, so the check inherits its default window.- (json ? console.error : console.log)(`Next: ${(await import('./sources-writer-movement.ts')).MOVEMENT_SUPERVISOR_STEP}`);+ (json ? console.error : console.log)(`Next: ${MOVEMENT_SUPERVISOR_STEP}`);if (json) await writeJsonDocument(JSON.stringify(report));}diff --git a/test/upgrade-post-swap-imports.test.ts b/test/upgrade-post-swap-imports.test.tsnew file mode 100644index 0000000000..8ec0914c68--- /dev/null+++ b/test/upgrade-post-swap-imports.test.ts@@ -0,0 +1,61 @@+/**+ * #6604: after `gbrain upgrade` swaps the install in place, the old parent+ * process still has the old release's modules cached. A dynamic import there+ * loads new files into the old graph, so a changed named export throws and the+ * upgrade exits 1 after a successful install. Every module the post-swap tail+ * needs must be imported statically (loaded before the swap).+ */+import { describe, expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';++const SRC = readFileSync(join(import.meta.dir, '..', 'src', 'commands', 'upgrade.ts'), 'utf-8');+const SWAP_MARKER = 'const newVersion = verifyUpgrade();';++function functionBody(name: string): string | null {+ const m = new RegExp(`(?:^|\\n)(?:export )?(?:async )?function ${name}\\s*\\(`).exec(SRC);+ if (!m) return null;+ let i = SRC.indexOf('{', SRC.indexOf(')', m.index + m[0].length));+ for (let depth = 0, j = i; j < SRC.length; j++) {+ if (SRC[j] === '{') depth++;+ else if (SRC[j] === '}' && --depth === 0) return SRC.slice(i, j + 1);+ }+ return null;+}++function postSwapCode(): Map<string, string> {+ const runUpgrade = functionBody('runUpgrade')!;+ const start = runUpgrade.indexOf(SWAP_MARKER);+ expect(start).toBeGreaterThan(0);+ const seen = new Map<string, string>([['runUpgrade (after the swap)', runUpgrade.slice(start)]]);+ const queue = [runUpgrade.slice(start)];+ while (queue.length) {+ for (const call of queue.pop()!.matchAll(/\b([A-Za-z_$][\w$]*)\s*\(/g)) {+ const name = call[1]!;+ if (seen.has(name)) continue;+ const body = functionBody(name);+ if (!body) continue;+ seen.set(name, body);+ queue.push(body);+ }+ }+ return seen;+}++describe('#6604 upgrade post-swap tail', () => {+ test('runUpgrade and every local helper it reaches after the swap use no dynamic import', () => {+ const offenders = [...postSwapCode()].filter(([, body]) => /await import\(/.test(body)).map(([name]) => name);+ expect(offenders).toEqual([]);+ });++ test('the post-swap walk reaches describeMigrationFailure and the verify helpers', () => {+ const names = [...postSwapCode().keys()];+ expect(names).toEqual(expect.arrayContaining(['describeMigrationFailure', 'postSwapSmoke', 'saveUpgradeState']));+ });++ test('the movement step constant lives in a leaf module with no imports', () => {+ const leaf = readFileSync(join(import.meta.dir, '..', 'src', 'commands', 'movement-step.ts'), 'utf-8');+ expect(new Bun.Transpiler({ loader: 'ts' }).scanImports(leaf)).toEqual([]);+ expect(SRC).toMatch(/^import \{ MOVEMENT_SUPERVISOR_STEP \} from '\.\/movement-step\.ts';$/m);+ });+});