Salvage uncommitted work from T3 worktree t3-dd8ce6b7 (disk cleanup #824)

This commit is contained in:
mos committed 2026-11-06 09:54:51 -06:00
1 parent e9271841f3
commit a71ccf8a2b
14 files changed
+377 -34

No files matched your search

+15
View File
@@ -1100,3 +1100,18 @@ for task creation. No PRD decision or historical snapshot is rewritten.
The existing `bootstrap.completed` journal payload has optional host-validated
attachment fields; old events retain their original meaning and schema 3s needs
no migration.
Lifecycle continuations wake a live PM when a new, complete validated push/review
evidence set becomes available. Committed attempt receipts deduplicate unchanged
evidence across recovery and host restarts. A normal recovery call inspects at
most its requested batch limit. An event overlapping a recovery keeps a full
reinspection cycle pending, in bounded batches, so retained history cannot hide
an already-inspected request until a later timer tick.
Assistant-to-chief-to-PM intake relays must link `in_reply_to` to the message
received. The broker derives the original request header from that authorized
recipient chain and its owner/thread/session evidence, never from a message body.
For lifecycle tasks, the first review request includes the exact raw JSON
verification-document and verdict-body contract; unrelated reviews retain their
existing free-text contract. The typed record tools describe the existing closed
requirement schema without relaxing host validation.
+39 -6
View File
@@ -614,6 +614,11 @@ export class Broker {
progress: state => this.#requestProgress(state),
deliveryEvidence: (state, args) => this.#deliveryEvidence(state, args),
continuationContext: (state, target) => this.#continuationContext(state, target),
continuationProgress: state => {
if (!['implementation', 'review'].includes(state.phase)) return null;
try { return this.#requestProgress(state); }
catch (e) { if (e.code === 'request-evidence-required') return null; throw e; }
},
continuationEffect: (state, intent, message) => {
if (intent.step !== 'send_message' || state.phase !== 'complete' || !state.thread) return null;
const b = this.#business(state.business);
@@ -963,11 +968,11 @@ export class Broker {
this.#requestAuthorize(s, { business: s.business, owner: b.human, pm }, 'get');
if (!s.human) {
// Only direct receipt or an existing, broker-authorized reply/relay chain exposes an origin.
const reachable = this.#store.get(`WITH RECURSIVE reachable(id,to_role) AS (
const reachable = this.#store.all(`WITH RECURSIVE reachable(id,to_role) AS (
SELECT id,to_role FROM messages WHERE business=? AND id=?
UNION SELECT m.id,m.to_role FROM messages m JOIN reachable r ON m.in_reply_to=r.id WHERE m.business=?
) SELECT 1 FROM reachable WHERE to_role=? LIMIT 1`, s.business, m.id, s.business, pm);
if (!reachable) fail('request-origin-refused');
UNION SELECT m.id,m.to_role FROM messages m JOIN reachable r ON m.in_reply_to=r.id AND m.from_role=r.to_role WHERE m.business=?
) SELECT m.* FROM reachable r JOIN messages m ON m.id=r.id WHERE r.to_role=?`, s.business, m.id, s.business, pm);
if (!reachable.some(message => this.#request(s.business, message) === request)) fail('request-origin-refused');
this.#checkMessaging(s.business, pm, 'human');
this.#checkMessaging(s.business, 'human', pm);
}
@@ -7007,11 +7012,15 @@ export class Broker {
{ task_ref: a.task_ref, project: push.project, ref: push.ref, commit: a.commit, to: a.to, message: mid, held },
a.task_ref,
);
const created = this.#store.all("SELECT body FROM events WHERE business=? AND kind='task.created' AND subject=? ORDER BY seq DESC", s.business, a.task_ref)
.map(row => JSON.parse(row.body));
const scoped = created.some(c => this.#requests?.reviewScope?.(s.business, c.request, a.task_ref, push.project, c.requirement_snapshot, s.role, a.to));
const contract = scoped ? `\n\nFor this lifecycle review, before the verdict use write_record to write a docs/*.md verification document whose entire content is raw JSON, without Markdown fences or prose: {"version":1,"task_ref":"${a.task_ref}","review_request":"${eid}","commit":"${a.commit}","results":"nonempty results"}. Then use review_verdict with a raw JSON body containing exactly {"verification_record":{"path":"...","commit":"..."},"results":"..."}; use the write_record receipt path and commit, and the same results string. You must independently inspect and test the commit.` : '';
this.#reviewMessage(s, mid, {
to: a.to,
cls: 'REVIEW-REQUEST',
decision: withinRole ? null : (a.decision ?? null),
body: `Review request ${eid} for ${a.task_ref}: commit ${a.commit} on ${push.ref} in project ${push.project}. Fetch it with fetch_review, then answer with review_verdict citing this request.${a.note ? '\n\n' + a.note : ''}`,
body: `Review request ${eid} for ${a.task_ref}: commit ${a.commit} on ${push.ref} in project ${push.project}. Fetch it with fetch_review, then answer with review_verdict citing this request.${contract}${a.note ? '\n\n' + a.note : ''}`,
});
return { request: eid, message: mid, commit: a.commit, ref: push.ref, held };
}
@@ -7833,7 +7842,31 @@ export class Broker {
business,
m.id,
);
if (own || m.class !== 'DECISION' || m.from_role !== 'human' || !m.decision) return own?.id ?? null;
if (own) return own.id;
// Only a chain of actual recipient replies can carry an owner's instruction.
// Message bodies and unlinked role messages never confer provenance.
if (m.in_reply_to && m.from_role !== 'human') {
let child = m; const seen = new Set([m.id]), scopes = [];
while (child.in_reply_to && !seen.has(child.in_reply_to)) {
const scope = this.#store.get('SELECT thread,session FROM message_threads WHERE message=?', child.id);
if (scope) scopes.push(scope);
const parent = this.#store.get('SELECT * FROM messages WHERE business=? AND id=?', business, child.in_reply_to);
if (!parent || parent.to_role !== child.from_role) break;
const roles = this.#business(business).roles;
if (![parent.from_role, parent.to_role, child.from_role, child.to_role].every(role => role === 'human' || Object.hasOwn(roles, role))) break;
try { this.#checkMessaging(business, parent.from_role, parent.to_role); this.#checkMessaging(business, child.from_role, child.to_role); } catch { break; }
seen.add(parent.id);
if (parent.from_role === 'human') {
const thread = this.#store.get('SELECT mt.thread,mt.session,t.owner FROM message_threads mt JOIN threads t ON t.id=mt.thread WHERE mt.message=?', parent.id);
if ((thread && thread.owner !== this.#business(business).human) || scopes.some(scope => !thread || scope.thread !== thread.thread || scope.session !== thread.session)) break;
const source = this.#store.get("SELECT id FROM events WHERE business=? AND kind='human.input' AND actor_role IS NULL AND actor_run IS NULL AND subject=? AND json_extract(body,'$.kind')='instruction' AND json_extract(body,'$.message')=? ORDER BY seq LIMIT 1", business, parent.id, parent.id);
if (source) return source.id;
break;
}
child = parent;
}
}
if (m.class !== 'DECISION' || m.from_role !== 'human' || !m.decision) return null;
return (
this.#store.get(
"SELECT id FROM events WHERE business=? AND kind='human.input' AND subject=? AND json_extract(body,'$.kind')='answer' AND json_extract(body,'$.op') IN ('resolved','withdrawn') ORDER BY seq LIMIT 1",
+11 -9
View File
@@ -39,7 +39,7 @@ export function createContinuations({ journal, services }) {
question: state.question?.id ?? null, answer: state.question?.answer ?? null, plan: state.plan_digest, spec_commit: state.spec_commit, candidate: state.candidate ? { prd_version: state.candidate.prd_version, records_commit: state.candidate.records_commit, prd_path: state.candidate.prd_path } : null, snapshot: state.snapshot, tasks: state.tasks, delivery: state.delivery_evidence ?? null, events: state.evidence ?? [] });
const intentFor = (state, target, step) => ({ key: digest([state.request, state.revision, target, step]),
request: state.request, revision: state.revision, target, step, phase: state.phase, project: state.project, evidence: evidence(state) });
function send(state, intent, context) {
function send(state, intent, context, progress = null) {
const control = { request: state.request, revision: state.revision, op: `continue-${intent.key.slice(0, 32)}` };
const next = {
intake_propose: { args: control, requires: ['source_project','project','name','tracker_project'] },
@@ -52,13 +52,13 @@ export function createContinuations({ journal, services }) {
task_close: { args: { task_ref: state.tasks[0] }, requires: ['verdict'] },
send_message: { args: { in_reply_to: state.source_message }, requires: ['to','body'] },
}[intent.step];
const body = `Request continuation ${intent.key}\n${JSON.stringify({ ...intent, next: { tool: intent.step, ...next } })}\n` +
const body = `Request continuation ${intent.key}\n${JSON.stringify({ ...intent, ...(progress ? { progress } : {}), next: { tool: intent.step, ...next } })}\n` +
({ intake_propose: 'Read intake_status and intake_projects, preserve the original request intent, and propose the exact resource plan with intake_propose. If the owner selected existing, select an accessible existing mapping. The owner confirms the plan; discovery needs no task or tracker effect.',
submit_prd: 'Read the committed spec and discovery records. Finish the product PRD and requirements with write_record, then submit_prd with their exact records commit, path, version and ids. Use request_staff for missing technical help.',
resolve_decision: 'Read the exact PRD candidate and requirements with intake_status(path), one selected path at a time. Resolve only the cited PRD decision through resolve_decision; ask for changes if evidence is incomplete.',
task_create: 'Read list_requirements for this project and snapshot. Check existing task/create receipts before creating or retrying. Create and assign the scoped tasks, request_staff for coder/reviewer sessions, then advance_request.',
push_working: 'Check the assigned tasks and existing receipts. Implement the approved requirements, push_working, and request_review for each latest commit.',
review_verdict: 'Fetch each current review request with fetch_review, run acceptance checks, write a verification Markdown record containing a JSON object with version 1, task_ref, review_request, commit and results (a nonempty string), then return review_verdict with a JSON body containing exactly verification_record: {path, commit} from write_record and results, matching the record.',
review_verdict: 'Fetch each current review request with fetch_review, run acceptance checks, before the verdict, write a docs/*.md verification document whose entire content is raw JSON (no Markdown fences or prose): {"version":1,"task_ref":"...","review_request":"...","commit":"...","results":"..."}. Results must be a nonempty string. Return review_verdict with a raw JSON body containing exactly {"verification_record":{"path":"...","commit":"..."},"results":"..."}, using the write_record receipt and matching results.',
advance_request: 'Check the existing task, push and review evidence, then call advance_request at the current intake_status revision. Never claim a success phase.',
task_close: 'Close each task with task_close citing the latest approve verdict. Read the review verdict JSON for verification_record and results, then call deliver_request for the reviewed HTML and that reviewer-authored verification record; closing alone does not complete delivery.',
send_message: 'Deliver the artifact and task/review evidence through the existing chief → assistant → user path, with send_message in_reply_to the original source_message so it returns to the originating session. Never coordinate the assistant directly with PM or reviewer.' }[intent.step]);
@@ -68,19 +68,21 @@ export function createContinuations({ journal, services }) {
const intent = row.result.intent, rows = effects(state);
const attempts = rows.filter(e => e.stage === 'committed' && e.result?.type === 'attempt' && e.result.key === intent.key);
const last = attempts.at(-1)?.result;
// Same role run means the same turn owns the work, even after it reads the notice.
// The same run gets one additional wake for each new complete progress evidence set.
// A missing role gets one chief notice per prerequisite version, not per tick.
const token = context.run ? `run:${context.run}` : `waiting:${context.prerequisite}`;
if (last?.token === token) return;
const wake = intent.step === 'advance_request' ? services.continuationProgress?.(state) ?? null : null;
const progress = wake ? digest(wake) : null;
const token = `${context.run ? `run:${context.run}` : `waiting:${context.prerequisite}`}${progress ? `:evidence:${progress}` : ''}`;
if (attempts.some(a => a.result.token === token)) return;
journal.transaction(() => {
let message = initialMessage;
if (!message && last?.message && (!context.run || services.continuationRouted?.(last.message, context.run))) {
if (!message && last?.message && (!context.run || (last.run !== context.run && (last.progress ?? null) === progress && services.continuationRouted?.(last.message, context.run)))) {
message = last.message;
if (!context.run) services.continuationRetry?.(state, message, intent.target, context);
}
message ??= send(state, intent, context);
message ??= send(state, intent, context, wake);
receipt(state, `attempt:${intent.key}:${attempts.length + 1}`, { type: 'attempt', key: intent.key, attempt: attempts.length + 1,
token, run: context.run, prerequisite: context.prerequisite, message });
token, run: context.run, prerequisite: context.prerequisite, progress, message });
});
}
function resume(state) {
+29 -10
View File
@@ -12,7 +12,7 @@ import { exact, object, id, key, text, digest, validatePlan, refuse, positive, o
export function createRequestLifecycle({ journal, services }) {
if (!journal || !services || !['origin','authorize','raiseDecision','readDecision','project'].every(k => typeof services[k] === 'function')) refuse('request-services-unavailable');
const continuations = createContinuations({ journal, services });
let closing = false, recovery = null, cursor = 0;
let closing = false, recovery = null, recoveryAgain = false, cursor = 0;
const pending = new Map();
const serial = (business, request, fn) => {
const k = business + '/' + request;
@@ -517,6 +517,16 @@ export function createRequestLifecycle({ journal, services }) {
return { mime: d.artifact.mime, filename: basename(d.artifact.path), base64: artifact.bytes.toString('base64'), sha256: artifact.sha256 };
}
return Object.freeze({ open, get, projects, propose, submit, question, answer, attach, cancel, advance, deliver, artifactConsole, modeConsole,
reviewScope: (business, request, task, project, snapshot, coder, reviewer) => {
if (typeof request !== 'string') return false;
const row = journal.listRequests().find(r => r.business === business && r.request === request);
if (!row) return false;
const state = journal.readRequest(business, request);
const staff = state.selection?.bindings.find(b => b.digest === state.plan_digest)?.plan.staff;
return ['planning', 'implementation', 'review', 'delivery'].includes(state.phase) && state.project === project &&
state.snapshot === snapshot && !!snapshot && staff?.coder === coder && staff?.reviewer === reviewer &&
(state.phase === 'planning' || state.tasks.includes(task));
},
hasWork: () => journal.listRequests().length > 0, launches: continuations.launches, launchResult: continuations.launchResult, manifestNeeded: continuations.manifestNeeded,
draftConsole: async (identity, args) => {
exact(args, ['request']); if (!id(args.request)) refuse('invalid-request');
@@ -537,16 +547,25 @@ export function createRequestLifecycle({ journal, services }) {
close: async () => { closing = true; await recovery; await Promise.allSettled([...pending.values()]); await services.catalog?.drain(); },
recover: ({ limit = Infinity } = {}) => {
if (closing) return Promise.resolve([]);
if (recovery) return recovery;
// An overlapping event may concern any already-inspected request. Keep a
// full reinspection cycle pending, using the same per-batch limit.
if (recovery) { recoveryAgain = true; return recovery; }
recovery = (async () => {
const states = [], rows = journal.listRequests();
const count = Math.min(rows.length, limit), start = cursor % (rows.length || 1);
for (let n = 0; n < count; n++) {
if (closing) break;
const { business, request } = rows[(start + n) % rows.length];
states.push(await resume(business, request));
}
cursor = (start + count) % (rows.length || 1);
const states = [];
let remaining = Math.min(journal.listRequests().length, limit);
do {
recoveryAgain = false;
const rows = journal.listRequests();
const count = Math.min(rows.length, limit, remaining), start = cursor % (rows.length || 1);
for (let n = 0; n < count; n++) {
if (closing) break;
const { business, request } = rows[(start + n) % rows.length];
states.push(await resume(business, request));
}
cursor = (start + count) % (rows.length || 1);
remaining = recoveryAgain ? journal.listRequests().length : Math.max(0, remaining - count);
if (count === 0) break;
} while (remaining > 0 && !closing);
return states;
})().finally(() => { recovery = null; });
return recovery;
@@ -316,3 +316,117 @@ test('historical complete event remains readable without delivery evidence and c
assert.equal(f.journal.readRequest('demo', f.request).phase, 'complete');
assert.equal(f.journal.readRequest('demo', f.request).revision, before.revision);
});
test('late implementation and review evidence wake a live PM exactly once through receive and recovery', async t => {
const f = await planned(t);
const drain = () => { const ms = f.call('pm', 'message.receive'); for (const m of ms) f.call('pm', 'message.read', { id: m.id }); return ms; };
await advance(f, 'implementation'); await f.bus.requestLifecycle.recover();
assert.ok(drain().some(m => m.body.includes('advance_request')));
await assert.rejects(advance(f, 'early-implementation'), /request-evidence-required/);
const commit = 'a'.repeat(40); f.push(commit);
await f.bus.requestLifecycle.recover();
assert.equal(drain().filter(m => m.body.includes('advance_request')).length, 0, 'push alone is insufficient');
await assert.rejects(advance(f, 'still-early'), /request-evidence-required/);
const review = f.review(commit);
await f.bus.requestLifecycle.recover();
const wake = drain().filter(m => m.body.includes('advance_request'));
assert.equal(wake.length, 1, 'new push and review wake PM');
assert.ok(wake[0].body.includes(review.request), 'wake carries the validated evidence');
await f.bus.requestLifecycle.recover(); assert.equal(drain().filter(m => m.body.includes('advance_request')).length, 0);
await advance(f, 'review'); await f.bus.requestLifecycle.recover(); drain();
await assert.rejects(advance(f, 'early-review'), /request-evidence-required/);
f.call('reviewer', 'review.verdict', { task_ref: f.task_ref, request: review.request, verdict: 'approve', body: 'Reviewed' });
await f.bus.requestLifecycle.recover();
assert.equal(drain().filter(m => m.body.includes('advance_request')).length, 1, 'new verdict wakes PM');
await f.bus.requestLifecycle.recover(); assert.equal(drain().filter(m => m.body.includes('advance_request')).length, 0);
});
test('first actionable lifecycle review request specifies raw verification and verdict JSON', async t => {
const f = await planned(t); await advance(f, 'implementation');
const commit = 'a'.repeat(40); f.push(commit); const review = f.review(commit);
const m = f.call('reviewer', 'message.receive').find(m => m.id === review.message);
assert.match(m.body, /raw JSON/i);
assert.match(m.body, /review_request/);
assert.match(m.body, /verification_record/);
assert.match(m.body, /before.*verdict/i);
});
test('late verdict wakes the same live PM after premature review advance', async t => {
const f = await planned(t); const drain = () => { const ms = f.call('pm', 'message.receive'); for (const m of ms) f.call('pm', 'message.read', { id: m.id }); return ms; };
await advance(f, 'implementation'); const commit = 'a'.repeat(40); f.push(commit); const review = f.review(commit);
await advance(f, 'review'); await f.bus.requestLifecycle.recover(); drain();
await assert.rejects(advance(f, 'early-review-only'), /request-evidence-required/);
f.call('reviewer', 'review.verdict', { task_ref: f.task_ref, request: review.request, verdict: 'approve', body: 'Reviewed' });
await f.bus.requestLifecycle.recover();
assert.equal(drain().filter(m => m.body.includes('advance_request')).length, 1);
const count = f.store.get("SELECT count(*) n FROM messages WHERE from_role='_bus' AND to_role='pm' AND body LIKE '%advance_request%'").n;
await f.bus.close(); const restarted = await f.boot(); await restarted.requestLifecycle.recover();
assert.equal(f.store.get("SELECT count(*) n FROM messages WHERE from_role='_bus' AND to_role='pm' AND body LIKE '%advance_request%'").n, count);
});
test('changed owner mode revokes a previously wakeable transition', async t => {
const f = await planned(t); await advance(f, 'implementation'); await f.bus.requestLifecycle.recover();
const commit = 'a'.repeat(40); f.push(commit); f.review(commit); await f.bus.requestLifecycle.recover();
const old = f.journal.readRequest('demo', f.request);
const changed = await f.call('console', 'request.mode.console', { request: f.request, revision: old.revision, mode_revision: old.mode_revision, mode: 'guided', op: 'change-mode' });
assert.equal(changed.phase, 'discovery');
await assert.rejects(f.call('pm', 'request.advance', { request: f.request, revision: old.revision, op: 'stale-wake' }), /request-revision-conflict|prd-admission-revoked/);
assert.equal(f.journal.readRequest('demo', f.request).snapshot, null);
});
test('review request before PM phase advance already contains lifecycle contract', async t => {
const f = await planned(t); const commit = 'a'.repeat(40); f.push(commit); const review = f.review(commit);
const first = f.call('reviewer', 'message.receive').find(m => m.id === review.message);
assert.match(first.body, /raw JSON/); assert.match(first.body, /verification_record/);
await advance(f, 'implementation'); await advance(f, 'review'); await f.bus.requestLifecycle.recover();
const continuation = f.call('reviewer', 'message.receive').find(m => m.body.includes('review_verdict'));
assert.match(continuation.body, /raw JSON/); assert.match(continuation.body, /verification_record/);
});
test('late reviewer record cannot repair an already issued generic verdict', async t => {
const f = await planned(t); await advance(f, 'implementation');
const commit = 'a'.repeat(40); f.push(commit); const review = f.review(commit); await advance(f, 'review');
const verdict = f.call('reviewer', 'review.verdict', { task_ref: f.task_ref, request: review.request, verdict: 'approve', body: 'Tests passed.' });
const record = await f.call('reviewer', 'record.write', { project: 'timer', path: 'docs/late.md', record: JSON.stringify({ version: 1, task_ref: f.task_ref, review_request: review.request, commit, results: 'Tests passed.' }) });
assert.throws(() => f.call('reviewer', 'review.verdict', { task_ref: f.task_ref, request: review.request, verdict: 'approve', body: JSON.stringify({ verification_record: { path: record.path, commit: record.commit }, results: 'Tests passed.' }) }), /verdict-exists/);
await advance(f, 'delivery'); await f.closeTask(verdict.verdict);
const state = f.journal.readRequest('demo', f.request);
await assert.rejects(f.call('pm', 'request.deliver', { request: f.request, revision: state.revision, op: 'late-record', task_ref: f.task_ref, verdict: verdict.verdict, path: 'timer.html', verification_record: { path: record.path, commit: record.commit } }), /request-verification-refused/);
});
test('non-Stack factory requirement example writes and malformed records remain refused', async t => {
const f = await requestFixture(t);
const example = { recordVersion: 1, id: 'REQ-2', title: 'Timer', text: 'The timer starts.', status: 'draft' };
await assert.rejects(f.call('pm', 'record.write', { project: 'timer', path: 'requirements/REQ-2.json', record: { id: 'REQ-2' } }), /project-record-invalid/);
const written = await f.call('pm', 'record.write', { project: 'timer', path: 'requirements/REQ-2.json', record: example });
assert.equal(written.path, 'requirements/REQ-2.json'); assert.match(written.commit, /^[a-f0-9]{40}$/);
await assert.rejects(f.call('pm', 'record.write', { project: 'timer', path: 'requirements/REQ-3.json', record: { ...example, extra: true } }), /project-record-invalid/);
});
test('a newly claimed PM that consumes a queued notice before recovery still wakes on late evidence', async t => {
const f = await planned(t); await advance(f, 'implementation');
f.bus.broker.endLaunch({ business: 'demo', run: 'pm-run', reason: 'exit', exitCode: 1 });
await f.bus.requestLifecycle.recover();
f.caps.pm = f.bus.broker.bindLaunch({ business: 'demo', role: 'pm', run: 'pm-next-run', harness: 'pi' });
f.call('pm', 'role.claim');
const drain = () => { const ms = f.call('pm', 'message.receive'); for (const m of ms) f.call('pm', 'message.read', { id: m.id }); return ms; };
assert.ok(drain().some(m => m.body.includes('advance_request')));
const commit = 'a'.repeat(40); f.push(commit); f.review(commit); await f.bus.requestLifecycle.recover();
assert.equal(drain().filter(m => m.body.includes('advance_request')).length, 1);
await f.bus.requestLifecycle.recover(); assert.equal(drain().filter(m => m.body.includes('advance_request')).length, 0);
});
test('evidence already recorded while PM is absent does not duplicate its queued notice on claim', async t => {
const f = await planned(t); await advance(f, 'implementation');
f.bus.broker.endLaunch({ business: 'demo', run: 'pm-run', reason: 'exit', exitCode: 1 });
await f.bus.requestLifecycle.recover();
const commit = 'a'.repeat(40); f.push(commit); f.review(commit); await f.bus.requestLifecycle.recover();
const intent = intents(f).find(e => e.result.intent.step === 'advance_request');
const before = messages(f, intent.result.intent.key).filter(m => m.to_role === 'pm').length;
f.caps.pm = f.bus.broker.bindLaunch({ business: 'demo', role: 'pm', run: 'pm-later-run', harness: 'pi' });
f.call('pm', 'role.claim');
const received = f.call('pm', 'message.receive');
for (const m of received) f.call('pm', 'message.read', { id: m.id });
await f.bus.requestLifecycle.recover();
assert.equal(messages(f, intent.result.intent.key).filter(m => m.to_role === 'pm').length, before);
});
@@ -0,0 +1,65 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createRequestLifecycle } from '../src/request-lifecycle.mjs';
function recoveryFixture({ retained, target = 0, signalAt = null }) {
const requests = Array.from({ length: retained }, (_, i) => ({
business: 'demo', request: `r${i}`, revision: 1, source_message: 'source',
phase: i === target ? 'implementation' : 'cancelled', pm: 'pm', project: 'factory',
wait: null, question: null, plan_digest: 'plan',
selection: { bindings: [{ digest: 'plan', plan: { staff: { coder: 'coder', reviewer: 'reviewer', chief: 'chief' } } }] },
spec_commit: null, candidate: null, snapshot: 'snapshot', tasks: ['vikunja:2/1'], evidence: [],
}));
const receipts = [], messages = [], inspected = new Set();
let lifecycle, evidence = false, signalled = false;
const journal = {
listRequests: () => requests.map(({ business, request }) => ({ business, request })),
readRequest(business, request) {
inspected.add(request);
if (!signalled && request === `r${signalAt}`) {
signalled = true; evidence = true;
lifecycle.recover({ limit: 64 });
}
return structuredClone(requests.find(row => row.business === business && row.request === request));
},
effects: (business, request) => receipts.filter(row => row.business === business && row.request === request),
transaction: fn => fn(),
prepareEffect(row) {
const old = receipts.find(r => r.business === row.business && r.request === row.request && r.op === row.op && r.stage === row.stage);
if (old) return old;
receipts.push(row); return row;
},
finishEffect(row) { receipts.push(row); return row; },
};
const services = {
origin() {}, authorize() {}, raiseDecision() {}, readDecision() {}, project() {},
continuationContext: (_, role) => ({ run: `${role}-live`, prerequisite: 'stable' }),
continuationProgress: state => state.request === `r${target}` && evidence
? { phase: 'review', tasks: state.tasks, evidence: ['validated-push', 'validated-review'] } : null,
continuationMessage(state, role, body) {
const id = `m${messages.length}`; messages.push({ id, request: state.request, role, body }); return id;
},
};
lifecycle = createRequestLifecycle({ journal, services });
return { lifecycle, inspected, wakes: () => messages.filter(m => m.request === `r${target}` && m.role === 'pm').length };
}
for (const [retained, target, signalAt, prime] of [[128, 0, 1, false], [257, 64, 65, true]]) {
test(`overlapping evidence revisits its request across bounded recovery batches (${retained} retained rows)`, async t => {
const f = recoveryFixture({ retained, target, signalAt }); t.after(() => f.lifecycle.close());
if (prime) await f.lifecycle.recover({ limit: 64 });
await f.lifecycle.recover({ limit: 64 });
assert.equal(f.wakes(), 2, 'the joined evidence-triggered recovery wakes the live PM without a later timer sweep');
for (let i = 0; i < 6; i++) await f.lifecycle.recover({ limit: 64 });
assert.equal(f.wakes(), 2, 'unchanged evidence remains durably deduplicated');
});
}
test('quiescent recovery keeps its per-call batch bound and advances the cursor', async t => {
const f = recoveryFixture({ retained: 128 }); t.after(() => f.lifecycle.close());
await f.lifecycle.recover({ limit: 64 });
assert.equal(f.inspected.size, 64);
await f.lifecycle.recover({ limit: 64 });
assert.equal(f.inspected.size, 128);
assert.equal(f.wakes(), 1);
});
+8
View File
@@ -236,3 +236,11 @@ test('a refusal the host decided is filed on the task it names, and only a task
[[TASK, 'non-fast-forward'], [null, 'invalid-request'], [null, 'invalid-request']],
);
});
test('unrelated generic review keeps free-text contract and verdict', t => {
const { call, push } = setup(t); push(A);
const review = call('coder', 'review.request', { task_ref: TASK, commit: A, to: 'reviewer' });
const message = call('reviewer', 'message.receive', {}).find(m => m.id === review.message);
assert.doesNotMatch(message.body, /verification_record|raw JSON/);
assert.ok(call('reviewer', 'review.verdict', { task_ref: TASK, request: review.request, verdict: 'approve', body: 'Tests passed.' }).verdict);
});
+4 -4
View File
@@ -102,7 +102,7 @@ export function typedTools({ resolved, arbiter = false, tracker = false, project
to: str("Role instance, its name, or \"human\""),
body: str("Message text"),
class: str("Message class", { enum: MESSAGE_CLASSES }),
in_reply_to: str("Id of the message this answers"),
in_reply_to: str("Id of the message this answers. For assistant → chief → PM intake, each relay must reply to the message received so the original user request remains reachable"),
decision: COMMON.decision,
}, ["to", "body"]));
// Row 140 (#1634, REQ-COS-1): the pm asks the chief of staff, the only launcher, for sessions. The broker
@@ -149,12 +149,12 @@ export function typedTools({ resolved, arbiter = false, tracker = false, project
}
if (resolved.definition === "pm") {
const control = { request: REQUEST, revision: { type: "integer", minimum: 1 }, op: str("Stable operation id; reuse only for the identical retry") };
if (held.has("message.send")) add("deliver_request", "request.deliver", "message.send", "Deliver a reviewed HTML artifact after task_close. Cite the reviewer-authored verification record (a Markdown document containing JSON with version, task_ref, review_request, commit and results); the review verdict body must be JSON containing verification_record {path, commit} and matching results.", obj({ ...control,
if (held.has("message.send")) add("deliver_request", "request.deliver", "message.send", "Deliver a reviewed HTML artifact after task_close. Cite the reviewer-authored verification record (a docs/*.md document containing only raw JSON (no fences or prose) with version, task_ref, review_request, commit and results); the review verdict body must be JSON containing verification_record {path, commit} and matching results.", obj({ ...control,
task_ref: TASK_REF, verdict: str("Latest approving review verdict id"), path: str("Relative path of the committed HTML artifact"),
verification_record: obj({ path: str("Reviewer-written docs/*.md"), commit: str("Exact records commit") }, ["path", "commit"]),
}, ["request", "revision", "op", "task_ref", "verdict", "path", "verification_record"]));
if (held.has("message.send")) add("advance_request", "request.advance", "message.send", "Verify evidence for the next fixed request transition. Never claim a success state; the broker derives it from admitted tasks, pushes, reviews and closure receipts.", obj(control, ["request", "revision", "op"]));
if (held.has("record.write")) add("submit_prd", "prd.submit", "record.write", "Submit exact committed discovery records for PRD approval. The broker reads and binds every blob, author and requirement; submission grants no approval.", obj({ ...control,
if (held.has("record.write")) add("submit_prd", "prd.submit", "record.write", "Submit exact committed discovery records for PRD approval. Requirements are written with write_record at requirements/ID.json as {\"recordVersion\":1,\"id\":\"ID\",\"title\":\"Title\",\"text\":\"Requirement text\",\"status\":\"draft\"}; id must match the filename. The broker reads and binds every blob, author and requirement; submission grants no approval.", obj({ ...control,
prd_version: str("Product PRD version, such as 1.0", { pattern: "^[0-9]+\\.[0-9]+(?:\\.[0-9]+)?$" }),
records_commit: str("Exact records repository commit", { pattern: "^[a-f0-9]{40}([a-f0-9]{24})?$" }),
prd_path: str("docs/prd-VERSION.md"),
@@ -322,7 +322,7 @@ export function typedTools({ resolved, arbiter = false, tracker = false, project
path: str("Named docs Markdown or requirement/decision JSON path", {
pattern: "^(docs/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\\.md|(requirements|decisions)/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\\.json)$",
}),
record: { type: ["string", "object"], description: "Markdown string or a JSON record matching the project's package-owned schema" },
record: { type: ["string", "object"], description: "Markdown string or JSON record. For requirements/REQ-1.json use {\"recordVersion\":1,\"id\":\"REQ-1\",\"title\":\"Title\",\"text\":\"Requirement text\",\"status\":\"draft\"}; exactly these five fields, id matching filename, status draft, accepted or complete. Title and text must be nonempty." },
decision: COMMON.decision,
}, ["project", "path", "record"]));
}
+75 -3
View File
@@ -30,7 +30,7 @@ function bundle(t, role, harness, mutate) {
});
const dir = scratch(t), workspace = join(dir, 'ws');
mkdirSync(workspace);
return buildBundle({ dir: join(dir, 'bundle'), resolved, contract: '# Fixture contract\n',
return buildBundle({ dir: join(dir, 'bundle'), resolved, contract: readFileSync(join(REPO, 'roles', `${roleDefinition(role)}.md`), 'utf8'),
tracker: false, credentials: [], skillsDir: REPO_SKILLS, harness: HARNESS[harness], harnessVersion: 'fixture',
session: { run: 'intake-run', workspace, toolSocket: join(dir, 'tools.sock'), turnMarker: join(dir, 'turn.done') } });
}
@@ -73,7 +73,8 @@ async function setup(t, harness = 'pi', { mute = false } = {}) {
launch: { by: 'chief', instances: ['pm', 'cto', 'coder', 'reviewer'], models: {}, limits: {} },
projects: { factory: { root: join(root, 'factory') } } };
const journal = createRequestStore(store);
const broker = new Broker({ store, businesses: { demo: business }, requestLifecycle: services => createRequestLifecycle({ journal, services: {
const access = { accessVersion: 1, revision: 1, users: [], grants: [] };
const broker = new Broker({ store, businesses: { demo: business }, access: () => access, requestLifecycle: services => createRequestLifecycle({ journal, services: {
...services, listProjects: () => [{ business: 'demo', project: 'factory', name: 'Factory', tracker: { root: 1, project: 2 } }],
preparePlans: (state, args, source) => ['autonomous', 'guided'].map(mode => ({
version: 1, business: 'demo', request: state.request, project: args.project, name: args.name, chat_project: null, mode,
@@ -101,7 +102,7 @@ async function setup(t, harness = 'pi', { mute = false } = {}) {
const socket = join(root, 'tools.sock');
const server = await runner.toolServer({ path: socket, tools: pm.tools, local: {}, client: { call: (verb, args) => call('pm', verb, args) } });
t.after(() => new Promise(resolve => server.close(resolve)));
return { root, store, broker, caps, call, source, pm, socket,
return { root, store, broker, caps, call, source, pm, socket, access, project, thread, business,
tool: (name, args) => callTool(socket, name, args) };
}
@@ -303,3 +304,74 @@ test('intake_question reports a bus unknown outcome without calling twice', asyn
await assert.rejects(callTool(path, 'intake_question', { request: 'r', revision: 1, op: 'q', text: 'Q?' }), e => /outcome-unknown/.test(e.message) && !/refused/.test(e.message));
assert.equal(attempts, 1);
});
for (const harness of ['pi', 'claude-code']) {
test(`${harness}: linked relay carries original request in runner header and PM gets requirement shape`, async t => {
const x = await setup(t, harness);
const relay = x.call('pm', 'message.receive').find(m => m.from_role === 'chief' && m.body.includes(x.source.request));
assert.equal(relay.request, x.source.request);
assert.match(runner.turnRequest(relay), new RegExp(`request ${x.source.request}`));
const record = x.pm.tools.find(t => t.name === 'write_record');
assert.match(JSON.stringify(record), /recordVersion/);
assert.match(JSON.stringify(record), /requirements\/REQ/);
});
}
test('PM typed record guidance exposes the closed requirement shape in a minimal factory', async t => {
const x = await setup(t);
const record = x.pm.tools.find(t => t.name === 'write_record');
assert.match(JSON.stringify(record), /recordVersion/);
assert.match(JSON.stringify(record), /requirements\/REQ/);
});
test('unlinked or unrelated relays cannot carry or authorize an owner request', async t => {
const x = await setup(t);
const thread = x.store.get('SELECT thread FROM message_threads WHERE message=?', x.source.id).thread;
const a = x.call('human', 'thread.send', { thread, body: 'First isolated instruction' });
const missingFirst = x.call('assistant', 'message.send', { to: 'chief', body: `Request ${a.request}` });
const toPm = x.call('chief', 'message.send', { to: 'pm', in_reply_to: missingFirst.id, body: `Request ${a.request}` });
const b = x.call('human', 'thread.send', { thread, body: 'Second isolated instruction' });
x.call('assistant', 'message.send', { to: 'chief', in_reply_to: b.id, body: `Request ${b.request}` });
const missingSecond = x.call('chief', 'message.send', { to: 'pm', body: `Request ${b.request}` });
const unrelated = x.call('human', 'message.send', { to: 'cto', body: 'Different recipient' });
const forged = x.call('chief', 'message.send', { to: 'pm', in_reply_to: unrelated.id, body: `Request ${unrelated.request}` });
const messages = x.call('pm', 'message.receive');
for (const id of [toPm.id, missingSecond.id, forged.id]) assert.equal(messages.find(m => m.id === id).request, null);
for (const source of [a, b, unrelated]) await assert.rejects(x.tool('intake_open', { request: source.request }), /request-origin-refused/);
assert.equal(x.store.get('SELECT count(*) n FROM request_events').n, 0);
assert.throws(() => x.call('assistant', 'message.send', { to: 'pm', in_reply_to: a.id, body: 'Direct relay' }), /message-recipient-refused|message-sender-refused/);
});
test('a different owner thread cannot borrow an owner request by linking its message ID', async t => {
const x = await setup(t);
const owner = x.call('human', 'thread.send', { thread: x.thread, body: 'Owner-only request' });
x.access.grants = [{ id: 'grant-alice', user: 'alice', business: 'demo', projects: [x.project], instances: ['assistant'], level: 'collaborator' }];
x.caps.user = x.broker.bindUser({ business: 'demo', user: 'alice' });
const thread = x.call('user', 'thread.create', { project: x.project, name: 'Other owner' }).id;
x.caps.assistant = x.broker.bindLaunch({ business: 'demo', role: 'assistant', run: 'other-assistant-run', harness: 'pi', thread });
x.call('assistant', 'role.claim');
const relay = x.call('assistant', 'message.send', { to: 'chief', in_reply_to: owner.id, body: `Request ${owner.request}` });
const sent = x.call('chief', 'message.send', { to: 'pm', in_reply_to: relay.id, body: `Request ${owner.request}` });
const message = x.call('pm', 'message.receive').find(m => m.id === sent.id);
assert.equal(message.request, null);
await assert.rejects(x.tool('intake_open', { request: owner.request }), /request-origin-refused/);
});
for (const harness of ['pi', 'claude-code']) {
test(`${harness}: generated role prompts preserve linked relay and raw reviewer instructions`, t => {
for (const role of ['assistant', 'chief', 'reviewer']) {
const prompt = readFileSync(bundle(t, role, harness).files.prompt, 'utf8');
if (role === 'reviewer') assert.match(prompt, /raw JSON verification-document/);
else assert.match(prompt, /in_reply_to/);
}
});
}
test('a relay through a removed role no longer carries or authorizes the original request', async t => {
const x = await setup(t);
const changed = structuredClone(x.business); delete changed.roles.assistant;
x.broker.reloadBusiness('demo', changed);
const received = x.call('pm', 'message.receive').find(m => m.from_role === 'chief' && m.body.includes(x.source.request));
assert.equal(received.request, null);
await assert.rejects(x.tool('intake_open', { request: x.source.request }), /request-origin-refused/);
});