neurastream 0.2.12 → 0.2.14

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,239 @@
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
+ /**
130
+ * One related run's trace, passed by the caller (INCIDENT I-20261025-23): a Main run's report
131
+ * cites the results it received from its subagents, and that evidence sits in the subagents' own
132
+ * sessions, not Main's. The adapter owns file discovery — depth-2 session files under Main's
133
+ * session dir — core only checks the texts.
134
+ */
135
+ export interface RelatedRun {
136
+ /** The subagent run's trace run id — the agent name. */
137
+ name: string;
138
+ events: TraceEvent[];
139
+ }
140
+
141
+ /** Every string an args object carries (commands, paths, labels), joined for substring checks. */
142
+ function argsText(args: Record<string, unknown> | undefined): string {
143
+ const parts: string[] = [];
144
+ const walk = (v: unknown): void => {
145
+ if (typeof v === "string") parts.push(v);
146
+ else if (Array.isArray(v)) for (const x of v) walk(x);
147
+ else if (v !== null && typeof v === "object") for (const x of Object.values(v as object)) walk(x);
148
+ };
149
+ walk(args ?? {});
150
+ return parts.join("\n");
151
+ }
152
+
153
+ /**
154
+ * The claims of one run, read from its last assistant text — the final report. Runs with no
155
+ * assistant text at all claim nothing.
156
+ */
157
+ export function claimsFromEvents(events: TraceEvent[]): Claim[] {
158
+ for (let i = events.length - 1; i >= 0; i--) {
159
+ const e = events[i];
160
+ if (e?.kind === "assistantText" && e.text?.trim()) return extractClaims(e.text);
161
+ }
162
+ return [];
163
+ }
164
+
165
+ /**
166
+ * Checks each claim against the events of the same run:
167
+ * tests-passed / tests-failed / exit — the same result line in some toolResult's output;
168
+ * sha — printed in the output of the very git call whose result it answered in (the i-th
169
+ * toolResult pairs with the i-th toolCall; a sha echoed by a non-git tool while some other
170
+ * git call ran elsewhere is not backing);
171
+ * heavy-label — the label, quoted, in a heavy-run call the run actually made;
172
+ * changed-path — carried by an edit/write tool call's arguments, or written by a shell
173
+ * command (a write operator before the path in one command segment).
174
+ *
175
+ * `related` (a Main run's subagent traces) gives the result-line family a second chance: a
176
+ * count or exit claim nothing in the run's own output shows is still backed when a subagent's
177
+ * toolResult shows it (`how: "subagent:<name>"`) — Main's report cites the result it received.
178
+ * The other kinds keep their own-run shape checks (a sha needs its git pairing, a label the
179
+ * heavy-run call, a path the write), so only the pure result-line kinds cross runs.
180
+ */
181
+ export function verifyClaims(claims: Claim[], events: TraceEvent[], related: RelatedRun[] = []): ClaimVerdict[] {
182
+ const results = events.filter((e) => e.kind === "toolResult").map((e) => e.text ?? "");
183
+ const calls = events
184
+ .filter((e) => e.kind === "toolCall")
185
+ .map((e) => ({ tool: e.tool ?? "", args: argsText(e.args) }));
186
+ // The harness writes exactly one toolResult per toolCall, in order, so the i-th result
187
+ // pairs with the i-th call.
188
+ const paired = results.map((text, i) => ({ text, call: calls[i] }));
189
+ // Related-run backing: the same result-line test against every subagent's toolResults.
190
+ const subBacked = (c: Claim, test: (text: string) => boolean): ClaimVerdict | null => {
191
+ for (const r of related) {
192
+ if (r.events.some((e) => e.kind === "toolResult" && typeof e.text === "string" && test(e.text)))
193
+ return { claim: c, backed: true, how: `subagent:${r.name}` };
194
+ }
195
+ return null;
196
+ };
197
+ const verdict = (c: Claim): ClaimVerdict => {
198
+ const unbacked: ClaimVerdict = { claim: c, backed: false, how: "" };
199
+ switch (c.kind) {
200
+ case "tests-passed":
201
+ case "tests-failed": {
202
+ const word = c.kind === "tests-passed" ? "pass" : "fail";
203
+ const re = new RegExp(`\\b${c.count}\\s+${word}(?:ed)?\\b`, "i");
204
+ if (results.some((t) => re.test(t))) return { claim: c, backed: true, how: "count in a toolResult" };
205
+ return subBacked(c, (t) => re.test(t)) ?? unbacked;
206
+ }
207
+ case "exit": {
208
+ const re = new RegExp(`\\bexit(?:\\s+code)?\\s*[:=]?\\s*${c.count}\\b`, "i");
209
+ if (results.some((t) => re.test(t))) return { claim: c, backed: true, how: "exit line in a toolResult" };
210
+ return subBacked(c, (t) => re.test(t)) ?? unbacked;
211
+ }
212
+ case "sha":
213
+ if (paired.some((p) => p.call !== undefined && /\bgit\b/.test(p.call.args) && p.text.includes(c.value ?? "\u0000")))
214
+ return { claim: c, backed: true, how: "in a git command's output" };
215
+ return unbacked;
216
+ case "heavy-label":
217
+ if (calls.some((c2) => c2.args.includes("heavy-run") && c2.args.includes(`"${c.value}"`)))
218
+ return { claim: c, backed: true, how: "label in a heavy-run call" };
219
+ return unbacked;
220
+ case "changed-path": {
221
+ const v = c.value ?? "\u0000";
222
+ if (calls.some((c2) => /edit|write/i.test(c2.tool) && c2.args.includes(v)))
223
+ return { claim: c, backed: true, how: "path in an edit/write call" };
224
+ // Files agents create through the shell (`cat > f <<EOF`) are real changes; a
225
+ // write operator before the path inside one command segment backs the claim,
226
+ // a bare mention (grep, cat) does not.
227
+ const written = calls.some((c2) =>
228
+ c2.args.split(/\n|&&|\|\||[;|]/).some((seg) => {
229
+ const at = seg.indexOf(v);
230
+ return at >= 0 && SHELL_WRITE.test(seg.slice(0, at));
231
+ })
232
+ );
233
+ if (written) return { claim: c, backed: true, how: "path written by a shell command" };
234
+ return unbacked;
235
+ }
236
+ }
237
+ };
238
+ return claims.map(verdict);
239
+ }
@@ -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.
@@ -28,6 +28,7 @@ score:
28
28
  false-claim: 5
