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(health): record deduplicated sentinel findings [A6]
Corey Olson24ec9e3b9b8c
diff --git a/src/board.js b/src/board.jsindex 38f376bc..043505b6 100644--- a/src/board.js+++ b/src/board.js@@ -19,6 +19,7 @@ import { ENGINE_VERSION, VERDICT_REVIEW_ENGINE, GUARDS, IN_STATE, MOVES, STATES,import { Refused } from './refused.js';import { causeProblem, requireNeverAgain } from './rigor.js';import { barCorrectionFields } from './bar-corrections.js';+import { HEALTH_SENTINEL_ENGINE, healthFindingIdentity, healthFindingNotice, normalizedHealthFindings } from './health-receipts.js';import { factReference } from './fact-reference.js';import { factFromEvent, requestAnswerRefusal, tellAnswerImplications, tellFactImplications, tellVerdictImplications } from './implies.js';import { landingFlakes, landingWaiverCovers, landingWaiverKind } from './landing-exceptions.js';@@ -1875,6 +1876,48 @@ export function shout(board, message) {return atomic(board, () => insertShout(board, message));}+/** Record one current health snapshot atomically, notifying each new or resolved episode once [A6]. */+export function recordHealthFindings(board, { agentId, observedRevision, findings }) {+ return atomic(board, () => {+ if ((board.executionEngineVersion ?? ENGINE_VERSION) < HEALTH_SENTINEL_ENGINE) {+ throw new Refused('ENGINE_VERSION', `sentinel receipts require engine ${HEALTH_SENTINEL_ENGINE}; upgrade Pullboard before scanning`);+ }+ if (!board.db.prepare('SELECT 1 FROM agent WHERE agent_id = ?').get(agentId)) {+ throw new Refused('NOT_JOINED', 'join this board before recording a health scan: pullboard join <lane>');+ }+ const revision = board.db.prepare('SELECT COALESCE(MAX(event_id), 0) AS revision FROM event').get().revision;+ if (!Number.isSafeInteger(observedRevision) || observedRevision !== revision) {+ throw new Refused('HEALTH_SCAN_STALE', 'the board changed while health was scanning; run pullboard resume again');+ }+ const active = normalizedHealthFindings(findings);+ const last = board.db.prepare("SELECT event_detail FROM event WHERE event_kind = 'health-scan' ORDER BY event_id DESC LIMIT 1").get();+ const previous = last ? JSON.parse(last.event_detail).active : [];+ const before = new Map(previous.map(finding => [healthFindingIdentity(finding), finding]));+ const after = new Map(active.map(finding => [healthFindingIdentity(finding), finding]));+ const added = active.filter(finding => !before.has(healthFindingIdentity(finding)));+ const resolved = previous.filter(finding => !after.has(healthFindingIdentity(finding)));+ if (!added.length && !resolved.length) return { added: [], resolved: [] };+ const agents = listAgents(board);+ const lanes = [...new Set(agents.map(agent => agent.agent_lane))];+ /** Deliver through ordinary feed/inbox records without registering a synthetic worktree seat. */+ const notify = (finding, cleared) => {+ const owner = finding.owner;+ const targets = new Set([COORDINATOR]);+ if (owner && (owner === PERSON || lanes.includes(owner) || agents.some(agent => agent.agent_id === owner))) targets.add(owner);+ for (const to of targets) insertShout(board, { from: 'sentinel', to, text: healthFindingNotice(finding, cleared), lanes });+ const item = finding.item === null ? null : itemById(board, finding.item);+ logEvent(board, 'sentinel', cleared ? 'health-resolved' : 'health-failure', finding.item, {+ key: finding.key, cause: `refusal:${finding.cause}`, since: finding.since, subject: finding.subject,+ owner, commit: item?.item_commit ?? null, engine: HEALTH_SENTINEL_ENGINE,+ });+ };+ for (const finding of resolved) notify(finding, true);+ for (const finding of added) notify(finding, false);+ logEvent(board, agentId, 'health-scan', null, { active, engine: HEALTH_SENTINEL_ENGINE });+ return { added: added.map(finding => finding.key), resolved: resolved.map(finding => finding.key) };+ });+}+/*** Pass an open coordinator decision to the person with the original question and note (B27).*diff --git a/src/cli.js b/src/cli.jsindex f35149a5..94586ab2 100644--- a/src/cli.js+++ b/src/cli.js@@ -91,6 +91,7 @@ import { watchCommand } from './watch.js';import { serveMcp } from './mcp.js';import { doctorProblems, doctrineProblems } from './doctor.js';import { boardHealth, healthLines } from './health.js';+import { scanHealthSentinel } from './health-sentinel.js';import { staleFrozenItems, staleItemFinding } from './approved-rows.js';import { mainPolicy, policyAt, itemPolicy, submissionPaths, frozenCheck, checkAtCommit, dependencySnapshots, requireTrunkMerge, trunkRef } from './trusted-policy.js';import { captureVerdictReview, staleVerdictRefusal, verdictProjector, verdictTrunk } from './verdict-freshness.js';@@ -1326,8 +1327,16 @@ function boardSetup(ctx, card, identity) {* @param {Awaited<ReturnType<typeof keepViewRunning>>} view what keeping the background view running did* @returns {number}*/-function resumeHere(io, view) {+async function resumeHere(io, view) {const ctx = context(io);+ await withBoard(ctx, async board => {+ const me = whoAmI(ctx, board);+ const observation = scanHealthSentinel(ctx.file, { root: ctx.info.root, config: ctx.config, now: ctx.clock.now() });+ if (observation) {+ try { await ordered(ctx, board, 'recordHealthFindings', [{ agentId: me.id, ...observation }]); }+ catch (error) { if (!(error instanceof Refused) || error.code !== 'HEALTH_SCAN_STALE') throw error; }+ }+ });const { root, isMain } = ctx.info;const mainRoot = primaryCheckoutRoot(ctx.info);const worktreeConfig = mainRoot ? (isMain ? ctx.config : loadConfig(mainRoot)) : null;diff --git a/src/engine.js b/src/engine.jsindex a88943bd..b109f1b3 100644--- a/src/engine.js+++ b/src/engine.js@@ -5,6 +5,7 @@ import { recordedRefusal } from './recorded-refusal.js';import { BAR_ENGINE, carriesBarReason } from './bar-corrections.js';import { carriesImplies, IMPLIES_ENGINE } from './implies.js';import { CHECK_ACCEPT_ENGINE } from './check-accept.js';+import { HEALTH_SENTINEL_ENGINE } from './health-receipts.js';import { CAUSE_ENGINE, ENGINE_VERSION, VERDICT_REVIEW_ENGINE } from './machine.js';import { Refused } from './refused.js';import { requestMoveProblem, recordRequestMove } from './relay-requests.js';@@ -20,6 +21,7 @@ export const ENGINE_OPERATIONS = Object.freeze(['addMilestone', 'editMilestoneItems', 'moveMilestone', 'editMilestone', 'removeMilestone','recordRowDecisions', 'applyRowDecisions', 'appendFact','recordLandingBatch', 'recordLandingWaiver', 'recordLandingFlake', 'finishLandingBatch', 'acceptCheck',+ 'recordHealthFindings',]);/** Engine version at which each ordered operation first has stable replay semantics. */@@ -27,6 +29,7 @@ const OPERATION_ENGINE = Object.freeze({ reopen: 8, recordLandingBatch: 8, recor/** Dependency edits, bar reasons and sealed review metadata retain their distinct recorded engine meanings. */function minimumOperationEngine(operation, args, board) {+ if (operation === 'recordHealthFindings') return HEALTH_SENTINEL_ENGINE;const options = args[1];const given = (name) => Boolean(options && typeof options === 'object' && Object.hasOwn(options, name) && options[name] !== undefined && options[name] !== null && options[name] !== false);if (board && ['recordLandingBatch', 'finishLandingBatch'].includes(operation)) {diff --git a/src/health-receipts.js b/src/health-receipts.jsnew file mode 100644index 00000000..e45758e8--- /dev/null+++ b/src/health-receipts.js@@ -0,0 +1,38 @@+/** Durable work-health observations, separate from the person's decisions [A6,H16]. */+import { Refused } from './refused.js';++/** The allocated engine for ordered sentinel observations; earlier moves keep their meaning. */+export const HEALTH_SENTINEL_ENGINE = 42;++/** Validate and retain only the fields needed to identify and explain a health finding. */+export function normalizedHealthFindings(findings) {+ if (!Array.isArray(findings) || findings.length > 10_000) {+ throw new Refused('HEALTH_FINDINGS', 'a sentinel scan needs at most 10000 health findings; run pullboard health and retry the scan');+ }+ const seen = new Set();+ return findings.map(finding => {+ const text = key => typeof finding?.[key] === 'string' && finding[key].length > 0 && finding[key].length <= 8192;+ if (!['key', 'cause', 'subject', 'title', 'since', 'why', 'next'].every(text)+ || !/^[A-Z][A-Z0-9_]*$/u.test(finding.cause) || !Number.isFinite(Date.parse(finding.since))+ || finding.item !== null && (!Number.isSafeInteger(finding.item) || finding.item < 1)+ || seen.has(finding.key)) {+ throw new Refused('HEALTH_FINDINGS', 'a sentinel finding needs a unique key, cause, subject, time and next step; run pullboard health again');+ }+ const who = finding.owner?.who ?? finding.detail?.reviewer ?? finding.detail?.builder ?? finding.detail?.holder ?? null;+ if (who !== null && (typeof who !== 'string' || !who || who.length > 256)) {+ throw new Refused('HEALTH_FINDINGS', 'a sentinel finding needs its owner address; run pullboard health again');+ }+ seen.add(finding.key);+ return Object.fromEntries(['key', 'cause', 'item', 'subject', 'title', 'since', 'why', 'next'].map(key => [key, finding[key]]).concat([['owner', who]]));+ });+}++/** A new lease or owner is a new episode, even if no scan observed the intervening clear state. */+export function healthFindingIdentity(finding) {+ return JSON.stringify([finding.key, finding.since, finding.owner]);+}++/** Keep a whole owner address and the original cause and next step in each feed notice. */+export function healthFindingNotice(finding, resolved = false) {+ return `${resolved ? 'Resolved' : 'Stuck'}: ${finding.subject} ${finding.title} [${finding.cause}], since ${finding.since}. ${finding.why}. ${finding.owner ? `Owner: ${finding.owner}. ` : ''}Next: ${finding.next}.`;+}diff --git a/src/health-sentinel.js b/src/health-sentinel.jsnew file mode 100644index 00000000..426901b7--- /dev/null+++ b/src/health-sentinel.js@@ -0,0 +1,23 @@+/** Snapshot health without keeping a board write lock across Git's merge checks [A6]. */+import { existsSync } from 'node:fs';+import { openBoardReadOnly } from './board.js';+import { healthReport } from './health.js';+import { healthSentinelEnabled } from './settings.js';+import { healthFindingIdentity, normalizedHealthFindings } from './health-receipts.js';++/** A missing board or an explicitly disabled sentinel has no observation to publish. */+export function scanHealthSentinel(file, { root, config, now }) {+ if (!healthSentinelEnabled(config) || !existsSync(file)) return null;+ const db = openBoardReadOnly(file);+ try {+ db.exec('BEGIN');+ const observedRevision = db.prepare('SELECT COALESCE(MAX(event_id), 0) AS revision FROM event').get().revision;+ const report = healthReport({ db, root, config, now });+ const last = db.prepare("SELECT event_detail FROM event WHERE event_kind = 'health-scan' ORDER BY event_id DESC LIMIT 1").get();+ const before = (last ? JSON.parse(last.event_detail).active : []).map(healthFindingIdentity).sort();+ const after = normalizedHealthFindings(report.stuck).map(healthFindingIdentity).sort();+ db.exec('COMMIT');+ if (JSON.stringify(before) === JSON.stringify(after)) return null;+ return { observedRevision, findings: report.stuck };+ } finally { db.close(); }+}diff --git a/src/machine.js b/src/machine.jsindex d569abe7..a8514dcc 100644--- a/src/machine.js+++ b/src/machine.js@@ -10,7 +10,7 @@*//** Executable move semantics, carried by every sealed move and retained during replay [H16]. */-export const ENGINE_VERSION = 33;+export const ENGINE_VERSION = 42;/** The engine at which a reject, reopen or person fact can carry a cause key (#713); older moves replay unchanged [D1,H16]. */export const CAUSE_ENGINE = 30;diff --git a/src/relay-sender.js b/src/relay-sender.jsindex e7d1924b..52fce8d3 100644--- a/src/relay-sender.js+++ b/src/relay-sender.js@@ -7,6 +7,7 @@ export function relayMoveActor(move) {if (!Array.isArray(args)) return null;if (move.operation === 'addItem') return args[0]?.by ?? null;if (move.operation === 'shout') return args[0]?.from ?? null;+ if (move.operation === 'recordHealthFindings') return args[0]?.agentId ?? null;if (['holdLane', 'releaseLane'].includes(move.operation) && args[1]?.asPerson) return 'person';if (move.operation === 'release') return args[1] ?? null;if (['reserveNextReview', 'addMilestone', 'recordRowDecisions', 'applyRowDecisions', 'recordLandingBatch', 'recordLandingWaiver', 'recordLandingFlake', 'finishLandingBatch'].includes(move.operation)) return args[0]?.agentId ?? null;diff --git a/src/rigor.js b/src/rigor.jsindex b6ccdd7e..9540357c 100644--- a/src/rigor.js+++ b/src/rigor.js@@ -5,6 +5,7 @@*/import { COORDINATOR } from './config.js';import { Refused } from './refused.js';+import { HEALTH_SENTINEL_ENGINE } from './health-receipts.js';/** The four kinds of cause key and their shapes, in the order help and refusals name them. */export const CAUSE_FORMS = Object.freeze(['test:<file>::<title>', 'refusal:<CODE>', 'row:<id>', 'doctrine:<id>']);@@ -135,10 +136,12 @@ export function rigorReport(events, { person }) {let uncaused = 0;/** The running record for one cause key. */const entry = (key) => {- if (!byKey.has(key)) byKey.set(key, { key, reads: causeReading(key), items: new Map(), occurrences: 0, neverAgain: false });+ if (!byKey.has(key)) byKey.set(key, { key, reads: causeReading(key), items: new Map(), occurrences: 0, healthOccurrences: 0, neverAgain: false });return byKey.get(key);};for (const event of events) {+ if (event.event_kind === 'health-failure'+ && (event.event_by !== 'sentinel' || JSON.parse(event.event_detail)?.engine !== HEALTH_SENTINEL_ENGINE)) continue;const never = neverAgainCause(event, person);if (never && !isMergeConflict(never)) {const found = entry(never);@@ -146,7 +149,7 @@ export function rigorReport(events, { person }) {if (event.item_id !== null && !found.items.has(event.item_id)) found.items.set(event.item_id, new Set());continue;}- if (!['reject', 'reopen'].includes(event.event_kind)) continue;+ if (!['reject', 'reopen', 'health-failure'].includes(event.event_kind)) continue;const keys = eventCauses(event);if (!keys.length) {uncaused += 1;@@ -156,15 +159,17 @@ export function rigorReport(events, { person }) {for (const key of keys.filter((candidate) => !isMergeConflict(candidate))) {const found = entry(key);found.occurrences += 1;+ if (event.event_kind === 'health-failure') found.healthOccurrences += 1;+ if (event.item_id === null) continue;const commits = found.items.get(event.item_id) ?? new Set();if (commit) commits.add(commit);found.items.set(event.item_id, commits);}}const causes = [...byKey.values()]+ .filter(found => found.neverAgain || found.healthOccurrences >= 2 || found.items.size >= 2 || [...found.items.values()].some(commits => commits.size >= 2)).map((found) => ({ key: found.key, reads: found.reads, occurrences: found.occurrences, neverAgain: found.neverAgain,items: [...found.items].map(([id, commits]) => ({ id, commits: [...commits] })).sort((a, b) => a.id - b.id) }))- .filter((found) => found.neverAgain || found.items.length >= 2 || found.items.some((item) => item.commits.length >= 2)).sort((a, b) => Number(b.neverAgain) - Number(a.neverAgain) || b.items.length - a.items.length || b.occurrences - a.occurrences || a.key.localeCompare(b.key));return { causes, uncaused };}diff --git a/src/serve-sentinel.js b/src/serve-sentinel.jsnew file mode 100644index 00000000..2ead76ba--- /dev/null+++ b/src/serve-sentinel.js@@ -0,0 +1,66 @@+/** Keep each view-served board's health observer running without overlapping scans [A6]. */+import { spawn } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { listProjects } from './projects.js';+import { loadConfig } from './config.js';+import { healthSentinelEnabled } from './settings.js';++/** Ten minutes is the declared background cadence, not a test performance budget. */+export const HEALTH_SENTINEL_INTERVAL_MS = 10 * 60_000;+const CLI = fileURLToPath(new URL('../bin/pullboard.js', import.meta.url));++/** Read the board and machine off switches before starting any background child. */+function sentinelRunsFor(root) {+ return healthSentinelEnabled(loadConfig(root));+}++/** Run the ordinary ordered resume path in one owned child and drain it on view shutdown. */+function resumeBoard(root, signal) {+ return new Promise((resolve, reject) => {+ const child = spawn(process.execPath, [CLI, 'resume', '--json'], {+ cwd: root, env: process.env, stdio: 'ignore', signal,+ });+ let timer;+ /** Bound shutdown of this exact child; never signal a peer or a process selected by name. */+ const stopping = () => {+ timer = setTimeout(() => { if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL'); }, 5_000); // budget: owned-child shutdown ceiling after AbortSignal sends SIGTERM.+ timer.unref();+ };+ signal.addEventListener('abort', stopping, { once: true });+ child.once('error', error => { if (error.name !== 'AbortError') reject(error); });+ child.once('close', code => {+ clearTimeout(timer); signal.removeEventListener('abort', stopping);+ if (code && !signal.aborted) reject(new Error(`health sentinel resume exited ${code}`));+ else resolve();+ });+ });+}++/** Start after the view listens; scans use ordinary resume so each board's off switch and ordering apply. */+export function startServeSentinel({ projectRoot, run = resumeBoard, projects = listProjects,+ every = setInterval, cancel = clearInterval, enabled = sentinelRunsFor, onError = () => {} } = {}) {+ const lifetime = new AbortController();+ let pending = null;+ /** Never start a second scan while the prior one or shutdown is still in flight. */+ const tick = () => {+ if (pending || lifetime.signal.aborted) return pending;+ pending = Promise.resolve().then(async () => {+ const roots = projectRoot ? [projectRoot] : projects().map(project => project.root);+ for (const root of new Set(roots)) {+ if (lifetime.signal.aborted) break;+ try { if (enabled(root)) await run(root, lifetime.signal); }+ catch (error) { if (!lifetime.signal.aborted) onError(error); }+ }+ }).catch(onError).finally(() => { pending = null; });+ return pending;+ };+ const timer = every(tick, HEALTH_SENTINEL_INTERVAL_MS);+ timer.unref?.();+ return {+ /** Stop the interval and wait for the exact active child to finish shutting down. */+ async close() {+ cancel(timer); lifetime.abort();+ if (pending) await pending;+ },+ };+}diff --git a/src/settings.js b/src/settings.jsindex 511bb8f2..2920e78d 100644--- a/src/settings.js+++ b/src/settings.js@@ -19,6 +19,9 @@ export function loadMachineSettings() {const file = machineSettingsFile();const value = readMachineSettingsFile(file);if (!value) return { gateSlots: DEFAULT_GATE_SLOTS, browserSlots: DEFAULT_BROWSER_SLOTS };+ if (value.health?.sentinel !== undefined && typeof value.health.sentinel !== 'boolean') {+ throw new Refused('BAD_MACHINE_SETTINGS', `health.sentinel in ${file} must be true or false`);+ }if (value.gate?.browserFreeChecks !== undefined && typeof value.gate.browserFreeChecks !== 'boolean') {throw new Refused('BAD_MACHINE_SETTINGS', `gate.browserFreeChecks in ${file} must be true or false`);}@@ -82,6 +85,14 @@ export function viewBackgroundEnabled() {return loadMachineSettings().view?.background !== false;}+/** The automatic health observer is on unless the machine or this board explicitly turns it off. */+export function healthSentinelEnabled(config = {}) {+ if (config.health?.sentinel !== undefined && typeof config.health.sentinel !== 'boolean') {+ throw new Refused('BAD_CONFIG', 'health.sentinel in pullboard.json must be true or false');+ }+ return config.health?.sentinel !== false && loadMachineSettings().health?.sentinel !== false;+}+/*** The free-memory floor, in megabytes, below which the machine gate pool holds its queue, or null* when the hold is off. Gate and queue behavior is off by default, the person's rule, so an absent