Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
feat(activity): record recipient interrupt receipts [R2,N26,H2,H16]
Corey Olson8cb093a56d3f
diff --git a/docs/formats.md b/docs/formats.mdindex 3ff92a4c..c5aa6728 100644--- a/docs/formats.md+++ b/docs/formats.md@@ -451,6 +451,8 @@ The `event` table is a SQLite schema object governed by `SCHEMA_VERSION`; its ap| `guards` | board | `missing`, `changed`, `stale` || `rigor-notice` | rigor | `cause`, `items`, `occurrences`, `neverAgain`, `engine`, automatic-Rigor `drafts` || `rigor-draft` | rigor | `id`, `target`, `cause`, exact typed `source`, `unproved` (always true), `items`, `occurrences`, `engine` |+| `activity-delivered` | recipient | `interrupts`, `through`, `observedThrough`, `digestThrough` |+| `activity-acted` | recipient | `interrupts` || `shout` | sender | `shout`, `to`, `decision`, `request`, `answers` || `shout_news` | sender | `shout`, `to`, `decision`, `request`, `answers` || `flake-observation` | reporting agent | `engine`, `observation` |@@ -676,3 +678,5 @@ not a native move, parent identity, configuration or authority record. Missing/dreplays activity. Reads freeze an event high-water mark before observing Git; subsequent eventsand messages remain pending. News has a separate cursor so an ordinary poll cannot consume afuture session-start digest.++The activity-delivery engine, numbered at landing, adds recipient-owned `recordActivityDelivery` and `actOnActivity` moves. Interrupt ids bind a native event (`event:<id>`) or an exact claim lease (`claim:<item>:<lease-until>`). A delivery event lists only interrupts actually included in that recipient's response; an acted event records a separate explicit acknowledgement. An inbox cursor or reading a response never means acted-on. Both moves use the joined recipient as their authenticated actor, preserve earlier event history, and refuse on an older replay engine before changing its prefix. Delivery state in indexed `board_meta` keys is part of the native board and its exports, not a checkout-only cursor. `through` is the safely covered interrupt prefix, `observedThrough` is the read snapshot's high-water mark, and optional `digestThrough` is the separately delivered digest prefix; an elided interrupt must remain available after a later small interrupt is delivered.diff --git a/docs/formats.test.js b/docs/formats.test.jsindex 0f01bac5..36c83e2f 100644--- a/docs/formats.test.js+++ b/docs/formats.test.js@@ -24,6 +24,8 @@ import { readEngineLeaves } from '../src/engine-numbers.js';import { applyEngineMove, prepareEngineMove } from '../src/engine.js';import {ACCEPT_REASON,+ actOnActivity,+ recordActivityDelivery,answerDecision,addItem,appendFact,@@ -315,6 +317,12 @@ function recordEventContract() {answerDecision(board, personQuestion, { agentId: coordinator, text: 'approved', lanes: ['docs', 'tests'], asPerson: true });const request = shout(board, { from: PERSON, to: coordinator, text: 'sample request', lanes: ['docs', 'tests'], request: true });answerDecision(board, request, { agentId: coordinator, text: 'done', lanes: ['docs', 'tests'] });+ const deliveryQuestion = shout(board, { from: builder, to: coordinator, text: 'sample delivery question', decision: true, lanes: ['docs', 'tests'] });+ answerDecision(board, deliveryQuestion, { agentId: coordinator, text: 'sample delivery answer', lanes: ['docs', 'tests'] });+ const deliveryEvent = events(board).findLast(event => event.event_kind === 'answer');+ recordActivityDelivery(board, { agentId: builder, through: deliveryEvent.event_id, digestThrough: deliveryEvent.event_id,+ interrupts: [{ id: `event:${deliveryEvent.event_id}`, eventId: deliveryEvent.event_id, reason: 'answered' }] });+ actOnActivity(board, { agentId: builder, ids: [`event:${deliveryEvent.event_id}`] });const decisions = recordRowDecisions(board, { agentId: PERSON, channel: 'terminal', decisions: [{ kind: 'spec', file: 'SPEC.md', id: 'A1', source: '- A1 [draft] Exact row.', replacement: '- A1 [approved] Exact row.', text: 'Exact row.', decision: 'approve', reason: '' }] });applyRowDecisions(board, { agentId: coordinator, events: decisions.map((record) => record.event) });draftSpecRow(board, { agentId: builder, row: { id: 'A2', text: 'A lane drafted row.', gate: 'review', tier: 'must', section: 'A · Fixture' } });@@ -727,6 +735,8 @@ test('[A5] schema, versions, event kinds and event detail fields match live beha'rigor-notice': 'rigor','rigor-draft': 'rigor',shout: 'sender',+ 'activity-delivered': 'recipient',+ 'activity-acted': 'recipient',shout_news: 'sender',pass: 'coordinator',answer: 'answerer',diff --git a/src/activity-delivery-engine.js b/src/activity-delivery-engine.jsnew file mode 100644index 00000000..b86e5c08--- /dev/null+++ b/src/activity-delivery-engine.js@@ -0,0 +1,3 @@+/** Canonical interrupt receipts require one shared interpretation on every replica [H16,N26]. */+import { unassignedEngine } from './engine-next.js';+export const ACTIVITY_DELIVERY_ENGINE = unassignedEngine();diff --git a/src/activity-delivery-read.js b/src/activity-delivery-read.jsnew file mode 100644index 00000000..ff6f6d0c--- /dev/null+++ b/src/activity-delivery-read.js@@ -0,0 +1,60 @@+/** Read a recipient's interrupt obligations without consuming a message or writing an acknowledgement [R2,N26,H16]. */+import { agentActivity } from './board-query.js';+import { activityEventDetail } from './activity-feed.js';+import { classifyActivityDelivery } from './activity-delivery.js';+import { activityDeliveryState, rejectionRecipient } from './activity-delivery-store.js';++/** Retain exact native references when supplementing the legacy projection with an original builder's rejection. */+function rejectionEntry(event, agentId) {+ return { id: `event:${event.event_id}`, eventId: event.event_id, at: event.event_at, by: event.event_by,+ kind: 'reject', item: event.item_id, recipient: agentId, text: `#${event.item_id} was rejected` };+}++/** Read old and new complete state in one SQLite snapshot, including immutable answer and rejection recipients. */+export function readActivityDelivery(board, agentId, options = {}) {+ board.db.exec('SAVEPOINT activity_delivery_read');+ try {+ const state = activityDeliveryState(board, agentId);+ const activity = agentActivity(board, agentId, { ...options,+ after: Math.min(state.through, state.digestThrough), newsAfter: state.digestThrough, sessionStart: true });+ const entries = new Map(activity.entries.map(entry => [entry.eventId, entry]));+ const rejected = board.db.prepare(`SELECT * FROM event WHERE event_kind='reject' AND event_id>? AND event_id<=? ORDER BY event_id`)+ .all(state.through, activity.cursor);+ for (const event of rejected) {+ const detail = activityEventDetail(event);+ if (detail && rejectionRecipient(board, event, detail) === agentId) entries.set(event.event_id, rejectionEntry(event, agentId));+ }+ const messages = new Map();+ for (const entry of entries.values()) if (entry.shout) {+ const message = board.db.prepare('SELECT * FROM shout WHERE shout_id=?').get(entry.shout);+ if (!message) continue;+ messages.set(message.shout_id, message);+ if (message.shout_answers !== null) {+ const question = board.db.prepare('SELECT * FROM shout WHERE shout_id=?').get(message.shout_answers);+ if (question) messages.set(question.shout_id, question);+ }+ }+ const all = classifyActivityDelivery({ agentId,+ items: board.db.prepare('SELECT * FROM item ORDER BY item_id').all(),+ activity: { ...activity, entries: [...entries.values()] }, shouts: [...messages.values()],+ at: board.clock.now().toISOString() });+ const pending = new Map(state.pending.map(interrupt => [interrupt.id, interrupt]));+ const fresh = [];+ for (const interrupt of all.interrupts) {+ if (pending.has(interrupt.id)) continue;+ const done = board.db.prepare('SELECT 1 FROM board_meta WHERE meta_key=?')+ .get(`activity:${agentId}:acted:${interrupt.id}`);+ if (done) continue;+ pending.set(interrupt.id, interrupt);+ fresh.push(interrupt);+ }+ const breakTime = options.sessionStart === true || options.afterSubmit === true;+ return { ...all, interrupts: [...pending.values()],+ digests: breakTime ? all.digests : [],+ // The ordered writer consumes this observation separately, after choosing what was actually rendered.+ observation: { fresh, through: activity.cursor, observedThrough: activity.cursor, ...(breakTime ? { digestThrough: activity.cursor } : {}) },+ shoutCursor: activity.shoutCursor, newsShouts: activity.newsShouts };+ } finally {+ board.db.exec('RELEASE activity_delivery_read');+ }+}diff --git a/src/activity-delivery-store.js b/src/activity-delivery-store.jsnew file mode 100644index 00000000..ef8a77e4--- /dev/null+++ b/src/activity-delivery-store.js@@ -0,0 +1,138 @@+/** Canonical interrupt acknowledgements are recipient-owned ordered records, never local cursors [R2,N26,H16]. */+import { Refused } from './refused.js';++/** Address one recipient's indexed derived state without sharing another seat's acknowledgement. */+function prefix(agentId, state) { return `activity:${agentId}:${state}:`; }++/** Read one derived record; malformed native state is not a successful acknowledgement. */+function value(board, key) {+ const row = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(key);+ return row ? JSON.parse(row.meta_value) : null;+}++/** Preserve the immutable source log while updating its per-recipient delivery projection. */+function save(board, key, data) {+ board.db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES (?,?) ON CONFLICT(meta_key) DO UPDATE SET meta_value=excluded.meta_value')+ .run(key, JSON.stringify(data));+}++/** Every receipt belongs to a real joined seat; transport authentication additionally binds the move actor. */+function recipient(board, agentId) {+ if (typeof agentId !== 'string' || !board.db.prepare('SELECT 1 FROM agent WHERE agent_id=?').get(agentId)) {+ throw new Refused('NOT_JOINED', 'join your own lane before recording activity delivery');+ }+}++/** Enumerate only pending records through the primary-key range, leaving acted history out of the hot read. */+export function activityDeliveryState(board, agentId) {+ recipient(board, agentId);+ const start = prefix(agentId, 'pending');+ const pending = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key>=? AND meta_key<? ORDER BY meta_key')+ .all(start, `${start}\uffff`).map(row => JSON.parse(row.meta_value));+ return { ...(value(board, prefix(agentId, 'cursor')) ?? { through: 0, digestThrough: 0 }), pending };+}++/** Resolve a rejection's original recipient from immutable receipts, not the item's later builder. */+export function rejectionRecipient(board, event, detail) {+ if (detail.reopenFirstRefusal?.builder) return detail.reopenFirstRefusal.builder;+ if (typeof detail.commit !== 'string') return null;+ return board.db.prepare(`SELECT event_by FROM event WHERE item_id=? AND event_kind='submit' AND event_id<?+ AND json_extract(CASE WHEN json_valid(event_detail) THEN event_detail ELSE '{}' END,'$.commit')=?+ ORDER BY event_id DESC LIMIT 1`).get(event.item_id, event.event_id, detail.commit)?.event_by ?? null;+}++/** Validate exact source identities before recording any part of a delivery batch. */+function canonicalInterrupt(board, agentId, input, observedThrough) {+ if (!input || typeof input.id !== 'string' || input.id.length > 256) {+ throw new Refused('BAD_ACTIVITY_RECEIPT', 'read inbox again to obtain an exact interrupt identity');+ }+ if (input.reason === 'claim-lapsing') {+ const item = board.db.prepare('SELECT * FROM item WHERE item_id=?').get(input.item);+ if (!item || item.item_status !== 'claimed' || item.item_owner !== agentId || item.item_lease_until !== input.leaseUntil+ || input.id !== `claim:${item.item_id}:${item.item_lease_until}`) {+ throw new Refused('STALE_ACTIVITY_RECEIPT', 'the claim changed; read inbox again before recording its delivery');+ }+ return { id: input.id, reason: input.reason, kind: 'claim', item: item.item_id,+ leaseUntil: item.item_lease_until, text: `#${item.item_id} claim is lapsing; renew or release it` };+ }+ if (!Number.isSafeInteger(input.eventId) || input.eventId < 1 || input.eventId > observedThrough || input.id !== `event:${input.eventId}`) {+ throw new Refused('BAD_ACTIVITY_RECEIPT', 'an interrupt must name an observed native event; read inbox again');+ }+ const event = board.db.prepare('SELECT * FROM event WHERE event_id=?').get(input.eventId);+ const detail = event && JSON.parse(event.event_detail);+ let text;+ if (input.reason === 'rejected' && event?.event_kind === 'reject' && rejectionRecipient(board, event, detail) === agentId) {+ text = `#${event.item_id} was rejected; read its verdict and repair or release it`;+ } else if (input.reason === 'answered' && event?.event_kind === 'answer') {+ const answer = board.db.prepare('SELECT * FROM shout WHERE shout_id=?').get(detail.shout);+ const question = answer && board.db.prepare('SELECT * FROM shout WHERE shout_id=?').get(answer.shout_answers);+ if (question?.shout_from === agentId && question.shout_decision) text = `question #${question.shout_id} was answered; read answer #${answer.shout_id}`;+ } else if (input.reason === 'files-changed' && event?.event_kind === 'main-moved') {+ if (!Array.isArray(input.files) || !input.files.length || input.files.some(path => typeof path !== 'string' || !path || path.length > 4096)) {+ throw new Refused('BAD_ACTIVITY_RECEIPT', 'a file interrupt needs its observed Git paths; read inbox again');+ }+ // Paths describe the recipient's Git observation. They grant no board or file authority.+ text = `main changed ${new Set(input.files).size} files you are editing; inspect the recorded main change`;+ }+ if (!text) throw new Refused('BAD_ACTIVITY_RECEIPT', 'that event is not this seat\'s interrupt; read your own inbox');+ return { id: input.id, eventId: event.event_id, at: event.event_at, by: event.event_by,+ reason: input.reason, kind: event.event_kind, ...(event.item_id === null ? {} : { item: event.item_id }),+ ...(input.reason === 'files-changed' ? { files: [...new Set(input.files)].toSorted() } : {}), text };+}++/** Record only actually included interrupts, once; withheld and later events stay available. */+export function recordActivityDelivery(board, { agentId, interrupts = [], through, observedThrough = through, digestThrough }, { atomic, logEvent }) {+ return atomic(board, () => {+ recipient(board, agentId);+ const high = board.db.prepare('SELECT COALESCE(MAX(event_id),0) AS id FROM event').get().id;+ if (!Number.isSafeInteger(through) || through < 0 || through > high+ || !Number.isSafeInteger(observedThrough) || observedThrough < through || observedThrough > high+ || !Array.isArray(interrupts) || interrupts.length > 1000+ || digestThrough !== undefined && (!Number.isSafeInteger(digestThrough) || digestThrough < 0 || digestThrough > observedThrough)) {+ throw new Refused('BAD_ACTIVITY_RECEIPT', 'delivery must name an observed native prefix; read inbox again');+ }+ const canonical = interrupts.map(input => canonicalInterrupt(board, agentId, input, observedThrough));+ const added = [];+ for (const interrupt of canonical) {+ const pendingKey = prefix(agentId, 'pending') + interrupt.id;+ if (value(board, pendingKey) || value(board, prefix(agentId, 'acted') + interrupt.id)) continue;+ save(board, pendingKey, interrupt);+ added.push(interrupt.id);+ }+ const key = prefix(agentId, 'cursor');+ const before = value(board, key) ?? { through: 0, digestThrough: 0 };+ const next = { through: Math.max(before.through, through), digestThrough: Math.max(before.digestThrough, digestThrough ?? 0) };+ if (added.length || next.digestThrough > before.digestThrough) {+ save(board, key, next);+ logEvent(board, agentId, 'activity-delivered', null, { interrupts: added, through, observedThrough, ...(digestThrough === undefined ? {} : { digestThrough }) });+ }+ return activityDeliveryState(board, agentId);+ });+}++/** Acknowledgement is explicit and recipient-owned; a read or local cursor can never create it. */+export function actOnActivity(board, { agentId, ids }, { atomic, logEvent }) {+ return atomic(board, () => {+ recipient(board, agentId);+ if (!Array.isArray(ids) || !ids.length || ids.length > 1000 || ids.some(id => typeof id !== 'string' || id.length > 256)) {+ throw new Refused('BAD_ACTIVITY_RECEIPT', 'name the interrupt ids returned by your inbox');+ }+ const unique = [...new Set(ids)];+ const records = unique.map(id => {+ const pending = value(board, prefix(agentId, 'pending') + id);+ if (!pending && !value(board, prefix(agentId, 'acted') + id)) {+ throw new Refused('ACTIVITY_NOT_DELIVERED', 'that interrupt was not delivered to this seat; read your own inbox first');+ }+ return pending;+ });+ const acted = [];+ for (const [index, record] of records.entries()) if (record) {+ const id = unique[index];+ save(board, prefix(agentId, 'acted') + id, record);+ board.db.prepare('DELETE FROM board_meta WHERE meta_key=?').run(prefix(agentId, 'pending') + id);+ acted.push(id);+ }+ if (acted.length) logEvent(board, agentId, 'activity-acted', null, { interrupts: acted });+ return activityDeliveryState(board, agentId);+ });+}diff --git a/src/activity-delivery.js b/src/activity-delivery.jsnew file mode 100644index 00000000..b45d9137--- /dev/null+++ b/src/activity-delivery.js@@ -0,0 +1,40 @@+/** Separate actionable activity from count-only summaries without acknowledging either [R2,N26]. */++/** A lapsing claim is an episode tied to its exact lease, not to a checkout's cursor. */+export const CLAIM_INTERRUPT_WINDOW_MS = 5 * 60 * 1000;++/** Classify a tailored read projection; canonical receipt handling remains a separate ordered write. */+export function classifyActivityDelivery({ agentId, items, activity, shouts, at }) {+ const byShout = new Map(shouts.map(shout => [shout.shout_id, shout]));+ const interrupts = [], direct = [], counts = new Map();+ /** Keep only a compact count for digest activity; item evidence remains on its native thread. */+ const count = kind => counts.set(kind, (counts.get(kind) ?? 0) + 1);+ for (const entry of activity.entries) {+ let reason;+ if (entry.kind === 'reject' && entry.recipient === agentId) reason = 'rejected';+ else if (entry.kind === 'main-moved' && entry.files?.length) reason = 'files-changed';+ else if (entry.kind === 'answer') {+ const reply = byShout.get(entry.shout);+ const question = byShout.get(reply?.shout_answers);+ if (question?.shout_from === agentId && question.shout_decision) reason = 'answered';+ }+ if (reason) interrupts.push({ ...entry, id: `event:${entry.eventId}`, reason });+ else if (entry.shout) direct.push(entry); // Governing instructions and active coordination remain direct.+ else count(entry.kind);+ }+ const now = Date.parse(at);+ for (const item of items) {+ if (item.item_status !== 'claimed' || item.item_owner !== agentId) continue;+ const until = Date.parse(item.item_lease_until);+ if (!Number.isFinite(until) || until - now > CLAIM_INTERRUPT_WINDOW_MS) continue;+ interrupts.push({ id: `claim:${item.item_id}:${item.item_lease_until}`, reason: 'claim-lapsing',+ kind: 'claim', item: item.item_id, leaseUntil: item.item_lease_until,+ text: `#${item.item_id} claim ${until <= now ? 'has lapsed' : 'is lapsing'}; renew or release it` });+ }+ const digests = [...counts].toSorted(([first], [second]) => first.localeCompare(second)).map(([kind, count]) => ({+ kind, count, text: `${count} ${kind} ${count === 1 ? 'activity' : 'activities'}; details remain on the board`,+ }));+ for (const digest of activity.digests) digests.push({ ...digest,+ text: `${digest.count} ${digest.kind} ${digest.count === 1 ? 'update' : 'updates'}; details remain on the board` });+ return { interrupts, entries: direct, digests, cursor: activity.cursor };+}diff --git a/src/board.js b/src/board.jsindex 38819a37..fa83cacb 100644--- a/src/board.js+++ b/src/board.js@@ -1,3 +1,4 @@+import * as activityDeliveryStore from './activity-delivery-store.js';import { requireFactKind } from './item-notes.js';import { activityNewsFlag } from './activity-news.js';import { migrateEventLogVersion } from './board-event-log-migrate.js';@@ -2343,3 +2344,18 @@ export function approveOutside(board, id, options) { return applyOutsideApproval/** Tailored inbox activity is the same canonical read projection as other board queries. */export { agentActivity } from './board-query.js';++/** Read recipient delivery state without mutating any cursor or receipt. */+export function activityDeliveryState(board, agentId) {+ return activityDeliveryStore.activityDeliveryState(board, agentId);+}++/** Record the exact interrupts included in an authenticated recipient response. */+export function recordActivityDelivery(board, options) {+ return activityDeliveryStore.recordActivityDelivery(board, options, { atomic, logEvent });+}++/** Record an explicit recipient acknowledgement separately from delivery. */+export function actOnActivity(board, options) {+ return activityDeliveryStore.actOnActivity(board, options, { atomic, logEvent });+}diff --git a/src/moves/actOnActivity.js b/src/moves/actOnActivity.jsnew file mode 100644index 00000000..d27089f2--- /dev/null+++ b/src/moves/actOnActivity.js@@ -0,0 +1,13 @@+/** Recipient-owned interrupt receipts use the existing authenticated ordered move protocol [H2,H16,N26]. */+import { ACTIVITY_DELIVERY_ENGINE } from '../activity-delivery-engine.js';+/** Never let an older replica silently omit a delivery or acknowledgement. */+function minimumEngine() { return ACTIVITY_DELIVERY_ENGINE; }+/** Use the actual recipient argument, never a transport-selected alias. */+function actor(move) { return move.args[0]?.agentId ?? null; }+export default Object.freeze({ operation: 'actOnActivity', order: 1000, engine: ACTIVITY_DELIVERY_ENGINE,+ itemIdFirstArgument: false, minimumEngine, actor,+ nextSteps: Object.freeze({+ NOT_JOINED: 'join a lane from this worktree: pullboard join <lane> --model "<model name>" (see: pullboard lanes)',+ BAD_ACTIVITY_RECEIPT: 'read your own inbox again and use its exact interrupt ids',+ ACTIVITY_NOT_DELIVERED: 'read your own inbox before marking its interrupt acted on',+ }) });diff --git a/src/moves/recordActivityDelivery.js b/src/moves/recordActivityDelivery.jsnew file mode 100644index 00000000..0443d5b4--- /dev/null+++ b/src/moves/recordActivityDelivery.js@@ -0,0 +1,13 @@+/** Recipient-owned interrupt receipts use the existing authenticated ordered move protocol [H2,H16,N26]. */+import { ACTIVITY_DELIVERY_ENGINE } from '../activity-delivery-engine.js';+/** Never let an older replica silently omit a delivery or acknowledgement. */+function minimumEngine() { return ACTIVITY_DELIVERY_ENGINE; }+/** Use the actual recipient argument, never a transport-selected alias. */+function actor(move) { return move.args[0]?.agentId ?? null; }+export default Object.freeze({ operation: 'recordActivityDelivery', order: 1000, engine: ACTIVITY_DELIVERY_ENGINE,+ itemIdFirstArgument: false, minimumEngine, actor,+ nextSteps: Object.freeze({+ NOT_JOINED: 'join a lane from this worktree: pullboard join <lane> --model "<model name>" (see: pullboard lanes)',+ BAD_ACTIVITY_RECEIPT: 'read your own inbox again and use its exact interrupt ids',+ STALE_ACTIVITY_RECEIPT: 'read inbox again; the claim changed before delivery was recorded',+ }) });diff --git a/test/activity-feed.test.js b/test/activity-feed.test.jsindex 5a902b27..7081d912 100644--- a/test/activity-feed.test.js+++ b/test/activity-feed.test.js@@ -13,6 +13,8 @@ import { ACTIVITY_NEWS_ENGINE } from '../src/activity-news-engine.js';import { ITEM_SHOUT_ENGINE } from '../src/item-shout-engine.js';import { LANDING_LEASE_ENGINE } from '../src/landing-lease-engine.js';import shoutMove from '../src/moves/shout.js';+import { ACTIVITY_DELIVERY_ENGINE } from '../src/activity-delivery-engine.js';+import { relaySenderProblem } from '../src/relay-sender.js';import { activityMainFiles, activityWorkingFiles, readActivityCursor, saveActivityCursor } from '../src/activity-inbox.js';const e2e = createE2eHelpers();@@ -408,3 +410,47 @@ test('interrupts arrive at once and the digest arrives as a short summary at a bassert.ok(delivered.length, 'delivery is recorded on the canonical board, not just a checkout cursor');assert.ok(delivered.every(event => event.event_by === 'web-1'), 'the recipient owns its delivery receipts');});+++test('interrupt receipts replay once and only their recipient can acknowledge delivered work [N26,H2,H16]', t => {+ const boards = ['origin', 'left', 'right'].map(() => store.openBoard(':memory:'));+ t.after(() => { for (const board of boards) store.closeBoard(board); });+ const [source, left, right] = boards;+ store.register(source, { lane: 'coordinator', path: '/interrupt-replay' });+ store.register(source, { lane: 'web', path: '/interrupt-replay/web-1' });+ store.register(source, { lane: 'web', path: '/interrupt-replay/web-2' });+ const question = store.shout(source, { from: 'web-1', to: 'coordinator', text: 'Choose a private path', decision: true, lanes: ['web'] });+ store.answerDecision(source, question, { agentId: 'coordinator', text: 'Use the reviewed path', lanes: ['web'] });+ const event = store.events(source).findLast(row => row.event_kind === 'answer');+ const initial = exportBoard(source);+ for (const board of [left, right]) importBoard(board, initial);+ const interrupt = { id: `event:${event.event_id}`, eventId: event.event_id, reason: 'answered', text: 'An answer is waiting' };+ const payload = { agentId: 'web-1', through: event.event_id, interrupts: [interrupt] };+ const delivery = prepareEngineMove(source, 'recordActivityDelivery', [payload]);+ const at = new Date().toISOString();+ assert.equal(relaySenderProblem(delivery, { kind: 'agent', agent: 'web-2' }, 'move')?.code, 'RELAY_ACTOR');+ const untouched = exportBoard(left);+ assert.throws(() => applyEngineMove(left, { ...delivery, engine: ACTIVITY_DELIVERY_ENGINE - 1 }, { sequence: 1, at }),+ error => error.code === 'RELAY_MOVE');+ assert.deepEqual(exportBoard(left), untouched, 'an older engine changes neither native history nor the replay prefix');+ const outcomes = boards.map(board => applyEngineMove(board, delivery, { sequence: 1, at }));+ assert.equal(outcomes[0].error, undefined);+ assert.deepEqual(outcomes[1], outcomes[2]);+ assert.equal(store.activityDeliveryState(left, 'web-1').pending.length, 1);+ assert.deepEqual(applyEngineMove(left, delivery, { sequence: 1, at }), outcomes[1]);+ assert.equal(store.events(left).filter(row => row.event_kind === 'activity-delivered').length, 1);+ const beforeBad = exportBoard(left);+ assert.throws(() => store.actOnActivity(left, { agentId: 'web-2', ids: [interrupt.id] }), error => error.code === 'ACTIVITY_NOT_DELIVERED');+ assert.throws(() => store.actOnActivity(left, { agentId: 'web-1', ids: [interrupt.id, 'event:999999'] }), error => error.code === 'ACTIVITY_NOT_DELIVERED');+ assert.deepEqual(exportBoard(left), beforeBad, 'a forged or partly invalid acknowledgement is atomic');+ const ack = prepareEngineMove(source, 'actOnActivity', [{ agentId: 'web-1', ids: [interrupt.id] }]);+ const acknowledged = boards.map(board => applyEngineMove(board, ack, { sequence: 2, at }));+ assert.deepEqual(acknowledged[1], acknowledged[2]);+ assert.equal(store.activityDeliveryState(left, 'web-1').pending.length, 0);+ assert.equal(store.events(left).filter(row => row.event_kind === 'activity-acted').length, 1);+ assert.deepEqual(exportBoard(left), exportBoard(right));+ const beforeRetry = exportBoard(left);+ store.recordActivityDelivery(left, payload);+ store.actOnActivity(left, { agentId: 'web-1', ids: [interrupt.id] });+ assert.deepEqual(exportBoard(left), beforeRetry, 'a new local retry cannot redeliver or re-acknowledge the same source event');+});diff --git a/test/relay-credential.test.js b/test/relay-credential.test.jsindex 762a5715..e4b5957d 100644--- a/test/relay-credential.test.js+++ b/test/relay-credential.test.js@@ -31,6 +31,8 @@ test('every current operation selects its native actor credential without a secoif (operation === 'setLineSetting') args = [{ agentId: actor, key: 'reviewsFirst', value: true, reason: 'credential fixture', window: { windowMinutes: 60, activeReviewers: 1 } }];if (operation === 'setBarReady') args = [{ agentId: actor, enabled: false }];if (operation === 'recordHealthFindings') args = [{ agentId: actor, observedRevision: 0, findings: [] }];+ if (operation === 'recordActivityDelivery') args = [{ agentId: actor, through: 0, interrupts: [] }];+ if (operation === 'actOnActivity') args = [{ agentId: actor, ids: ['event:1'] }];if (operation === 'recordSpecApprovalBaseline') args = [{ agentId: actor, baseline: { version: 1, file: 'SPEC.md', anchor: null, rows: [] } }];if (operation === 'recordFlakeObservation') args = [{ agentId: actor, lane: box.lane, observation: syntheticFlakeObservation('credential-fixture') }];if (operation === 'recordGateRun') args = [{ agentId: actor, lane: box.lane, receipt: { version: 1, id: '00000000-0000-4000-8000-00000000c0de', kind: 'gate', tree: 'b'.repeat(40), head: 'a'.repeat(40),@@ -74,6 +76,8 @@ test('every current operation selects its native actor credential without a seco{ operation: 'takeHandoff', args: [{ item: 999999 }], kind: 'agent', sent: false, expected: 'RELAY_ACTOR' },{ operation: 'recordPublishFinding', args: [{ item: 999999 }], kind: 'agent', sent: false, expected: 'RELAY_ACTOR' },{ operation: 'recordHealthFindings', args: [{ observedRevision: 0, findings: [] }], kind: 'agent', sent: false, expected: 'RELAY_ACTOR' },+ { operation: 'recordActivityDelivery', args: [{ through: 0, interrupts: [] }], kind: 'agent', sent: false, expected: 'RELAY_ACTOR' },+ { operation: 'actOnActivity', args: [{ ids: ['event:1'] }], kind: 'agent', sent: false, expected: 'RELAY_ACTOR' },{ operation: 'recordSpecApprovalBaseline', args: [{ baseline: { version: 1, file: 'SPEC.md', anchor: null, rows: [] } }], kind: 'agent', sent: false, expected: 'RELAY_ACTOR' },{ operation: 'recordFlakeObservation', args: [{ lane: box.lane, observation: syntheticFlakeObservation('missing-actor') }], kind: 'agent', sent: false, expected: 'RELAY_ACTOR' },{ operation: 'recordGateRun', args: [{ lane: box.lane, receipt: {} }], kind: 'agent', sent: false, expected: 'GATE_RUN_EVIDENCE' },