brl-subagent 2.9.1 → 2.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/AGENT.md +3 -0
  2. package/CHANGELOG.md +366 -0
  3. package/README.md +11 -5
  4. package/package.json +14 -11
  5. package/src/agent-tools.ts +178 -19
  6. package/src/atomic-write.ts +101 -0
  7. package/src/background-guard.ts +295 -0
  8. package/src/background-pipeline.ts +21 -5
  9. package/src/boot-recovery.ts +16 -0
  10. package/src/brief.ts +228 -0
  11. package/src/delegate-handler.ts +51 -12
  12. package/src/dispatch-header.ts +226 -0
  13. package/src/history.ts +0 -6
  14. package/src/index.ts +27 -5
  15. package/src/kill-escalation.ts +32 -9
  16. package/src/mode-prologue.ts +3 -11
  17. package/src/mode-runners.ts +0 -3
  18. package/src/notify-completion.ts +81 -12
  19. package/src/params.ts +10 -2
  20. package/src/prelude.ts +1 -9
  21. package/src/proc.ts +73 -15
  22. package/src/project-flags.ts +42 -6
  23. package/src/recovery-engine.ts +16 -2
  24. package/src/recovery.ts +29 -0
  25. package/src/retry-armed.ts +383 -0
  26. package/src/run-registry.ts +121 -1
  27. package/src/runner.ts +308 -10
  28. package/src/schema.ts +0 -11
  29. package/src/session-manager.ts +490 -54
  30. package/src/state.ts +16 -1
  31. package/src/stop-lineage.ts +280 -0
  32. package/src/templates.ts +97 -1
  33. package/src/terminal-notifier.ts +70 -4
  34. package/src/types.ts +110 -0
  35. package/src/unit-run.ts +7 -2
  36. package/src/validate.ts +47 -86
  37. package/templates/analyze-data.md +1 -0
  38. package/templates/code-review.md +1 -0
  39. package/templates/debug-issue.md +1 -0
  40. package/templates/implement-feature.md +1 -0
  41. package/templates/prototype.md +1 -0
  42. package/templates/refactor.md +1 -0
  43. package/templates/security-audit.md +1 -0
  44. package/templates/write-docs.md +1 -0
  45. package/templates/write-tests.md +1 -0
  46. package/src/dispatch-line.ts +0 -144
