brl-subagent 2.9.2 → 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.
package/src/state.ts CHANGED
@@ -29,6 +29,7 @@ import {
29
29
  CIRCUIT_DEGRADED_THINKING,
30
30
  type SubagentState,
31
31
  type SubagentRun,
32
+ type SubagentUsageGroup,
32
33
  type LiveSubagent,
33
34
  type ThinkingLevel,
34
35
  type ApprovalMode,
@@ -39,7 +40,7 @@ import {
39
40
  type ModeContext,
40
41
  } from "./types";
41
42
  import { cleanupRuns } from "./history";
42
- import { persistRunRecord, type InflightRunKind } from "./run-registry";
43
+ import { persistRunRecord, persistSettledRunRecord, type InflightRunKind } from "./run-registry";
43
44
 
44
45
  // ---------------------------------------------------------------------------
45
46
  // Live-monitor staleness sweep (issue #52 part 2)
@@ -334,6 +335,20 @@ export class SessionState {
334
335
  persistRunRecord(pi, run, kind);
335
336
  }
336
337
 
338
+ /**
339
+ * Issue #648 (Q6): the TERMINAL subagent write. `usageGroups` is REQUIRED —
340
+ * the run's spend rides on the same choke point as its record, so a future
341
+ * settle site that forgets to pass it is a type error, not a silent
342
+ * undercount in the footer. Aggregate/structural writes keep `persistRun`.
343
+ */
344
+ persistSettledRun(
345
+ pi: ExtensionAPI,
346
+ run: SubagentRun,
347
+ usageGroups: readonly SubagentUsageGroup[],
348
+ ): void {
349
+ persistSettledRunRecord(pi, run, usageGroups);
350
+ }
351
+
337
352
  // -------------------------------------------------------------------
338
353
  // F5/F9: Safe state restoration from session entries
339
354
  // -------------------------------------------------------------------
@@ -84,7 +84,7 @@ interface TerminalNotifierDeps {
84
84
  spawnBackgroundRun: (
85
85
  pi: ExtensionAPI,
86
86
  ctx: ExtensionContext,
87
- params: (DelegateTaskParams & { noJev?: string }) | ReturnType<typeof resolveRetryParams>,
87
+ params: DelegateTaskParams | ReturnType<typeof resolveRetryParams>,
88
88
  singleTask: string,
89
89
  retrySourceRun?: SubagentRun,
90
90
  attemptContext?: string,
package/src/types.ts CHANGED
@@ -9,6 +9,7 @@ import type { DispatchKind } from "./dispatch-header";
9
9
  import type { delegateTaskParamsSchema } from "./schema";
10
10
  import type { TranscriptMessage } from "./transcript-tail";
11
11
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
12
+ import type { Usage } from "@earendil-works/pi-ai";
12
13
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
13
14
  import type { Static } from "typebox";
14
15
 
@@ -551,6 +552,21 @@ export interface UsageStats {
551
552
  turns: number;
552
553
  }
553
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
+
554
570
  export interface SubagentResult {
555
571
  messages: Array<Record<string, unknown>>;
556
572
  model?: string;
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,6 @@
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';
12
11
  import { parseDispatchHeader, type BriefDeclaration } from './dispatch-header';
13
12
  import { validateBriefFile } from './brief';
14
13
  import { isProcessChecksEnabled } from './project-flags';
@@ -37,21 +36,6 @@ export interface ValidateConfig {
37
36
  * (issues #412, #415).
38
37
  */
39
38
  cwd?: string;
40
- /**
41
- * delegate_task's `noJev` param — the STATED bypass for the Jev-line check
42
- * (issue #412, ADR 0018). It downgrades the rejection to a warning that
43
- * carries the reason, so the bypass is visible in the result, never silent.
44
- * It bypasses ONLY the line check: every capability conflict still rejects
45
- * (unlike `force`, which is capability-only).
46
- *
47
- * Typed `unknown` on purpose (issue #419, ADR 0020): the schema DECLARES a
48
- * non-empty string, but the harness validates with `coerce: true` and
49
- * pi-schema's string rule stringifies booleans/numbers before the handler
50
- * runs, so the value that arrives is not guaranteed to be the declared type
51
- * (a direct caller can pass anything at all). `readNoJevReason` is the
52
- * runtime guard, and it is the ONLY place this value may be read.
53
- */
54
- noJev?: unknown;
55
39
  }
56
40
 
57
41
  export interface ValidateResult {
@@ -333,60 +317,11 @@ export function diagnoseFailure(config: DiagnoseConfig): string[] {
333
317
  return suggestions;
334
318
  }
335
319
 
336
- // ── The noJev bypass reason (issue #419, ADR 0020) ───────────────────
337
-
338
- /**
339
- * What the harness's coercion turns a non-string reason INTO: `compile(schema,
340
- * { coerce: true })` stringifies booleans and numbers, so `noJev: true`
341
- * reaches the handler as `"true"` — a value that passes `Type.String({
342
- * minLength: 1 })` and is NOT a stated reason. Matching the coerced text is the
343
- * only way to tell it apart from a real one at this seam.
344
- */
345
- const COERCED_PRIMITIVE_RE = /^(true|false|-?\d+(\.\d+)?)$/i;
346
-
347
- /** The three outcomes of reading `noJev`: no bypass, a usable reason, or a refusal. */
348
- type NoJevVerdict =
349
- | { kind: 'absent' }
350
- | { kind: 'reason'; reason: string }
351
- | { kind: 'invalid'; problem: string };
352
-
353
- /**
354
- * Reads `noJev` defensively. The schema declares a non-empty string, but that
355
- * is a DECLARATION, not a runtime guarantee: coercion stringifies primitives
356
- * (above), and a direct caller can pass any value. So: never `.trim()` a
357
- * non-string, and treat a coerced primitive (or an empty/whitespace reason) as
358
- * an INVALID bypass rather than a usable one — a boolean must neither bypass
359
- * the check nor crash it.
360
- */
361
- function readNoJevReason(value: unknown): NoJevVerdict {
362
- // Omitted, or an optional `null` (pi-schema drops those during coercion):
363
- // no bypass was stated, so the caller gets the plain missing-line error.
364
- if (value === undefined || value === null) return { kind: 'absent' };
365
- if (typeof value !== 'string') {
366
- const shape = Array.isArray(value) ? 'array' : typeof value;
367
- return { kind: 'invalid', problem: `expected a non-empty reason string, got ${shape}` };
368
- }
369
- const reason = value.trim();
370
- if (reason === '') {
371
- return { kind: 'invalid', problem: 'the reason is empty' };
372
- }
373
- if (COERCED_PRIMITIVE_RE.test(reason)) {
374
- const coerced = /^(true|false)$/i.test(reason) ? 'boolean' : 'number';
375
- return {
376
- kind: 'invalid',
377
- problem:
378
- `\`${reason}\` is a coerced ${coerced}, not a stated reason — the tool-argument validator ` +
379
- `stringifies booleans and numbers before the handler sees them`,
380
- };
381
- }
382
- return { kind: 'reason', reason };
383
- }
384
-
385
320
  // ── The dispatch header (issue #606, Unit 1) ─────────────────────────
386
321
 
387
322
  /**
388
- * The mandatory dispatch header, checked at the same seam as the Jev line and
389
- * behind the SAME umbrella flag (#415) — no new manifest key. Four rules
323
+ * The mandatory dispatch header, checked behind the project-local umbrella
324
+ * `processChecks` flag (#415) — no new manifest key. Four rules
390
325
  * (spec §3), each refused with the three accepted forms quoted verbatim:
391
326
  *
392
327
  * 1. no `dispatch:` in the leading block → refused;
@@ -396,7 +331,7 @@ function readNoJevReason(value: unknown): NoJevVerdict {
396
331
  * 4. `brief: none — <reason>` → valid, WARNED with the reason.
397
332
  *
398
333
  * Rule 4 is warning-class on every validating path on purpose: the escape is a
399
- * recorded gap (like noJev), not a silent one, and the statement "no code from
334
+ * recorded gap, not a silent one, and the statement "no code from
400
335
  * an unagreed plan" stays honest only while an escape is visible (a refusal or
401
336
  * a surfaced warning — never a quiet pass).
402
337
  */
@@ -448,41 +383,10 @@ export function validatePreTask(config: ValidateConfig): ValidateResult {
448
383
  return { valid: true, warnings: [], errors: [] };
449
384
  }
450
385
 
451
- // Issue #412 (absorbs #407): the Jev dispatch line, checked BEFORE anything
452
- // spawns. Opt-in per project via the umbrella `processChecks` flag (#415,
453
- // ADR 0019): this is our process, not a product requirement, so a user's
454
- // dispatch is never rejected for a missing line. The flag read is fail-open
455
- // (`src/project-flags.ts`). `noJev` — a stated reason — downgrades the
456
- // rejection to a WARNING that names the reason, so the bypass is surfaced
457
- // rather than silent (ADR 0007's pattern). The reason itself is read through
458
- // a runtime guard, never off the declared type (issue #419, ADR 0020): a
459
- // boolean/number arrives here coercion-stringified, and it must be refused
460
- // 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.
461
389
  if (isProcessChecksEnabled(config.cwd)) {
462
- const verdict = parseDispatchLine(taskText);
463
- if (!verdict.ok) {
464
- const bypass = readNoJevReason(config.noJev);
465
- if (bypass.kind === 'reason') {
466
- warnings.push(
467
- `noJev override: the Jev dispatch line was skipped — ${bypass.reason} (${verdict.reason})`,
468
- );
469
- } else {
470
- if (bypass.kind === 'invalid') {
471
- errors.push(
472
- `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.`,
473
- );
474
- }
475
- errors.push(
476
- `missing Jev dispatch line: ${verdict.reason}. ` +
477
- `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}. ` +
478
- `When the classifier did not run, append \`${JEV_UNAVAILABLE}\` instead, or pass noJev: "<reason>".`,
479
- );
480
- }
481
- }
482
-
483
- // Issue #606 (Unit 1): the dispatch header, behind the SAME flag. It runs
484
- // after the Jev check so a task missing both names both — a conductor
485
- // should not have to re-dispatch twice to learn two independent rules.
486
390
  checkDispatchHeader(taskText, config.cwd, errors, warnings);
487
391
  }
488
392
 
@@ -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
- }