neurastream 0.2.15 → 0.2.17

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/README.md CHANGED
@@ -76,6 +76,9 @@ bun test
76
76
  Green is both exiting 0.
77
77
 
78
78
  ## Scoring details
79
+ ### Trace efficiency
80
+
81
+ `neurastream traces efficiency --since 7d` reports wasted tool calls from recent traces; pass a run id to inspect one run, or add `--json` for machine-readable per-run records (including step indexes and matched rules). Waste rules cover repeated reads and failed commands, failed edits, repeated guard blocks and idle polling. The agent-score board adds `Calls/acc` and `Waste` columns; `score.waste_weight` (default `0`) scales ranking by the wasted-call fraction while leaving the default ranking unchanged.
79
82
 
80
83
  `agent-score accept` records accepted work by commit; `agent-score validate <Agent> --plan <plan.md> --phase <P> --evidence <report.md> --section "<heading prefix>"` records a validation phase (checks/tests ran, report section written, no commits) with proof Main cannot fake by typing: the plan line must be ticked `- [x]`, the cited section body must name a heavy-run label run by that agent (from `paths.heavy_log`), and the phase must not be scored already. The ranking board counts it in `Accepted (diag/val)` as `N (d/v)`.
81
84
 
@@ -96,7 +99,7 @@ A plan parked for the owner has one line: `WAITING on owner: <what>`. That line
96
99
 
97
100
  ## Queue priority
98
101
 
99
- `INDEX.md` order is priority: the top line is rank 1. The queue summary lists plans in that order (`N. <file> [flags] <goal>`). Before a spawn, the guard checks every plan above each plan the brief names: a higher plan that is idle (open, no `WAITING on owner:`, not awaiting merge, still has an unticked phase) and not staffed by a running job must be named in a `Priority skip: <plan> — <why>` line, or the spawn is refused. Staffing is `<queue_state>/staffing.json` (each plan's newest spawn's task names) matched against omp's running job labels. The owner reorders the queue by dragging cards on the phone page.
102
+ `INDEX.md` order is priority: the top line is rank 1. The queue summary lists plans in that order (`N. <file> [flags] <goal>`). Before a spawn, the guard checks every plan above each plan the brief names. A higher plan that is idle — open, no `WAITING on owner:`, not awaiting merge, still has an unticked phase, and not itself waiting on another open indexed plan via a `Waits on: <plan>` line — and not staffed by a running job blocks the spawn unless the brief quotes the owner: `Priority skip: <plan> — owner: "<his words>"`, at least four words that appear in an owner message of the last 24 h (`<queue_state>/owner-messages.jsonl`, recorded from Main's prompts); any other skip line is refused. `Waits on:` lines are Main-only, like `WAITING on owner:`. Staffing is `<queue_state>/staffing.json` (each plan's newest spawn's task names) matched against omp's running job labels. The owner reorders the queue by dragging cards on the phone page.
100
103
 
101
104
  ## Owner page (`neurastream ui`)
102
105
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.15",
3
+ "version": "0.2.17",
4
4
  "description": "Guardrails for running many AI coding agents at once: plan queue, blockers, call budgets, provider caps, scoring, merge-verified close.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -39,10 +39,17 @@ export function parseTs(ts: string): number | null {
39
39
  const [date, time] = s.split("T") as [string, string];
40
40
  const [Y, M, D] = date.split("-").map(Number);
41
41
  const [h, m, sec] = time.split(":").map(Number);
42
+ const suffix = ts.slice(19);
43
+ const zone = suffix.replace(/^\.\d+/, "");
44
+ if (zone === "Z" || /^[+-]\d{2}:\d{2}$/.test(zone)) {
45
+ const utc = Date.UTC(Y!, M! - 1, D, h, m, sec);
46
+ const offset = zone === "Z" ? 0 : (Number(zone.slice(1, 3)) * 60 + Number(zone.slice(4, 6))) * (zone[0] === "+" ? 1 : -1);
47
+ return (utc - offset * 60_000) / 1000;
48
+ }
49
+ if (zone !== "") return null;
42
50
  const local = new Date(Y!, M! - 1, D, h, m, sec);
43
51
  if (Number.isNaN(local.getTime())) return null;
44
- const timezone = new Date(Y!, 0, 1).getTimezoneOffset() * 60;
45
- return local.getTime() / 1000 - timezone;
52
+ return local.getTime() / 1000;
46
53
  }
47
54
 
