Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: guard purge migrations against destructive rerun on lost applied-list (#2770)

[._.]/ Adam Eivy123348c2e8e0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index adbd5c4e21..97b79e7e28 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -52,6 +52,8 @@
## Fixed
+- [issue-2770] **Losing the migration bookkeeping file can no longer wipe legitimately-earned learning history.** The two one-time cleanups that cleared mis-recorded task stats (#2700, #2696) find their target by presence — "is this bucket here?" — which is exactly right the first time, but dangerous on a rerun. If `data/migrations.applied.json` (the list of which migrations have run) ever went missing or got corrupted, the runner rebuilt it from scratch and reran *every* migration — so those cleanups would fire again and delete the real success/failure history you'd accumulated since. Migrations that purge by presence now declare themselves to the runner, and the runner refuses to rerun one whenever it had to rebuild that bookkeeping file from empty: your post-fix history survives, and on a fresh install (where there's nothing to clear anyway) the cleanup is simply recorded as done. The guard lives in one place and is shared by both cleanups, so they can't drift apart.
+
- [issue-2696] **Background jobs that finish your work through git/GitHub/Jira instead of a commit no longer report a permanent 0% success rate.** The branch-reconcile, issue-reconcile, branch-cleanup, and Jira status-report jobs deliver their result as a side effect — a merged PR, a resolved conflict, a deleted branch, a posted report — so they deliberately never make a `task-…` commit of their own. But the success check only knew how to look for that commit, so it scored every *successful* run as a failure and pinned those task types at 0% on the CoS Learning card (which in turn steered the self-improvement loop away from them on evidence that was never true). They're now judged the same way pipeline and media jobs already were — by whether the run itself succeeded — and a one-time migration clears the mis-recorded history on upgrade (and the "Backfill History" button no longer re-poisons it from the old records). This is the same measurement bug already fixed for the Layered Intelligence reasoning run; jobs that genuinely do commit their work — the accessibility audit, the Jira sprint manager, the PLAN.md replan — are unaffected and still judged on their commit, so a real failure there is never masked.
- [issue-2737] **An unattended background AI job that hits a failing provider no longer buries you in a stack of red error toasts.** Jobs that run without you watching — like the weekly goal check-in, which makes one AI call per goal at once — used to fire a separate red error toast for *every* failed call when a provider was down (an expired key, a dead endpoint, a model returning nothing). A seven-goal check-in against a broken provider meant seven stacked toasts you never saw coming. Those background failures now collapse into a single toast per provider that counts them ("Example Provider failed on 5 background AI calls"), with the first one still showing the provider's real reason. AI actions *you* triggered are unchanged: they still report their failure the instant it happens, one toast each, with the provider's actual error — so a failure you're waiting on is never aggregated away.
diff --git a/scripts/migrations/197-purge-poisoned-li-learning-bucket.js b/scripts/migrations/197-purge-poisoned-li-learning-bucket.js
index 2ef34144b9..19082a8332 100644
--- a/scripts/migrations/197-purge-poisoned-li-learning-bucket.js
+++ b/scripts/migrations/197-purge-poisoned-li-learning-bucket.js
@@ -54,6 +54,14 @@
*
* No-op by construction on installs that never ran LI (the common case) — the
* file is only rewritten when the bucket is actually present.
+ *
+ * This purge identifies its target by bucket PRESENCE, so a rerun after
+ * data/migrations.applied.json is lost/corrupt would drop legitimately-earned
+ * post-fix history. It therefore opts into the runner's PURGE class
+ * (`purge: true`): run-migrations.js records a purge migration as applied
+ * WITHOUT executing it whenever the applied-list started empty/rebuilt (#2770).
+ * The guard lives in the runner and is shared with migration 198 — no
+ * per-migration marker to drift.
*/
import { readFile, writeFile } from 'fs/promises';
@@ -70,6 +78,9 @@ const LEARNING_REL = 'data/cos/learning.json';
const LI_BUCKET = 'self-improve:layered-intelligence';
export default {
+ // Opt into the runner's non-idempotent PURGE class — no-op on a rerun against
+ // a rebuilt-from-[] ledger so post-fix learning data is never destroyed (#2770).
+ purge: true,
async up({ rootDir }) {
const path = join(rootDir, LEARNING_REL);
const raw = await readFile(path, 'utf-8').catch((err) => {
diff --git a/scripts/migrations/198-purge-poisoned-coordinator-learning-buckets.js b/scripts/migrations/198-purge-poisoned-coordinator-learning-buckets.js
index 331512bab3..8e066e3831 100644
--- a/scripts/migrations/198-purge-poisoned-coordinator-learning-buckets.js
+++ b/scripts/migrations/198-purge-poisoned-coordinator-learning-buckets.js
@@ -42,11 +42,12 @@
* No-op by construction on installs that never ran these types — the file is only
* rewritten when at least one bucket is actually present.
*
- * Known caveat (shared with migration 197, tracked in #2770): if data/migrations.applied.json
- * is lost/corrupt, the runner rebuilds the ledger from [] and reruns every migration — this
- * purge identifies its target by bucket PRESENCE, so a rerun would also drop legitimate
- * post-fix coordinator history. Deferred as a cross-cutting fix (a per-198 marker would diverge
- * from 197); see #2770.
+ * Destructive-rerun guard (#2770): this purge identifies its target by bucket PRESENCE, so a
+ * rerun after data/migrations.applied.json is lost/corrupt (the runner rebuilds the ledger from
+ * [] and reruns every migration) would drop legitimate post-fix coordinator history. It therefore
+ * opts into the runner's PURGE class (`purge: true`): run-migrations.js records a purge migration
+ * as applied WITHOUT executing it whenever the applied-list started empty/rebuilt. The guard lives
+ * in the runner and is shared with migration 197 — one mechanism, no per-migration marker to drift.
*/
import { readFile, writeFile } from 'fs/promises';
@@ -65,6 +66,9 @@ const LEARNING_REL = 'data/cos/learning.json';
const COORDINATOR_BUCKETS = [...NON_COMMITTING_COORDINATOR_TASK_TYPES].map((t) => `self-improve:${t}`);
export default {
+ // Opt into the runner's non-idempotent PURGE class — no-op on a rerun against
+ // a rebuilt-from-[] ledger so post-fix learning data is never destroyed (#2770).
+ purge: true,
async up({ rootDir }) {
const path = join(rootDir, LEARNING_REL);
const raw = await readFile(path, 'utf-8').catch((err) => {
diff --git a/scripts/run-migrations.js b/scripts/run-migrations.js
index b520197e01..97a474cae7 100644
--- a/scripts/run-migrations.js
+++ b/scripts/run-migrations.js
@@ -109,18 +109,41 @@ export async function runMigrations({
// readAppliedList).
const applied = await readAppliedList(appliedFile, { repair: true });
+ // Guard for #2770: when the applied-list started EMPTY — missing, corrupt and
+ // rebuilt from [], or a genuinely fresh install — we cannot prove that a
+ // non-idempotent PURGE migration hasn't already run. Rerunning one (they
+ // identify their targets by PRESENCE, e.g. a learning bucket) would delete
+ // legitimately-earned data accumulated since the purge first ran. So a
+ // migration that opts into the purge class (`export default { purge: true }`)
+ // is recorded as applied WITHOUT executing whenever the ledger started empty:
+ // on a fresh install there is nothing to purge anyway, and on a lost/corrupt
+ // ledger this protects post-fix data. The rare install that has genuine
+ // poisoned data AND lost its ledger before the purge ran keeps that stale data
+ // rather than losing real data — the deliberately safer trade. This is the
+ // single shared guard for every purge migration (197, 198, …) — no per-migration
+ // marker to drift out of sync.
+ const ledgerStartedEmpty = applied.length === 0;
+
const files = await scanMigrationFiles(migrationsDir);
let ran = 0;
for (const file of files) {
if (applied.includes(file)) continue;
- console.log(`🔄 Running migration: ${file}`);
const mod = await import(pathToFileURL(join(migrationsDir, file)).href);
const migration = (mod?.default && typeof mod.default.up === 'function') ? mod.default : mod;
if (!migration || typeof migration.up !== 'function') {
throw new Error(`Migration "${file}" does not export an up() function`);
}
+
+ if (migration.purge && ledgerStartedEmpty) {
+ console.warn(`⏭️ Skipping purge migration ${file}: applied-list started empty/rebuilt — recorded as applied without running to avoid a destructive rerun (#2770)`);
+ applied.push(file);
+ await writeFile(appliedFile, JSON.stringify(applied, null, 2) + '\n');
+ continue;
+ }
+
+ console.log(`🔄 Running migration: ${file}`);
await migration.up({ rootDir, migrationsDir });
applied.push(file);
await writeFile(appliedFile, JSON.stringify(applied, null, 2) + '\n');
diff --git a/scripts/run-migrations.test.js b/scripts/run-migrations.test.js
index 42cb9ac1ee..7653bcac1f 100644
--- a/scripts/run-migrations.test.js
+++ b/scripts/run-migrations.test.js
@@ -110,6 +110,128 @@ export const md5 = (s) => s;
});
});
+describe('runMigrations purge-migration guard (#2770)', () => {
+ let rootDir;
+ let dataDir;
+ let migrationsDir;
+ let appliedFile;
+ let warnSpy;
+ let logSpy;
+
+ // A purge migration that identifies its target by PRESENCE: it deletes a
+ // bucket from a data file every time up() runs. If the runner reran it after
+ // the applied-list was lost, it would destroy legitimately-earned data.
+ const PURGE_FIXTURE = `
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+export default {
+ purge: true,
+ async up({ rootDir }) {
+ const path = join(rootDir, 'data', 'learning.json');
+ const raw = await readFile(path, 'utf-8').catch(() => null);
+ if (raw == null) return { purged: 0 };
+ const data = JSON.parse(raw);
+ const had = data.bucket !== undefined;
+ delete data.bucket;
+ await writeFile(path, JSON.stringify(data));
+ return { purged: had ? 1 : 0 };
+ }
+};
+`;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'run-migrations-purge-'));
+ dataDir = join(rootDir, 'data');
+ migrationsDir = join(rootDir, 'migrations');
+ mkdirSync(dataDir, { recursive: true });
+ mkdirSync(migrationsDir, { recursive: true });
+ appliedFile = join(dataDir, 'migrations.applied.json');
+ writeFileSync(join(migrationsDir, '197-purge.js'), PURGE_FIXTURE);
+
+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+ warnSpy.mockRestore();
+ logSpy.mockRestore();
+ });
+
+ const seedLearning = (data) =>
+ writeFileSync(join(dataDir, 'learning.json'), JSON.stringify(data));
+ const readLearning = () =>
+ JSON.parse(readFileSync(join(dataDir, 'learning.json'), 'utf-8'));
+
+ it('runs a purge migration normally when the applied-list has prior content', async () => {
+ // The healthy upgrade path: an install with earlier migrations recorded runs
+ // the purge for the first time and it DOES purge the poisoned bucket.
+ writeFileSync(appliedFile, JSON.stringify(['000-earlier.js'], null, 2) + '\n');
+ seedLearning({ bucket: { poisoned: true }, keep: 1 });
+
+ const ran = await runMigrations({ rootDir, migrationsDir });
+
+ expect(ran).toBe(1);
+ expect(readLearning()).toEqual({ keep: 1 }); // bucket purged
+ expect(JSON.parse(readFileSync(appliedFile, 'utf-8'))).toContain('197-purge.js');
+ });
+
+ it('does NOT rerun a purge migration when the applied-list was lost — post-fix data survives', async () => {
+ // The bug: applied-list deleted, learning.json holds ONLY post-fix runs.
+ // A destructive rerun would delete the legitimately-earned bucket.
+ expect(existsSync(appliedFile)).toBe(false);
+ seedLearning({ bucket: { legitPostFixRuns: 12 }, keep: 1 });
+
+ const ran = await runMigrations({ rootDir, migrationsDir });
+
+ expect(ran).toBe(0); // recorded-as-applied without executing
+ // The earned bucket is untouched — NOT purged.
+ expect(readLearning()).toEqual({ bucket: { legitPostFixRuns: 12 }, keep: 1 });
+ // Still recorded so a later boot with a healthy ledger won't rerun it either.
+ expect(JSON.parse(readFileSync(appliedFile, 'utf-8'))).toEqual(['197-purge.js']);
+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('Skipping purge migration'));
+ });
+
+ it('does NOT rerun a purge migration when the applied-list was corrupt-rebuilt', async () => {
+ writeFileSync(appliedFile, '{ truncated'); // corrupt → rebuilt from []
+ seedLearning({ bucket: { legitPostFixRuns: 5 }, keep: 2 });
+
+ const ran = await runMigrations({ rootDir, migrationsDir });
+
+ expect(ran).toBe(0);
+ expect(readLearning()).toEqual({ bucket: { legitPostFixRuns: 5 }, keep: 2 });
+ expect(JSON.parse(readFileSync(appliedFile, 'utf-8'))).toEqual(['197-purge.js']);
+ });
+
+ it('records a purge migration as applied on a fresh install (nothing to purge)', async () => {
+ // No learning.json at all — the empty-ledger skip is harmless and still marks
+ // it applied so it never fires destructively later.
+ const ran = await runMigrations({ rootDir, migrationsDir });
+
+ expect(ran).toBe(0);
+ expect(JSON.parse(readFileSync(appliedFile, 'utf-8'))).toEqual(['197-purge.js']);
+ });
+
+ it('still runs non-purge migrations when the applied-list starts empty', async () => {
+ // Only purge-flagged migrations are held back on an empty ledger — ordinary
+ // idempotent migrations must still run on a fresh/rebuilt install.
+ writeFileSync(join(migrationsDir, '001-normal.js'), `
+import { writeFileSync } from 'fs';
+import { join } from 'path';
+export default {
+ async up({ rootDir }) { writeFileSync(join(rootDir, 'data', 'normal-marker.txt'), 'ran'); }
+};
+`);
+
+ const ran = await runMigrations({ rootDir, migrationsDir });
+
+ expect(ran).toBe(1); // the normal one ran; the purge one was skip-recorded
+ expect(existsSync(join(dataDir, 'normal-marker.txt'))).toBe(true);
+ expect(JSON.parse(readFileSync(appliedFile, 'utf-8')).sort())
+ .toEqual(['001-normal.js', '197-purge.js']);
+ });
+});
+
describe('runMigrations worktree backstop (#1947)', () => {
let baseDir;
let migrationsDir;