@@ -0,0 +1,295 @@
1
+ // Purpose: Resolve, contain and verify the conductor-named background guard (#620).
2
+ /**
3
+ * A background delegation builds its own resource loader with extension
4
+ * discovery OFF, because background sessions have no trust prompt and would
5
+ * otherwise import model-chosen code into the conductor's process (F1). The
6
+ * side effect was that the repository's own policy guard never loaded either,
7
+ * so rule #5 had no mechanical enforcement for the DEFAULT dispatch shape
8
+ * (#620; a live probe wrote the cockpit's `src/` by absolute path).
9
+ *
10
+ * The fix keeps `noExtensions: true` and adds exactly ONE absolute entry to
11
+ * `additionalExtensionPaths` — a path the loader imports (one mechanism, one
12
+ * module instance) that our shipped `src/` never imports itself. That makes
13
+ * three properties load-bearing, and this module owns all three so they cannot
14
+ * drift apart:
15
+ *
16
+ * 1. THE NAME IS NOT A PATH. `brl-subagent.backgroundGuard` is a single path
17
+ * component, validated against `GUARD_NAME_RE`, resolved to
18
+ * `<projectRoot>/.pi/extensions/<name>/index.ts`. A relative name, a
19
+ * separator, `.`/`..` and an absolute name have no spelling that passes.
20
+ * 2. THE RESOLVED FILE MUST BE INSIDE THE PROJECT. A relative
21
+ * `additionalExtensionPath` resolves against the loader's cwd — the
22
+ * CHILD's, which the model chooses (F5) — so the entry must be absolute, and
23
+ * an absolute entry is only safe if it is contained. Both the root and the
24
+ * file are realpathed and compared with a `sep`-anchored prefix, so a
25
+ * symlink resolving out of the project is a named refusal, never a silent
26
+ * load. A bare `startsWith` would accept `<root>-evil/…`.
27
+ * 3. LOADING IS NOT REGISTRATION. `reload()` never throws; a load failure or a
28
+ * factory that registers nothing lands in `getExtensions()` (F9). So
29
+ * "required" is only real if the handlers are read back, which
30
+ * `verifyGuardLoaded` does for the two handlers the guard exists to
31
+ * provide.
32
+ *
33
+ * Every refusal is a thrown `Error` whose message starts `background guard:`
34
+ * and names the setting plus the concrete cause, and it is thrown BEFORE
35
+ * `createAgentSession` — so a refused spawn leaves no agent record and no run
36
+ * entry, and the pipeline's existing `catch` renders it as an ordinary
37
+ * "Failed to spawn background agent: …" result.
38
+ *
39
+ * The manifest read itself stays in `project-flags.ts` (re-exported here): that
40
+ * module is the ONE reader of the `brl-subagent` section, and its ratchet test
41
+ * fails a second one.
42
+ */
43
+
44
+ import { realpathSync, statSync } from "node:fs";
45
+ import { join, resolve, sep } from "node:path";
46
+ import { readBackgroundGuard, readProcessChecks } from "./project-flags";
47
+
48
+ export { readBackgroundGuard };
49
+
50
+ /**
51
+ * The value that turns the setting OFF while keeping the key — what a project writes
52
+ * after opting out of a guard it once required.
53
+ */
54
+ export const GUARD_DISABLED = "none";
55
+
56
+ /**
57
+ * A guard name is ONE path component: it starts alphanumeric (so `.`, `..` and a
58
+ * leading dot are all impossible) and contains no separator, so no name can
59
+ * escape the extension directory it is resolved under. Deliberately narrower
60
+ * than a filename: a guard directory is a package-shaped unit.
61
+ */
62
+ const GUARD_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
63
+
64
+ /**
65
+ * The two handlers a required guard must register. `tool_call` is the
66
+ * enforcement; `before_agent_start` is the reminder that covers the `bash`
67
+ * blind spot — a guard without the second is a guard whose silence looks like
68
+ * compliance.
69
+ */
70
+ export const REQUIRED_GUARD_HANDLERS = ["tool_call", "before_agent_start"] as const;
71
+
72
+ /** The project-wide symbol key a loaded guard registers itself under (see `.pi/extensions/worktree-guard`). */
73
+ export const LOADED_GUARDS_SYMBOL_KEY = "brl-subagent.loaded-guards";
74
+
75
+ /** The setting's name as it is written in `package.json` — every message names it. */
76
+ const SETTING = "brl-subagent.backgroundGuard";
77
+
78
+ function refusal(cause: string): Error {
79
+ return new Error(`background guard: ${SETTING} ${cause}`);
80
+ }
81
+
82
+ /**
83
+ * The guard this project REQUIRES, or `null` for "off". The `"none"` sentinel is
84
+ * folded here — the one place — so the spawn seam and the conductor-start
85
+ * warning cannot disagree about what "off" means.
86
+ */
87
+ export function readRequiredGuard(cwd: string | undefined): string | null {
88
+ const named = readBackgroundGuard(cwd);
89
+ return named === null || named === GUARD_DISABLED ? null : named;
90
+ }
91
+
92
+ /** `realpath` of `path`, or `null` when it does not exist (the caller names the cause). */
93
+ function resolveExisting(path: string): string | null {
94
+ try {
95
+ return realpathSync(path);
96
+ } catch {
97
+ return null;
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Resolve `name` to the absolute, realpathed path of the guard's entry module
103
+ * under `projectRoot`, or throw a named refusal.
104
+ *
105
+ * The returned path is used VERBATIM as the loader entry: it is already
106
+ * canonical and absolute, which is the only shape that cannot be re-resolved
107
+ * against the child's cwd (F5).
108
+ */
109
+ export function resolveGuardPath(projectRoot: string, name: string): string {
110
+ if (!GUARD_NAME_RE.test(name)) {
111
+ throw refusal(
112
+ `names "${name}", which is not a single path component (letters, digits, dot, dash and underscore; no separator, no leading dot) — refusing to resolve it`,
113
+ );
114
+ }
115
+ const realRoot = resolveExisting(projectRoot);
116
+ if (realRoot === null) {
117
+ throw refusal(
118
+ `names "${name}", but the project root ${projectRoot} does not exist — cannot resolve it`,
119
+ );
120
+ }
121
+ const candidate = join(realRoot, ".pi", "extensions", name, "index.ts");
122
+ const realGuard = resolveExisting(candidate);
123
+ if (realGuard === null) {
124
+ throw refusal(
125
+ `names "${name}", but ${candidate} does not exist — the named guard was not found (a missing, renamed or mis-spelled guard is a refusal, not a silent spawn)`,
126
+ );
127
+ }
128
+ let isFile: boolean;
129
+ try {
130
+ isFile = statSync(realGuard).isFile();
131
+ } catch (error) {
132
+ throw refusal(`names "${name}", but ${candidate} cannot be read — ${(error as Error).message}`);
133
+ }
134
+ if (!isFile) throw refusal(`names "${name}", but ${candidate} is not a file — the guard entry point must be a module`);
135
+ // `sep`-anchored containment: a bare `startsWith(realRoot)` also accepts a
136
+ // sibling named `<root>-something`, which is the escape this check exists for.
137
+ if (realGuard !== realRoot && !realGuard.startsWith(realRoot + sep)) {
138
+ throw refusal(
139
+ `names "${name}", but ${candidate} resolves to ${realGuard}, which is OUTSIDE the project root ${realRoot} — a symlink may not carry the guard out of the project`,
140
+ );
141
+ }
142
+ return realGuard;
143
+ }
144
+
145
+ /** The minimal shape `verifyGuardLoaded` reads — one small interface, so the caller is not coupled to the SDK class. */
146
+ export interface GuardLoaderView {
147
+ getExtensions(): {
148
+ readonly extensions?: readonly GuardExtensionView[];
149
+ readonly errors?: readonly { readonly path: string; readonly error: string }[];
150
+ };
151
+ }
152
+
153
+ /** An extension as the loader reports it: its advertised paths and its registered handlers. */
154
+ export interface GuardExtensionView {
155
+ readonly path?: string;
156
+ readonly resolvedPath?: string;
157
+ readonly sourceInfo?: { readonly path?: string };
158
+ readonly handlers?: ReadonlyMap<string, readonly unknown[]>;
159
+ }
160
+
161
+ /** Every path an extension advertises, canonicalized; used only for identity comparison. */
162
+ function extensionPaths(extension: GuardExtensionView): string[] {
163
+ const advertised = [extension.sourceInfo?.path, extension.resolvedPath, extension.path];
164
+ return advertised.filter((p): p is string => typeof p === "string" && p !== "");
165
+ }
166
+
167
+ /** Two spellings of one file: canonical when it exists, absolute-lexical otherwise. */
168
+ function samePath(left: string, right: string): boolean {
169
+ const a = resolveExisting(left) ?? resolve(left);
170
+ const b = resolveExisting(right) ?? resolve(right);
171
+ return a === b;
172
+ }
173
+
174
+ /**
175
+ * Prove the named guard is loaded AND registered both handlers, or throw.
176
+ *
177
+ * Three failure shapes, each named, because they are three different fixes:
178
+ * - a loader `errors` entry for the guard file (syntax error, bad export, a
179
+ * throwing factory) — the module never became an extension (F9);
180
+ * - no extension advertises that path at all — the loader silently skipped it;
181
+ * - the extension is there but a handler is missing — `{ block }` will never be
182
+ * produced, which is the silent-success shape of F9/#620.
183
+ */
184
+ export function verifyGuardLoaded(loader: GuardLoaderView, guardPath: string): void {
185
+ let reported: ReturnType<GuardLoaderView["getExtensions"]>;
186
+ try {
187
+ reported = loader.getExtensions();
188
+ } catch (error) {
189
+ throw refusal(`resolved ${guardPath}, but the resource loader could not report its extensions: ${(error as Error).message}`);
190
+ }
191
+ const errors = reported.errors ?? [];
192
+ const failed = errors.find((entry) => samePath(entry.path, guardPath));
193
+ if (failed !== undefined) {
194
+ throw refusal(`resolved ${guardPath}, but it FAILED TO LOAD: ${failed.error}`);
195
+ }
196
+ const loaded = (reported.extensions ?? []).find((extension) =>
197
+ extensionPaths(extension).some((advertised) => samePath(advertised, guardPath)),
198
+ );
199
+ if (loaded === undefined) {
200
+ throw refusal(
201
+ `resolved ${guardPath}, but the resource loader did not load it as an extension — no registered guard means no enforcement`,
202
+ );
203
+ }
204
+ const missing = REQUIRED_GUARD_HANDLERS.filter((handler) => {
205
+ const registered = loaded.handlers?.get(handler);
206
+ return registered === undefined || registered.length === 0;
207
+ });
208
+ if (missing.length > 0) {
209
+ throw refusal(
210
+ `resolved ${guardPath} and loaded it, but it registered no ${missing.join(" and no ")} handler — a required guard must register both: the block enforces, the reminder covers the shell blind spot`,
211
+ );
212
+ }
213
+ }
214
+
215
+ /**
216
+ * The loaded-guard marker's shape: guard directory basename → how many LIVE
217
+ * registrations this process holds. It is the ONLY channel from a loaded
218
+ * extension back to the conductor's start-up warning, and nothing else in this
219
+ * repository uses a global (ADR 0029).
220
+ *
221
+ * A COUNT, not a set, because more than one loader can import the same guard in
222
+ * one process (the conductor's own runtime, plus every background delegation). A
223
+ * plain set would be erased by whichever instance shut down first — a background
224
+ * child's shutdown would blank the conductor's marker, and `/reload` would blank
225
+ * it for the instant between the old runner's shutdown and the new load. The guard
226
+ * factory increments AFTER its handlers are armed; its `session_shutdown` handler
227
+ * decrements and deletes at zero (`/reload` emits shutdown to the OLD runner, so
228
+ * the pair nets to unchanged).
229
+ *
230
+ * A guard that never arms cannot write it, which is exactly what makes its
231
+ * absence meaningful. Missing or foreign marker ⇒ empty counts (never a throw):
232
+ * the warning is a sensor, not a new fault.
233
+ */
234
+ export function readLoadedGuardCounts(): ReadonlyMap<string, number> {
235
+ const marker = (globalThis as Record<symbol, unknown>)[Symbol.for(LOADED_GUARDS_SYMBOL_KEY)];
236
+ if (!(marker instanceof Map)) return new Map<string, number>();
237
+ const counts = new Map<string, number>();
238
+ for (const [name, count] of marker as Map<unknown, unknown>) {
239
+ // A foreign writer may leave anything under the key; only a positive count names a guard.
240
+ if (typeof name === "string" && typeof count === "number" && count > 0) counts.set(name, count);
241
+ }
242
+ return counts;
243
+ }
244
+
245
+ /**
246
+ * The names whose count is positive — "present" for every caller that only asks
247
+ * whether a guard is armed. Derived from {@link readLoadedGuardCounts} so the two
248
+ * can never disagree about what presence means.
249
+ */
250
+ export function readLoadedGuards(): ReadonlySet<string> {
251
+ return new Set(readLoadedGuardCounts().keys());
252
+ }
253
+
254
+ /**
255
+ * The conductor-start warning text, or `null` when there is nothing to say.
256
+ *
257
+ * SILENT unless all three hold: process checks are on for this project, a guard
258
+ * is named (not absent, not `"none"`), and that name is missing from the
259
+ * loaded-guard marker. The silence for `"none"`/absent is the contract — a
260
+ * project that did not opt in must never see our process machinery.
261
+ */
262
+ export function missingGuardWarning(cwd: string | undefined): string | null {
263
+ const named = readRequiredGuard(cwd);
264
+ if (named === null) return null;
265
+ if (!readProcessChecks(cwd)) return null;
266
+ if ((readLoadedGuardCounts().get(named) ?? 0) > 0) return null;
267
+ // The consequence must be the TRUE one (review of PR #627, F1): a background
268
+ // delegation loads this guard EXPLICITLY from its absolute path, so it is
269
+ // guarded whether or not this conductor's own session is. What is missing is
270
+ // the conductor's own enforcement, and that is what the text must say.
271
+ return (
272
+ `${SETTING} names "${named}", but no extension named "${named}" registered its handlers in this process, ` +
273
+ `so THIS conductor session is not guarded — its own write/edit calls are not checked. ` +
274
+ `Background delegations are still guarded: each one loads .pi/extensions/${named}/index.ts explicitly. ` +
275
+ `To guard this session too, enable project extensions and trust this project (or remove the setting).`
276
+ );
277
+ }
278
+
279
+ /**
280
+ * `missingGuardWarning`, latched: the returned closure answers on the first
281
+ * `session_start` that has something to say and `null` forever after. The latch
282
+ * is per closure, and the composition root builds one per extension invocation —
283
+ * so it is once per process for the surface that matters, and never twice for one.
284
+ * One flag, no repeats — the warning exists to end a silence, not to fill the log
285
+ * on every session switch.
286
+ */
287
+ export function createGuardStartNotice(): (cwd: string | undefined) => string | null {
288
+ let emitted = false;
289
+ return (cwd) => {
290
+ if (emitted) return null;
291
+ const warning = missingGuardWarning(cwd);
292
+ if (warning !== null) emitted = true;
293
+ return warning;
294
+ };
295
+ }
@@ -66,6 +66,7 @@ import {
66
66
  type DelegateTaskParams,
67
67
  type GitMode,
68
68
  type RecoveryMode,
69
+ type RetryCause,
69
70
  type SubagentResult,
70
71
  type SubagentRun,
71
72
  type SubagentToolOptions,
@@ -140,6 +141,9 @@ interface BackgroundAgentSpawnRequest {
140
141
  dispatchId?: string;
141
142
  resumeOf?: string;
142
143
  attempt?: number;
144
+ // Issue #616: why this attempt exists — stated by the MINT SITE, never
145
+ // inferred from the source run's failure class.
146
+ retryCause?: RetryCause;
143
147
  // Option B U3 (D4): recovery posture snapshot for the background run.
144
148
  recoveryPosture?: RecoveryMode;
145
149
  }
@@ -166,10 +170,16 @@ interface BackgroundPipeline {
166
170
  spawnBackgroundRun: (
167
171
  pi: ExtensionAPI,
168
172
  ctx: ExtensionContext,
169
- params: (DelegateTaskParams & { noJev?: string }) | ReturnType<typeof resolveRetryParams>,
173
+ params: DelegateTaskParams | ReturnType<typeof resolveRetryParams>,
170
174
  singleTask: string,
171
175
  retrySourceRun?: SubagentRun,
172
176
  attemptContext?: string,
177
+ /**
178
+ * Issue #616: WHY this spawn is a retry. `scheduleTransportRetry` passes
179
+ * `"transport"`; a caller-driven `retryRunId` retry passes `"manual"`.
180
+ * Omitted for a fresh dispatch. Never derived from the source record.
181
+ */
182
+ retryCause?: RetryCause,
173
183
  ) => Promise<ToolResult<undefined>>;
174
184
  }
175
185
 
@@ -324,7 +334,6 @@ export function createBackgroundPipeline(
324
334
  outputFile: merged.outputFile,
325
335
  force: params.force as boolean | undefined,
326
336
  cwd: targets.cwd,
327
- noJev: params.noJev,
328
337
  },
329
338
  });
330
339
  if (preTask.error) return preTask.error;
@@ -520,6 +529,9 @@ export function createBackgroundPipeline(
520
529
  attempt: spawn.attempt,
521
530
  // Option B U3 (D4): recovery posture snapshot for the background run.
522
531
  recoveryPosture: spawn.recoveryPosture,
532
+ // Issue #616: the retry cause rides the spawn onto the agent record, the
533
+ // run entry and the registry entry.
534
+ retryCause: spawn.retryCause,
523
535
  });
