neurastream 0.2.11 → 0.2.13

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.
@@ -0,0 +1,115 @@
1
+ // `neurastream traces claims …` (plan 20261024_0300 P3): check what a run's final report CLAIMS
2
+ // against what the same run's tool activity shows. Claims come from the run's last assistant
3
+ // message; a claim with no backing toolResult line, git output, heavy-run call or edit/write is
4
+ // reported as a claim-unbacked finding (src/core/incident-detectors.ts D5). Read-only over the
5
+ // sessions root; --json prints machine-readable records.
6
+
7
+ import { join } from "node:path";
8
+ import { nowSec } from "../core/clock.ts";
9
+ import type { TraceSource } from "../core/adapter.ts";
10
+ import { ConfigError, loadConfig, type Config } from "../core/config.ts";
11
+ import { claimUnbacked } from "../core/incident-detectors.ts";
12
+ import { claimsFromEvents } from "../core/trace-claims.ts";
13
+ import { ompTraceRuns, ompTraceSource } from "../adapters/omp/traces.ts";
14
+
15
+ export const TRACES_USAGE = [
16
+ "usage: neurastream traces claims <runId> [--json]",
17
+ " neurastream traces claims --since <N m|h|d> [--json]",
18
+ ].join("\n");
19
+
20
+ const SINCE = /^(\d+)(m|h|d)$/;
21
+
22
+ export interface RunClaimsReport {
23
+ runId: string;
24
+ claims: number;
25
+ backed: number;
26
+ unbacked: { kind: string; summary: string; evidence?: string }[];
27
+ }
28
+
29
+ /** Verify one run: claims from its final report, findings for the ones no tool output backs. */
30
+ export function claimsReport(src: TraceSource, runId: string): RunClaimsReport {
31
+ const events = src.events(runId);
32
+ const claims = claimsFromEvents(events);
33
+ const findings = claimUnbacked(claims, events);
34
+ return {
35
+ runId,
36
+ claims: claims.length,
37
+ backed: claims.length - findings.length,
38
+ unbacked: findings.map((f) => ({ kind: f.kind, summary: f.summary, evidence: f.evidence })),
39
+ };
40
+ }
41
+
42
+ /** `neurastream traces claims`: one run by id, or every run touched inside a --since window. */
43
+ export async function runTraces(args: string[]): Promise<number> {
44
+ if (args[0] !== "claims") {
45
+ console.error(TRACES_USAGE);
46
+ return 2;
47
+ }
48
+ let cfg: Config;
49
+ try {
50
+ cfg = loadConfig();
51
+ } catch (err) {
52
+ console.error(err instanceof ConfigError ? err.message : String(err));
53
+ return 1;
54
+ }
55
+ const root = cfg.adapter?.sessions || join(cfg.paths.home, ".omp", "agent", "sessions");
56
+ const rest = args.slice(1);
57
+ let runId: string | undefined;
58
+ let windowSec: number | undefined;
59
+ let json = false;
60
+ for (let i = 0; i < rest.length; i++) {
61
+ const a = rest[i]!;
62
+ if (a === "--json") {
63
+ json = true;
64
+ } else if (a === "--since") {
65
+ const m = SINCE.exec(rest[++i] ?? "");
66
+ if (!m) {
67
+ console.error(TRACES_USAGE);
68
+ return 2;
69
+ }
70
+ // SINCE only matches digits followed by m, h or d, so the unit is one of the three.
71
+ windowSec = Number(m[1]) * (m[2] === "h" ? 3600 : m[2] === "d" ? 86400 : 60);
72
+ } else if (runId !== undefined) {
73
+ console.error(TRACES_USAGE);
74
+ return 2;
75
+ } else {
76
+ runId = a;
77
+ }
78
+ }
79
+ if ((runId !== undefined) === (windowSec !== undefined)) {
80
+ console.error(TRACES_USAGE);
81
+ return 2;
82
+ }
83
+ const runs = ompTraceRuns(root);
84
+ const src = ompTraceSource(root);
85
+ const reports: RunClaimsReport[] = [];
86
+ if (windowSec !== undefined) {
87
+ const cutoff = nowSec() - windowSec;
88
+ for (const r of runs) {
89
+ if (r.mtimeSec < cutoff) continue;
90
+ reports.push(claimsReport(src, r.runId));
91
+ }
92
+ } else {
93
+ if (!runs.some((r) => r.runId === runId)) {
94
+ console.error(`no trace for run ${runId}`);
95
+ return 1;
96
+ }
97
+ reports.push(claimsReport(src, runId!));
98
+ }
99
+ if (json) {
100
+ console.log(JSON.stringify(reports, null, 2));
101
+ return 0;
102
+ }
103
+ for (const r of reports) {
104
+ if (r.claims === 0) {
105
+ console.log(`${r.runId}: no verifiable claims in the final report`);
106
+ continue;
107
+ }
108
+ console.log(`${r.runId}: ${r.claims} claims, ${r.backed} backed, ${r.unbacked.length} unbacked`);
109
+ for (const u of r.unbacked) {
110
+ console.log(` ${u.kind}: ${u.summary}`);
111
+ if (u.evidence) console.log(` evidence: ${u.evidence}`);
112
+ }
113
+ }
114
+ return 0;
115
+ }
@@ -42,6 +42,38 @@ export interface RunSource {
42
42
  mainSession(file?: string): MainSession | null;
43
43
  }
