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.
package/README.md CHANGED
@@ -94,11 +94,15 @@ Owner rule: never write a plan when another agent is doing the research or readi
94
94
 
95
95
  A plan parked for the owner has one line: `WAITING on owner: <what>`. That line is the only hold, and only Main writes it (plan-guard refuses subagents). The queue summary shows it as a flag on the plan, cut at 80 characters. Compaction and the rollover handoff read the same lines through `ownerHolds`: the compaction context lists each `<plan file>: WAITING on owner: <text>` line (or `none`) and says any other "needs the owner" or "paused" claim is unverified; the handoff's generated state carries the same lines. Main does not keep holds in a handoff note.
96
96
 
97
+ ## Queue priority
98
+
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.
100
+
97
101
  ## Owner page (`neurastream ui`)
98
102
 
99
103
  `neurastream ui on --login <tailscale login> [--port N]` does the whole setup in one sentence: it writes `ui.enabled: true` and `ui.owner_login` (plus `ui.port` with `--port`) into `~/.config/neurastream/config.yml` — every other line of the file is kept byte-for-byte — copies `templates/systemd/neurastream-ui.service` to `~/.config/systemd/user/neurastream-ui.service`, runs `systemctl --user daemon-reload`, `enable` and `restart`, then prints the phone link `http://<MagicDNS name>:<port>`. The login must be one the tailnet knows (`tailscale status --json`); when tailscale cannot answer, the check is skipped with a printed warning, never a refusal. `neurastream ui off` stops and disables the unit and sets `ui.enabled: false`, keeping `ui.owner_login` for the next `on`.
100
104
 
101
- With `ui.enabled: true` and `ui.owner_login` set (`neurastream config`, `docs/config.md`), `neurastream ui` serves one page bound to this machine's tailnet address only (port `ui.port`, default 7787; `templates/systemd/neurastream-ui.service` runs it as a user unit). It shows the plans whose `WAITING on owner:` line is open, with answer buttons; the guard unlock (`unlock 5/15/30`, `lock now`); the running agents; the queue; recent merges/CI; open incidents; agent scores; and machine health. No chat, no plan editing, no shell.
105
+ With `ui.enabled: true` and `ui.owner_login` set (`neurastream config`, `docs/config.md`), `neurastream ui` serves one page bound to this machine's tailnet address only (port `ui.port`, default 7787; `templates/systemd/neurastream-ui.service` runs it as a user unit). The page reads top to bottom: a sticky status strip with the amber "needs you" count plus working/CI/disk signals that turn red only when something is actually wrong; one card per open `WAITING on owner:` plan — the plan's `#` title, the ask in plain words, the goal folded into a Background block, and named actions ("Yes, go ahead", "No", "Reply…") whose answer shows as a one-time receipt ("Sent to Main · 08:12"); a working-now row per running or waiting agent; and closed details blocks for the queue (one flat list in `INDEX.md` order — drag a card by its handle, or tap "↑ top"/"↑"/"↓"; the drop rewrites `INDEX.md`, Main gets the move as a message and the page confirms "Moved to #2"), merges/CI, incidents, agent scores (a real table) and machine health. A sticky bottom bar holds the guard unlock ("Unlock 15 min", "Unlock 30 min", "Lock now") and, when `guards.chat_unlock` is off, says so in plain words with the exact config line. Light and dark follow the OS; there are no external assets and no build step — one server-rendered HTML string, inline CSS and one small inline script under a per-response CSP nonce (`bun scripts/ui-preview.ts <out.html>` renders a preview without a server). No chat, no plan editing, no shell.
102
106
 