524
536
 
525
537
  // -----------------------------------------------------------------
@@ -820,7 +832,7 @@ export function createBackgroundPipeline(
820
832
  * the two shapes disagree on, and claiming the recorded value was
821
833
  * schema-validated would be a lie: records are read back from disk.
822
834
  */
823
- params: (DelegateTaskParams & { noJev?: string }) | ReturnType<typeof resolveRetryParams>,
835
+ params: DelegateTaskParams | ReturnType<typeof resolveRetryParams>,
824
836
  singleTask: string,
825
837
  // Option B U1: the spawn entry a retryRunId resolved to, so a retried
826
838
  // background run inherits dispatchId/resumeOf/attempt (record identity,
@@ -835,6 +847,10 @@ export function createBackgroundPipeline(
835
847
  * cannot be steered by the preamble's wording.
836
848
  */
837
849
  attemptContext?: string,
850
+ /** Issue #616: WHY this spawn is a retry — stated by the caller, never
851
+ * inferred. `"transport"` from `scheduleTransportRetry`, `"manual"` from a
852
+ * caller-driven retry; omitted for a fresh dispatch. */
853
+ retryCause?: RetryCause,
838
854
  ): Promise<ToolResult<undefined>> {
839
855
  // Issue #443: the DECLARED level, guarded before `bgResolved` clamps it.
840
856
  // This is the seam for the TRANSPORT auto-retry (`scheduleTransportRetry`
@@ -922,7 +938,6 @@ export function createBackgroundPipeline(
922
938
  outputFile: bgResolvedOutputFile,
923
939
  force: params.force,
924
940
  cwd: targets.cwd,
925
- noJev: params.noJev,
926
941
  },
927
942
  });