44
44
 
45
+ // Trace events: the raw activity of one run, used for claimed-vs-done checks and cross-run
46
+ // questions. Harness-specific parsing lives in the adapters; core only defines the shape.
47
+
48
+ export interface TraceUsage {
49
+ input: number;
50
+ output: number;
51
+ cacheRead: number;
52
+ cacheWrite: number;
53
+ totalTokens: number;
54
+ cost: number;
55
+ }
56
+
57
+ export type TraceEventKind = "toolCall" | "toolResult" | "usage" | "modelChange" | "assistantText";
58
+
59
+ export interface TraceEvent {
60
+ kind: TraceEventKind;
61
+ /** Unix seconds; null when the source line carries no readable timestamp. */
62
+ ts: number | null;
63
+ runId: string;
64
+ tool?: string;
65
+ args?: Record<string, unknown>;
66
+ isError?: boolean;
67
+ text?: string;
68
+ model?: string;
69
+ provider?: string;
70
+ usage?: TraceUsage;
71
+ }
72
+
73
+ export interface TraceSource {
74
+ events(runId: string): TraceEvent[];
75
+ }
76
+
45
77
  export interface Decision {
46
78
  allow: boolean;
47
79
  reason: string;
@@ -61,12 +93,16 @@ export interface ToolEvent {
61
93
  paths: string[];
62
94
  writes: string[];
63
95
  command: string;
96
+ /** Labels of the harness's own running background jobs at call time; undefined when the caller has no job info (CLI without it). */
97
+ runningJobs?: string[];
64
98
  }
65
99
 
66
100
  export interface SpawnEvent {
67
101
  agent: string;
68
102
  invocationKind: string;
69
103
  brief: string;
104
+ /** Labels of the harness's own running background jobs; undefined when the caller has no job info. */
105
+ runningJobs?: string[];
70
106
  }
71
107
 
72
108
  export interface InjectEvent {
@@ -79,6 +79,23 @@ function spawnsFile(): string {
79
79
  return path.join(q.STATE_DIR, "spawns.json");
80
80
  }
81
81
 
82
+ function staffingFile(): string {
83
+ return path.join(q.STATE_DIR, "staffing.json");
84
+ }
85
+
86
+ /** plan → the task names of its newest spawn (staffing.json); read for the staffed check. */
87
+ export function readStaffing(): Record<string, string[]> {
88
+ try {
89
+ const raw: unknown = JSON.parse(readFileSync(staffingFile(), "utf8"));
90
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
91
+ const out: Record<string, string[]> = {};
92
+ for (const [k, v] of Object.entries(raw)) if (Array.isArray(v)) out[k] = v.map(String);
93
+ return out;
94
+ } catch {
95
+ return {};
96
+ }
97
+ }
98
+
82
99
  function readSpawns(): Record<string, string> {
83
100
  try {
84
101
  const raw: unknown = JSON.parse(readFileSync(spawnsFile(), "utf8"));
@@ -91,8 +108,8 @@ function readSpawns(): Record<string, string> {
91
108
  }
92
109
  }
93
110
 
94
- /** Remember the "## Progress" hash of the plans an agent was just spawned on. */
95
- export function recordSpawns(files: string[]): void {
111
+ /** Remember the "## Progress" hash of the plans an agent was just spawned on. With `staffing`, also record the spawn's task names per plan (staffing.json); a plan's entry is replaced by the newest spawn that names it. */
112
+ export function recordSpawns(files: string[], staffing: Record<string, string[]> = {}): void {
96
113
  const s = readSpawns();
97
114
  for (const f of files) {
98
115
  try {
@@ -105,6 +122,23 @@ export function recordSpawns(files: string[]): void {
105
122
  } catch (err) {
106
123
  log(`${q.STATE_DIR}/../main-guard.log`, `cannot write ${spawnsFile()}: ${err}`);
107
124
  }
125
+ if (!Object.keys(staffing).length) return;
126
+ const st = readStaffing();
127
+ for (const [f, names] of Object.entries(staffing)) if (names.length) st[f] = [...names];
128
+ try {
129
+ mkdirSync(q.STATE_DIR, { recursive: true });
130
+ writeFileSync(staffingFile(), JSON.stringify(st, null, 1));
131
+ } catch (err) {
132
+ log(`${q.STATE_DIR}/../main-guard.log`, `cannot write ${staffingFile()}: ${err}`);
133
+ }
134
+ }
135
+
136
+ /** Plans with a running subagent: one of the plan's staffing names equals a running job label, or the label is that name with the spawner's uniqueness suffix ("-2", "-3", …; real snapshot 2026-10-25: `allocate()` keeps the exact name first, then appends). Pure; no job info staffs nothing. */
137
+ export function staffedPlans(staffing: Record<string, string[]>, runningJobs: string[] | undefined): string[] {
138
+ if (!runningJobs?.length) return [];
139
+ return Object.entries(staffing)
140
+ .filter(([, names]) => names.some(n => runningJobs.some(j => j === n || j.startsWith(`${n}-`))))
141
+ .map(([file]) => file);
108
142
  }
109
143
 
110
144
  /** Re-key a plan's spawn hash after its Progress body was trimmed. Only a hash that matched the old body moves. Pure. */
@@ -253,7 +287,10 @@ export function planGate(text: string, label: string): [string | null, string[]]
253
287
  `${label}: ${unclosed.map(p => `${p.file} (${p.status})`).join(", ")} is still indexed. Verify it and run \`queue-close <plan>\` before any new spawn.`,
254
288
  [],
255
289
  ];
256
- const named = plans.filter(p => text.includes(p.file));
290
+ // A `Priority skip: <path> — <why>` line names a plan it does NOT run on (20261025_0215 P3);
291
+ // only the remaining text decides which plans this brief targets.
292
+ const body = text.replace(/^\s*(?:[-*]\s+)?priority skip:.*$/gim, "");
293
+ const named = plans.filter(p => body.includes(p.file));
257
294
  if (!named.length)
258
295
  return [
259
296
  `${label}: an implementer needs an open plan. Name the plan's absolute path in the brief; the plan must be listed in ${q.INDEX}.`,
@@ -285,12 +322,76 @@ export function planGate(text: string, label: string): [string | null, string[]]
285
322
  return [null, named.map(p => p.file)];
286
323
  }
287
324
 
288
- /** Reason to refuse a `task` brief, or null; `files` receives the plans to record, `budgets` every named task's call budget (null = none). */
325
+ // --- priority: index order is priority (plan 20261025_0215_index_priority) ---
326
+
327
+ export interface PrioritySkip {
328
+ plan: string;
329
+ why: string;
330
+ }
331
+
332
+ export interface PriorityOutcome {
333
+ /** Refusal text, without the caller's label prefix. */
334
+ problem?: string;
335
+ /** Skip lines the brief justified; the caller logs each, then allows. */
336
+ skips?: PrioritySkip[];
337
+ /** No job info was available: the gate never refuses. */
338
+ unknown?: boolean;
339
+ }
340
+
341
+ const SKIP_LINE = /^\s*(?:[-*]\s+)?priority skip:\s*(.+?)\s+[—–-]\s*(.+?)\s*$/gim;
342
+
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 {
345
+ return p.status === "open" && !p.waiting && !q.awaitingMerge(p) && !p.errors.length && unticked(p).length > 0;
346
+ }
347
+
348
+ /**
349
+ * 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.
353
+ */
354
+ export function priorityProblem(plans: Plan[], named: string[], staffed: string[] | undefined, brief: string): PriorityOutcome | null {
355
+ if (staffed === undefined) return { unknown: true };
356
+ const namedRanks = named.map(f => plans.findIndex(p => p.file === f)).filter(n => n >= 0);
357
+ if (!namedRanks.length) return null;
358
+ const higher = plans.slice(0, Math.min(...namedRanks));
359
+ const skipLines: Record<string, string> = {};
360
+ for (const m of brief.matchAll(SKIP_LINE)) {
361
+ const plan = (m[1] ?? "").trim();
362
+ const why = (m[2] ?? "").trim();
363
+ if (plan && why) skipLines[plan] = why;
364
+ }
365
+ const skips: PrioritySkip[] = [];
366
+ for (let i = 0; i < higher.length; i++) {
367
+ const p = higher[i]!;
368
+ if (!priorityIdle(p) || staffed.includes(p.file)) continue;
369
+ const why = skipLines[p.file];
370
+ if (why) {
371
+ skips.push({ plan: p.file, why });
372
+ continue;
373
+ }
374
+ return { problem: `higher plan ${p.file} (rank ${i + 1}) is idle; spawn on it first or add "Priority skip: ${p.file} — <why>"` };
375
+ }
376
+ return skips.length ? { skips } : null;
377
+ }
378
+
379
+ /** Load staffing, run the pure priority gate and log its outcome; the refusal comes back with the caller's label, or null. */
380
+ 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);
382
+ if (outcome?.unknown) log(cfg.paths.guard_log, "PRIORITY unknown jobs");
383
+ for (const s of outcome?.skips ?? []) log(cfg.paths.guard_log, `PRIORITY skip ${s.plan}: ${s.why}`);
384
+ return outcome?.problem ? `${label}: ${outcome.problem}` : null;
385
+ }
386
+
387
+ /** Reason to refuse a `task` brief, or null; `files` receives the plans to record, `budgets` every named task's call budget (null = none), `staffing` each plan's named tasks of this call, `runningJobs` the caller's running job labels (undefined = no job info). */
289
388
  export function spawnProblem(
290
389
  input: Record<string, unknown>,
291
390
  cfg: Config,
292
391
  files: string[] = [],
293
392
  budgets: Record<string, number | null> = {},
393
+ staffing: Record<string, string[]> = {},
394
+ runningJobs?: string[],
294
395
  ): string | null {
295
396
  const tasks = Array.isArray(input?.tasks) ? input.tasks : [];
296
397
  const context = String(input?.context ?? "");
@@ -310,11 +411,23 @@ export function spawnProblem(
310
411
  if (budget < 10 || budget > cfg.guards.sub_max_calls_cap)
311
412
  return `${label}: call budget ${budget} is outside the allowed range 10..${cfg.guards.sub_max_calls_cap}.`;
312
413
  }
313
- if (t?.name) named[label] = budget;
414
+ if (t?.name) {
415
+ named[label] = budget;
416
+ for (const f of plans) staffing[f] = [...(staffing[f] ?? []), label];
417
+ }
314
418
  files.push(...plans);
315
419
  }
316
420
  Object.assign(budgets, named);
317
- return null;
421
+ // Priority gate (20261025_0215 P3): once per `task` call, over the plans this call names; the
422
+ // skip lines may sit in the shared context or any task text.
423
+ const gate = priorityGate(
424
+ files,
425
+ runningJobs,
426
+ `${context}\n${tasks.map(t => String(t?.task ?? "")).join("\n")}`,
427
+ cfg,
428
+ String((tasks[0] && (tasks[0].name ?? tasks[0].agent)) ?? "task"),
429
+ );
430
+ return gate;
318
431
  }
319
432
 
320
433
  function runBlockers(plan: Plan, hit: string[], e: ToolEvent, cfg: Config): string | null {
@@ -492,14 +605,15 @@ function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config): De
492
605
  }
493
606
  const files: string[] = [];
494
607
  const budgets: Record<string, number | null> = {};
495
- const why = spawnProblem(input, cfg, files, budgets);
608
+ const staffing: Record<string, string[]> = {};
609
+ const why = spawnProblem(input, cfg, files, budgets, staffing, e.runningJobs);
496
610
  if (why) {
497
611
  log(cfg.paths.guard_log, `BLOCK spawn: ${why}`);
498
612
  return deny(`main-guard: ${why}`);
499
613
  }
500
614
  const inc = incidentSpawnProblem("spawn", JSON.stringify(input), files, cfg);
501
615
  if (inc) return deny(`main-guard: ${inc}`);
502
- recordSpawns(files);
616
+ recordSpawns(files, staffing);
503
617
  recordBudgets(budgets);
504
618
  return ALLOW;
505
619
  }
