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
harden ledger reconciliation against a failed append, an unsafe run id, and a corrupt record (#4540)
[._.]/ Adam Eivyafce67a9438c
diff --git a/server/services/agentRunReconciler.js b/server/services/agentRunReconciler.jsindex 95a328c699..31989fd2c8 100644--- a/server/services/agentRunReconciler.js+++ b/server/services/agentRunReconciler.js@@ -27,19 +27,46 @@ import { RUN_EVENT_READ_LIMITS } from '../lib/agentRunEvents.js';import { reconcileRunRecords, planRunRecordRepair, isAgentFallbackKey } from '../lib/agentRunReconcile.js';import { getRunProjections, appendRunEvent } from './agentRunEventLog.js';-const metadataPath = (runId) => join(PATHS.runs, runId, 'metadata.json');+/**+ * A run id is about to become a filesystem path, and it arrives from a file on+ * disk rather than from this process. The ledger's envelope schema bounds ids+ * by LENGTH only, so a hand-edited or truncated-and-recovered line could carry+ * `../` and point the read — or the repair write — at a `metadata.json`+ * outside `data/runs`. Every id the server itself mints is a uuid, so+ * demanding a single plain path segment costs nothing and closes that.+ */+const SAFE_RUN_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;+const metadataPath = (runId) =>+ (SAFE_RUN_ID.test(runId) && runId !== '.' && runId !== '..' ? join(PATHS.runs, runId, 'metadata.json') : null);++/**+ * A parsed `metadata.json`, or null if the file held something that is not a+ * run record. `readJSONFile` returns whatever the file parsed to, and a+ * truncated or hand-edited file can parse to `[]` or `"…"` — both truthy, both+ * with no `endTime`, so an unguarded read would call a corrupt file an open run+ * and then spread an array into the repaired record.+ */+const asRecord = (value) =>+ (value && typeof value === 'object' && !Array.isArray(value) ? value : null);++const readRecord = async (runId) => {+ const path = metadataPath(runId);+ return path ? asRecord(await readJSONFile(path, null)) : null;+};/*** Load the run records the given projections name.** Absent records are stored as an explicit `null` rather than left out of the* map, so the diff can tell "no record on disk" from "not looked at" — the- * sentinel-over-truthiness rule that runs through this whole feature.+ * sentinel-over-truthiness rule that runs through this whole feature. An+ * unusable id or a corrupt file lands on that same `null`, and so is reported+ * as `record-missing` — which is what it is from here: no readable run record.*/async function loadRecordsFor(projections) {const runIds = projections.map((p) => p.id).filter((id) => id && !isAgentFallbackKey(id));- const records = await Promise.all(runIds.map((id) => readJSONFile(metadataPath(id), null)));- return new Map(runIds.map((id, index) => [id, records[index] ?? null]));+ const records = await Promise.all(runIds.map(readRecord));+ return new Map(runIds.map((id, index) => [id, records[index]]));}const cap = (limit) => Math.min(@@ -106,22 +133,26 @@ async function repairNow({ runId, limit } = {}) {const path = metadataPath(item.runId);// Fresh read — the report above may be a few disk reads old, and the run's// own completion path is the one writer allowed to win that race.- const record = await readJSONFile(path, null);+ const record = await readRecord(item.runId);const patch = planRunRecordRepair(projection, record, new Date().toISOString());if (!patch) {skipped += 1;continue;}- await atomicWrite(path, { ...record, ...patch });- console.log(`🩹 Closed run ${item.runId} from the event ledger: ledger read ${item.detail.ledgerStatus}, record now ${patch.success ? 'success' : 'failure'}`);-- // The repair is a lifecycle fact of its own. An explicit natural key rather- // than the content-derived default: re-running a repair for the same run- // and the same close stamp is the same fact, and the content hash covers- // the wall-clock `reconciledAt`, so it would otherwise mint a new event on- // every pass.- await appendRunEvent({+ // The ledger entry goes FIRST, and a failed append aborts the repair.+ //+ // Order decides which half of a half-finished repair survives a crash, and+ // only one order is recoverable. Event-then-record: the next pass reads the+ // run as terminal, the record as still open, plans the same repair, and the+ // event's natural key dedupes the second append — self-healing. The reverse+ // leaves a record closed by an event nothing recorded, which for an orphan+ // repair reads as a permanent `ledger-open` finding no later pass can+ // resolve, because the record it would have to fix is already closed.+ //+ // `appendRunEvent` never rejects; it REPORTS failure, so the result has to+ // be read rather than awaited and ignored.+ const appended = await appendRunEvent({kind: 'run.reconciled',eventId: `reconcile:${item.runId}:${patch.endTime}`,runId: item.runId,@@ -135,6 +166,14 @@ async function repairNow({ runId, limit } = {}) {durationMs: patch.duration}});+ if (appended?.error) {+ console.error(`❌ Skipped reconciling run ${item.runId}: could not record the repair (${appended.error})`);+ skipped += 1;+ continue;+ }++ await atomicWrite(path, { ...record, ...patch });+ console.log(`🩹 Closed run ${item.runId} from the event ledger: ledger read ${item.detail.ledgerStatus}, record now ${patch.success ? 'success' : 'failure'}`);repaired.push({ runId: item.runId, from: item.detail.ledgerStatus, success: patch.success, endTime: patch.endTime });}diff --git a/server/services/agentRunReconciler.test.js b/server/services/agentRunReconciler.test.jsindex be1a43cd6a..30dfa86877 100644--- a/server/services/agentRunReconciler.test.js+++ b/server/services/agentRunReconciler.test.js@@ -12,9 +12,10 @@ const { LEDGER_DIR, RUNS_DIR, hooks } = await vi.hoisted(async () => {return {LEDGER_DIR: mk(j(tmp(), 'portos-reconcile-ledger-')),RUNS_DIR: mk(j(tmp(), 'portos-reconcile-runs-')),- // A seam for the one test that has to interleave a write between the- // service's two reads of the same record. Nothing else installs a hook.- hooks: { afterRecordRead: null }+ // Seams for the two tests that need to interleave a write between the+ // service's two reads of the same record, or make the ledger append fail.+ // Nothing else installs a hook.+ hooks: { afterRecordRead: null, failAppend: false }};});@@ -27,6 +28,10 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => {const value = await actual.readJSONFile(path, fallback);if (hooks.afterRecordRead) await hooks.afterRecordRead(path);return value;+ },+ appendJSONLine: async (path, line) => {+ if (hooks.failAppend) throw new Error('ledger disk full');+ return actual.appendJSONLine(path, line);}};});@@ -69,6 +74,7 @@ beforeEach(() => {afterEach(() => {hooks.afterRecordRead = null;+ hooks.failAppend = false;vi.useRealTimers();});afterAll(() => {@@ -221,6 +227,61 @@ describe('repairRunRecords', () => {expect(record.error).toContain('reconciliation');});+ it('leaves the record open when the repair cannot be recorded in the ledger', async () => {+ writeRecord('r1', { endTime: null, success: null });+ await spawn('r1');+ await finalize('r1', false);++ // Only one order survives a crash (or a failed write) mid-repair. With the+ // event first, a repair that could not be recorded leaves an open record+ // the NEXT pass retries. With the record first, the record would be closed+ // by an event nothing recorded — and for an orphan repair that reads as a+ // permanent 'ledger-open' finding no later pass can resolve.+ hooks.failAppend = true;+ const result = await repairRunRecords();+ hooks.failAppend = false;++ expect(result.repaired).toEqual([]);+ expect(result.skipped).toBe(1);+ expect(readRecord('r1').endTime).toBeNull();+ expect(await readRunEvents({ runId: 'r1', kind: 'run.reconciled' })).toEqual([]);++ // ...and the next pass still finds the same repairable drift.+ const retry = await repairRunRecords();+ expect(retry.repaired).toEqual([{ runId: 'r1', from: 'failed', success: false, endTime: LATER }]);+ });++ it('skips a run whose record file is not a run record', async () => {+ mkdirSync(join(RUNS_DIR, 'r1'), { recursive: true });+ writeFileSync(metaPath('r1'), '["not", "a", "record"]');+ await spawn('r1');+ await finalize('r1', false);++ const result = await repairRunRecords();+ // A corrupt file is unreadable, not an open run — repairing it would have+ // spread an array into the "repaired" record.+ expect(result.findings[0].finding).toBe('record-missing');+ expect(result.repaired).toEqual([]);+ expect(readFileSync(metaPath('r1'), 'utf8')).toBe('["not", "a", "record"]');+ });++ it('refuses to follow a run id out of the runs directory', async () => {+ // A hand-edited or truncated-and-recovered ledger line is the only way this+ // id gets in — every id the server mints is a uuid — but it would otherwise+ // become a path.+ const escaping = '../escape';+ mkdirSync(join(RUNS_DIR, '..', 'escape'), { recursive: true });+ const outside = join(RUNS_DIR, '..', 'escape', 'metadata.json');+ writeFileSync(outside, JSON.stringify({ id: escaping, startTime: AT, endTime: null }));+ await appendRunEvent({ kind: 'run.spawned', runId: escaping, at: AT, data: {} });+ await appendRunEvent({ kind: 'run.finalized', runId: escaping, at: LATER, data: { success: false, exitCode: 1 } });++ const result = await repairRunRecords();+ expect(result.findings.map((f) => f.finding)).toEqual(['record-missing']);+ expect(result.repaired).toEqual([]);+ expect(JSON.parse(readFileSync(outside, 'utf8')).endTime).toBeNull();+ });+it('runs one pass at a time', async () => {writeRecord('r1', { endTime: null, success: null });await spawn('r1');