Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(self-upgrade): count a relaunch onto a newer version as applied (#5813, #5826)
garrytan399eb47f95e2
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 3eb706b937..d0e89fcf3c 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -4,7 +4,7 @@# the same commit as any peel (the guard fails on >50 lines of stale slack).# Columns: path max_lines policy notesrc/cli.ts 3202 ratchet +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult-src/commands/autopilot.ts 1635 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195)+src/commands/autopilot.ts 1637 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + auditsrc/commands/doctor.ts 653 ratchet refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.tssrc/commands/embed.ts 2190 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stalesrc/commands/extract-conversation-facts.ts 2146 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts)diff --git a/src/commands/autopilot.ts b/src/commands/autopilot.tsindex 8db039b649..f6f8140121 100644--- a/src/commands/autopilot.ts+++ b/src/commands/autopilot.ts@@ -329,14 +329,15 @@ export function decideLockAcquisition(/*** Reconcile the pre-swap breadcrumb at daemon boot (the post-swap attribution- * gate). If we're running the version we attempted, the swap+relaunch worked;- * if not, the new binary failed to launch and we record it as a known-bad- * version so the auto channel never retries it. Best-effort.+ * gate). If we're running the version we attempted or a newer one, the+ * swap+relaunch worked; if not, the new binary failed to launch and we record+ * it as a known-bad version so the auto channel never retries it. Best-effort.*/export function reconcileSelfUpgradeAtBoot(): void {try {const cfg = loadConfig();if (!cfg) return;+ const attempted = cfg.self_upgrade?.attempting_version;const { state, transition } = reconcileBreadcrumb(cfg.self_upgrade, VERSION);if (!transition) return;cfg.self_upgrade = state;@@ -345,16 +346,17 @@ export function reconcileSelfUpgradeAtBoot(): void {channel: 'autopilot',action: 'apply',current: VERSION,+ latest: attempted,outcome: transition === 'applied' ? 'applied' : 'failed',reason:transition === 'applied'- ? 'breadcrumb matched running version'- : 'crash-on-launch: attempted version != running version (recorded known-bad)',+ ? 'running version is at or past the attempted version'+ : 'crash-on-launch: running version is not at or past the attempted version (recorded known-bad)',});if (transition === 'applied') {- console.log(`[autopilot] self-upgrade confirmed: now running ${VERSION}.`);+ console.log(`[autopilot] self-upgrade confirmed: attempted ${attempted}, now running ${VERSION}.`);} else {- console.error('[autopilot] self-upgrade did not take (running an older version); recorded known-bad.');+ console.error(`[autopilot] self-upgrade did not take: attempted ${attempted}, still running ${VERSION}; recorded ${attempted} known-bad.`);}} catch {/* best-effort */diff --git a/src/core/self-upgrade.ts b/src/core/self-upgrade.tsindex bce51515b1..d8c53301ba 100644--- a/src/core/self-upgrade.ts+++ b/src/core/self-upgrade.ts@@ -451,12 +451,18 @@ export type BreadcrumbTransition = 'applied' | 'failed' | null;* via attribution). Called by the relaunched binary:** - No breadcrumb → nothing to do.- * - breadcrumb === currentVersion → the swap+relaunch worked. Clear it and- * record `last_applied_version`. (`applied`)- * - breadcrumb !== currentVersion → we're NOT the attempted version (the new- * binary crashed on launch and the supervisor relaunched the old one, or a- * stale breadcrumb). Record the attempted version in `failed_versions` so- * `decideSelfUpgrade` never retries it, and clear the breadcrumb. (`failed`)+ * - currentVersion >= breadcrumb → the swap+relaunch worked. The swap+ * installs whatever is current at swap time (`git pull`, `bun update`,+ * `releases/latest`), so a release published after the update check lands+ * a NEWER version than the breadcrumb names (#5813). Clear it, record+ * `last_applied_version`, and drop `failed_versions` entries at or below+ * the running version: `decideSelfUpgrade` only acts on a strictly newer+ * release, so they can never be targeted again. (`applied`)+ * - otherwise → we're NOT at the attempted version (the new binary crashed+ * on launch and the supervisor relaunched the old one, or a stale+ * breadcrumb, or an unparseable version). Record the attempted version in+ * `failed_versions` so `decideSelfUpgrade` never retries it, and clear the+ * breadcrumb. (`failed`)** Pure: returns the next state + the transition; the caller persists + audits.*/@@ -468,9 +474,20 @@ export function reconcileBreadcrumb(const attempting = state.attempting_version;if (!attempting) return { state, transition: null };- if (attempting === currentVersion) {+ const running = parseSemver(currentVersion);+ const attempted = parseSemver(attempting);+ if (attempting === currentVersion || (running && attempted && semverLte(attempted, running))) {delete state.attempting_version;state.last_applied_version = currentVersion;+ if (state.failed_versions) {+ // Unparseable entries stay: there is no ordering to prove them superseded.+ const stillBad = state.failed_versions.filter((v) => {+ const t = parseSemver(v);+ return !t || !running || semverGt(t, running);+ });+ if (stillBad.length > 0) state.failed_versions = stillBad;+ else delete state.failed_versions;+ }return { state, transition: 'applied' };}diff --git a/test/autopilot-self-upgrade.test.ts b/test/autopilot-self-upgrade.test.tsindex 27ec3218ce..e51c36ac22 100644--- a/test/autopilot-self-upgrade.test.ts+++ b/test/autopilot-self-upgrade.test.ts@@ -1,6 +1,12 @@-import { describe, expect, test } from 'bun:test';-import { generateSystemdUnit } from '../src/commands/autopilot.ts';+import { describe, expect, spyOn, test } from 'bun:test';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { generateSystemdUnit, reconcileSelfUpgradeAtBoot } from '../src/commands/autopilot.ts';+import { readRecentSelfUpgrades } from '../src/core/audit/self-upgrade-audit.ts';+import { VERSION } from '../src/version.ts';import { surfaceFileSource, surfaceSource } from './helpers/source-surface.ts';+import { withEnv } from './helpers/with-env.ts';// W4 autopilot: containment reads the autopilot surface; the positional spans stay on// autopilot.ts, which still holds attemptAutopilotSelfUpgrade.@@ -44,3 +50,35 @@ describe('autopilot self-upgrade static-shape regressions', () => {expect(SELF_UPGRADE_SRC).toMatch(/unlinkSync\(lockPath\)[\s\S]{0,120}process\.exit\(0\)/);});});++describe('reconcileSelfUpgradeAtBoot', () => {+ test('a relaunch onto a NEWER version than attempted is confirmed, prunes known-bad, and names both versions (#5813)', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-su-boot-'));+ const log = spyOn(console, 'log').mockImplementation(() => {});+ try {+ await withEnv({ GBRAIN_HOME: dir, GBRAIN_AUDIT_DIR: join(dir, 'audit') }, () => {+ const configPath = join(dir, '.gbrain', 'config.json');+ mkdirSync(join(dir, '.gbrain'), { recursive: true });+ writeFileSync(configPath, JSON.stringify({+ engine: 'pglite',+ self_upgrade: { mode: 'auto', attempting_version: '0.1.0.0', failed_versions: ['0.0.9.0'] },+ }));++ reconcileSelfUpgradeAtBoot();++ const su = JSON.parse(readFileSync(configPath, 'utf-8')).self_upgrade;+ expect(su.attempting_version).toBeUndefined();+ expect(su.last_applied_version).toBe(VERSION);+ expect(su.failed_versions).toBeUndefined();+ const events = readRecentSelfUpgrades(7);+ expect(events).toHaveLength(1);+ expect(events[0]).toMatchObject({ outcome: 'applied', current: VERSION, latest: '0.1.0.0' });+ const lines = log.mock.calls.map((args) => String(args[0]));+ expect(lines.some((l) => l.includes('0.1.0.0') && l.includes(VERSION))).toBe(true);+ });+ } finally {+ log.mockRestore();+ rmSync(dir, { recursive: true, force: true });+ }+ });+});diff --git a/test/self-upgrade.test.ts b/test/self-upgrade.test.tsindex 6ab60c3a4f..46b433c068 100644--- a/test/self-upgrade.test.ts+++ b/test/self-upgrade.test.ts@@ -20,6 +20,7 @@ import {writeSnooze,writeUpdateCache,type DecideSelfUpgradeInputs,+ type SelfUpgradeState,} from '../src/core/self-upgrade.ts';function baseInputs(over: Partial<DecideSelfUpgradeInputs> = {}): DecideSelfUpgradeInputs {@@ -262,6 +263,44 @@ describe('reconcileBreadcrumb', () => {const r = reconcileBreadcrumb({ attempting_version: '0.43.0', failed_versions: ['0.43.0', '0.41.0'] }, '0.42.0');expect(r.state.failed_versions?.filter((v) => v === '0.43.0').length).toBe(1);});+ test('unparseable running version → failed (no ordering to trust)', () => {+ const r = reconcileBreadcrumb({ attempting_version: '0.43.0' }, 'dev');+ expect(r.transition).toBe('failed');+ expect(r.state.failed_versions).toEqual(['0.43.0']);+ });+ // #5813: the swap installs whatever is current at swap time (git pull, bun+ // update, releases/latest), so the relaunched binary can be NEWER than the+ // version the breadcrumb recorded from the update cache.+ const appliedCases: Array<{ name: string; su: SelfUpgradeState; running: string; failed: string[] | undefined }> = [+ { name: 'running newer than attempted', su: { attempting_version: '0.60.22.0' }, running: '0.60.25.0', failed: undefined },+ {+ name: 'prunes known-bad entries at or below the running version',+ su: { attempting_version: '0.60.22.0', failed_versions: ['0.59.2.0', '0.60.25.0', '0.60.30.0'] },+ running: '0.60.25.0',+ failed: ['0.60.30.0'],+ },+ {+ name: 'exact match prunes too and keeps unparseable entries',+ su: { attempting_version: '0.43.0', failed_versions: ['0.41.0', 'not-a-version'] },+ running: '0.43.0',+ failed: ['not-a-version'],+ },+ {+ name: 'pruning every entry drops the key',+ su: { attempting_version: '0.60.22.0', failed_versions: ['0.59.2.0', '0.60.8.0'] },+ running: '0.60.25.0',+ failed: undefined,+ },+ ];+ for (const c of appliedCases) {+ test(`applied: ${c.name}`, () => {+ const r = reconcileBreadcrumb(c.su, c.running);+ expect(r.transition).toBe('applied');+ expect(r.state.attempting_version).toBeUndefined();+ expect(r.state.last_applied_version).toBe(c.running);+ expect(r.state.failed_versions).toEqual(c.failed);+ });+ }});describe('resolveSelfUpgradeMode', () => {