neurastream 0.2.12 → 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.
@@ -50,6 +50,10 @@ export interface Plan {
50
50
  waiting: boolean;
51
51
  waitingLine: string | null;
52
52
  priorityId: string | null;
53
+ /** First level-1 "# " heading in the plan, else the file basename. */
54
+ title: string;
55
+ /** Bullet lines under "## Goal", capped at 6. */
56
+ goal: string[];
53
57
  errors: string[];
54
58
  }
55
59
 
@@ -179,7 +183,7 @@ function headerField(text: string, name: string): string | null {
179
183
  }
180
184
 
181
185
  export function parsePlan(repo: string, file: string, text: string | null, blockersDir = blockersDirPath()): Plan {
182
- const empty = { repo, file, text: "", status: null, blockers: [], doneCheck: null, worktree: null, branch: null, appliesTo: [], waiting: false, waitingLine: null, priorityId: null };
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: [] };
183
187
  if (text === null) return { ...empty, errors: ["plan file listed in the index does not exist"] };
184
188
  const errors: string[] = [];
185
189
  const secs = sections(text);
@@ -225,6 +229,8 @@ export function parsePlan(repo: string, file: string, text: string | null, block
225
229
  waiting: /^WAITING on owner:/m.test(text),
226
230
  waitingLine: text.match(/^WAITING on owner:[ \t]*(.*)$/m)?.[1] ?? null,
227
231
  priorityId: text.match(/^PRIORITY-ID:\s*`?([A-Z]{2}[0-9]{2})`?/m)?.[1] ?? null,
232
+ title: text.match(/^# (.+)$/m)?.[1]?.trim() || path.basename(file),
233
+ goal: items(secs.get("goal") ?? "").slice(0, 6),
228
234
  errors,
229
235
  };
230
236
  }
@@ -829,20 +835,20 @@ export function queueProblems(index = INDEX, blockersDir = BLOCKERS_DIR): QueueP
829
835
  }
830
836
 
