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
package/src/types.ts CHANGED
@@ -5,9 +5,11 @@
5
5
  * All shared type definitions and constants for the brl-subagent extension.
6
6
  */
7
7
 
8
+ import type { DispatchKind } from "./dispatch-header";
8
9
  import type { delegateTaskParamsSchema } from "./schema";
9
10
  import type { TranscriptMessage } from "./transcript-tail";
10
11
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
12
+ import type { Usage } from "@earendil-works/pi-ai";
11
13
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
12
14
  import type { Static } from "typebox";
13
15
 
@@ -31,6 +33,38 @@ export type RecoveryMode = (typeof RECOVERY_MODES)[number];
31
33
 
32
34
  export const DEFAULT_RECOVERY: RecoveryMode = "offer";
33
35
 
36
+ /**
37
+ * Issue #616: the TERMINAL statuses of an agent record — one definition, shared
38
+ * by `session-manager`'s `isTerminalAgentStatus` (the long-standing export) and
39
+ * by the stop contract, which must not accept the word "Stopped" for a record
40
+ * that is still live.
41
+ */
42
+ export const TERMINAL_AGENT_STATUSES = ["completed", "failed", "stopped"] as const;
43
+
44
+ export function isTerminalAgentStatusValue(status: AgentStatus): boolean {
45
+ return (TERMINAL_AGENT_STATUSES as readonly string[]).includes(status);
46
+ }
47
+
48
+ /**
49
+ * Issue #616: WHY a retry attempt exists. Two different retries mint the same
50
+ * lineage shape (same `dispatchId`, `resumeOf` pointing at the source,
51
+ * `attempt + 1`), so the shape alone cannot tell them apart:
52
+ *
53
+ * - `"transport"` — the background transport auto-retry (#365): the run died
54
+ * on a transport-class error and one replacement was dispatched for it.
55
+ * It is part of the dispatch a `stop_subagent` aims at.
56
+ * - `"manual"` — a caller-driven retry (`retryRunId`): a run someone
57
+ * deliberately started. A stop aimed at the original dispatch must NOT
58
+ * halt it (naming it directly does).
59
+ *
60
+ * Additive by contract: a record written before this field exists lacks it, and
61
+ * ABSENT READS AS **UNKNOWN** — never as either cause, and never as the
62
+ * stop-scoped one. Inference from the parent's failure class cannot substitute:
63
+ * a manual retry of a transport-failed attempt looks identical (issue #616 F6).
64
+ */
65
+ export const RETRY_CAUSES = ["transport", "manual"] as const;
66
+ export type RetryCause = (typeof RETRY_CAUSES)[number];
67
+
34
68
  export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh";
35
69
 
36
70
  export const THINKING_LEVELS: ThinkingLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh"];
@@ -110,6 +144,19 @@ export const SUBAGENT_SIGNAL_KILLED_MESSAGE = "Subagent killed by external signa
110
144
  // timeout, an abort, or an exit error.
111
145
  export const PROMPT_NEVER_ISSUED_MESSAGE = "Subagent prompt was never issued";
112
146
 
147
+ /**
148
+ * Issue #616 (Q3): the stamp on a transport retry that a dispatch-scoped stop
149
+ * cancelled while it was being set up — armed, but never prompted. Shared by the
150
+ * pre-prompt gate that writes it (session-manager) and the stop tool, which
151
+ * reports the cancel, so the two surfaces cannot describe the same non-event
152
+ * differently.
153
+ *
154
+ * It deliberately carries the "aborted" vocabulary `classifyError` already maps
155
+ * (like SUBAGENT_ABORTED_MESSAGE): a cancelled retry is a stop, never a failure.
156
+ */
157
+ export const CANCELLED_RETRY_MESSAGE =
158
+ "Transport retry stopped before its prompt was issued (cancelled by stop_subagent)";
159
+
113
160
  /**
114
161
  * Classify a subagent result into an error category based on its errorMessage,
115
162
  * stopReason, exitCode, and stderr content. Inspects patterns in priority order.
@@ -201,6 +248,12 @@ export interface TaskTemplate {
201
248
  excludeTools?: string[];
202
249
  noBuiltinTools?: boolean;
203
250
  inheritSystemPrompt?: boolean;
251
+ /**
252
+ * Issue #606 (§3a): the kind a rendered dispatch declares. Validated as an
253
+ * ENUM (an unknown or misspelled value is a render error naming the field
254
+ * and the allowed set — never a silently ignored key).
255
+ */
256
+ dispatch?: DispatchKind;
204
257
  }