928
943
  if (bgPreTask.error) return bgPreTask.error;
@@ -939,7 +954,7 @@ export function createBackgroundPipeline(
939
954
  );
940
955
 
941
956
  // Option B U1: durability identity (retry inherits the original dispatch).
942
- const bgIdentity = newDispatchIdentity(retrySourceRun);
957
+ const bgIdentity = newDispatchIdentity(retrySourceRun, retryCause);
943
958
  const spawned = await startBackgroundAgent(pi, ctx, {
944
959
  // Issue #411: the preamble rides the system-prompt side
945
960
  // (`resumeContext`), never the task. The task stays the recorded
@@ -964,6 +979,7 @@ export function createBackgroundPipeline(
964
979
  dispatchId: bgIdentity.dispatchId,
965
980
  resumeOf: bgIdentity.resumeOf,
966
981
  attempt: bgIdentity.attempt,
982
+ retryCause: bgIdentity.retryCause,
967
983
  recoveryPosture: state.config.recovery,
968
984
  });
969
985
 
@@ -129,6 +129,19 @@ export function createBootRecovery(rt: RuntimeContext): BootRecovery {
129
129
  });
130
130
  }
131
131
  const wiring = sm;
132
+ // Issue #554: a SIGKILL cannot run the atomic writer's cleanup, so `.tmp`
133
+ // siblings accumulate in the agent store. Bound them at boot, beside the
134
+ // other store-hygiene steps. Only temps older than an hour are removed, so
135
+ // a live writer's temp always survives; the sweep never throws, and the
136
+ // line is emitted only when something was actually reclaimed.
137
+ if (wiring) {
138
+ try {
139
+ const sweptTemps = wiring.sweepAgentRecordTemps();
140
+ if (sweptTemps > 0) log.info("Boot recovery swept stale agent-record temps", { count: sweptTemps });
141
+ } catch (err) {
142
+ log.warn("Boot recovery temp sweep failed", { error: (err as Error).message });
143
+ }
144
+ }
132
145
  try {
133
146
  // `recoverProduction` owns the /proc platform guard (nothing is marked or
134
147
  // killed without start-token verification) — see src/recovery.ts.
@@ -186,6 +199,9 @@ export function createBootRecovery(rt: RuntimeContext): BootRecovery {
186
199
  repaired: summary.flipRepaired,
187
200
  retired: summary.flipRetired,
188
201
  failures: summary.flipFailures,
202
+ // Issue #554: the corrupt SUBSET of `failures`, present only when
203
+ // non-zero — with none, this object is byte-identical to today's.
204
+ ...(summary.flipCorrupt > 0 ? { corrupt: summary.flipCorrupt } : {}),
189
205
  });
