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
close three reconciliation races found in local review (#4540)
[._.]/ Adam Eivy5331ab345914
diff --git a/client/src/components/cos/tabs/RunEventsTab.jsx b/client/src/components/cos/tabs/RunEventsTab.jsxindex 80a812e25c..e03d5b52df 100644--- a/client/src/components/cos/tabs/RunEventsTab.jsx+++ b/client/src/components/cos/tabs/RunEventsTab.jsx@@ -337,13 +337,7 @@ function ReconciliationPanel({ report, onSelect, confirming, onAskRepair, onCanc))}</div>- {result && (- <Banner tone={result.repaired?.length ? 'success' : 'info'}>- {result.repaired?.length- ? `Closed ${result.repaired.length} run record${result.repaired.length === 1 ? '' : 's'} from the ledger.`- : 'Nothing left to close — every repairable record had already been closed.'}- </Banner>- )}+ {result && <RepairResult result={result} />}{findings.length === 0 ? (<p className="mt-2 text-xs text-port-text-muted">@@ -377,6 +371,32 @@ function ReconciliationPanel({ report, onSelect, confirming, onAskRepair, onCanc);}+/**+ * What a repair pass actually did.+ *+ * "Repaired none" and "repaired none, and N were skipped" are different+ * outcomes and must not read alike: a skip means the record is still open —+ * either it closed itself underneath the pass, or the repair could not be+ * recorded in the ledger — so reporting it as "nothing left to close" would+ * tell the user the drift is gone while it is still on screen.+ */+function RepairResult({ result }) {+ const closed = result.repaired?.length ?? 0;+ const skipped = result.skipped ?? 0;+ const runs = (n) => `${n} run record${n === 1 ? '' : 's'}`;++ if (closed === 0 && skipped === 0) {+ return <Banner tone="info">Nothing left to close — every repairable record had already been closed.</Banner>;+ }+ return (+ <Banner tone={closed > 0 ? 'success' : 'warning'}>+ {closed > 0 ? `Closed ${runs(closed)} from the ledger.` : ''}+ {closed > 0 && skipped > 0 ? ' ' : ''}+ {skipped > 0 ? `Left ${runs(skipped)} alone — they changed underneath the repair, or it could not be recorded in the ledger.` : ''}+ </Banner>+ );+}+function LedgerStat({ label, value }) {return (<div className="rounded border border-port-border px-3 py-2">diff --git a/client/src/components/cos/tabs/RunEventsTab.test.jsx b/client/src/components/cos/tabs/RunEventsTab.test.jsxindex 8f974749b1..6096e5804e 100644--- a/client/src/components/cos/tabs/RunEventsTab.test.jsx+++ b/client/src/components/cos/tabs/RunEventsTab.test.jsx@@ -243,6 +243,23 @@ describe('RunEventsTab — reconciliation panel', () => {expect(api.getRunEventProjections).toHaveBeenCalledTimes(2);});+ it('does not report a skipped repair as nothing left to do', async () => {+ api.getRunReconciliation.mockResolvedValue({+ ...CLEAN_REPORT,+ findings: [finding()],+ summary: { ...CLEAN_REPORT.summary, findings: 1, repairable: 1 },+ });+ // The record is still open — saying "nothing left to close" would claim the+ // drift is gone while it is still listed on screen.+ api.repairRunRecords.mockResolvedValue({ ...CLEAN_REPORT, repaired: [], skipped: 1 });+ renderTab();++ await userEvent.click(await screen.findByRole('button', { name: /Close 1 from ledger/ }));+ await userEvent.click(screen.getByRole('button', { name: 'Close records' }));+ expect(await screen.findByText(/Left 1 run record alone/)).toBeInTheDocument();+ expect(screen.queryByText(/Nothing left to close/)).not.toBeInTheDocument();+ });+it('hides the panel entirely for an empty ledger', async () => {api.getRunEventProjections.mockResolvedValue([]);api.getRunReconciliation.mockResolvedValue({ ...CLEAN_REPORT, summary: { ...CLEAN_REPORT.summary, checked: 0 } });diff --git a/server/services/agentRunReconciler.js b/server/services/agentRunReconciler.jsindex 31989fd2c8..6b1e6304b5 100644--- a/server/services/agentRunReconciler.js+++ b/server/services/agentRunReconciler.js@@ -22,7 +22,7 @@*/import { join } from 'path';-import { PATHS, readJSONFile, atomicWrite } from '../lib/fileUtils.js';+import { PATHS, readJSONFile, atomicWrite, sha256Text } from '../lib/fileUtils.js';import { RUN_EVENT_READ_LIMITS } from '../lib/agentRunEvents.js';import { reconcileRunRecords, planRunRecordRepair, isAgentFallbackKey } from '../lib/agentRunReconcile.js';import { getRunProjections, appendRunEvent } from './agentRunEventLog.js';@@ -69,6 +69,18 @@ async function loadRecordsFor(projections) {return new Map(runIds.map((id, index) => [id, records[index]]));}+/**+ * The idempotency key for one repair: this run, closed at this instant.+ *+ * Hashed rather than spelled out because `buildRunEvent` truncates `eventId` at+ * 128 characters, and a readable `reconcile:<runId>:<endTime>` key puts the+ * run id FIRST — so two ids sharing a long prefix would truncate to the same+ * key and the second repair would be silently suppressed as a duplicate of the+ * first. A fixed-width digest cannot be truncated into a collision. The+ * `reconcile:` prefix stays so the key is still recognizable in the ledger.+ */+const repairEventId = (runId, endTime) => `reconcile:${sha256Text(`${runId}\u0000${endTime}`).slice(0, 32)}`;+const cap = (limit) => Math.min(Number.isFinite(limit) && limit > 0 ? Math.floor(limit) : RUN_EVENT_READ_LIMITS.default,RUN_EVENT_READ_LIMITS.max@@ -154,7 +166,7 @@ async function repairNow({ runId, limit } = {}) {// be read rather than awaited and ignored.const appended = await appendRunEvent({kind: 'run.reconciled',- eventId: `reconcile:${item.runId}:${patch.endTime}`,+ eventId: repairEventId(item.runId, patch.endTime),runId: item.runId,agentId: item.agentId,taskId: item.taskId,@@ -172,7 +184,20 @@ async function repairNow({ runId, limit } = {}) {continue;}- await atomicWrite(path, { ...record, ...patch });+ // The append did disk I/O of its own, so the record read before it is a+ // read old again. The LAST read before the write is the one that has to be+ // current — otherwise a run whose own completion path landed during the+ // append gets overwritten with a verdict this pass computed before it. A+ // re-plan that comes back null means the record closed itself; the already+ // appended event is harmless (a real `run.finalized` outranks it in the+ // fold, and its key dedupes a later retry).+ const fresh = await readRecord(item.runId);+ if (!planRunRecordRepair(projection, fresh, patch.reconciledAt)) {+ skipped += 1;+ continue;+ }++ await atomicWrite(path, { ...fresh, ...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 30dfa86877..1145433b5e 100644--- a/server/services/agentRunReconciler.test.js+++ b/server/services/agentRunReconciler.test.js@@ -282,6 +282,53 @@ describe('repairRunRecords', () => {expect(JSON.parse(readFileSync(outside, 'utf8')).endTime).toBeNull();});+ it('does not overwrite a record that closed itself while the repair was being recorded', async () => {+ writeRecord('r1', { endTime: null, success: null });+ await spawn('r1');+ await finalize('r1', false);++ // Reads of r1 in one pass: the batch load, the pre-plan read, and the+ // re-read after the ledger append. The run's own completion path lands+ // between the second and the third — which is exactly what the third read+ // exists to notice.+ let reads = 0;+ hooks.afterRecordRead = (path) => {+ if (!path.includes('r1')) return;+ reads += 1;+ if (reads === 2) writeRecord('r1', { endTime: LATER, success: true, duration: 7 });+ };++ const result = await repairRunRecords();+ hooks.afterRecordRead = null;++ expect(reads).toBe(3);+ expect(result.repaired).toEqual([]);+ expect(result.skipped).toBe(1);+ expect(readRecord('r1')).toMatchObject({ success: true, duration: 7 });+ expect(readRecord('r1').reconciledFromLedger).toBeUndefined();+ });++ it('keys repairs by a fixed-width digest so long run ids cannot collide', async () => {+ // `eventId` is truncated at 128 chars by the envelope schema. A readable+ // `reconcile:<runId>:<endTime>` key would put the run id first, so two long+ // ids sharing a prefix would truncate to one key and the second repair+ // would be suppressed as a duplicate that never happened.+ const long = (suffix) => `${'a'.repeat(120)}${suffix}`;+ for (const suffix of ['1', '2']) {+ const runId = long(suffix);+ writeRecord(runId, { endTime: null, success: null });+ await appendRunEvent({ kind: 'run.spawned', runId, at: AT, data: {} });+ await appendRunEvent({ kind: 'run.finalized', runId, at: LATER, data: { success: false, exitCode: 1 } });+ }++ const result = await repairRunRecords();+ expect(result.repaired.map((r) => r.runId).sort()).toEqual([long('1'), long('2')].sort());+ expect(readRecord(long('1')).endTime).toBe(LATER);+ expect(readRecord(long('2')).endTime).toBe(LATER);+ const ids = (await readRunEvents({ kind: 'run.reconciled' })).map((e) => e.eventId);+ expect(new Set(ids).size).toBe(2);+ });+it('runs one pass at a time', async () => {writeRecord('r1', { endTime: null, success: null });await spawn('r1');