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(core): report excessive agent process CPU once per birth [A6,H16]
Corey Olsonbe992a26eff2
diff --git a/src/health-sentinel.js b/src/health-sentinel.jsindex 159a8dcc..d8e39e7b 100644--- a/src/health-sentinel.js+++ b/src/health-sentinel.js@@ -4,19 +4,21 @@ import { openBoardReadOnly } from './board.js';import { healthReport } from './health.js';import { healthSentinelEnabled } from './settings.js';import { Refused } from './refused.js';+import { agentCpuFindings } from './sentinel-cpu.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 }) {+export function scanHealthSentinel(file, { root, config, now, cpu = agentCpuFindings }) {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 });+ report.stuck.push(...cpu(db));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();diff --git a/src/sentinel-cpu.js b/src/sentinel-cpu.jsnew file mode 100644index 00000000..d830d447--- /dev/null+++ b/src/sentinel-cpu.js@@ -0,0 +1,68 @@+/** Native CPU observations for registered agent worktrees; no process is signalled [A6,H16]. */+import { execFileSync } from 'node:child_process';+import { readlinkSync, realpathSync } from 'node:fs';+import { basename, relative, sep } from 'node:path';++/** Read bounded native utility output without arguments or environment supplied by a process. */+function native(command, args) {+ return execFileSync(command, args, { encoding: 'utf8', timeout: 3000, maxBuffer: 8 * 1024 * 1024,+ stdio: ['ignore', 'pipe', 'ignore'], env: { ...process.env, LC_ALL: 'C', LANG: 'C' } });+}+/** ps CPU time is [days-][hours:]minutes:seconds, not elapsed wall time or percent CPU. */+function minutes(text) {+ const match = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+(?:\.\d+)?)$/u.exec(text);+ return match ? Number(match[1] ?? 0) * 1440 + Number(match[2] ?? 0) * 60 + Number(match[3]) + Number(match[4]) / 60 : NaN;+}+/** Parse birth identity separately from executable name, retaining only processes over the fixed CPU threshold. */+function rows(text) {+ return text.split('\n').flatMap(line => {+ const match = /^\s*(\d+)\s+(\S+)\s+(.{24})\s+(.+)$/u.exec(line);+ if (!match) return [];+ const cpu = minutes(match[2]), started = Date.parse(match[3]);+ return cpu > 20 && Number.isFinite(started) ? [{ pid: Number(match[1]), cpu, since: new Date(started).toISOString(), name: basename(match[4].trim()) }] : [];+ });+}+/** Canonical paths avoid symlink spelling differences; unreadable or vanished cwd never establishes ownership. */+function canonical(path) {+ try { return realpathSync(path); } catch { return null; /* A disappearing process/worktree has no attributable cwd. */ }+}+/** Report only native cwd ownership revalidated against the same PID birth after the cwd observation. */+export function agentCpuFindings(db, { platform = process.platform, run = native, readLink = readlinkSync } = {}) {+ if (!['darwin', 'linux'].includes(platform)) return [];+ const format = ['pid=', 'time=', 'lstart=', 'comm='].flatMap(field => ['-o', field]);+ let candidates, confirmed, directories = new Map();+ try {+ candidates = rows(run('/bin/ps', ['-e', ...format]));+ if (!candidates.length) return [];+ if (platform === 'darwin') {+ const output = run('/usr/sbin/lsof', ['-b', '-a', '-d', 'cwd', '-p', candidates.map(row => row.pid).join(','), '-Fpn']);+ let pid;+ for (const line of output.split('\n')) {+ if (/^p\d+$/u.test(line)) pid = Number(line.slice(1));+ else if (pid && line.startsWith('n')) directories.set(pid, canonical(line.slice(1)));+ }+ } else {+ for (const row of candidates) {+ try { directories.set(row.pid, canonical(readLink(`/proc/${row.pid}/cwd`))); }+ catch { /* A process may exit or deny cwd access between the ps and readlink observations. */ }+ }+ }+ confirmed = new Set(rows(run('/bin/ps', ['-p', candidates.map(row => row.pid).join(','), ...format])).map(row => `${row.pid}:${row.since}`));+ } catch { return []; /* Unavailable native observations cannot prove process ownership or CPU use. */ }+ const agents = db.prepare('SELECT agent_id, agent_path FROM agent WHERE agent_id != ?').all('coordinator')+ .map(agent => ({ ...agent, path: canonical(agent.agent_path) })).filter(agent => agent.path)+ .sort((left, right) => right.path.length - left.path.length);+ return candidates.flatMap(row => {+ const cwd = directories.get(row.pid);+ if (!cwd || !confirmed.has(`${row.pid}:${row.since}`)) return [];+ const agent = agents.find(agent => { const child = relative(agent.path, cwd); return !child || child !== '..' && !child.startsWith('..' + sep) && !child.startsWith(sep); });+ if (!agent) return [];+ const key = `AGENT_CPU:${row.pid}:${row.since}`;+ // Durable prior alerts survive temporary observation gaps and observer restarts; PID birth prevents reuse collisions.+ const last = db.prepare("SELECT event_detail FROM event WHERE event_kind='health-scan' ORDER BY event_id DESC LIMIT 1").get();+ const active = last ? JSON.parse(last.event_detail).active.some(finding => finding.key === key) : false;+ if (!active && db.prepare("SELECT 1 FROM event WHERE event_kind='health-failure' AND json_extract(event_detail,'$.key')=? LIMIT 1").get(key)) return [];+ return [{ key, cause: 'AGENT_CPU', item: null, subject: `pid ${row.pid}`, title: row.name, since: row.since,+ why: `${row.cpu.toFixed(2)} CPU minutes used in agent worktree ${agent.path}`, next: 'inspect the owning agent process before deciding whether to stop it', owner: { who: agent.agent_id } }];+ });+}diff --git a/test/sentinel-cpu.test.js b/test/sentinel-cpu.test.jsindex 97ba6ecf..d58c3b2d 100644--- a/test/sentinel-cpu.test.js+++ b/test/sentinel-cpu.test.js@@ -5,6 +5,7 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { test } from 'node:test';import * as store from '../src/board.js';+import { runFixtureGit } from './fixture-child.js';import { scanHealthSentinel } from '../src/health-sentinel.js';// CPU time is observed, not burned: the native utility port supplies an exact ps/lsof transcript.@@ -13,6 +14,7 @@ test('the sentinel names an agent process past 20 CPU minutes once [A6,H16]', asconst directory = mkdtempSync(join(tmpdir(), 'pullboard-cpu-'));const root = join(directory, 'repo'), work = join(directory, 'core');mkdirSync(root); mkdirSync(work);+ runFixtureGit(['init', '-q', '-b', 'main'], { cwd: root });const file = join(directory, 'board.sqlite'), board = store.openBoard(file);store.register(board, { lane: 'coordinator', path: root });const seat = store.register(board, { lane: 'core', path: work });