@@ -676,9 +790,16 @@ export function checkSpawn(e: SpawnEvent, cfg: Config): Decision {
676
790
  log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${why}`);
677
791
  return deny(`main-guard: ${why}`);
678
792
  }
793
+ const gate = priorityGate(named, e.runningJobs, e.brief, cfg, e.agent);
794
+ if (gate) {
795
+ log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${gate}`);
796
+ return deny(`main-guard: ${gate}`);
797
+ }
679
798
  const inc = incidentSpawnProblem(`spawn ${e.agent}`, e.brief, named, cfg);
680
799
  if (inc) return deny(`main-guard: ${inc}`);
681
- recordSpawns(named);
800
+ const staffing: Record<string, string[]> = {};
801
+ for (const f of named) staffing[f] = [e.agent];
802
+ recordSpawns(named, staffing);
682
803
  return ALLOW;
683
804
  }
684
805
 
@@ -11,16 +11,19 @@
11
11
  // D3 block-loop: the same guard BLOCK reason (keyed like M5) logged incidents.block_repeat
12
12
  // times within one hour.
13
13
  // D4 owner-correction: an owner message matching the M4 correction patterns.
14
+ // D5 claim-unbacked: a run's final report claims something its own tool output never
15
+ // showed (gathered by the traces claims CLI, src/cli/traces.ts).
14
16
 
