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): forget boards already deleted remotely [H1,H18,P5]
Corey Olsondd758d948764
diff --git a/src/cli.js b/src/cli.jsindex a27ace02..ffb6ccae 100644--- a/src/cli.js+++ b/src/cli.js@@ -1811,7 +1811,7 @@ async function runCommand(argv, io) {const result = first === 'on' ? await relayOn(ctx.info.root, values.url, io): first === 'off' ? await relayOff(ctx.info.root, io) : relayStatus(ctx.info.root);io.result?.(result);- io.say(result.linked ? `${result.link}\nrelay: sequence ${result.sequence}; ${result.behind} pending uploads` : 'relay off; the local board is complete');+ io.say(result.linked ? `${result.link}\nrelay: sequence ${result.sequence}; ${result.behind} pending uploads` : (result.notice || 'relay off; the local board is complete'));return 0;}if (command === 'gate') {diff --git a/src/relay.js b/src/relay.jsindex db2a2d64..6a1e7af8 100644--- a/src/relay.js+++ b/src/relay.js@@ -12,6 +12,7 @@ import { Refused } from './refused.js';export const DEFAULT_RELAY = 'https://app.pullboard.dev';const LINK_FILES = new WeakMap();+const WARNED_COMMANDS = new WeakSet();/** Require a trusted origin; HTTP exists only for loopback development and test relays. */function relayOrigin(address) {@@ -101,13 +102,14 @@ async function locked(file, work) {/** Surface retention notices on the very command that receives them, without exposing credentials. */function notices(document, io) {const warnings = [document.warning, document.state?.warning, ...(document.warnings ?? [])].filter(Boolean);- for (const warning of warnings) if (warning.code === 'BOARD_INACTIVE') {+ for (const warning of warnings) if (warning.code === 'BOARD_INACTIVE' && !WARNED_COMMANDS.has(io)) {+ WARNED_COMMANDS.add(io);io.err(`pullboard: [BOARD_INACTIVE] ${warning.daysLeft} days left before this relay board is deleted; ${warning.next || 'make a board move before the deadline to keep it'}`);}}/** The sole outbound transport in the CLI: explicit sign-in or a saved, opted-in board link. */-async function request(state, path, { method = 'GET', body } = {}, io) {+async function request(state, path, { method = 'GET', body, allowMissing = false } = {}, io) {let response;try {response = await fetch(relayOrigin(state.url) + path, {@@ -119,6 +121,8 @@ async function request(state, path, { method = 'GET', body } = {}, io) {let document;try { document = await response.json(); } catch { throw new Refused('RELAY_RESPONSE', 'the relay returned an invalid response; retry with the configured relay address'); }notices(document, io);+ // Only off can forget a link after a supported API reports that the board is gone.+ if (allowMissing && method === 'DELETE' && response.status === 404 && document.version === 1) return { alreadyDeleted: true };if (!response.ok) throw new Refused(document.error?.code || 'RELAY_UNAVAILABLE', (document.error?.code === 'AUTH_REQUIRED' ? 'the relay sign-in expired or was revoked; run pullboard relay on to sign in again without changing the board key' : document.error?.message) || 'the relay refused this send; the next command retries it');if (document.version !== 1) throw new Refused('RELAY_VERSION', 'the relay API version is unsupported; upgrade Pullboard before syncing');return document;@@ -285,12 +289,14 @@ export async function relayOff(root, io) {const state = loadLink(file);if (!state) return summary(root, null);if (!state.unlinking) {- await request(state, '/api/v1/boards/' + state.board, { method: 'DELETE' }, io);+ const deleted = await request(state, '/api/v1/boards/' + state.board, { method: 'DELETE', allowMissing: true }, io);+ if (deleted.alreadyDeleted) state.alreadyDeleted = true;state.unlinking = true;saveLink(file, state);}forgetBoardKey(state.board, state.keyStorage);rmSync(file, { force: true });- return { linked: false, board: state.board, url: state.url, link: '', sequence: state.sequence, behind: 0 };+ return { linked: false, board: state.board, url: state.url, link: '', sequence: state.sequence, behind: 0,+ ...(state.alreadyDeleted ? { alreadyDeleted: true, notice: 'the relay had already deleted this board; this device is unlinked and the local board is complete' } : {}) };});}diff --git a/test/relay-client-fixture.js b/test/relay-client-fixture.jsnew file mode 100644index 00000000..b1ed883f--- /dev/null+++ b/test/relay-client-fixture.js@@ -0,0 +1,130 @@+/** Private real CLI, auth and relay fixture; credentials never enter assertion messages [H1,H7,H18]. */+import assert from 'node:assert/strict';+import { spawn, spawnSync } from 'node:child_process';+import { createServer } from 'node:http';+import { once } from 'node:events';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { delimiter, join, resolve } from 'node:path';+import { tmpdir } from 'node:os';+import { createAuthHandler } from '../relay/auth-http.js';+import { createRelayAuth } from '../relay/auth.js';+import { createRelayHandler } from '../relay/service.js';+import { createGitHubClient } from '../relay/github.js';+import { githubFixture } from './relay-fixture.js';++const CLI = resolve(import.meta.dirname, '../bin/pullboard.js');++/** Capture a real child result without exposing its private output in failure diagnostics. */+function childResult(root, env, argv) {+ return new Promise((resolveResult, reject) => {+ const child = spawn(process.execPath, argv, { cwd: root, env, stdio: ['ignore', 'pipe', 'pipe'] });+ let stdout = '';+ const timer = setTimeout(() => child.kill('SIGKILL'), 25000);+ child.stdout.setEncoding('utf8').on('data', part => { stdout += part; });+ child.stderr.resume();+ child.once('error', error => { clearTimeout(timer); reject(error); });+ child.once('close', (code, signal) => {+ clearTimeout(timer);+ if (signal) return reject(new Error('private relay fixture child exceeded its deadline'));+ let document;+ try { document = JSON.parse(stdout); }+ catch { return reject(new Error('private relay fixture child did not return JSON')); }+ resolveResult({ code, document });+ });+ });+}++/** Start an isolated board with fallback-file keys and a real authorized loopback relay. */+export async function relayClientFixture(t) {+ const scratch = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-relay-cleanup-')));+ const root = join(scratch, 'repo');+ const home = join(scratch, 'home');+ const privateBin = join(scratch, 'path');+ mkdirSync(root);+ mkdirSync(home, { mode: 0o700 });+ mkdirSync(privateBin, { mode: 0o700 });+ const git = process.env.PATH.split(delimiter).map(entry => join(entry, 'git')).find(existsSync);+ assert.ok(git, 'fixture has a git executable');+ symlinkSync(realpathSync(git), join(privateBin, 'git'));+ symlinkSync(realpathSync(process.execPath), join(privateBin, 'node'));+ const env = {+ ...process.env, HOME: home, PULLBOARD_HOME: join(home, '.pullboard'),+ PULLBOARD_MACHINE_HOME: join(scratch, 'machine'), PATH: privateBin,+ GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',+ GIT_AUTHOR_NAME: 'Relay Fixture', GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Relay Fixture', GIT_COMMITTER_EMAIL: '[email protected]',+ };+ const provider = await githubFixture(t);+ provider.state.deviceAuthorized = true;+ const auth = createRelayAuth({ database: join(scratch, 'auth.sqlite'), github: createGitHubClient(provider.config) });+ let time = Date.now();+ let override = null;+ let signIn;+ let api;+ const calls = [];+ const server = createServer(async (req, res) => {+ calls.push({ method: req.method, path: req.url });+ if (override && req.method === 'DELETE') {+ res.writeHead(override.status, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ version: override.version ?? 1, error: { code: override.code, message: 'fixture refusal' } }));+ return;+ }+ if (await signIn(req, res)) return;+ await api(req, res);+ });+ server.listen(0, '127.0.0.1');+ await once(server, 'listening');+ const origin = 'http://127.0.0.1:' + server.address().port;+ signIn = createAuthHandler({ auth, publicOrigin: origin });+ api = createRelayHandler({ directory: join(scratch, 'relay'), auth, publicOrigin: origin, pollMs: 10, maintenanceMs: 0, now: () => time });+ t.after(async () => {+ api.close();+ server.closeAllConnections();+ await new Promise(ready => server.close(ready));+ auth.close();+ rmSync(scratch, { recursive: true, force: true });+ });++ /** Invoke the production CLI in this private repository. */+ async function cli(...args) { return childResult(root, env, [CLI, ...args, '--json']); }+ assert.equal(spawnSync('git', ['init', '-q', '-b', 'main'], { cwd: root, env }).status, 0);+ assert.equal((await cli('init')).code, 0);+ assert.equal(spawnSync('git', ['remote', 'add', 'origin', '[email protected]:fixture/repository.git'], { cwd: root, env }).status, 0);+ const lane = Object.keys(JSON.parse(readFileSync(join(root, 'pullboard.json'), 'utf8')).lanes)[0];+ assert.equal((await cli('add', lane, 'private cleanup fixture item')).code, 0);+ const before = (await cli('export')).document;+ const id = before.tables.board_meta.find(row => row.meta_key === 'board_id').meta_value;+ const linkFile = join(root, '.git', 'pullboard', 'relay.json');+ const keyFile = join(env.PULLBOARD_HOME, 'relay-keys', id + '.key');++ /** Start a saved real relay link without exposing the pairing fragment. */+ async function link() { assert.equal((await cli('relay', 'on', '--url', origin)).code, 0, 'real device sign-in links the board'); }+ /** Pair and unlink from a second real repository with its own private device home and key. */+ async function otherDeviceOff() {+ const otherRoot = join(scratch, 'other-device');+ const otherHome = join(scratch, 'other-home');+ mkdirSync(otherRoot);+ mkdirSync(otherHome, { mode: 0o700 });+ const otherEnv = { ...env, HOME: otherHome, PULLBOARD_HOME: join(otherHome, '.pullboard') };+ /** Invoke the independent device's production CLI without retaining its output in diagnostics. */+ const run = (...args) => childResult(otherRoot, otherEnv, [CLI, ...args, '--json']);+ assert.equal(spawnSync('git', ['init', '-q', '-b', 'main'], { cwd: otherRoot, env: otherEnv }).status, 0);+ assert.equal((await run('init')).code, 0);+ assert.equal(spawnSync('git', ['remote', 'add', 'origin', '[email protected]:fixture/repository.git'], { cwd: otherRoot, env: otherEnv }).status, 0);+ const snapshot = join(scratch, 'snapshot.json');+ writeFileSync(snapshot, JSON.stringify(before), { mode: 0o600 });+ assert.equal((await run('import', snapshot)).code, 0, 'second device imports the same real board');+ assert.equal((await run('relay', 'on', '--url', origin)).code, 0, 'second device signs in independently');+ return (await run('relay', 'off')).code;+ }+ /** Run multiple production commands in one process, emitting only safe counters. */+ async function script(source) {+ return childResult(root, env, ['--input-type=module', '-e', source]);+ }+ return {+ root, env, lane, before, linkFile, keyFile, calls, cli, link, otherDeviceOff, script,+ advance(days) { time = Date.now() + days * 86400000; },+ overrideDelete(value) { override = value; },+ mainURL: new URL('../src/cli.js', import.meta.url).href,+ };+}diff --git a/test/relay.test.js b/test/relay.test.jsindex 137d2e0f..bebba1da 100644--- a/test/relay.test.js+++ b/test/relay.test.js@@ -8,6 +8,7 @@ import { createGitHubClient } from '../relay/github.js';import { createRelayAuth, ACCESS_WINDOW_MS } from '../relay/auth.js';import { serveRelay } from '../relay/service.js';import { githubFixture } from './relay-fixture.js';+import { relayClientFixture } from './relay-client-fixture.js';/** Use real private SQLite and an actual HTTP provider with a controllable expiry clock. */async function fixture(t, options = {}) {@@ -346,3 +347,101 @@ test('an explicit read role still hides a public board below triage [H13,H14,H8]await assert.rejects(box.auth.authenticate(signed.token, { board: 'alpha', write: true }), { code: 'BOARD_NOT_LINKED' });await assert.rejects(box.auth.issueToken(signed.token, { board: 'alpha', agent: 'worker' }), { code: 'BOARD_NOT_LINKED' });});++test('relay off forgets expired and independently unlinked boards while preserving local rows [H1,H7,H18]', async (t) => {+ for (const cause of ['expired', 'other-client']) await t.test(cause, async (t) => {+ const box = await relayClientFixture(t);+ await box.link();+ if (cause === 'expired') box.advance(90);+ else assert.equal(await box.otherDeviceOff(), 0, 'a second real CLI device unlinks the shared board');+ const off = await box.cli('relay', 'off');+ assert.equal(off.code, 0);+ assert.equal(off.document.linked, false);+ assert.equal(off.document.alreadyDeleted, true);+ assert.match(off.document.notice, /already deleted/);+ assert.equal(existsSync(box.linkFile), false, 'local link metadata is forgotten');+ assert.equal(existsSync(box.keyFile), false, 'device-only fallback key is forgotten');+ assert.deepEqual((await box.cli('export')).document.tables, box.before.tables, 'local board is complete after remote deletion');+ const count = box.calls.length;+ assert.equal((await box.cli('relay', 'off')).code, 0);+ assert.equal((await box.cli('status')).code, 0);+ assert.equal(box.calls.length, count, 'repeated off and local commands make no relay connection');+ });+});++test('relay off retains credentials and metadata after non-missing or unsupported refusals [H1,H7]', async (t) => {+ const box = await relayClientFixture(t);+ await box.link();+ for (const failure of [+ { status: 403, code: 'NO_REPO_ACCESS' },+ { status: 401, code: 'AUTH_REQUIRED' },+ { status: 500, code: 'NO_BOARD' },+ { status: 404, code: 'NO_BOARD', version: 2 },+ ]) {+ box.overrideDelete(failure);+ assert.notEqual((await box.cli('relay', 'off')).code, 0, 'only a supported missing-board response permits cleanup');+ assert.equal(existsSync(box.linkFile), true);+ assert.equal(existsSync(box.keyFile), true);+ }+ box.overrideDelete(null);+ assert.equal((await box.cli('relay', 'off')).code, 0);+ assert.equal(existsSync(box.keyFile), false);+});++test('BOARD_INACTIVE appears once per command and resets for a second command in the same process [H18]', async (t) => {+ const box = await relayClientFixture(t);+ await box.link();+ box.advance(80);+ const result = await box.script(`+ import { main } from ${JSON.stringify(box.mainURL)};+ const counts = [];+ for (let i = 0; i < 2; i++) {+ let output = '';+ const code = await main(['status', '--json'], {+ cwd: process.cwd(), stdout: { write(part) { output += part; } },+ stderr: { write() {} },+ });+ const value = JSON.parse(output);+ counts.push({ code, warnings: (value.diagnostics || []).filter(line => line.includes('BOARD_INACTIVE')).length });+ }+ console.log(JSON.stringify(counts));+ `);+ assert.equal(result.code, 0);+ assert.deepEqual(result.document, [{ code: 0, warnings: 1 }, { code: 0, warnings: 1 }]);+});++test('unlinked board commands attempt zero outbound requests [H1,P5]', async (t) => {+ const box = await relayClientFixture(t);+ const result = await box.script(`+ import { main } from ${JSON.stringify(box.mainURL)};+ let attempts = 0;+ globalThis.fetch = async () => { attempts++; throw new Error('unexpected outbound attempt'); };+ const codes = [];+ for (const args of [+ ['status'], ['list'], ['show', '1'], ['add', ${JSON.stringify(box.lane)}, 'another fixture item'],+ ['shout', 'coordinator', 'fixture local message'], ['relay'], ['relay', 'off'],+ ]) codes.push(await main([...args, '--json'], {+ cwd: process.cwd(), stdout: { write() {} }, stderr: { write() {} },+ }));+ console.log(JSON.stringify({ attempts, codes }));+ `);+ assert.equal(result.code, 0);+ assert.equal(result.document.attempts, 0);+ assert.ok(result.document.codes.every(code => code === 0), 'all ordinary local board commands succeed without transport');+});++test('plain relay off explains an already-deleted board without printing credentials [H1,H18]', async (t) => {+ const box = await relayClientFixture(t);+ await box.link();+ box.advance(90);+ const result = await box.script(`+ import { main } from ${JSON.stringify(box.mainURL)};+ let output = '';+ const code = await main(['relay', 'off'], {+ cwd: process.cwd(), stdout: { write(part) { output += part; } }, stderr: { write() {} },+ });+ console.log(JSON.stringify({ code, explained: output.includes('already deleted'), credential: /ps_|key=/.test(output) }));+ `);+ assert.equal(result.code, 0);+ assert.deepEqual(result.document, { code: 0, explained: true, credential: false });+});