Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 73 additions & 1 deletion src/confirmations.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,84 @@
import { createServer } from 'node:http';
import { networkInterfaces } from 'node:os';
import { randomUUID, createHmac, timingSafeEqual } from 'node:crypto';
import { appendFileSync } from 'node:fs';
import { appendFileSync, existsSync, readFileSync } from 'node:fs';
import { spawn } from 'node:child_process';
import { deliverToSession, listSessionAgents, HOP_HEADER } from './session-send.mjs';

// --- registry ---------------------------------------------------------------

// id -> {prompt, session, channels, status, createdAt, decidedAt, decision, resolvers}
const intents = new Map();

// ---------------------------------------------------------------------------
// DURABLE STATE
//
// `intents` used to live only in this process. A restart threw the queue away
// with no warning and nothing read it back, so every pending approval card
// silently became undecidable. That bit three times on 2026-09-19: restarts
// while wiring /lead wiped the queue, including an intent that was mid-review.
//
// Append-only JSONL replayed at boot. Append-only because a rewrite-in-place
// can truncate on a crash and take the whole queue with it -- that is the
// failure being removed, not relocated.
//
// Deliberately NOT persisted: `resolvers`. Those are live promise callbacks
// belonging to callers of waitForDecision that died with the old process; a
// replayed intent gets an empty list and a new caller can wait on it again.
// ---------------------------------------------------------------------------
let statePath = null;

function appendState(entry) {
if (!statePath) return;
try {
appendFileSync(statePath, JSON.stringify(entry) + '\n');
} catch (e) {
// Never let a persistence failure break the decision path: losing the
// record is bad, refusing the approval is worse.
process.stderr.write(`[confirmations] state append failed: ${e.message}\n`);
}
}

/** Replay the log into memory. Last write wins per id. Returns a summary so a
* caller can log what came back rather than assume it worked. */
export function loadPersistedState(path) {
statePath = path || null;
const summary = { intents: 0, skipped: 0 };
if (!statePath || !existsSync(statePath)) return summary;
let lines;
try {
lines = readFileSync(statePath, 'utf8').split('\n');
} catch (e) {
process.stderr.write(`[confirmations] state read failed: ${e.message}\n`);
return summary;
}
for (const line of lines) {
if (!line.trim()) continue;
let e;
// A truncated final line is expected after a hard kill mid-append. Skip it
// and keep the rest rather than discarding the whole queue.
try { e = JSON.parse(line); } catch { summary.skipped += 1; continue; }
if (e.kind === 'intent' && e.id && e.intent) {
intents.set(e.id, { ...e.intent, resolvers: [] });
Comment on lines +80 to +81

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Persist and replay typed action records

When persistence is enabled, replay restores only intents; the associated entry in the actions map is never stored or reconstructed. If the process restarts after /actions/request, approving the surviving intent takes the pure-confirmation branch because no action is found, so the UI records approval but the requested merge or other executor never runs, and GET /actions/:nonce returns unknown.

Useful? React with 👍 / 👎.

}
// NOTE: `kind: 'lead'` entries are written by the team-lead branch and are
// ignored here on purpose. Main has no lead feature yet, so replaying one
// would have nowhere to put it. Forward-compatible: an older log written
// by that branch replays its intents cleanly and skips the lead rows.
}
summary.intents = intents.size;
return summary;
}

/** Write an intent's current state. Called on create and on decide. */
function persistIntent(id, i) {
if (!id || !i) return;
// The id is the Map KEY, not a field on the intent, so it has to be written
// explicitly. Without this the log looks perfectly healthy and replays
// nothing -- found by the restart test, which is why it exists.
const { resolvers, ...rest } = i;
appendState({ kind: 'intent', id, intent: rest, at: Date.now() });
}
// nonce -> typed action request. Actions reuse the intent approval UI but run
// through a strict registry instead of arbitrary shell.
const actions = new Map();
Expand Down Expand Up @@ -134,6 +204,7 @@ export function decideIntent(id, decision, { receiptsPath } = {}) {
i.status = 'decided';
i.decision = decision;
i.decidedAt = Date.now();
persistIntent(id, i);
postReceipt(receiptsPath, {
kind: 'intent.decided', id, decision, decidedAt: i.decidedAt, prompt: i.prompt,
});
Expand Down Expand Up @@ -216,6 +287,7 @@ export async function createIntent({
timeoutSec,
};
intents.set(id, intent);
persistIntent(id, intent);
postReceipt(receiptsPath, {
kind: 'intent.created', id, prompt, session, channels, createdAt: intent.createdAt,
});
Expand Down
70 changes: 70 additions & 0 deletions test/persist-intents.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// Durable intents across a restart.
//
// Scope note: the lead-appointment case from the original commit is NOT here.
// Main has no team-lead feature, so setLead/getLead do not exist to test. That
// case rides with the team-lead branch; this file covers the queue only.
//
// Written because on 2026-09-19 three daemon restarts silently wiped every
// pending intent AND the lead petrus had just appointed. The store was a bare
// `new Map()` with nothing read back at boot, so an approval card became
// undecidable and nobody was told.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';

const dir = mkdtempSync(join(tmpdir(), 'iak-persist-'));
const statePath = join(dir, 'state.jsonl');

// Fresh module instance per "process", which is what a restart actually is.
async function boot(path) {
const m = await import('../src/confirmations.mjs?v=' + Math.random());
const summary = m.loadPersistedState(path);
return { m, summary };
}

test('an intent survives a restart, with its decision', async () => {
const a = await boot(statePath);
const id = await a.m.createIntent({ prompt: 'benign test', session: 's', channels: [] });
assert.ok(id, 'intent created');

// Restart: a brand new module instance replays the log.
const b = await boot(statePath);
assert.equal(b.summary.intents, 1, 'one intent replayed');
const after = b.m.listIntents().find((i) => i.id === id);
assert.ok(after, 'the intent came back');
assert.equal(after.status, 'pending', 'and it is still pending, so it can still be decided');
});

test('a decision survives a restart', async () => {
const p2 = join(dir, 'state2.jsonl');
const a = await boot(p2);
const id = await a.m.createIntent({ prompt: 'decide me', session: 's', channels: [] });
a.m.decideIntent(id, 'approve', { actor: 'petrus' });

const b = await boot(p2);
const after = b.m.listIntents().find((i) => i.id === id);
assert.equal(after.status, 'decided');
assert.equal(after.decision, 'approve', 'the decision replayed, not just the intent');
});

test('a truncated final line is skipped, the rest survives', async () => {
const p4 = join(dir, 'state4.jsonl');
const a = await boot(p4);
await a.m.createIntent({ prompt: 'first', session: 's', channels: [] });
// Simulate a hard kill mid-append: valid lines, then a partial one.
writeFileSync(p4, readFileSync(p4, 'utf8') + '{"kind":"intent","intent":{"id":"trunc"');

const b = await boot(p4);
assert.equal(b.summary.skipped, 1, 'the partial line was skipped');
assert.equal(b.summary.intents, 1, 'and the intact intent still loaded');
});

test('with no state path nothing is written — persistence is opt-in', async () => {
const unused = join(dir, 'never.jsonl');
const a = await boot(null);
await a.m.createIntent({ prompt: 'no persistence', session: 's', channels: [] });
assert.equal(existsSync(unused), false, 'no file appeared');
assert.equal(a.summary.intents, 0, 'and loading nothing reports nothing');
});
Loading