15
17
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
16
18
  import { dirname, join } from "node:path";
17
19
  import { fileURLToPath } from "node:url";
18
- import type { Run } from "./adapter.ts";
20
+ import type { Run, TraceEvent } from "./adapter.ts";
19
21
  import type { Config } from "./config.ts";
20
22
  import { nowSec, strftime } from "./clock.ts";
21
23
  import { log } from "./guards.ts";
22
24
  import { addIncident, type IncidentView } from "./incidents.ts";
23
25
  import type { GuardBlock } from "./metrics.ts";
26
+ import { verifyClaims, type Claim } from "./trace-claims.ts";
24
27
 
25
28
  const HERE = dirname(fileURLToPath(import.meta.url));
26
29
 
@@ -141,6 +144,30 @@ export function ownerCorrection(text: string, patterns: RegExp[], now: number):
141
144
  };
142
145
  }
143
146
 
147
+ // ---- D5: the final report claims something the run's own tool output never showed ----
148
+
149
+ /**
150
+ * Final-report claims (src/core/trace-claims.ts) with no backing activity in the same run's
151
+ * trace: a "13 passed" no toolResult shows, a SHA no git command printed, a label never passed
152
+ * to a heavy-run call, a path no edit/write call carried. Evidence is the claiming line, which
153
+ * the extractor already masked and capped, so nothing secret reaches the incident store.
154
+ */
155
+ export function claimUnbacked(claims: Claim[], events: TraceEvent[]): Finding[] {
156
+ const out: Finding[] = [];
157
+ for (const v of verifyClaims(claims, events)) {
158
+ if (v.backed) continue;
159
+ const c = v.claim;
160
+ const what = c.count !== undefined ? `${c.kind} ${c.count}` : `${c.kind} ${c.value ?? ""}`;
161
+ out.push({
162
+ kind: "claim-unbacked",
163
+ summary: `final report claims ${what.trim()} but the run's tool output never shows it`,
164
+ evidence: c.evidence,
165
+ fingerprint: `claim-unbacked:${c.kind}:${c.count ?? c.value ?? ""}`,
166
+ });
167
+ }
168
+ return out;
169
+ }
170
+
144
171
  // ---- the runner ----
145
172
 
146
173
  /** The plain inputs the callers gather; a detector without its input does not run. */
@@ -154,6 +181,9 @@ export interface DetectorInput {
154
181
  bash?: { command: string; output: string };
155
182
  /** D4: the owner prompt at before_agent_start; never a main-guard continuation. */
156
183
  prompt?: string;
184
+ /** D5: one run's final-report claims plus the same run's trace events (the traces CLI gathers both). */
185
+ claims?: Claim[];
186
+ events?: TraceEvent[];
157
187
  }
158
188
 
159
189
  /**
@@ -198,6 +228,9 @@ export function runDetectors(cfg: Config, input: DetectorInput, now = nowSec()):
198
228
  return f ? [f] : [];
199
229
  });
200
230
  }
231
+ if (input.claims && input.events) {
232
+ attempt("claim-unbacked", () => claimUnbacked(input.claims!, input.events!));
233
+ }
201
234
  return out;
202
235
  }
203
236