205
258
 
206
259
  export interface CircuitBreakerState {
@@ -406,6 +459,12 @@ export interface SubagentRun {
406
459
  dispatchId?: string;
407
460
  resumeOf?: string;
408
461
  attempt?: number;
462
+ /**
463
+ * Issue #616: why THIS attempt exists. Absent on a first dispatch and on every
464
+ * record written before the field existed — absent means UNKNOWN, and unknown
465
+ * is never treated as the stop-scoped cause (`transport`).
466
+ */
467
+ retryCause?: RetryCause;
409
468
  interruptedAt?: string;
410
469
  owner?: ProcessOwner;
411
470
  childMarker?: string;
@@ -493,6 +552,21 @@ export interface UsageStats {
493
552
  turns: number;
494
553
  }
495
554
 
555
+ /**
556
+ * Issue #648: one model-attributed slice of a run's spend, carried in the HOST's
557
+ * `Usage` shape (`input`/`output`/`cacheRead`/`cacheWrite`/`totalTokens`/`cost`)
558
+ * rather than our flattened {@link UsageStats}.
559
+ *
560
+ * The pair `(provider, model)` is the SAME key pi's footer breakdown groups by
561
+ * (`${provider}/${responseModel ?? model}`), so appending one entry per group
562
+ * keeps `/session`'s per-model table truthful when a single run spans models.
563
+ */
564
+ export interface SubagentUsageGroup {
565
+ provider: string;
566
+ model: string;
567
+ usage: Usage;
568
+ }
569
+
496
570
  export interface SubagentResult {
497
571
  messages: Array<Record<string, unknown>>;
498
572
  model?: string;
@@ -852,6 +926,17 @@ export interface BackgroundAgent {
852
926
  // Issue #114: per-unit priority for the drill-in header (`p:critical` etc.).
853
927
  priority?: string;
854
928
  error?: string;
929
+ /**
930
+ * Issue #574: the KIND of this record's terminal state, stamped by the status
931
+ * flip that produced it — a deadline and a user stop are BOTH
932
+ * `status:"stopped"`, so the status alone cannot name the friction. Additive:
933
+ * absent on records written before the field existed, and never invented by
934
+ * the settlement or the boot scan (a record that stopped for an unknown
935
+ * reason reads as "no kind known", not as `aborted`).
936
+ */
937
+ errorCategory?: ErrorCategory;
938
+ /** The terminal stopReason of that same flip (mirrors `SubagentRun.stopReason`). */
939
+ stopReason?: string;
855
940
  result?: SubagentResult;
856
941
  finalOutput?: string;
857
942
  /**
@@ -885,6 +970,10 @@ export interface BackgroundAgent {
885
970
  dispatchId?: string;
886
971
  resumeOf?: string;
887
972
  attempt?: number;
973
+ // Issue #616: why this attempt exists (mirrors `SubagentRun.retryCause`).
974
+ // Persisted so the stop lineage can scope a dispatch-scoped stop to the
975
+ // automatic transport retries; absent means unknown, never "transport".
976
+ retryCause?: RetryCause;
888
977
  interruptedAt?: string;
889
978
  owner?: ProcessOwner;
890
979
  childMarker?: string;
@@ -1310,9 +1399,30 @@ export function isSubagentRunShape(value: unknown): value is SubagentRun {
1310
1399
  if (v.recoveryPosture !== undefined) {
1311
1400
  if (!RECOVERY_MODES.includes(v.recoveryPosture as RecoveryMode)) return false;
1312
1401
  }
1402
+ // Issue #616: a MISTYPED retry cause is rejected like any other bad field; an
1403
+ // ABSENT one is fine (a first dispatch, and every pre-#616 record) and reads
1404
+ // as unknown through `runRetryCause`.
1405
+ if (v.retryCause !== undefined) {
1406
+ if (!(RETRY_CAUSES as readonly unknown[]).includes(v.retryCause)) return false;
1407
+ }
1313
1408
  return true;
1314
1409
  }
1315
1410
 
1411
+ /**
1412
+ * Issue #616: the retry cause recorded for an attempt, or `undefined` when it
1413
+ * cannot be established. ONE reader, so no consumer invents a cause: absent (a
1414
+ * first dispatch, a pre-#616 record) and an unrecognized value both read as
1415
+ * unknown. Unknown is NOT `"transport"` — the stop contract must never widen a
1416
+ * dispatch-scoped stop on a cause it cannot prove.
1417
+ */
1418
+ export function runRetryCause(
1419
+ run: Pick<SubagentRun, "retryCause">,
1420
+ ): RetryCause | undefined {
1421
+ return (RETRY_CAUSES as readonly unknown[]).includes(run.retryCause)
1422
+ ? run.retryCause
1423
+ : undefined;
1424
+ }
1425
+
1316
1426
  /**
1317
1427
  * Option B U3 (D4): the recovery posture recorded for a run. Absent (pre-U3
1318
1428
  * records) or an unrecognized value reads as the default "offer" — the
package/src/unit-run.ts CHANGED
@@ -34,6 +34,7 @@ import { currentProcessOwner } from "./recovery";
34
34
  import { capOutput, stripAnsi, buildCrashResult } from "./sanitize";
35
35
  import { prepareRunScratch } from "./scratch-spawn";
36
36
  import { finalizeRunRecord, pruneSessionRuns } from "./history";
37
+ import { usageGroupsFrom } from "./runner";
37
38
  import { SessionState } from "./state";
38
39
  import { attachWorktreeState } from "./worktree-report";
39
40
 
@@ -196,7 +197,9 @@ export function finalizeUnitRun(
196
197
  const finalOutput = capOutput(stripAnsi(getFinalOutput(result.messages)));
197
198
  finalizeRunRecord(run, result, finalOutput, new Date(run.startedAt).getTime());
198
199
  run.originalParams = { ...run.originalParams, errorCategory: result.errorCategory };
199
- state.persistRun(pi, run);
200
+ // Issue #648 (Q6): the terminal write carries the run's spend — one footer
201
+ // entry per model group — through the required-payload choke point.
202
+ state.persistSettledRun(pi, run, usageGroupsFrom(result.messages));
200
203
  pruneHistoryIfNeeded(state, ctx, log);
201
204
  state.finalizeLiveSubagent(run.id);
202
205
  log.debug("Unit run finalized", { runId: run.id, status: run.status });
@@ -246,7 +249,9 @@ export function finalizeUnitRunCrash(
246
249
  ...run.originalParams,
247
250
  errorCategory: classifyError(crash.details),
248
251
  };
249
- state.persistRun(pi, run);
252
+ // Issue #648: a crash before the first assistant turn has nothing to append;
253
+ // the empty group list is the honest measurement, not a missing call.
254
+ state.persistSettledRun(pi, run, usageGroupsFrom(crash.details.messages));
250
255
  log.error(`${modeLabel} crashed`, {
251
256
  ...logContext,
252
257
  runId: run.id,
package/src/validate.ts CHANGED
@@ -8,7 +8,8 @@
8
8
  */
9
9
 
10
10
  import { THINKING_LEVELS, type ThinkingLevel, type SubagentToolOptions } from './types';
11
- import { DISPATCH_LINE_FORM, JEV_UNAVAILABLE, parseDispatchLine } from './dispatch-line';
11
+ import { parseDispatchHeader, type BriefDeclaration } from './dispatch-header';
12
+ import { validateBriefFile } from './brief';
12
13
  import { isProcessChecksEnabled } from './project-flags';
13
14
 
14
15
  // ── Types ────────────────────────────────────────────────────────────
@@ -35,21 +36,6 @@ export interface ValidateConfig {
35
36
  * (issues #412, #415).
36
37
  */
37
38
  cwd?: string;
38
- /**
39
- * delegate_task's `noJev` param — the STATED bypass for the Jev-line check
40
- * (issue #412, ADR 0018). It downgrades the rejection to a warning that
41
- * carries the reason, so the bypass is visible in the result, never silent.
42
- * It bypasses ONLY the line check: every capability conflict still rejects
43
- * (unlike `force`, which is capability-only).
44
- *
45
- * Typed `unknown` on purpose (issue #419, ADR 0020): the schema DECLARES a
46
- * non-empty string, but the harness validates with `coerce: true` and
47
- * pi-schema's string rule stringifies booleans/numbers before the handler
48
- * runs, so the value that arrives is not guaranteed to be the declared type
49
- * (a direct caller can pass anything at all). `readNoJevReason` is the
50
- * runtime guard, and it is the ONLY place this value may be read.
51
- */
52
- noJev?: unknown;
53
39
  }
54
40
 
55
41
  export interface ValidateResult {
@@ -331,53 +317,54 @@ export function diagnoseFailure(config: DiagnoseConfig): string[] {
331
317
  return suggestions;
332
318
  }
333
319
 
334
- // ── The noJev bypass reason (issue #419, ADR 0020) ───────────────────
320
+ // ── The dispatch header (issue #606, Unit 1) ─────────────────────────
335
321
 
336
322
  /**
337
- * What the harness's coercion turns a non-string reason INTO: `compile(schema,
338
- * { coerce: true })` stringifies booleans and numbers, so `noJev: true`
339
- * reaches the handler as `"true"` — a value that passes `Type.String({
340
- * minLength: 1 })` and is NOT a stated reason. Matching the coerced text is the
341
- * only way to tell it apart from a real one at this seam.
323
+ * The mandatory dispatch header, checked behind the project-local umbrella
324
+ * `processChecks` flag (#415) — no new manifest key. Four rules
325
+ * (spec §3), each refused with the three accepted forms quoted verbatim:
326
+ *
327
+ * 1. no `dispatch:` in the leading block → refused;
328
+ * 2. `dispatch: impl` with no `brief:` → refused;
329
+ * 3. `brief: <slug>` → briefs/<slug>.md in the dispatch
330
+ * cwd's tree must exist and satisfy §2 (src/brief.ts), else refused;
331
+ * 4. `brief: none — <reason>` → valid, WARNED with the reason.
332
+ *
333
+ * Rule 4 is warning-class on every validating path on purpose: the escape is a
334
+ * recorded gap, not a silent one, and the statement "no code from
335
+ * an unagreed plan" stays honest only while an escape is visible (a refusal or
336
+ * a surfaced warning — never a quiet pass).
342
337
  */
343
- const COERCED_PRIMITIVE_RE = /^(true|false|-?\d+(\.\d+)?)$/i;
338
+ function checkDispatchHeader(
339
+ taskText: string,
340
+ cwd: string | undefined,
341
+ errors: string[],
342
+ warnings: string[],
343
+ ): void {
344
+ // Unreachable behind the flag (a check that is ON has a cwd), stated so the
345
+ // seam never depends on that inference.
346
+ if (cwd === undefined) return;
347
+
348
+ const verdict = parseDispatchHeader(taskText);
349
+ if (!verdict.ok) {
350
+ errors.push(verdict.reason);
351
+ return;
352
+ }
344
353
 
345
- /** The three outcomes of reading `noJev`: no bypass, a usable reason, or a refusal. */
346
- type NoJevVerdict =
347
- | { kind: 'absent' }
348
- | { kind: 'reason'; reason: string }
349
- | { kind: 'invalid'; problem: string };
354
+ const brief: BriefDeclaration | undefined = verdict.brief;
355
+ if (brief === undefined) return;
350
356
 
351
- /**
352
- * Reads `noJev` defensively. The schema declares a non-empty string, but that
353
- * is a DECLARATION, not a runtime guarantee: coercion stringifies primitives
354
- * (above), and a direct caller can pass any value. So: never `.trim()` a
355
- * non-string, and treat a coerced primitive (or an empty/whitespace reason) as
356
- * an INVALID bypass rather than a usable one — a boolean must neither bypass
357
- * the check nor crash it.
358
- */
359
- function readNoJevReason(value: unknown): NoJevVerdict {
360
- // Omitted, or an optional `null` (pi-schema drops those during coercion):
361
- // no bypass was stated, so the caller gets the plain missing-line error.
362
- if (value === undefined || value === null) return { kind: 'absent' };
363
- if (typeof value !== 'string') {
364
- const shape = Array.isArray(value) ? 'array' : typeof value;
365
- return { kind: 'invalid', problem: `expected a non-empty reason string, got ${shape}` };
366
- }
367
- const reason = value.trim();
368
- if (reason === '') {
369
- return { kind: 'invalid', problem: 'the reason is empty' };
357
+ if (brief.kind === "none") {
358
+ warnings.push(
359
+ `dispatch: ${verdict.kind} escaped the signed brief — no brief was agreed because ${brief.reason}`,
360
+ );
361
+ return;
370
362
  }
371
- if (COERCED_PRIMITIVE_RE.test(reason)) {
372
- const coerced = /^(true|false)$/i.test(reason) ? 'boolean' : 'number';
373
- return {
374
- kind: 'invalid',
375
- problem:
376
- `\`${reason}\` is a coerced ${coerced}, not a stated reason — the tool-argument validator ` +
377
- `stringifies booleans and numbers before the handler sees them`,
378
- };
363
+
364
+ const checked = validateBriefFile(cwd, brief.slug);
365
+ if (!checked.ok) {
366
+ errors.push(checked.reason);
379
367
  }
380
- return { kind: 'reason', reason };
381
368
  }
382
369
 
383
370
  // ── Main validation ──────────────────────────────────────────────────
@@ -396,37 +383,11 @@ export function validatePreTask(config: ValidateConfig): ValidateResult {
396
383
  return { valid: true, warnings: [], errors: [] };
397
384
  }
398
385
 
399
- // Issue #412 (absorbs #407): the Jev dispatch line, checked BEFORE anything
400
- // spawns. Opt-in per project via the umbrella `processChecks` flag (#415,
401
- // ADR 0019): this is our process, not a product requirement, so a user's
402
- // dispatch is never rejected for a missing line. The flag read is fail-open
403
- // (`src/project-flags.ts`). `noJev` — a stated reason — downgrades the
404
- // rejection to a WARNING that names the reason, so the bypass is surfaced
405
- // rather than silent (ADR 0007's pattern). The reason itself is read through
406
- // a runtime guard, never off the declared type (issue #419, ADR 0020): a
407
- // boolean/number arrives here coercion-stringified, and it must be refused
408
- // as the missing line, not accepted as a bypass.
386
+ // Issue #606 (Unit 1): the mandatory dispatch header, behind the opt-in
387
+ // project-local `processChecks` flag (#415, ADR 0019). The flag read is
388
+ // fail-open (`src/project-flags.ts`), so a user's dispatch is unaffected.
409
389
  if (isProcessChecksEnabled(config.cwd)) {
410
- const verdict = parseDispatchLine(taskText);
411
- if (!verdict.ok) {
412
- const bypass = readNoJevReason(config.noJev);
413
- if (bypass.kind === 'reason') {
414
- warnings.push(
415
- `noJev override: the Jev dispatch line was skipped — ${bypass.reason} (${verdict.reason})`,
416
- );
417
- } else {
418
- if (bypass.kind === 'invalid') {
419
- errors.push(
420
- `invalid noJev: ${bypass.problem}. Pass the reason the line was skipped as a non-empty string (e.g. noJev: "classifier unreachable; maintainer approved"), or append the line.`,
421
- );
422
- }
423
- errors.push(
424
- `missing Jev dispatch line: ${verdict.reason}. ` +
425
- `Classify with the Jev classifier, format the answer with \`jev-check --line '<json>'\` (it prints the line verbatim), and append it to the task as: ${DISPATCH_LINE_FORM}. ` +
426
- `When the classifier did not run, append \`${JEV_UNAVAILABLE}\` instead, or pass noJev: "<reason>".`,
427
- );
428
- }
429
- }
390
+ checkDispatchHeader(taskText, config.cwd, errors, warnings);
430
391
  }
431
392
 
432
393
  // Check tool requirements. A missing capability is warning-class by
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  name: analyze-data
3
3
  description: Data analysis with patterns and recommendations
4
+ dispatch: probe
4
5
  preset: data-analyst
5
6
  thinkingLevel: medium
6
7
  ---
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  name: code-review
3
3
  description: Review code for correctness, security, and style
4
+ dispatch: review
4
5
  preset: code-reviewer
5
6
  thinkingLevel: medium
6
7
  ---
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  name: debug-issue
3
3
  description: Reproduce, isolate, and fix a bug
4
+ dispatch: impl
4
5
  preset: debugger
5
6
  thinkingLevel: medium
6
7
  ---
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  name: implement-feature
3
3
  description: Feature implementation following project conventions
4
+ dispatch: impl
4
5
  preset: dev-agent
5
6
  thinkingLevel: medium
6
7
  ---
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  name: prototype
3
3
  description: Fast throwaway prototype
4
+ dispatch: impl
4
5
  preset: rapid-prototyper
5
6
  thinkingLevel: low
6
7
  ---
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  name: refactor
3
3
  description: Behavior-preserving structural refactor
4
+ dispatch: impl
4
5
  preset: refactorer
5
6
  thinkingLevel: medium
6
7
  ---
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  name: security-audit
3
3
  description: Security audit with severity-ranked findings
4
+ dispatch: review
4
5
  preset: security-auditor
5
6
  thinkingLevel: high
6
7
  ---
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  name: write-docs
3
3
  description: Developer documentation with examples
4
+ dispatch: docs
4
5
  preset: tech-writer
5
6
  thinkingLevel: low
6
7
  ---
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  name: write-tests
3
3
  description: Test generation with edge-case coverage
4
+ dispatch: impl
4
5
  preset: test-engineer
5
6
  thinkingLevel: medium
6
7
  ---
@@ -1,144 +0,0 @@
1
- // Purpose: Parse and validate the Rule 22 dispatch line (the project-local opt-in lives in project-flags.ts).
2
- /**
3
- * The Jev dispatch line — parse side (issue #412, absorbing #407).
4
- *
5
- * A dispatch task carries one classifier line:
6
- *
7
- * jev: medium (0.84) · C2 · worktree y
8
- *
9
- * `.pi/skills/worktree/jev-check.mjs` already PARSES that line for the audit
10
- * (`--log`, `--ledger`) and FORMATS it (`--line`). This module is the
11
- * dispatch-time half: the pre-flight needs the verdict before a spawn, and
12
- * `.pi/` is not shipped (it is dev process tooling), so the extension cannot
13
- * import the script. A second implementation is a second source of truth —
14
- * which is why `dispatch-line.test.ts` shells the real script and requires
15
- * accept/reject agreement on a vector set, and why the two patterns below are
16
- * kept byte-comparable with the script's (`DISPATCH_LINE_PATTERN`,
17
- * `BARE_DISPATCH_LINE_PATTERN`, `GAP_MARKERS`). Change one, change both.
18
- *
19
- * The check is OPT-IN per project, through the umbrella flag in
20
- * `src/project-flags.ts`: the project's manifest carries the `processChecks`
21
- * field (issue #415, ADR 0019). Absent (every user's project) → no check,
22
- * ever: this is our process, not a product requirement. This module owns the
23
- * PARSER only; the manifest read lives in `project-flags.ts` (the
24
- * single-reader ratchet).
25
- */
26
-
27
- /**
28
- * The exact form a dispatch task must carry — quoted verbatim in every
29
- * rejection so the conductor never has to guess. Kept identical to
30
- * `REQUIRED_DISPATCH_FORM` in `jev-check.mjs`.
31
- */
32
- export const DISPATCH_LINE_FORM = "jev: <level> (<0.xx>) · C<1|2|3> · worktree <y|n>";
33
-
34
- /**
35
- * The sanctioned escape when the classifier did not run (SKILL.md: "record
36
- * `jev: unavailable` and proceed — never block a dispatch on the classifier").
37
- * It is a RECORDED gap, not a silent one, and it is accepted by both this
38
- * parser and the script's audit.
39
- */
40
- export const JEV_UNAVAILABLE = "jev: unavailable";
41
-
42
- const LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh"] as const;
43
- const RISKS = ["C1", "C2", "C3"] as const;
44
-
45
- /**
46
- * The line as it appears inside a dispatch task. Mirrors `jev-check.mjs`'s
47
- * `DISPATCH_LINE_PATTERN`: the confidence group is OPTIONAL so a bare level
48
- * can be reported as such (the skip's exact form) instead of a generic
49
- * "invalid". The worktree token is a word because the script's normalizer
50
- * accepts y|yes|true / n|no|false.
51
- */
52
- const DISPATCH_LINE_PATTERN =
53
- /jev:\s*([A-Za-z]+)\s*(?:\(\s*([0-9.]+)\s*\))?\s*·\s*(C\d)\s*·\s*worktree\s*([A-Za-z]+)/i;
54
-
55
- /** A line that at least TRIED to be a dispatch line — tells "bare level" from "missing". */
56
- const BARE_DISPATCH_LINE_PATTERN = /jev:\s*(?:off|minimal|low|medium|high|xhigh)\b/i;
57
-
58
- /**
59
- * Explicit "the classifier did not run" markers. Mirrors `GAP_MARKERS` in
60
- * `jev-check.mjs`, anchored to the `jev:` prefix so prose that merely contains
61
- * the word "unavailable" cannot pass as a classification.
62
- */
63
- const GAP_MARKER_PATTERN = /^jev:\s*(?:unavailable|not classified|n\/a|ritual gap)\b/i;
64
-
65
- export type DispatchLineVerdict =
66
- | { ok: true; line: string }
67
- | { ok: false; reason: string };
68
-
69
- /** Keep a refusal reason to one readable line (mirrors the script's `clip`). */
70
- function clip(text: string, limit = 110): string {
71
- const flat = text.replace(/\s+/g, " ").trim();
72
- return flat.length > limit ? `${flat.slice(0, limit - 1)}…` : flat;
73
- }
74
-
75
- function normalizeWorktree(value: string): "y" | "n" | undefined {
76
- const normalized = value.trim().toLowerCase();
77
- if (normalized === "y" || normalized === "yes" || normalized === "true") return "y";
78
- if (normalized === "n" || normalized === "no" || normalized === "false") return "n";
79
- return undefined;
80
- }
81
-
82
- /**
83
- * Parse a dispatch task for the Rule 22 line. Any line may satisfy it (the
84
- * script audits per line and accepts the first valid one), and the returned
85
- * `line` is the matched canonical text — not the whole raw line, which may
86
- * carry a recorded reason after it.
87
- *
88
- * The reason strings mirror the script's, because the same wording is what
89
- * closes the loop for the conductor: a bare level names the confidence as the
90
- * missing piece, and a missing line names the exact form.
91
- */
92
- export function parseDispatchLine(task: string): DispatchLineVerdict {
93
- const attempts: string[] = [];
94
- for (const raw of String(task).split(/\r?\n/)) {
95
- if (!/jev:/i.test(raw)) continue;
96
- const line = raw.trim();
97
- if (GAP_MARKER_PATTERN.test(line)) return { ok: true, line };
98
-
99
- const match = DISPATCH_LINE_PATTERN.exec(line);
100
- if (match === null) {
101
- attempts.push(
102
- BARE_DISPATCH_LINE_PATTERN.test(line)
103
- ? `bare level without its classifier confidence — ${clip(line)}`
104
- : `unparseable dispatch line — ${clip(line)}`,
105
- );
106
- continue;
107
- }
108
-
109
- const [, levelText, confidenceText, riskText, worktreeText] = match;
110
- // The regex accepts a confidence-less line on purpose: naming the
111
- // missing confidence is what makes the rejection actionable.
112
- if (confidenceText === undefined) {
113
- attempts.push(`bare level without its classifier confidence — ${clip(line)}`);
114
- continue;
115
- }
116
-
117
- const level = levelText.toLowerCase();
118
- if (!(LEVELS as readonly string[]).includes(level)) {
119
- attempts.push(`unknown thinking level "${levelText}" — ${clip(line)}`);
120
- continue;
121
- }
122
- const risk = riskText.toUpperCase();
123
- if (!(RISKS as readonly string[]).includes(risk)) {
124
- attempts.push(`unknown risk class "${riskText}" — ${clip(line)}`);
125
- continue;
126
- }
127
- const confidence = Number(confidenceText);
128
- if (!Number.isFinite(confidence) || confidence < 0 || confidence > 1) {
129
- attempts.push(`confidence out of range "${confidenceText}" — ${clip(line)}`);
130
- continue;
131
- }
132
- const worktree = normalizeWorktree(worktreeText);
133
- if (worktree === undefined) {
134
- attempts.push(`invalid workspace answer "${worktreeText}" — ${clip(line)}`);
135
- continue;
136
- }
137
- return { ok: true, line: match[0] };
138
- }
139
-
140
- if (attempts.length === 0) {
141
- return { ok: false, reason: `missing Jev dispatch line (${DISPATCH_LINE_FORM})` };
142
- }
143
- return { ok: false, reason: attempts[0] };
144
- }