brl-subagent 2.9.0 → 2.9.2

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.
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
+ }
@@ -295,7 +295,7 @@ function warnUnknownParams(
295
295
  function applyTemplate(
296
296
  params: DelegateTaskParams,
297
297
  templates: readonly TaskTemplate[],
298
- deps: Pick<NormalizeDeps, "pi" | "log">,
298
+ deps: Pick<NormalizeDeps, "pi" | "log" | "ctx">,
299
299
  ): Outcome<void> {
300
300
  const { pi, log } = deps;
301
301
  if (!params.template) return { ok: true, value: undefined };
@@ -318,7 +318,11 @@ function applyTemplate(
318
318
  };
319
319
  }
320
320
 
321
- const resolved = resolveTemplate(templateEntry, params.params ?? {});
321
+ // Issue #606 (§3a): the renderer needs the DISPATCH cwd, because a template
322
+ // with no `dispatch:` field is refused only where the project opted in.
323
+ const resolved = resolveTemplate(templateEntry, params.params ?? {}, {
324
+ cwd: templateDispatchCwd(params, deps.ctx),
325
+ });
322
326
  if (!resolved.ok) {
323
327
  return {
324
328
  ok: false,
@@ -376,6 +380,18 @@ function applyTemplate(
376
380
  return { ok: true, value: undefined };
377
381
  }
378
382
 
383
+ /**
384
+ * The cwd a rendered dispatch will run in, as far as THIS seam can know it:
385
+ * the call's own `cwd` resolved against the harness cwd, else the harness cwd.
386
+ * The later resolver may refine it (a worktree branch, a per-step cwd), so this
387
+ * is the project the CONDUCTOR named — and the read is fail-open, which is what
388
+ * keeps a template rendering untouched in a project that never opted in.
389
+ */
390
+ function templateDispatchCwd(params: DelegateTaskParams, ctx: ExtensionContext): string {
391
+ const declared = typeof params.cwd === "string" ? params.cwd : "";
392
+ return declared === "" ? ctx.cwd : path.resolve(ctx.cwd, declared);
393
+ }
394
+
379
395
  /**
380
396
  * Seam A — resolve the dispatch inputs: unknown-param warning, template
381
397
  * resolution, retry restore (issue #430).
@@ -402,7 +418,7 @@ function normalizeInput(
402
418
  // A1: the two pre-resolution notices (unknown keys, ignored task) and the
403
419
  // template application itself.
404
420
  warnUnknownParams(params, { pi, log });
405
- const templated = applyTemplate(params, state.config.templates, { pi, log });
421
+ const templated = applyTemplate(params, state.config.templates, { pi, log, ctx });
406
422
  if (!templated.ok) return templated;
407
423
 
408
424
  // Handle retryRunId — MUST run after template resolution and before the
@@ -881,7 +897,19 @@ function routeDispatch(
881
897
  if (useBackground) {
882
898
  return {
883
899
  kind: "returned",
884
- result: runners.spawnBackgroundRun(pi, ctx, params, singleTask, retrySourceRun),
900
+ // Issue #616: a background spawn reached from `delegate_task` is a
901
+ // CALLER-driven retry when a `retryRunId` resolved — `"manual"`, never
902
+ // `"transport"`. Only `scheduleTransportRetry` may claim the automatic
903
+ // cause, because only it IS the automatic retry.
904
+ result: runners.spawnBackgroundRun(
905
+ pi,
906
+ ctx,
907
+ params,
908
+ singleTask,
909
+ retrySourceRun,
910
+ undefined,
911
+ retrySourceRun ? "manual" : undefined,
912
+ ),
885
913
  };
886
914
  }
887
915
 
@@ -1524,7 +1552,11 @@ function registerForegroundRun(
1524
1552
  // Option B U1: durability identity — a retry inherits the original
1525
1553
  // dispatchId and records resumeOf/attempt; a fresh marker keys the
1526
1554
  // child process for boot-time orphan discovery.
1527
- const identity = newDispatchIdentity(retrySourceRun);
1555
+ // Issue #616: a foreground retry is always CALLER-driven (`retryRunId` or
1556
+ // `retryOnTimeout`), so its cause is `manual` — there is no automatic
1557
+ // foreground retry. Recorded for completeness; a foreground run has no agent
1558
+ // record, so the dispatch-scoped stop never reaches it (stated non-goal).
1559
+ const identity = newDispatchIdentity(retrySourceRun, retrySourceRun ? "manual" : undefined);
1528
1560
  // Issue #511 (U2): create this run's scratch directory at record creation so
1529
1561
  // the record can name it (the retry preamble, U3, reads `scratchDir`). The
1530
1562
  // spawn seam in `runner.ts` re-prepares idempotently and is the gate that
@@ -1545,6 +1577,7 @@ function registerForegroundRun(
1545
1577
  dispatchId: identity.dispatchId,
1546
1578
  resumeOf: identity.resumeOf,
1547
1579
  attempt: identity.attempt,
1580
+ retryCause: identity.retryCause,
1548
1581
  owner: currentProcessOwner(),
1549
1582
  childMarker: crypto.randomUUID(),
1550
1583
  // U3 (D4): the session recovery posture at dispatch.
@@ -2148,13 +2181,13 @@ export function createDelegateHandler(
2148
2181
  "You can customize per-call via inheritSystemPrompt and systemPrompt: set inheritSystemPrompt: false to save context, provide a systemPrompt for custom instructions, or use both to add instructions on top of inheritance.",
2149
2182
  "Set thinkingLevel per call to match task complexity. The level is capped at the user's configured maximum. Map tasks to levels using this heuristic: off = file listing, grep, simple read. minimal = file diff, syntax check, find-and-replace. low = refactoring, test generation, documentation. medium = default — code review, debugging, moderate analysis. high = security audit, architecture review, complex debugging. xhigh = multi-step causal reasoning, research, novel problem solving. Default to 'off' or 'minimal' for trivial tasks — do not waste the user's budget.",
2150
2183
  "Use outputFile to have the subagent write full findings to disk and return only a structured summary — saves context tokens for large investigations.",
2151
- "Set timeout (in ms) to limit how long a subagent can run. Useful for tasks that might hang or get stuck. Background runs default to a 30-minute deadline when no timeout is given; an explicit timeout is honored as given (30 minutes is a default, not a ceiling).",
2184
+ "Set timeout (in ms) to limit how long a subagent can run. Useful for tasks that might hang or get stuck. Background runs default to a 30-minute deadline when no timeout is given; a foreground run has no default. An explicit positive timeout is honored as given — except a raw value ≥ 2³¹−1 ms or a nonpositive value (both normalize to no timeout; for a background run the 30-minute default then applies, a foreground run has none) and the opt-in high-thinking foreground switch that may drop it. 30 minutes is a background default, not a ceiling.",
2152
2185
  "Set cwd to override the subagent's working directory. Defaults to the current project directory.",
2153
2186
  "Set label to give the subagent a human-readable name (e.g., 'security-audit' or 'docs-review'). Labels appear in the status bar and tool call display.",
2154
2187
  `Use preset to apply a delegation configuration (built-in or custom via /brl-subagent preset). Preset values are defaults — explicit parameters override them. IMPORTANT: some presets restrict tools — e.g. outputFile requires the subagent's write tool, which security-auditor and code-reviewer exclude. Built-in presets: ${presetRestrictionSummary}. Custom presets are NOT listed here — inspect them via /brl-subagent preset before combining with outputFile or tool-dependent work. When combining a preset with outputFile or tool-dependent work, verify the preset allows the required tools.`,
2155
2188
  buildTemplateGuideline(templateSummary),
2156
2189
  "To retry a failed subagent, pass its run ID as retryRunId. The retry restores the recorded params - including background, gitMode, approvalMode, force - with explicit values on this call winning. Multi-step runs degrade to a single task. See the retryRunId description for the full field list.",
2157
- "Set retryOnTimeout: true to automatically retry a FOREGROUND subagent that times out. Only retries once — the second timeout is treated as a final failure. A background run is not retried on its deadline, but it IS retried once automatically when it dies on a transport-class error (a dropped connection before the work started), recorded as attempt 2 and announced with a warning toast — do not re-dispatch it yourself. Any other background failure needs an explicit retryRunId.",
2190
+ "Set retryOnTimeout: true to automatically retry a FOREGROUND subagent that times out. Only retries once — the second timeout is treated as a final failure. A background run is not retried on its deadline, but it IS retried once automatically when it dies on a transport-class error (a transport death at any point before the run settles, not only before it starts work), recorded as attempt 2 and announced with a warning toast — do not re-dispatch it yourself. A second transport death is NOT retried again: that settle is an ordinary failure, and its completion notice says to change the shape (run it in the conductor, override the model, or split the brief). Any other background failure needs an explicit retryRunId.",
2158
2191
  "Background is the CONDITIONAL default for delegate_task. With background omitted, a single task or a tasks fan-out runs in the BACKGROUND when the effective approvalMode is 'auto' (call param, else config): the tool returns an agent ID immediately, and with tasks it fans out — every task starts as its own background agent, one ID per task in task order, and the conductor is woken once per agent as each finishes. It stays FOREGROUND when the effective approvalMode is 'writes' or 'always' (a background run has no approval dialog, so a gate that needs the user must keep blocking), and for chain and graph (they block by definition; an explicit background: true with chain/graph is rejected). Pass background: false for a quick probe whose answer the next step needs inline; pass background: true to force a background run where the default would block. Background runs wake the conductor with a structured completion message when they finish — do not poll: polling is only correct when completion notifications are disabled (completionNotify \"off\"); one status check as a stall check is legitimate. A background run defaults to a 30-minute deadline when no timeout is given.",
2159
2192
  "",
2160
2193
  "## Conductor Guardrails",
@@ -2164,7 +2197,7 @@ export function createDelegateHandler(
2164
2197
  "2. **Thinking level**: Match thinking level to task complexity: off/minimal for trivial tasks (file listing, grep), low for refactoring/docs, medium for code review/debugging, high for security audits/complex debugging, xhigh for multi-step reasoning/novel problems.",
2165
2198
  "3. **Git mode**: Use gitMode='branch' for tasks that create commits or PRs. Use gitMode='none' for read-only tasks.",
2166
2199
  "4. **Tools**: Verify the subagent has the tools it needs. If the task writes files, ensure write and edit are not excluded. If the task runs commands, ensure bash is not excluded.",
2167
- "5. **Timeout**: Set timeout based on task complexity. Simple: 30s. Medium: 60s. Complex: 120s+. xhigh thinking: at least 120s. Background runs default to a 30-minute deadline when no timeout is set; an explicit timeout is honored.",
2200
+ "**5. Timeout:** A deadline is a cap, not a schedule: over-allocating is cheap, under-allocating is expensive. The `timeout` parameter is milliseconds; think in minutes. The 30-minute **background** default applies only when no valid timeout remains after normalization — it is a default, not an enforced floor; a **foreground** run has no default deadline. An explicit **positive** value is honored as given, except a raw value ≥ 2³¹−1 ms **or a nonpositive value** (both normalize to no timeout; a background run then gets the 30m default, a foreground run has none) and the opt-in high-thinking foreground switch that may drop it. When in doubt **pass `timeout: 7200000`** — 2 hours (7,200,000 ms); for slow/local models or long tasks, pass more. Reference-workload priors: `AGENT.md` §Deadlines and retries.",
2168
2201
  "",
2169
2202
  "These guardrails prevent common misconfigurations. The extension also validates configuration before spawning (H1): tool warnings are surfaced in the returned result, but two mismatches are HARD errors that reject the delegation — outputFile with the write tool excluded, and a capability-critical task/toolset mismatch (a run/execute/test/compile/benchmark task without bash, or an exploration task with none of find/ls/grep/bash; pass force: true to override the capability class). Getting it right the first time is faster and more efficient.",
2170
2203
  "",
@@ -0,0 +1,230 @@
1
+ // Purpose: The mandatory dispatch header (issue #606): split it from the task body and parse it.
2
+ /**
3
+ * The dispatch header — one definition, two consumers (issue #606, Unit 1).
4
+ *
5
+ * Every dispatch task must open with a block:
6
+ *
7
+ * dispatch: impl | review | probe | docs
8
+ * brief: <slug> (required when dispatch: impl)
9
+ * brief: none — <reason> (the stated escape; reason non-empty)
10
+ *
11
+ * Two consumers, never two parsers:
12
+ * - `parseDispatchHeader` — the validator's gate (src/validate.ts). It reads
13
+ * the leading BLOCK only, so a task that merely quotes `dispatch: impl` in
14
+ * its prose (inline or fenced) stays valid (T3).
15
+ * - `splitDispatchHeader` — the router's seam (src/params.ts keeps the header
16
+ * out of `classifyTask`). A header would otherwise re-route a dispatch:
17
+ * `dispatch: review` matches the code-reviewer rule before the body's own
18
+ * "write tests" ever reaches the test-engineer rule (spec §3b).
19
+ *
20
+ * BOUNDARY, stated once so CRLF/BOM/blank-separator cases have one answer:
21
+ * the block starts at the first non-blank line and consumes consecutive lines
22
+ * matching `^(dispatch|brief|jev):`, ending at the first line that does not
23
+ * match (a blank line ends it too). The task is `\r?\n`-split and a leading BOM
24
+ * is stripped before the first line is read. A title (`# Task`) before the block
25
+ * ends it — that is a refusal, not a tolerance, because a silent tolerance would
26
+ * let a quoted example at the top of a task become the declaration.
27
+ *
28
+ * The Jev line may still appear ANYWHERE (src/dispatch-line.ts scans every line
29
+ * and takes the first valid one), which is why `jev:` is a block-continuation
30
+ * line here but does not have to be inside the block.
31
+ */
32
+
33
+ /** The four dispatch kinds. `impl` is the gated class: it needs a brief. */
34
+ export const DISPATCH_KINDS = ["impl", "review", "probe", "docs"] as const;
35
+ export type DispatchKind = (typeof DISPATCH_KINDS)[number];
36
+
37
+ /** The kinds as one comma-separated list, quoted verbatim in every refusal. */
38
+ export const DISPATCH_KIND_LIST = DISPATCH_KINDS.join(", ");
39
+
40
+ /**
41
+ * The three accepted forms, quoted VERBATIM in every refusal so the conductor
42
+ * never has to guess. Kept as one constant: a second copy is a second truth.
43
+ */
44
+ export const DISPATCH_HEADER_FORMS = [
45
+ "dispatch: impl | review | probe | docs",
46
+ "brief: <slug> (required when dispatch: impl)",
47
+ "brief: none — <reason> (the stated escape; reason non-empty)",
48
+ ].join("\n");
49
+
50
+ /**
51
+ * A brief slug: one path component, lowercase alphanumeric plus interior
52
+ * hyphens, 1-64 characters. `none` is reserved for the escape and is therefore
53
+ * rejected as a slug. Separators, dots and traversal are all refused by this
54
+ * pattern — never join a slug that has not matched it.
55
+ */
56
+ export const BRIEF_SLUG_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;
57
+
58
+ /** The reserved escape token (`brief: none — <reason>`). */
59
+ export const BRIEF_ESCAPE_TOKEN = "none";
60
+
61
+ /** A line that belongs to the leading block. Anchored: an indented copy does not. */
62
+ const BLOCK_LINE_RE = /^(dispatch|brief|jev):/;
63
+
64
+ const DISPATCH_PREFIX = "dispatch:";
65
+ const BRIEF_PREFIX = "brief:";
66
+ const EM_DASH = "—";
67
+
68
+ /** The token is reserved only when it STANDS ALONE — `none-extra` is a legal slug. */
69
+ const ESCAPE_PREFIX_RE = new RegExp(`^${BRIEF_ESCAPE_TOKEN}(?:\\s|$)`);
70
+ const ESCAPE_VALUE_RE = new RegExp(`^${BRIEF_ESCAPE_TOKEN}\\s*${EM_DASH}\\s*(.*)$`);
71
+
72
+ export interface DispatchHeaderSplit {
73
+ /** The consumed block, `\n`-joined (empty when the task does not open with one). */
74
+ header: string;
75
+ /** Everything after the block. */
76
+ body: string;
77
+ }
78
+
79
+ /** A brief reference: a signed brief's slug, or the stated escape and its reason. */
80
+ export type BriefDeclaration =
81
+ | { kind: "slug"; slug: string }
82
+ | { kind: "none"; reason: string };
83
+
84
+ export type DispatchHeaderVerdict =
85
+ | { ok: true; kind: DispatchKind; brief: BriefDeclaration | undefined }
86
+ | { ok: false; reason: string };
87
+
88
+ /**
89
+ * Split a task into its leading dispatch block and the body that follows.
90
+ *
91
+ * Pure and total: any string maps to a pair, and `header + "\n" + body`
92
+ * reconstructs the task apart from the leading blank lines the block start
93
+ * consumes. Never throws — the validator and the router both call it on
94
+ * conductor-supplied text.
95
+ */
96
+ export function splitDispatchHeader(task: string): DispatchHeaderSplit {
97
+ const text = String(task ?? "").replace(/^\uFEFF/, "");
98
+ const lines = text.split(/\r?\n/);
99
+
100
+ let start = 0;
101
+ while (start < lines.length && lines[start].trim() === "") start++;
102
+
103
+ let end = start;
104
+ while (end < lines.length && BLOCK_LINE_RE.test(lines[end])) end++;
105
+
106
+ return {
107
+ header: lines.slice(start, end).join("\n"),
108
+ body: lines.slice(end).join("\n"),
109
+ };
110
+ }
111
+
112
+ /** One refusal shape: the finding first, then the three accepted forms verbatim. */
113
+ function refuse(detail: string): DispatchHeaderVerdict {
114
+ return { ok: false, reason: `${detail} The accepted dispatch block is:\n${DISPATCH_HEADER_FORMS}` };
115
+ }
116
+
117
+ /** The block's value for one prefix (`undefined` when the line carries none). */
118
+ function lineValue(line: string, prefix: string): string {
119
+ return line.slice(prefix.length).trim();
120
+ }
121
+
122
+ /** Parse one `brief:` value into its declaration, or the reason it is not one. */
123
+ function parseBriefValue(value: string): BriefDeclaration | { error: string } {
124
+ if (value === "") {
125
+ return { error: "the brief line needs a value — a slug, or the stated escape." };
126
+ }
127
+ // The escape is `none — <reason>` with an EM DASH. The bare token is judged
128
+ // here so `brief: none` cannot slide through as a slug.
129
+ if (ESCAPE_PREFIX_RE.test(value)) {
130
+ const match = ESCAPE_VALUE_RE.exec(value);
131
+ if (match === null) {
132
+ return {
133
+ error: `the brief escape is \`brief: ${BRIEF_ESCAPE_TOKEN} ${EM_DASH} <reason>\` — the em dash and the reason are both required.`,
134
+ };
135
+ }
136
+ const reason = match[1].trim();
137
+ if (reason === "") {
138
+ return { error: "the brief escape's reason is empty — say why no brief was agreed." };
139
+ }
140
+ return { kind: "none", reason };
141
+ }
142
+ if (value === BRIEF_ESCAPE_TOKEN || !BRIEF_SLUG_PATTERN.test(value)) {
143
+ return {
144
+ error:
145
+ `invalid brief slug "${value}": a slug matches ${BRIEF_SLUG_PATTERN.source}, ` +
146
+ `is a single path component (no "/", no ".", no ".."), and "${BRIEF_ESCAPE_TOKEN}" is reserved for the escape.`,
147
+ };
148
+ }
149
+ return { kind: "slug", slug: value };
150
+ }
151
+
152
+ /**
153
+ * Parse the leading dispatch block. Refusals quote the three accepted forms
154
+ * verbatim (§3); success returns the kind and, when one was declared, the brief.
155
+ *
156
+ * A task that does NOT open with a block is refused, and the reason says which:
157
+ * a stray `dispatch:` line later in the text gets "the block must be the first
158
+ * content" (P12), because that is the mistake an author actually makes.
159
+ */
160
+ export function parseDispatchHeader(task: string): DispatchHeaderVerdict {
161
+ const { header, body } = splitDispatchHeader(task);
162
+ const blockLines = header === "" ? [] : header.split("\n");
163
+
164
+ const dispatchLines = blockLines.filter((line) => line.startsWith(DISPATCH_PREFIX));
165
+ if (dispatchLines.length === 0) {
166
+ const strayDeclaration = body.split(/\r?\n/).some((line) => line.startsWith(DISPATCH_PREFIX));
167
+ return refuse(
168
+ strayDeclaration
169
+ ? "missing dispatch header: the block must be the first content — the task's first non-blank line " +
170
+ "is not one of `dispatch:`/`brief:`/`jev:`, so a later declaration is outside the block. " +
171
+ "Move the block to the top of the task."
172
+ : "missing dispatch header: the task's first non-blank line must declare the kind.",
173
+ );
174
+ }
175
+ if (dispatchLines.length > 1) {
176
+ return refuse("more than one `dispatch:` line in the leading block — declare the kind exactly once.");
177
+ }
178
+
179
+ const dispatchRest = lineValue(dispatchLines[0], DISPATCH_PREFIX);
180
+ if (dispatchRest === "") {
181
+ return refuse("the dispatch line has no kind — name exactly one.");
182
+ }
183
+ // The one-token rule: no trailing comment, no extra words. `dispatch: impl #
184
+ // note` is ambiguous, and an ambiguous declaration is not a declaration.
185
+ if (/\s/.test(dispatchRest)) {
186
+ return refuse(
187
+ `the dispatch line takes exactly one token — no trailing comment or extra words after "${dispatchRest.split(/\s+/)[0]}".`,
188
+ );
189
+ }
190
+ if (!(DISPATCH_KINDS as readonly string[]).includes(dispatchRest)) {
191
+ return refuse(`unknown dispatch kind "${dispatchRest}" — must be one of: ${DISPATCH_KIND_LIST}.`);
192
+ }
193
+ const kind = dispatchRest as DispatchKind;
194
+
195
+ const briefLines = blockLines.filter((line) => line.startsWith(BRIEF_PREFIX));
196
+ if (briefLines.length > 1) {
197
+ return refuse("more than one `brief:` line in the leading block — declare the brief exactly once.");
198
+ }
199
+
200
+ let brief: BriefDeclaration | undefined;
201
+ if (briefLines.length === 1) {
202
+ const parsed = parseBriefValue(lineValue(briefLines[0], BRIEF_PREFIX));
203
+ if ("error" in parsed) return refuse(parsed.error);
204
+ brief = parsed;
205
+ }
206
+
207
+ if (kind === "impl" && brief === undefined) {
208
+ return refuse(
209
+ "`dispatch: impl` requires a brief — add `brief: <slug>` (the file is briefs/<slug>.md) " +
210
+ `or \`brief: ${BRIEF_ESCAPE_TOKEN} ${EM_DASH} <reason>\` for the stated escape.`,
211
+ );
212
+ }
213
+
214
+ return { ok: true, kind, brief };
215
+ }
216
+
217
+ /**
218
+ * The frontmatter `dispatch:` field's problem, or `undefined` when it is absent
219
+ * or one of the four kinds. Shared by the template's load-time validation and
220
+ * its render-time check: an unknown or misspelled value must be an error naming
221
+ * the field and the allowed set, never a silently ignored key (spec §3a).
222
+ */
223
+ export function dispatchFieldProblem(value: unknown): string | undefined {
224
+ if (value === undefined) return undefined;
225
+ if (typeof value !== "string" || !(DISPATCH_KINDS as readonly string[]).includes(value)) {
226
+ const shown = typeof value === "string" ? `"${value}"` : JSON.stringify(value);
227
+ return `invalid "dispatch" value ${shown} — must be one of: ${DISPATCH_KIND_LIST}.`;
228
+ }
229
+ return undefined;
230
+ }
package/src/index.ts CHANGED
@@ -42,6 +42,7 @@ import { loadBuiltinPresets, loadCustomPresets, getAllPresets, writePresetFile }
42
42
  import { cleanupTempDirs, reapActiveChildren } from "./runner";
43
43
  import { clearProgressLinger, repaintStatus, stopProgressTicker } from "./concurrency";
44
44
  import { setLogCwd } from "./logging";
45
+ import { createGuardStartNotice } from "./background-guard";
45
46
  import { createTerminalNotifier } from "./terminal-notifier";
46
47
 
47
48
  // ---------------------------------------------------------------------------
@@ -162,6 +163,13 @@ export default function (pi: ExtensionAPI) {
162
163
  resetRecoveryNotice,
163
164
  } = createBootRecovery(rt);
164
165
 
166
+ // Issue #620 (Q14): the cheap half of "required". A project that names a
167
+ // background guard must hear about a guard that never loaded — the silence is
168
+ // what let #620 hide — but exactly once per process, and not at all when the
169
+ // project did not opt in. The latch is per invocation (D5), like every other
170
+ // once-per-boot flag here.
171
+ const guardStartNotice = createGuardStartNotice();
172
+
165
173
  // -------------------------------------------------------------------
166
174
  // Config change callback
167
175
  // -------------------------------------------------------------------
@@ -239,6 +247,13 @@ export default function (pi: ExtensionAPI) {
239
247
  // Issue #179 (D6): createLogger ran at module load with no cwd — point
240
248
  // the shared file sink at this session's cwd now that it exists.
241
249
  setLogCwd(ctx.cwd);
250
+ // Issue #620 (Q14): one warning per process when this project names a
251
+ // background guard that is not loaded. Silent for an absent key and for
252
+ // "none" — a project that did not opt in never sees our machinery.
253
+ {
254
+ const warning = guardStartNotice(ctx.cwd);
255
+ if (warning !== null) log.warn(warning);
256
+ }
242
257
  // Load built-in presets
243
258
  const presetsDir = pkgPath("presets");
244
259
  state.builtinPresets = loadBuiltinPresets(presetsDir, log);
@@ -287,6 +302,17 @@ export default function (pi: ExtensionAPI) {
287
302
  // records interrupted BEFORE anything else touches their worktrees.
288
303
  await performBootRecovery();
289
304
 
305
+ // Issue #616 / review 624 (B1): reclaim the armed-retry markers a conductor
306
+ // left behind when it died between an arm write and the retry's spawn. No
307
+ // run-shaped reader enumerates `armed/` (that is what keeps an intent from
308
+ // rendering as a run row), so nothing else would ever notice them, and a
309
+ // stale marker makes every later stop of its dispatch cancel a phantom.
310
+ {
311
+ const { sweepStaleArmedRetries } = await import("./retry-armed");
312
+ const swept = sweepStaleArmedRetries();
313
+ if (swept.reclaimed > 0) log.info("Reclaimed stale armed-retry markers", swept);
314
+ }
315
+
290
316
  // Issue #466 (ADR 0026 D2/D5): reconcile the durable head-state records —
291
317
  // the ONE step allowed to move git at boot, and only for a record whose
292
318
  // owner it has proved dead.