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
fix(relay): every move kind says where it names an item [B26,H16]
Corey Olson6ace41f471e3
diff --git a/src/next-steps.js b/src/next-steps.jsindex 6e114ff4..dca2c6b7 100644--- a/src/next-steps.js+++ b/src/next-steps.js@@ -458,6 +458,7 @@ export const NEXT_STEPS = Object.freeze({RELAY_BOARD_DELETED: 'keep working locally, or run pullboard relay on to link the board again',RELAY_BUSY: 'run the command again after the other worktree finishes sending',RELAY_OUTBOX: 'keep the relay-outbox.sealed file and the board as they are, then ask for help before relinking',+ RELAY_OUTBOX_UNBOUND: 'run the command again once the relay answers; pullboard status shows when the outbox has gone up',RELAY_OUTBOX_PENDING: 'run pullboard status once the relay answers; it sends the queued moves in order first',RELAY_CURSOR: 'fetch a consistent snapshot: pullboard relay',RELAY_DIVERGED: 'run pullboard relay off, then pullboard relay on to link again from this machine',diff --git a/src/relay-outbox.js b/src/relay-outbox.jsindex 9aec585a..5228ef70 100644--- a/src/relay-outbox.js+++ b/src/relay-outbox.js@@ -147,28 +147,96 @@ export function refusalLine(kept) {return `[RELAY_OUTBOX_REFUSED] the queued move ${kept.move} (made ${kept.queuedAt}) was refused when it replayed: [${kept.code}] ${kept.message}${first}`;}-/** Moves whose first argument is an item number; a decision's answer names a shout instead. */-const ITEM_MOVES = new Set(['claim', 'release', 'submit', 'verify', 'reopen', 'refreeze', 'merged', 'withdraw', 'editItem', 'holdItem', 'releaseItemHold', 'escalate', 'appendFact']);+/** The ordered operations whose first argument is an item number; a decision's answer names a shout instead. */+const FIRST_ITEM = ['editItem', 'completeCheckBaseline', 'escalate', 'recordAttempt', 'claim', 'release', 'submit', 'reserveReview', 'verify',+ 'merged', 'withdraw', 'refreeze', 'reopen', 'holdItem', 'releaseItemHold', 'appendFact', 'acceptCheck'];-/** Where a move names an item: its first argument for item moves, and an add's or edit's parent and after list. */-function itemSlots(move) {- const slots = ITEM_MOVES.has(move.operation) && Number.isSafeInteger(move.args[0]) ? [[0]] : [];- const at = move.operation === 'addItem' ? 0 : move.operation === 'editItem' ? 1 : null;- const options = at === null ? null : move.args[at];- if (options && typeof options === 'object') {- if (Number.isSafeInteger(options.parentId)) slots.push([at, 'parentId']);- if (Array.isArray(options.after)) options.after.forEach((id, index) => { if (Number.isSafeInteger(id)) slots.push([at, 'after', index]); });+/**+ * Where each ordered operation names an item, as paths into its arguments: `*` is every element of a list. Every+ * engine operation is listed, most with no item field, so a new operation must say where its items sit+ * (test/relay-outbox.test.js walks them all) (#922).+ */+export const ITEM_SLOTS = Object.freeze({+ register: [], ensureCoordinator: [], shout: [], passDecision: [], holdLane: [], releaseLane: [],+ moveMilestone: [], editMilestone: [], removeMilestone: [], shipMilestone: [],+ recordRowDecisions: [], applyRowDecisions: [], draftSpecRow: [],+ recordLandingBatch: [], recordLandingWaiver: [], recordLandingFlake: [], finishLandingBatch: [],+ recordHealthFindings: [], decideSentinel: [], beginSentinelRun: [], finishSentinelRun: [],+ recordFlakeObservation: [], recordGateRun: [], declareJob: [], recordJobRun: [],+ ...Object.fromEntries(FIRST_ITEM.map((operation) => [operation, [[0]]])),+ addItem: [[0, 'parentId'], [0, 'after', '*']],+ editItem: [[0], [1, 'after', '*']],+ verify: [[0], [1, 'implies', '*']],+ appendFact: [[0], [1, 'implies', '*']],+ answerDecision: [[1, 'implies', '*']],+ reserveNextReview: [[0, 'skipIds', '*']],+ addMilestone: [[0, 'items', '*']],+ editMilestoneItems: [[1, 'add', '*'], [1, 'remove', '*']],+ orderMilestoneItems: [[1, 'items', '*']],+ proposeSentinel: [[0, 'evidence', 'items', '*', 'id']],+});++/** An item number as a move holds it: a whole number, or the CLI's "12" or "#12". */+function itemNumber(value) {+ if (Number.isSafeInteger(value)) return value;+ const match = typeof value === 'string' ? /^#?(\d{1,15})$/u.exec(value.trim()) : null;+ return match ? Number(match[1]) : null;+}++/** Write a number back in the form the move held it, so a string stays a string. */+function sameForm(old, value) {+ return typeof old === 'string' ? `${old.trim().startsWith('#') ? '#' : ''}${value}` : value;+}++/** Every concrete path in a move's arguments that one declared slot pattern reaches. */+function expand(args, pattern) {+ let paths = [[]];+ for (const key of pattern) {+ paths = paths.flatMap((path) => {+ const at = path.reduce((value, step) => value?.[step], args);+ if (key !== '*') return at !== null && typeof at === 'object' && Object.hasOwn(at, key) ? [[...path, key]] : [];+ return Array.isArray(at) ? at.map((_, index) => [...path, index]) : [];+ });}- return slots;+ return paths;}-/** Read or write the item number at one slot of a move's arguments. */+/** Where a move names an item, as concrete paths into its arguments. */+function itemSlots(move) {+ return (ITEM_SLOTS[move.operation] ?? []).flatMap((pattern) => expand(move.args, pattern))+ .filter((path) => itemNumber(slot(move, path)) !== null);+}++/** Read or write the value at one slot of a move's arguments. */function slot(move, path, value) {const holder = path.slice(0, -1).reduce((at, key) => at[key], move.args);if (value !== undefined) holder[path.at(-1)] = value;return holder[path.at(-1)];}+/** Keys under which a move might name an item that no declared slot reaches. */+const ITEM_KEYS = /^(id|ids|item|items|itemId|parentId|after|implies|add|remove|skipIds)$/u;++/**+ * Item numbers of offline adds that a move names outside its declared slots. Such a move is refused rather than+ * queued, because the outbox could not follow the item if the relay renumbers it (#922).+ */+export function strayItemRefs(outbox, move) {+ const pending = new Set(outbox.moves.filter((entry) => Number.isSafeInteger(entry.visible)).map((entry) => entry.visible));+ if (!pending.size) return [];+ const declared = new Set(itemSlots(move).map((path) => JSON.stringify(path)));+ const found = [];+ const walk = (value, path, itemish) => {+ if (Array.isArray(value)) { value.forEach((element, index) => walk(element, [...path, index], itemish)); return; }+ if (value !== null && typeof value === 'object') { for (const [key, inner] of Object.entries(value)) walk(inner, [...path, key], ITEM_KEYS.test(key)); return; }+ const number = itemNumber(value);+ if (itemish && number !== null && pending.has(number) && !declared.has(JSON.stringify(path))) found.push(number);+ };+ // A bare top-level number is an item only through a declared slot; a decision's first argument names a shout.+ move.args.forEach((value, index) => walk(value, [index], false));+ return found;+}+/*** Bind the item numbers a new move names to the queued adds that made those items here, by the add's move id.* Why: a number shown on this machine for an item it added offline is temporary; the relay may give another machine@@ -176,7 +244,7 @@ function slot(move, path, value) {*/export function bindRefs(outbox, move) {const pending = new Map(outbox.moves.filter((entry) => Number.isSafeInteger(entry.visible)).map((entry) => [entry.visible, entry.move.id]));- return itemSlots(move).filter((path) => pending.has(slot(move, path))).map((path) => ({ path, add: pending.get(slot(move, path)) }));+ return itemSlots(move).filter((path) => pending.has(itemNumber(slot(move, path)))).map((path) => ({ path, add: pending.get(itemNumber(slot(move, path))) }));}/**@@ -189,8 +257,8 @@ export function resolveMove(entry, outbox, { local = false } = {}) {for (const { path, add } of entry.refs ?? []) {const waiting = local ? outbox.moves.find((other) => other.move.id === add) : null;const value = waiting ? waiting.visible : outbox.results?.[add];- if (value === null) lost.push(slot(entry.move, path));- else if (Number.isSafeInteger(value)) slot(move, path, value);+ if (value === null) lost.push(itemNumber(slot(entry.move, path)));+ else if (Number.isSafeInteger(value)) slot(move, path, sameForm(slot(entry.move, path), value));}return { move, lost };}@@ -256,6 +324,10 @@ export async function queueMove(link, { operation, args, command, move, error, amove = localRecords(root, (board) => prepareEngineMove(board, operation, sent));move.actor = relayMoveActor(move) ?? credentialActor(move);}+ const stray = strayItemRefs(outbox, move);+ if (stray.length) {+ throw new Refused('RELAY_OUTBOX_UNBOUND', `this move names #${stray[0]}, which this machine added while the relay was down, in a field the outbox cannot follow if the relay renumbers it; run it again once the relay answers`);+ }// `after` is the relay sequence this machine had seen: a refusal at replay names the moves ordered since.const entry = { move, refs: bindRefs(outbox, move), intent: operationIntent(operation, args), queuedAt: new Date().toISOString(), after: state.sequence,...(command ? { command, commandIntent: operationIntent('cli:' + command.cliOperation, command) } : {}) };diff --git a/test/relay-outbox.test.js b/test/relay-outbox.test.jsindex 141ef5f0..d24573bf 100644--- a/test/relay-outbox.test.js+++ b/test/relay-outbox.test.js@@ -3,9 +3,12 @@ import { readFileSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import test from 'node:test';import { fileURLToPath } from 'node:url';+import { ENGINE_OPERATIONS } from '../src/engine.js';import {+ ITEM_SLOTS,bindRefs,resolveMove,+ strayItemRefs,} from '../src/relay-outbox.js';import { runFixtureGit } from './fixture-child.js';import { relayClientFixture } from './relay-client-fixture.js';@@ -28,9 +31,10 @@ function shoutTexts(exported) {}/** Two machines on one accepted relay board with the outbox on, and an item added before the outage. */-async function twoMachines(t, title) {+async function twoMachines(t, title, { beforeLink } = {}) {const box = await relayClientFixture(t);enableOutbox(box);+ await beforeLink?.(box);await box.link();const contested = (await box.cli('add', box.lane, title)).document.item.item_id;const printed = await box.cli('relay', 'pair');@@ -159,3 +163,74 @@ test('a queued move names an offline item by the add that made it, never by a nuoutbox.results = { a: 3, b: null };assert.deepEqual(resolveMove(queued, outbox).lost, [3], 'a move on an item whose add was refused is named, not sent');});++/** The milestones a board export holds, by name, with their item numbers as numbers. */+function milestoneItems(exported) {+ const row = exported.tables.board_meta.find((meta) => meta.meta_key === 'milestones');+ return Object.fromEntries(JSON.parse(row?.meta_value ?? '[]').map((milestone) => [milestone.name, milestone.items.map(Number)]));+}++test('every ordered move kind says where it names an item, and each place follows an offline item renumbered at replay [B26,H16]', () => {+ assert.deepEqual(ENGINE_OPERATIONS.filter((operation) => !Object.hasOwn(ITEM_SLOTS, operation)), [], 'every engine operation declares its item places, even when it has none');+ assert.deepEqual(Object.keys(ITEM_SLOTS).filter((operation) => !ENGINE_OPERATIONS.includes(operation)), [], 'no declaration names an operation the engine lacks');+ /** Build arguments that hold `value` at one declared place, with a list of one where the pattern has `*`. */+ const holding = (pattern, value) => {+ const args = [];+ let at = args;+ pattern.forEach((key, index) => {+ const last = index === pattern.length - 1;+ const next = last ? value : pattern[index + 1] === '*' ? [] : {};+ if (key === '*') at.push(next); else at[key] = next;+ at = key === '*' ? at.at(-1) : at[key];+ });+ return args;+ };+ const outbox = { moves: [{ move: { id: 'offline-add', operation: 'addItem', args: [{}] }, visible: 7 }], results: { 'offline-add': 12 } };+ let places = 0;+ for (const [operation, patterns] of Object.entries(ITEM_SLOTS)) {+ for (const pattern of patterns) {+ for (const value of pattern.at(-1) === '*' ? [7, '7', '#7'] : [7]) {+ const move = { id: `${operation}-${places}`, operation, args: holding(pattern, value) };+ const entry = { move, refs: bindRefs(outbox, move) };+ assert.equal(entry.refs.length, 1, `${operation} binds the offline item at ${pattern.join('.')} (${JSON.stringify(value)})`);+ const sent = resolveMove(entry, outbox).move;+ const written = entry.refs[0].path.reduce((held, key) => held[key], sent.args);+ assert.deepEqual(written, typeof value === 'string' ? value.replace('7', '12') : 12, `${operation} sends the relay's number at ${pattern.join('.')}, in the form it was given`);+ assert.equal(strayItemRefs(outbox, move).length, 0, `${operation}'s declared place is never treated as stray`);+ places += 1;+ }+ }+ }+ assert.ok(places >= 30, `the walk covers every declared place (${places})`);+});++test('a move that names an offline item where the outbox cannot follow it is refused, never sent [B26,H16]', () => {+ const outbox = { moves: [{ move: { id: 'offline-add', operation: 'addItem', args: [{}] }, visible: 7 }] };+ assert.deepEqual(strayItemRefs(outbox, { operation: 'recordHealthFindings', args: [{ agentId: 'coordinator', findings: [{ item: 7, cause: 'x' }] }] }), [7]);+ assert.deepEqual(strayItemRefs(outbox, { operation: 'answerDecision', args: [7, { agentId: 'coordinator', text: 'yes' }] }), [], 'a decision number is a shout, never an item');+ assert.deepEqual(strayItemRefs(outbox, { operation: 'recordAttempt', args: [3, { agentId: 'core-1', n: 7, seconds: 7 }] }), [], 'counts and durations are not items');+});++test('a milestone edit naming an offline item follows that item when another machine takes its number first [B26,H16,H17]', async (t) => {+ // The milestone is part of the linked baseline, as on a board that already had one before the outage.+ const { box, other } = await twoMachines(t, 'Added before the outage', {+ beforeLink: async (unlinked) => assert.equal((await unlinked.cli('milestone', 'add', 'next')).code, 0),+ });+ await box.stopRelay();+ const added = await box.cli('add', box.lane, 'Added here while the relay is down');+ const local = added.document.item.item_id;+ const listed = await box.cli('milestone', 'items', 'next', '--add', String(local));+ assert.equal(listed.code, 0, listed.failure);+ await box.restartRelay();+ assert.equal((await other.cli('add', box.lane, 'Added there first')).document.item.item_id, local, 'the other machine takes the number used offline');++ const replayed = await box.cli('status');+ assert.equal(replayed.code, 0, replayed.failure);+ assert.equal(replayed.document.relay.outboxRefusals, undefined, 'nothing is refused');+ for (const machine of [box, other]) {+ const exported = (await machine.cli('export')).document;+ const titles = new Map(exported.tables.item.map((row) => [row.item_id, row.item_title]));+ assert.deepEqual(milestoneItems(exported).next.map((id) => titles.get(id)), ['Added here while the relay is down'],+ 'the milestone holds the item this machine added, not the other machine\'s');+ }+});