103
107
  A request is served only when the peer is a tailnet address that is neither loopback nor this machine's own tailnet IP, `tailscale whois` names the `ui.owner_login` login — and the Host header is this machine: the tailnet address or the MagicDNS name, with the served port. The Host check runs on every request before whois, and a POST's Origin must match it, so a DNS-rebinding page (foreign Host, matching Origin, owner's phone) gets a 403 like everyone else. Every request logs one `UI <method> <path> login=<l> → <code>` line to the guard log.
104
108
 
@@ -170,6 +174,20 @@ Guard rules around it:
170
174
  - A stop the guard blocks posts nothing; when Main continues and really hands back later, that later stop posts the final text. A subagent session never posts, and a relaunch (the launcher's rollover) posts nothing.
171
175
  - The post never delays the stop decision: it times out at 5 seconds per chunk, makes one attempt, and writes one guard-log line when a channel fails. Long replies are split per channel (Discord 2000, Slack 3000 characters) on line boundaries where possible.
172
176
 
177
+ "Needs you" pings use the same channels so the owner learns on the phone that a decision is his: when a Main turn ends with an open plan whose `WAITING on owner:` line was not pinged before, neurastream posts `🔔 Needs you — <plan>: <question>` (with the `neurastream ui` phone-page link when `ui.enabled: true`), and when the guard refuses a Main tool call because it touches a protected guard file, it posts `🔓 Main needs an unlock to continue (<file>)` — the unlock ping at most once per 30 minutes, each waiting question once until its line changes or disappears, remembered in `<queue_state>/notify-waiting.json`. Every decision logs one `notify: needs-you posted|skipped (<why>)` guard-log line.
178
+
179
+ ## Trace claims (`neurastream traces claims`)
180
+
181
+ Agents' final reports assert results — "530 passed", "exit 0", commit SHAs, heavy-run labels, changed files. This command reads a run's trace (its session file, read-only) and checks each claim in the run's last assistant message against what the run's own tool activity shows: a count or exit code must appear in some tool output, a commit SHA must be printed by the output of a git command the run itself ran, a heavy-run label must appear in a quoted heavy-run call, and a changed path must be carried by an edit/write call or a shell write in the path's own command segment. A claim nothing shows becomes a `claim-unbacked` finding.
182
+
183
+ ```
184
+ neurastream traces claims --since 24h # every run touched in the window
185
+ neurastream traces claims NsTracesVerifyGlm # one run, by id
186
+ neurastream traces claims --since 24h --json # machine-readable
187
+ ```
188
+
189
+ Known boundary: a report that cites other runs' work (Main quoting a subagent, a relaunched agent quoting its predecessor) can produce `claim-unbacked` findings that are true in this run's trace but provable only in the cited run's own trace.
190
+
173
191
  ## Self-metrics
174
192
 
175
193
  `neurastream metrics report [--days N]` compares this window (the last `metrics.report_days`, default 7) with the one before it, writes `<paths.notes>/metrics.md`, and prints the same report. Worst change is marked `◀ worst`. The five numbers:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.11",
3
+ "version": "0.2.13",
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",
@@ -23,13 +23,14 @@ import { loadConfig, type Config } from "../../core/config.ts";
23
23
  import { nowSec, strftime } from "../../core/clock.ts";
24
24
  import { runDetectorsGated } from "../../core/incident-detectors.ts";
25
25
  import { checkInject, checkPlanEdit, checkStop, checkTool, MAIN_PLAN_FILE, recordMainResult, revertMainEdit, rekeySpawnFile } from "../../core/guards.ts";
26
- import { postReply } from "../../core/notify.ts";
26
+ import { notifyProviders, postReply } from "../../core/notify.ts";
27
27
  import { inboxPath } from "../../core/owner-ui.ts";
28
+ import { realTailscale } from "../../core/tailscale.ts";
28
29
  import { applyQueueEnv } from "../../core/queue/env.ts";
29
30
  import { mainStartText, runDailyCheck } from "../../core/main-start.ts";
30
31
  import { readBlocks } from "../../core/metrics.ts";
31
32
  import { buildHandoff, holdsBlock, notePath, noteRequest, OWNER_AWAY, ownerText, relaunchPath, rolloverState, spawnRefusal, type RolloverState } from "../../core/rollover.ts";
32
- import { defaultCompletedResults, defaultRunSource, lastAssistantText } from "./sessions.ts";
33
+ import { defaultCompletedResults, defaultRunSource } from "./sessions.ts";
33
34
  import { packageJsonPath, packageVersion } from "./package-root.ts";
34
35
  import * as q from "../../core/queue/lib.ts";
35
36
  // Registers the plugin-command matcher into core's writeTargets (side effect).
@@ -60,6 +61,37 @@ function asString(v: unknown, fallback = ""): string {
60
61
  return typeof v === "string" ? v : fallback;
61
62
  }
62
63
 
64
+ /** The last assistant message of an omp event's `messages` array, as the adapter needs it: its
65
+ * joined text-block text and the shape that tells a real hand-back from a mid-run continuation
66
+ * (plan 20261025_0130). omp sends the reply in `session_stop.last_assistant_message` (falling
67
+ * back to the last assistant entry of `messages`) and in `agent_end.messages`; reading the
68
+ * session file instead lags a whole turn because session_stop fires BEFORE agent_end. */
69
+ interface EventReply {
70
+ text: string;
71
+ stopReason: string | null;
72
+ toolCalls: number;
73
+ }
74
+
75
+ function lastAssistantIn(messages: unknown): EventReply | null {
76
+ const arr = Array.isArray(messages) ? messages : [];
77
+ for (let i = arr.length - 1; i >= 0; i--) {
78
+ const m = asRecord(arr[i]);
79
+ if (m.role !== "assistant") continue;
80
+ const content = Array.isArray(m.content) ? m.content : [];
81
+ const text = content
82
+ .filter(c => asRecord(c).type === "text")
83
+ .map(c => asString(asRecord(c).text))
84
+ .join("\n")
85
+ .trim();
86
+ return {
87
+ text,
88
+ stopReason: typeof m.stopReason === "string" ? m.stopReason : null,
89
+ toolCalls: content.filter(c => asRecord(c).type === "toolCall").length,
90
+ };
91
+ }
92
+ return null;
93
+ }
94
+
63
95
  function asCtx(v: unknown): HostCtx {
64
96
  const r = asRecord(v);
65
97
  // The agent envelope only ever carries kind/id strings (original extensions read just those);
@@ -378,10 +410,109 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
378
410
  let inboxTimer: unknown;
379
411
  const calls = new Map<string, number>(); // subagent call budget, by agent id
380
412
  const pending = new Map<string, Map<string, string>>(); // toolCallId -> plan snapshots
381
- // Chat notify (plan 20261024_2155): the last assistant text of the main session, and the text
382
- // a stop already posted (attempted) — one post per distinct text, never a retry loop.
383
- let lastReply: string | null = null;
413
+ // Chat notify (plans 20261024_2155, 20261025_0130): the text a hand-back already posted
414
+ // (attempted) — one post per distinct text, never a retry loop. The reply itself comes from
415
+ // the stop/agent_end event, never the session file (session_stop fires BEFORE agent_end, and
416
+ // omp skips it entirely while an async job is pending, so a file read lags a whole turn).
384
417
  let postedReply: string | null = null;
418
+ // Set by every session_stop path that returns block; the willContinue agent_end that omp then
419
+ // emits (sessionStopWillContinue) consumes it and posts nothing — a blocked stop's reply is a
420
+ // mid-work report, never a hand-back.
421
+ let stopBlocked = false;
422
+ // One guard-log line per notify decision: `notify: posted|skipped (<why>)`. Fire-and-forget:
423
+ // the decision never awaits the post; a failed or slow post logs one line and never blocks
424
+ // or retries.
425
+ const notifyHandback = (reply: EventReply | null, why: string): void => {
426
+ if (!reply || !reply.text) {
427
+ adapterLog(cfg, `notify: skipped (no reply text, ${why})`);
428
+ return;
429
+ }
430
+ if (reply.text === postedReply) {
431
+ adapterLog(cfg, `notify: skipped (duplicate, ${why})`);
432
+ return;
433
+ }
434
+ postedReply = reply.text;
435
+ adapterLog(cfg, `notify: posted (${why})`);
436
+ void postReply(reply.text, cfg).then(results => {
437
+ for (const r of results) if (!r.posted) adapterLog(cfg, `notify: ${r.provider}: ${r.error}`);
438
+ });
439
+ };
440
+
441
+ // "Needs you" pings (P3b): the owner learns on Discord that a decision or an unlock is his —
442
+ // deterministic, no model call, Main session only, the same webhook path, fire-and-forget, one
443
+ // guard-log line per decision (`notify: needs-you posted|skipped (<why>)`).
444
+ const needsYouPost = (text: string, why: string): void => {
445
+ if (notifyProviders(cfg).length === 0) {
446
+ adapterLog(cfg, `notify: needs-you skipped (notify off, ${why})`);
447
+ return;
448
+ }
449
+ adapterLog(cfg, `notify: needs-you posted (${why})`);
450
+ void postReply(text, cfg).then(results => {
451
+ for (const r of results) if (!r.posted) adapterLog(cfg, `notify: ${r.provider}: ${r.error}`);
452
+ });
453
+ };
454
+ // The phone-page link only when the page is on and this machine's MagicDNS name is known;
455
+ // computed at most once per process (tailscale status is a subprocess call).
456
+ let phonePageSuffix: string | null = null;
457
+ const phonePage = (): string => {
458
+ if (!cfg.ui.enabled) return "";
459
+ if (phonePageSuffix === null) {
460
+ const dns = realTailscale.dnsName();
461
+ phonePageSuffix = dns ? ` Answer on the phone page: http://${dns}:${cfg.ui.port}` : "";
462
+ }
463
+ return phonePageSuffix;
464
+ };
465
+ // WAITING: every Main turn end asks whether an open plan now waits on the owner (the same
466
+ // source the owner page lists). Keys are `plan file|waiting line`, remembered in
467
+ // <queue_state>/notify-waiting.json; a key whose line is gone is dropped, so the same question
468
+ // asked again later posts again. No waiting plans: no decision, no log line.
469
+ const waitingKeysFile = join(cfg.paths.queue_state, "notify-waiting.json");
470
+ const notifyWaitingPlans = (): void => {
471
+ const waiting = q.activePlans(cfg.paths.queue_index).filter(p => p.waiting && p.status === "open" && p.waitingLine);
472
+ let stored: string[] = [];
473
+ try {
474
+ const parsed: unknown = JSON.parse(readFileSync(waitingKeysFile, "utf8"));
475
+ if (Array.isArray(parsed)) stored = parsed.filter((k): k is string => typeof k === "string");
476
+ } catch {}
477
+ // Persist after reading: a key whose WAITING line is gone is dropped, so the same question
478
+ // asked again later posts again. No waiting plans: the set prunes to empty, no decision,
479
+ // no line.
480
+ const current: string[] = [];
481
+ const fresh: typeof waiting = [];
482
+ for (const p of waiting) {
483
+ const key = `${p.file}|${p.waitingLine}`;
484
+ current.push(key);
485
+ if (!stored.includes(key)) fresh.push(p);
486
+ }
487
+ try {
488
+ mkdirSync(cfg.paths.queue_state, { recursive: true });
489
+ writeFileSync(waitingKeysFile, JSON.stringify(current));
490
+ } catch {}
491
+ if (current.length === 0) return;
492
+ if (fresh.length === 0) {
493
+ adapterLog(cfg, "notify: needs-you skipped (no new waiting lines)");
494
+ return;
495
+ }
496
+ for (const p of fresh) {
497
+ const title = p.text.match(/^# (.+)$/m)?.[1] ?? basename(p.file);
498
+ needsYouPost(`🔔 Needs you — ${title}: ${p.waitingLine}.${phonePage()}`, `waiting: ${basename(p.file)}`);
499
+ }
500
+ };
501
+ // UNLOCK: a protected-file refusal of a Main tool call means Main sits blocked until the owner
502
+ // unlocks — ping, at most once per 30 min.
503
+ let unlockPingMs = -Infinity;
504
+ const notifyUnlockNeeded = (reason: string): void => {
505
+ if (Date.now() - unlockPingMs < 30 * 60_000) {
506
+ adapterLog(cfg, "notify: needs-you skipped (unlock ping sent recently)");
507
+ return;
508
+ }
509
+ unlockPingMs = Date.now();
510
+ const target = basename(asString(reason.match(/plan-guard: (.+) is a protected guard file/)?.[1] ?? "guard file"));
511
+ needsYouPost(
512
+ `🔓 Main needs an unlock to continue (${target}). Tap "unlock ${cfg.guards.unlock_minutes}" on the phone page.`,
513
+ "protected-file refusal",
514
+ );
515
+ };
385
516
 
386
517
  pi.on("session_start", (_e, ctx) => {
387
518
  const c = asCtx(ctx);
@@ -452,11 +583,14 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
452
583
  const snap = new Map<string, string>();
453
584
  snapshotPlans(tool, input, cwd, snap, !isSub);
454
585
  // Drain (src/core/rollover.ts): while a rollover is pending no new subagent starts; the
455
- // running ones finish first. Subagents' own tool calls are unaffected.
456
- if (!isSub && tool === "task" && cfg.rollover.enabled) {
586
+ // running ones finish first. Subagents' own tool calls are unaffected. Main's task calls
587
+ // also carry the running job labels for the priority gate (20261025_0215 P2).
588
+ let runningJobs: string[] | undefined;
589
+ if (!isSub && tool === "task") {
457
590
  const rc = asRolloverCtx(ctx);
458
- if (rc) {
459
- const why = spawnRefusal(rolloverSnapshot(rc).state, rc.runningJobs());
591
+ runningJobs = rc?.runningJobs();
592
+ if (cfg.rollover.enabled && rc) {
593
+ const why = spawnRefusal(rolloverSnapshot(rc).state, runningJobs ?? []);
460
594
  if (why) {
461
595
  const tasks = Array.isArray(input.tasks) ? input.tasks : [];
462
596
  adapterLog(cfg, `BLOCK spawn ${String(asRecord(tasks[0]).agent ?? "task")}: rollover pending`);
@@ -465,10 +599,14 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
465
599
  }
466
600
  }
467
601
  const d = checkTool(
468
- { tool, input, cwd, agent, agentId: id, calls: n - 1, paths: [], writes: [], command: asString(input.command) },
602
+ { tool, input, cwd, agent, agentId: id, calls: n - 1, paths: [], writes: [], command: asString(input.command), runningJobs },
469
603
  cfg,
470
604
  );
471
- if (!d.allow) return { block: true, reason: d.reason };
605
+ if (!d.allow) {
606
+ // P3b: Main refused on a protected guard file sits blocked until the owner unlocks.
607
+ if (!isSub && d.reason.includes("is a protected guard file. Only the owner changes it")) notifyUnlockNeeded(d.reason);
608
+ return { block: true, reason: d.reason };
609
+ }
472
610
  if (snap.size) pending.set(asString(e.toolCallId), snap);
473
611
  // The originals return nothing on a clean call; only warn injects carry an object.
474
612
  const out = toExtensionResult(d);
@@ -534,22 +672,20 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
534
672
  return undefined;
535
673
  });
536
674
 
537
- pi.on("session_stop", (_e, ctx) => {
675
+ pi.on("session_stop", (e, ctx) => {
538
676
  const c = asCtx(ctx);
539
677
  if (c.hasAgent && c.kind !== "main") return;
540
678
  // A relaunch is requested: omp shuts down at the next idle, so the stop must not be continued.
541
- if (relaunched) return undefined;
542
- // The stop hands the turn back to the owner: post Main's final reply, once per distinct
543
- // text. Fire-and-forget: the decision never awaits the post; a failed or slow post logs
544
- // one line and never blocks or retries.
545
- const notifyOwner = (): void => {
546
- const text = lastReply;
547
- if (!text || text === postedReply) return;
548
- postedReply = text;
549
- void postReply(text, cfg).then(results => {
550
- for (const r of results) if (!r.posted) adapterLog(cfg, `notify: ${r.provider}: ${r.error}`);
551
- });
552
- };
679
+ if (relaunched) {
680
+ adapterLog(cfg, "notify: skipped (relaunch requested)");
681
+ return undefined;
682
+ }
683
+ // The stop hands the turn back to the owner: post the stop event's own final reply, once
684
+ // per distinct text. The reply comes from the event (last_assistant_message, falling back
685
+ // to the last assistant entry of messages), never the session file: omp fires session_stop
686
+ // BEFORE agent_end, so a file read would lag a whole turn.
687
+ const stopMsg = asRecord(e).last_assistant_message;
688
+ const reply = stopMsg ? lastAssistantIn([stopMsg]) : lastAssistantIn(asRecord(e).messages);
553
689
  // A pending rollover decides the stop and checkStop is not consulted: its queue, incident and cancel
554
690
  // blocks would hold Main at a wait the new session raises again through main-start, and its "spawn an
555
691
  // agent" text is refused while the rollover is pending.
@@ -558,6 +694,8 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
558
694
  const snap = rolloverSnapshot(rc);
559
695
  if (snap.state === "need-note") {
560
696
  adapterLog(cfg, "BLOCK stop: rollover need-note");
697
+ adapterLog(cfg, "notify: skipped (stop blocked: rollover need-note)");
698
+ stopBlocked = true;
561
699
  return { decision: "block", reason: noteRequestFor(rc, snap) };
562
700
  }
563
701
  if (snap.state === "ready" || snap.state === "wait-jobs") {
@@ -565,7 +703,8 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
565
703
  // Under the launcher a ready rollover starts now (not a hand-back to the owner);
566
704
  // plain omp waits for the owner's next message.
567
705
  const handsToOwner = !(snap.state === "ready" && process.env.NEURASTREAM_MAIN_LAUNCHER === "1" && requestRelaunch(rc, notePath(rc.sessionId)));
568
- if (handsToOwner) notifyOwner();
706
+ if (handsToOwner) notifyHandback(reply, "allowed session_stop");
707
+ else adapterLog(cfg, "notify: skipped (relaunch requested)");
569
708
  return undefined;
570
709
  }
571
710
  }
@@ -573,9 +712,11 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
573
712
  callsSinceStop = d.state?.callsSinceStop ?? 0;
574
713
  idleStops = d.state?.idleStops ?? idleStops;
575
714
  if (d.allow) {
576
- notifyOwner();
715
+ notifyHandback(reply, "allowed session_stop");
577
716
  return undefined;
578
717
  }
718
+ adapterLog(cfg, "notify: skipped (stop blocked by guard)");
719
+ stopBlocked = true;
579
720
  return { decision: "block", reason: d.reason };
580
721
  });
581
722
 
@@ -764,20 +905,47 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
764
905
  }
765
906
  };
766
907
  pi.on("agent_end", (e, ctx) => onSizeCheck("agent_end", e, ctx));
767
- // The text a later allowed stop posts: the last assistant message of each terminal run end in
768
- // the main session (omp 18.11.1 sets willContinue on a non-terminal end). A blocked stop keeps
769
- // Main talking, so the final run end overwrites this before the stop that really hands back.
908
+ // Hand-back without a session_stop (plan 20261025_0130): while an async job is pending omp
909
+ // fires agent_end with willContinue:true and SKIPS session_stop — this deferred hand-back
910
+ // posts from the event's own messages. omp also sets willContinue after a BLOCKED stop
911
+ // (sessionStopWillContinue) and for todo/plan-mode/rewind continuations, so a post here needs
912
+ // both: no blocked stop just decided (the flag), and an async job really pending. A terminal
913
+ // end (willContinue unset) is not a hand-back: the session_stop that follows it decides. A
914
+ // mid-run continuation — tool calls, or a non-"stop" reason such as an auto-retry — posts
915
+ // nothing.
770
916
  pi.on("agent_end", (e, ctx) => {
771
917
  if (!isMain(ctx)) return;
772
- if (asRecord(e).willContinue === true) return;
773
- const rc = asRolloverCtx(ctx);
774
- if (!rc) return;
775
- const text = lastAssistantText(rc.sessionFile);
776
- lastReply = text.trim() ? text : null;
918
+ if (asRecord(e).willContinue !== true) return;
919
+ if (stopBlocked) {
920
+ stopBlocked = false;
921
+ adapterLog(cfg, "notify: skipped (stop blocked, agent_end)");
922
+ return;
923
+ }
924
+ const jobCount = asRolloverCtx(ctx)?.runningJobs().length ?? 0;
925
+ if (jobCount === 0) {
926
+ adapterLog(cfg, "notify: skipped (no pending job, agent_end)");
927
+ return;
928
+ }
929
+ const reply = lastAssistantIn(asRecord(e).messages);
930
+ if (!reply || !reply.text) {
931
+ adapterLog(cfg, "notify: skipped (no reply text, agent_end hand-back)");
932
+ return;
933
+ }
934
+ if (reply.stopReason !== "stop" || reply.toolCalls > 0) {
935
+ adapterLog(
936
+ cfg,
937
+ `notify: skipped (mid-run: stop reason ${reply.stopReason ?? "unknown"}${reply.toolCalls > 0 ? ` + ${reply.toolCalls} tool call(s)` : ""}, agent_end hand-back)`,
938
+ );
939
+ return;
940
+ }
941
+ notifyHandback(reply, "agent_end hand-back");
777
942
  });
778
- // Turn end: page answers that arrived during the turn go out now (P3b). Main only.
943
+ // Turn end: page answers that arrived during the turn go out (P3b), then open plans that now
944
+ // WAIT on the owner ping Discord (P3b). Main only.
779
945
  pi.on("agent_end", (_e, ctx) => {
780
- if (isMain(ctx)) deliverOwnerInbox(pi, cfg);
946
+ if (!isMain(ctx)) return;
947
+ deliverOwnerInbox(pi, cfg);
948
+ notifyWaitingPlans();
781
949
  });
782
950
 
783
951
  // omp is really shutting down: the exit-grace fallback must not fire.
@@ -27,13 +27,13 @@ function walk(dir: string, depth: number, out: string[]): void {
27
27
  }
28
28
  }
29
29
 
30
- function jsonlAt(root: string, levels: number): string[] {
30
+ export function jsonlAt(root: string, levels: number): string[] {
31
31
  const out: string[] = [];
32
32
  walk(root, levels, out);
33
33
  return out;
34
34
  }
35
35
 
36
- function parseTs(ts: string): number | null {
36
+ export function parseTs(ts: string): number | null {
37
37
  const s = ts.slice(0, 19);
38
38
  if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/.test(s)) return null;
39
39
  const [date, time] = s.split("T") as [string, string];
@@ -45,47 +45,22 @@ function parseTs(ts: string): number | null {
45
45
  return local.getTime() / 1000 - timezone;
46
46
  }
47
47
 
48
- function asObj(v: unknown): Record<string, unknown> | null {
48
+ export function asObj(v: unknown): Record<string, unknown> | null {
49
49
  return typeof v === "object" && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : null;
50
50
  }
51
51
 
52
- /** The joined text of the session file's last assistant message, trimmed; "" when there is none
53
- * (unreadable file, no assistant message, or a tool-use-only ending). */
54
- export function lastAssistantText(file: string): string {
55
- let text: string;
56
- try {
57
- text = readFileSync(file, "utf8");
58
- } catch {
59
- return "";
60
- }
61
- let out = "";
62
- for (const line of text.split("\n")) {
63
- if (!line.trim()) continue;
64
- let parsed: unknown;
65
- try {
66
- parsed = JSON.parse(line);
67
- } catch {
68
- continue;
69
- }
70
- const d = asObj(parsed);
71
- if (!d) continue;
72
- const m = asObj(d.message) ?? d;
73
- if (m.role !== "assistant") continue;
74
- const content = Array.isArray(m.content) ? m.content : [];
75
- const texts = content
76
- .filter((c): c is Record<string, unknown> => asObj(c) !== null && asObj(c)?.type === "text")
77
- .map(c => String(c.text ?? ""));
78
- out = texts.join("\n").trim();
79
- }
80
- return out;
81
- }
82
-
83
52
  function costOf(m: Record<string, unknown>): number {
84
53
  const u = asObj(m.usage);
85
54
  const c = u ? asObj(u.cost) : null;
86
55
  return c && typeof c.total === "number" ? c.total : 0;
87
56
  }
88
57
 
58
+ /** Ledger run id for a session file: `MAIN <HH-MM-SS>` for dated main files, stem otherwise. */
59
+ export function runIdOf(file: string): string {
60
+ const stem = basename(file).slice(0, -6);
61
+ return /^\d{4}/.test(stem) ? `MAIN ${stem.slice(11, 19)}` : stem;
62
+ }
63
+
89
64
  function build(file: string, cfg: Config, mtime: number): Run | null {
90
65
  let text: string;
91
66
  try {
@@ -95,7 +70,7 @@ function build(file: string, cfg: Config, mtime: number): Run | null {
95
70
  }
96
71
  const stem = basename(file).slice(0, -6);
97
72
  const isMain = /^\d{4}/.test(stem);
98
- const id = isMain ? `MAIN ${stem.slice(11, 19)}` : stem;
73
+ const id = runIdOf(file);
99
74
  let model = "?";
100
75
  let scoreModel = "?";
101
76
  let calls = 0;
@@ -0,0 +1,140 @@
1
+ // Session-file trace reader: replays one run's raw activity as TraceEvents (plan
2
+ // 20261024_0300 P1). Run-id derivation matches the ledger (src/adapters/omp/sessions.ts):
3
+ // dated depth-1 files are main runs with id `MAIN <HH-MM-SS>` from the stem, deeper files are
4
+ // subagent runs with the bare stem as id. Every line type this harness writes that carries
5
+ // trace-relevant data is mapped; anything else (session banners, custom lines, compaction
6
+ // notes, unparseable lines) is skipped.
7
+
8
+ import { readFileSync, statSync } from "node:fs";
9
+ import type { TraceEvent, TraceSource, TraceUsage } from "../../core/adapter.ts";
10
+ import { asObj, jsonlAt, parseTs, runIdOf } from "./sessions.ts";
11
+
12
+ function str(v: unknown): string | undefined {
13
+ return typeof v === "string" && v !== "" ? v : undefined;
14
+ }
15
+
16
+ function num(v: unknown): number {
17
+ return typeof v === "number" && Number.isFinite(v) ? v : 0;
18
+ }
19
+
20
+ function usageOf(u: unknown): TraceUsage | undefined {
21
+ const o = asObj(u);
22
+ if (!o) return undefined;
23
+ const c = asObj(o.cost);
24
+ return {
25
+ input: num(o.input),
26
+ output: num(o.output),
27
+ cacheRead: num(o.cacheRead),
28
+ cacheWrite: num(o.cacheWrite),
29
+ totalTokens: num(o.totalTokens),
30
+ cost: c ? num(c.total) : 0,
31
+ };
32
+ }
33
+
34
+ function textOf(content: unknown): string {
35
+ if (typeof content === "string") return content;
36
+ if (!Array.isArray(content)) return "";
37
+ return content
38
+ .map((p) => (asObj(p)?.type === "text" ? String(asObj(p)?.text ?? "") : ""))
39
+ .filter((t) => t !== "")
40
+ .join("\n");
41
+ }
42
+
43
+ /** Every trace event in one session file, in file order. */
44
+ export function parseTraceFile(file: string, runId: string): TraceEvent[] {
45
+ let text: string;
46
+ try {
47
+ text = readFileSync(file, "utf8");
48
+ } catch {
49
+ return [];
50
+ }
51
+ const out: TraceEvent[] = [];
52
+ for (const line of text.split("\n")) {
53
+ if (!line.trim()) continue;
54
+ let parsed: unknown;
55
+ try {
56
+ parsed = JSON.parse(line);
57
+ } catch {
58
+ continue;
59
+ }
60
+ const d = asObj(parsed);
61
+ if (!d) continue;
62
+ const ts = typeof d.timestamp === "string" ? parseTs(d.timestamp) : null;
63
+ if (d.type === "model_change") {
64
+ out.push({ kind: "modelChange", ts, runId, model: str(d.model), provider: str(d.provider) });
65
+ continue;
66
+ }
67
+ if (d.type === "model_usage") {
68
+ const usage = usageOf(d.usage);
69
+ if (usage) out.push({ kind: "usage", ts, runId, model: str(d.model), provider: str(d.provider), usage });
70
+ continue;
71
+ }
72
+ const m = asObj(d.message) ?? (d.type === "message" || d.role ? d : null);
73
+ if (!m) continue;
74
+ const role = str(m.role);
75
+ const model = str(m.model);
76
+ const provider = str(m.provider);
77
+ const usage = usageOf(m.usage);
78
+ if (role === "assistant") {
79
+ const content = Array.isArray(m.content) ? m.content : [];
80
+ for (const part of content) {
81
+ const p = asObj(part);
82
+ if (!p) continue;
83
+ if (p.type === "text") {
84
+ const t = String(p.text ?? "");
85
+ if (t.trim()) out.push({ kind: "assistantText", ts, runId, text: t, model, provider, usage });
86
+ } else if (p.type === "toolCall") {
87
+ out.push({
88
+ kind: "toolCall",
89
+ ts,
90
+ runId,
91
+ tool: str(p.name) ?? "?",
92
+ args: asObj(p.arguments) ?? {},
93
+ model,
94
+ provider,
95
+ usage,
96
+ });
97
+ }
98
+ }
99
+ } else if (role === "toolResult") {
100
+ out.push({
101
+ kind: "toolResult",
102
+ ts,
103
+ runId,
104
+ tool: str(m.toolName) ?? "?",
105
+ isError: m.isError === true,
106
+ text: textOf(m.content),
107
+ usage,
108
+ });
109
+ }
110
+ }
111
+ return out;
112
+ }
113
+
114
+ /** Every run id with a trace under the root, each mapped to its newest file. */
115
+ export function ompTraceRuns(root: string): { runId: string; file: string; mtimeSec: number }[] {
116
+ const newest: Record<string, { file: string; mtimeSec: number }> = {};
117
+ for (const file of [...jsonlAt(root, 1), ...jsonlAt(root, 2)]) {
118
+ let mt: number;
119
+ try {
120
+ mt = statSync(file).mtimeMs;
121
+ } catch {
122
+ continue;
123
+ }
124
+ const mtimeSec = mt / 1000;
125
+ const id = runIdOf(file);
126
+ const prev = newest[id];
127
+ if (!prev || mtimeSec > prev.mtimeSec) newest[id] = { file, mtimeSec };
128
+ }
129
+ return Object.entries(newest).map(([runId, v]) => ({ runId, file: v.file, mtimeSec: v.mtimeSec }));
130
+ }
131
+
132
+ /** TraceSource over a sessions root: dated main files at depth 1, subagent files at depth 2. */
133
+ export function ompTraceSource(root: string): TraceSource {
134
+ return {
135
+ events(runId: string): TraceEvent[] {
136
+ const file = ompTraceRuns(root).find((r) => r.runId === runId)?.file;
137
+ return file ? parseTraceFile(file, runId) : [];
138
+ },
139
+ };
140
+ }
@@ -8,6 +8,7 @@ import { runInit } from "./init.ts";
8
8
  import { PORTED, runMain, runPorted } from "./commands.ts";
9
9
  import { runMetrics } from "./metrics.ts";
10
10
  import { runIncident } from "./incident.ts";
11
+ import { runTraces } from "./traces.ts";
11
12
  import { runUi } from "./ui.ts";
12
13
  import { runUninstall } from "../core/uninstall.ts";
13
14
  import { queueMigrate } from "../core/queue-migrate.ts";
@@ -61,6 +62,10 @@ export function helpText(): string {
61
62
  " neurastream main [args] run omp under the launcher (automatic session rollover)",
62
63
  " neurastream metrics <cmd> self-metrics: report, ci, false-alarm, rule (see README)",
63
64
  " neurastream incident <cmd> incidents Main must act on: list, add, plan, dismiss (see README)",
65
+ " neurastream traces claims <runId|--since 24h> [--json]",
66
+ " check a run's final-report claims (test counts, exit codes,",
67
+ " SHAs, heavy-run labels, changed paths) against the run's own",
68
+ " tool activity; unmatched ones print as claim-unbacked findings",
64
69
  " neurastream ui serve the owner's phone page on the tailnet address (ui.enabled, ui.owner_login)",
65
70
  " neurastream ui on --login <tailscale login> [--port N]",
66
71
  " one go: writes ui.enabled/owner_login (and port) into the config,",
@@ -86,6 +91,7 @@ export async function run(cmd: string, args: string[]): Promise<number> {
86
91
  if (cmd === "init") return runInit(args);
87
92
  if (cmd === "metrics") return runMetrics(args);
88
93
  if (cmd === "incident") return runIncident(args);
94
+ if (cmd === "traces") return runTraces(args);
89
95
  if (cmd === "ui") return runUi(args);
90
96
  if (cmd === "adapter") return runAdapterInstall(args);
91
97
  if (cmd === "config") {
package/src/cli/guard.ts CHANGED
@@ -44,6 +44,7 @@ function toolEvent(p: Record<string, unknown>): ToolEvent {
44
44
  paths: asStringList(p.paths),
45
45
  writes: asStringList(p.writes),
46
46
  command: asString(p.command),
47
+ ...(p.runningJobs === undefined ? {} : { runningJobs: asStringList(p.runningJobs) }),
47
48
  };
48
49
  }
49
50
 
@@ -59,7 +60,12 @@ function decide(event: string, p: Record<string, unknown>, cfg: Config): Decisio
59
60
  return checkInject(e, cfg);
60
61
  }
61
62
  case "spawn": {
62
- const e: SpawnEvent = { agent: asString(p.agent), invocationKind: asString(p.invocationKind, "task"), brief: asString(p.brief ?? p.context ?? p.task) };
63
+ const e: SpawnEvent = {
64
+ agent: asString(p.agent),
65
+ invocationKind: asString(p.invocationKind, "task"),
66
+ brief: asString(p.brief ?? p.context ?? p.task),
67
+ ...(p.runningJobs === undefined ? {} : { runningJobs: asStringList(p.runningJobs) }),
68
+ };
63
69
  return checkSpawn(e, cfg);
64
70
  }
65
71
  case "plan-edit": {