29
29
  rule-break: 2
30
30
  escaped-defect: 8
31
+ unreported-finding: 5
31
32
  diagnose_weight: 4
32
33
  gate_days: 7
33
34
  board_days: 7
@@ -107,6 +108,11 @@ guards:
107
108
  chat_unlock: false # the owner's whole chat message "unlock"/"unlock N"/"lock" moves the guard unlock file
108
109
  plan_read_max_hours: 24
109
110
  idle_stops: 3
111
+ rate_limit:
112
+ patterns: ["429", "rate_limit", "rate limit", "overloaded", "529"] # error-text substrings (case-insensitive) that mark a provider rate limit
113
+ default_wait_s: 300 # wait when the error text names no retry-after
114
+ max_wait_s: 3600 # cap for the parsed (or doubled) wait, before slack
115
+ slack_s: 15 # added on top of every wait
110
116
  blocker_timeout_ms: 10000
111
117
  skip_tools: [todo, wait, ask, web_search, job, cancel_job]
112
118
  read_tools: [read, grep, glob, find]
@@ -190,3 +196,26 @@ snapshot:
190
196
  - ".font-unix"
191
197
  - "snap-private-tmp"
192
198
  - "*.sock"
199
+
200
+ traces:
201
+ allowed_hosts: # hosts a network command may touch without a finding
202
+ - localhost
203
+ - 127.0.0.1
204
+ - "::1"
205
+ owned_repos: [] # product names another product's run may not read quietly; the intended list lives in docs/config.md
206
+ actions:
207
+ secret_globs: # a read matching any glob is a high finding; evidence is masked either way
208
+ - "~/.ssh/**"
209
+ - "**/*.env*"
210
+ - "**/*keys*.txt"
211
+ - "**/mcp.json"
212
+ - "**/keyring*/**"
213
+ - "**/.gnupg/**"
214
+ - "**/.password-store/**"
215
+ net_tools: [curl, wget, nc, ssh, scp] # commands that reach a host (word match inside shell tools)
216
+ shell_patterns: ['| sh', '| bash', 'eval "$('] # a command containing one feeds a shell from a pipe
217
+ write_roots: [] # prefixes a run may write (plan Worktree: roots); empty falls back to paths.work_roots; both empty = the scope check is off
218
+ deny_globs: # writes matching any glob are flagged wherever they land
219
+ - "~/.omp/**"
220
+ - "~/.local/bin/**"
221
+ - "~/.local/state/**"