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.

perf(cli): keep offline status on its own import graph [C7]

Corey Olson2ff08c00cd5a
diff --git a/src/cli-context.js b/src/cli-context.js
index f8c33ac9..9c810476 100644
--- a/src/cli-context.js
+++ b/src/cli-context.js
@@ -284,3 +284,17 @@ export function uncommittedSetup(mainRoot, config) {
stage: `${cdTo(mainRoot)} git add${force} -- ${words}`,
};
}
+
+/**
+ * How long ago an ISO time was, or how long until it, in the board's clock: 45m, 3h, 2d.
+ *
+ * @param {any} ctx
+ * @param {string} iso
+ * @returns {string}
+ */
+export function span(ctx, iso) {
+ const minutes = Math.round(Math.abs(ctx.clock.now().getTime() - Date.parse(iso)) / 60_000);
+ if (minutes < 60) return `${minutes}m`;
+ if (minutes < 48 * 60) return `${Math.round(minutes / 60)}h`;
+ return `${Math.round(minutes / 1440)}d`;
+}
diff --git a/src/cli-identity.js b/src/cli-identity.js
new file mode 100644
index 00000000..d199bdb7
--- /dev/null
+++ b/src/cli-identity.js
@@ -0,0 +1,33 @@
+/** Caller identity shared by read and write commands without loading their transports [C7,E18]. */
+import * as store from './board.js';
+import { COORDINATOR } from './config.js';
+import { displayAgentName } from './agent-names.js';
+import { Refused } from './refused.js';
+
+/**
+ * Who is asking: the coordinator in the main checkout, or the agent this worktree joined as.
+ *
+ * @param {any} ctx
+ * @param {any} board
+ * @returns {{ id: string, lane: string, route?: string, family: string | null, model: string | null, displayName: string }}
+ */
+export function identifyCaller(ctx, board, { environmentAgent, relayLinked }) {
+ // A CI or cloud session works as the agent its environment token names, on that one board [E18].
+ const seat = environmentAgent(ctx.info.root, board);
+ if (seat) return { id: seat.agent_id, lane: seat.agent_lane, route: seat.agent_route, family: seat.agent_family ?? null, model: seat.agent_model ?? 'unknown', displayName: displayAgentName(seat, ctx.config.agents.names) };
+ if (ctx.info.isMain) {
+ ctx.io.caller?.('coordinator', ctx.info.root);
+ const registered = store.listAgents(board).find((agent) => agent.agent_id === COORDINATOR);
+ const linked = relayLinked(ctx.info.root);
+ if (linked && !registered) throw new Refused('NO_AGENT', 'the linked snapshot has no coordinator; restore a consistent relay snapshot before acting');
+ const id = linked ? COORDINATOR : store.ensureCoordinator(board, ctx.info.root);
+ const agent = registered ?? store.agentAt(board, ctx.info.root);
+ return { id, lane: COORDINATOR, family: agent?.agent_family ?? null, model: agent?.agent_model ?? 'unknown', displayName: displayAgentName(agent ?? { agent_id: id }, ctx.config.agents.names) };
+ }
+ const agent = store.agentAt(board, ctx.info.root);
+ if (!agent) {
+ throw new Refused('NOT_JOINED', 'this worktree has not joined a lane: pullboard join <lane> --model "<model name>" (see: pullboard lanes)');
+ }
+ ctx.io.caller?.('seat', ctx.info.root);
+ return { id: agent.agent_id, lane: agent.agent_lane, route: agent.agent_route, family: agent.agent_family ?? null, model: agent.agent_model ?? 'unknown', displayName: displayAgentName(agent, ctx.config.agents.names) };
+}
diff --git a/src/cli.js b/src/cli.js
index 8383055c..2896038a 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -1,3 +1,4 @@
+import { identifyCaller } from './cli-identity.js';
/**
* The pullboard command line: every command, bound to who is asking (B3, R3). The main checkout is the
* coordinator; every other worktree is the agent that joined from it.
@@ -58,6 +59,7 @@ import {
sayBrief,
setupFiles,
shellWord,
+ span,
uncommittedSetup,
withBoard,
} from './cli-context.js';
@@ -75,7 +77,7 @@ import {
// Commands and tests import these from here; each lives in the module a read can load without the rest.
export {
agentDisplayName, cdTo, CHECKOUT_LEASES, context, firstLineOf, HELP, idArg, idList, itemLine, main, printHelp,
- resultCommands, sayBrief, shellWord, uncommittedSetup, unknownCommand, withBoard,
+ resultCommands, sayBrief, shellWord, span, uncommittedSetup, unknownCommand, withBoard,
};
import {
CONFIG_FILE,
@@ -683,32 +685,9 @@ export function refuseRemoteCoordinatorModel(ctx, command) {
throw new Refused('REMOTE_COORDINATOR_MODEL', `the coordinator's model is declared on the coordinator's own checkout (${name}); run pullboard ${command} there`);
}
-/**
- * Who is asking: the coordinator in the main checkout, or the agent this worktree joined as.
- *
- * @param {any} ctx
- * @param {any} board
- * @returns {{ id: string, lane: string, route?: string, family: string | null, model: string | null, displayName: string }}
- */
+/** Resolve the caller with the existing environment and relay identity checks. */
export function whoAmI(ctx, board) {
- // A CI or cloud session works as the agent its environment token names, on that one board [E18].
- const seat = environmentAgent(ctx.info.root, board);
- if (seat) return { id: seat.agent_id, lane: seat.agent_lane, route: seat.agent_route, family: seat.agent_family ?? null, model: seat.agent_model ?? 'unknown', displayName: displayAgentName(seat, ctx.config.agents.names) };
- if (ctx.info.isMain) {
- ctx.io.caller?.('coordinator', ctx.info.root);
- const registered = store.listAgents(board).find((agent) => agent.agent_id === COORDINATOR);
- const linked = relayLinked(ctx.info.root);
- if (linked && !registered) throw new Refused('NO_AGENT', 'the linked snapshot has no coordinator; restore a consistent relay snapshot before acting');
- const id = linked ? COORDINATOR : store.ensureCoordinator(board, ctx.info.root);
- const agent = registered ?? store.agentAt(board, ctx.info.root);
- return { id, lane: COORDINATOR, family: agent?.agent_family ?? null, model: agent?.agent_model ?? 'unknown', displayName: displayAgentName(agent ?? { agent_id: id }, ctx.config.agents.names) };
- }
- const agent = store.agentAt(board, ctx.info.root);
- if (!agent) {
- throw new Refused('NOT_JOINED', 'this worktree has not joined a lane: pullboard join <lane> --model "<model name>" (see: pullboard lanes)');
- }
- ctx.io.caller?.('seat', ctx.info.root);
- return { id: agent.agent_id, lane: agent.agent_lane, route: agent.agent_route, family: agent.agent_family ?? null, model: agent.agent_model ?? 'unknown', displayName: displayAgentName(agent, ctx.config.agents.names) };
+ return identifyCaller(ctx, board, { environmentAgent, relayLinked });
}
/**
@@ -922,20 +901,6 @@ export function refuseUnverifiedStack(root, board, item, commit, trunk) {
}
}
-/**
- * How long ago an ISO time was, or how long until it, in the board's clock: 45m, 3h, 2d.
- *
- * @param {any} ctx
- * @param {string} iso
- * @returns {string}
- */
-export function span(ctx, iso) {
- const minutes = Math.round(Math.abs(ctx.clock.now().getTime() - Date.parse(iso)) / 60_000);
- if (minutes < 60) return `${minutes}m`;
- if (minutes < 48 * 60) return `${Math.round(minutes / 60)}h`;
- return `${Math.round(minutes / 1440)}d`;
-}
-
/**
* A shout's text cut to one short line.
*
diff --git a/src/commands/status.js b/src/commands/status.js
index cbc93481..a8e2e491 100644
--- a/src/commands/status.js
+++ b/src/commands/status.js
@@ -1,6 +1,9 @@
/** The pullboard status command, in its own module so an item adding another command never edits these lines. */
import * as store from '../board.js';
-import { personNeedsSummary } from '../needs-state.js';
+import { personNeedsSummary } from '../needs-summary.js';
+import { identifyCaller } from '../cli-identity.js';
+import { relayStateExists } from '../local-state.js';
+import { unlinkedRelayStatus } from '../relay-status-fields.js';
import {
reviewQueueLine,
} from '../next-steps.js';
@@ -8,11 +11,7 @@ import {
productLine,
productSummaries,
} from '../products.js';
-import * as relayOutput from '../relay-output.js';
-import {
- originRepository,
- relayStatus,
-} from '../relay.js';
+import { originRepository } from '../github-origin.js';
import {
loadSpec,
} from '../spec.js';
@@ -23,25 +22,29 @@ import {
import {
context,
span,
- whoAmI,
withBoard,
-} from '../cli.js';
+} from '../cli-context.js';
/** Run `pullboard status` and return its exit code. */
-export function run(io, { values }) {
+export async function run(io, { values }) {
const ctx = context(io);
+ const hasRelayState = relayStateExists(ctx.info.commonDir);
+ const relay = hasRelayState ? await import('../relay.js') : null;
+ const environment = hasRelayState && process.env.PULLBOARD_RELAY_TOKEN !== undefined
+ ? await import('../relay-environment.js') : null;
const summary = withBoard(ctx, (board) => {
- const me = whoAmI(ctx, board);
+ const me = identifyCaller(ctx, board, { environmentAgent: environment?.environmentAgent ?? (() => null),
+ relayLinked: relay?.relayLinked ?? (() => false) });
const mine = store.listItems(board).filter((item) => item.item_status === 'claimed' && item.item_owner === me.id);
const approvalState = personNeedsSummary(ctx.info.root, { board, config: ctx.config });
- return { me, mine, needs: approvalState.needs, specApprovalBaseline: approvalState.specApprovalBaseline, specApprovalEvidenceErrors: approvalState.specApprovalEvidenceErrors, stats: store.stats(board), reviewQueue: { ...store.reviewQueue(board), ...store.reviewQueueBreakdown(board) }, unread: store.unreadCount(board, me.id), relay: relayStatus(ctx.info.root),
+ return { me, mine, needs: approvalState.needs, specApprovalBaseline: approvalState.specApprovalBaseline, specApprovalEvidenceErrors: approvalState.specApprovalEvidenceErrors, stats: store.stats(board), reviewQueue: { ...store.reviewQueue(board), ...store.reviewQueueBreakdown(board) }, unread: store.unreadCount(board, me.id), relay: relay ? relay.relayStatus(ctx.info.root) : unlinkedRelayStatus(),
submitInvariantProposals: submitInvariantProposals(store.eventsOfKinds(board, ['submit', 'landing_batch']), ctx.config) };
});
if (values.json) {
io.result(summary);
return 0;
}
- for (const line of relayOutput.briefLines(summary.relay)) io.say(line);
+ if (hasRelayState) for (const line of (await import('../relay-output.js')).briefLines(summary.relay)) io.say(line);
const { items, accepted, rejected } = summary.stats;
io.say(`${summary.me.displayName}: ${summary.unread} unread shouts; holding ${summary.mine.map((item) => `#${item.item_id}`).join(', ') || 'nothing'}`);
io.say(`board: ${items.open} open, ${items.claimed} claimed, ${items.submitted} awaiting verification, ${items.verified} verified, ${items.withdrawn} withdrawn`);
diff --git a/src/github-origin.js b/src/github-origin.js
new file mode 100644
index 00000000..0e004071
--- /dev/null
+++ b/src/github-origin.js
@@ -0,0 +1,26 @@
+/** GitHub origin discovery without loading relay transport [C7,H16]. */
+import { tryGit } from './git.js';
+import { Refused } from './refused.js';
+
+/** Resolve the actual GitHub origin; optional discovery leaves ineligible local projects alone. */
+export function originRepository(root, { optional = false } = {}) {
+ const remote = tryGit(root, ['remote', 'get-url', 'origin']);
+ if (remote.status !== 0 && optional) return null;
+ if (remote.status !== 0) throw new Refused('RELAY_ORIGIN', 'add a GitHub origin remote before running pullboard relay on');
+ let repository;
+ const ssh = /^git@github\.com:([^\s?#]+)$/.exec(remote.stdout);
+ if (ssh) repository = ssh[1];
+ else {
+ try {
+ const url = new URL(remote.stdout);
+ if (url.hostname === 'github.com' && !url.password && !url.search && !url.hash &&
+ ((url.protocol === 'https:' && !url.username) || (url.protocol === 'ssh:' && url.username === 'git')) && !url.port) repository = url.pathname.slice(1);
+ } catch { /* A local path or another host is not a GitHub repository. */ }
+ }
+ repository = repository?.replace(/\.git$/, '');
+ if (!repository || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository) || repository.split('/').some((part) => ['.', '..'].includes(part))) {
+ if (optional) return null;
+ throw new Refused('RELAY_ORIGIN', 'origin must name a GitHub owner/repository using HTTPS or git SSH; fix origin and run pullboard relay on');
+ }
+ return repository;
+}
diff --git a/src/needs-state.js b/src/needs-state.js
index da50a011..86fe62ad 100644
--- a/src/needs-state.js
+++ b/src/needs-state.js
@@ -16,8 +16,8 @@ import {
undraftedRigor,
} from './rigor-notices.js';
import { personNeeds } from './needs.js';
-import { personBlockWords } from './blocks.js';
-import { displayAgentName } from './agent-names.js';
+import { recentBlocks } from './needs-summary.js';
+export { personNeedsSummary, recentBlocks } from './needs-summary.js';
import {
projectSpecApprovals,
specApprovalState,
@@ -45,20 +45,3 @@ export function personNeedsState(root, { board: providedBoard = null, includeRig
if (!providedBoard) store.closeBoard(board);
}
}
-
-/** Keep status's complete obligation list without dashboard history, Git ages, or release notes. */
-export function personNeedsSummary(root, { board, config }) {
- const spec = loadSpec(root, config);
- const rows = projectRowDecisions(store.rowDecisions(board), { root, spec: spec.rows, practice: loadDoctrine(root, config).rows });
- const projected = projectSpecApprovals({ ...rows,
- decisions: store.openDecisions(board, store.PERSON), holds: store.laneHolds(board),
- agents: store.listAgents(board).map(agent => ({ ...agent, displayName: displayAgentName(agent, config.agents.names) })),
- rigorDrafts: rigorDraftNeeds(rows), sentinelDrafts: sentinelDraftNeeds(sentinels(board)), blocks: recentBlocks(repoInfo(root).commonDir, board),
- }, specApprovalState(root, { board, config, spec }));
- return projected;
-}
-
-/** The person's blocks from the last day, by the board's clock, for Needs you [C6]. */
-export function recentBlocks(commonDir, board) {
- return personBlockWords(commonDir, (board?.clock ?? store.systemClock).now());
-}
diff --git a/src/needs-summary.js b/src/needs-summary.js
new file mode 100644
index 00000000..e826c3de
--- /dev/null
+++ b/src/needs-summary.js
@@ -0,0 +1,34 @@
+/** Status obligations without loading the dashboard projection [N26,A9]. */
+import * as store from './board.js';
+import { repoInfo } from './git.js';
+import { projectRowDecisions } from './row-decisions.js';
+import { loadSpec } from './spec.js';
+import { loadDoctrine } from './doctrine.js';
+import { rigorDraftNeeds } from './rigor-notices.js';
+import { personBlockWords } from './blocks.js';
+import { displayAgentName } from './agent-names.js';
+import {
+ projectSpecApprovals,
+ specApprovalState,
+} from './spec-approval.js';
+import {
+ sentinelDraftNeeds,
+ sentinels,
+} from './sentinels.js';
+
+/** Keep status's complete obligation list without dashboard history, Git ages, or release notes. */
+export function personNeedsSummary(root, { board, config }) {
+ const spec = loadSpec(root, config);
+ const rows = projectRowDecisions(store.rowDecisions(board), { root, spec: spec.rows, practice: loadDoctrine(root, config).rows });
+ const projected = projectSpecApprovals({ ...rows,
+ decisions: store.openDecisions(board, store.PERSON), holds: store.laneHolds(board),
+ agents: store.listAgents(board).map(agent => ({ ...agent, displayName: displayAgentName(agent, config.agents.names) })),
+ rigorDrafts: rigorDraftNeeds(rows), sentinelDrafts: sentinelDraftNeeds(sentinels(board)), blocks: recentBlocks(repoInfo(root).commonDir, board),
+ }, specApprovalState(root, { board, config, spec }));
+ return projected;
+}
+
+/** The person's blocks from the last day, by the board's clock, for Needs you [C6]. */
+export function recentBlocks(commonDir, board) {
+ return personBlockWords(commonDir, (board?.clock ?? store.systemClock).now());
+}
diff --git a/src/relay-status-fields.js b/src/relay-status-fields.js
new file mode 100644
index 00000000..dd30e407
--- /dev/null
+++ b/src/relay-status-fields.js
@@ -0,0 +1,12 @@
+/** Transport-free local relay status fields shared with offline read commands [C7,H16]. */
+/** Expose only the actionable recovery choice; checkpoint ciphertext and local digests stay private. */
+export function recoverySummary(state) {
+ const skip = Number.isSafeInteger(state?.recovery?.skip) ? state.recovery.skip : 0;
+ return { pending: skip > 0, skip, next: skip > 0 ? `pullboard relay recover --skip ${skip}` : '' };
+}
+
+/** Preserve the unlinked status document, including a deleted-copy notice when present. */
+export function unlinkedRelayStatus(deleted = null) {
+ return { linked: false, board: deleted?.board ?? '', url: deleted?.url ?? '', link: '', sequence: 0, behind: 0, recovery: recoverySummary(null),
+ ...(deleted ? { deleted: true, notice: 'The relay copy was deleted; your local board is complete. Keep working locally, or run pullboard relay on to link it again.' } : {}) };
+}
diff --git a/src/relay.js b/src/relay.js
index 1665faea..c225fbad 100644
--- a/src/relay.js
+++ b/src/relay.js
@@ -1,3 +1,9 @@
+import {
+ recoverySummary,
+ unlinkedRelayStatus,
+} from './relay-status-fields.js';
+import { originRepository } from './github-origin.js';
+export { originRepository };
import {
clearUploadPauseNotices,
firstUploadPauseNotice,
@@ -164,28 +170,6 @@ export function relayOrigin(address) {
}
return url.origin;
}
-/** Resolve the actual GitHub origin; optional discovery leaves ineligible local projects alone. */
-export function originRepository(root, { optional = false } = {}) {
- const remote = tryGit(root, ['remote', 'get-url', 'origin']);
- if (remote.status !== 0 && optional) return null;
- if (remote.status !== 0) throw new Refused('RELAY_ORIGIN', 'add a GitHub origin remote before running pullboard relay on');
- let repository;
- const ssh = /^git@github\.com:([^\s?#]+)$/.exec(remote.stdout);
- if (ssh) repository = ssh[1];
- else {
- try {
- const url = new URL(remote.stdout);
- if (url.hostname === 'github.com' && !url.password && !url.search && !url.hash &&
- ((url.protocol === 'https:' && !url.username) || (url.protocol === 'ssh:' && url.username === 'git')) && !url.port) repository = url.pathname.slice(1);
- } catch { /* A local path or another host is not a GitHub repository. */ }
- }
- repository = repository?.replace(/\.git$/, '');
- if (!repository || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository) || repository.split('/').some((part) => ['.', '..'].includes(part))) {
- if (optional) return null;
- throw new Refused('RELAY_ORIGIN', 'origin must name a GitHub owner/repository using HTTPS or git SSH; fix origin and run pullboard relay on');
- }
- return repository;
-}
/** Find the shared local link metadata without opening a board or connecting for an unlinked repo. */
function linkFile(root) { return relayFiles(repoInfo(root).commonDir).link; }
@@ -437,18 +421,11 @@ function behind(root, state) {
return localRecords(root, (board) => board.db.prepare('SELECT COUNT(*) AS count FROM event WHERE event_id > ?').get(state.cursor).count);
}
-/** Expose only the actionable recovery choice; checkpoint ciphertext and local digests stay private. */
-function recoverySummary(state) {
- const skip = Number.isSafeInteger(state?.recovery?.skip) ? state.recovery.skip : 0;
- return { pending: skip > 0, skip, next: skip > 0 ? `pullboard relay recover --skip ${skip}` : '' };
-}
-
/** Expose key-free link status; only an explicit link operation includes its pairing carrier. */
function summary(root, state, { pairing = false } = {}) {
if (!state) {
const deleted = deletedLink(root);
- return { linked: false, board: deleted?.board ?? '', url: deleted?.url ?? '', link: '', sequence: 0, behind: 0, recovery: recoverySummary(null),
- ...(deleted ? { deleted: true, notice: 'The relay copy was deleted; your local board is complete. Keep working locally, or run pullboard relay on to link it again.' } : {}) };
+ return unlinkedRelayStatus(deleted);
}
if (state.unlinking) return { linked: false, board: state.board, url: state.url, link: '', sequence: state.sequence, behind: 0, cleanup: true, recovery: recoverySummary(state) };
const fragment = pairing ? '&key=' + encodeBoardKey(readBoardKey(state.board)) : '';
diff --git a/test/cli-startup-budget-fixture.js b/test/cli-startup-budget-fixture.js
new file mode 100644
index 00000000..c07b03f5
--- /dev/null
+++ b/test/cli-startup-budget-fixture.js
@@ -0,0 +1,96 @@
+import { spawnSync } from 'node:child_process';
+import { resolve } from 'node:path';
+/** Complete fresh-process CLI reads on a private board at the measured production scale [C7]. */
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir, loadavg, cpus } from 'node:os';
+import { join } from 'node:path';
+import { DatabaseSync } from 'node:sqlite';
+import * as store from '../src/board.js';
+import { runFixtureGit } from './fixture-child.js';
+import { submitFixture } from './board-submit-fixture.js';
+
+/** Seed real rows, not cached command results, with many historical submissions and a small live queue. */
+function fixture(t) {
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-cli-startup-budget-')));
+ let db;
+ t.after(() => { db?.close(); rmSync(root, { recursive: true, force: true }); });
+ const env = { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',
+ GIT_AUTHOR_NAME: 'Performance fixture', GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Performance fixture', GIT_COMMITTER_EMAIL: '[email protected]' };
+ runFixtureGit(['init', '-q', '-b', 'main'], { cwd: root, env });
+ writeFileSync(join(root, 'pullboard.json'), JSON.stringify({ gate: 'true', submitGate: 'landing',
+ lanes: { core: { owns: ['src/'], specs: ['C7'] } }, spec: 'SPEC.md' }));
+ writeFileSync(join(root, 'SPEC.md'), '# Performance fixture\n## C\n- C7 [approved, must] Reads preserve the board. | gate: test\n');
+ writeFileSync(join(root, 'PRACTICE.md'), '');
+ runFixtureGit(['add', '-A'], { cwd: root, env });
+ runFixtureGit(['commit', '-qm', 'Seed performance fixture'], { cwd: root, env });
+ const file = join(root, '.git', 'pullboard', 'board.sqlite');
+ const board = store.openBoard(file);
+ store.register(board, { lane: 'coordinator', path: root });
+ store.closeBoard(board);
+ db = new DatabaseSync(file);
+ const at = '2026-10-23T00:00:00.000Z';
+ db.exec('BEGIN');
+ const agent = db.prepare('INSERT INTO agent (agent_id, agent_lane, agent_path, agent_created_at) VALUES (?, ?, ?, ?)');
+ for (let n = 1; n <= 800; n++) agent.run(`core-${n}`, 'core', join(root, 'seats', String(n)), at);
+ const item = db.prepare(`INSERT INTO item (item_lane, item_title, item_criterion, item_status,
+ item_created_by, item_created_at, item_updated_at) VALUES ('core', ?, 'The read preserves evidence.', ?, 'coordinator', ?, ?)`);
+ for (let n = 1; n <= 1000; n++) item.run(`Item ${n}`, 'open', at, at);
+ const event = db.prepare('INSERT INTO event (event_at, event_by, event_kind, item_id, event_detail) VALUES (?, ?, ?, ?, ?)');
+ const commit = 'a'.repeat(40);
+ const proof = JSON.stringify({ commit, submissionProof: { version: 1, files: ['test/a.test.js'], full: false, deferred: false, reason: 'affected selection' } });
+ for (let n = 0; n < 45000; n++) event.run(at, `core-${1 + n % 800}`, n < 1600 ? 'submit' : n % 2 ? 'claim' : 'edit', 1 + n % 1000, n < 1600 ? proof : '{}');
+ const shout = db.prepare('INSERT INTO shout (shout_from, shout_to, shout_text, shout_at) VALUES (?, ?, ?, ?)');
+ for (let n = 0; n < 23000; n++) shout.run(`core-${1 + n % 800}`, 'all', `Board activity ${n}`, at);
+ db.exec('COMMIT');
+ const live = store.openBoard(file);
+ try {
+ for (let id = 1; id <= 10; id++) {
+ store.claim(live, id, { agentId: `core-${id}`, lane: 'core', leaseMs: 3_600_000,
+ freeze: () => ({ text: JSON.stringify({ rows: [] }), digest: 'performance-fixture' }) });
+ submitFixture(live, id, { agentId: `core-${id}`, commit, tree: 'b'.repeat(40) });
+ }
+ } finally { store.closeBoard(live); }
+ return { root, db };
+}
+
+/** Hash every persistent table outside the timed region, so a read cannot silently change board state. */
+function boardDigest(db) {
+ const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all();
+ const rows = tables.map(({ name }) => [name, db.prepare(`SELECT * FROM "${name.replaceAll('"', '""')}" ORDER BY rowid`).all()]);
+ return createHash('sha256').update(JSON.stringify(rows)).digest('hex');
+}
+
+
+/** Measure complete fresh CLI processes without a module hook, warmup, or output shortcut. */
+export async function assertStartupBudgets(t) {
+ const cleanups=[];
+ const {root,db}=fixture({after(fn){cleanups.push(fn);}});
+ try {
+ const code=resolve(import.meta.dirname,'../bin/pullboard.js');
+ const initial=boardDigest(db);
+ const samples={version:[],show:[],status:[],list:[]};
+ const childEnvironment={...process.env,PULLBOARD_HOME:join(root,'private-home'),PULLBOARD_MACHINE_HOME:join(root,'private-machine'),GIT_CONFIG_GLOBAL:'/dev/null',GIT_CONFIG_NOSYSTEM:'1'};
+ for(const name of ['PULLBOARD_RELAY_TOKEN','PULLBOARD_RELAY_KEY']) delete childEnvironment[name];
+ for(let round=0;round<5;round++) for(const name of Object.keys(samples)) {
+ const args=name==='version'?['--version','--json']:name==='show'?['show','4','--json']:[name,'--json'];
+ const started=performance.now();
+ const result=spawnSync(process.execPath,[code,...args],{cwd:root,encoding:'utf8',env:childEnvironment,maxBuffer:16*1024*1024});
+ const milliseconds=performance.now()-started;
+ assert.equal(result.status,0,`${name} round ${round}: ${result.error?.message ?? result.stderr ?? result.stdout}`);
+ const data=JSON.parse(result.stdout);
+ assert.equal(data.version,1);
+ if(name==='show') assert.equal(data.item_id,4);
+ if(name==='status') assert.equal(data.stats.items.submitted,10);
+ if(name==='list') assert.equal(data.items.length,1000);
+ samples[name].push(milliseconds);
+ }
+ assert.equal(boardDigest(db),initial,'all persistent board rows remain unchanged');
+ const medians=Object.fromEntries(Object.entries(samples).map(([name,values])=>[name,[...values].sort((a,b)=>a-b)[2]]));
+ const report={code,node:process.version,method:'end-to-end real child process, round-robin five, no warmup; full stdout+JSON assertions',population:{items:1000,events:db.prepare('SELECT count(*) AS n FROM event').get().n,shouts:23000,agents:801,historicalSubmits:1600,landingBatches:0},samplesMs:samples,mediansMs:medians,load:loadavg(),cpus:cpus().length,boardSha256:initial};
+ t.diagnostic(JSON.stringify(report));
+ for (const [name, median] of Object.entries(medians)) assert.ok(median < 100, `${name} end-to-end median ${median.toFixed(2)} ms exceeds 100 ms`); // budget: declared #1048 five-run fresh-process criterion; baseline measured 106-176 ms on the same seeded shape.
+ } finally { for(const fn of cleanups.reverse())fn(); }
+}
diff --git a/test/cli-startup.test.js b/test/cli-startup.test.js
index 1016ccbf..f440f596 100644
--- a/test/cli-startup.test.js
+++ b/test/cli-startup.test.js
@@ -10,6 +10,7 @@ import { delimiter, join, resolve, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
import { test } from 'node:test';
import { runFixtureChild } from './fixture-child.js';
+import { assertStartupBudgets } from './cli-startup-budget-fixture.js';
const REPO = resolve(import.meta.dirname, '..');
const BIN = join(REPO, 'bin', 'pullboard.js');
@@ -106,7 +107,7 @@ function fixture(t) {
return { run, runIn, worktree };
}
-test('a read command loads only its own modules [C7]', (t) => {
+test('a read command loads only its own modules [C7]', async (t) => {
const box = fixture(t);
const version = box.run('--version');
assert.match(version.stdout, /^\d+\.\d+\.\d+/u);
@@ -125,4 +126,5 @@ test('a read command loads only its own modules [C7]', (t) => {
assert.equal(here.length, 1, `claim asked the worktree for repo facts ${here.length} times: ${here.join(' | ')}`);
assert.ok(revParses.length <= 2, `claim started ${revParses.length} rev-parse processes: ${revParses.join(' | ')}`);
assert.ok(claim.gitCalls.length <= 10, `claim started ${claim.gitCalls.length} Git processes: ${claim.gitCalls.join(' | ')}`);
+ await assertStartupBudgets(t);
});