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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: stop reporting a faithful foundation rollback as a corrupted checkpoint
[._.]/ Adam Eivybf1f760aca44
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 12b8a65e12..ca4c9acf4c 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -26,3 +26,5 @@- **The Claude CLI's own model rejection is now a recognized, actionable failure.** "There's an issue with the selected model (…)" is printed by the CLI at startup, before any API call, so it carries no `API Error: 4NN` token and matched none of the model-error patterns. It landed in the `unknown` bucket with "Error did not match known patterns" — which autoFixer maps to Tier 4 (escalate), so a task with a bad model id burned all three retries against an id that could never work and then spent an agent run on an investigation task. It now classifies as `model-not-found` with the rejected id extracted from the message, putting it in Tier 1 (config/env) where a model correction belongs. Promoted to a structured `provider`-origin signal, since the full banner with the parenthesised id and the `--model` hint is CLI text rather than something a task's own output prints in passing.- **Stopping the CoS Runner no longer burns through queued agent tasks.** `portos-cos` is a separate PM2 app you can stop from the Apps page, and while runner mode is active it owns every agent process — but the spawn path dispatched into it regardless and recorded the resulting rejection as a task failure. The CLI arm charged a retry each time (a runner left off overnight walked every queued task through its retry budget and into `blocked`), and the TUI arm reported an *actionable* spawn error, parking the task for a human over an app you had simply turned off. Tasks now hold instead, gated in two places: the queue stops dequeuing entirely while the runner is down — before the priority tiers drain on-demand requests, advance review cooldowns, or bind an app's "in review" marker — and dispatch itself holds anything that still reaches it, releasing that marker and freeing the scheduler's spawn reservation so an autonomous job re-registers instead of sitting wedged for five minutes. A held task keeps its exact queued record: pending, unclaimed, no agent, no retry charged. It spawns for real the moment the runner is back, because the runner socket's reconnect re-runs the dequeue. That reconnect is also now unbounded: the socket gave up after ten attempts (~10 seconds), so a runner that came back a minute later left the server connected to nothing while still routing every spawn at it. Backoff is capped at 10s and the resulting dequeue is debounced, so neither a long outage nor a crash-looping runner is expensive. You get one log line when the runner drops and one when it returns, not one per task. "Run now" is never held — it answers with the real reason (runner unreachable, or the daemon stopped, which was never checked at all) instead of toasting "Spawning" at a task that would sit pending.- **The Antigravity account-eligibility banner no longer kills an agy run before it can start.** "We're finishing verifying your account eligibility. This usually takes a moment. Please try again shortly." is the front of agy's sign-in handshake, not its verdict — the CLI's own log shows the session authenticating fine (OAuth succeeds, the keyring token refreshes for another hour) and then retrying `loadCodeAssist` while the composer shows that notice. PortOS was treating the banner as an immediate fatal signal and killing the terminal 0.85–1.5s after the prompt was pasted, so the model was never asked for a token. Every agy CoS agent run from 2026-08-07 onward died this way in 3–5s, while the same account and model answered instantly over `--print` and over a PTY whose eligibility was already warm. The signal is now marked self-clearing: both TUI paths hold the session for up to 60s and let the run continue the moment agy starts generating, and only fail over to a fallback provider if the banner outlasts that window with no sign of life. The grace window also suppresses the idle reaper while it's armed, so a waiting run can't be finalized as a bogus `idle-complete` success that scrapes the banner as its answer. Other fallback signals (usage limits, rejected model ids) still fail immediately.++- **A foundation repair that was correctly rolled back no longer reports the rollback as corrupted.** When Series Autopilot reverted a character repair that failed to improve its target dimension, the pause said "checkpoint verification failed after rollback: restored foundation fields did not match the checkpoint" — implying the cast had been left in a half-repaired state. Nothing was actually wrong: undoing a repair is itself a content change, so the universe write path re-stamped `updatedAt` on every canon entry it restored (it has to — that timestamp is the clock the canon→catalog projection uses to carry the revert), and the verification compared those server-owned stamps byte-for-byte along with the authored prose. Every faithful character rollback therefore failed its own check. The comparison now ignores exactly the per-entry fields the write path owns and deliberately does not revert — the LWW timestamp, plus the reference-sheet and render pointers, which are preserved from the live record so a render that finished mid-repair isn't thrown away by the undo — while still comparing all authored content byte-for-byte. When a restore genuinely doesn't come back, the pause now names the fields that failed instead of stating only that something didn't match.diff --git a/server/services/pipeline/foundationJudge.js b/server/services/pipeline/foundationJudge.jsindex b8123692af..6f0e6f4757 100644--- a/server/services/pipeline/foundationJudge.js+++ b/server/services/pipeline/foundationJudge.js@@ -1467,14 +1467,67 @@ const pickFoundationFields = (record, fields) => Object.fromEntries(]),);-const foundationSnapshotComparable = (snapshot) => JSON.stringify({- universeId: snapshot?.universeId || null,- universe: snapshot?.universe || null,- series: snapshot?.series || null,- arc: snapshot?.arcState?.arc ?? null,- seasons: snapshot?.arcState?.seasons || [],- episodes: snapshot?.arcState?.episodes || [],-});+// Per-canon-entry fields the universe WRITE PATH owns, which a faithful restore+// therefore does NOT (and must not) bring back to the checkpoint value:+// - `updatedAt` is re-stamped by `updateUniverse` on every canon entry whose+// content changed vs the live record — and undoing a repair IS a content+// change, so a correct revert always comes back with a fresh LWW clock (it+// has to, or the canon→catalog projection would never carry the revert).+// - the render/sheet pointers are deliberately preserved FROM the live record+// (`mergePreservedSheetPointers` / `preserveImageRefsById`) so a sheet or+// render that completed while the repair ran isn't thrown away by the undo.+// Comparing them made every faithful character rollback report itself as a+// failed restore, which stalled the foundation gate with a checkpoint-corruption+// warning that was never true. Authored content is still compared byte-for-byte.+const CANON_WRITE_PATH_OWNED_FIELDS = Object.freeze([+ 'updatedAt', 'referenceSheetImageRef', 'referenceSheets', 'imageRefs',+]);++const comparableCanonEntry = (entry) => {+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return entry;+ const rest = { ...entry };+ for (const field of CANON_WRITE_PATH_OWNED_FIELDS) delete rest[field];+ return rest;+};++const comparableUniverseFields = (universe) => {+ if (!universe || typeof universe !== 'object') return universe ?? null;+ if (!Array.isArray(universe.characters)) return universe;+ return { ...universe, characters: universe.characters.map(comparableCanonEntry) };+};++// `undefined` (field absent from the record) is NOT the same as `null` — the+// restore skips absent fields, so a repair-added field the checkpoint never had+// is a genuine leftover the verification must still catch. The sentinel keeps+// the two distinguishable through JSON.+const comparablePart = (value) => (value === undefined ? '<absent>' : JSON.stringify(value ?? null));++/**+ * Field-keyed projection of a foundation snapshot for the post-restore check.+ * Keyed (rather than one blob) so a mismatch can NAME what failed to come back —+ * a bare "did not match" pause tells an operator nothing about what to inspect.+ */+const foundationSnapshotParts = (snapshot) => {+ const universe = comparableUniverseFields(snapshot?.universe);+ const parts = { universeId: comparablePart(snapshot?.universeId || null) };+ for (const field of FOUNDATION_UNIVERSE_SNAPSHOT_FIELDS) {+ parts[`universe.${field}`] = comparablePart(universe ? universe[field] : null);+ }+ for (const field of FOUNDATION_SERIES_SNAPSHOT_FIELDS) {+ parts[`series.${field}`] = comparablePart(snapshot?.series ? snapshot.series[field] : null);+ }+ parts.arc = comparablePart(snapshot?.arcState?.arc ?? null);+ parts.seasons = comparablePart(snapshot?.arcState?.seasons || []);+ parts.episodes = comparablePart(snapshot?.arcState?.episodes || []);+ return parts;+};++/** The snapshot fields that did NOT come back — [] when the restore was faithful. */+const mismatchedFoundationFields = (checkpoint, restored) => {+ const before = foundationSnapshotParts(checkpoint);+ const after = foundationSnapshotParts(restored);+ return Object.keys(before).filter((field) => before[field] !== after[field]);+};/*** Capture every field an owned foundation repair may rewrite. Arc planning has@@ -1513,10 +1566,14 @@ export async function restoreFoundationState(seriesId, snapshot) {));const arcRestore = await restoreArcState(seriesId, snapshot.arcState);const restoredSnapshot = await snapshotFoundationState(seriesId);- const restored = foundationSnapshotComparable(restoredSnapshot) === foundationSnapshotComparable(snapshot);+ const mismatched = mismatchedFoundationFields(snapshot, restoredSnapshot);+ const restored = mismatched.length === 0;return {restored,- reason: restored ? null : 'restored foundation fields did not match the checkpoint',+ reason: restored+ ? null+ : `restored foundation fields did not match the checkpoint: ${mismatched.join(', ')}`,+ mismatchedFields: mismatched,episodesRestored: arcRestore.episodesRestored || 0,};}@@ -1682,4 +1739,6 @@ export const __testing = {CHARACTER_FOUNDATION_TIMEOUT_MS,CHARACTER_FOUNDATION_BATCH_SIZE,FRAMEWORK_STRING_FIELDS,+ mismatchedFoundationFields,+ CANON_WRITE_PATH_OWNED_FIELDS,};diff --git a/server/services/pipeline/foundationJudge.rollback.test.js b/server/services/pipeline/foundationJudge.rollback.test.jsnew file mode 100644index 0000000000..c389654c62--- /dev/null+++ b/server/services/pipeline/foundationJudge.rollback.test.js@@ -0,0 +1,216 @@+/**+ * Foundation rollback fidelity — verified against the REAL universe write path.+ *+ * The main `foundationJudge.test.js` suite stubs `updateUniverse` with a shallow+ * merge, so it cannot see what actually stalled the gate in production: undoing a+ * character repair is ITSELF a content change, and the real `updateUniverse`+ * re-stamps `updatedAt` on every canon entry whose content changed (the+ * canon→catalog LWW clock). A byte-comparison of the checkpoint therefore failed+ * on a perfectly faithful revert, and the autopilot paused with+ * "checkpoint verification failed after rollback" every single time a character+ * repair was rolled back.+ *+ * These tests run the checkpoint/restore round-trip through the actual+ * universeBuilder store (file-backed, in a per-suite tmpdir) so the write path's+ * stamping and pointer-preservation behavior is exercised, not re-implemented.+ */+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import { mkdtempSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { mockNoPeerSync, mockNoPeers } from '../../lib/mockPathsDataRoot.js';++const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'foundation-rollback-test-'));++vi.mock('../../lib/fileUtils.js', async (importActual) => {+ const actual = await importActual();+ return {+ ...actual,+ PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT },+ // Every sheet filename "exists" so mergePreservedSheetPointers takes its+ // preserve branch — the behavior this suite asserts the comparison tolerates.+ resolveImageRef: vi.fn((ref) => (typeof ref === 'string' && ref ? `/mock/refs/${ref}` : null)),+ };+});+vi.mock('../instances.js', () => mockNoPeers());+vi.mock('../sharing/peerSync.js', () => mockNoPeerSync());++// Everything the foundation judge needs but this round-trip doesn't exercise.+vi.mock('../../lib/stageRunner.js', () => ({+ runStagedLLM: vi.fn(),+ resolveStageContext: vi.fn(async () => ({ contextWindow: 200_000 })),+ resolveJudgeForStage: vi.fn(async () => ({ provider: { id: 'judge-x' }, model: 'jm-heavy' })),+}));+vi.mock('../promptService.js', () => ({ getStage: vi.fn(() => ({ name: 'writer' })) }));+vi.mock('./issues.js', async (importActual) => ({+ ...(await importActual()),+ listIssues: vi.fn(async () => []),+}));+vi.mock('./seriesCanon.js', async (importActual) => ({+ ...(await importActual()),+ getSeriesCanon: vi.fn(async () => ({ characters: [] })),+}));+vi.mock('./arcPlanner.js', async (importActual) => ({+ ...(await importActual()),+ restoreArcState: vi.fn(async () => ({ restored: true, episodesRestored: 0 })),+ snapshotArcState: vi.fn(async () => ({ seriesId: 'ser-1', arc: null, seasons: [], episodes: [] })),+}));++// In-memory series record — the series store isn't what's under test here; the+// universe canon write path is.+let seriesState = null;+vi.mock('./series.js', async (importActual) => ({+ ...(await importActual()),+ getSeries: vi.fn(async () => structuredClone(seriesState)),+ updateSeries: vi.fn(async (_id, patch) => {+ seriesState = { ...seriesState, ...structuredClone(patch) };+ return structuredClone(seriesState);+ }),+}));++const { createUniverse, getUniverse, updateUniverse, PREMISE_MAX } = await import('../universeBuilder.js');+const {+ snapshotFoundationState,+ restoreFoundationState,+ __testing,+} = await import('./foundationJudge.js');++afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));++const CAST = [+ {+ name: 'Example Lead',+ role: 'protagonist',+ want: 'to reopen the gateway network',+ need: 'to stop bargaining with the dead',+ referenceSheetImageRef: 'lead-sheet.png',+ imageRefs: ['lead-1.png'],+ },+ { name: 'Example Rival', role: 'antagonist', want: 'to keep the gates shut', need: 'to be believed' },+];++async function seedFoundation() {+ const universe = await createUniverse({+ name: `Example Universe ${Math.random().toString(36).slice(2, 8)}`,+ logline: 'world before',+ premise: 'rules before',+ styleNotes: 'style before',+ influences: { embrace: ['Example'], avoid: [] },+ characters: CAST,+ });+ seriesState = {+ id: 'ser-1',+ universeId: universe.id,+ styleNotes: 'voice before',+ styleGuide: null,+ characterArcs: [{ characterName: 'Example Lead', want: 'to reopen the network', status: 'draft' }],+ };+ return universe;+}++beforeEach(() => {+ vi.clearAllMocks();+});++describe('restoreFoundationState — against the real universe write path', () => {+ it('reports a character rollback as restored even though the write path re-stamps updatedAt', async () => {+ const universe = await seedFoundation();+ const checkpoint = await snapshotFoundationState('ser-1');++ // What a character repair does: rewrite the framework fields of the existing+ // cast through the mutator form, and add a character the judge asked for.+ await updateUniverse(universe.id, (latest) => ({+ characters: [+ ...latest.characters.map((c) => ({ ...c, need: `${c.need} (rewritten by the repair)` })),+ { name: 'Example Confidant', role: 'supporting', want: 'to be trusted', need: 'to trust' },+ ],+ }));+ seriesState = {+ ...seriesState,+ characterArcs: [+ ...seriesState.characterArcs,+ { characterName: 'Example Confidant', want: 'a seat at the table', status: 'draft' },+ ],+ };++ const rollback = await restoreFoundationState('ser-1', checkpoint);++ expect(rollback).toMatchObject({ restored: true, mismatchedFields: [] });+ expect(rollback.reason).toBeNull();++ const after = await getUniverse(universe.id);+ expect(after.characters.map((c) => c.name)).toEqual(['Example Lead', 'Example Rival']);+ expect(after.characters.map((c) => c.need)).toEqual([+ 'to stop bargaining with the dead',+ 'to be believed',+ ]);+ expect(seriesState.characterArcs).toHaveLength(1);++ // The reason the naive byte-comparison failed: the revert legitimately moved+ // the LWW clock forward on every entry it changed back.+ const beforeStamp = checkpoint.universe.characters.find((c) => c.name === 'Example Lead').updatedAt;+ const afterStamp = after.characters.find((c) => c.name === 'Example Lead').updatedAt;+ expect(Date.parse(afterStamp)).toBeGreaterThan(Date.parse(beforeStamp));+ });++ it('still reports a mismatch — naming the field — when authored content does not come back', async () => {+ const universe = await seedFoundation();+ const checkpoint = await snapshotFoundationState('ser-1');+ // A checkpoint the write path provably cannot reproduce: an over-cap premise+ // comes back truncated by the sanitizer, so the restored record legitimately+ // differs from what was asked for — exactly the case the check exists for.+ const corrupted = structuredClone(checkpoint);+ corrupted.universe.premise = 'x'.repeat(PREMISE_MAX + 100);++ const rollback = await restoreFoundationState('ser-1', corrupted);++ expect(rollback.restored).toBe(false);+ expect(rollback.mismatchedFields).toContain('universe.premise');+ expect(rollback.reason).toContain('universe.premise');+ // Untouched fields stay out of the diagnosis so the pause names one thing.+ expect(rollback.mismatchedFields).not.toContain('universe.characters');+ await getUniverse(universe.id);+ });++ it('ignores only the write-path-owned canon fields, not authored ones', () => {+ const { mismatchedFoundationFields, CANON_WRITE_PATH_OWNED_FIELDS } = __testing;+ const entry = {+ id: 'chr-1', name: 'Example Lead', need: 'trust',+ updatedAt: '2026-01-01T00:00:00.000Z',+ referenceSheetImageRef: 'a.png', referenceSheets: { front: 'f.png' }, imageRefs: ['a.png'],+ };+ const snap = (character) => ({+ universeId: 'uni-1',+ universe: { logline: 'L', premise: 'P', styleNotes: 'S', influences: {}, characters: [character] },+ series: { styleNotes: 'V', styleGuide: null, characterArcs: [] },+ arcState: { arc: null, seasons: [], episodes: [] },+ });++ // Every owned field differing → still a faithful restore.+ const volatile = {+ ...entry,+ updatedAt: '2026-08-11T12:00:00.000Z',+ referenceSheetImageRef: 'b.png', referenceSheets: { front: 'g.png' }, imageRefs: ['a.png', 'b.png'],+ };+ expect(CANON_WRITE_PATH_OWNED_FIELDS).toContain('updatedAt');+ expect(mismatchedFoundationFields(snap(entry), snap(volatile))).toEqual([]);++ // An authored field differing → still caught.+ expect(mismatchedFoundationFields(snap(entry), snap({ ...volatile, need: 'something else' })))+ .toEqual(['universe.characters']);+ });++ it('distinguishes an absent checkpoint field from a null one', () => {+ const { mismatchedFoundationFields } = __testing;+ const base = {+ universeId: 'uni-1',+ universe: { logline: 'L', premise: 'P', styleNotes: 'S', influences: {}, characters: [] },+ arcState: { arc: null, seasons: [], episodes: [] },+ };+ // Checkpoint never carried a styleGuide (the restore skips absent fields), but+ // the repair added one — an unrevertable leftover the verification must catch.+ const checkpoint = { ...base, series: { styleNotes: 'V', characterArcs: [] } };+ const after = { ...base, series: { styleNotes: 'V', styleGuide: null, characterArcs: [] } };+ expect(mismatchedFoundationFields(checkpoint, after)).toEqual(['series.styleGuide']);+ });+});