190
206
  }
191
207
  if (summary.neverStarted > 0) {
package/src/brief.ts ADDED
@@ -0,0 +1,228 @@
1
+ // Purpose: The signed-brief contract (issue #606 §2): fence-aware section predicates over briefs/<slug>.md.
2
+ /**
3
+ * A signed brief is the record of what the human agreed before any code was
4
+ * written. The predicate is deliberately content-based, because a heading and a
5
+ * marker are trivial to emit and prove nothing:
6
+ *
7
+ * 1. `## Want` — at least one section-body line outside fences that contains
8
+ * non-whitespace, is not a heading, and is NOT the confirmation marker.
9
+ * 2. `## Settled decisions` — either one table row outside fences (excluding
10
+ * the header row and the `|---` separator) whose decision cell AND answer
11
+ * cell are both non-blank, or the explicit zero-decision form
12
+ * `none — <why>` (the points the human chose not to settle).
13
+ * 3. `confirmed: <YYYY-MM-DD> by <name>` — the last non-blank line outside
14
+ * fences, with no unfilled `<…>` placeholder left in it.
15
+ *
16
+ * FENCES AND SECTIONS ARE DEFINED ONCE, here, and applied to every predicate:
17
+ * a line inside a ``` fence is not a heading, not a body line and not a table
18
+ * row. `^## ` headings OUTSIDE fences delimit sections; a body runs to the next
19
+ * such heading or to EOF. That single rule is what makes the four shapes below
20
+ * have defined outcomes instead of accidents of whichever predicate an
21
+ * implementer picked: a marker-only file fails (1), a fenced-only Want fails
22
+ * (1), a row with an empty answer cell fails (2), and an honest confirmed want
23
+ * with no decisions passes (2) through the zero-decision form.
24
+ *
25
+ * THE MARKER IS A RECORD, NOT AUTHENTICATION. Nothing here proves the human
26
+ * typed the line; the gate records that a brief claims to be confirmed, the way
27
+ * a commit message records intent. Treat it as evidence to audit, never as a
28
+ * signature to trust.
29
+ */
30
+
31
+ import { readFileSync } from "node:fs";
32
+ import { join } from "node:path";
33
+
34
+ /** The directory holding briefs, relative to the dispatch cwd. */
35
+ export const BRIEF_DIR = "briefs";
36
+
37
+ /** The confirmation marker's shape — `confirmed: 2026-11-28 by azmeen`. */
38
+ const CONFIRMATION_RE = /^confirmed:\s*(\d{4}-\d{2}-\d{2})\s+by\s+(\S.*)$/;
39
+
40
+ /** An unfilled template slot: `<date>`, `<name>`, `<…>`. */
41
+ const PLACEHOLDER_RE = /<[^>]*>/;
42
+
43
+ /** The zero-decision form: the em dash AND a non-blank reason. */
44
+ const ZERO_DECISION_RE = /^none\s*—\s*\S/;
45
+
46
+ /** The line that ends the zero-decision form and every Want body. */
47
+ const MARKER_LINE_RE = /^confirmed:/i;
48
+
49
+ /** A section heading, outside fences only — `^## ` delimits sections (spec §2). */
50
+ const SECTION_HEADING_RE = /^## /;
51
+
52
+ /**
53
+ * Any heading at all, for predicate 1's "(b) is not a heading": `### Sub` inside
54
+ * a Want body is a sub-heading, not the human's words, and it must not be able
55
+ * to fill an otherwise empty section.
56
+ */
57
+ const ANY_HEADING_RE = /^#{1,6}\s/;
58
+
59
+ /** One source line, tagged with whether a code fence encloses it. */
60
+ interface BriefLine {
61
+ text: string;
62
+ inFence: boolean;
63
+ }
64
+
65
+ export interface BriefVerdict {
66
+ ok: boolean;
67
+ /** Which predicate failed, in prose an author can act on ('' when ok). */
68
+ reason: string;
69
+ }
70
+
71
+ export const BRIEF_OK: BriefVerdict = Object.freeze({ ok: true, reason: "" });
72
+
73
+ function fail(reason: string): BriefVerdict {
74
+ return { ok: false, reason };
75
+ }
76
+
77
+ /**
78
+ * Tag every line with its fence state. A fence marker line is itself fenced
79
+ * (so it is not a heading and not a body line); a fence left unclosed fences
80
+ * everything after it, which is the fail-closed reading: an unparsable brief is
81
+ * not a signed brief.
82
+ */
83
+ function classifyLines(text: string): BriefLine[] {
84
+ const lines: BriefLine[] = [];
85
+ let inFence = false;
86
+ for (const raw of text.split(/\r?\n/)) {
87
+ const isMarker = raw.trim().startsWith("```");
88
+ lines.push({ text: raw, inFence: isMarker || inFence });
89
+ if (isMarker) inFence = !inFence;
90
+ }
91
+ return lines;
92
+ }
93
+
94
+ function isContentLine(line: BriefLine): boolean {
95
+ return !line.inFence && !ANY_HEADING_RE.test(line.text) && line.text.trim() !== "";
96
+ }
97
+
98
+ /**
99
+ * Split fenced-outside lines into sections keyed by their `## ` heading. The
100
+ * heading line itself is dropped; the body runs to the next heading or EOF.
101
+ */
102
+ function sections(lines: readonly BriefLine[]): Map<string, BriefLine[]> {
103
+ const map = new Map<string, BriefLine[]>();
104
+ let current: string | undefined;
105
+ for (const line of lines) {
106
+ if (!line.inFence && SECTION_HEADING_RE.test(line.text)) {
107
+ const title = line.text.slice(3).trim();
108
+ current = title;
109
+ if (!map.has(title)) map.set(title, []);
110
+ continue;
111
+ }
112
+ if (current !== undefined) map.get(current)!.push(line);
113
+ }
114
+ return map;
115
+ }
116
+
117
+ /** §2 predicate 1 — a Want section with the human's own words in it. */
118
+ function wantProblem(body: readonly BriefLine[] | undefined): string | undefined {
119
+ if (body === undefined) return "`## Want` is missing — state what the human wants, in their words.";
120
+ const filled = body.some(
121
+ (line) => isContentLine(line) && !MARKER_LINE_RE.test(line.text.trim()),
122
+ );
123
+ return filled
124
+ ? undefined
125
+ : "`## Want` is empty — the section needs at least one non-blank line of the human's words. " +
126
+ "A fence, a heading and the `confirmed:` marker do not count.";
127
+ }
128
+
129
+ /** §2 predicate 2 — one decision with an answer, or the stated zero-decision form. */
130
+ function decisionsProblem(body: readonly BriefLine[] | undefined): string | undefined {
131
+ if (body === undefined) {
132
+ return "`## Settled decisions` is missing — record each settled decision, or write `none — <why>`.";
133
+ }
134
+ const hasRow = body.some((line) => isDecisionRow(line));
135
+ const hasZeroForm = body.some(
136
+ (line) => isContentLine(line) && !MARKER_LINE_RE.test(line.text.trim()) && ZERO_DECISION_RE.test(line.text.trim()),
137
+ );
138
+ if (hasRow || hasZeroForm) return undefined;
139
+ return (
140
+ "`## Settled decisions` is empty — a row needs a non-blank decision cell AND a non-blank answer cell, " +
141
+ "or write the zero-decision form `none — <why>`."
142
+ );
143
+ }
144
+
145
+ /**
146
+ * A table row that settles a decision: decision cell (between the 1st and 2nd
147
+ * `|`) and answer cell (between the 2nd and 3rd `|`) both non-blank. The header
148
+ * row and the `|---` separator are not decisions.
149
+ */
150
+ function isDecisionRow(line: BriefLine): boolean {
151
+ if (line.inFence) return false;
152
+ const trimmed = line.text.trim();
153
+ if (!trimmed.startsWith("|")) return false;
154
+ const cells = trimmed.split("|").slice(1, 4);
155
+ if (cells.length < 2) return false;
156
+ const decision = cells[0].trim();
157
+ const answer = cells[1].trim();
158
+ if (decision === "" && answer === "") return false;
159
+ // The `|---|:--|` separator row.
160
+ if (/^[\s:-]+$/.test(decision)) return false;
161
+ // The header row (`| Decision | Answer | …`).
162
+ if (/^decision$/i.test(decision)) return false;
163
+ return decision !== "" && answer !== "";
164
+ }
165
+
166
+ /** §2 predicate 3 — the confirmation marker, last, with no unfilled slot. */
167
+ function confirmationProblem(lines: readonly BriefLine[]): string | undefined {
168
+ const outside = lines.filter((line) => !line.inFence);
169
+ let index = outside.length - 1;
170
+ while (index >= 0 && outside[index].text.trim() === "") index--;
171
+ if (index < 0) {
172
+ return "the brief has no confirmation marker — the last non-blank line must be `confirmed: <YYYY-MM-DD> by <name>`.";
173
+ }
174
+ const last = outside[index].text.trim();
175
+ if (PLACEHOLDER_RE.test(last)) {
176
+ return `the confirmation marker still holds an unfilled placeholder — replace it with the date and the human's name: ${last}`;
177
+ }
178
+ if (!CONFIRMATION_RE.test(last)) {
179
+ return `the last non-blank line must be the confirmation marker \`confirmed: <YYYY-MM-DD> by <name>\` — found: ${last}`;
180
+ }
181
+ return undefined;
182
+ }
183
+
184
+ /**
185
+ * Check a brief's TEXT against §2. Predicates are checked in document order so
186
+ * a file that fails several names the first one an author would fix.
187
+ */
188
+ export function validateBriefText(text: string): BriefVerdict {
189
+ const lines = classifyLines(String(text ?? ""));
190
+ const bySection = sections(lines);
191
+ for (const problem of [
192
+ wantProblem(bySection.get("Want")),
193
+ decisionsProblem(bySection.get("Settled decisions")),
194
+ confirmationProblem(lines),
195
+ ]) {
196
+ if (problem !== undefined) return fail(problem);
197
+ }
198
+ return BRIEF_OK;
199
+ }
200
+
201
+ /** The brief's path for a slug — one `join`, never a slug that skipped the grammar. */
202
+ export function briefPath(cwd: string, slug: string): string {
203
+ return join(cwd, BRIEF_DIR, `${slug}.md`);
204
+ }
205
+
206
+ /**
207
+ * Check the brief file at `cwd/briefs/<slug>.md`. Fail-closed in every failure
208
+ * mode: a missing brief is the refusal the gate exists for, and an unreadable
209
+ * one is not evidence of anything.
210
+ */
211
+ export function validateBriefFile(cwd: string, slug: string): BriefVerdict {
212
+ const path = briefPath(cwd, slug);
213
+ let text: string;
214
+ try {
215
+ text = readFileSync(path, "utf8");
216
+ } catch (error) {
217
+ const code = (error as NodeJS.ErrnoException).code;
218
+ if (code === "ENOENT") {
219
+ return fail(
220
+ `brief "${slug}" not found at ${path} — the dispatch cwd's tree carries no such brief. ` +
221
+ "Commit the brief before dispatching from this tree, or rebase the tree onto the commit that added it.",
222
+ );
223
+ }
224
+ return fail(`brief "${slug}" at ${path} could not be read (${code ?? "unknown error"}) — an unreadable brief is not a signed brief.`);
225
+ }
226
+ const verdict = validateBriefText(text);
227
+ return verdict.ok ? BRIEF_OK : fail(`brief "${slug}" at ${path} does not satisfy the brief contract: ${verdict.reason}`);
228
+ }