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(rules): count trunk proof and recent failures [S1,A1,A2]
Corey Olson5e52f935ead5
diff --git a/src/api.js b/src/api.jsindex 2c3227d2..1705ce53 100644--- a/src/api.js+++ b/src/api.js@@ -44,6 +44,10 @@ import {} from './projects.js';import { milestoneRoadmap } from './roadmap.js';import { proofStats } from './stats.js';+import {+ ruleProofCounts,+ ruleProofWindow,+} from './rule-proof-counts.js';import {SUMMARY_KEYS,itemSummary,@@ -86,7 +90,7 @@ export { moveArgs } from './api-moves.js';/** Inputs shared by the complete state cache and the lightweight live-change watcher. */const STATE_REVISION_INPUTS = Object.freeze([- 'identity', 'head', 'trunk', 'files', 'event', 'agents', 'leases', 'requestReceipts', 'milestones', 'externalRoadmap', 'eventLogVersion',+ 'identity', 'head', 'trunk', 'files', 'event', 'agents', 'leases', 'requestReceipts', 'milestones', 'externalRoadmap', 'eventLogVersion', 'ruleProofWindow',]);/** Serialize named state inputs in one stable order for cache and stream comparisons. */@@ -126,13 +130,15 @@ function localRevisionInputs(board, now) {item.item_status === 'submitted' && Boolean(item.item_review_by) && (item.item_review_until ?? '') > now,]);const expiries = leases.flatMap(([, , , leaseUntil, , reviewUntil, claimLive, reviewLive]) => [claimLive ? leaseUntil : null, reviewLive ? reviewUntil : null]);+ const proofWindow = ruleProofWindow(board, now);return {event: board.db.prepare('SELECT COALESCE(MAX(event_id), 0) AS id FROM event').get().id,agents: store.listAgents(board),leases,requestReceipts: board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get('relay_person_requests')?.meta_value ?? null,milestones: store.milestones(board),- nextExpiry: expiries.filter(Boolean).sort()[0] ?? null,+ ruleProofWindow: proofWindow.events,+ nextExpiry: [...expiries, proofWindow.nextExpiry].filter(Boolean).sort()[0] ?? null,};}@@ -172,6 +178,7 @@ function boardStateRevision(root, id, isMain, { projects = listApiProjects, scopmilestones: visibleMilestoneInputs(local.milestones, scopeCommonDir !== null),externalRoadmap: local.externalMilestones,eventLogVersion: store.EVENT_LOG_VERSION,+ ruleProofWindow: local.ruleProofWindow,};const revision = stateRevision(inputs);return { cacheId: info.commonDir + '\0' + id, revision, event: local.event, milestones: local.externalMilestones,@@ -420,6 +427,7 @@ function watchLocalStateRevision(board, { scopeCommonDir = null } = {}) {milestones: visibleMilestoneInputs(local.milestones, scopeCommonDir !== null),externalRoadmap,eventLogVersion: store.EVENT_LOG_VERSION,+ ruleProofWindow: local.ruleProofWindow,});}@@ -492,6 +500,7 @@ function buildLocalBoardState(root, boardId, board, codeIsMain, { previous = nulstate.milestones = projectData.milestones;state.blocks = personBlockWords(repoInfo(root).commonDir, board.clock.now()); // Needs you below is recomputed with them [C6].const decorated = projectSpecApprovals(projectFit(pendingFit(repoInfo(root).commonDir), projectRowDecisions(projectData.rowDecisions, state)), specApprovalState(root, { board, config }));+ decorated.ruleCounts = ruleProofCounts(root, board, decorated.spec);const bases = new Map(decorated.items.map((item) => [item.id, item]));for (const id of dirtyIds) {if (!currentById.has(id)) continue;diff --git a/src/browser-admission.js b/src/browser-admission.jsindex 3e535050..32e2c2e5 100644--- a/src/browser-admission.js+++ b/src/browser-admission.js@@ -23,6 +23,7 @@ import {cleanGitEnvironment,git,} from './git.js';+import { literalShellWords } from './literal-shell-words.js';import { foreignNodeOptions } from './test-isolation.js';const MODULE_SUFFIXES = ['.js', '.mjs', '.cjs', '.cts', '.json'];@@ -65,41 +66,7 @@ const SAFE_CHILD_PROCESS_MODULES = new Map([['src/resources.js', 'reads process identity with /bin/ps'],]);-/** Split a literal shell command into words, refusing expansion, operators, and incomplete quoting. */-export function literalShellWords(command) {- if (typeof command !== 'string' || !command.trim()) return null;- const words = [];- let word = '';- let started = false;- let quote = '';- for (const character of command) {- if (character === '\n' || character === '\r') return null;- if (quote === "'") {- if (character === "'") quote = '';- else word += character;- started = true;- continue;- }- if (quote === '"') {- if (character === '"') quote = '';- else if ('$`\\'.includes(character)) return null;- else word += character;- started = true;- continue;- }- if (character === '"' || character === "'") { quote = character; started = true; continue; }- if (/\s/u.test(character)) {- if (started) { words.push(word); word = ''; started = false; }- continue;- }- if (';&|<>$`(){}*?[]\\'.includes(character)) return null;- word += character;- started = true;- }- if (quote) return null;- if (started) words.push(word);- return words;-}+export { literalShellWords } from './literal-shell-words.js';/** Parse only explicit Node test-runner files and the small, literal option set used by frozen checks. */function explicitRunnerFiles(args) {diff --git a/src/commands/status.js b/src/commands/status.jsindex fc3c0bf0..178df5f3 100644--- a/src/commands/status.js+++ b/src/commands/status.js@@ -1,6 +1,8 @@/** 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 { projectRowDecisions } from '../row-decisions.js';+import { ruleProofCounts } from '../rule-proof-counts.js';import {reviewQueueLine,} from '../next-steps.js';@@ -34,7 +36,8 @@ export function run(io, { values }) {const me = whoAmI(ctx, board);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),+ const rows = projectRowDecisions(store.rowDecisions(board), { root: ctx.info.root, spec: loadSpec(ctx.info.root, ctx.config).rows }).spec;+ return { me, mine, ruleCounts: ruleProofCounts(ctx.info.root, board, rows), 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),submitInvariantProposals: submitInvariantProposals(store.eventsOfKinds(board, ['submit', 'landing_batch']), ctx.config) };});if (values.json) {diff --git a/src/json.js b/src/json.jsindex b3eb10d9..4d436375 100644--- a/src/json.js+++ b/src/json.js@@ -41,7 +41,7 @@ export const JSON_SHAPES = {'milestone ship': shape({ milestone: 'object', into: 'string|null', moved: 'array', notMoved: 'array' }),show: shape({ item_id: 'number', item_title: 'string', item_lane: 'string', item_status: 'string', verdicts: 'array', thread: 'array' }),stats: shape({ stats: 'object', gateWaits: 'array' }),- status: shape({ me: 'object', mine: 'array', stats: 'object', reviewQueue: 'object', unread: 'number', relay: 'object' }),+ status: shape({ me: 'object', mine: 'array', ruleCounts: 'object', stats: 'object', reviewQueue: 'object', unread: 'number', relay: 'object' }),doctor: shape({ problems: 'array' }),health: shape({ asOf: 'string', thresholds: 'object', stuck: 'array', waiting: 'array' }),'sentinel propose': shape({ sentinel: 'object' }),diff --git a/src/literal-shell-words.js b/src/literal-shell-words.jsnew file mode 100644index 00000000..0665b158--- /dev/null+++ b/src/literal-shell-words.js@@ -0,0 +1,37 @@+/** Read literal shell words without interpreting expansions or operators. */+/** Split a literal shell command into words, refusing expansion, operators, and incomplete quoting. */+export function literalShellWords(command) {+ if (typeof command !== 'string' || !command.trim()) return null;+ const words = [];+ let word = '';+ let started = false;+ let quote = '';+ for (const character of command) {+ if (character === '\n' || character === '\r') return null;+ if (quote === "'") {+ if (character === "'") quote = '';+ else word += character;+ started = true;+ continue;+ }+ if (quote === '"') {+ if (character === '"') quote = '';+ else if ('$`\\'.includes(character)) return null;+ else word += character;+ started = true;+ continue;+ }+ if (character === '"' || character === "'") { quote = character; started = true; continue; }+ if (/\s/u.test(character)) {+ if (started) { words.push(word); word = ''; started = false; }+ continue;+ }+ if (';&|<>$`(){}*?[]\\'.includes(character)) return null;+ word += character;+ started = true;+ }+ if (quote) return null;+ if (started) words.push(word);+ return words;+}+diff --git a/src/rule-proof-counts.js b/src/rule-proof-counts.jsnew file mode 100644index 00000000..5ebffb46--- /dev/null+++ b/src/rule-proof-counts.js@@ -0,0 +1,110 @@+/** Counts distinguish named rule gates from committed trunk execution evidence [S1,A1,A2]. */+import { createHash } from 'node:crypto';+import { readFileSync } from 'node:fs';+import { basename } from 'node:path';+import {+ mainCheckout,+ tryGit,+} from './git.js';+import { literalShellWords } from './literal-shell-words.js';+import { receiptFields } from './gate-run-receipt.js';++const WEEK = 7 * 86_400_000;+const FILE = /^(?:test\/)[A-Za-z0-9_./-]+\.(?:[cm]?js|cts)$/u;++/** Read schema-valid recorded runs only; old or incomplete receipts cannot prove a row. */+function runs(board) {+ return board.db.prepare("SELECT event_id, event_by, event_detail FROM event WHERE event_kind = 'gate-run' ORDER BY event_id").all().flatMap(row => {+ try {+ const run = receiptFields(JSON.parse(row.event_detail).run);+ return run ? [{ ...run, event: row.event_id, by: row.event_by }] : [];+ } catch { return []; }+ });+}++/** Only explicit test-file declarations identify a machine gate; review and opaque commands do not. */+function rowFiles(row) {+ const files = String(row.gate ?? '').split(',').map(file => file.trim().replace(/^\.\//u, ''));+ return files.length && files.every(file => FILE.test(file) && !file.split('/').includes('..')) ? files : [];+}++/** Parse one literal Node test selection without pretending filtered, sharded or unknown options ran the file. */+function selectedFiles(args, tracked, canonical) {+ const files = [];+ for (let at = 0; at < args.length; at += 1) {+ const arg = args[at];+ if (/^--test-concurrency=\d+$/u.test(arg)) continue;+ if (arg === '--test-concurrency') { if (!/^\d+$/u.test(args[++at] ?? '')) return []; continue; }+ if (arg.startsWith('-')) return [];+ const file = arg.replace(/^\.\//u, '');+ if (!FILE.test(file) || !tracked.has(file)) return [];+ files.push(file);+ }+ // The canonical runner deliberately selects tracked .test.js/.test.mjs entry points, not helper modules.+ if (!files.length) return [...tracked].filter(file => !file.split('/').some(part => part === 'node_modules' || part.startsWith('.'))).filter(file => canonical+ ? /(?:^|\/)[^/]+\.test\.(?:js|mjs)$/u.test(file)+ : /(?:^|\/)(?:test\.[cm]?js|(?:test-.+|.+[._-]test)\.[cm]?js)$/u.test(file));+ return files;+}++/** Resolve supported configured test commands at the receipt's committed source; opaque commands prove no file. */+function includedFiles(root, commit, command, tracked, depth = 0) {+ if (depth > 4) return [];+ const words = literalShellWords(command);+ if (!words) {+ // Only an AND chain is safe to compose: a green shell result means each selected command succeeded.+ const parts = command.split(' && ');+ return parts.length > 1 && parts.every(part => literalShellWords(part))+ ? parts.flatMap(part => includedFiles(root, commit, part, tracked, depth + 1)) : [];+ }+ if (words[0] === 'npm' && (words[1] === 'test' && words.length === 2 || words[1] === 'run' && words.length === 3)) {+ try {+ const source = tryGit(root, ['show', `${commit}:package.json`]);+ const script = JSON.parse(source.stdout).scripts?.[words[1] === 'test' ? 'test' : words[2]];+ return typeof script === 'string' ? includedFiles(root, commit, script, tracked, depth + 1) : [];+ } catch { return []; }+ }+ if (basename(words[0] ?? '') !== 'node') return [];+ if (words[1] === '--test') return selectedFiles(words.slice(2), tracked, false);+ if (words[1]?.replace(/^\.\//u, '') === 'bin/run-tests.js' && tracked.has('bin/run-tests.js')) {+ const source = tryGit(root, ['show', `${commit}:bin/run-tests.js`]);+ if (source.status !== 0 || source.stdout !== readFileSync(new URL('../bin/run-tests.js', import.meta.url), 'utf8')) return [];+ return selectedFiles(words.slice(2), tracked, true);+ }+ return [];+}++/** Count the board's approved Spec rows against current trunk gates and independently recent trunk failures. */+export function ruleProofCounts(root, board, rows, { now = board.clock.now().getTime() } = {}) {+ const approved = rows.filter(row => row.status === 'approved');+ const gated = approved.filter(row => String(row.gate ?? '').trim());+ const counts = { approved: approved.length, gated: gated.length, ungated: approved.length - gated.length, proven: 0, unproven: gated.length, contradicted: 0 };+ if (!gated.length) return counts;+ const history = runs(board).filter(run => run.by === 'coordinator' && run.head === run.main && ['gate', 'land'].includes(run.kind));+ const failures = new Set(history.filter(run => !run.green && Date.parse(run.at) <= now && Date.parse(run.at) >= now - WEEK).flatMap(run => run.failures.map(failure => failure.file)));+ counts.contradicted = gated.filter(row => rowFiles(row).some(file => failures.has(file))).length;+ const trunk = mainCheckout(root);+ if (!trunk?.commit || !trunk.branch) return counts;+ try {+ const config = JSON.parse(tryGit(root, ['show', `${trunk.commit}:pullboard.json`]).stdout);+ if (typeof config.gate !== 'string' || !config.gate.trim()) return counts;+ const command = createHash('sha256').update(config.gate).digest('hex');+ const tree = tryGit(root, ['rev-parse', `${trunk.commit}^{tree}`]).stdout.trim();+ if (!history.some(run => run.green && run.head === trunk.commit && run.tree === tree && run.command === command)) return counts;+ const tracked = new Set(tryGit(root, ['ls-tree', '-rz', trunk.commit]).stdout.split('\0')+ .filter(entry => /^(?:100644|100755) blob /u.test(entry)).map(entry => entry.slice(entry.indexOf('\t') + 1)));+ const included = new Set(includedFiles(root, trunk.commit, config.gate, tracked));+ counts.proven = gated.filter(row => { const files = rowFiles(row); return files.length > 0 && files.every(file => included.has(file)); }).length;+ counts.unproven = gated.length - counts.proven;+ } catch { /* Missing committed inputs leave named gates unproven, never green. */ }+ return counts;+}++/** The time-dependent receipt window is a cache input, with an expiry even when no board event changes. */+export function ruleProofWindow(board, now) {+ const at = Date.parse(now);+ const candidates = runs(board).filter(run => !run.green && run.by === 'coordinator' && run.head === run.main);+ const active = candidates.filter(run => Date.parse(run.at) <= at && Date.parse(run.at) >= at - WEEK);+ const boundaries = candidates.flatMap(run => [Date.parse(run.at), Date.parse(run.at) + WEEK + 1]).filter(time => time > at);+ return { events: active.map(run => run.event), nextExpiry: boundaries.length ? new Date(boundaries.reduce((a, b) => Math.min(a, b))).toISOString() : null };+}