831
837
  export function queueSummary(index = INDEX): string {
838
+ // Index order IS priority (20261025_0215_index_priority): the list is flat and ranked,
839
+ // rank 1 = the index's top line; repos only surface through each plan's own path.
832
840
  const plans = activePlans(index);
833
841
  const repos = [...new Set(plans.map(p => p.repo))];
834
842
  const lines = [`Queue (${index}): ${plans.length ? `${plans.length} plan(s) in ${repos.length} repo(s)` : "empty, no open work"}`];
835
- for (const repo of repos) {
836
- const nCancelled = readCancelled(repo).length;
837
- lines.push(`- ${repo}${nCancelled ? ` (${nCancelled} cancelled)` : ""}`);
838
- for (const p of plans.filter(pl => pl.repo === repo)) {
839
- const status = awaitingMerge(p) ? "complete, awaiting merge" : (p.status ?? "INVALID");
840
- const hold = p.waiting ? `WAITING on owner: ${(p.waitingLine ?? "").slice(0, 80)}` : "";
841
- const flags = [status, hold, p.priorityId ?? ""].filter(Boolean).join(", ");
842
- const goal = items(sections(p.text).get("goal") ?? "")[0]?.slice(0, 100) ?? "";
843
- lines.push(` - ${p.file} [${flags}] ${goal}`);
844
- }
845
- }
843
+ plans.forEach((p, i) => {
844
+ const status = awaitingMerge(p) ? "complete, awaiting merge" : (p.status ?? "INVALID");
845
+ const hold = p.waiting ? `WAITING on owner: ${(p.waitingLine ?? "").slice(0, 80)}` : "";
846
+ const flags = [status, hold, p.priorityId ?? ""].filter(Boolean).join(", ");
847
+ const goal = items(sections(p.text).get("goal") ?? "")[0]?.slice(0, 100) ?? "";
848
+ lines.push(` ${i + 1}. ${p.file} [${flags}] ${goal}`);
849
+ });
850
+ const nCancelled = repos.reduce((n, repo) => n + readCancelled(repo).length, 0);
851
+ if (nCancelled) lines.push(`Cancelled rules: ${nCancelled}`);
846
852
  const probs = queueProblems(index);
847
853
  if (probs.length) lines.push(`Problems (fix first):`, ...probs.map(q => ` - ${q.where}: ${q.problem}`));
848
854
  return lines.join("\n");
@@ -0,0 +1,212 @@
1
+ // Claim extraction (plan 20261024_0300 P2): what an agent's final report CLAIMS happened —
2
+ // test result counts, exit codes, commit SHAs, heavy-run labels, changed file paths. Pure text
3
+ // in, claims out; the P3 verifier matches each claim against TraceEvents of the same run and
4
+ // turns unmatched claims into findings. Evidence is capped at 160 chars and long token-like
5
+ // runs are masked, so a claim line can never carry a secret into findings or logs.
6
+
7
+ import type { TraceEvent } from "./adapter.ts";
8
+
9
+ export type ClaimKind =
10
+ | "tests-passed"
11
+ | "tests-failed"
12
+ | "exit"
13
+ | "sha"
14
+ | "heavy-label"
15
+ | "changed-path";
16
+
17
+ export interface Claim {
18
+ kind: ClaimKind;
19
+ /** tests-passed / tests-failed: the claimed count; exit: the claimed exit code. */
20
+ count?: number;
21
+ /** sha: the commit SHA; heavy-label: the label text; changed-path: the path. */
22
+ value?: string;
23
+ /** At most 160 chars of the claiming line, token-masked. */
24
+ evidence: string;
25
+ }
26
+
27
+ const TOKEN_MASK = /[A-Za-z0-9_-]{24,}/g;
28
+ const EVIDENCE_MAX = 160;
29
+
30
+ /** Mask long token-like runs (they may be credentials) and cap the length. */
31
+ export function maskEvidence(line: string): string {
32
+ return line.replace(TOKEN_MASK, "[masked]").slice(0, EVIDENCE_MAX);
33
+ }
34
+
35
+ // "pass"/"fail" with or without "ed" so both prose ("530 passed") and test-runner summary
36
+ // lines ("3 pass / 0 fail") are claimed; "passing"/"failing" have no word boundary and are not.
37
+ const PASSED = /(\d+)\s+pass(?:ed)?\b/gi;
38
+ const FAILED = /(\d+)\s+fail(?:ed)?\b/gi;
39
+ const EXIT = /\bexit(?:\s+code)?\s*[:=]?\s*(\d+)\b/gi;
40
+ // Lowercase hex, 7 (git short) to 40 (full); at least one a-f letter keeps numeric counts out.
41
+ const SHA = /\b[0-9a-f]{7,40}\b/g;
42
+ // heavy-run <agent> "<label>" — the quoted label is the claim (both bin spellings).
43
+ const HEAVY_LABEL = /heavy-run(?:\.sh)?\s+\S+\s+"([^"]+)"/;
44
+ // "3. Run `heavy-run.sh agent \"x full\" …`" is a next-step instruction, not a claim that the
45
+ // label ran (P4 smoke: an agent's numbered TODO list read as label claims).
46
+ const INSTRUCTION = /^\s*\d+[.)]\s+(?:run|execute|start|kick off)\b/i;
47
+ // A path only counts as "changed" on a line that says a change happened; the token must end in
48
+ // a file extension so branch names (feat/x) and prose never become path claims. The extension
49
+ // must be a real one: the P4 smoke flagged dotted API symbols (`Bun.sleep`, `os.remove`,
50
+ // `entry.kind`) and emails (`x@y.z`) because any `.word` looked like an extension.
51
+ const CHANGE_VERB = /\b(chang|commit|edit|writ|updat|creat|add|remov|delet|fix|touch|modif|refactor|migrat)/i;
52
+ const EXTENSIONS: Record<string, true> = {
53
+ ts: true, tsx: true, mts: true, cts: true, js: true, jsx: true, mjs: true, cjs: true,
54
+ json: true, jsonl: true, md: true, mdx: true, txt: true, yml: true, yaml: true, toml: true,
55
+ sh: true, bash: true, zsh: true, py: true, pyi: true, rb: true, go: true, rs: true,
56
+ java: true, kt: true, swift: true, c: true, h: true, cpp: true, hpp: true, cc: true,
57
+ hh: true, cs: true, php: true, lua: true, sql: true, html: true, htm: true, css: true,
58
+ scss: true, xml: true, csv: true, tsv: true, ini: true, cfg: true, conf: true, env: true,
59
+ lock: true, service: true, socket: true, timer: true, patch: true, diff: true,
60
+ };
61
+ const PATH_TOKEN = /(?:[\w@.-]+\/)*[\w@.-]+\.[A-Za-z][A-Za-z0-9]{0,7}\b/g;
62
+ // A shell segment writes a file when one of these operators precedes the path: redirection,
63
+ // heredoc, tee/touch/cp/mv. A bare mention (grep, cat) never writes.
64
+ const SHELL_WRITE = /(?:>>?|<<|\btee\b|\btouch\b|\bcp\b|\bmv\b)/;
65
+
66
+ /**
67
+ * A hex run glued into a longer identifier is not a commit reference: hyphen-joined hex is a
68
+ * session-UUID fragment (`…_01a16feb-3a5d-…jsonl`), a hyphen/colon-joined preceding identifier
69
+ * is a catalog id (`…-accounts-991b4d35`) or a digest (`sha256:e61c0a9d2f47…`). Found in the
70
+ * P4 smoke over real sessions (a report citing its own session file name; pipeline catalog
71
+ * ids and digests quoted in a final report).
72
+ */
73
+ function joinedFragment(line: string, at: number, match: string): boolean {
74
+ const after = line.slice(at + match.length);
75
+ if (after.startsWith("-") && /^[0-9a-f]/i.test(after.slice(1))) return true;
76
+ const glued = line[at - 1];
77
+ if ((glued === "-" || glued === ":") && /[A-Za-z0-9]{2,}$/i.test(line.slice(0, at - 1))) return true;
78
+ return false;
79
+ }
80
+
81
+ /** Every verifiable claim in one final-report text, in order of appearance, deduped. */
82
+ export function extractClaims(text: string): Claim[] {
83
+ const out: Claim[] = [];
84
+ const seen = new Set<string>();
85
+ for (const raw of text.split("\n")) {
86
+ if (!raw.trim()) continue;
87
+ // Claims are read from the raw line (masking must not eat real SHAs); only the stored
88
+ // evidence is masked and capped.
89
+ const evidence = maskEvidence(raw);
90
+ const push = (c: Omit<Claim, "evidence">) => {
91
+ const key = `${c.kind}:${c.count ?? ""}:${c.value ?? ""}`;
92
+ if (seen.has(key)) return;
93
+ seen.add(key);
94
+ out.push({ ...c, evidence });
95
+ };
96
+ for (const m of raw.matchAll(PASSED)) push({ kind: "tests-passed", count: Number(m[1]) });
97
+ for (const m of raw.matchAll(FAILED)) push({ kind: "tests-failed", count: Number(m[1]) });
98
+ for (const m of raw.matchAll(EXIT)) push({ kind: "exit", count: Number(m[1]) });
99
+ for (const m of raw.matchAll(SHA)) {
100
+ if (!/[a-f]/.test(m[0])) continue; // digit-only runs are counts, not SHAs
101
+ if (joinedFragment(raw, m.index!, m[0])) continue; // session UUIDs, catalog ids and digests are not SHAs
102
+ push({ kind: "sha", value: m[0] });
103
+ }
104
+ if (!INSTRUCTION.test(raw)) {
105
+ const label = HEAVY_LABEL.exec(raw);
106
+ if (label) push({ kind: "heavy-label", value: label[1] });
107
+ }
108
+ if (CHANGE_VERB.test(raw)) {
109
+ for (const m of raw.matchAll(PATH_TOKEN)) {
110
+ if (m[0].includes("@")) continue; // emails and npm scopes are not files
111
+ if (!EXTENSIONS[m[0].slice(m[0].lastIndexOf(".") + 1).toLowerCase()]) continue;
112
+ push({ kind: "changed-path", value: m[0] });
113
+ }
114
+ }
115
+ }
116
+ return out;
117
+ }
118
+
119
+ // ---- P3 verifier: every claim must be backed by the same run's tool activity ----
120
+
121
+ /** One claim's check result; backed verdicts carry where the proof was found. */
122
+ export interface ClaimVerdict {
123
+ claim: Claim;
124
+ backed: boolean;
125
+ /** Where the proof came from, "" when unbacked. */
126
+ how: string;
127
+ }
128
+
129
+ /** Every string an args object carries (commands, paths, labels), joined for substring checks. */
130
+ function argsText(args: Record<string, unknown> | undefined): string {
131
+ const parts: string[] = [];
132
+ const walk = (v: unknown): void => {
133
+ if (typeof v === "string") parts.push(v);
134
+ else if (Array.isArray(v)) for (const x of v) walk(x);
135
+ else if (v !== null && typeof v === "object") for (const x of Object.values(v as object)) walk(x);
136
+ };
137
+ walk(args ?? {});
138
+ return parts.join("\n");
139
+ }
140
+
141
+ /**
142
+ * The claims of one run, read from its last assistant text — the final report. Runs with no
143
+ * assistant text at all claim nothing.
144
+ */
145
+ export function claimsFromEvents(events: TraceEvent[]): Claim[] {
146
+ for (let i = events.length - 1; i >= 0; i--) {
147
+ const e = events[i];
148
+ if (e?.kind === "assistantText" && e.text?.trim()) return extractClaims(e.text);
149
+ }
150
+ return [];
151
+ }
152
+
153
+ /**
154
+ * Checks each claim against the events of the same run:
155
+ * tests-passed / tests-failed / exit — the same result line in some toolResult's output;
156
+ * sha — printed in the output of the very git call whose result it answered in (the i-th
157
+ * toolResult pairs with the i-th toolCall; a sha echoed by a non-git tool while some other
158
+ * git call ran elsewhere is not backing);
159
+ * heavy-label — the label, quoted, in a heavy-run call the run actually made;
160
+ * changed-path — carried by an edit/write tool call's arguments, or written by a shell
161
+ * command (a write operator before the path in one command segment).
162
+ */
163
+ export function verifyClaims(claims: Claim[], events: TraceEvent[]): ClaimVerdict[] {
164
+ const results = events.filter((e) => e.kind === "toolResult").map((e) => e.text ?? "");
165
+ const calls = events
166
+ .filter((e) => e.kind === "toolCall")
167
+ .map((e) => ({ tool: e.tool ?? "", args: argsText(e.args) }));
168
+ // The harness writes exactly one toolResult per toolCall, in order, so the i-th result
169
+ // pairs with the i-th call.
170
+ const paired = results.map((text, i) => ({ text, call: calls[i] }));
171
+ const verdict = (c: Claim): ClaimVerdict => {
172
+ const unbacked: ClaimVerdict = { claim: c, backed: false, how: "" };
173
+ switch (c.kind) {
174
+ case "tests-passed":
175
+ case "tests-failed": {
176
+ const word = c.kind === "tests-passed" ? "pass" : "fail";
177
+ if (results.some((t) => new RegExp(`\\b${c.count}\\s+${word}(?:ed)?\\b`, "i").test(t)))
178
+ return { claim: c, backed: true, how: "count in a toolResult" };
179
+ return unbacked;
180
+ }
181
+ case "exit":
182
+ if (results.some((t) => new RegExp(`\\bexit(?:\\s+code)?\\s*[:=]?\\s*${c.count}\\b`, "i").test(t)))
183
+ return { claim: c, backed: true, how: "exit line in a toolResult" };
184
+ return unbacked;
185
+ case "sha":
186
+ if (paired.some((p) => p.call !== undefined && /\bgit\b/.test(p.call.args) && p.text.includes(c.value ?? "\u0000")))
187
+ return { claim: c, backed: true, how: "in a git command's output" };
188
+ return unbacked;
189
+ case "heavy-label":
190
+ if (calls.some((c2) => c2.args.includes("heavy-run") && c2.args.includes(`"${c.value}"`)))
191
+ return { claim: c, backed: true, how: "label in a heavy-run call" };
192
+ return unbacked;
193
+ case "changed-path": {
194
+ const v = c.value ?? "\u0000";
195
+ if (calls.some((c2) => /edit|write/i.test(c2.tool) && c2.args.includes(v)))
196
+ return { claim: c, backed: true, how: "path in an edit/write call" };
197
+ // Files agents create through the shell (`cat > f <<EOF`) are real changes; a
198
+ // write operator before the path inside one command segment backs the claim,
199
+ // a bare mention (grep, cat) does not.
200
+ const written = calls.some((c2) =>
201
+ c2.args.split(/\n|&&|\|\||[;|]/).some((seg) => {
202
+ const at = seg.indexOf(v);
203
+ return at >= 0 && SHELL_WRITE.test(seg.slice(0, at));
204
+ })
205
+ );
206
+ if (written) return { claim: c, backed: true, how: "path written by a shell command" };
207
+ return unbacked;
208
+ }
209
+ }
210
+ };
211
+ return claims.map(verdict);
212
+ }
@@ -4,6 +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
8
  - Entering a repo: read its AGENTS.md first.
8
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.
9
10
  - Phase 0 of every plan: blocker scripts that stop the implementer from going against the plan. They must exist before any spawn.