48
55
  export function asObj(v: unknown): Record<string, unknown> | null {
@@ -6,7 +6,8 @@
6
6
  // notes, unparseable lines) is skipped.
7
7
 
8
8
  import { readFileSync, statSync } from "node:fs";
9
- import { dirname } from "node:path";
9
+ import { dirname, join } from "node:path";
10
+ import type { Config } from "../../core/config.ts";
10
11
  import type { TraceEvent, TraceSource, TraceUsage } from "../../core/adapter.ts";
11
12
  import { asObj, jsonlAt, parseTs, runIdOf } from "./sessions.ts";
12
13
 
@@ -98,6 +99,7 @@ export function parseTraceFile(file: string, runId: string): TraceEvent[] {
98
99
  runId,
99
100
  tool: str(p.name) ?? "?",
100
101
  args: asObj(p.arguments) ?? {},
102
+ callId: str(p.id),
101
103
  model,
102
104
  provider,
103
105
  usage,
@@ -118,6 +120,7 @@ export function parseTraceFile(file: string, runId: string): TraceEvent[] {
118
120
  ts,
119
121
  runId,
120
122
  tool: str(m.toolName) ?? "?",
123
+ callId: str(m.toolCallId),
121
124
  isError: m.isError === true,
122
125
  text: textOf(m.content),
123
126
  usage,
@@ -179,6 +182,11 @@ export function ompTraceSource(root: string): TraceSource {
179
182
  };
180
183
  }
181
184
 
185
+ /** TraceSource for agent-score, over the config's sessions root (the traces CLI's root rule). */
186
+ export function ompScoreTraces(cfg: Config): TraceSource {
187
+ return ompTraceSource(cfg.adapter?.sessions || join(cfg.paths.home, ".omp", "agent", "sessions"));
188
+ }
189
+
182
190
  export interface RelatedTrace {
183
191
  /** The subagent run's trace run id — the agent name. */
184
192
  name: string;
@@ -20,6 +20,7 @@ import { wipSnapshot } from "../core/wip-snapshot.ts";
20
20
  import { runtime } from "./runtime.ts";
21
21
  import { runMainLauncher } from "../adapters/omp/launch.ts";
22
22
  import { defaultCompletedResults, defaultRunSource } from "../adapters/omp/sessions.ts";
23
+ import { ompScoreTraces } from "../adapters/omp/traces.ts";
23
24
 
24
25
  export const PORTED = [
25
26
  "agent-score",
@@ -51,7 +52,7 @@ export async function runPorted(cmd: string, args: string[]): Promise<number> {
51
52
  const rt = runtime();
52
53
  switch (cmd) {
53
54
  case "agent-score":
54
- return agentScore(args, rt.cfg, rt.source);
55
+ return agentScore(args, rt.cfg, rt.source, ompScoreTraces(rt.cfg));
55
56
  case "agent-ledger":
56
57
  return agentLedger(args, rt.cfg, rt.source);
57
58
  case "brief-lint":
@@ -71,6 +71,10 @@ export function helpText(): string {
71
71
  " path reads, network commands to unknown hosts, writes outside",
72
72
  " the allowed roots or on deny paths, pipes into a shell); the",
73
73
  " high ones also open realtime suspicious-action incidents",
74
+ " neurastream traces efficiency <runId|--since 24h> [--json]",
75
+ " count the run's wasted tool calls (same file re-read, failed",
76
+ " command rerun, failed edit, repeated guard block, idle poll):",
77
+ " calls, wasted, waste % and the count per waste rule",
74
78
  " neurastream ui serve the owner's phone page on the tailnet address (ui.enabled, ui.owner_login)",
75
79
  " neurastream ui on --login <tailscale login> [--port N]",
76
80
  " one go: writes ui.enabled/owner_login (and port) into the config,",
package/src/cli/traces.ts CHANGED
@@ -6,6 +6,8 @@
6
6
  // run's trace shows (src/core/trace-actions.ts); the high ones fold into the incident store as
7
7
  // realtime `suspicious-action` incidents (D6). Read-only over the sessions root; --json prints
8
8
  // machine-readable records.
9
+ // `neurastream traces efficiency …` (plan 20261024_0304 P2): count the run's wasted tool calls
10
+ // under the config's waste rules (src/core/trace-efficiency.ts).
9
11
 
10
12
  import { join } from "node:path";
11
13
  import { nowSec } from "../core/clock.ts";
@@ -14,6 +16,8 @@ import { ConfigError, loadConfig, type Config } from "../core/config.ts";
14
16
  import { claimUnbacked } from "../core/incident-detectors.ts";
15
17
  import { claimsFromEvents, type RelatedRun } from "../core/trace-claims.ts";
16
18
  import { actionsRules, suspiciousActions, type ActionsRules, type SuspiciousAction } from "../core/trace-actions.ts";
19
+ import { efficiencyRules, runEfficiency, RULE_ORDER, type EfficiencyRules, type WasteRule } from "../core/trace-efficiency.ts";
20
+ import { pyPercent0 } from "../core/pyfmt.ts";
17
21
  import { ompTraceRuns, ompTraceSource, subagentTraces } from "../adapters/omp/traces.ts";
18
22
 
19
23
  export const TRACES_USAGE = [
@@ -21,6 +25,8 @@ export const TRACES_USAGE = [
21
25
  " neurastream traces claims --since <N m|h|d> [--json]",
22
26
  " neurastream traces actions <runId> [--json]",
23
27
  " neurastream traces actions --since <N m|h|d> [--json]",
28
+ " neurastream traces efficiency <runId> [--json]",
29
+ " neurastream traces efficiency --since <N m|h|d> [--json]",
24
30
  ].join("\n");
25
31
 
26
32
  const SINCE = /^(\d+)(m|h|d)$/;
@@ -59,10 +65,23 @@ export function actionsReport(src: TraceSource, runId: string, rules: ActionsRul
59
65
  return { runId, actions: suspiciousActions(src.events(runId), rules) };
60
66
  }
61
67
 
62
- /** `neurastream traces claims|actions`: one run by id, or every run touched inside a --since window. */
68
+ export interface RunEfficiencyReport {
69
+ runId: string;
70
+ calls: number;
71
+ wasted: number;
72
+ wastePct: number;
73
+ byRule: Record<WasteRule, number>;
74
+ }
75
+
76
+ /** Count one run's wasted tool calls under the config's waste rules. */
77
+ export function efficiencyReport(src: TraceSource, runId: string, rules: EfficiencyRules): RunEfficiencyReport {
78
+ return { runId, ...runEfficiency(src.events(runId), rules) };
79
+ }
80
+
81
+ /** `neurastream traces claims|actions|efficiency`: one run by id, or every run touched inside a --since window. */
63
82
  export async function runTraces(args: string[], opts: { home?: string } = {}): Promise<number> {
64
83
  const sub = args[0];
65
- if (sub !== "claims" && sub !== "actions") {
84
+ if (sub !== "claims" && sub !== "actions" && sub !== "efficiency") {
66
85
  console.error(TRACES_USAGE);
67
86
  return 2;
68
87
  }
@@ -103,15 +122,15 @@ export async function runTraces(args: string[], opts: { home?: string } = {}): P
103
122
  }
104
123
  const runs = ompTraceRuns(root);
105
124
  const src = ompTraceSource(root);
106
- const rules = sub === "actions" ? actionsRules(cfg) : null;
125
+ const rules = sub === "actions" ? actionsRules(cfg) : sub === "efficiency" ? efficiencyRules(cfg) : null;
107
126
  // A Main run's report cites its subagents' results: their traces under the Main session dir
108
127
  // back the pure result-line claims (P5). No time filter — the text match is the guard, and
109
128
  // a sub's file keeps being written while its Main run lives, inside whatever window.
110
129
  const relatedOf = (id: string): RelatedRun[] =>
111
130
  sub === "claims" ? subagentTraces(root, id).map(({ name, events }) => ({ name, events })) : [];
112
- const reports: (RunClaimsReport | RunActionsReport)[] = [];
113
- const reportOf = (id: string): RunClaimsReport | RunActionsReport =>
114
- sub === "claims" ? claimsReport(src, id, relatedOf(id)) : actionsReport(src, id, rules!);
131
+ const reports: (RunClaimsReport | RunActionsReport | RunEfficiencyReport)[] = [];
132
+ const reportOf = (id: string): RunClaimsReport | RunActionsReport | RunEfficiencyReport =>
133
+ sub === "claims" ? claimsReport(src, id, relatedOf(id)) : sub === "actions" ? actionsReport(src, id, rules as ActionsRules) : efficiencyReport(src, id, rules as EfficiencyRules);
115
134
  if (windowSec !== undefined) {
116
135
  const cutoff = nowSec() - windowSec;
117
136
  for (const r of runs) {
@@ -140,6 +159,9 @@ export async function runTraces(args: string[], opts: { home?: string } = {}): P
140
159
  console.log(` ${u.kind}: ${u.summary}`);
141
160
  if (u.evidence) console.log(` evidence: ${u.evidence}`);
142
161
  }
162
+ } else if ("byRule" in r) {
163
+ console.log(`${r.runId}: ${r.calls} calls, ${r.wasted} wasted (${pyPercent0(r.wastePct)})`);
164
+ for (const rule of RULE_ORDER) console.log(` ${rule}: ${r.byRule[rule]}`);
143
165
  } else {
144
166
  if (r.actions.length === 0) {
145
167
  console.log(`${r.runId}: no suspicious actions in the trace`);
@@ -63,6 +63,8 @@ export interface TraceEvent {
63
63
  runId: string;
64
64
  tool?: string;
65
65
  args?: Record<string, unknown>;
66
+ /** Harness call id: the toolCall part id on a call, the toolCallId on its result; pairs them. */
67
+ callId?: string;
66
68
  isError?: boolean;
67
69
  text?: string;
68
70
  model?: string;
@@ -1,12 +1,13 @@
1
1
  import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
  import type { Config } from "./config.ts";
4
- import type { Run, RunSource } from "./adapter.ts";
4
+ import type { Run, RunSource, TraceSource } from "./adapter.ts";
5
5
  import { nowSec, strftime } from "./clock.ts";
6
6
  import { exitText, helpDoc, printText } from "./help.ts";
7
7
  import { formatG, pyFixed, pyPercent0 } from "./pyfmt.ts";
8
8
  import { PyFloat, pyDumps } from "./pyjson.ts";
9
9
  import { gitRaw } from "./proc.ts";
10
+ import { efficiencyRules, runEfficiency } from "./trace-efficiency.ts";
10
11
 
11
12
  function opt(args: string[], name: string): string | undefined {
12
13
  const i = args.indexOf(name);
@@ -52,6 +53,18 @@ export function recordPenalty(cfg: Config, p: { agent: string; kind: string; pla
52
53
  appendFileSync(eventsPath(cfg), `${pyDumps(ev)}\n`);
53
54
  }
54
55
 
56
+ /**
57
+ * Waste counters over one agent's trace, shaped for a score event. Undefined when the agent has
58
+ * no trace or made no tool calls: the event then carries no waste keys at all (byte parity with
59
+ * events written before this existed; a text-only session must not grow keys).
60
+ */
61
+ function wasteOf(traces: TraceSource | undefined, cfg: Config, agent: string): { calls: number; wasted: number; waste_pct: number } | undefined {
62
+ if (!traces) return undefined;
63
+ const eff = runEfficiency(traces.events(agent), efficiencyRules(cfg));
64
+ if (eff.calls === 0) return undefined;
65
+ return { calls: eff.calls, wasted: eff.wasted, waste_pct: eff.wastePct };
66
+ }
67
+
55
68
  function expandCommits(repo: string, spec: string): string[] {
56
69
  const out: string[] = [];
57
70
  for (const raw of spec.split(",")) {
@@ -167,6 +180,9 @@ interface Row {
167
180
  pen: number;
168
181
  diag: number;
169
182
  val: number;
183
+ /** Summed over score events that carry them (0 = no event does). */
184
+ calls: number;
185
+ wasted: number;
170
186
  net: number;
171
187
  total: number;
172
188
  ppd: number | null;
@@ -240,7 +256,7 @@ function table(days: number, cfg: Config, source: RunSource): { rows: Row[]; byA
240
256
  for (const [n, r] of byAgent) agentModel.set(n, r.model);
241
257
  const rows = new Map<string, Row>();
242
258
  const blank = (model: string): Row => ({
243
- model, runs: 0, done: 0, running: 0, cost: 0, steer: 0, hours: 0, pts: 0, acc: 0, first: 0, pen: 0, diag: 0, val: 0,
259
+ model, runs: 0, done: 0, running: 0, cost: 0, steer: 0, hours: 0, pts: 0, acc: 0, first: 0, pen: 0, diag: 0, val: 0, calls: 0, wasted: 0,
244
260
  net: 0, total: 0, ppd: null, pph: null, surv: null, fp: null,
245
261
  });
246
262
  for (const r of byAgent.values()) {
@@ -269,6 +285,8 @@ function table(days: number, cfg: Config, source: RunSource): { rows: Row[]; byA
269
285
  } else if (e.type === "penalty") {
270
286
  m.pen += cfg.score.penalties[String(e.kind)] ?? 0;
271
287
  }
288
+ if (typeof e.calls === "number") m.calls += e.calls;
289
+ if (typeof e.wasted === "number") m.wasted += e.wasted;
272
290
  rows.set(model, m);
273
291
  }
274
292
  const out: Row[] = [];
@@ -283,14 +301,25 @@ function table(days: number, cfg: Config, source: RunSource): { rows: Row[]; byA
283
301
  out.push(m);
284
302
  }
285
303
  out.sort((a, b) => {
286
- const ap = a.ppd !== null ? a.ppd : -1e9;
287
- const bp = b.ppd !== null ? b.ppd : -1e9;
304
+ const ap = rankPpd(a, cfg);
305
+ const bp = rankPpd(b, cfg);
288
306
  if (bp !== ap) return bp - ap;
289
307
  return (b.pph || 0) - (a.pph || 0);
290
308
  });
291
309
  return { rows: out, byAgent };
292
310
  }
293
311
 
312
+ /**
313
+ * ppd as the ranking uses it: with score.waste_weight > 0 a row's wasted-call fraction scales it
314
+ * down, clamped at 0 (weight 0 keeps every ppd — and so the ranking — exactly as before). The
315
+ * displayed pts/$ stays the raw ppd.
316
+ */
317
+ function rankPpd(r: Row, cfg: Config): number {
318
+ if (r.ppd === null) return -1e9;
319
+ if (cfg.score.waste_weight <= 0 || r.calls === 0) return r.ppd;
320
+ return Math.max(0, r.ppd * (1 - cfg.score.waste_weight * (r.wasted / r.calls)));
321
+ }
322
+
294
323
  function fmt(v: number | null, kind: "pct" | "1f"): string {
295
324
  if (v === null) return "-";
296
325
  return kind === "pct" ? pyPercent0(v) : pyFixed(v, 1);
@@ -305,12 +334,12 @@ function board(days: number, cfg: Config, source: RunSource): void {
305
334
  + "(false-claim 5, rule-break 2, escaped-defect 8). Survival = finished runs that ended with a final result. Steering is approximate "
306
335
  + "(Main turns naming the agent).",
307
336
  "",
308
- "| # | Worker model | Runs (live) | Survival | Accepted (diag/val) | First-pass | Net pts | $ worker | $ steering | pts/$ | pts/h |",
309
- "|---|---|---|---|---|---|---|---|---|---|---|",
337
+ "| # | Worker model | Runs (live) | Survival | Accepted (diag/val) | First-pass | Net pts | $ worker | $ steering | pts/$ | pts/h | Calls/acc | Waste |",
338
+ "|---|---|---|---|---|---|---|---|---|---|---|---|---|",
310
339
  ];
311
340
  rows.forEach((r, i) => {
312
341
  lines.push(
313
- `| ${i + 1} | ${r.model} | ${r.runs} (${r.running}) | ${fmt(r.surv, "pct")} | ${r.acc} (${r.diag}/${r.val}) | ${fmt(r.fp, "pct")} | ${r.net} | ${pyFixed(r.cost, 2)} | ${pyFixed(r.steer, 2)} | ${fmt(r.ppd, "1f")} | ${fmt(r.pph, "1f")} |`,
342
+ `| ${i + 1} | ${r.model} | ${r.runs} (${r.running}) | ${fmt(r.surv, "pct")} | ${r.acc} (${r.diag}/${r.val}) | ${fmt(r.fp, "pct")} | ${r.net} | ${pyFixed(r.cost, 2)} | ${pyFixed(r.steer, 2)} | ${fmt(r.ppd, "1f")} | ${fmt(r.pph, "1f")} | ${r.acc > 0 && r.calls > 0 ? pyFixed(r.calls / r.acc, 1) : "-"} | ${r.calls > 0 ? pyPercent0(r.wasted / r.calls) : "-"} |`,
314
343
  );
315
344
  });
316
345
  const text = `${lines.join("\n")}\n`;
@@ -366,7 +395,7 @@ function parseScoreTarget(cmd: string, rest: string[]): { agent: string } | numb
366
395
  return { agent };
367
396
  }
368
397
 
369
- export function agentScore(args: string[], cfg: Config, source: RunSource): number {
398
+ export function agentScore(args: string[], cfg: Config, source: RunSource, traces?: TraceSource): number {
370
399
  mkdirSync(cfg.paths.score_state, { recursive: true });
371
400
  if (args.length < 1 || args[0] === "-h" || args[0] === "--help") {
372
401
  printText(helpDoc("agent-score"));
@@ -393,6 +422,7 @@ export function agentScore(args: string[], cfg: Config, source: RunSource): numb
393
422
  record({
394
423
  type: "accept", agent, plan, phase, weight: w * units, unit_weight: w, units, weight_src: src,
395
424
  repo, branch, commits, rework: rest.includes("--rework"), note: opt(rest, "--note") ?? "",
425
+ ...wasteOf(traces, cfg, agent),
396
426
  }, cfg);
397
427
  return 0;
398
428
  }
@@ -407,6 +437,7 @@ export function agentScore(args: string[], cfg: Config, source: RunSource): numb
407
437
  const weighted = rest.includes("--weight") ? weightFor(rest, plan, phase, cfg, cfg.score.diagnose_weight) : { w: cfg.score.diagnose_weight, src: "default" };
408
438
  record({
409
439
  type: "diagnose", agent, plan, phase, weight: weighted.w, weight_src: weighted.src, evidence: ev, note: opt(rest, "--note") ?? "",
440
+ ...wasteOf(traces, cfg, agent),
410
441
  }, cfg);
411
442
  return 0;
412
443
  }
@@ -432,6 +463,7 @@ export function agentScore(args: string[], cfg: Config, source: RunSource): numb
432
463
  record({
433
464
  type: "validate", agent, plan, phase, weight: w, weight_src: src, evidence: ev, section,
434
465
  labels, rework: rest.includes("--rework"), note: opt(rest, "--note") ?? "",
466
+ ...wasteOf(traces, cfg, agent),
435
467
  }, cfg);
436
468
  return 0;
437
469
  }
@@ -49,6 +49,7 @@ export interface Config {
49
49
  board_days: number;
50
50
  min_dollars: number;
51
51
  min_hours: number;
52
+ waste_weight: number;
52
53
  };
53
54
  ledger: {
54
55
  default_hours: number;
@@ -189,6 +190,15 @@ export interface Config {
189
190
  write_roots: string[];
190
191
  deny_globs: string[];
191
192
  };
193
+ /** Waste counters (src/core/trace-efficiency.ts): what makes a tool call wasted. */
194
+ efficiency: {
195
+ /** The Nth identical read (same args JSON, no write between) counts; >= 2. */
196
+ repeat_read_min: number;
197
+ /** A toolResult text starting with one of these is a guard block. */
198
+ guard_prefixes: string[];
199
+ /** Shell commands matching this poll while nothing else runs. */
200
+ poll_pattern: string;
201
+ };
192
202
  };
193
203
  /** Optional overlay written by adapter install. Absent until an adapter is installed. */
194
204
  adapter?: { name: string; sessions: string; pins: string; extensions: string };
@@ -325,6 +335,9 @@ function applyEnv(cfg: Record<string, unknown>, env: NodeJS.ProcessEnv): void {
325
335
  }
326
336
 
327
337
  function check(cfg: Config): void {
338
+ if (!(Number.isFinite(cfg.score.waste_weight) && cfg.score.waste_weight >= 0 && cfg.score.waste_weight <= 1)) {
339
+ throw new ConfigError("score.waste_weight must be between 0 and 1");
340
+ }
328
341
  if (cfg.ledger.max_slots < 1) throw new ConfigError("ledger.max_slots must be >= 1");
329
342
  if (cfg.guards.sub_warn_calls > cfg.guards.sub_max_calls) {
330
343
  throw new ConfigError("guards.sub_warn_calls must be <= guards.sub_max_calls");
@@ -381,6 +394,17 @@ function check(cfg: Config): void {
381
394
  throw new ConfigError("traces lists must be non-empty strings");
382
395
  }
383
396
  }
397
+ if (!(cfg.traces.efficiency.repeat_read_min >= 2)) {
398
+ throw new ConfigError("traces.efficiency.repeat_read_min must be >= 2");
399
+ }
400
+ if (cfg.traces.efficiency.guard_prefixes.some((p) => typeof p !== "string" || p === "")) {
401
+ throw new ConfigError("traces.efficiency.guard_prefixes must be non-empty strings");
402
+ }
403
+ try {
404
+ new RegExp(cfg.traces.efficiency.poll_pattern);
405
+ } catch {
406
+ throw new ConfigError(`traces.efficiency.poll_pattern: not a valid regex: ${cfg.traces.efficiency.poll_pattern}`);
407
+ }
384
408
  for (const [key, value] of Object.entries(cfg.paths)) {
385
409
  if (key === "work_roots") {
386
410
  if (!Array.isArray(value) || value.some(v => typeof v !== "string")) {
@@ -27,6 +27,7 @@ import { notifyProtectedPaths, notifySecretReadHit } from "./notify.ts";
27
27
  import * as q from "./queue/lib.ts";
28
28
  import type { Plan } from "./queue/lib.ts";
29
29
 
30
+ import { nowSec } from "./clock.ts";
30
31
  const ALLOW: Decision = { allow: true, reason: "" };
31
32
 
32
33
  function deny(reason: string): Decision {
@@ -83,6 +84,43 @@ function staffingFile(): string {
83
84
  return path.join(q.STATE_DIR, "staffing.json");
84
85
  }
85
86
 
87
+ export interface OwnerMessage {
88
+ at: number;
89
+ text: string;
90
+ }
91
+
92
+ function ownerMessagesFile(): string {
93
+ return path.join(q.STATE_DIR, "owner-messages.jsonl");
94
+ }
95
+
96
+ function readOwnerMessages(): OwnerMessage[] {
97
+ try {
98
+ return readFileSync(ownerMessagesFile(), "utf8").split("\n").filter(Boolean)
99
+ .map(line => JSON.parse(line) as OwnerMessage);
100
+ } catch {
101
+ return [];
102
+ }
103
+ }
104
+
105
+ export function ownerSaid(words: string, messages: OwnerMessage[], now: number): boolean {
106
+ const quote = words.toLowerCase().replace(/\s+/g, " ").trim();
107
+ if (quote.split(" ").length < 4) return false;
108
+ return messages.some(m => now - m.at >= 0 && now - m.at <= 86400 && m.text.toLowerCase().replace(/\s+/g, " ").includes(quote));
109
+ }
110
+
111
+ function recordOwnerMessage(text: string, cfg: Config): void {
112
+ if (text.trimStart().startsWith("main-guard:") || text.trimStart().startsWith("<system-notice>") || text.includes("<task-result")) return;
113
+ const file = ownerMessagesFile();
114
+ try {
115
+ mkdirSync(q.STATE_DIR, { recursive: true });
116
+ const messages = readOwnerMessages();
117
+ messages.push({ at: nowSec(), text });
118
+ writeFileSync(file, `${messages.slice(-50).map(m => JSON.stringify(m)).join("\n")}\n`);
119
+ } catch (err) {
120
+ log(cfg.paths.guard_log, `cannot write ${file}: ${err}`);
121
+ }
122
+ }
123
+
86
124
  /** plan → the task names of its newest spawn (staffing.json); read for the staffed check. */
87
125
  export function readStaffing(): Record<string, string[]> {
88
126
  try {
@@ -340,18 +378,23 @@ export interface PriorityOutcome {
340
378
 
341
379
  const SKIP_LINE = /^\s*(?:[-*]\s+)?priority skip:\s*(.+?)\s+[—–-]\s*(.+?)\s*$/gim;
342
380
 
343
- /** One plan is idle when a subagent could start on it right now: open, no owner hold, not awaiting merge, no template errors, and an unticked phase left. */
344
- function priorityIdle(p: Plan): boolean {
381
+ /** One plan is idle when a subagent could start on it right now: open, no owner hold, not awaiting merge, no template errors, an unticked phase left, and not waiting on another open plan of the active index. */
382
+ function priorityIdle(p: Plan, plans: Plan[]): boolean {
383
+ if (p.waitsOn.some(f => plans.some(w => w.file === f && w.status === "open"))) return false;
345
384
  return p.status === "open" && !p.waiting && !q.awaitingMerge(p) && !p.errors.length && unticked(p).length > 0;
346
385
  }
347
386
 
348
387
  /**
349
388
  * Pure priority gate: for the brief's named plans, every higher plan in index order that is idle
350
- * and unstaffed needs a `Priority skip: <path> — <why>` line (non-empty why) in the brief;
351
- * otherwise the spawn is refused. `staffed === undefined` means the caller had no running-job
352
- * info (CLI spawn without it): never refuse. Plans already named by this call never block it.
389
+ * and unstaffed needs proof before a lower plan takes a free slot; otherwise the spawn is refused.
390
+ * Proof is either the higher plan's own `Waits on: <plan>` line for a plan still open in the index
391
+ * (then it is not idle at all) or a `Priority skip: <path> — owner: "<words>"` line whose quoted
392
+ * words (≥ 4, normalised) appear in one of `messages` (the owner's recorded words of the last
393
+ * 24 h; `now` is the current unix seconds). Any other skip line is refused.
394
+ * `staffed === undefined` means the caller had no running-job info (CLI spawn without it): never
395
+ * refuse. Plans already named by this call never block it.
353
396
  */
354
- export function priorityProblem(plans: Plan[], named: string[], staffed: string[] | undefined, brief: string): PriorityOutcome | null {
397
+ export function priorityProblem(plans: Plan[], named: string[], staffed: string[] | undefined, brief: string, messages: OwnerMessage[] = [], now: number = nowSec()): PriorityOutcome | null {
355
398
  if (staffed === undefined) return { unknown: true };
356
399
  const namedRanks = named.map(f => plans.findIndex(p => p.file === f)).filter(n => n >= 0);
357
400
  if (!namedRanks.length) return null;
@@ -365,20 +408,21 @@ export function priorityProblem(plans: Plan[], named: string[], staffed: string[
365
408
  const skips: PrioritySkip[] = [];
366
409
  for (let i = 0; i < higher.length; i++) {
367
410
  const p = higher[i]!;
368
- if (!priorityIdle(p) || staffed.includes(p.file)) continue;
411
+ if (!priorityIdle(p, plans) || staffed.includes(p.file)) continue;
369
412
  const why = skipLines[p.file];
370
- if (why) {
413
+ const quote = why?.match(/^owner:\s*"(.+)"\s*$/);
414
+ if (why && quote && ownerSaid(quote[1]!, messages, now)) {
371
415
  skips.push({ plan: p.file, why });
372
416
  continue;
373
417
  }
374
- return { problem: `higher plan ${p.file} (rank ${i + 1}) is idle; spawn on it first or add "Priority skip: ${p.file} — <why>"` };
418
+ return { problem: `higher plan ${p.file} (rank ${i + 1}) is idle; a skip needs the owner's words (Priority skip: ${p.file} — owner: "<quote>") or a "Waits on: ${p.file}" line in that plan` };
375
419
  }
376
420
  return skips.length ? { skips } : null;
377
421
  }
378
422
 
379
- /** Load staffing, run the pure priority gate and log its outcome; the refusal comes back with the caller's label, or null. */
423
+ /** Load staffing and the owner's recorded words, run the pure priority gate and log its outcome; the refusal comes back with the caller's label, or null. */
380
424
  function priorityGate(named: string[], runningJobs: string[] | undefined, brief: string, cfg: Config, label: string): string | null {
381
- const outcome = priorityProblem(q.activePlans(), named, runningJobs === undefined ? undefined : staffedPlans(readStaffing(), runningJobs), brief);
425
+ const outcome = priorityProblem(q.activePlans(), named, runningJobs === undefined ? undefined : staffedPlans(readStaffing(), runningJobs), brief, readOwnerMessages(), nowSec());
382
426
  if (outcome?.unknown) log(cfg.paths.guard_log, "PRIORITY unknown jobs");
383
427
  for (const s of outcome?.skips ?? []) log(cfg.paths.guard_log, `PRIORITY skip ${s.plan}: ${s.why}`);
384
428
  return outcome?.problem ? `${label}: ${outcome.problem}` : null;
@@ -834,6 +878,7 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
834
878
  if (e.agent !== "main") return ALLOW;
835
879
  const continuation = e.inject.trimStart().startsWith("main-guard:");
836
880
  if (!continuation) writeWindow({ used: [], windowStart: 0 });
881
+ recordOwnerMessage(e.inject, cfg);
837
882
  let summary: string;
838
883
  try {
839
884
  summary = q.queueSummary();
@@ -852,8 +897,8 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
852
897
  };
853
898
  }
854
899
 
855
- // Lines only Main may write: the status, owner parking, owner cancellation, cancelled-list clearance.
856
- const MAIN_ONLY_LINE = /^\s*(?:[-*]\s+)?(Status:|WAITING on owner:|Cancelled by owner:|False positive:)/;
900
+ // Lines only Main may write: the status, owner parking, plan waits, owner cancellation, cancelled-list clearance.
901
+ const MAIN_ONLY_LINE = /^\s*(?:[-*]\s+)?(Status:|WAITING on owner:|Waits on:|Cancelled by owner:|False positive:)/;
857
902
 
858
903
  function mainOnlyLines(text: string): string {
859
904
  return text.split("\n").filter(l => MAIN_ONLY_LINE.test(l)).join("\n");
@@ -872,7 +917,7 @@ export function checkPlanEdit(e: PlanEditEvent, cfg: Config): Decision {
872
917
  log(cfg.paths.plan_guard_log, `RESTORE ${e.path}`);
873
918
  return {
874
919
  allow: false,
875
- reason: `plan-guard: you changed ${e.path} outside your progress entries (only "## Progress" entries are yours; the "Status:", "WAITING on owner:", "Cancelled by owner:" and "False positive:" lines are Main's, it marks a plan complete after reviewing your work). The file was restored.`,
920
+ reason: `plan-guard: you changed ${e.path} outside your progress entries (only "## Progress" entries are yours; the "Status:", "WAITING on owner:", "Waits on:", "Cancelled by owner:" and "False positive:" lines are Main's, it marks a plan complete after reviewing your work). The file was restored.`,
876
921
  restore: { path: e.path, text: e.before },
877
922
  };
878
923
  }
@@ -49,6 +49,7 @@ export interface Plan {
49
49
  appliesTo: string[];
50
50
  waiting: boolean;
51
51
  waitingLine: string | null;
52
+ waitsOn: string[];
52
53
  priorityId: string | null;
53
54
  /** First level-1 "# " heading in the plan, else the file basename. */
54
55
  title: string;
@@ -112,9 +113,9 @@ export function progressBody(text: string): string {
112
113
  export type ProgressTrim = { body: string; moved: string; count: number };
113
114
 
114
115
  // Entries start at a top-level "- " line. The pointer line that a trim leaves behind is not an entry,
115
- // and Main-only lines (status, owner parking/cancel, cancelled-list clearance) never move to the archive.
116
+ // and Main-only lines (status, owner parking, plan waits, owner cancel, cancelled-list clearance) never move to the archive.
116
117
  const POINTER_PREFIX = "- Older Progress entries:";
117
- const MAIN_ONLY_LINE = /^\s*(?:[-*]\s+)?(Status:|WAITING on owner:|Cancelled by owner:|False positive:)/;
118
+ const MAIN_ONLY_LINE = /^\s*(?:[-*]\s+)?(Status:|WAITING on owner:|Waits on:|Cancelled by owner:|False positive:)/;
118
119
 
119
120
  /** Keep the first `keep` entries (the file lists them newest first) and move the rest. Pure. */
120
121
  export function trimProgressBody(body: string, keep: number, pointer: string): ProgressTrim | undefined {
@@ -183,7 +184,7 @@ function headerField(text: string, name: string): string | null {
183
184
  }
184
185
 
185
186
  export function parsePlan(repo: string, file: string, text: string | null, blockersDir = blockersDirPath()): Plan {
186
- const empty = { repo, file, text: "", status: null, blockers: [], doneCheck: null, worktree: null, branch: null, appliesTo: [], waiting: false, waitingLine: null, priorityId: null, title: path.basename(file), goal: [] };
187
+ const empty = { repo, file, text: "", status: null, blockers: [], doneCheck: null, worktree: null, branch: null, appliesTo: [], waiting: false, waitingLine: null, waitsOn: [], priorityId: null, title: path.basename(file), goal: [] };
187
188
  if (text === null) return { ...empty, errors: ["plan file listed in the index does not exist"] };
188
189
  const errors: string[] = [];
189
190
  const secs = sections(text);
@@ -228,6 +229,7 @@ export function parsePlan(repo: string, file: string, text: string | null, block
228
229
  appliesTo: items(secs.get("applies to") ?? "").map(p => path.resolve(repo, expandHome(p.replace(/`/g, "")))),
229
230
  waiting: /^WAITING on owner:/m.test(text),
230
231
  waitingLine: text.match(/^WAITING on owner:[ \t]*(.*)$/m)?.[1] ?? null,
232
+ waitsOn: [...text.matchAll(/^[ \t]*(?:[-*][ \t]+)?Waits on:[ \t]*(.+)$/gm)].map(m => m[1]!.trim()),
231
233
  priorityId: text.match(/^PRIORITY-ID:\s*`?([A-Z]{2}[0-9]{2})`?/m)?.[1] ?? null,
232
234
  title: text.match(/^# (.+)$/m)?.[1]?.trim() || path.basename(file),
233
235
  goal: items(secs.get("goal") ?? "").slice(0, 6),
@@ -0,0 +1,148 @@
1
+ // Waste counters (plan 20261024_0304 P1): score how much of a run's tool activity was wasted —
2
+ // the same file read again, a failed command rerun unchanged, an edit that errored, the same
3
+ // guard refusal hit twice, idle polling while waiting. Every input comes from config (the guard
4
+ // tool lists and the `traces.efficiency` values), so owners tune the rules without touching
5
+ // code. One call counts as wasted at most once: the first rule in the order below wins.
6
+
7
+ import type { TraceEvent } from "./adapter.ts";
8
+ import type { Config } from "./config.ts";
9
+
10
+ export type WasteRule = "repeat-read" | "repeat-fail" | "failed-edit" | "guard-repeat" | "poll";
11
+
12
+ /** First match wins; the array order is the rule order. */
13
+ export const RULE_ORDER: WasteRule[] = ["repeat-read", "repeat-fail", "failed-edit", "guard-repeat", "poll"];
14
+
15
+ export interface EfficiencyRules {
16
+ read_tools: string[];
17
+ shell_tools: string[];
18
+ write_tools: string[];
19
+ /** The Nth identical read (same args JSON, no write between) counts; 2 = the first re-read. */
20
+ repeat_read_min: number;
21
+ /** A toolResult text starting with one of these is a guard block. */
22
+ guard_prefixes: string[];
23
+ /** Shell commands matching this poll while nothing else runs. */
24
+ poll_pattern: string;
25
+ }
26
+
27
+ export interface WasteStep {
28
+ /** Ordinal of the wasted call among the run's toolCall events (0-based). */
29
+ index: number;
30
+ rule: WasteRule;
31
+ }
32
+
33
+ export interface Efficiency {
34
+ /** Number of toolCall events in the run. */
35
+ calls: number;
36
+ wasted: number;
37
+ /** wasted / calls; 0 when calls is 0. */
38
+ wastePct: number;
39
+ byRule: Record<WasteRule, number>;
40
+ steps: WasteStep[];
41
+ }
42
+
43
+ /** Maps config onto the rule set: the guard tool lists plus `traces.efficiency`. */
44
+ export function efficiencyRules(cfg: Config): EfficiencyRules {
45
+ return {
46
+ read_tools: cfg.guards.read_tools,
47
+ shell_tools: cfg.guards.shell_tools,
48
+ write_tools: cfg.guards.write_tools,
49
+ repeat_read_min: cfg.traces.efficiency.repeat_read_min,
50
+ guard_prefixes: cfg.traces.efficiency.guard_prefixes,
51
+ poll_pattern: cfg.traces.efficiency.poll_pattern,
52
+ };
53
+ }
54
+
55
+ function emptyByRule(): Record<WasteRule, number> {
56
+ return { "repeat-read": 0, "repeat-fail": 0, "failed-edit": 0, "guard-repeat": 0, poll: 0 };
57
+ }
58
+
59
+ /**
60
+ * Waste counters over one run's trace events. Calls are the toolCall events in event order; a
61
+ * toolResult pairs to its call by callId (first result wins), and rules that look at outcomes
62
+ * (repeat-fail, failed-edit, guard blocks) read the paired result. A write-tool call breaks the
63
+ * read/fail chains — the agent changed something, so a rerun after it is not a blind repeat.
64
+ */
65
+ export function runEfficiency(events: TraceEvent[], rules: EfficiencyRules): Efficiency {
66
+ const calls = events.filter((e) => e.kind === "toolCall");
67
+ const resultByCallId = new Map<string, TraceEvent>();
68
+ for (const e of events) {
69
+ if (e.kind !== "toolResult" || e.callId === undefined) continue;
70
+ if (!resultByCallId.has(e.callId)) resultByCallId.set(e.callId, e);
71
+ }
72
+ const resultOf = (c: TraceEvent): TraceEvent | undefined => (c.callId === undefined ? undefined : resultByCallId.get(c.callId));
73
+
74
+ const pollRe = new RegExp(rules.poll_pattern);
75
+ const byRule = emptyByRule();
76
+ const steps: WasteStep[] = [];
77
+
78
+ const readCounts = new Map<string, number>(); // args JSON -> occurrences since the last write
79
+ const failedCmds = new Set<string>(); // commands with an earlier failed result since the last write
80
+ const guardFirstLines = new Set<string>();
81
+ let pollRun = 0; // consecutive poll calls so far
82
+
83
+ calls.forEach((c, index) => {
84
+ const tool = c.tool ?? "?";
85
+ const isRead = rules.read_tools.includes(tool);
86
+ const isShell = rules.shell_tools.includes(tool);
87
+ const isWrite = rules.write_tools.includes(tool);
88
+ const command = isShell && typeof c.args?.command === "string" ? c.args.command : "";
89
+ const res = resultOf(c);
90
+ if (isWrite) {
91
+ readCounts.clear();
92
+ failedCmds.clear();
93
+ }
94
+ const isPoll = isShell && command !== "" && pollRe.test(command);
95
+ if (!isPoll) pollRun = 0;
96
+
97
+ // Every rule sees every call and keeps its own state up to date even when another rule
98
+ // already counted this one (a later repeat must not be undercounted); only the counted
99
+ // rule is first-wins.
100
+ let repeatRead = false;
101
+ if (isRead) {
102
+ const argsJson = JSON.stringify(c.args ?? {});
103
+ const n = (readCounts.get(argsJson) ?? 0) + 1;
104
+ readCounts.set(argsJson, n);
105
+ repeatRead = n >= rules.repeat_read_min;
106
+ }
107
+ let repeatFail = false;
108
+ if (isShell && command !== "") {
109
+ repeatFail = failedCmds.has(command);
110
+ if (res?.isError === true) failedCmds.add(command);
111
+ }
112
+ const failedEdit = isWrite && res?.isError === true;
113
+ let guardRepeat = false;
114
+ if (res !== undefined) {
115
+ const text = res.text ?? "";
116
+ const prefix = rules.guard_prefixes.find((p) => text.startsWith(p));
117
+ if (prefix !== undefined) {
118
+ const firstLine = text.split("\n", 1)[0] ?? text;
119
+ guardRepeat = guardFirstLines.has(firstLine);
120
+ guardFirstLines.add(firstLine);
121
+ }
122
+ }
123
+ let pollHit = false;
124
+ if (isPoll) {
125
+ pollRun += 1;
126
+ pollHit = pollRun >= 2;
127
+ }
128
+
129
+ const hit: WasteRule | null = repeatRead
130
+ ? "repeat-read"
131
+ : repeatFail
132
+ ? "repeat-fail"
133
+ : failedEdit
134
+ ? "failed-edit"
135
+ : guardRepeat
136
+ ? "guard-repeat"
137
+ : pollHit
138
+ ? "poll"
139
+ : null;
140
+ if (hit !== null) {
141
+ byRule[hit] += 1;
142
+ steps.push({ index, rule: hit });
143
+ }
144
+ });
145
+
146
+ const wasted = steps.length;
147
+ return { calls: calls.length, wasted, wastePct: calls.length > 0 ? wasted / calls.length : 0, byRule, steps };
148
+ }
@@ -4,7 +4,7 @@ You are Main, the orchestrator. Main plans, delegates, reviews and lands; implem
4
4
 
5
5
  ## Plans
6
6
  - When the owner asks for work in a repo, write the plan to `<main checkout>/docs/plans/` and list its absolute path in the one index `{{AGENT_DIR}}/INDEX.md` (one plan file per line, never a repo directory). One plan = one worktree: the plan's Worktree line names a worktree no other open plan names.
7
- - INDEX.md order is priority: top first; a spawn skipping an idle higher plan needs `Priority skip: <plan> — <why>`.
7
+ - INDEX.md order is priority: free agents go to the top plans first. A lower plan goes first only when the higher one says `Waits on: <plan>`, is WAITING on owner, or the brief quotes the owner: `Priority skip: <plan> — owner: "<his words>"`.
8
8
  - Entering a repo: read its AGENTS.md first.
9
9
  - Main writes every plan in `<repo>/docs/plans/`, shaped like `{{AGENT_DIR}}/queue/TEMPLATE.md`. Do the research yourself; never base a plan on another agent's findings.
10
10
  - Phase 0 of every plan: blocker scripts that stop the implementer from going against the plan. They must exist before any spawn.
@@ -33,6 +33,7 @@ score:
33
33
  gate_days: 7
34
34
  board_days: 7
35
35
  min_dollars: 0.01
36
+ waste_weight: 0 # rank multiplier for wasted-call rate (0 disables)
36
37
  min_hours: 0.05
37
38
 
38
39
  ledger:
@@ -229,3 +230,9 @@ traces:
229
230
  - "~/.omp/**"
230
231
  - "~/.local/bin/**"
231
232
  - "~/.local/state/**"
233
+ efficiency: # wasted-call rules (src/core/trace-efficiency.ts); the board ranks on them via score.waste_weight
234
+ repeat_read_min: 3 # the Nth identical read (same args, no write between) counts; 2 = the first re-read
235
+ guard_prefixes: # a toolResult text starting with one of these is a guard block
236
+ - "plan-guard:"
237
+ - "main-guard:"
238
+ poll_pattern: '^\s*(sleep\s+\d|ps\b|pgrep\b)' # shell commands that poll while nothing else runs