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(watch): pullboard watch follows the live event stream [A2,N26]
Corey Olson666032e0c728
diff --git a/docs/api.md b/docs/api.mdindex 6d09e627..d64026ce 100644--- a/docs/api.md+++ b/docs/api.md@@ -115,6 +115,7 @@ For example: `flow: review wait average 61 min (1 measured; > 60 min); bottlenec| `view` | `version:number`, `url:string`, `port:number` || `view export` | `version:number`, `path:string` || `serve` | `version:number`, `url:string`, `port:number` |+| `watch` | one document per line: `version:number`, `sequence:number`, `kind:string`, `item:number\|null`, `actor:string\|null`, `detail:string` || `forget` | `version:number`, `root:string` || `prompt` | `version:number`, `role:string`, `text:string` || `gate` | `version:number`, `green:boolean`, `report:string` |@@ -307,6 +308,8 @@ For live events, send `Accept: text/event-stream` to the events path. Ordinary mTo follow several boards on one connection, send `Accept: text/event-stream` to `GET /api/v1/events?boards=<id>,<id>`, naming each board once by its id from `GET /api/v1/boards`. A browser holds at most six connections per origin, so a project group's view follows all its repos through this one stream. Each frame's `data` also names its `board`: an event is `{"version":1,"board":"<id>","event":{...}}`, and the changed signal is `{"version":1,"board":"<id>","event":{"event_kind":"changed"}}`, sent on the same terms as a single board's. An ordinary event's `id` carries one cursor per board, `<id>:<sequence>` pairs joined by commas, so reconnecting with `Last-Event-ID`, or passing the same cursor as `after`, resumes each board where it left off. A followed board the cursor leaves out starts from its first event, and a pair for a board not followed is ignored. Every named board must be one the caller may read: otherwise the request is refused with that board's refusal, naming the board, and nothing is streamed. The path is live only; a request without `Accept: text/event-stream` is refused with `BAD_REQUEST`. The single-board events path is unchanged.+`pullboard watch` follows this same stream from a terminal. It uses the running view's stream when the view serves the board, and otherwise serves API v1 for that one board on a private loopback port and follows that. It prints one line per event, or one JSON document per line with `--json`; it only reads the board. A dropped stream is followed again with `Last-Event-ID` set to the last sequence it handled, and `--since <sequence>` starts a new watch there. Work notices from `--work <lane>` (`claimable`, `review-wait` and `main`) carry `notice: true` and the sequence they follow.+The local server uses a shared HTTP router. Streams recheck access before each poll and close with a versioned refusal if access ends. Slow readers pause delivery and resume from the last delivered sequence.HTTP refusals use the same versioned error envelope above: 400 for malformed calls, 401 for a missing or wrong session secret, 403 for an agent belonging to another board, 404 for an unknown board, path or shout, and 409 for the CLI engine's refusal. Shouts and answers append their events in the same transaction as their records. A move returns its own event, including when it also sends a coordinator shout.diff --git a/src/cli.js b/src/cli.jsindex ccf54309..00c75af2 100644--- a/src/cli.js+++ b/src/cli.js@@ -79,6 +79,7 @@ import { citedTestFiles, rowEvidence, rowStage } from './evidence.js';import { exportView, serveView } from './serve.js';import { forgetView, portHolder, rememberView, runningView } from './view-session.js';import { serveApi } from './api.js';+import { watchCommand } from './watch.js';import { serveMcp } from './mcp.js';import { doctorProblems, doctrineProblems } from './doctor.js';import { staleFrozenItems, staleItemFinding } from './approved-rows.js';@@ -198,6 +199,7 @@ function commandHelp(name) {] : []),'Example:',` ${entry.example}`,+ ...entry.notes,].join('\n');}@@ -301,6 +303,7 @@ const OPTIONS = {evidence: { type: 'string' },outcome: { type: 'string' },item: { type: 'string' },+ kinds: { type: 'string' }, to: { type: 'string' }, work: { type: 'string' }, 'review-wait': { type: 'string' },commit: { type: 'string' },ref: { type: 'string' },supersedes: { type: 'string' },@@ -3774,6 +3777,11 @@ async function runCommand(argv, io) {if (command === 'view') return await viewHere(io, values);if (command === 'serve') return await serveHere(io, values);if (command === 'mcp') return await mcpHere(io, args);+ if (command === 'watch') {+ const ctx = context(io);+ return await watchCommand({ io, values, positionals: [first, second, ...rest].filter((word) => word !== undefined), info: ctx.info,+ config: ctx.config, file: ctx.file, mainRoot: primaryCheckoutRoot(ctx.info) ?? ctx.info.root, isMain: ctx.allowSchemaUpgrade, runCommand: main });+ }if (command === 'forget') {if (!first || second) throw new Refused('USAGE', 'pullboard forget <path>');const root = resolve(io.cwd, first);@@ -4001,7 +4009,7 @@ async function runMain(argv, streams) {positionals: parsed.positionals.slice(1),values: Object.fromEntries(Object.keys(parsed.values).filter(key => key !== 'json').sort().map(key => [key, parsed.values[key]])) };sync = Boolean(command) && !parsed.values.help && !parsed.values.version- && !['help', 'version', 'hook', 'init', 'relay', 'tour', 'mcp'].includes(command)+ && !['help', 'version', 'hook', 'init', 'relay', 'tour', 'mcp', 'watch'].includes(command)// A coordinator declaration on a linked clone must refuse before auto-link or relay sync.&& !(command === 'join' && parsed.positionals[1] === COORDINATOR);needsRepo = !(parsed.values.help || parsed.values.version || command === 'help' || command === 'version');@@ -4066,7 +4074,7 @@ export function resultCommands() {...Object.keys(setupCommands({}, args)),...Object.keys(readCommands({}, args)),...Object.keys(workCommands({}, args)),- 'help', 'version', 'tour', 'lifecycle', 'view', 'serve', 'forget', 'spec', 'prompt', 'hook', 'gate', 'settings', 'runner', 'relay',+ 'help', 'version', 'tour', 'lifecycle', 'view', 'serve', 'watch', 'forget', 'spec', 'prompt', 'hook', 'gate', 'settings', 'runner', 'relay',])].sort();}diff --git a/src/help.js b/src/help.jsindex f04bad16..deca7773 100644--- a/src/help.js+++ b/src/help.js@@ -110,6 +110,11 @@ Worksupersedes the person's answerpullboard pass <shout-id> <note> coordinator passes a decision to the personpullboard decisions [--as person] shouts waiting for you; main checkout defaults to coordinator+ pullboard watch [--to <agent|lane|all>] [--kinds <kinds>] [--item <id>] [--since <sequence>] [--json]+ [--work <lane>] [--review-wait <minutes>]+ follow the board's live events, one line each as it happens, with or without the view+ --work also says when an item there becomes claimable, a review waits longer than+ --review-wait minutes (default 20), or main moves; Ctrl-C stops itpullboard export print the whole board as versioned JSONpullboard import <file> restore a versioned export into an empty board@@ -195,12 +200,12 @@ Gate and hooks${lifecycleHelp()}Reject reasons: TEST_FAILURE, BEHAVIOR_MISMATCH, INSUFFICIENT_EVIDENCE, STALE_HEAD, OTHER.---json prints one versioned document for every command; refusals include their code and next step.`;+--json prints one versioned document for every command, and one per line for watch; refusals include their code and next step.`;const HELP_NAMES = ['tour', 'init', 'worktree', 'join', 'takeover', 'whoami', 'lanes', 'lane', 'lane add', 'status', 'resources', 'settings', 'view', 'view export','serve', 'mcp', 'relay', 'relay recover', 'resume', 'hooks', 'add', 'edit', 'escalate', 'run', 'list', 'doctor', 'skills', 'show', 'next', 'land',- 'check', 'claim', 'release', 'submit', 'done', 'verify', 'fact', 'why', 'shout', 'answer', 'pass', 'decisions', 'inbox', 'export', 'import',+ 'check', 'claim', 'release', 'submit', 'done', 'verify', 'fact', 'why', 'shout', 'answer', 'pass', 'decisions', 'inbox', 'watch', 'export', 'import','sweep', 'merged', 'withdraw', 'refreeze', 'reopen', 'hold', 'stats', 'ledger', 'log', 'spec', 'spec check', 'spec view','spec show', 'spec unmet', 'spec signoff', 'spec draft', 'spec signers', 'spec signers add', 'doctrine', 'doctrine check', 'forget', 'prompt', 'gate', 'hook','hook pre-commit', 'hook pre-merge-commit', 'hook commit-msg', 'hook pre-push', 'view export', 'version', 'lifecycle', 'help',@@ -222,7 +227,7 @@ const HELP_EXAMPLES = {fact: 'pullboard fact 12 measurement "The check passes in 8 seconds"',why: 'pullboard why 12',verify: 'pullboard verify 12 accept --note "removed the fix; the test failed"',- answer: 'pullboard answer 12 "done"', pass: 'pullboard pass 12 "please decide"',+ watch: 'pullboard watch --to web', answer: 'pullboard answer 12 "done"', pass: 'pullboard pass 12 "please decide"',status: 'pullboard status', view: 'pullboard view', mcp: 'pullboard mcp', stats: 'pullboard stats --since 2026-10-08', log: 'pullboard log 12', ledger: 'pullboard ledger','lane add': 'pullboard lane add web --owns apps/web/', lane: 'pullboard lane add web --owns apps/web/',roadmap: 'pullboard roadmap', milestone: 'pullboard milestone add "0.7.0" --items 12,13',@@ -283,6 +288,14 @@ const HELP_FLAG_EXPLANATIONS = {'--route': 'sets which work the model can take',};+/** Lines a command's own help adds after its example. */+const HELP_NOTES = {+ watch: [+ 'Claude Code: run pullboard watch --to <your id> under the Monitor tool, and each event line wakes the seat.',+ 'Any other harness: run it as a long-running command and treat each stdout line as an event.',+ ],+};+/** Build command-specific help rows from the preserved full list so its syntax stays authoritative. */function commandHelpRows(fullHelp) {const lines = fullHelp.split('\n');@@ -315,7 +328,7 @@ function commandHelpRows(fullHelp) {return explanation ? `${flag} — ${explanation}` : flag;});const example = exampleFor(name, usages[0]);- return [name, Object.freeze({ usages, flags, example })];+ return [name, Object.freeze({ usages, flags, example, notes: HELP_NOTES[name] ?? [] })];}));}diff --git a/src/json.js b/src/json.jsindex 8397aaf0..f9b3c4bf 100644--- a/src/json.js+++ b/src/json.js@@ -69,6 +69,8 @@ export const JSON_SHAPES = {view: shape({ url: 'string', port: 'number' }),'view export': shape({ path: 'string' }),serve: shape({ url: 'string', port: 'number' }),+ // watch --json prints one of these per line, for each event or work notice, and no end-of-command document.+ watch: shape({ sequence: 'number', kind: 'string', item: 'number|null', actor: 'string|null', detail: 'string' }),forget: shape({ root: 'string' }),prompt: shape({ role: 'string', text: 'string' }),gate: shape({ green: 'boolean', report: 'string' }),diff --git a/src/templates.js b/src/templates.jsindex 86f78deb..3beabee3 100644--- a/src/templates.js+++ b/src/templates.js@@ -134,6 +134,8 @@ If your item needs code another lane owns and it is not there yet, shout that la**Talk.** \`pullboard shout <lane|agent|all> "<text>"\`. Read \`pullboard inbox\` before you start and after you submit. An MCP client can do the same as your agent: add \`pullboard mcp\`, run from your worktree, as a stdio server; it reads the board, shows an item, shouts and captures ideas for the coordinator, and never makes a person's move.+**Listen.** Where your client can run a command in the background, run \`pullboard watch --to <your id>\` there: it prints one line per event as it happens, and Claude Code wakes on each line when it runs under the Monitor tool. \`pullboard watch --work <lane>\` also says when an item in your lane becomes claimable, a review has waited too long, or main moves. Where your client cannot, read \`pullboard inbox\` at session start, after submit and before ending a turn. Coordinator answers and sentinel findings arrive there either way.+**Never.** Bypass a hook with \`--no-verify\`, or get past a refusal with filler text: fix what it names. Edit the board's database. Verify your own work. Change an approved spec row without the person's OK. Delete or renumber a spec row. Act from the main checkout; it is the coordinator's. Count a yes relayed by another agent as the person's approval.## Helping the persondiff --git a/src/watch.js b/src/watch.jsnew file mode 100644index 00000000..8bc7498e--- /dev/null+++ b/src/watch.js@@ -0,0 +1,338 @@+/**+ * pullboard watch: follow the board's own live event stream and print one line per event [A2,N26].+ *+ * Watch is a client of API v1's live events path, never a second event reader. When the person's+ * view is up and serves this board, watch follows the view's stream. Otherwise it serves the same+ * API on a private loopback port, scoped to this one board, and follows that. Either way the board+ * file is only read: watch makes no move and writes no event.+ */+import { setTimeout as pause } from 'node:timers/promises';+import { basename } from 'node:path';+import { serveApi } from './api.js';+import { openBoardReadOnly } from './board.js';+import { headCommit, withGitFacts } from './git.js';+import { isLane } from './lanes.js';+import { fetchLocal } from './local-fetch.js';+import { Refused } from './refused.js';+import { runningView } from './view-session.js';++/** The kinds that carry a shout, so --to can match their addressee. */+const SHOUT_KINDS = new Set(['shout', 'answer', 'pass']);++/** How long to wait before following the stream again after it drops. */+const RECONNECT_MS = 200;++/** A text-mode detail stays on one short line, whatever the record holds. */+function oneLine(value, limit = 160) {+ const text = String(value ?? '').replace(/[\u0000-\u001f\u007f-\u009f\s]+/gu, ' ').trim();+ return text.length > limit ? text.slice(0, limit - 1) + '…' : text;+}++/**+ * Read the flags into filters, refusing a bad value before anything is followed.+ *+ * @param {Record<string, any>} values+ * @param {{ config: any, agents: { agent_id: string, agent_lane: string }[] }} board+ */+export function watchOptions(values, { config, agents }) {+ const kinds = values.kinds === undefined ? null+ : new Set(String(values.kinds).split(',').map((kind) => kind.trim()).filter(Boolean));+ if (kinds && !kinds.size) throw new Refused('USAGE', '--kinds needs event kinds separated by commas, such as --kinds shout,submit; pullboard log shows the kinds');+ let item = null;+ if (values.item !== undefined) {+ if (!/^[1-9]\d*$/u.test(String(values.item))) throw new Refused('USAGE', '--item needs an item id, such as --item 12');+ item = Number(values.item);+ }+ let to = null;+ if (values.to !== undefined) {+ const name = String(values.to);+ const agent = agents.find((entry) => entry.agent_id === name);+ if (!agent && !['all', 'person', 'coordinator'].includes(name) && !isLane(config, name)) {+ throw new Refused('USAGE', `--to needs an agent id, a lane or all, and ${name} is none of them; pullboard lanes lists the lanes and pullboard status the agents`);+ }+ to = new Set(['all', name, ...(agent?.agent_lane ? [agent.agent_lane] : [])]);+ }+ const work = values.work === undefined ? null : String(values.work);+ if (work !== null && !isLane(config, work)) throw new Refused('USAGE', `--work needs a lane, and ${work} is not one; pullboard lanes lists them`);+ const reviewWait = values['review-wait'] === undefined ? 20 : Number(values['review-wait']);+ if (values['review-wait'] !== undefined && (String(values['review-wait']).trim() === '' || !Number.isFinite(reviewWait) || reviewWait < 0)) {+ throw new Refused('USAGE', '--review-wait needs a number of minutes, such as --review-wait 20');+ }+ if (values['review-wait'] !== undefined && work === null) throw new Refused('USAGE', '--review-wait goes with --work <lane>, such as --work core --review-wait 20');+ let since = null;+ if (values.since !== undefined) {+ if (!/^\d+$/u.test(String(values.since)) || !Number.isSafeInteger(Number(values.since))) {+ throw new Refused('USAGE', '--since needs the last sequence watch printed, such as --since 120');+ }+ since = Number(values.since);+ }+ return { kinds, item, to, work, reviewWaitMs: reviewWait * 60_000, since, json: Boolean(values.json) };+}++/** Run one read against the board file, opened read-only, and close it again. */+function readBoard(file, read) {+ const db = openBoardReadOnly(file);+ try { return read(db); } finally { db.close(); }+}++/** The board's id, its registered agents and its latest event sequence, in one read. */+export function watchStart(file) {+ return readBoard(file, (db) => ({+ id: db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get('board_id').meta_value,+ agents: db.prepare('SELECT agent_id, agent_lane FROM agent').all(),+ sequence: db.prepare('SELECT COALESCE(MAX(event_id), 0) AS id FROM event').get().id,+ }));+}++/** Split a live stream body into its frames, keeping a partial frame until the rest arrives. */+async function* streamFrames(body) {+ const decoder = new TextDecoder();+ let pending = '';+ for await (const chunk of body) {+ pending = (pending + decoder.decode(chunk, { stream: true })).replace(/\r\n/gu, '\n');+ let end;+ while ((end = pending.indexOf('\n\n')) >= 0) {+ const lines = pending.slice(0, end).split('\n');+ pending = pending.slice(end + 2);+ const name = lines.find((line) => line.startsWith('event:'))?.slice(6).trim() ?? 'message';+ const data = lines.filter((line) => line.startsWith('data:')).map((line) => line.slice(5).trimStart()).join('\n');+ if (data) yield { name, data: JSON.parse(data) };+ }+ }+}++/**+ * Open the board's live events after `after`: the running view's stream when it serves this board,+ * otherwise the private API's. Returns null when the view could not give it, so the caller falls back.+ */+async function openStream(base, key, boardId, after, signal) {+ const url = new URL(`/api/v1/boards/${encodeURIComponent(boardId)}/events`, base);+ const response = await fetchLocal(url, {+ headers: { accept: 'text/event-stream', 'x-pullboard-key': key, 'last-event-id': String(after) },+ signal, redirect: 'error',+ });+ if (response.ok && /^text\/event-stream\b/iu.test(response.headers.get('content-type') ?? '')) return response.body;+ await response.body?.cancel();+ return null;+}++/** The person's running view as a stream source: its loopback origin and its session secret. */+async function viewSource(commonDir) {+ const view = await runningView(0, null) ?? await runningView(0, commonDir);+ if (!view) return null;+ const address = new URL(view.url);+ return { name: `the view on port ${view.port}`, base: address.origin, key: address.searchParams.get('k') };+}++/**+ * The private API source: API v1 itself, on a free loopback port, serving only this board.+ * It starts on first use and stops when watch stops.+ */+function directSource({ mainRoot, config, isMain, runCommand, serveApi }) {+ let api = null;+ return {+ name: 'the board directly',+ async open() {+ api ??= await serveApi({ port: 0, runCommand, isMain, stateDetail: 'summary',+ projects: () => [{ root: mainRoot, name: config.name ?? basename(mainRoot), project: config.project ?? '', added: new Date(0).toISOString() }] });+ const address = new URL(api.url);+ return { base: address.origin, key: address.searchParams.get('k') };+ },+ async close() { if (api) await api.close(); api = null; },+ };+}++/** The short detail of one event: a shout's text, an item's title, or the record's own fields. */+function eventDetail(file, event) {+ let detail = {};+ try { detail = JSON.parse(event.event_detail ?? '{}') ?? {}; } catch { /* An unreadable detail prints as the raw text below. */ detail = { text: event.event_detail }; }+ return readBoard(file, (db) => {+ if (SHOUT_KINDS.has(event.event_kind) && detail.shout) {+ const shout = db.prepare('SELECT shout_to, shout_text FROM shout WHERE shout_id = ?').get(detail.shout);+ return { to: shout?.shout_to ?? detail.to ?? null, text: `to ${shout?.shout_to ?? detail.to}: ${shout?.shout_text ?? ''}` };+ }+ const fields = Object.entries(detail).filter(([name, value]) => name !== 'model' && value !== null && typeof value !== 'object')+ .map(([name, value]) => `${name} ${value}`).join(', ');+ if (event.item_id) {+ const title = db.prepare('SELECT item_title FROM item WHERE item_id = ?').get(event.item_id)?.item_title ?? '';+ return { to: null, text: fields ? `${title} (${fields})` : title };+ }+ return { to: null, text: fields };+ });+}++/**+ * The lane's work as watch --work sees it: the items free to claim, the submissions left waiting+ * for review past the threshold, and when either can next change with no event (a lapsing lease+ * or a submission reaching the threshold).+ */+function laneWork(file, lane, reviewWaitMs, nowMs) {+ return readBoard(file, (db) => {+ const now = new Date(nowMs).toISOString();+ const laneHeld = Boolean(db.prepare('SELECT 1 FROM hold WHERE hold_lane = ?').get(lane));+ const status = new Map(db.prepare('SELECT item_id, item_status FROM item').all().map((row) => [row.item_id, row.item_status]));+ const items = db.prepare('SELECT * FROM item WHERE item_lane = ? ORDER BY item_id').all(lane);+ const claimable = new Map();+ const waiting = new Map();+ const wakes = [];+ for (const item of items) {+ const lapsed = item.item_status === 'claimed' && (item.item_lease_until ?? '') <= now;+ if (item.item_status === 'claimed' && !lapsed && item.item_lease_until) wakes.push(Date.parse(item.item_lease_until));+ const after = item.item_after ? item.item_after.split(',').map(Number) : [];+ if ((item.item_status === 'open' || lapsed) && !laneHeld && !item.item_hold_reason && after.every((id) => status.get(id) === 'verified')) {+ claimable.set(item.item_id, item);+ }+ if (item.item_status !== 'submitted') continue;+ const reviewed = item.item_review_by && (item.item_review_until ?? '') > now;+ if (reviewed) { wakes.push(Date.parse(item.item_review_until)); continue; }+ const submit = db.prepare("SELECT event_id, event_at FROM event WHERE item_id = ? AND event_kind = 'submit' ORDER BY event_id DESC LIMIT 1").get(item.item_id);+ if (!submit) continue;+ const due = Date.parse(submit.event_at) + reviewWaitMs;+ if (due <= nowMs) waiting.set(`${item.item_id}:${submit.event_id}`, { item, since: submit.event_at });+ else wakes.push(due);+ }+ return { claimable, waiting, wake: wakes.filter((at) => at > nowMs).sort((a, b) => a - b)[0] ?? null };+ });+}++/**+ * Follow the board's live events until the signal aborts, printing each one as it arrives.+ * A dropped stream is followed again from the last sequence handled, so nothing is missed or repeated.+ *+ * @param {{ file: string, mainRoot: string, commonDir: string, config: any, isMain: boolean, runCommand: Function,+ * serveApi: Function, options: ReturnType<typeof watchOptions>, start: ReturnType<typeof watchStart>,+ * write: (text: string) => void, note: (text: string) => void, signal: AbortSignal, now?: () => number }} watch+ */+export async function followBoard({ file, mainRoot, commonDir, config, isMain, runCommand, serveApi, options, start, write, note, signal, now = Date.now }) {+ let cursor = options.since ?? start.sequence;+ const direct = directSource({ mainRoot, config, isMain, runCommand, serveApi });+ /** Print one record as a plain line or as one JSON object, immediately. */+ const print = (record) => {+ if (options.json) write(JSON.stringify({ version: 1, ...record }) + '\n');+ else write(`${record.sequence} ${record.kind} ${record.item === null ? '-' : '#' + record.item} ${record.actor ?? '-'} ${oneLine(record.detail)}`.trimEnd() + '\n');+ };+ /** Whether an event passes the --kinds, --item and --to filters. */+ const wanted = (event, to) => (!options.kinds || options.kinds.has(event.event_kind))+ && (options.item === null || event.item_id === options.item)+ && (!options.to || (SHOUT_KINDS.has(event.event_kind) && options.to.has(to)));++ let work = null;+ let mainHead = null;+ let wakeTimer = null;+ /** Recheck the lane's work and main, printing what changed; quiet the first time, when it sets the baseline. */+ const checkWork = async () => {+ if (options.work === null || signal.aborted) return;+ clearTimeout(wakeTimer);+ const current = laneWork(file, options.work, options.reviewWaitMs, now());+ const head = await withGitFacts(() => headCommit(mainRoot));+ if (work) {+ for (const [id, item] of current.claimable) {+ if (!work.claimable.has(id) && (options.item === null || id === options.item)) {+ print({ sequence: cursor, kind: 'claimable', item: id, actor: null, detail: `${options.work}: ${item.item_title}`, notice: true });+ }+ }+ for (const [key, { item, since }] of current.waiting) {+ if (!work.waiting.has(key) && (options.item === null || item.item_id === options.item)) {+ print({ sequence: cursor, kind: 'review-wait', item: item.item_id, actor: item.item_built_by ?? null,+ detail: `${options.work}: ${item.item_title}, waiting for review since ${since}`, since, notice: true });+ }+ }+ if (head !== mainHead && options.item === null) {+ print({ sequence: cursor, kind: 'main', item: null, actor: null, detail: `main moved to ${head ?? 'no commit'}`, commit: head, notice: true });+ }+ }+ work = current;+ mainHead = head;+ if (current.wake !== null) {+ wakeTimer = setTimeout(() => { queue = queue.then(checkWork).catch(fail); }, Math.min(2_147_483_647, Math.max(1, current.wake - now() + 5)));+ }+ };+ let failure = null;+ /** Keep the first failure and stop following. */+ const fail = (error) => { failure ??= error; stopped.abort(); };+ const stopped = new AbortController();+ const both = AbortSignal.any([signal, stopped.signal]);+ // Work checks and printed events share one queue, so their lines never interleave out of order.+ let queue = Promise.resolve();++ let source = null;+ try {+ await checkWork();+ while (!both.aborted) {+ let body = null;+ const view = await viewSource(commonDir).catch(() => null);+ if (view) body = await openStream(view.base, view.key, start.id, cursor, both).catch((error) => { if (both.aborted) throw error; return null; });+ const name = body ? view.name : direct.name;+ if (!body) {+ const own = await direct.open();+ body = await openStream(own.base, own.key, start.id, cursor, both);+ if (!body) throw new Refused('BOARD_UNAVAILABLE', 'this board\'s own event stream did not open; run pullboard doctor, then pullboard watch again');+ }+ if (name !== source) note(`watch: following ${name} after sequence ${cursor}`);+ source = name;+ try {+ for await (const frame of streamFrames(body)) {+ if (frame.name === 'error') throw new Refused(frame.data.error?.code ?? 'BOARD_UNAVAILABLE', frame.data.error?.message ?? 'the live stream stopped; run pullboard watch again');+ const event = frame.data.event;+ if (!event) continue;+ queue = queue.then(async () => {+ if (event.event_kind !== 'changed' && Number.isSafeInteger(event.event_id) && event.event_id > cursor) {+ const detail = eventDetail(file, event);+ if (wanted(event, detail.to)) {+ print({ sequence: event.event_id, kind: event.event_kind, item: event.item_id ?? null, actor: event.event_by ?? null,+ detail: detail.text, at: event.event_at, ...(detail.to ? { to: detail.to } : {}) });+ }+ cursor = event.event_id;+ }+ await checkWork();+ }).catch(fail);+ await queue;+ if (both.aborted) break;+ }+ } catch (error) {+ if (both.aborted) break;+ if (error instanceof Refused) throw error;+ // A dropped connection is followed again below, from the last sequence handled.+ }+ if (!both.aborted) {+ note(`watch: the stream dropped after sequence ${cursor}; following again`);+ source = null;+ await pause(RECONNECT_MS, undefined, { signal: both }).catch(() => {});+ }+ }+ } catch (error) {+ if (!both.aborted) throw error;+ } finally {+ stopped.abort();+ clearTimeout(wakeTimer);+ await queue.catch(() => {});+ await direct.close();+ }+ if (failure) throw failure;+ return 0;+}++/**+ * Run pullboard watch for one checkout until Ctrl-C (SIGINT or SIGTERM), or until `io.signal` aborts.+ * Each line is its own document, so --json never adds an end-of-command envelope.+ */+export async function watchCommand({ io, values, positionals, info, config, file, mainRoot, isMain, runCommand }) {+ if (positionals.length) throw new Refused('USAGE', 'pullboard watch takes flags only, such as pullboard watch --to core; run pullboard help watch');+ const start = watchStart(file);+ const options = watchOptions(values, { config, agents: start.agents });+ const abort = new AbortController();+ const stop = () => abort.abort();+ process.once('SIGINT', stop);+ process.once('SIGTERM', stop);+ io.signal?.addEventListener('abort', stop, { once: true });+ if (io.signal?.aborted) stop();+ io.jsonMode?.(false);+ try {+ return await followBoard({ file, mainRoot, commonDir: info.commonDir, config, isMain, runCommand, serveApi, options, start,+ write: (text) => io.stdout.write(text), note: (text) => io.stderr.write(text + '\n'), signal: abort.signal });+ } finally {+ process.off('SIGINT', stop);+ process.off('SIGTERM', stop);+ io.signal?.removeEventListener('abort', stop);+ }+}diff --git a/test/api.test.js b/test/api.test.jsindex 008edff9..94d99f74 100644--- a/test/api.test.js+++ b/test/api.test.js@@ -920,6 +920,38 @@ test('[A1] long-running servers flush one JSON document before shutdown', asyncassert.deepEqual(parseOneDocument(stdout), document, `${command} does not flush a second document on shutdown`);}});+test('[A1,A2] watch --json prints one catalog document per event line', async (t) => {+ const box = project();+ t.after(() => rmSync(box.dir, { recursive: true, force: true }));+ const child = spawn(process.execPath, [BIN, 'watch', '--json', '--kinds', 'shout'], { cwd: box.repo, env: box.env, stdio: ['ignore', 'pipe', 'pipe'] });+ const closed = once(child, 'close');+ t.after(() => { if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL'); });+ let stdout = '';+ let stderr = '';+ child.stdout.setEncoding('utf8');+ child.stderr.setEncoding('utf8');+ let changed = () => {};+ child.stdout.on('data', (part) => { stdout += part; changed(); });+ child.stderr.on('data', (part) => { stderr += part; changed(); });+ /** Resolve once `read()` holds what the step waits for, or fail at the hang ceiling. */+ const until = (read, label) => new Promise((resolveWait, rejectWait) => {+ const timer = setTimeout(() => rejectWait(new Error(`watch printed no ${label}\nstdout: ${stdout}\nstderr: ${stderr}`)), 10_000); // budget: hang ceiling for private CLI startup and one line, not a latency claim.+ changed = () => { if (read()) { clearTimeout(timer); changed = () => {}; resolveWait(); } };+ changed();+ });+ await until(() => /following/u.test(stderr), 'start note');+ json(box, box.repo, 'shout', ['app', 'catalog watch line']);+ await until(() => stdout.includes('\n'), 'event line');+ const document = JSON.parse(stdout.split('\n')[0]);+ assert.equal(document.version, 1);+ assertRequiredShape(document, shapeFor('watch').required, 'watch');+ assert.equal(document.detail, 'to app: catalog watch line');+ child.kill('SIGTERM');+ const [code] = await closed;+ assert.equal(code, 0);+ assert.equal(stdout, `${JSON.stringify(document)}\n`, 'watch prints no end-of-command document');+});+test('[A1,A10] view exports a static folder through its JSON variant', () => {const box = project();const item = json(box, box.repo, 'add', ['app', 'Snapshot item', '--specs', 'G1']).item;diff --git a/test/watch.test.js b/test/watch.test.jsnew file mode 100644index 00000000..498cdd01--- /dev/null+++ b/test/watch.test.js@@ -0,0 +1,336 @@+/** pullboard watch follows the board's live event stream, from a real CLI on a real board [A2,N26]. */+import assert from 'node:assert/strict';+import { once } from 'node:events';+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { delimiter, join, resolve } from 'node:path';+import { DatabaseSync } from 'node:sqlite';+import { after, test } from 'node:test';+import { runFixtureChild, runFixtureGit, startFixtureChild } from './fixture-child.js';++const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');+const folders = [];++after(() => {+ for (const folder of folders) rmSync(folder, { recursive: true, force: true });+});++/** A clean environment for fixture Git and CLI children: no inherited GIT_* or relay token. */+function fixtureEnv(home, bin) {+ const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith('GIT_') && !name.startsWith('PULLBOARD_')));+ return {+ ...env, HOME: home, PULLBOARD_HOME: home, PULLBOARD_MACHINE_HOME: home, PATH: bin + delimiter + process.env.PATH,+ GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',+ GIT_AUTHOR_NAME: 'Watch Test', GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Watch Test', GIT_COMMITTER_EMAIL: '[email protected]',+ };+}++/** A private Git repo with an initialized board, two lanes and a gate that passes. */+function project() {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-watch-')));+ folders.push(dir);+ const root = join(dir, 'repo');+ const home = join(dir, 'home');+ const bin = join(dir, 'bin');+ for (const folder of [root, home, bin]) mkdirSync(folder);+ writeFileSync(join(bin, 'pullboard'), `#!/bin/sh\nexec '${process.execPath}' '${BIN}' "$@"\n`);+ chmodSync(join(bin, 'pullboard'), 0o755);+ const env = fixtureEnv(home, bin);+ const git = (...args) => runFixtureGit(args, { cwd: root, env, encoding: 'utf8', stdio: 'pipe' }).toString().trim();+ const run = (cwd, ...args) => runFixtureChild(process.execPath, [BIN, ...args], { cwd, env, encoding: 'utf8' });+ /** Run one CLI command with --json and return its document. */+ const cli = (cwd, ...args) => {+ const result = run(cwd, ...args, '--json');+ assert.equal(result.status, 0, `${args.join(' ')}: ${result.stderr}${result.stdout}`);+ return JSON.parse(result.stdout);+ };+ git('init', '-q', '-b', 'main');+ cli(root, 'init');+ const configFile = join(root, 'pullboard.json');+ const config = JSON.parse(readFileSync(configFile, 'utf8'));+ writeFileSync(configFile, JSON.stringify({ ...config, gate: 'true', spec: 'SPEC.md', practice: 'DOCTRINE.md',+ lanes: { app: { owns: ['app/'], specs: ['G1'] }, docs: { owns: ['docs/'], specs: ['G1'] } }, shared: [] }, null, 2) + '\n');+ writeFileSync(join(root, 'SPEC.md'), '# Watch fixture\n\n## Goals\n- G1 [approved, must] Keep the board. | gate: true\n');+ writeFileSync(join(root, 'DOCTRINE.md'), '');+ git('add', '-A');+ git('commit', '-q', '-m', 'chore: watch fixture');+ return { dir, root, home, env, git, run, cli };+}++/** Read the fixture board's events straight from its SQLite file, read-only. */+function events(box) {+ const db = new DatabaseSync(join(box.root, '.git', 'pullboard', 'board.sqlite'), { readOnly: true });+ try { return db.prepare('SELECT event_id, event_kind, item_id, event_by FROM event ORDER BY event_id').all(); }+ finally { db.close(); }+}++/** The latest event sequence on the fixture board. */+function lastSequence(box) {+ return events(box).at(-1)?.event_id ?? 0;+}++/**+ * Start the real CLI's watch as a child. Each test waits on it with a deadline and stops it by its+ * own pid, so a watch that never prints fails the test instead of hanging it.+ */+function startWatch(box, args, { cwd = box.root } = {}) {+ const child = startFixtureChild(process.execPath, [BIN, 'watch', ...args], { cwd, env: box.env, stdio: ['ignore', 'pipe', 'pipe'] });+ const out = { lines: [], waiters: [], buffer: '' };+ const err = { lines: [], waiters: [], buffer: '' };+ /** Keep complete lines and hand each to the waiter whose test it passes. */+ const feed = (stream, part) => {+ stream.buffer += part;+ let end;+ while ((end = stream.buffer.indexOf('\n')) >= 0) {+ const line = stream.buffer.slice(0, end);+ stream.buffer = stream.buffer.slice(end + 1);+ stream.lines.push({ line, at: Date.now() });+ for (const waiter of [...stream.waiters]) {+ if (waiter.match(line)) { stream.waiters.splice(stream.waiters.indexOf(waiter), 1); waiter.found({ line, at: Date.now() }); }+ }+ }+ };+ child.stdout.setEncoding('utf8');+ child.stderr.setEncoding('utf8');+ child.stdout.on('data', (part) => feed(out, part));+ child.stderr.on('data', (part) => feed(err, part));+ const closed = once(child, 'close');+ /** Wait for the first line, already printed or still to come, that passes `match`. */+ const waitFor = (stream, match, ms, label) => {+ const seen = stream.lines.find(({ line }) => match(line));+ if (seen) return Promise.resolve(seen);+ return new Promise((found, failed) => {+ const waiter = { match, found: (value) => { clearTimeout(timer); found(value); } };+ const timer = setTimeout(() => {+ stream.waiters.splice(stream.waiters.indexOf(waiter), 1);+ failed(new Error(`watch printed no ${label} within ${ms} ms\nstdout:\n${out.lines.map((entry) => entry.line).join('\n')}\nstderr:\n${err.lines.map((entry) => entry.line).join('\n')}`));+ }, ms);+ stream.waiters.push(waiter);+ });+ };+ return {+ child,+ out,+ err,+ line: (match, ms, label) => waitFor(out, match, ms, label),+ note: (match, ms, label) => waitFor(err, match, ms, label),+ /** Stop this watch by its own pid, and kill it if it does not stop. */+ async stop(signal = 'SIGINT') {+ if (child.exitCode !== null || child.signalCode !== null) return { code: child.exitCode, signal: child.signalCode };+ child.kill(signal);+ const force = setTimeout(() => child.kill('SIGKILL'), 5_000); // budget: hang ceiling for a stopping child, not a latency claim.+ try { const [code, killed] = await closed; return { code, signal: killed }; } finally { clearTimeout(force); }+ },+ };+}++test('pullboard watch prints a move as it happens [A2,N26]', async (t) => {+ const box = project();+ assert.equal(readdirSync(box.home).some((name) => /^view(?:-\d+)?\.json$/u.test(name)), false, 'no view runs for this board');+ const before = events(box).length;+ const watch = startWatch(box, []);+ t.after(() => watch.stop('SIGKILL'));+ await watch.note((line) => /following the board directly/u.test(line), 10_000, 'note that it follows the board directly'); // budget: hang ceiling for CLI startup, not a latency claim.++ const added = box.cli(box.root, 'add', 'app', 'Live watch item', '--criterion', 'arrives on the live stream', '--specs', 'G1').item;+ const moved = Date.now();+ const event = events(box).at(-1);+ assert.equal(event.item_id, added.item_id);+ const printed = await watch.line((line) => line.startsWith(`${event.event_id} `), 2_000, 'line for the add'); // budget: declared by #544's frozen criterion (within two seconds); a hang ceiling for one line.+ assert.ok(printed.at - moved <= 2_000, 'the line arrives within two seconds of the move'); // budget: declared by #544's frozen criterion (within two seconds).+ assert.equal(printed.line, `${event.event_id} add #${added.item_id} ${event.event_by} Live watch item (lane app, route strong)`,+ 'one line: sequence, kind, item, actor and a short detail');++ const stopped = await watch.stop('SIGINT');+ assert.deepEqual(stopped, { code: 0, signal: null }, 'Ctrl-C stops watch cleanly');+ assert.equal(watch.out.lines.length, 1, 'one line per event, and nothing else on stdout');+ assert.equal(events(box).length, before + 1, 'watch wrote no event: the only new one is the add');+});++test('a dropped watch resumes from its last event [A2,N26]', async (t) => {+ const box = project();+ const view = startFixtureChild(process.execPath, [BIN, 'view', '--no-open', '--port', '0', '--json'],+ { cwd: box.root, env: { ...box.env, PULLBOARD_VIEW_FOREGROUND: '1' }, stdio: ['ignore', 'pipe', 'pipe'] });+ const viewClosed = once(view, 'close');+ t.after(() => { if (view.exitCode === null && view.signalCode === null) view.kill('SIGKILL'); });+ let viewOut = '';+ view.stdout.setEncoding('utf8');+ const viewReady = new Promise((ready, failed) => {+ const timer = setTimeout(() => failed(new Error(`the view did not start: ${viewOut}`)), 10_000); // budget: hang ceiling for view startup, not a latency claim.+ view.stdout.on('data', (part) => {+ viewOut += part;+ try { const document = JSON.parse(viewOut); clearTimeout(timer); ready(document); } catch { /* The document is pretty-printed; wait for the rest. */ }+ });+ });+ const { port } = await viewReady;++ const before = events(box).length;+ const watch = startWatch(box, ['--json', '--kinds', 'shout']);+ t.after(() => watch.stop('SIGKILL'));+ await watch.note((line) => line.includes(`following the view on port ${port}`), 10_000, 'note that it follows the view'); // budget: hang ceiling for CLI startup, not a latency claim.++ box.cli(box.root, 'shout', 'app', 'first, through the view');+ const first = events(box).at(-1);+ await watch.line((line) => JSON.parse(line).sequence === first.event_id, 5_000, 'first shout'); // budget: hang ceiling for one line, not a latency claim.++ // Stop the view by its own pid: its stream ends, and watch must carry on from its last event.+ view.kill('SIGTERM');+ await viewClosed;+ box.cli(box.root, 'shout', 'app', 'second, while the stream was down');+ const second = events(box).at(-1);+ await watch.note((line) => /following the board directly/u.test(line), 10_000, 'note that it follows the board directly'); // budget: hang ceiling for reconnecting, not a latency claim.+ box.cli(box.root, 'shout', 'all', 'third, after the stream came back');+ const third = events(box).at(-1);+ await watch.line((line) => JSON.parse(line).sequence === third.event_id, 5_000, 'third shout'); // budget: hang ceiling for one line, not a latency claim.++ assert.deepEqual(await watch.stop('SIGTERM'), { code: 0, signal: null });+ const printed = watch.out.lines.map(({ line }) => JSON.parse(line));+ assert.deepEqual(printed.map((record) => record.sequence), [first.event_id, second.event_id, third.event_id],+ 'each shout once, in order: nothing missed while the stream was down and nothing repeated');+ assert.deepEqual(printed.map((record) => record.detail),+ ['to app: first, through the view', 'to app: second, while the stream was down', 'to all: third, after the stream came back']);+ for (const record of printed) {+ assert.equal(record.version, 1);+ assert.equal(record.kind, 'shout');+ assert.equal(record.item, null);+ assert.equal(record.actor, 'coordinator');+ }+ assert.equal(events(box).length, before + 3, 'watch wrote no event: the only new ones are the three shouts');+});++test('watch --work announces a claimable item and a review left waiting [A2,N26]', async (t) => {+ const box = project();+ const builder = box.cli(box.root, 'worktree', 'app', '--model', 'watch-builder');+ const waiting = box.cli(box.root, 'add', 'app', 'Waits on another item', '--criterion', 'waits', '--specs', 'G1', '--check', 'true').item;+ const before = events(box).length;+ const watch = startWatch(box, ['--json', '--work', 'app', '--review-wait', '0.02']);+ t.after(() => watch.stop('SIGKILL'));+ await watch.note((line) => /following the board directly/u.test(line), 10_000, 'note that it follows the board directly'); // budget: hang ceiling for CLI startup, not a latency claim.+ assert.equal(watch.out.lines.length, 0, 'work already claimable when watch starts is its baseline, so it prints nothing');++ // A newly opened item in the lane is claimable.+ const added = box.cli(box.root, 'add', 'app', 'Fresh app work', '--criterion', 'claimable', '--specs', 'G1', '--check', 'true').item;+ const notice = JSON.parse((await watch.line((line) => JSON.parse(line).kind === 'claimable', 5_000, 'claimable notice')).line); // budget: hang ceiling for one line, not a latency claim.+ assert.equal(notice.item, added.item_id);+ assert.equal(notice.notice, true);+ assert.equal(notice.detail, 'app: Fresh app work');+ assert.equal(notice.sequence, lastSequence(box), 'a notice carries the sequence it follows');+ const blocked = box.cli(box.root, 'add', 'app', 'Waits for the fresh work', '--criterion', 'after', '--specs', 'G1', '--after', String(added.item_id)).item;++ // A released claim makes the item claimable again.+ box.cli(builder.path, 'claim', String(waiting.item_id));+ box.cli(builder.path, 'release', String(waiting.item_id));+ const released = JSON.parse((await watch.line((line) => JSON.parse(line).kind === 'claimable' && JSON.parse(line).item === waiting.item_id, 5_000, 'claimable notice after release')).line); // budget: hang ceiling for one line, not a latency claim.+ assert.equal(released.detail, 'app: Waits on another item');++ // A submission nobody reserves is announced once it has waited past --review-wait (1.2 s here).+ box.cli(builder.path, 'claim', String(added.item_id));+ mkdirSync(join(builder.path, 'app'), { recursive: true });+ writeFileSync(join(builder.path, 'app', 'work.txt'), 'built\n');+ runFixtureGit(['add', '-A'], { cwd: builder.path, env: box.env, stdio: 'pipe' });+ runFixtureGit(['commit', '-q', '-m', 'feat(app): fresh work [G1]'], { cwd: builder.path, env: box.env, stdio: 'pipe' });+ const firstCommit = box.cli(builder.path, 'submit', String(added.item_id)).commit;+ const submitted = lastSequence(box);+ const review = JSON.parse((await watch.line((line) => JSON.parse(line).kind === 'review-wait', 10_000, 'review-wait notice')).line); // budget: hang ceiling for a 1.2 s review threshold, not a latency claim.+ assert.equal(review.item, added.item_id);+ assert.match(review.detail, /^app: Fresh app work, waiting for review since /u);+ assert.equal(lastSequence(box), submitted, 'the threshold woke watch with no new board event');++ // Accepting the work an item waits on makes that item claimable.+ const reviewer = join(box.dir, 'reviewer');+ box.git('worktree', 'add', '-q', '--detach', reviewer, firstCommit);+ box.cli(reviewer, 'join', 'docs', '--model', 'watch-reviewer');+ box.cli(reviewer, 'next', '--verify', String(added.item_id));+ box.cli(reviewer, 'verify', String(added.item_id), 'accept', '--note', 'read the fixture file');+ const unblocked = JSON.parse((await watch.line((line) => JSON.parse(line).kind === 'claimable' && JSON.parse(line).item === blocked.item_id, 5_000, 'claimable notice after its wait was verified')).line); // budget: hang ceiling for one line, not a latency claim.+ assert.equal(unblocked.detail, 'app: Waits for the fresh work');++ // A rejected submission is claimable again.+ box.cli(builder.path, 'claim', String(waiting.item_id));+ writeFileSync(join(builder.path, 'app', 'waiting.txt'), 'built\n');+ runFixtureGit(['add', '-A'], { cwd: builder.path, env: box.env, stdio: 'pipe' });+ runFixtureGit(['commit', '-q', '-m', 'feat(app): waiting work [G1]'], { cwd: builder.path, env: box.env, stdio: 'pipe' });+ const secondCommit = box.cli(builder.path, 'submit', String(waiting.item_id)).commit;+ runFixtureGit(['switch', '-q', '--detach', secondCommit], { cwd: reviewer, env: box.env, stdio: 'pipe' });+ box.cli(reviewer, 'next', '--verify', String(waiting.item_id));+ box.cli(reviewer, 'verify', String(waiting.item_id), 'reject', '--reason', 'TEST_FAILURE', '--note', 'the fixture sends it back');+ const rejected = watch.out.lines.filter(({ line }) => JSON.parse(line).kind === 'claimable' && JSON.parse(line).item === waiting.item_id).length;+ await watch.line((line) => JSON.parse(line).kind === 'reject', 5_000, 'reject line'); // budget: hang ceiling for one line, not a latency claim.+ const again = await watch.line((line) => JSON.parse(line).kind === 'claimable' && JSON.parse(line).item === waiting.item_id+ && watch.out.lines.filter((entry) => JSON.parse(entry.line).kind === 'claimable' && JSON.parse(entry.line).item === waiting.item_id).length > rejected, 5_000, 'claimable notice after reject'); // budget: hang ceiling for one line, not a latency claim.+ assert.equal(JSON.parse(again.line).detail, 'app: Waits on another item');++ // Main moving is a notice too.+ box.git('commit', '-q', '--allow-empty', '-m', 'chore: move main');+ const head = box.git('rev-parse', 'HEAD');+ const main = JSON.parse((await watch.line((line) => JSON.parse(line).kind === 'main', 5_000, 'main notice')).line); // budget: hang ceiling for one line, not a latency claim.+ assert.equal(main.commit, head);+ assert.equal(main.detail, `main moved to ${head}`);++ assert.deepEqual(await watch.stop('SIGINT'), { code: 0, signal: null });+ const kinds = watch.out.lines.map(({ line }) => JSON.parse(line).kind);+ assert.equal(watch.out.lines.filter(({ line }) => JSON.parse(line).kind === 'review-wait' && JSON.parse(line).item === added.item_id).length, 1,+ 'a waiting review is announced once');+ assert.ok(kinds.includes('accept') && kinds.includes('reject'), 'the verdicts print as events too');+ const moves = events(box).slice(before).map((event) => event.event_kind);+ assert.deepEqual(moves, ['add', 'add', 'claim', 'release', 'claim', 'submit', 'join', 'reserve', 'accept', 'claim', 'submit', 'reserve', 'reject'],+ 'watch wrote no event: the new ones are exactly the moves this test made');+});++test('watch filters by kind, item and addressee, and refuses a flag it cannot follow [A2]', async (t) => {+ const box = project();+ const other = box.cli(box.root, 'add', 'docs', 'Docs item', '--criterion', 'docs', '--specs', 'G1').item;+ const watch = startWatch(box, ['--json', '--to', 'app']);+ t.after(() => watch.stop('SIGKILL'));+ const items = startWatch(box, ['--kinds', 'edit', '--item', String(other.item_id)]);+ t.after(() => items.stop('SIGKILL'));+ await watch.note((line) => /following/u.test(line), 10_000, 'start note'); // budget: hang ceiling for CLI startup, not a latency claim.+ await items.note((line) => /following/u.test(line), 10_000, 'start note'); // budget: hang ceiling for CLI startup, not a latency claim.++ box.cli(box.root, 'shout', 'docs', 'for docs only');+ box.cli(box.root, 'add', 'app', 'App item', '--criterion', 'app', '--specs', 'G1');+ box.cli(box.root, 'shout', 'app', 'for app');+ box.cli(box.root, 'edit', String(other.item_id), '--brief', 'Docs brief');+ box.cli(box.root, 'shout', 'all', 'for everyone');+ const last = lastSequence(box);+ await watch.line((line) => JSON.parse(line).sequence === last, 5_000, 'shout to all'); // budget: hang ceiling for one line, not a latency claim.+ const edit = events(box).find((event) => event.event_kind === 'edit');+ await items.line((line) => line.startsWith(`${edit.event_id} edit #${other.item_id} `), 5_000, 'edit line'); // budget: hang ceiling for one line, not a latency claim.+ assert.deepEqual(await watch.stop(), { code: 0, signal: null });+ assert.deepEqual(await items.stop(), { code: 0, signal: null });+ assert.deepEqual(watch.out.lines.map(({ line }) => JSON.parse(line).detail), ['to app: for app', 'to all: for everyone'],+ '--to app takes shouts to app and to all, and nothing else');+ assert.deepEqual(watch.out.lines.map(({ line }) => JSON.parse(line).to), ['app', 'all']);+ assert.equal(items.out.lines.length, 1, '--kinds and --item keep only that item\'s edits');++ for (const [args, pattern] of [[['--to', 'nobody'], /--to needs an agent id, a lane or all/u], [['--work', 'nowhere'], /--work needs a lane/u],+ [['--review-wait', '5'], /--review-wait goes with --work/u], [['--since', 'later'], /--since needs the last sequence/u], [['extra'], /takes flags only/u]]) {+ const refused = box.run(box.root, 'watch', ...args, '--json');+ assert.equal(refused.status, 1, `${args.join(' ')}: ${refused.stdout}${refused.stderr}`);+ const { error } = JSON.parse(refused.stdout);+ assert.equal(error.code, 'USAGE');+ assert.match(error.message, pattern);+ assert.ok(error.next, 'the refusal names a next step');+ }+});++test('help watch and the generated agent instructions teach seats to listen with watch [A2,I11]', async () => {+ const box = project();+ const help = box.run(box.root, 'help', 'watch');+ assert.equal(help.status, 0, help.stderr);+ const lines = help.stdout.trimEnd().split('\n');+ const example = lines.indexOf('Example:');+ assert.deepEqual(lines.slice(example + 2), [+ 'Claude Code: run pullboard watch --to <your id> under the Monitor tool, and each event line wakes the seat.',+ 'Any other harness: run it as a long-running command and treat each stdout line as an event.',+ ], 'two lines after the example: the Claude Code way and the way for any other harness');+ const { agentsBlock } = await import('../src/templates.js');+ const listen = agentsBlock().split('\n').find((line) => line.startsWith('**Listen.**'));+ assert.ok(listen, 'the AGENTS.md that init writes has a Listen paragraph');+ assert.match(listen, /run `pullboard watch --to <your id>` there/u);+ assert.match(listen, /read `pullboard inbox` at session start, after submit and before ending a turn/u);+ assert.match(listen, /Coordinator answers and sentinel findings arrive there/u);+ const written = readFileSync(join(box.root, 'AGENTS.md'), 'utf8');+ assert.ok(written.includes(listen), 'pullboard init wrote that paragraph into the repo');+});