Skip to content

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.

feat(why): decisions record their origin; why names a file [N29]

Corey Olson2fcf755a9b7a
diff --git a/docs/formats.md b/docs/formats.md
index 30e0ae3f..9fe1cbd7 100644
--- a/docs/formats.md
+++ b/docs/formats.md
@@ -453,7 +453,7 @@ The `event` table is a SQLite schema object governed by `SCHEMA_VERSION`; its ap
| `sentinel-run` | running agent | `name`, `digest`, `run`, `result`, `engine` |
| `sentinel-failure` | sentinel | `name`, `digest`, `run`, `cause`, `engine` |
| `pass` | coordinator | `shout`, `to`, `decision`, `request`, `answers` |
-| `answer` | answerer | `shout`, `to`, `decision`, `request`, `answers`, `outcome`, `channel`, engine-20 `implies`, `supersedes` |
+| `answer` | answerer | `shout`, `to`, `decision`, `request`, `answers`, `outcome`, `channel`, engine-20 `implies`, `supersedes`, decision-origin `provenance` |
| `row_decision` | person | `record`, `channel` |
| `row_draft` | builder, or rigor | engine-55 `row`, `written` |
| `flake-observation` | reporting agent | engine-59 `engine`, `observation` |
@@ -571,6 +571,8 @@ Landing queue grants, first queue entries and releases are shared ordered transi
Engine 93 adds item-addressed shouts. A shout move's optional `item` names an existing item; its event belongs to that item and includes the message text. Its canonical `shout_to` is `item:<id>`, read by the item's current builder and reviewer and the coordinator. Inbox, resume and seat watch use the same audience; an explicit seat or lane destination with `--item` still uses the item's audience. An item decision is answerable by its current participants or coordinator; replies stay in its thread and audience. The coordinator can still pass it to the person through the existing decision flow. A registered seat's shout to `all` is accepted and stored at reserved address `coordinator+person`, read only by coordination audiences. The plus sign cannot occur in valid lane names or their derived seat ids. Coordinator and person broadcasts retain `all` and reach everyone; recorded older-engine `all` rows retain their original global meaning without a retrospective sender filter. Main-checkout watch remains the person's board-wide observer. A joined seat's default watch filters shouts to its own address, lane, items and `all`, while ordinary lifecycle events remain visible.
+The decision-origin engine, numbered at landing, records where an answered decision came from. An `answerDecision` move may carry `origin` (`person-relayed`, `agent` or `inherited`) and `rationale`; either makes it a move of this engine, and an older engine refuses it with `RELAY_MOVE` before changing its board or cursor. From this engine every answer event also records `provenance: {statement, rationale, decidedBy, relayedBy, origin}`. The board sets it, not the caller: a real person answer is `person`, an agent that names no origin is `agent`, and `relayedBy` is the answering seat only for `person-relayed`. An agent naming `person` is refused with `BAD_ORIGIN`. An answer recorded before this engine has no provenance and reads as `unknown`, never as the person's. `pullboard why <file>[:<line>]` lists the items, spec rows and answered decisions behind the landed commits that touched that file or line, found by their `Pullboard-Item: #N` trailers.
+
### Outside intake and sandbox receipts
`pullboard intake <GitHub PR URL> --criterion "behavior" --check "command"`
diff --git a/src/api-moves.js b/src/api-moves.js
index 6e924741..f34ad421 100644
--- a/src/api-moves.js
+++ b/src/api-moves.js
@@ -24,7 +24,7 @@ const MOVES = {
escalate: { item: true, flags: ['note'] },
hold: { positions: ['lane'], flags: ['reason'], booleans: ['off'] },
shout: { positions: ['to', 'text'], optional: ['to'], booleans: ['decision'], flags: ['evidence', 'outcome', 'item', 'commit'] },
- answer: { item: true, positions: ['text'], flags: ['as', 'implies', 'supersedes'] },
+ answer: { item: true, positions: ['text'], flags: ['as', 'implies', 'supersedes', 'origin', 'rationale'] },
pass: { item: true, positions: ['note'] },
next: { flags: ['as'], booleans: ['verify', 'build'] },
};
diff --git a/src/board.js b/src/board.js
index 79f49d64..1cf6811e 100644
--- a/src/board.js
+++ b/src/board.js
@@ -1,3 +1,4 @@
+import { answerProvenance } from './decision-origin.js';
import { ensureProofCounters } from './proof-counters.js';
import { correctedNoVerdictReopen } from './reopen-history.js';
import {
@@ -1772,10 +1773,10 @@ export function passDecision(board, id, { agentId, note, lanes }) {
*
* @param {any} board
* @param {number} id
- * @param {{ agentId: string, text: string, lanes: string[], asPerson?: boolean, channel?: 'terminal' | 'view', implies?: number[], supersedes?: number | null, impliesId?: string }} options - implies and supersedes tell items (B29,B31)
+ * @param {{ agentId: string, text: string, lanes: string[], asPerson?: boolean, channel?: 'terminal' | 'view', implies?: number[], supersedes?: number | null, impliesId?: string, origin?: string, rationale?: string }} options - implies and supersedes tell items (B29,B31); origin and rationale record where the decision came from (N29)
* @returns {number}
*/
-export function answerDecision(board, id, { agentId, text, lanes, asPerson = false, channel = 'terminal', implies, supersedes = null, impliesId }) {
+export function answerDecision(board, id, { agentId, text, lanes, asPerson = false, channel = 'terminal', implies, supersedes = null, impliesId, origin, rationale }) {
return atomic(board, () => {
const ask = getShout(board, id);
if (ask.shout_request) {
@@ -1798,7 +1799,8 @@ export function answerDecision(board, id, { agentId, text, lanes, asPerson = fal
throw new Refused('NOT_YOUR_DECISION', `shout #${id} is addressed to ${ask.shout_to}, not ${lane} (agent ${agentId})`);
}
const from = personAnswer ? PERSON : agentId;
- const answerId = tellAnswerImplications(board, (by, itemId, fact) => logEvent(board, by, 'fact', itemId, fact), insertShout(board, { from, to: ask.shout_from, text, lanes, answers: id, channel, ...(addressedItem === null ? {} : { item: addressedItem }), detail: { ...(implies?.length ? { implies } : {}), ...(supersedes !== null ? { supersedes } : {}) } }), { seed: impliesId, implies, supersedes, from, person: PERSON });
+ const provenance = answerProvenance(board, { agentId, asPerson: personAnswer, text, origin, rationale });
+ const answerId = tellAnswerImplications(board, (by, itemId, fact) => logEvent(board, by, 'fact', itemId, fact), insertShout(board, { from, to: ask.shout_from, text, lanes, answers: id, channel, ...(addressedItem === null ? {} : { item: addressedItem }), detail: { ...(implies?.length ? { implies } : {}), ...(supersedes !== null ? { supersedes } : {}), ...(provenance ? { provenance } : {}) } }), { seed: impliesId, implies, supersedes, from, person: PERSON });
if (personAnswer && ask.shout_answers !== null) {
const original = getShout(board, ask.shout_answers);
insertShout(board, { from: PERSON, to: original.shout_from, text: `Person answered #${id}: ${String(text).trim()}`, lanes, answers: original.shout_id, channel, ...(shoutItemId(original.shout_to) === null ? {} : { item: shoutItemId(original.shout_to) }) });
diff --git a/src/cli-main.js b/src/cli-main.js
index 0bad3f05..6fd8ed4d 100644
--- a/src/cli-main.js
+++ b/src/cli-main.js
@@ -130,6 +130,8 @@ const OPTIONS = {
commit: { type: 'string' },
ref: { type: 'string' },
supersedes: { type: 'string' },
+ origin: { type: 'string' },
+ rationale: { type: 'string' },
conflict: { type: 'string', multiple: true },
'withdraw-verdict': { type: 'boolean' },
cause: { type: 'string' },
diff --git a/src/commands/answer.js b/src/commands/answer.js
index a2bc2abe..26809178 100644
--- a/src/commands/answer.js
+++ b/src/commands/answer.js
@@ -26,7 +26,8 @@ export async function run(io, { first, second, rest, values }) {
const implies = parseImplies(values.implies);
const supersedes = values.supersedes === undefined ? undefined : idArg(String(values.supersedes).replace(/^#/u, ''));
const id = await ordered(ctx, board, 'answerDecision', [idArg(first), { agentId: me.id, text: [second, ...rest].filter(Boolean).join(' '), lanes: laneNames(ctx.config), asPerson, channel: ctx.io.personChannel ?? 'terminal',
- ...(implies ? { implies } : {}), ...(supersedes ? { supersedes } : {}) }]);
+ ...(implies ? { implies } : {}), ...(supersedes ? { supersedes } : {}),
+ ...(values.origin === undefined ? {} : { origin: values.origin }), ...(values.rationale === undefined ? {} : { rationale: values.rationale }) }]);
const ask = store.getShout(board, idArg(first));
io.result?.({ id, answers: ask.shout_id });
if (asPerson) {
diff --git a/src/commands/why.js b/src/commands/why.js
index 66128898..c77d07a3 100644
--- a/src/commands/why.js
+++ b/src/commands/why.js
@@ -4,6 +4,7 @@ import {
decisionsImplying,
whyLine,
} from '../implies.js';
+import { whyFile } from '../why-file.js';
import {
Refused,
} from '../refused.js';
@@ -15,8 +16,9 @@ import {
/** Run `pullboard why` and return its exit code. */
export function run(io, { first, second, rest }) {
- if (!first || second || rest.length) throw new Refused('USAGE', 'pullboard why <id>: the decisions that imply an item, newest first');
+ if (!first || second || rest.length) throw new Refused('USAGE', 'pullboard why <id> | <file>[:<line>]: the decisions that imply an item, or sit behind a file, newest first');
const ctx = context(io);
+ if (!/^#?[1-9]\d*$/u.test(first)) return runFile(io, ctx, first);
const id = idArg(first);
const decisions = withBoard(ctx, (board) => decisionsImplying(store.itemThread(board, id)));
io.result?.({ id, decisions });
@@ -24,3 +26,18 @@ export function run(io, { first, second, rest }) {
for (const entry of decisions) io.say(whyLine(entry));
return 0;
}
+
+/** Print the items, rows and decisions behind a file or line, each decision with its origin [N29]. */
+function runFile(io, ctx, target) {
+ const found = withBoard(ctx, (board) => whyFile(board, ctx.info.root, target));
+ io.result?.(found);
+ const where = found.line === null ? found.file : `${found.file}:${found.line}`;
+ if (!found.items.length) io.say(`no landed commit that names an item touched ${where}`);
+ for (const item of found.items) io.say(`item #${item.id} (${item.status}): ${item.title}`);
+ for (const row of found.rows) io.say(`row ${row.id}, served by ${row.items.map((id) => `#${id}`).join(', ')}`);
+ for (const entry of found.decisions) {
+ const relay = entry.relayedBy ? `, relayed by ${entry.relayedBy}` : '';
+ io.say(`decision #${entry.id} [${entry.origin}] by ${entry.decidedBy}${relay}: ${entry.statement.split('\n')[0]}${entry.rationale ? ` (because ${entry.rationale})` : ''}`);
+ }
+ return 0;
+}
diff --git a/src/decision-origin-engine.js b/src/decision-origin-engine.js
new file mode 100644
index 00000000..51e04b3e
--- /dev/null
+++ b/src/decision-origin-engine.js
@@ -0,0 +1,4 @@
+/** The first engine whose answers record a decision's origin, rationale and relayer (#970). */
+import { unassignedEngine } from './engine-next.js';
+
+export const DECISION_ORIGIN_ENGINE = unassignedEngine();
diff --git a/src/decision-origin.js b/src/decision-origin.js
new file mode 100644
index 00000000..8c0d182d
--- /dev/null
+++ b/src/decision-origin.js
@@ -0,0 +1,87 @@
+/**
+ * Where a decision came from: its statement, rationale, who decided, who relayed it and its origin [N29,B29,P6].
+ *
+ * The record lives in the answer's own event, so no schema changes. Only the board decides the person
+ * origin: a real person answer carries it, and no caller can name it, so an agent's word is never shown
+ * as the person's (P6). A decision with no recorded origin reads as unknown, never as the person's.
+ */
+import { DECISION_ORIGIN_ENGINE } from './decision-origin-engine.js';
+import { ENGINE_VERSION } from './engine-metadata.js';
+import { Refused } from './refused.js';
+
+/** The origins an agent may name; `person` is reserved for a real person answer. */
+export const NAMEABLE_ORIGINS = Object.freeze(['person-relayed', 'agent', 'inherited']);
+
+/**
+ * True when an answer move carries this engine's meaning, so older engines refuse it.
+ *
+ * @param {any[]} args the sealed move arguments
+ * @returns {boolean}
+ */
+export function carriesOrigin(args) {
+ const options = args?.[1];
+ return Boolean(options && typeof options === 'object' && (options.origin !== undefined || options.rationale !== undefined));
+}
+
+/**
+ * Build the provenance an answer records, or null on a board replaying an older engine.
+ *
+ * @param {any} board
+ * @param {{ agentId: string, asPerson: boolean, text: string, origin?: string, rationale?: string }} answer
+ * @returns {{ statement: string, rationale: string, decidedBy: string, relayedBy: string | null, origin: string } | null}
+ */
+export function answerProvenance(board, { agentId, asPerson, text, origin, rationale }) {
+ const engine = board.executionEngineVersion ?? ENGINE_VERSION;
+ const named = origin !== undefined && origin !== null;
+ const reason = String(rationale ?? '').trim();
+ if (engine < DECISION_ORIGIN_ENGINE) {
+ if (named || reason) throw new Refused('ENGINE_VERSION', `recording an origin or a rationale requires engine ${DECISION_ORIGIN_ENGINE}; this board uses engine ${engine}; upgrade Pullboard first`);
+ return null;
+ }
+ if (named && !NAMEABLE_ORIGINS.includes(origin)) {
+ throw new Refused('BAD_ORIGIN', `an origin is ${NAMEABLE_ORIGINS.join(', ')}, not "${origin}"; only a real person answer is the person's origin: pullboard answer <id> <text> --origin person-relayed`);
+ }
+ if (asPerson && named) throw new Refused('BAD_ORIGIN', 'a person answer is its own origin; leave out --origin');
+ const decidedBy = asPerson ? 'person' : agentId;
+ const chosen = asPerson ? 'person' : (origin ?? 'agent');
+ return { statement: String(text).trim(), rationale: reason, decidedBy, relayedBy: chosen === 'person-relayed' ? agentId : null, origin: chosen };
+}
+
+/**
+ * The origin an answer event recorded; unknown when it recorded none.
+ *
+ * @param {{ provenance?: { origin?: string } }} detail an answer event's detail
+ * @returns {string}
+ */
+export function originOf(detail) {
+ const origin = detail?.provenance?.origin;
+ return typeof origin === 'string' && origin ? origin : 'unknown';
+}
+
+/**
+ * The answered decisions behind some items: answers that imply an item, or were addressed to it.
+ *
+ * @param {any} board
+ * @param {number[]} itemIds
+ * @returns {{ id: number, items: number[], statement: string, rationale: string, decidedBy: string, relayedBy: string | null, origin: string, at: string }[]}
+ */
+export function decisionsBehind(board, itemIds) {
+ if (!itemIds.length) return [];
+ const marks = itemIds.map(() => '?').join(',');
+ const byShout = new Map();
+ const note = (shout, item) => byShout.set(shout, [...new Set([...(byShout.get(shout) ?? []), item])].sort((a, b) => a - b));
+ for (const row of board.db.prepare(`SELECT item_id, event_detail FROM event WHERE event_kind = 'fact' AND item_id IN (${marks}) AND json_extract(event_detail, '$.decision.source') = 'answer' AND json_extract(event_detail, '$.supersededBy') IS NULL`).all(...itemIds)) {
+ note(JSON.parse(row.event_detail).decision.id, row.item_id);
+ }
+ for (const row of board.db.prepare(`SELECT item_id, event_detail FROM event WHERE event_kind = 'answer' AND item_id IN (${marks})`).all(...itemIds)) {
+ note(JSON.parse(row.event_detail).shout, row.item_id);
+ }
+ return [...byShout].sort(([left], [right]) => left - right).map(([id, items]) => {
+ const shout = board.db.prepare('SELECT shout_from, shout_text, shout_at FROM shout WHERE shout_id = ?').get(id);
+ const event = board.db.prepare("SELECT event_detail FROM event WHERE event_kind = 'answer' AND json_extract(event_detail, '$.shout') = ?").get(id);
+ const recorded = event ? JSON.parse(event.event_detail).provenance : undefined;
+ return { id, items, statement: recorded?.statement ?? shout.shout_text, rationale: recorded?.rationale ?? '',
+ decidedBy: recorded?.decidedBy ?? shout.shout_from, relayedBy: recorded?.relayedBy ?? null,
+ origin: originOf({ provenance: recorded }), at: shout.shout_at };
+ });
+}
diff --git a/src/help.js b/src/help.js
index 0bf71342..1915f73c 100644
--- a/src/help.js
+++ b/src/help.js
@@ -123,6 +123,7 @@ Work
and is told again when the decision is superseded
the person adds --cause <key> --never-again --as person: rigor lists it at once
pullboard why <id> the decisions that imply an item, newest first, and what superseded them
+ pullboard why <file>[:<line>] the decisions, rows and items behind a file or line, each with its origin
pullboard next [--wait <minutes>] offer an eligible review when reviews pile up, otherwise claim work
pullboard next --build claim a build explicitly, recording a skipped review offer
pullboard next --verify reserve the next submitted item you can check;
@@ -152,6 +153,7 @@ Work
pullboard shout [<to>] <text> --decision ask for a decision; defaults to your coordinator or the person
pullboard shout <to> <text> --evidence attempt|receipt --outcome <word> --item <id> --commit <rev>
pullboard answer <shout-id> <text> [--as person] [--implies <ids>] [--supersedes <answer-id>]
+ [--origin person-relayed|agent|inherited] [--rationale <why>]
answer your decision; person mode is main-checkout only
--supersedes tells the items an earlier answer implied; only the person
supersedes the person's answer
diff --git a/src/moves/answerDecision.js b/src/moves/answerDecision.js
index 2d9fc158..fa135a85 100644
--- a/src/moves/answerDecision.js
+++ b/src/moves/answerDecision.js
@@ -2,6 +2,8 @@ import { RIGOR_AUTO_ENGINE } from '../rigor-auto-engine.js';
/** Routing metadata owned by answerDecision, discovered without a shared registry edit [C7,V4,H16]. */
import { LANDING_LEASE_ENGINE } from '../landing-lease-engine.js';
import { IMPLIES_ENGINE } from '../move-engine-constants.js';
+import { DECISION_ORIGIN_ENGINE } from '../decision-origin-engine.js';
+import { carriesOrigin } from '../decision-origin.js';
import { carriesImplies } from '../move-implies.js';
import { BOARD_SENTINEL_ENGINE } from '../sentinel-engine.js';
@@ -11,6 +13,7 @@ function minimumEngine(args, board, at) {
if (args[0]?.landingFence !== undefined) return LANDING_LEASE_ENGINE;
if (typeof args[1]?.cause === 'string' && args[1].cause.startsWith('sentinel:')) return BOARD_SENTINEL_ENGINE;
if (carriesImplies('answerDecision', args)) return IMPLIES_ENGINE;
+ if (carriesOrigin(args)) return DECISION_ORIGIN_ENGINE;
return 1;
}
@@ -23,5 +26,6 @@ export default Object.freeze({ operation: "answerDecision", order: 25, engine: 1
"ALREADY_ANSWERED": "read the answer with pullboard inbox; ask again with a new pullboard shout <to> \"<text>\" --decision",
"B26_PERSON_ANSWER": "ask your coordinator to answer or pass the decision: pullboard shout coordinator \"<question>\" --decision",
"NOT_A_DECISION": "reply with a shout: pullboard shout <to> \"<text>\"",
+ "BAD_ORIGIN": "name where the decision came from with --origin person-relayed, agent or inherited, or leave --origin out",
"NOT_YOUR_DECISION": "answer only decisions addressed to you; see pullboard inbox"
}) });
diff --git a/src/next-step-defaults.js b/src/next-step-defaults.js
index f83db823..b2dab889 100644
--- a/src/next-step-defaults.js
+++ b/src/next-step-defaults.js
@@ -1,5 +1,6 @@
/** General CLI recovery text; operation-owned codes live in src/moves/ [P4,C7]. */
export const DEFAULT_NEXT_STEPS = Object.freeze({
+ "WHY_GIT": "run pullboard why from inside the repository, with a path that git can read",
"NESTED_RUN_HANDLE_REQUIRED": "pass the original ChildProcess or fixture promise retaining .child to awaitNestedRun",
"NESTED_RUN_OFFER_REQUIRED": "start the child with the current spawn export after test-file token admission, then await its original handle",
"NESTED_RUN_WAIT_REUSED": "await the original returned wait; do not lend the same child a second time",
diff --git a/src/why-file.js b/src/why-file.js
new file mode 100644
index 00000000..ceafb7ca
--- /dev/null
+++ b/src/why-file.js
@@ -0,0 +1,60 @@
+/**
+ * The decisions, rows and items behind a file or a line, from the commits that landed on it [N29].
+ *
+ * A commit pins its item with a `Pullboard-Item: #N` trailer; the items it names carry the rows they
+ * serve and the answered decisions that imply them. One query over Git history and the board.
+ */
+import { tryGit } from './git.js';
+import { Refused } from './refused.js';
+import { decisionsBehind } from './decision-origin.js';
+
+/**
+ * Split `path` or `path:line` into the file and an optional line.
+ *
+ * @param {string} target
+ * @returns {{ file: string, line: number | null }}
+ */
+export function parseFileTarget(target) {
+ const match = /^(.+?):([1-9]\d*)$/u.exec(target);
+ return match ? { file: match[1], line: Number(match[2]) } : { file: target, line: null };
+}
+
+/**
+ * The item ids named by the landed commits that touched a file or line, oldest first.
+ *
+ * @param {string} root the repository root
+ * @param {{ file: string, line: number | null }} target
+ * @returns {number[]}
+ */
+export function itemsTouching(root, { file, line }) {
+ const range = line === null ? ['--', file] : [`-L${line},${line}:${file}`, '-s'];
+ const log = tryGit(root, ['log', '--reverse', '--format=%x01%B', ...range]);
+ if (log.status !== 0) {
+ if (line !== null && /no such path|file .* has only|there is no path/iu.test(log.stderr)) return [];
+ if (/does not have any commits|unknown revision|bad revision|ambiguous argument/iu.test(log.stderr)) return [];
+ throw new Refused('WHY_GIT', `git could not read the history of ${file}: ${log.stderr.split('\n')[0]}`);
+ }
+ const ids = [];
+ for (const body of log.stdout.split('\x01')) {
+ for (const match of body.matchAll(/^Pullboard-Item:\s*#(\d+)\s*$/gmu)) ids.push(Number(match[1]));
+ }
+ return [...new Set(ids)];
+}
+
+/**
+ * Everything behind a file or line: its items, the rows they serve and the decisions that imply them.
+ *
+ * @param {any} board
+ * @param {string} root
+ * @param {string} target `path` or `path:line`
+ * @returns {{ file: string, line: number | null, items: object[], rows: object[], decisions: object[] }}
+ */
+export function whyFile(board, root, target) {
+ const parsed = parseFileTarget(target);
+ const ids = itemsTouching(root, parsed);
+ const found = ids.map((id) => board.db.prepare('SELECT item_id, item_title, item_status, item_spec_ids FROM item WHERE item_id = ?').get(id)).filter(Boolean);
+ const items = found.map((item) => ({ id: item.item_id, title: item.item_title, status: item.item_status }));
+ const rows = [...new Set(found.flatMap((item) => item.item_spec_ids.split(',').filter(Boolean)))]
+ .map((id) => ({ id, items: found.filter((item) => item.item_spec_ids.split(',').includes(id)).map((item) => item.item_id) }));
+ return { file: parsed.file, line: parsed.line, items, rows, decisions: decisionsBehind(board, items.map((item) => item.id)) };
+}
diff --git a/test/move-registry-baseline.json b/test/move-registry-baseline.json
index 29ae5911..f1aac8f7 100644
--- a/test/move-registry-baseline.json
+++ b/test/move-registry-baseline.json
@@ -6715,6 +6715,8 @@
"RIGOR_UNPROVEN": "name a check that fails at --red and passes at --green: pullboard rigor draft <key> \"<rule>\" --check \"<command>\" --red <commit> --green <commit>",
"RIGOR_PERSON_ONLY": "ask the person to mark it from the main checkout: pullboard fact <id> root-cause \"<why>\" --cause <key> --never-again --as person",
"SANDBOX_BLOCKED": "ask the coordinator to bring it to the person: pullboard shout coordinator \"<what is needed>\" --decision; or run the gate outside the sandbox; keep the tests unchanged",
+ "BAD_ORIGIN": "name where the decision came from with --origin person-relayed, agent or inherited, or leave --origin out",
+ "WHY_GIT": "run pullboard why from inside the repository, with a path that git can read",
"NOT_YOUR_DECISION": "answer only decisions addressed to you; see pullboard inbox",
"NO_AGENT": "create and join a lane worktree: pullboard worktree <lane> --model \"<model name>\"",
"NO_BOARD": "initialize the board in this repository: pullboard init",
@@ -7403,7 +7405,7 @@
},
{
"meta_key": "relay_engine_version",
- "meta_value": "106"
+ "meta_value": "107"
},
{
"meta_key": "relay_receipt_registry-snapshot-2",
diff --git a/test/why.test.js b/test/why.test.js
new file mode 100644
index 00000000..da98d36a
--- /dev/null
+++ b/test/why.test.js
@@ -0,0 +1,112 @@
+/** A decision records where it came from, and pullboard why <file> names the decisions behind a file [N29,B29,P6]. */
+import assert from 'node:assert/strict';
+import { runFixtureChild, runFixtureGit } from './fixture-child.js';
+import { chmodSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { after, test } from 'node:test';
+import { originOf } from '../src/decision-origin.js';
+
+const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');
+const sandboxes = [];
+const SPEC = '# Why fixture\n\n## G · Goals\n- G1 [approved, must] The feature works. | gate: test\n';
+
+after(() => {
+ for (const dir of sandboxes) rmSync(dir, { recursive: true, force: true });
+});
+
+/** Make an isolated real-Git repo with a board, a coordinator, one web builder and two web items. */
+function fixture() {
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-why-')));
+ sandboxes.push(dir);
+ const shims = join(dir, 'bin');
+ mkdirSync(shims);
+ writeFileSync(join(shims, 'pullboard'), `#!/bin/sh\nexec "${process.execPath}" "${BIN}" "$@"\n`, { mode: 0o755 });
+ chmodSync(join(shims, 'pullboard'), 0o755);
+ const env = {
+ ...process.env,
+ PATH: `${shims}:${process.env.PATH}`,
+ GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',
+ GIT_AUTHOR_NAME: 'Test Agent', GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Test Agent', GIT_COMMITTER_EMAIL: '[email protected]',
+ PULLBOARD_HOME: join(dir, 'home'), PULLBOARD_MACHINE_HOME: join(dir, 'machine-home'),
+ };
+ for (const name of Object.keys(env)) if (name.startsWith('GIT_') && !name.startsWith('GIT_CONFIG') && !name.startsWith('GIT_AUTHOR') && !name.startsWith('GIT_COMMITTER')) delete env[name];
+ delete env.PULLBOARD_RELAY_TOKEN;
+ const repo = join(dir, 'repo');
+ mkdirSync(repo);
+ /** Run Git in this private fixture with its isolated identity. */
+ const git = (cwd, ...args) => runFixtureGit(args, { cwd, env });
+ /** Run the actual CLI in a fixture checkout and keep both output streams. */
+ const run = (cwd, ...args) => {
+ const result = runFixtureChild(process.execPath, [BIN, ...args], { cwd, env, encoding: 'utf8' });
+ return { code: result.status, out: result.stdout ?? '', err: result.failure ?? result.stderr ?? '' };
+ };
+ /** Run a command that must succeed with --json and return its one document. */
+ const json = (cwd, ...args) => {
+ const result = run(cwd, ...args, '--json');
+ assert.equal(result.code, 0, `${args.join(' ')}: ${result.err}${result.out}`);
+ return JSON.parse(result.out);
+ };
+ git(repo, 'init', '-q', '-b', 'main');
+ assert.equal(run(repo, 'init').code, 0);
+ writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({
+ gate: 'true', spec: 'SPEC.md', verify: 'any', lease: '2h',
+ lanes: { web: { owns: ['web/'], specs: ['G1'] } },
+ }, null, 2));
+ writeFileSync(join(repo, 'SPEC.md'), SPEC);
+ mkdirSync(join(repo, 'web'));
+ writeFileSync(join(repo, 'web', 'shared.txt'), 'one\ntwo\nthree\n');
+ writeFileSync(join(repo, 'web', 'other.txt'), 'other\n');
+ git(repo, 'add', '-A');
+ git(repo, 'commit', '-q', '-m', 'chore: create why fixture');
+ for (const title of ['First item', 'Second item']) {
+ json(repo, 'add', 'web', title, '--specs', 'G1', '--criterion', `${title} works`, '--check', 'true');
+ }
+ return { git, repo, run, json };
+}
+
+test('a decision records its origin and pullboard why names the decisions behind a file [N29,B29,P6]', () => {
+ const box = fixture();
+ const web = box.json(box.repo, 'worktree', 'web', '--route', 'strong', '--model', 'fixture-model').path;
+
+ writeFileSync(join(box.repo, 'web', 'shared.txt'), 'one\nTWO\nthree\n');
+ box.git(box.repo, 'commit', '-q', '-am', 'feat(web): change line two [G1]\n\nPullboard-Item: #1');
+ writeFileSync(join(box.repo, 'web', 'other.txt'), 'other, changed\n');
+ box.git(box.repo, 'commit', '-q', '-am', 'feat(web): change the other file [G1]\n\nPullboard-Item: #2');
+
+ const ask = box.json(web, 'shout', 'coordinator', 'Keep line two upper case?', '--decision').id;
+ const answer = box.json(box.repo, 'answer', String(ask), 'Keep it upper case', '--implies', '1',
+ '--origin', 'person-relayed', '--rationale', 'the person wants it to read as a heading').id;
+ const askOther = box.json(web, 'shout', 'coordinator', 'Change the other file?', '--decision').id;
+ const answerOther = box.json(box.repo, 'answer', String(askOther), 'Change it', '--implies', '2').id;
+
+ const third = box.json(web, 'shout', 'coordinator', 'One more?', '--decision').id;
+ const forged = box.run(box.repo, 'answer', String(third), 'x', '--origin', 'person');
+ assert.notEqual(forged.code, 0, 'an agent cannot name the person as the origin');
+ assert.match(forged.err, /BAD_ORIGIN/u);
+
+ const file = box.json(box.repo, 'why', 'web/shared.txt');
+ assert.equal(file.file, 'web/shared.txt');
+ assert.deepEqual(file.items.map((item) => item.id), [1], 'only the item whose landed commit touched the file');
+ assert.deepEqual(file.rows.map((row) => row.id), ['G1']);
+ assert.equal(file.decisions.length, 1, 'only the decision implying that item');
+ assert.deepEqual({ id: file.decisions[0].id, statement: file.decisions[0].statement, rationale: file.decisions[0].rationale,
+ decidedBy: file.decisions[0].decidedBy, relayedBy: file.decisions[0].relayedBy, origin: file.decisions[0].origin },
+ { id: answer, statement: 'Keep it upper case', rationale: 'the person wants it to read as a heading',
+ decidedBy: 'coordinator', relayedBy: 'coordinator', origin: 'person-relayed' });
+
+ const text = box.run(box.repo, 'why', 'web/shared.txt');
+ assert.equal(text.code, 0, text.err);
+ assert.match(text.out, /person-relayed/u);
+ assert.match(text.out, /Keep it upper case/u);
+
+ assert.deepEqual(box.json(box.repo, 'why', 'web/shared.txt:2').items.map((item) => item.id), [1], 'the changed line');
+ assert.deepEqual(box.json(box.repo, 'why', 'web/shared.txt:1').items, [], 'a line no landed commit touched');
+ const other = box.json(box.repo, 'why', 'web/other.txt');
+ assert.deepEqual(other.decisions.map((entry) => [entry.id, entry.origin]), [[answerOther, 'agent']], 'an answer that names no origin is an agent decision');
+
+ assert.equal(originOf({}), 'unknown', 'a decision with no recorded origin is unknown');
+ assert.equal(originOf({ provenance: { origin: 'inherited' } }), 'inherited');
+ assert.equal(box.json(box.repo, 'why', 'web/missing.txt').items.length, 0, 'a file no commit touched has nothing behind it');
+});