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.

fix(sentinels): integrate board watches [A6,doctrine:C9]

Corey Olsone1c6c8f07fbd
diff --git a/docs/api.md b/docs/api.md
index 29c648ff..170dee53 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -164,6 +164,10 @@ For example: `flow: review wait average 61 min (1 measured; > 60 min); bottlenec
| `hook pre-merge-commit` | `version:number`, `messages:array` |
| `hook commit-msg` | `version:number`, `messages:array` |
| `hook pre-push` | `version:number`, `messages:array` |
+| `sentinel propose` | `version:number`, `sentinel:object` |
+| `sentinel approve` | `version:number`, `sentinel:object` |
+| `sentinel decline` | `version:number`, `sentinel:object` |
+| `sentinels` | `version:number`, `sentinels:array` |
<!-- api-command-shapes:end -->
`spec draft "<rule>" --doctrine --source "chat, 2026-10-16"` proposes a sourced doctrine row and returns a qualified `id`, such as `doctrine:DR1`, for the existing person approval commands. Resume adds `doctrineNotes`, an array of newly seen approved rules with `id`, `text` and `gate`; each checkout consumes its own notices. Drafts and pending applications are excluded. The shared approved doctrine also supplies frozen citations and stale-item comparisons in older checkouts.
@@ -519,3 +523,9 @@ Agents and the coordinator can set explicit item ranks with `milestone order <na
`resume` on the coordinator seat includes `rigor: {undrafted: [...]}`, naming each repeated cause that has no live or approved proved draft. Each entry retains the ordinary Rigor cause key, item evidence and commits. The text resume names the proof-bearing `pullboard rigor draft` command. Declined repeats stay quiet until a new item repeats them. `needsYou` may contain an individual `kind: "rigor-draft"` call with `cause`, `evidence`, `proof`, a qualified spec or doctrine `target`, and `what: "Approve or Decline"`. An ordinary draft remains in the existing aggregate count; a Rigor draft is not counted twice. These fields add no person permission: the existing person-only approval and decline channels still apply.
A project may declare a `staticChecks` command in `pullboard.json` (empty by default). Submit uses the command from accepted main, and an explicit item check uses its accepted policy, so candidate settings cannot remove the guard. It runs before the frozen check and affected proof; a refusal retains the static log and reports the offending source. The existing queue and conservative browser classification still apply. Pullboard's own command checks actual CLI/View import bindings, the source-only prose command declaration, wall-clock budget explanations and doctrine counts. Browser prose behavior remains in the ordinary test suite.
+
+### Board-owned watches
+
+`pullboard sentinel propose <name> --check "<command>" --every 10m|hourly|daily --owner <seat or lane>` proposes a board row. Optional `--directory <relative path>`, `--timeout <milliseconds>` and `--next "<step>"` are part of the exact proposal. The directory defaults to this project, and must stay inside it; timeout defaults to 30000 ms and is a hang ceiling. The person approves or declines through the same person-channel guard as spec rows: `pullboard sentinel approve <name>` or `pullboard sentinel decline <name> --reason "<why>"`. An agent cannot approve. Any new command, directory, schedule, owner, timeout or next step needs fresh approval. No row in SPEC.md is edited.
+
+An approved watch runs when due on `resume` and through the background view’s ordinary resume worker. The existing board and machine `health.sentinel: false` switches suppress it. Ordered run leases prevent duplicate concurrent observers. External checks run outside the database write lock, in the approved directory, with bounded final output and an owned-child timeout; recorded replay never executes a command. On POSIX hosts shutdown drains the owned process group; Windows uses direct-child termination. A failed check notifies its owner once with its name, final output and next step; staying red posts no duplicate, and recovery posts one cleared notice. Every red run remains a `sentinel:<name>` cause receipt for Rigor, without inventing a code change. Cancellation records its outcome without creating a failure or recovery notice. `pullboard sentinels --json` lists current rows, their owners, approval, latest result and current proposal’s run history. This is engine 53; earlier engines refuse the new moves before replay.
diff --git a/docs/formats.md b/docs/formats.md
index 0bc8057e..e3562965 100644
--- a/docs/formats.md
+++ b/docs/formats.md
@@ -148,6 +148,8 @@ Engine 42 adds ordered `recordHealthFindings` observations. A scan retains its b
Engine 52 reopens an accepted item that conflicts with the trunk for a main merge. A `reopen` move may carry `conflict: {files, trunk}`: the files that conflict, and the full trunk commit they conflict with. The CLI takes one exact path per `--conflict <file>` flag and splits or trims nothing inside it, so a path with spaces or commas is named as Git reports it in `git merge-tree --write-tree --name-only -z`; `files` holds those exact paths, nonempty and without NUL. The CLI fills `trunk` from Git and refuses `NOT_CONFLICTING` when the accepted commit merges cleanly, or `CONFLICT_FILES` when a named file is not one Git reports as conflicting. The board refuses `NOT_ACCEPTED` unless the item is verified with an accept at its commit, and `BAD_CONFLICT` for a malformed conflict. A conflict needs no note and no landing failure; the event records `supersedes`, the accept it sets aside, `conflict`, and `cause: "refusal:MERGE_CONFLICT"`, never `landingFailure`, so rigor counts it as a merge conflict and never as a failing test. The item reads `needs main merge` until its next verdict, and the re-review checks the frozen check at the new head. A `reopen` move carrying `conflict` requires engine 52, and older engines refuse it with `RELAY_MOVE` before changing their board or cursor; a board replaying an older engine refuses it with `ENGINE_VERSION`. Moves recorded under engines 51 and earlier replay unchanged. The unlanded feature’s previous allocations were 36 and 47; it moved to 52 after the trunk reached engine 50 and milestone withdrawal was allocated engine 51, preserving every landed feature’s engine.
+Engine 53 adds board-owned watch proposals, exact person approve/decline decisions, ordered due-run claims and completed run receipts. Approval binds the entire execution definition; changing it creates a pending proposal. Replay records history without executing commands. Every non-cancelled red run records `sentinel:<name>` for Rigor; feed notices only mark failure and recovery transitions. Older engines refuse these operations and this new cause form before replay.
+
Engine 55 (`ROW_DRAFT_ENGINE`) adds `draftSpecRow`: an agent in a lane worktree records a drafted spec row on the board, since SPEC.md is the coordinator's file and a lane cannot write it. The move carries `row: {id, text, gate, tier, section, target}` and `written`. Every writer of a new row reserves its id with this move, in one write transaction, before any file names the id: a lane's spec draft, the main checkout's spec draft and doctrine rulings, Rigor and blueprints. The sender plans the id from its files; the board takes that id or the next number after it that no draft holds, so writers that planned the same id at the same moment get distinct ids, and the same row again keeps the id it reserved. `written: true` marks a writer that puts the row in its own file now; only unwritten spec drafts, which come from lanes, are written by spec apply. Until spec apply writes it, the commit-msg hook and `spec check` read a board draft as a draft row, so a lane cites the returned id at once and its worktree stays clean. The coordinator's `spec apply` writes each pending board draft into SPEC.md at its own id, and the person approves it there as before; a draft counts as applied once SPEC.md has its id. A move carrying `draftSpecRow` requires engine 55, and older engines refuse it before changing their board or cursor. Engine 54 is the strong-rejection notice above; engine 53 is allocated to another change.
The CLI declares its engine in every relay request's `X-Pullboard-Engine` header.
@@ -369,6 +371,11 @@ The `event` table is a SQLite schema object governed by `SCHEMA_VERSION`; its ap
| `health-scan` | observing agent | `active`, `engine` |
| `health-failure` | sentinel | `key`, `cause`, `since`, `subject`, `owner`, `commit`, `engine` |
| `health-resolved` | sentinel | `key`, `cause`, `since`, `subject`, `owner`, `commit`, `engine` |
+| `sentinel-proposal` | proposing agent | `row`, `digest`, `engine` |
+| `sentinel-decision` | person | `name`, `digest`, `decision`, `reason`, `channel`, `engine` |
+| `sentinel-start` | running agent | `name`, `digest`, `run`, `until`, `engine` |
+| `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` |
| `row_decision` | person | `record`, `channel` |
diff --git a/docs/formats.test.js b/docs/formats.test.js
index 0c136ce0..7d6cf139 100644
--- a/docs/formats.test.js
+++ b/docs/formats.test.js
@@ -7,6 +7,10 @@ import { join, relative } from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { test } from 'node:test';
import { submitFixture } from '../test/board-submit-fixture.js';
+import { proposeSentinel } from '../src/sentinels.js';
+import { decideSentinel } from '../src/sentinels.js';
+import { beginSentinelRun } from '../src/sentinels.js';
+import { finishSentinelRun } from '../src/sentinels.js';
import { COORDINATOR } from '../src/config.js';
import { JSON_SHAPES } from '../src/json.js';
import { exportView } from '../src/serve.js';
@@ -360,6 +364,12 @@ function recordEventContract() {
const revision = () => events(board).at(-1)?.event_id ?? 0;
recordHealthFindings(board, { agentId: coordinator, observedRevision: revision(), findings: [healthFinding] });
recordHealthFindings(board, { agentId: coordinator, observedRevision: revision(), findings: [] });
+ // Explicitly synthetic event-contract history; no external command or gate is claimed.
+ const watch = proposeSentinel(board, { agentId: coordinator, row: { name: 'format-watch', check: 'false', every: 'daily', owner: 'coordinator' } });
+ decideSentinel(board, { agentId: PERSON, channel: 'view', name: watch.name, digest: watch.digest, decision: 'approve' });
+ beginSentinelRun(board, { agentId: coordinator, name: watch.name, digest: watch.digest, run: 'format-run' });
+ finishSentinelRun(board, { agentId: coordinator, name: watch.name, digest: watch.digest, run: 'format-run',
+ result: { green: false, code: 1, timedOut: false, durationMs: 0, output: 'synthetic format receipt' } });
const rows = events(board).map((row) => ({ ...row, detail: JSON.parse(row.event_detail) }));
closeBoard(board);
return { rows, actors: { [coordinator]: 'coordinator', [builder]: 'builder', [returnedBuilder]: 'builder', [reviewer]: 'reviewer', [PERSON]: 'person', board: 'board' } };
@@ -635,6 +645,11 @@ test('[A5] schema, versions, event kinds and event detail fields match live beha
'health-scan': 'observing agent',
'health-failure': 'sentinel',
'health-resolved': 'sentinel',
+ 'sentinel-proposal': 'proposing agent',
+ 'sentinel-decision': 'person',
+ 'sentinel-start': 'running agent',
+ 'sentinel-run': 'running agent',
+ 'sentinel-failure': 'sentinel',
};
for (const row of actualRows) {
const kind = row.event_kind;
diff --git a/docs/lifecycle.md b/docs/lifecycle.md
index f3bd64a6..c1cbf050 100644
--- a/docs/lifecycle.md
+++ b/docs/lifecycle.md
@@ -158,7 +158,7 @@ Each move checks its guards in this order and refuses with the first one that do
| NOTE_REQUIRED | a review release gives a nonempty one-line reason, engine 5 or newer, only when freeing a submitted review reservation | release with --note "why", or --note-file <file> |
| REVIEW_COOLDOWN | the reviewer has not released this submission within the past hour, engine 5 or newer, only for the same reviewer and current submission | let another reviewer take it, or wait an hour or for a new submission |
| NOTE_REQUIRED | the move carries a note: what failed, what was tried, or why | --note "..." or --note-file <file> |
-| BAD_CAUSE | a cause, when given, is test:<file>::<title>, refusal:<CODE>, row:<id> or doctrine:<id> | fix --cause, or leave it out |
+| BAD_CAUSE | a cause, when given, is test:<file>::<title>, refusal:<CODE>, row:<id>, doctrine:<id> or sentinel:<name> | fix --cause, or leave it out |
| ALREADY_MERGED | the item has no recorded merge receipt | a merged item cannot be reopened |
| SUBMISSION_PROOF | recorded test selection names literal project files and its full-fallback policy, engine 38 or later; absent legacy selection remains unknown | rerun submit with the current CLI |
| LANDING_FAILURE_REQUIRED | a verified item note names the failing test and landing merge commit, unless the reopen names a trunk conflict | cite the recorded batch, or name the test and merge commit in a manual note; work that only conflicts with the trunk reopens with --conflict <file> for each conflicting file |
diff --git a/src/board.js b/src/board.js
index 6069b002..a0361d8f 100644
--- a/src/board.js
+++ b/src/board.js
@@ -102,6 +102,7 @@ import { submissionProof } from './submit-invariants.js';
import { SUBMISSION_PROOF_ENGINE } from './submit-invariants.js';
export { landingFlakes, landingWaiverCovers, landingWaiverKind };
export { acceptCheck } from './check-accept.js';
+export { proposeSentinel, decideSentinel, beginSentinelRun, finishSentinelRun } from './sentinels.js';
/** The seat readers live in seats.js; the board re-exports them so `store.*` callers keep one import. */
export { agentAt, agentCreator, listAgents, nextSeatId, seatEnrolled, seatLineage, withVerifierStanding } from './seats.js';
diff --git a/src/cli.js b/src/cli.js
index 55218aa0..0786a893 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -342,6 +342,10 @@ import { serveApi } from './api.js';
import { watchCommand } from './watch.js';
import { serveMcp } from './mcp.js';
import { scanHealthSentinel } from './health-sentinel.js';
+import { SENTINEL_OPTIONS } from './sentinel-command.js';
+import { resumeSentinels } from './sentinel-command.js';
+import { sentinelCommand } from './sentinel-command.js';
+import { sentinelListCommand } from './sentinel-command.js';
import {
doctorProblems,
doctrineProblems,
@@ -619,6 +623,7 @@ const OPTIONS = {
model: { type: 'string' },
as: { type: 'string' },
check: { type: 'string' },
+ ...SENTINEL_OPTIONS,
yes: { type: 'boolean' },
landing: { type: 'boolean' },
adopt: { type: 'boolean' },
@@ -1701,6 +1706,7 @@ async function resumeHere(io, view) {
catch (error) { if (!(error instanceof Refused) || error.code !== 'HEALTH_SCAN_STALE') throw error; }
}
});
+ await resumeSentinels({ ctx, withBoard, whoAmI, ordered });
const { root, isMain } = ctx.info;
const mainRoot = primaryCheckoutRoot(ctx.info);
const worktreeConfig = mainRoot ? (isMain ? ctx.config : loadConfig(mainRoot)) : null;
@@ -4361,6 +4367,8 @@ async function runCommand(argv, io) {
if (values.as === 'person' && !['answer', 'decisions', 'fact'].includes(command)) {
throw new Refused('USAGE', '--as person works only with pullboard answer, decisions, or fact --never-again');
}
+ if (command === 'sentinel') return await sentinelCommand({ ctx: context(io), words: [first, second, ...rest].filter(value => value !== undefined), values, withBoard, whoAmI, ordered });
+ if (command === 'sentinels') return sentinelListCommand(first, () => context(io), withBoard);
if (command === 'tour') return tour(io);
if (command === 'lifecycle') {
io.result?.({ markdown: lifecycleMarkdown().trimEnd() });
@@ -4674,7 +4682,7 @@ export function resultCommands() {
...Object.keys(setupCommands({}, args)),
...Object.keys(readCommands({}, args)),
...Object.keys(workCommands({}, args)),
- 'help', 'version', 'tour', 'lifecycle', 'view', 'serve', 'watch', 'forget', 'spec', 'prompt', 'hook', 'gate', 'settings', 'runner', 'relay',
+ 'help', 'version', 'tour', 'lifecycle', 'view', 'serve', 'watch', 'forget', 'spec', 'prompt', 'hook', 'gate', 'settings', 'runner', 'relay', 'sentinel', 'sentinels',
])].sort();
}
diff --git a/src/engine.js b/src/engine.js
index d825afd7..1fa5abe8 100644
--- a/src/engine.js
+++ b/src/engine.js
@@ -20,6 +20,7 @@ import {
} from './trunk-conflict.js';
import { CHECK_ACCEPT_ENGINE } from './check-accept.js';
import { HEALTH_SENTINEL_ENGINE } from './health-receipts.js';
+import { BOARD_SENTINEL_ENGINE } from './sentinels.js';
import {
CAUSE_ENGINE,
ENGINE_VERSION,
@@ -57,7 +58,7 @@ export const ENGINE_OPERATIONS = Object.freeze([
'addMilestone', 'editMilestoneItems', 'orderMilestoneItems', 'moveMilestone', 'editMilestone', 'removeMilestone', 'shipMilestone',
'recordRowDecisions', 'applyRowDecisions', 'draftSpecRow', 'appendFact',
'recordLandingBatch', 'recordLandingWaiver', 'recordLandingFlake', 'finishLandingBatch', 'acceptCheck',
- 'recordHealthFindings',
+ 'recordHealthFindings', 'proposeSentinel', 'decideSentinel', 'beginSentinelRun', 'finishSentinelRun',
]);
/** Engine version at which each ordered operation first has stable replay semantics. */
@@ -66,6 +67,7 @@ const OPERATION_ENGINE = Object.freeze({ draftSpecRow: ROW_DRAFT_ENGINE, orderMi
/** Dependency edits, causes, sealed reviews, submission proofs, trunk conflicts, health observations and milestone targets retain distinct recorded engine meanings. */
function minimumOperationEngine(operation, args, board) {
+ if (['proposeSentinel', 'decideSentinel', 'beginSentinelRun', 'finishSentinelRun'].includes(operation) || typeof args[1]?.cause === 'string' && args[1].cause.startsWith('sentinel:')) return BOARD_SENTINEL_ENGINE;
if (operation === 'recordHealthFindings') return HEALTH_SENTINEL_ENGINE;
const options = args[1];
if (carriesConflict(operation, args)) return CONFLICT_ENGINE;
diff --git a/src/help.js b/src/help.js
index e127d77f..2d4afec6 100644
--- a/src/help.js
+++ b/src/help.js
@@ -87,6 +87,11 @@ Work
pullboard milestone remove <name> remove a milestone without changing its items
pullboard doctor check board integrity without changing it
pullboard health every stuck item: why, since when, the next step and who takes it
+ pullboard sentinel propose <name> --check "<command>" --every 10m|hourly|daily --owner <seat or lane> [--directory <path>] [--timeout <milliseconds>] [--next "<step>"]
+ propose an exact board watch; only the person may approve it
+ pullboard sentinel approve <name> person: approve this command, directory and schedule
+ pullboard sentinel decline <name> --reason "<why>" person: prevent future runs
+ pullboard sentinels approvals, owners and the last result; does not run checks
reads the board and changes nothing; exits 1 when something is stuck
pullboard.json health.stuck (default 1h), health.holds (1d), health.release (1d)
pullboard skills --update refresh unchanged Claude Code skills from shipped versions
diff --git a/src/json.js b/src/json.js
index 252043b7..10024eb0 100644
--- a/src/json.js
+++ b/src/json.js
@@ -42,6 +42,10 @@ export const JSON_SHAPES = {
status: shape({ me: 'object', mine: 'array', 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' }),
+ 'sentinel approve': shape({ sentinel: 'object' }),
+ 'sentinel decline': shape({ sentinel: 'object' }),
+ sentinels: shape({ sentinels: 'array' }),
skills: shape({ updated: 'array', current: 'array', customized: 'array' }),
inbox: shape({ shouts: 'array' }),
decisions: shape({ decisions: 'array' }),
diff --git a/src/machine.js b/src/machine.js
index 107eafb9..355dbf14 100644
--- a/src/machine.js
+++ b/src/machine.js
@@ -31,6 +31,7 @@ export const ENGINE_VERSION = Math.max(
WITHDRAW_MILESTONE_ENGINE,
STRONG_REJECTION_NOTICE_ENGINE,
52,
+ 53,
);
/**
@@ -179,7 +180,7 @@ export const GUARDS = [
{ id: 'reviewReleaseExplained', refuse: 'NOTE_REQUIRED', rule: 'a review release gives a nonempty one-line reason', next: 'release with --note "why", or --note-file <file>', source: 'board', when: 'engine 5 or newer, only when freeing a submitted review reservation' },
{ id: 'reviewCooldownElapsed', refuse: 'REVIEW_COOLDOWN', rule: 'the reviewer has not released this submission within the past hour', next: 'let another reviewer take it, or wait an hour or for a new submission', source: 'board', when: 'engine 5 or newer, only for the same reviewer and current submission' },
{ id: 'noteGiven', refuse: 'NOTE_REQUIRED', rule: 'the move carries a note: what failed, what was tried, or why', next: '--note "..." or --note-file <file>', source: 'board' },
- { id: 'causeWellFormed', refuse: 'BAD_CAUSE', rule: 'a cause, when given, is test:<file>::<title>, refusal:<CODE>, row:<id> or doctrine:<id>', next: 'fix --cause, or leave it out', source: 'board' },
+ { id: 'causeWellFormed', refuse: 'BAD_CAUSE', rule: 'a cause, when given, is test:<file>::<title>, refusal:<CODE>, row:<id>, doctrine:<id> or sentinel:<name>', next: 'fix --cause, or leave it out', source: 'board' },
{ id: 'notMerged', refuse: 'ALREADY_MERGED', rule: 'the item has no recorded merge receipt', next: 'a merged item cannot be reopened', source: 'board' },
{ id: 'submissionProofValid', refuse: 'SUBMISSION_PROOF', rule: 'recorded test selection names literal project files and its full-fallback policy', next: 'rerun submit with the current CLI', source: 'board', when: 'engine 38 or later; absent legacy selection remains unknown' },
{ id: 'landingFailureRecorded', refuse: 'LANDING_FAILURE_REQUIRED', rule: 'a verified item note names the failing test and landing merge commit', next: 'cite the recorded batch, or name the test and merge commit in a manual note; work that only conflicts with the trunk reopens with --conflict <file> for each conflicting file', source: 'board', when: 'unless the reopen names a trunk conflict' },
diff --git a/src/next-steps.js b/src/next-steps.js
index 6b455ed4..38248095 100644
--- a/src/next-steps.js
+++ b/src/next-steps.js
@@ -524,6 +524,10 @@ export const NEXT_STEPS = Object.freeze({
TOKEN_REVOKED: 'stop using this seat and ask the coordinator for a fresh one: pullboard worktree <lane> --model "<model name>"',
TOKENS_NOT_AVAILABLE: 'manage agent tokens in pullboard view or the signed-in relay account',
TOKEN_NOT_OWNED: 'name a token id from pullboard relay tokens',
+ BAD_SENTINEL: 'read pullboard sentinel --help and propose an exact command, project directory, owner and schedule',
+ STALE_SENTINEL: 'read pullboard sentinels and ask the person to approve the current exact proposal',
+ SENTINEL_ABORTED: 'resume this board again when the background view is running',
+ SENTINEL_DRAIN: 'inspect the latest watch outcome with pullboard sentinels; report the shutdown failure to its owner before retrying',
TOO_LARGE: 'open the file in your editor instead',
UNAUTHORIZED_SIGNERS_CHANGE: 'restore the previous signer list (git checkout HEAD -- .pullboard/signers), or sign the change with a listed key',
UNKNOWN_SPEC: 'ask the coordinator to restore the named spec rows or withdraw the item: pullboard shout coordinator "please fix the rows cited by #<id>"',
diff --git a/src/relay-sender.js b/src/relay-sender.js
index 410fa0ae..1991f723 100644
--- a/src/relay-sender.js
+++ b/src/relay-sender.js
@@ -9,6 +9,7 @@ export function relayMoveActor(move) {
if (move.operation === 'register' && move.engine >= VERIFIER_STANDING_ENGINE) return args[0]?.createdBy === 'machine' ? null : args[0]?.createdBy ?? null;
if (move.operation === 'addItem') return args[0]?.by ?? null;
if (move.operation === 'shout') return args[0]?.from ?? null;
+ if (['proposeSentinel', 'decideSentinel', 'beginSentinelRun', 'finishSentinelRun'].includes(move.operation)) return args[0]?.agentId ?? 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;
@@ -62,7 +63,7 @@ export function relaySenderProblem(move, sender, kind, { phoneReceipt = false }
move.operation === 'ensureCoordinator' && typeof move.args?.[0] === 'string')) return null;
return new Refused('RELAY_PERSON_ONLY', 'a machine cannot act as the person; approve this action on the paired phone');
}
- if (kind === 'snapshot' || move?.operation === 'recordRowDecisions' || move?.operation === 'answerDecision' && move.args?.[1]?.asPerson ||
+ if (kind === 'snapshot' || move?.operation === 'recordRowDecisions' || move?.operation === 'decideSentinel' || move?.operation === 'answerDecision' && move.args?.[1]?.asPerson ||
move?.operation === 'shout' && move.args?.[0]?.request || relayMoveActor(move) === 'person') {
return new Refused('RELAY_PERSON_ONLY', `agent ${sender.agent} cannot make a person-only relay ${kind}; use the person's authenticated session`);
}
diff --git a/src/rigor.js b/src/rigor.js
index d3289c68..1487543f 100644
--- a/src/rigor.js
+++ b/src/rigor.js
@@ -6,11 +6,12 @@
import { COORDINATOR } from './config.js';
import { Refused } from './refused.js';
import { HEALTH_SENTINEL_ENGINE } from './health-receipts.js';
+import { BOARD_SENTINEL_ENGINE } from './sentinels.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>']);
+/** The 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>', 'sentinel:<name>']);
-const CAUSE = /^(?:test:(?<file>[^\s:][^\r\n:]*)::(?<title>\S[^\r\n]*)|refusal:(?<code>[A-Z][A-Z0-9_]*)|row:(?<row>[A-Z][A-Za-z0-9.]*)|doctrine:(?<doctrine>[A-Z][A-Za-z0-9.]*))$/u;
+const CAUSE = /^(?:test:(?<file>[^\s:][^\r\n:]*)::(?<title>\S[^\r\n]*)|refusal:(?<code>[A-Z][A-Z0-9_]*)|row:(?<row>[A-Z][A-Za-z0-9.]*)|doctrine:(?<doctrine>[A-Z][A-Za-z0-9.]*)|sentinel:(?<sentinel>[a-z0-9][a-z0-9._-]{0,63}))$/u;
/** Refusal codes that name a merge conflict: a collision between branches, never a repeated error. */
const CONFLICT_CODES = new Set(['MERGE_CONFLICT']);
@@ -96,9 +97,10 @@ export function causeReading(key) {
* @returns {string[]}
*/
export function eventCauses(event) {
- if (!['reject', 'reopen', 'health-failure'].includes(event.event_kind)) return [];
+ if (!['reject', 'reopen', 'health-failure', 'sentinel-failure'].includes(event.event_kind)) return [];
const detail = JSON.parse(event.event_detail);
if (event.event_kind === 'health-failure' && (event.event_by !== 'sentinel' || detail.engine !== HEALTH_SENTINEL_ENGINE)) return [];
+ if (event.event_kind === 'sentinel-failure' && (event.event_by !== 'sentinel' || detail.engine !== BOARD_SENTINEL_ENGINE)) return [];
const keys = [];
if (typeof detail.cause === 'string' && !causeProblem(detail.cause)) keys.push(detail.cause);
const tests = Array.isArray(detail.landingFailure?.tests) ? detail.landingFailure.tests : [];
@@ -143,6 +145,8 @@ export function rigorReport(events, { person }) {
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;
+ if (event.event_kind === 'sentinel-failure'
+ && (event.event_by !== 'sentinel' || JSON.parse(event.event_detail)?.engine !== BOARD_SENTINEL_ENGINE)) continue;
const never = neverAgainCause(event, person);
if (never && !isMergeConflict(never)) {
const found = entry(never);
@@ -150,7 +154,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', 'health-failure'].includes(event.event_kind)) continue;
+ if (!['reject', 'reopen', 'health-failure', 'sentinel-failure'].includes(event.event_kind)) continue;
const keys = eventCauses(event);
if (!keys.length) {
uncaused += 1;
@@ -160,7 +164,7 @@ 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 (['health-failure', 'sentinel-failure'].includes(event.event_kind)) found.healthOccurrences += 1;
if (event.item_id === null) continue;
const commits = found.items.get(event.item_id) ?? new Set();
if (commit) commits.add(commit);
diff --git a/src/sentinel-command.js b/src/sentinel-command.js
new file mode 100644
index 00000000..5d9f3896
--- /dev/null
+++ b/src/sentinel-command.js
@@ -0,0 +1,74 @@
+/** CLI proposal and exact person decisions for board-owned watches [A6,D3]. */
+import { PERSON } from './board.js';
+import { requirePersonChannel } from './person.js';
+import { Refused } from './refused.js';
+import { sentinels } from './sentinels.js';
+import { runDueSentinels } from './sentinel-runner.js';
+import { healthSentinelEnabled } from './settings.js';
+
+/** The watch command's existing string options, shared with the CLI parser. */
+export const SENTINEL_OPTIONS = {
+ every: { type: 'string' },
+ owner: { type: 'string' },
+ directory: { type: 'string' },
+ timeout: { type: 'string' },
+ next: { type: 'string' },
+};
+
+/** Run due approved watches from ordinary resume, respecting the health switches. */
+export async function resumeSentinels({ ctx, withBoard, whoAmI, ordered }) {
+ return withBoard(ctx, async board => {
+ const me = whoAmI(ctx, board);
+ if (!healthSentinelEnabled(ctx.config)) return;
+ await runDueSentinels({ root: ctx.info.root, board, agentId: me.id,
+ ordered: (operation, args) => ordered(ctx, board, operation, args) });
+ });
+}
+
+/** Keep command parsing separate from the CLI's process and server setup. */
+export async function sentinelCommand({ ctx, words, values, withBoard, whoAmI, ordered }) {
+ const [verb, name, ...extra] = words;
+ if (extra.length || !['propose', 'approve', 'decline'].includes(verb) || !name) {
+ throw new Refused('USAGE', 'use pullboard sentinel propose <name> --check "<command>" --every 10m --owner <seat or lane>, sentinel approve <name>, sentinel decline <name> --reason "<why>", or pullboard sentinels');
+ }
+ if (verb !== 'propose') requirePersonChannel(ctx.io.personChannel);
+ return withBoard(ctx, async board => {
+ const me = whoAmI(ctx, board);
+ let row;
+ if (verb === 'propose') {
+ row = await ordered(ctx, board, 'proposeSentinel', [{ agentId: me.id, row: {
+ name, check: values.check, every: values.every, owner: values.owner,
+ directory: values.directory, timeoutMs: values.timeout === undefined ? undefined : Number(values.timeout), next: values.next,
+ } }]);
+ } else {
+ if (!ctx.info.isMain || me.id !== 'coordinator') throw new Refused('B26_PERSON_APPROVAL', 'only the person from the main checkout approves or declines a sentinel; use their terminal or Pullboard View');
+ const current = sentinels(board).find(entry => entry.name === name);
+ if (!current) throw new Refused('STALE_SENTINEL', 'read the current proposals with pullboard sentinels');
+ row = await ordered(ctx, board, 'decideSentinel', [{ agentId: PERSON, channel: ctx.io.personChannel ?? 'terminal',
+ name, digest: current.digest, decision: verb, reason: values.reason }]);
+ }
+ ctx.io.result?.({ sentinel: row });
+ ctx.io.say(`${name}: ${row.status}; ${row.every}; owner ${row.owner}; directory ${row.directory}\n ${row.check}`);
+ if (row.status === 'pending') ctx.io.say(`next: the person approves this exact row with pullboard sentinel approve ${name}, or declines it with --reason "<why>"`);
+ return 0;
+ });
+}
+
+/** Reject an extra list argument before opening the board, as the CLI does. */
+export function sentinelListCommand(first, getContext, withBoard) {
+ if (first) throw new Refused('USAGE', 'pullboard sentinels lists the current board watches');
+ return sentinelList(getContext(), withBoard);
+}
+
+/** Show the current approval, latest outcome and owner without running any command. */
+export function sentinelList(ctx, withBoard) {
+ return withBoard(ctx, board => {
+ const rows = sentinels(board);
+ ctx.io.result?.({ sentinels: rows });
+ for (const row of rows) {
+ ctx.io.say(`${row.name}: ${row.status}; ${row.every}; owner ${row.owner}; last ${row.lastRun?.at ?? 'never'}; ${row.lastRun ? row.lastRun.green ? 'green' : 'red' : 'unrun'}\n directory ${row.directory}; ${row.check}`);
+ }
+ if (!rows.length) ctx.io.say('no board watches; propose one with pullboard sentinel propose <name> --check "<command>" --every 10m --owner coordinator');
+ return 0;
+ });
+}
diff --git a/src/sentinel-runner.js b/src/sentinel-runner.js
new file mode 100644
index 00000000..cb2035ea
--- /dev/null
+++ b/src/sentinel-runner.js
@@ -0,0 +1,168 @@
+/** Run only an approved due board watch, outside any SQLite write transaction [A6]. */
+import { spawn } from 'node:child_process';
+import { spawnSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { realpathSync } from 'node:fs';
+import { relative } from 'node:path';
+import { resolve } from 'node:path';
+import { sep } from 'node:path';
+import { performance } from 'node:perf_hooks';
+import { Refused } from './refused.js';
+import { parseProcessCensus } from './process-census.js';
+import { sentinels } from './sentinels.js';
+
+/** Keep only bounded final output; a noisy check cannot grow a board receipt without limit. */
+function outputTail(previous, chunk) {
+ return Buffer.concat([previous, chunk]).subarray(-12_000);
+}
+
+/** Read a locale-stable POSIX census; an unavailable census never means an empty owned group. */
+function watchCensus() {
+ const read = spawnSync('/bin/ps', ['-axo', 'pid=,ppid=,pgid=,lstart=,stat=,comm='], {
+ encoding: 'utf8', timeout: 3_000, maxBuffer: 8 * 1024 * 1024, env: { ...process.env, LC_ALL: 'C' },
+ }); // budget: bounded process-identity inspection, independent of checker throughput.
+ const rows = read.status === 0 ? parseProcessCensus(read.stdout) : null;
+ if (!rows) throw new Refused('SENTINEL_DRAIN', 'the watch process census is unavailable; inspect its owned process before retrying');
+ return rows;
+}
+
+/** Read only the detached session captured before its approved command was allowed to start. */
+function watchMembers(pgid, anchor) {
+ const rows = watchCensus(), leader = rows.get(pgid);
+ if (!anchor || leader && leader.started !== anchor.started) {
+ throw new Refused('SENTINEL_DRAIN', 'the watch process-group identity changed; no replacement process was touched');
+ }
+ return [...rows.values()].filter(row => row.pgid === pgid && !row.state.startsWith('Z'));
+}
+
+/** Signal individual owned members only after rechecking PID, start, group and executable. */
+function signalWatch(pgid, anchor, signal) {
+ for (const member of watchMembers(pgid, anchor)) {
+ const now = watchCensus().get(member.pid);
+ if (!now || now.pgid !== member.pgid || now.started !== member.started || now.processSha256 !== member.processSha256) continue;
+ try { process.kill(member.pid, signal); } catch (error) { if (error.code !== 'ESRCH') throw error; }
+ }
+}
+
+/** Retain custody through normal exit too: redirected, unreferenced children still need shutdown. */
+async function drainWatch(pgid, anchor) {
+ if (process.platform === 'win32' || !pgid) return;
+ for (const signal of ['SIGTERM', 'SIGKILL']) {
+ if (!watchMembers(pgid, anchor).length) return;
+ signalWatch(pgid, anchor, signal);
+ const deadline = Date.now() + 2_000; // budget: owned-group shutdown grace, not a performance threshold.
+ do {
+ if (!watchMembers(pgid, anchor).length) return;
+ await new Promise(resolve => setTimeout(resolve, 25));
+ } while (Date.now() < deadline);
+ }
+ throw new Refused('SENTINEL_DRAIN', 'the owned watch group did not drain; inspect its recorded process before retrying');
+}
+
+/** Run one owned process group in the approved directory, with a bounded hang and drained shutdown. */
+export function executeSentinel(root, row, { signal, environment = process.env } = {}) {
+ return new Promise((settle, reject) => {
+ let directory;
+ try {
+ const base = realpathSync(root);
+ directory = realpathSync(resolve(base, row.directory));
+ const path = relative(base, directory);
+ if (path === '..' || path.startsWith('..' + sep)) throw new Refused('BAD_SENTINEL', 'the approved sentinel directory must remain inside its project');
+ } catch (error) { reject(error); return; }
+ if (signal?.aborted) { reject(new Refused('SENTINEL_ABORTED', 'the background view stopped before this check began; retry on resume')); return; }
+ const start = performance.now();
+ const group = process.platform !== 'win32';
+ // The shell waits on a private start pipe until its detached group identity is captured.
+ // The approved command remains one exact argument, and receives the original ignored stdin.
+ const child = group ? spawn('/bin/sh', ['-c', 'IFS= read -r pullboard_watch_start || exit 125; exec /bin/sh -c "$1" </dev/null', 'pullboard-watch', row.check],
+ { cwd: directory, env: environment, detached: true, stdio: ['pipe', 'pipe', 'pipe'] })
+ : spawn(row.check, { cwd: directory, env: environment, shell: true, stdio: ['ignore', 'pipe', 'pipe'] });
+ let anchor = null;
+ let startupError = null;
+ let drainError = null;
+ let output = Buffer.alloc(0);
+ let timedOut = false;
+ let stopping = false;
+ let closed = false;
+ let interrupted = false;
+ let hardTimer;
+ /** Stop only the child this command spawned, then wait for its close before returning. */
+ const send = signalName => {
+ if (!Number.isSafeInteger(child.pid)) return;
+ try {
+ if (group && anchor) signalWatch(child.pid, anchor, signalName);
+ else child.kill(signalName); // Before the start handshake, only this direct child can exist.
+ } catch (error) {
+ drainError ||= error;
+ if (!closed) child.kill(signalName);
+ }
+ };
+ const stop = () => {
+ if (stopping || closed) return;
+ stopping = true; send('SIGTERM');
+ hardTimer = setTimeout(() => send('SIGKILL'), 5_000); // budget: owned process-group shutdown grace after TERM.
+ hardTimer.unref();
+ };
+ const timer = setTimeout(() => { timedOut = true; stop(); }, row.timeoutMs);
+ timer.unref();
+ signal?.addEventListener('abort', stop, { once: true });
+ /** A background resume child also drains its approved command before honoring view shutdown. */
+ const interrupt = () => { interrupted = true; stop(); };
+ process.once('SIGTERM', interrupt); process.once('SIGINT', interrupt);
+ /** Remove only this run's handlers, leaving the embedding process's other handlers untouched. */
+ const cleanup = () => {
+ closed = true; clearTimeout(timer); clearTimeout(hardTimer); signal?.removeEventListener('abort', stop);
+ process.removeListener('SIGTERM', interrupt); process.removeListener('SIGINT', interrupt);
+ };
+ if (group) {
+ child.stdin.on('error', error => { startupError ||= error; stop(); });
+ child.once('spawn', () => {
+ try {
+ anchor = watchCensus().get(child.pid);
+ if (!anchor || anchor.pgid !== child.pid) throw new Refused('SENTINEL_DRAIN', 'the watch did not start in its own process group');
+ child.stdin.end('start\n');
+ } catch (error) { startupError ||= error; stop(); }
+ });
+ }
+ child.stdout.on('data', chunk => { output = outputTail(output, chunk); });
+ child.stderr.on('data', chunk => { output = outputTail(output, chunk); });
+ child.once('error', error => {
+ cleanup(); reject(error);
+ });
+ child.once('close', async (code, stoppedBy) => {
+ try {
+ if (group && anchor) await drainWatch(child.pid, anchor);
+ if (startupError || drainError) throw startupError || drainError;
+ const aborted = interrupted || Boolean(signal?.aborted);
+ settle({ green: code === 0 && !timedOut && !aborted, code, timedOut,
+ signal: stoppedBy, aborted, durationMs: performance.now() - start, output: output.toString('utf8').split(/\r?\n/u).slice(-12).join('\n') });
+ } catch (error) { reject(error); }
+ finally { cleanup(); }
+ });
+ });
+}
+
+/** Claim through the ordinary ordered engine, execute without a lock, then publish its exact result. */
+export async function runDueSentinels({ root, board, agentId, ordered, signal, execute = executeSentinel }) {
+ const results = [];
+ for (const row of sentinels(board).filter(entry => entry.status === 'approved')) {
+ if (signal?.aborted) break;
+ const run = randomUUID();
+ let claimed;
+ try { claimed = await ordered('beginSentinelRun', [{ agentId, name: row.name, digest: row.digest, run }]); }
+ catch (error) { if (error instanceof Refused && error.code === 'STALE_SENTINEL') continue; throw error; }
+ if (!claimed) continue;
+ let result;
+ const began = performance.now();
+ try { result = await execute(root, claimed, { signal }); }
+ catch (error) {
+ result = { green: false, code: null, timedOut: false, signal: null,
+ aborted: Boolean(signal?.aborted) || error?.code === 'SENTINEL_ABORTED', durationMs: performance.now() - began,
+ output: String(error?.message ?? error).slice(-12_000) };
+ }
+ try { results.push(await ordered('finishSentinelRun', [{ agentId, name: row.name, digest: row.digest, run, result }])); }
+ catch (error) { if (!(error instanceof Refused) || error.code !== 'STALE_SENTINEL') throw error; }
+ if (result.aborted) break;
+ }
+ return results;
+}
diff --git a/src/sentinels.js b/src/sentinels.js
new file mode 100644
index 00000000..1ec33d95
--- /dev/null
+++ b/src/sentinels.js
@@ -0,0 +1,177 @@
+/** Person-approved board watches and their append-only run history [A6,D1,D3]. */
+import { createHash } from 'node:crypto';
+import { atomic } from './board.js';
+import { listAgents } from './board.js';
+import { logEvent } from './board.js';
+import { PERSON } from './board.js';
+import { shout } from './board.js';
+import { ENGINE_VERSION } from './machine.js';
+import { Refused } from './refused.js';
+
+/** Coordinator allocation, 18 Oct: all new board-watch moves begin here [H16]. */
+export const BOARD_SENTINEL_ENGINE = 53;
+const NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/u;
+const INTERVALS = Object.freeze({ '10m': 600_000, hourly: 3_600_000, daily: 86_400_000 });
+
+/** Normalize the exact row the person approves; no execution settings live outside its digest. */
+export function sentinelDefinition(value) {
+ if (!value || typeof value.name !== 'string' || !NAME.test(value.name) || typeof value.check !== 'string' || !value.check.trim()
+ || value.check.length > 8_192 || typeof value.every !== 'string' || !Object.hasOwn(INTERVALS, value.every)
+ || typeof value.owner !== 'string' || !value.owner.trim() || /\s/u.test(value.owner)) {
+ throw new Refused('BAD_SENTINEL', 'name a watch, its check, owner and --every 10m, hourly or daily: pullboard sentinel propose <name> --check "<command>" --owner <seat or lane> --every 10m');
+ }
+ const directory = value.directory ?? '.';
+ if (typeof directory !== 'string' || !directory || directory.startsWith('/') || directory.includes('\\')
+ || directory.split('/').some(part => part === '..') || /[\r\n\0]/u.test(directory)) {
+ throw new Refused('BAD_SENTINEL', 'use a working directory inside this project with --directory <relative path>');
+ }
+ const timeoutMs = value.timeoutMs ?? 30_000; // budget: default hang ceiling for an approved external check.
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 100 || timeoutMs > 300_000) {
+ throw new Refused('BAD_SENTINEL', 'set --timeout to a whole number of milliseconds from 100 through 300000');
+ }
+ const next = value.next ?? `inspect the check and propose a repair for sentinel ${value.name}`;
+ if (typeof next !== 'string' || !next.trim() || next.length > 1_024 || /[\r\n\0]/u.test(next)) {
+ throw new Refused('BAD_SENTINEL', 'give one readable next step with --next "<what to do>"');
+ }
+ return { name: value.name, check: value.check, directory, every: value.every, owner: value.owner,
+ timeoutMs, next: next.trim() };
+}
+
+/** Bind approval to every execution and notification field, including schedule and timeout. */
+export function sentinelDigest(value) {
+ return createHash('sha256').update(JSON.stringify(sentinelDefinition(value))).digest('hex');
+}
+
+/** Read only allocated receipts; legacy events with similar names never enable command execution. */
+export function sentinels(board) {
+ const rows = new Map();
+ const events = board.db.prepare("SELECT * FROM event WHERE event_kind IN ('sentinel-proposal','sentinel-decision','sentinel-start','sentinel-run') ORDER BY event_id").all();
+ for (const event of events) {
+ const detail = JSON.parse(event.event_detail);
+ if (detail.engine !== BOARD_SENTINEL_ENGINE) continue;
+ if (event.event_kind === 'sentinel-proposal') {
+ rows.set(detail.row.name, { ...detail.row, digest: detail.digest, status: 'pending', proposedBy: event.event_by,
+ proposedAt: event.event_at, lastRun: null, activeRun: null, history: [] });
+ continue;
+ }
+ const row = rows.get(detail.name);
+ if (!row || row.digest !== detail.digest) continue;
+ if (event.event_kind === 'sentinel-decision' && event.event_by === PERSON) {
+ row.status = detail.decision === 'approve' ? 'approved' : 'declined';
+ row.reason = detail.reason; row.decidedAt = event.event_at; row.activeRun = null;
+ } else if (event.event_kind === 'sentinel-start') {
+ row.activeRun = { id: detail.run, by: event.event_by, startedAt: event.event_at, until: detail.until };
+ } else if (event.event_kind === 'sentinel-run' && row.activeRun?.id === detail.run) {
+ row.lastRun = { ...detail.result, id: detail.run, at: event.event_at };
+ row.history.push(row.lastRun); row.activeRun = null;
+ }
+ }
+ return [...rows.values()];
+}
+
+/** All mutations retain their allocated replay minimum and require a registered actor. */
+function requireSentinelActor(board, agentId, person = false) {
+ if ((board.executionEngineVersion ?? ENGINE_VERSION) < BOARD_SENTINEL_ENGINE) {
+ throw new Refused('ENGINE_VERSION', `board watches require engine ${BOARD_SENTINEL_ENGINE}; upgrade Pullboard`);
+ }
+ if (person ? agentId !== PERSON : !listAgents(board).some(agent => agent.agent_id === agentId)) {
+ throw new Refused(person ? 'B26_PERSON_APPROVAL' : 'NOT_JOINED', person
+ ? 'only the person approves or declines a sentinel; use their terminal or Pullboard View'
+ : 'join this board before proposing or running a sentinel: pullboard join <lane>');
+ }
+}
+
+/** Read one current proposal, refusing a replaced approval or run receipt before any mutation. */
+function currentSentinel(board, name, digest) {
+ const row = sentinels(board).find(entry => entry.name === name);
+ if (!row || row.digest !== digest) throw new Refused('STALE_SENTINEL', 'read the current proposal with pullboard sentinels; the person approves its exact command, directory and schedule');
+ return row;
+}
+
+/** Propose or replace a watch; every replacement becomes pending and loses all prior approval. */
+export function proposeSentinel(board, { agentId, row: value }) {
+ return atomic(board, () => {
+ requireSentinelActor(board, agentId);
+ const row = sentinelDefinition(value);
+ const agents = listAgents(board);
+ if (row.owner !== 'coordinator' && !agents.some(agent => [agent.agent_id, agent.agent_lane].includes(row.owner))) {
+ throw new Refused('BAD_SENTINEL', 'choose the coordinator, a registered seat or a lane as the sentinel owner');
+ }
+ const digest = sentinelDigest(row);
+ logEvent(board, agentId, 'sentinel-proposal', null, { row, digest, engine: BOARD_SENTINEL_ENGINE });
+ return sentinels(board).find(entry => entry.name === row.name);
+ });
+}
+
+/** Approve or decline precisely the row the person saw, through the same person channels as spec rows. */
+export function decideSentinel(board, { agentId, channel, name, digest, decision, reason = '' }) {
+ return atomic(board, () => {
+ requireSentinelActor(board, agentId, true);
+ if (!['terminal', 'view'].includes(channel)) throw new Refused('B26_PERSON_CHANNEL', 'sentinel decisions use the person’s terminal or Pullboard View');
+ if (!['approve', 'decline'].includes(decision) || typeof reason !== 'string'
+ || /[\r\n]/u.test(reason) || decision === 'decline' && !reason.trim()) {
+ throw new Refused('BAD_SENTINEL', 'approve the current sentinel, or decline it with --reason "<why>"');
+ }
+ const row = currentSentinel(board, name, digest);
+ if (decision === 'approve' && row.status === 'approved') return row;
+ logEvent(board, PERSON, 'sentinel-decision', null, { name, digest, decision, reason: reason.trim(), channel, engine: BOARD_SENTINEL_ENGINE });
+ return sentinels(board).find(row => row.name === name);
+ });
+}
+
+/** Atomically claim a due approved check, so simultaneous resume/view workers cannot run it twice. */
+export function beginSentinelRun(board, { agentId, name, digest, run }) {
+ return atomic(board, () => {
+ requireSentinelActor(board, agentId);
+ const row = currentSentinel(board, name, digest);
+ const now = board.clock.now().getTime();
+ if (typeof run !== 'string' || !/^[a-zA-Z0-9-]{1,80}$/u.test(run)) throw new Refused('BAD_SENTINEL', 'start a sentinel with a unique run id');
+ if (row.status !== 'approved' || row.activeRun && Date.parse(row.activeRun.until) > now
+ || row.lastRun && !row.lastRun.aborted && Date.parse(row.lastRun.at) + INTERVALS[row.every] > now) return null;
+ const until = new Date(now + row.timeoutMs + 10_000).toISOString(); // budget: command hang ceiling plus exact-child shutdown grace.
+ logEvent(board, agentId, 'sentinel-start', null, { name, digest, run, until, engine: BOARD_SENTINEL_ENGINE });
+ return { ...row, run, until };
+ });
+}
+
+/** Keep completed receipts small and internally consistent before writing any event or consuming a lease. */
+function completedWatchResult(value) {
+ const fields = ['green', 'code', 'timedOut', 'signal', 'aborted', 'durationMs', 'output'];
+ const result = value && {
+ green: value.green, code: value.code, timedOut: value.timedOut,
+ signal: value.signal ?? null, aborted: value.aborted ?? false,
+ durationMs: value.durationMs, output: value.output,
+ };
+ if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key => !fields.includes(key))
+ || typeof result.green !== 'boolean' || typeof result.timedOut !== 'boolean' || typeof result.aborted !== 'boolean'
+ || result.code !== null && (!Number.isInteger(result.code) || result.code < 0 || result.code > 255)
+ || result.signal !== null && (typeof result.signal !== 'string' || !/^SIG[A-Z0-9]+$/u.test(result.signal) || result.code !== null)
+ || !Number.isFinite(result.durationMs) || result.durationMs < 0 || typeof result.output !== 'string' || result.output.length > 16_384
+ || result.green !== (result.code === 0 && !result.timedOut && !result.aborted && result.signal === null)) {
+ throw new Refused('BAD_SENTINEL', 'record a completed check with its exit status, bounded final output, timeout and elapsed time');
+ }
+ return result;
+}
+
+/** Retain every red receipt for Rigor, but notify the owner only on the red/green transitions. */
+export function finishSentinelRun(board, { agentId, name, digest, run, result }) {
+ return atomic(board, () => {
+ requireSentinelActor(board, agentId);
+ const row = currentSentinel(board, name, digest);
+ if (row.status !== 'approved' || row.activeRun?.id !== run || row.activeRun.by !== agentId) {
+ throw new Refused('STALE_SENTINEL', 'this sentinel run no longer owns the approved proposal; read pullboard sentinels and retry when due');
+ }
+ result = completedWatchResult(result);
+ logEvent(board, agentId, 'sentinel-run', null, { name, digest, run, result, engine: BOARD_SENTINEL_ENGINE });
+ if (!result.green && !result.aborted) logEvent(board, 'sentinel', 'sentinel-failure', null, {
+ name, digest, run, cause: `sentinel:${name}`, engine: BOARD_SENTINEL_ENGINE,
+ });
+ const previous = row.history.findLast(entry => !entry.aborted);
+ if (!result.aborted && (!result.green && previous?.green !== false || result.green && previous?.green === false)) {
+ const cleared = result.green;
+ const text = `${cleared ? 'Cleared' : 'Sentinel failed'}: ${name}\n${row.check}\n${result.output || '(no output)'}\nNext: ${row.next}`;
+ shout(board, { from: 'sentinel', to: row.owner, text, lanes: [...new Set(listAgents(board).map(agent => agent.agent_lane))] });
+ }
+ return sentinels(board).find(entry => entry.name === name);
+ });
+}
diff --git a/src/templates.js b/src/templates.js
index 25e3ed9b..300e232c 100644
--- a/src/templates.js
+++ b/src/templates.js
@@ -140,6 +140,8 @@ When a reject names a structured cause, add \`--cause <key>\` (\`test:<file>::<t
The coordinator merges verified items into the main line; builders never merge. When a release ships, the coordinator runs \`pullboard milestone ship <name>\`: it records main's commit and moves the items that have not landed into the next milestone. \`pullboard health\` lists every stuck item: a lapsed claim, a review nobody took, accepted work that never landed, an old hold, an unanswered decision. Each line says why, since when, the next step and who takes it; run it at the start of a session and take the steps that name you.
+For recurring checks, \`pullboard sentinels\` lists this board's watches, their approvals and their latest results. Propose one with \`pullboard sentinel propose <name> --check "<command>" --every hourly --owner coordinator\`; a proposal does not run until the person approves its exact command, directory and schedule. Only the person runs \`pullboard sentinel approve <name>\` or \`pullboard sentinel decline <name> --reason "<why>"\` from their own terminal or Pullboard View. Agents never approve their own proposals; send the decision to the coordinator.
+
For spare test capacity, use \`pullboard runner add <ssh-host> --slots <n> --browser <n>\`. It registers SSH capacity on this machine; \`pullboard resources\` shows runners and their usage. Only committed source goes to a runner, and board moves stay here. To see whether this board is linked to the relay, and for which GitHub account, run \`pullboard relay status\`.
If your item needs code another lane owns and it is not there yet, shout that lane and take another item. Never copy their code into your lane, and never build another lane's item, even one that was rejected and blocks you: shout that lane and the coordinator. A claim refused as BLOCKED names the item it waits on.
diff --git a/test/agent-model-engine.test.js b/test/agent-model-engine.test.js
index 5a6af8b5..cbb3a106 100644
--- a/test/agent-model-engine.test.js
+++ b/test/agent-model-engine.test.js
@@ -14,6 +14,7 @@ import {
MILESTONE_SHIP_ENGINE,
WITHDRAW_MILESTONE_ENGINE,
} from '../src/milestones.js';
+import { BOARD_SENTINEL_ENGINE } from '../src/sentinels.js';
import { RIGOR_NOTICE_ENGINE } from '../src/rigor-source.js';
import { HEALTH_SENTINEL_ENGINE } from '../src/health-receipts.js';
import { CONFLICT_ENGINE } from '../src/trunk-conflict.js';
@@ -36,6 +37,8 @@ test('model declarations and event snapshots retain all supported engine semanti
assert.ok(ENGINE_VERSION >= VERIFIER_STANDING_ENGINE, 'the current writer retains verifier standing');
assert.ok(ENGINE_VERSION >= RIGOR_NOTICE_ENGINE, 'the next writer preserves every historical model snapshot through main engine 33');
assert.ok(ENGINE_VERSION >= HEALTH_SENTINEL_ENGINE, 'the current writer retains the sentinel minimum and historical behavior');
+ assert.equal(BOARD_SENTINEL_ENGINE, 53, 'board watches retain their allocated feature engine');
+ assert.ok(ENGINE_VERSION >= BOARD_SENTINEL_ENGINE, 'the current writer retains board-watch semantics');
for (const version of Array.from({ length: ENGINE_VERSION }, (_, index) => index + 1)) {
const board = store.openBoard(':memory:');
t.after(() => store.closeBoard(board));
diff --git a/test/api.test.js b/test/api.test.js
index 2fa7ef62..81684b27 100644
--- a/test/api.test.js
+++ b/test/api.test.js
@@ -1006,6 +1006,11 @@ test('[A1] every catalog command and subcommand has a real CLI exercise', () =>
assert.deepEqual(landing.items, []);
json(source, source.repo, 'roadmap');
json(source, source.repo, 'rigor');
+ const watch = json(source, source.repo, 'sentinel', ['propose', 'catalog-watch', '--check', 'true', '--every', 'hourly', '--owner', 'coordinator'], 'propose');
+ assert.equal(watch.sentinel.status, 'pending');
+ assert.equal(json(source, source.repo, 'sentinel', ['approve', 'catalog-watch'], 'approve').sentinel.status, 'approved');
+ assert.equal(json(source, source.repo, 'sentinel', ['decline', 'catalog-watch', '--reason', 'Catalog coverage complete'], 'decline').sentinel.status, 'declined');
+ assert.equal(json(source, source.repo, 'sentinels').sentinels[0].name, 'catalog-watch');
json(source, source.repo, 'milestone', ['add', 'Catalog', '--items', String(catalog.item_id)], 'add');
json(source, source.repo, 'milestone', ['items', 'Catalog', '--remove', String(catalog.item_id)], 'items');
json(source, source.repo, 'milestone', ['items', 'Catalog', '--add', String(catalog.item_id)], 'items');
diff --git a/test/pending-refreeze.test.js b/test/pending-refreeze.test.js
index 9ac2485c..b9592ab6 100644
--- a/test/pending-refreeze.test.js
+++ b/test/pending-refreeze.test.js
@@ -18,6 +18,7 @@ import {
MILESTONE_SHIP_ENGINE,
WITHDRAW_MILESTONE_ENGINE,
} from '../src/milestones.js';
+import { BOARD_SENTINEL_ENGINE } from '../src/sentinels.js';
import { RIGOR_NOTICE_ENGINE } from '../src/rigor-source.js';
import { HEALTH_SENTINEL_ENGINE } from '../src/health-receipts.js';
import { CONFLICT_ENGINE } from '../src/trunk-conflict.js';
@@ -286,6 +287,8 @@ test('dependency edits replay the same on every engine [B3,V2,H16]', async (t) =
assert.ok(ENGINE_VERSION >= VERIFIER_STANDING_ENGINE, 'the current writer retains verifier standing');
assert.ok(ENGINE_VERSION >= RIGOR_NOTICE_ENGINE, 'the next writer retains all recorded dependency-edit behavior');
assert.ok(ENGINE_VERSION >= HEALTH_SENTINEL_ENGINE, 'the current writer retains the sentinel minimum and historical behavior');
+ assert.equal(BOARD_SENTINEL_ENGINE, 53, 'board watches retain their allocated feature engine');
+ assert.ok(ENGINE_VERSION >= BOARD_SENTINEL_ENGINE, 'the current writer retains board-watch semantics');
const directory = mkdtempSync(join(tmpdir(), 'pullboard-dependency-engines-'));
const cleanup = [];
t.after(() => {
diff --git a/test/relay-credential.test.js b/test/relay-credential.test.js
index b6cef0ce..e78c4010 100644
--- a/test/relay-credential.test.js
+++ b/test/relay-credential.test.js
@@ -24,6 +24,15 @@ test('every current operation selects its native actor credential without a seco
if (['claim', 'refreeze'].includes(operation)) args = [box.before.tables.item[0].item_id, options];
if (operation === 'reserveNextReview') args = [options];
if (operation === 'recordHealthFindings') args = [{ agentId: actor, observedRevision: 0, findings: [] }];
+ if (operation === 'proposeSentinel') args = [{ agentId: actor,
+ row: { name: 'credential-watch', check: 'true', every: 'hourly', owner: actor } }];
+ if (['beginSentinelRun', 'finishSentinelRun'].includes(operation)) {
+ args = [{ agentId: actor, name: 'credential-watch', digest: 'f'.repeat(64), run: 'credential-run' }];
+ }
+ if (operation === 'decideSentinel') {
+ args = [{ agentId: 'person', channel: 'terminal', name: 'credential-watch', digest: 'f'.repeat(64), decision: 'approve' }];
+ kind = 'person';
+ }
// This missing-item fixture still supplies modern proof metadata before testing submit's transport credential.
if (operation === 'submit') args = [999999, { ...options, submissionProof: { version: 1, files: [], full: false, deferred: false, reason: '' } }];
if (operation === 'completeCheckBaseline') args = [999999, { ...options,
diff --git a/test/rigor.test.js b/test/rigor.test.js
index a3035c26..f56f47e9 100644
--- a/test/rigor.test.js
+++ b/test/rigor.test.js
@@ -389,7 +389,7 @@ test('a repeated failure cause is noticed [D1,V1]', () => {
assert.match(lines[0], /^doctrine:C3 {2}reads as work {2}never again \(the person\) {2}items #\d+$/u);
assert.equal(lines[1], `${catalog} reads as both 2 failures items #${first}, #${second}`);
assert.equal(lines[2], `refusal:UNDECLARED_REFUSAL reads as work 2 failures items #${third} (2 commits)`);
- assert.equal(lines[3], '1 rejects and reopens carry no cause key; name one with --cause <key> (test:<file>::<title>, refusal:<CODE>, row:<id>, doctrine:<id>)',
+ assert.equal(lines[3], '1 rejects and reopens carry no cause key; name one with --cause <key> (test:<file>::<title>, refusal:<CODE>, row:<id>, doctrine:<id>, sentinel:<name>)',
'rigor says how many rejects and reopens are uncaused');
assert.equal(lines.length, 4);
});
diff --git a/test/sentinels.test.js b/test/sentinels.test.js
new file mode 100644
index 00000000..58e17303
--- /dev/null
+++ b/test/sentinels.test.js
@@ -0,0 +1,359 @@
+/** Real board watches: exact person approval, automatic execution, owner notices and replay [A6,D1,D3,H16]. */
+import assert from 'node:assert/strict';
+import { existsSync } from 'node:fs';
+import { mkdirSync } from 'node:fs';
+import { mkdtempSync } from 'node:fs';
+import { readFileSync } from 'node:fs';
+import { realpathSync } from 'node:fs';
+import { rmSync } from 'node:fs';
+import { symlinkSync } from 'node:fs';
+import { writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname } from 'node:path';
+import { join } from 'node:path';
+import { test } from 'node:test';
+import * as store from '../src/board.js';
+import { main } from '../src/cli.js';
+import { appliedSequence } from '../src/engine.js';
+import { applyEngineMove } from '../src/engine.js';
+import { applyRelayMove } from '../src/engine.js';
+import { prepareEngineMove } from '../src/engine.js';
+import { exportBoard } from '../src/exchange.js';
+import { importBoard } from '../src/exchange.js';
+import { eventCauses } from '../src/rigor.js';
+import { rigorReport } from '../src/rigor.js';
+import { executeSentinel } from '../src/sentinel-runner.js';
+import { runDueSentinels } from '../src/sentinel-runner.js';
+import { startServeSentinel } from '../src/serve-sentinel.js';
+import { BOARD_SENTINEL_ENGINE } from '../src/sentinels.js';
+import { sentinelDefinition } from '../src/sentinels.js';
+import { sentinelDigest } from '../src/sentinels.js';
+import { sentinels } from '../src/sentinels.js';
+import { machineSettingsFile } from '../src/settings.js';
+import { runFixtureChild } from './fixture-child.js';
+import { runFixtureGit } from './fixture-child.js';
+import { parseProcessCensus } from '../src/process-census.js';
+
+/** Isolate actual SQLite, Git, settings and subprocess files; due time is explicitly injected. */
+function fixture(t) {
+ const directory = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-board-watch-')));
+ const root = join(directory, 'repo'); mkdirSync(root);
+ const overrides = { PULLBOARD_HOME: join(directory, 'home'), PULLBOARD_MACHINE_HOME: join(directory, 'machine'),
+ GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' };
+ const original = Object.fromEntries(Object.keys(overrides).map(key => [key, process.env[key]]));
+ Object.assign(process.env, overrides);
+ const env = { ...process.env, GIT_AUTHOR_NAME: 'Fixture', GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Fixture', GIT_COMMITTER_EMAIL: '[email protected]' };
+ runFixtureGit(['init', '-q', '-b', 'main'], { cwd: root, env });
+ writeFileSync(join(root, 'pullboard.json'), JSON.stringify({ gate: 'true', lanes: { core: { owns: ['src/'] } } }));
+ writeFileSync(join(root, 'SPEC.md'), '# Fixture\n\n## A\n- A6 [approved, must] Watch the board. | gate: review\n');
+ writeFileSync(join(root, 'DOCTRINE.md'), '# Fixture\n\n## PB\n- PB1 [approved, must] Keep the fixture private. | gate: review\n');
+ runFixtureGit(['add', '-A'], { cwd: root, env });
+ runFixtureGit(['commit', '-q', '-m', 'chore: private watch fixture [A6]'], { cwd: root, env });
+ const settings = machineSettingsFile(); mkdirSync(dirname(settings), { recursive: true });
+ writeFileSync(settings, JSON.stringify({ view: { background: false }, relay: { offerAtInit: false } }));
+ const clock = { time: Date.parse('2026-10-18T03:00:00Z'), now() { return new Date(this.time); } };
+ const board = store.openBoard(join(root, '.git/pullboard/board.sqlite'), clock);
+ store.register(board, { lane: 'coordinator', path: root });
+ const agent = store.register(board, { lane: 'core', path: join(directory, 'agent') });
+ /** Apply the actual ordered board engine with deterministic injected receipt time. */
+ const ordered = async (operation, args) => {
+ const move = prepareEngineMove(board, operation, args);
+ const receipt = applyEngineMove(board, move, { sequence: appliedSequence(board) + 1, at: clock.now().toISOString() });
+ assert.equal(receipt.error, undefined, JSON.stringify(receipt)); return receipt.result;
+ };
+ /** Run the actual CLI against this real board; view means the explicit test person adapter. */
+ const cli = async (args, personChannel) => {
+ let output = ''; let error = '';
+ const code = await main([...args, '--json'], { cwd: root, clock, personChannel,
+ stdout: { isTTY: false, write: text => { output += text; } }, stderr: { write: text => { error += text; } } });
+ return { code, document: output ? JSON.parse(output) : null, error };
+ };
+ t.after(() => {
+ store.closeBoard(board); rmSync(directory, { recursive: true, force: true });
+ for (const [key, value] of Object.entries(original)) { if (value === undefined) delete process.env[key]; else process.env[key] = value; }
+ });
+ return { root, directory, board, agent, clock, ordered, cli,
+ run: () => runDueSentinels({ root, board, agentId: 'coordinator', ordered }) };
+}
+
+/** Quote only a controlled fixture path as a shell word. */
+function quote(word) { return `'${word.replaceAll("'", "'\\''")}'`; }
+
+/** Write one actual checker and return the command the person will approve. */
+function checker(box, source, name = 'check.mjs') {
+ const path = join(box.root, name); writeFileSync(path, source);
+ return `${quote(process.execPath)} ${quote(path)}`;
+}
+
+test('an approved sentinel runs by itself and reports to its owner once [A6,D1,D3]', async t => {
+ const box = fixture(t);
+ mkdirSync(join(box.root, 'watch'));
+ const check = checker(box, "import {existsSync,appendFileSync} from 'node:fs'; appendFileSync('runs','run\\n'); console.log('check receipt'); process.exit(existsSync('green')?0:1);");
+ const proposal = await box.cli(['sentinel', 'propose', 'staging', '--check', check, '--every', '10m', '--owner', box.agent,
+ '--directory', 'watch', '--next', 'repair the staging check']);
+ assert.equal(proposal.code, 0, proposal.error);
+ assert.equal(proposal.document.sentinel.status, 'pending');
+ await box.run(); assert.equal(existsSync(join(box.root, 'watch/runs')), false, 'unapproved commands never execute');
+ const approved = await box.cli(['sentinel', 'approve', 'staging'], 'view');
+ assert.equal(approved.code, 0, approved.error);
+ assert.equal(approved.document.sentinel.status, 'approved');
+ assert.equal((await box.cli(['resume'])).code, 0, 'the real automatic resume caller executes the due approved watch');
+ let notices = store.allShouts(box.board).filter(row => row.shout_from === 'sentinel');
+ assert.equal(notices.length, 1); assert.equal(notices[0].shout_to, box.agent);
+ assert.match(notices[0].shout_text, /staging[\s\S]*check receipt[\s\S]*Next: repair the staging check/u);
+ assert.equal(readFileSync(join(box.root, 'watch/runs'), 'utf8'), 'run\n', 'execution uses the approved per-watch directory');
+ await box.run(); assert.equal(readFileSync(join(box.root, 'watch/runs'), 'utf8'), 'run\n', 'not due means no child');
+ box.clock.time += 600_001;
+ await box.run();
+ assert.equal(store.allShouts(box.board).filter(row => row.shout_from === 'sentinel').length, 1, 'a second red run sends no duplicate notice');
+ assert.equal(store.events(box.board).filter(row => row.event_kind === 'sentinel-failure').length, 2, 'every actual red run retains its own cause receipt');
+ const report = rigorReport(store.events(box.board), { person: store.PERSON });
+ assert.equal(report.causes.find(row => row.key === 'sentinel:staging')?.occurrences, 2);
+ writeFileSync(join(box.root, 'watch/green'), 'yes'); box.clock.time += 600_001;
+ await box.run();
+ notices = store.allShouts(box.board).filter(row => row.shout_from === 'sentinel');
+ assert.equal(notices.length, 2); assert.match(notices[1].shout_text, /^Cleared: staging/u);
+ box.clock.time += 600_001; await box.run();
+ assert.equal(store.allShouts(box.board).filter(row => row.shout_from === 'sentinel').length, 2, 'staying green sends no duplicate cleared notice');
+ const listed = await box.cli(['sentinels']);
+ assert.equal(listed.code, 0, listed.error);
+ assert.equal(listed.document.sentinels[0].lastRun.green, true);
+ assert.equal(listed.document.sentinels[0].owner, box.agent);
+ assert.equal(listed.document.sentinels[0].history.length, 4);
+});
+
+test('an agent cannot approve a sentinel [A6,D3,H16]', async t => {
+ const box = fixture(t);
+ const row = store.proposeSentinel(box.board, { agentId: box.agent, row: { name: 'private-check', check: 'true', every: 'hourly', owner: 'core' } });
+ const before = exportBoard(box.board);
+ assert.throws(() => store.decideSentinel(box.board, { agentId: box.agent, channel: 'view', name: row.name, digest: row.digest, decision: 'approve' }), error => error.code === 'B26_PERSON_APPROVAL');
+ assert.deepEqual(exportBoard(box.board), before);
+ const forged = prepareEngineMove(box.board, 'decideSentinel', [{ agentId: store.PERSON, channel: 'view', name: row.name, digest: row.digest, decision: 'approve' }]);
+ for (const sender of [{ kind: 'agent', agent: box.agent, userId: 'fixture' }, { kind: 'machine', machine: 'fixture', userId: 'fixture' }]) {
+ const receipt = applyRelayMove(box.board, { ...forged, id: `forged-${sender.kind}` }, {
+ sequence: appliedSequence(box.board) + 1, at: box.clock.now().toISOString(), kind: 'move', sender });
+ assert.equal(receipt.error?.code, 'RELAY_PERSON_ONLY');
+ assert.equal(sentinels(box.board)[0].status, 'pending');
+ }
+ const key = 'CODEX_THREAD_ID'; const previous = process.env[key]; process.env[key] = 'fixture-agent';
+ try {
+ const attempt = await box.cli(['sentinel', 'approve', row.name]);
+ assert.equal(attempt.code, 1); assert.equal(attempt.document.error.code, 'B26_PERSON_CHANNEL');
+ } finally { if (previous === undefined) delete process.env[key]; else process.env[key] = previous; }
+});
+
+test('a changed command, directory or schedule loses approval and stale receipts cannot restore it [A6,H16]', async t => {
+ const box = fixture(t);
+ const definition = { name: 'daily-check', check: 'true', every: 'daily', owner: 'coordinator' };
+ const initial = store.proposeSentinel(box.board, { agentId: box.agent, row: definition });
+ store.decideSentinel(box.board, { agentId: store.PERSON, channel: 'view', name: initial.name, digest: initial.digest, decision: 'approve' });
+ for (const change of [{ check: 'false' }, { directory: 'other' }, { every: 'hourly' }, { owner: 'core' }, { timeoutMs: 500 }]) {
+ const changed = store.proposeSentinel(box.board, { agentId: box.agent, row: { ...definition, ...change } });
+ assert.notEqual(changed.digest, initial.digest); assert.equal(changed.status, 'pending');
+ const before = exportBoard(box.board);
+ assert.throws(() => store.decideSentinel(box.board, { agentId: store.PERSON, channel: 'view', name: initial.name, digest: initial.digest, decision: 'approve' }), error => error.code === 'STALE_SENTINEL');
+ assert.deepEqual(exportBoard(box.board), before);
+ assert.equal(store.beginSentinelRun(box.board, { agentId: box.agent, name: changed.name, digest: changed.digest, run: 'not-approved' }), null);
+ }
+ const current = sentinels(box.board)[0];
+ store.decideSentinel(box.board, { agentId: store.PERSON, channel: 'view', name: current.name, digest: current.digest, decision: 'decline', reason: 'Not this check' });
+ assert.equal((await box.run()).length, 0);
+ assert.equal(sentinels(box.board)[0].status, 'declined');
+});
+
+test('simultaneous observers run one child and an identical approval cannot steal its lease [A6,H16]', async t => {
+ const box = fixture(t);
+ const check = checker(box, "import {appendFileSync} from 'node:fs'; appendFileSync('count','run\\n');");
+ const row = store.proposeSentinel(box.board, { agentId: box.agent, row: { name: 'one-child', check, every: '10m', owner: 'core' } });
+ store.decideSentinel(box.board, { agentId: store.PERSON, channel: 'view', name: row.name, digest: row.digest, decision: 'approve' });
+ await Promise.all([box.run(), box.run()]);
+ assert.equal(readFileSync(join(box.root, 'count'), 'utf8'), 'run\n');
+ box.clock.time += 600_001;
+ const started = store.beginSentinelRun(box.board, { agentId: box.agent, name: row.name, digest: row.digest, run: 'claimed-run' });
+ assert.ok(started);
+ store.decideSentinel(box.board, { agentId: store.PERSON, channel: 'view', name: row.name, digest: row.digest, decision: 'approve' });
+ assert.equal(store.beginSentinelRun(box.board, { agentId: 'coordinator', name: row.name, digest: row.digest, run: 'must-not-run' }), null);
+});
+
+test('watch timeout drains its owned child group and retains only bounded final output [A6]', async t => {
+ const box = fixture(t);
+ const check = checker(box, "import {spawn} from 'node:child_process'; import {writeFileSync} from 'node:fs'; const child=spawn(process.execPath,['-e','setInterval(()=>{},1000)'],{stdio:'inherit'});writeFileSync('child-pid',String(child.pid));console.log('x'.repeat(50000));console.log('final receipt');setInterval(()=>{},1000);");
+ const row = sentinelDefinition({ name: 'bounded', check, every: '10m', owner: 'coordinator', timeoutMs: 3_000 }); // budget: actual checker hang ceiling, with startup room under shared CI load.
+ const result = await executeSentinel(box.root, row);
+ assert.equal(result.green, false); assert.equal(result.timedOut, true);
+ assert.ok(result.output.length <= 16_384); assert.match(result.output, /final receipt/u);
+ const pid = Number(readFileSync(join(box.root, 'child-pid'), 'utf8'));
+ const status = runFixtureChild('/bin/ps', ['-p', String(pid), '-o', 'stat='], { encoding: 'utf8' });
+ assert.ok(status.status !== 0 || /^\s*Z/u.test(status.stdout), 'the owned descendant is gone or reaped to a non-running zombie');
+});
+
+test('a project directory symlink cannot change an approved watch into outside execution [A6]', async t => {
+ const box = fixture(t); const outside = join(box.directory, 'outside'); mkdirSync(outside);
+ symlinkSync(outside, join(box.root, 'escape'), 'dir');
+ const row = sentinelDefinition({ name: 'inside', check: 'echo must-not-run', every: 'daily', owner: 'coordinator', directory: 'escape' });
+ await assert.rejects(executeSentinel(box.root, row), error => error.code === 'BAD_SENTINEL');
+ assert.throws(() => sentinelDefinition({ ...row, directory: '../outside' }), error => error.code === 'BAD_SENTINEL');
+});
+
+test('watch receipts replay deterministically, export without execution and keep older engines unchanged [A6,H16]', async t => {
+ const box = fixture(t); const replica = store.openBoard(':memory:', box.clock); t.after(() => store.closeBoard(replica));
+ importBoard(replica, exportBoard(box.board));
+ const args = [{ agentId: box.agent, row: { name: 'replayed', check: 'false', every: '10m', owner: 'core' } }];
+ const move = prepareEngineMove(box.board, 'proposeSentinel', args);
+ const at = box.clock.now().toISOString();
+ const first = applyEngineMove(box.board, move, { sequence: 1, at });
+ const second = applyEngineMove(replica, move, { sequence: 1, at });
+ assert.deepEqual(second, first); assert.deepEqual(exportBoard(replica), exportBoard(box.board));
+ const before = exportBoard(replica);
+ assert.throws(() => applyEngineMove(replica, { ...move, engine: BOARD_SENTINEL_ENGINE - 1, id: 'old-engine' }, { sequence: 2, at }), error => error.code === 'RELAY_MOVE');
+ assert.deepEqual(exportBoard(replica), before);
+ const legacy = { event_kind: 'sentinel-failure', event_by: 'sentinel', item_id: null,
+ event_detail: JSON.stringify({ engine: BOARD_SENTINEL_ENGINE - 1, cause: 'sentinel:replayed' }) };
+ assert.deepEqual(eventCauses(legacy), []);
+ assert.equal(rigorReport([legacy, legacy], { person: store.PERSON }).causes.length, 0);
+ assert.notEqual(sentinelDigest({ ...args[0].row, every: 'daily' }), first.result.digest);
+});
+
+/** Read a real locale-stable child census without confusing failure with an empty process set. */
+function childCensus() {
+ const read = runFixtureChild('/bin/ps', ['-axo', 'pid=,ppid=,pgid=,lstart=,stat=,comm='], { encoding: 'utf8', env: { ...process.env, LC_ALL: 'C' } });
+ assert.equal(read.status, 0); const rows = parseProcessCensus(read.stdout); assert.ok(rows); return rows;
+}
+
+/** Compare the captured PID, group, start and executable before touching this fixture's child. */
+function sameChild(left, right) {
+ return left && right && left.pid === right.pid && left.pgid === right.pgid && left.started === right.started && left.processSha256 === right.processSha256;
+}
+
+test('a successful watch drains an unreferenced descendant before returning its receipt [A6]', async t => {
+ if (process.platform === 'win32') return t.skip('POSIX process-group drain');
+ const box = fixture(t);
+ const check = checker(box, "import {spawn} from 'node:child_process';import {writeFileSync} from 'node:fs';const c=spawn(process.execPath,['-e',\"setInterval(()=>{},1000)\"],{stdio:'ignore'});writeFileSync('background-pid',String(c.pid));c.unref();");
+ let owned;
+ t.after(async () => {
+ if (!owned) return;
+ for (const signal of ['SIGTERM', 'SIGKILL']) {
+ const current = childCensus().get(owned.pid);
+ if (!current || current.state.startsWith('Z')) return;
+ assert.ok(sameChild(owned, current), 'fixture cleanup requires the exact captured child identity');
+ try { process.kill(owned.pid, signal); } catch(error) { if(error.code !== 'ESRCH') throw error; }
+ const deadline = Date.now()+2_000;
+ while(Date.now()<deadline) { const child=childCensus().get(owned.pid); if(!child || child.state.startsWith('Z')) return; await new Promise(resolve=>setTimeout(resolve,25)); }
+ }
+ assert.fail('the positively owned fixture child did not drain');
+ });
+ const result = await executeSentinel(box.root, sentinelDefinition({name:'background',check,every:'hourly',owner:'coordinator'}));
+ const pid = Number(readFileSync(join(box.root, 'background-pid'), 'utf8'));
+ owned = childCensus().get(pid);
+ assert.equal(result.green, true);
+ assert.ok(!owned || owned.state.startsWith('Z'), 'a successful receipt must not precede its owned descendant shutdown');
+});
+
+test('watch receipts reject extra or contradictory fields without consuming the run lease [A6,H16]', t => {
+ const box=fixture(t);
+ const row=store.proposeSentinel(box.board,{agentId:box.agent,row:{name:'receipt',check:'true',every:'hourly',owner:'core'}});
+ store.decideSentinel(box.board,{agentId:store.PERSON,channel:'view',name:row.name,digest:row.digest,decision:'approve'});
+ store.beginSentinelRun(box.board,{agentId:box.agent,name:row.name,digest:row.digest,run:'receipt-run'});
+ const args={agentId:box.agent,name:row.name,digest:row.digest,run:'receipt-run'};
+ const good={green:true,code:0,timedOut:false,signal:null,aborted:false,durationMs:1,output:'done'};
+ for(const result of [{...good,extra:'not a receipt field'},{...good,green:false},{...good,signal:'bad signal'}, {...good,aborted:'false'}, {...good,code:-1}]) {
+ const before=exportBoard(box.board);
+ assert.throws(()=>store.finishSentinelRun(box.board,{...args,result}),error=>error.code==='BAD_SENTINEL');
+ assert.deepEqual(exportBoard(box.board),before,'invalid receipts neither write events nor consume the lease');
+ }
+ store.finishSentinelRun(box.board,{...args,result:good});
+ assert.equal(sentinels(box.board)[0].lastRun.green,true);
+});
+
+
+test('cancellation after a watch lease but before launch records no false failure [A6,H16]', async t => {
+ const box=fixture(t), controller=new AbortController();
+ const row=store.proposeSentinel(box.board,{agentId:box.agent,row:{name:'cancelled',check:'true',every:'hourly',owner:'core'}});
+ store.decideSentinel(box.board,{agentId:store.PERSON,channel:'view',name:row.name,digest:row.digest,decision:'approve'});
+ await runDueSentinels({root:box.root,board:box.board,agentId:'coordinator',ordered:box.ordered,signal:controller.signal,
+ execute:async (root,definition,options)=>{controller.abort();return executeSentinel(root,definition,options);}});
+ assert.equal(sentinels(box.board)[0].lastRun.aborted,true,'cancellation keeps its actual outcome');
+ assert.equal(store.events(box.board).filter(event=>event.event_kind==='sentinel-failure').length,0,'shutdown does not invent a Rigor failure');
+ assert.equal(store.allShouts(box.board).filter(shout=>shout.shout_from==='sentinel').length,0,'shutdown creates no failure or recovery finding');
+});
+
+test('a successful watch drains a descendant that ignores TERM before publishing its receipt [A6]', async t => {
+ if (process.platform === 'win32') return t.skip('POSIX process-group drain');
+ const box = fixture(t);
+ const childFile = join(box.root, 'stubborn-child.mjs');
+ writeFileSync(childFile, "import {writeFileSync} from 'node:fs'; process.on('SIGTERM',()=>{}); setInterval(()=>{},1000); writeFileSync('stubborn-pid',String(process.pid)); process.send('ready'); process.disconnect();");
+ const check = checker(box, `import {spawn} from 'node:child_process'; import {once} from 'node:events'; const child=spawn(process.execPath,[${JSON.stringify(childFile)}],{stdio:['ignore','ignore','ignore','ipc']}); await once(child,'message'); child.unref();`, 'stubborn-parent.mjs');
+ let owned;
+ t.after(async () => {
+ if (!owned) return;
+ for (const signal of ['SIGTERM', 'SIGKILL']) {
+ const current = childCensus().get(owned.pid);
+ if (!current || current.state.startsWith('Z')) return;
+ assert.ok(sameChild(owned, current), 'cleanup requires the captured PID, start, group and executable');
+ try { process.kill(owned.pid, signal); } catch (error) { if (error.code !== 'ESRCH') throw error; }
+ const deadline = Date.now() + 2_000; // budget: exact owned-child shutdown grace, not a speed assertion.
+ while (Date.now() < deadline) {
+ const child = childCensus().get(owned.pid);
+ if (!child || child.state.startsWith('Z')) return;
+ await new Promise(resolve => setTimeout(resolve, 25));
+ }
+ }
+ assert.fail('the positively owned stubborn fixture child did not drain');
+ });
+ const running = executeSentinel(box.root, sentinelDefinition({ name: 'stubborn', check, every: 'hourly', owner: 'coordinator', timeoutMs: 10_000 })); // budget: fixture command hang ceiling, no throughput claim.
+ void running.catch(() => {});
+ const pidFile = join(box.root, 'stubborn-pid');
+ const readyDeadline = Date.now() + 10_000; // budget: wait for the fixture's actual child-start receipt.
+ while (!existsSync(pidFile) && Date.now() < readyDeadline) await new Promise(resolve => setTimeout(resolve, 25));
+ assert.ok(existsSync(pidFile), 'the descendant installs its TERM handler before its parent exits');
+ const pid = Number(readFileSync(pidFile, 'utf8'));
+ owned = childCensus().get(pid);
+ const result = await running;
+ assert.equal(result.green, true, 'the approved parent succeeded');
+ const remaining = childCensus().get(pid);
+ assert.ok(!remaining || remaining.state.startsWith('Z'), 'no receipt precedes the stubborn descendant shutdown');
+});
+
+test('the background observer runs an approved board watch through its real resume child [A6,D3]', async t => {
+ const box = fixture(t);
+ const check = checker(box, "import {appendFileSync} from 'node:fs'; appendFileSync('background-runs','run\\n'); console.log('background receipt'); process.exit(1);");
+ const row = store.proposeSentinel(box.board, { agentId: box.agent, row: { name: 'background', check, every: '10m', owner: box.agent } });
+ let tick;
+ let cancelled = false;
+ const errors = [];
+ const timer = { unref() {} };
+ const observer = startServeSentinel({ projectRoot: box.root,
+ every: (callback, interval) => { assert.equal(interval, 600_000, 'the production cadence is unchanged'); tick = callback; return timer; },
+ cancel: actual => { assert.equal(actual, timer); cancelled = true; },
+ onError: error => errors.push(error),
+ });
+ t.after(() => observer.close());
+ await tick();
+ const runs = join(box.root, 'background-runs');
+ assert.equal(existsSync(runs), false, 'the real child cannot execute a pending proposal');
+ store.decideSentinel(box.board, { agentId: store.PERSON, channel: 'view', name: row.name, digest: row.digest, decision: 'approve' });
+ const configFile = join(box.root, 'pullboard.json');
+ const config = readFileSync(configFile, 'utf8');
+ writeFileSync(configFile, JSON.stringify({ ...JSON.parse(config), health: { sentinel: false } }));
+ await tick();
+ assert.equal(existsSync(runs), false, 'the board off switch suppresses an approved watch');
+ writeFileSync(configFile, config);
+ const settingsFile = machineSettingsFile();
+ const settings = readFileSync(settingsFile, 'utf8');
+ writeFileSync(settingsFile, JSON.stringify({ ...JSON.parse(settings), health: { sentinel: false } }));
+ await tick();
+ assert.equal(existsSync(runs), false, 'the machine off switch suppresses an approved watch');
+ writeFileSync(settingsFile, settings);
+ await tick();
+ assert.deepEqual(errors, []);
+ assert.equal(readFileSync(runs, 'utf8'), 'run\n', 'the default background callback launches the real resume child');
+ const notices = store.allShouts(box.board).filter(shout => shout.shout_text.startsWith('Sentinel failed: background'));
+ assert.equal(notices.length, 1);
+ assert.equal(notices[0].shout_to, box.agent);
+ assert.match(notices[0].shout_text, /background receipt/u);
+ await tick();
+ assert.equal(readFileSync(runs, 'utf8'), 'run\n', 'the next callback honors the recorded due time');
+ await observer.close();
+ assert.equal(cancelled, true);
+});