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): fail refused approval publication [H15,H12]
Corey Olson81b6937666a1
diff --git a/docs/api.md b/docs/api.mdindex 5dcea990..e2c4939a 100644--- a/docs/api.md+++ b/docs/api.md@@ -159,7 +159,7 @@ Phone enrollment uses a one-use `#device=<locator>.<secret>` fragment, removed b`POST /auth/machines {board,machine}` requires a foreground person session and returns a `pm_` credential bound to that board and machine. This delegate can mint board-scoped `pa_` tokens through `/auth/tokens` and list only its board’s token ids and metadata. It cannot link a board, issue a machine credential, post a phone request, revoke another credential directly, or use person-only cookie endpoints. Agent tokens cannot mint any credential.-A machine publishes an opaque approval with `POST /api/v1/devices/approvals {context,sealed}`. The publishing machine may GET only its own requests. The paired phone reads `/api/v1/devices/:deviceId/approvals`, explicitly POSTs `/:requestId/authorize {}` and completes the encrypted reply through `/:requestId/complete {response}`. The publishing machine executes a native revocation through `/:requestId/execute {grant}`; the two-minute grant binds the entire context and is atomically consumed once. Native reply keys and grants never persist. A refused foreground approval fails immediately with the original refusal code and reason plus its request id. Local unlinking and registration still succeed when their remote approval fails: one warning identifies that request and the next action, and the JSON result includes `remote: {code, reason, requestId}`. New-board linking uses a durable non-person reply key and returns only a board-scoped machine credential. `relay off` immediately unlinks locally even offline or in an agent shell, reports that the relay copy remains, and queues a separate one-tap phone deletion request when possible.+A machine publishes an opaque approval with `POST /api/v1/devices/approvals {context,sealed}`. The publishing machine may GET only its own requests. The paired phone reads `/api/v1/devices/:deviceId/approvals`, explicitly POSTs `/:requestId/authorize {}` and completes the encrypted reply through `/:requestId/complete {response}`. The publishing machine executes a native revocation through `/:requestId/execute {grant}`; the two-minute grant binds the entire context and is atomically consumed once. Native reply keys and grants never persist. A refused foreground approval fails immediately with the original refusal code and reason plus its request id. A refused remote approval makes local unlinking or registration exit nonzero while retaining the completed local work: one line names that completion, the refusal code and reason, the request id and the next action. The JSON result preserves the local outcome and includes `remote: {code, reason, requestId}`. New-board linking uses a durable non-person reply key and returns only a board-scoped machine credential. `relay off` immediately unlinks locally even offline or in an agent shell, reports that the relay copy remains, and queues a separate one-tap phone deletion request when possible.The result and refusal tables are checked against `JSON_SHAPES` in `src/json.js` by `docs/api.test.js`.diff --git a/src/cli.js b/src/cli.jsindex e9c51ddd..15fbf310 100644--- a/src/cli.js+++ b/src/cli.js@@ -2843,8 +2843,9 @@ async function runMain(argv, streams) {const code = await runCommand(argv, io);if (code === 0) await checkoutSession?.finish?.();if (sync && code === 0) await retry();- io.flush(code);- return code;+ const status = io.exitCode(code);+ io.flush(status);+ return status;} finally {CHECKOUT_LEASES.delete(io);checkoutSession?.lease?.release();diff --git a/src/json.js b/src/json.jsindex e25c72b2..3ded1a14 100644--- a/src/json.js+++ b/src/json.js@@ -143,7 +143,7 @@ export function commandOutput(argv, streams) {document = native && !Array.isArray(native) && typeof native.version === 'number'? { ...native, ...(diagnostics.length ? { diagnostics } : {}) } : { version: JSON_SHAPES.version, messages, ...(diagnostics.length ? { diagnostics } : {}) };}- if (code === 0 && remote) document.remote = remote;+ if (remote) document.remote = remote;streams.stdout.write(`${JSON.stringify(document, null, 2)}\n`);};return {@@ -154,6 +154,7 @@ export function commandOutput(argv, streams) {result: (value) => { result = value; },refusal: (error) => { refusal = error; },remote: (value) => { remote = value; },+ exitCode: (code) => code || (remote ? 1 : 0),jsonMode: (value) => { enabled = Boolean(value); },flush,};diff --git a/src/relay-phone.js b/src/relay-phone.jsindex 75ea6ae1..79d42250 100644--- a/src/relay-phone.js+++ b/src/relay-phone.js@@ -43,7 +43,7 @@ export async function publishPhoneApproval(state, proposal, io, send) {} catch (error) { throw approvalRefusal(context, error); }}-/** Report a refused remote approval without undoing a completed local action. */+/** Record a partial failure and its request identity without undoing the completed local action. */export function warnPhoneApproval(proposal, error, io, next) {const code = error instanceof Refused ? error.code : 'PHONE_APPROVAL_UNAVAILABLE';let reason = error instanceof Refused ? error.message.replace(/^\[[A-Z][A-Z0-9_]*\] /u, '')diff --git a/src/relay.js b/src/relay.jsindex 96ff156d..54693e7f 100644--- a/src/relay.js+++ b/src/relay.js@@ -1086,7 +1086,7 @@ export async function relayOff(root, io) {await publishPhoneApproval(state, proposal, io, request);requested = true;} catch (error) {- if (proposal) remote = warnPhoneApproval(proposal, error, io, 'Manage the relay copy from the phone, or relink this board and run pullboard relay off again explicitly.');+ if (proposal) remote = warnPhoneApproval(proposal, error, io, 'Local link removed. Manage the relay copy from the phone, or relink this board and run pullboard relay off again explicitly.');}return { linked: false, board: state.board, url: state.url, link: '', sequence: state.sequence, behind: 0,...(remote ? { remote } : {}),diff --git a/test/relay-approval-delivery.test.js b/test/relay-approval-delivery.test.jsindex 3a00c1fe..4d6ab8ce 100644--- a/test/relay-approval-delivery.test.js+++ b/test/relay-approval-delivery.test.js@@ -23,8 +23,8 @@ async function waitFor(read, message, timeoutMs = 20_000) {}/** Run the production CLI in the isolated project, preserving JSON for precise refusal checks. */-function cliCommand(root, env, args, timeoutMs = APPROVAL_TIMEOUT_MS) {- const child = spawn(process.execPath, [CLI, ...args, '--json'], { cwd: root, env, stdio: ['ignore', 'pipe', 'pipe'] });+function cliCommand(root, env, args, timeoutMs = APPROVAL_TIMEOUT_MS, { json = true } = {}) {+ const child = spawn(process.execPath, [CLI, ...args, ...(json ? ['--json'] : [])], { cwd: root, env, stdio: ['ignore', 'pipe', 'pipe'] });let stdout = '';let stderr = '';child.stdout.setEncoding('utf8').on('data', chunk => { stdout += chunk; });@@ -35,7 +35,7 @@ function cliCommand(root, env, args, timeoutMs = APPROVAL_TIMEOUT_MS) {child.once('close', (code, signal) => {clearTimeout(timer);if (signal) return reject(new Error('A private native approval command exceeded its finite fixture bound.'));- try { resolveResult({ code, document: JSON.parse(stdout), stderr }); }+ try { resolveResult({ code, document: json ? JSON.parse(stdout) : null, stdout, stderr }); }catch { reject(new Error('The private approval command did not return JSON.')); }});});@@ -317,45 +317,58 @@ function unregisteredProject(box, name) {return root;}-/** Compare one nonblocking warning with the actual rejected HTTP proposal and reason. */-function assertRemoteWarning(box, before, result, action) {+/** Match a real publication refusal to its native partial failure and preserved local outcome. */+function assertRemoteFailure(box, before, result, action, completed) {const post = box.transit.slice(before).find(record => record.method === 'POST'&& record.path === '/api/v1/devices/approvals');- assert.ok(post, 'the nonblocking operation attempted its real remote approval');+ assert.ok(post, 'the operation attempted its real remote approval');const context = JSON.parse(post.request.toString('utf8')).context;const response = JSON.parse(post.response.toString('utf8'));assert.equal(context.action, action);- assert.equal(result.code, 0, 'the completed local operation remains successful');- assert.deepEqual(result.document.remote, { code: 'PHONE_APPROVAL_CONTEXT',- reason: 'the relay ' + box.origin + ': ' + response.error.message, requestId: context.id }, 'JSON preserves the original remote refusal separately');- assert.ok(Array.isArray(result.document.diagnostics), 'local success carries the remote warning');- const warnings = result.document.diagnostics.filter(line => line.includes('Remote approval request'));- assert.equal(warnings.length, 1, 'exactly one remote warning accompanies local success');- assert.ok(warnings[0].includes(context.id), 'the warning identifies the refused request');- assert.ok(warnings[0].includes(response.error.message), 'the warning retains the relay reason');- assert.match(warnings[0], /\[PHONE_APPROVAL_CONTEXT\]/u);- assert.match(warnings[0], /explicitly/u, 'the warning gives an explicit recovery step');+ assert.equal(response.error.code, 'PHONE_APPROVAL_CONTEXT', 'the actual relay refused the proposal');+ assert.equal(result.code, 1, 'a remote publication refusal makes the native command fail');+ if (result.document) {+ assert.deepEqual(result.document.remote, { code: 'PHONE_APPROVAL_CONTEXT',+ reason: 'the relay ' + box.origin + ': ' + response.error.message, requestId: context.id }, 'JSON preserves the original remote refusal separately');+ assert.ok(Array.isArray(result.document.diagnostics), 'the partial failure carries its named diagnostic');+ }+ const lines = result.document?.diagnostics ?? result.stderr.split('\n');+ const refusals = lines.filter(line => line.includes('Remote approval request'));+ assert.equal(refusals.length, 1, 'exactly one line names the partial failure');+ assert.ok(refusals[0].includes(context.id), 'the refusal identifies the exact request');+ assert.ok(refusals[0].includes(response.error.message), 'the refusal retains the relay reason');+ assert.ok(refusals[0].includes(completed), 'the same line names the completed local action');+ assert.match(refusals[0], /\[PHONE_APPROVAL_CONTEXT\]/u);+ assert.match(refusals[0], /explicitly/u, 'the refusal gives an explicit recovery step');+ assert.equal(box.transit.slice(before).some(record => record.method === 'GET'+ && record.path === '/api/v1/devices/approvals/' + context.id), false, 'refused publication never waits for an approval');}-test('local unlink and registration succeed with one named remote refusal [H15,H12]', {+test('local unlink and registration fail on a remote refusal while retaining local work [H15,H12]', {skip: !findChromeExecutable() && 'Chrome is not installed',}, async t => {- const box = await relayClientFixture(t);- const { native } = await pairPhone(box, t);- const project = unregisteredProject(box, 'remote-refused-registration');- box.advance(-31 / 86400);- const registerBefore = box.transit.length;- const registration = cliCommand(project, box.env, ['init']);- native.push(registration);- assertRemoteWarning(box, registerBefore, await registration.done, 'link');- assert.equal(existsSync(join(project, '.git/pullboard/board.sqlite')), true, 'registration persists the local board');- assert.equal(existsSync(join(project, '.git/pullboard/relay.json')), false, 'refused linking does not invent a linked board');- const offBefore = box.transit.length;- const off = await box.cli('relay', 'off');- assertRemoteWarning(box, offBefore, off, 'delete-board');- assert.equal(off.document.linked, false);- assert.equal(existsSync(box.linkFile), false, 'local unlink is durable despite the remote publication refusal');- box.advance(0);+ for (const json of [true, false]) await t.test(json ? 'JSON partial failures' : 'text partial failures', async t => {+ const box = await relayClientFixture(t);+ const { native, machineFile } = await pairPhone(box, t);+ const project = unregisteredProject(box, 'remote-refused-registration');+ box.advance(-31 / 86400);+ const registerBefore = box.transit.length;+ const registration = cliCommand(project, box.env, ['init'], APPROVAL_TIMEOUT_MS, { json });+ native.push(registration);+ const registered = await registration.done;+ const offBefore = box.transit.length;+ const unlink = cliCommand(box.root, box.env, ['relay', 'off'], APPROVAL_TIMEOUT_MS, { json });+ native.push(unlink);+ const off = await unlink.done;+ assert.deepEqual([registered.code, off.code], [1, 1], 'both real native publication-refusal paths fail immediately');+ assertRemoteFailure(box, registerBefore, registered, 'link', 'Local registration is complete');+ assertRemoteFailure(box, offBefore, off, 'delete-board', 'Local link removed');+ assert.equal(existsSync(join(project, '.git/pullboard/board.sqlite')), true, 'registration persists the local board');+ assert.equal(existsSync(join(project, '.git/pullboard/relay.json')), false, 'refused linking does not invent a linked board');+ if (json) assert.equal(off.document.linked, false);+ assert.equal(existsSync(box.linkFile), false, 'local unlink is durable despite the remote publication refusal');+ assert.ok(JSON.parse(readFileSync(machineFile, 'utf8')).excluded.includes(box.root), 'the local opt-out remains durable');+ });});test('expired and unreachable approvals fail with their exact request id [H15,H12]', {