neurastream 0.2.13 → 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.
- package/README.md +14 -0
- package/package.json +1 -1
- package/src/adapters/omp/index.ts +122 -4
- package/src/adapters/omp/install.ts +14 -7
- package/src/adapters/omp/traces.ts +27 -0
- package/src/cli/dispatch.ts +5 -0
- package/src/cli/traces.ts +64 -22
- package/src/core/agent-score.ts +7 -0
- package/src/core/config.ts +36 -0
- package/src/core/guards.ts +6 -5
- package/src/core/incident-detectors.ts +59 -5
- package/src/core/incidents.ts +2 -2
- package/src/core/rate-limit.ts +63 -0
- package/src/core/trace-actions.ts +487 -0
- package/src/core/trace-claims.ts +35 -8
- package/templates/config.yml +29 -0
|
@@ -13,6 +13,11 @@
|
|
|
13
13
|
// D4 owner-correction: an owner message matching the M4 correction patterns.
|
|
14
14
|
// D5 claim-unbacked: a run's final report claims something its own tool output never
|
|
15
15
|
// showed (gathered by the traces claims CLI, src/cli/traces.ts).
|
|
16
|
+
// D6 suspicious-action: a high-severity suspicious tool action the run's trace shows
|
|
17
|
+
// (gathered by the traces actions CLI, src/cli/traces.ts).
|
|
18
|
+
// D7 unreported-finding: a subagent run read files of another owned repo (config
|
|
19
|
+
// traces.owned_repos) while its final report says "Findings: none"; folds as source
|
|
20
|
+
// "traces" and records an agent-score penalty event for that agent on the plan.
|
|
16
21
|
|
|
17
22
|
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
18
23
|
import { dirname, join } from "node:path";
|
|
@@ -23,7 +28,9 @@ import { nowSec, strftime } from "./clock.ts";
|
|
|
23
28
|
import { log } from "./guards.ts";
|
|
24
29
|
import { addIncident, type IncidentView } from "./incidents.ts";
|
|
25
30
|
import type { GuardBlock } from "./metrics.ts";
|
|
26
|
-
import { verifyClaims, type Claim } from "./trace-claims.ts";
|
|
31
|
+
import { verifyClaims, type Claim, type RelatedRun } from "./trace-claims.ts";
|
|
32
|
+
import { recordPenalty } from "./agent-score.ts";
|
|
33
|
+
import type { SuspiciousAction, UnreportedFinding } from "./trace-actions.ts";
|
|
27
34
|
|
|
28
35
|
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
29
36
|
|
|
@@ -149,12 +156,14 @@ export function ownerCorrection(text: string, patterns: RegExp[], now: number):
|
|
|
149
156
|
/**
|
|
150
157
|
* Final-report claims (src/core/trace-claims.ts) with no backing activity in the same run's
|
|
151
158
|
* 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.
|
|
153
|
-
*
|
|
159
|
+
* to a heavy-run call, a path no edit/write call carried. `related` — the traces of the
|
|
160
|
+
* subagent runs under a Main run's session dir (INCIDENT I-20261025-23) — backs the pure
|
|
161
|
+
* result-line claims Main's report cites from its subagents. Evidence is the claiming line,
|
|
162
|
+
* which the extractor already masked and capped, so nothing secret reaches the incident store.
|
|
154
163
|
*/
|
|
155
|
-
export function claimUnbacked(claims: Claim[], events: TraceEvent[]): Finding[] {
|
|
164
|
+
export function claimUnbacked(claims: Claim[], events: TraceEvent[], related: RelatedRun[] = []): Finding[] {
|
|
156
165
|
const out: Finding[] = [];
|
|
157
|
-
for (const v of verifyClaims(claims, events)) {
|
|
166
|
+
for (const v of verifyClaims(claims, events, related)) {
|
|
158
167
|
if (v.backed) continue;
|
|
159
168
|
const c = v.claim;
|
|
160
169
|
const what = c.count !== undefined ? `${c.kind} ${c.count}` : `${c.kind} ${c.value ?? ""}`;
|
|
@@ -168,6 +177,25 @@ export function claimUnbacked(claims: Claim[], events: TraceEvent[]): Finding[]
|
|
|
168
177
|
return out;
|
|
169
178
|
}
|
|
170
179
|
|
|
180
|
+
// ---- D6: a high-severity suspicious tool action ----
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Suspicious tool actions (src/core/trace-actions.ts) at severity high: secret-path reads and
|
|
184
|
+
* exfil-shaped network commands. Medium and low findings stay in the `traces actions` report;
|
|
185
|
+
* only the ones worth waking the owner for become incidents. Evidence is already masked and
|
|
186
|
+
* capped by the rule engine, so nothing secret reaches the incident store.
|
|
187
|
+
*/
|
|
188
|
+
export function suspiciousAction(actions: SuspiciousAction[]): Finding[] {
|
|
189
|
+
return actions
|
|
190
|
+
.filter((a) => a.severity === "high")
|
|
191
|
+
.map((a) => ({
|
|
192
|
+
kind: "suspicious-action",
|
|
193
|
+
summary: `${a.runId}: ${a.summary}`,
|
|
194
|
+
evidence: a.evidence,
|
|
195
|
+
fingerprint: `suspicious-action:${a.rule}:${a.target}`,
|
|
196
|
+
}));
|
|
197
|
+
}
|
|
198
|
+
|
|
171
199
|
// ---- the runner ----
|
|
172
200
|
|
|
173
201
|
/** The plain inputs the callers gather; a detector without its input does not run. */
|
|
@@ -184,6 +212,10 @@ export interface DetectorInput {
|
|
|
184
212
|
/** D5: one run's final-report claims plus the same run's trace events (the traces CLI gathers both). */
|
|
185
213
|
claims?: Claim[];
|
|
186
214
|
events?: TraceEvent[];
|
|
215
|
+
/** D6: suspicious tool actions from one or more scanned runs (the traces actions CLI gathers them). */
|
|
216
|
+
actions?: SuspiciousAction[];
|
|
217
|
+
/** D7: cross-product reads a subagent run hid behind a Findings: none line (src/core/trace-actions.ts). */
|
|
218
|
+
unreported?: UnreportedFinding[];
|
|
187
219
|
}
|
|
188
220
|
|
|
189
221
|
/**
|
|
@@ -231,6 +263,28 @@ export function runDetectors(cfg: Config, input: DetectorInput, now = nowSec()):
|
|
|
231
263
|
if (input.claims && input.events) {
|
|
232
264
|
attempt("claim-unbacked", () => claimUnbacked(input.claims!, input.events!));
|
|
233
265
|
}
|
|
266
|
+
if (input.actions) {
|
|
267
|
+
attempt("suspicious-action", () => suspiciousAction(input.actions!));
|
|
268
|
+
}
|
|
269
|
+
if (input.unreported) {
|
|
270
|
+
for (const f of input.unreported!) {
|
|
271
|
+
try {
|
|
272
|
+
const { incident, deduped } = addIncident(
|
|
273
|
+
cfg,
|
|
274
|
+
{ source: "traces", kind: "unreported-finding", summary: f.summary, evidence: f.evidence, fingerprint: `unreported-finding:${f.agent}:${f.target}` },
|
|
275
|
+
now,
|
|
276
|
+
);
|
|
277
|
+
if (!deduped) recordPenalty(cfg, { agent: f.agent, kind: "unreported-finding", plan: f.plan, note: f.summary });
|
|
278
|
+
log(
|
|
279
|
+
cfg.paths.guard_log,
|
|
280
|
+
`incident ${incident.id} [traces/${incident.kind}]${deduped ? ` sighting #${incident.count}` : " opened"}: ${incident.summary}`,
|
|
281
|
+
);
|
|
282
|
+
out.push(incident);
|
|
283
|
+
} catch (err) {
|
|
284
|
+
log(cfg.paths.guard_log, `detector unreported-finding failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|
|
234
288
|
return out;
|
|
235
289
|
}
|
|
236
290
|
|
package/src/core/incidents.ts
CHANGED
|
@@ -14,7 +14,7 @@ import { nowSec, strftime } from "./clock.ts";
|
|
|
14
14
|
import type { Config } from "./config.ts";
|
|
15
15
|
import * as q from "./queue/lib.ts";
|
|
16
16
|
|
|
17
|
-
export type IncidentSource = "realtime" | "daily" | "weekly" | "main" | "findings";
|
|
17
|
+
export type IncidentSource = "realtime" | "daily" | "weekly" | "main" | "findings" | "traces";
|
|
18
18
|
|
|
19
19
|
export interface IncidentRec {
|
|
20
20
|
id: string;
|
|
@@ -80,7 +80,7 @@ function parseLine(line: string): IncidentRec | ResolutionRec | null {
|
|
|
80
80
|
if (rec.type !== undefined) return null;
|
|
81
81
|
if (typeof rec.fingerprint !== "string" || typeof rec.kind !== "string" || typeof rec.summary !== "string" || typeof rec.ts !== "number")
|
|
82
82
|
return null;
|
|
83
|
-
const source = rec.source === "realtime" || rec.source === "daily" || rec.source === "weekly" || rec.source === "findings" ? rec.source : "main";
|
|
83
|
+
const source = rec.source === "realtime" || rec.source === "daily" || rec.source === "weekly" || rec.source === "findings" || rec.source === "traces" ? rec.source : "main";
|
|
84
84
|
return {
|
|
85
85
|
id: rec.id,
|
|
86
86
|
fingerprint: rec.fingerprint,
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// Provider rate limits (plan 20261025_0640): a turn that ended on one waits it out instead of
|
|
2
|
+
// asking again straight into the limit. Pure decisions only: what counts as a rate limit, and how
|
|
3
|
+
// long to wait. The words and the waits come from config (guards.rate_limit); the adapter supplies
|
|
4
|
+
// the turn's stop reason and error text and arms the timer.
|
|
5
|
+
|
|
6
|
+
export interface RateLimitConfig {
|
|
7
|
+
/** Case-insensitive substrings in the error text that mark a rate limit. */
|
|
8
|
+
patterns: string[];
|
|
9
|
+
/** Wait when the error text names no retry-after. */
|
|
10
|
+
default_wait_s: number;
|
|
11
|
+
/** Cap for the parsed (or doubled) wait, before slack. */
|
|
12
|
+
max_wait_s: number;
|
|
13
|
+
/** Added on top of every wait. */
|
|
14
|
+
slack_s: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface RateLimitWait {
|
|
18
|
+
/** Epoch ms when the next turn should start. */
|
|
19
|
+
untilMs: number;
|
|
20
|
+
/** Total wait in ms, slack included. */
|
|
21
|
+
waitMs: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const RETRY_AFTER_MS = /retry-after-ms[=:]\s*(\d+)/i;
|
|
25
|
+
const RETRY_AFTER_S = /retry-after[=:]\s*(\d+)/i;
|
|
26
|
+
|
|
27
|
+
function retryAfterMs(errorText: string, cfg: RateLimitConfig): number {
|
|
28
|
+
const ms = RETRY_AFTER_MS.exec(errorText);
|
|
29
|
+
if (ms) return Number(ms[1]);
|
|
30
|
+
const s = RETRY_AFTER_S.exec(errorText);
|
|
31
|
+
if (s) return Number(s[1]) * 1000;
|
|
32
|
+
return cfg.default_wait_s * 1000;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The wait for a turn that ended on a provider rate limit, or null when it did not: the stop
|
|
37
|
+
* reason must be "error" and the error text must contain one of the configured patterns
|
|
38
|
+
* (case-insensitive). The wait is the retry-after the text names (`retry-after-ms=<ms>` or
|
|
39
|
+
* `retry-after: <seconds>`, else default_wait_s); attempt >= 2 doubles the previous wait of the
|
|
40
|
+
* episode; every wait is clamped to max_wait_s, then slack_s is added.
|
|
41
|
+
*/
|
|
42
|
+
export function rateLimitWait(
|
|
43
|
+
stopReason: string | null,
|
|
44
|
+
errorText: string | null,
|
|
45
|
+
now: number,
|
|
46
|
+
cfg: RateLimitConfig,
|
|
47
|
+
attempt: number,
|
|
48
|
+
): RateLimitWait | null {
|
|
49
|
+
if (stopReason !== "error" || !errorText) return null;
|
|
50
|
+
const text = errorText.toLowerCase();
|
|
51
|
+
if (!cfg.patterns.some(p => text.includes(p.toLowerCase()))) return null;
|
|
52
|
+
const capMs = cfg.max_wait_s * 1000;
|
|
53
|
+
let baseMs = retryAfterMs(errorText, cfg);
|
|
54
|
+
for (let i = 1; i < Math.max(1, attempt); i++) {
|
|
55
|
+
baseMs *= 2;
|
|
56
|
+
if (baseMs >= capMs) {
|
|
57
|
+
baseMs = capMs;
|
|
58
|
+
break;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const waitMs = Math.min(baseMs, capMs) + cfg.slack_s * 1000;
|
|
62
|
+
return { untilMs: now + waitMs, waitMs };
|
|
63
|
+
}
|
|
@@ -0,0 +1,487 @@
|
|
|
1
|
+
// Suspicious tool actions (plan 20261024_0301 P1): flags the trace activity an owner reads as
|
|
2
|
+
// hostile — reads of secret paths, network commands to hosts outside the allow list, writes
|
|
3
|
+
// outside the plan worktree roots or onto deny paths, and shells fed from a pipe. Every list
|
|
4
|
+
// comes from config (`traces.*`, plus the guard shell/write tool names), so owners tune the
|
|
5
|
+
// rules without touching code. Evidence is masked and capped by the shared claim masker, so a
|
|
6
|
+
// finding line can never carry a secret value into the CLI, a log or the incident store.
|
|
7
|
+
|
|
8
|
+
import type { TraceEvent } from "./adapter.ts";
|
|
9
|
+
import type { Config } from "./config.ts";
|
|
10
|
+
import { maskEvidence } from "./trace-claims.ts";
|
|
11
|
+
|
|
12
|
+
export type ActionSeverity = "high" | "medium" | "low";
|
|
13
|
+
|
|
14
|
+
export type ActionRule = "secret-read" | "net-unknown-host" | "write-out-of-scope" | "pipe-to-shell";
|
|
15
|
+
|
|
16
|
+
export interface ActionsRules {
|
|
17
|
+
home: string;
|
|
18
|
+
secret_globs: string[];
|
|
19
|
+
net_tools: string[];
|
|
20
|
+
allowed_hosts: string[];
|
|
21
|
+
/** Prefixes a run may write (plan `Worktree:` roots); empty falls back to paths.work_roots; both empty = the scope check is off. */
|
|
22
|
+
write_roots: string[];
|
|
23
|
+
deny_globs: string[];
|
|
24
|
+
/** Substrings that mean a shell is fed from a pipe. */
|
|
25
|
+
shell_patterns: string[];
|
|
26
|
+
shell_tools: string[];
|
|
27
|
+
write_tools: string[];
|
|
28
|
+
/** Product names (config `traces.owned_repos`) whose files another product's run may not read quietly. */
|
|
29
|
+
owned_repos: string[];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface SuspiciousAction {
|
|
33
|
+
rule: ActionRule;
|
|
34
|
+
severity: ActionSeverity;
|
|
35
|
+
runId: string;
|
|
36
|
+
ts: number | null;
|
|
37
|
+
tool: string;
|
|
38
|
+
/** Short human sentence; safe for an incident summary. */
|
|
39
|
+
summary: string;
|
|
40
|
+
/** Masked and capped command/args text. */
|
|
41
|
+
evidence: string;
|
|
42
|
+
/** Host (net), matched path (secret/write) or shell pattern (pipe); fingerprint material. */
|
|
43
|
+
target: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Maps config onto the rule set: the `traces.*` lists plus the guard shell/write tool names. */
|
|
47
|
+
export function actionsRules(cfg: Config): ActionsRules {
|
|
48
|
+
const write_roots = cfg.traces.actions.write_roots.length > 0 ? cfg.traces.actions.write_roots : cfg.paths.work_roots;
|
|
49
|
+
return {
|
|
50
|
+
home: cfg.paths.home,
|
|
51
|
+
secret_globs: cfg.traces.actions.secret_globs,
|
|
52
|
+
net_tools: cfg.traces.actions.net_tools,
|
|
53
|
+
allowed_hosts: cfg.traces.allowed_hosts,
|
|
54
|
+
write_roots,
|
|
55
|
+
deny_globs: cfg.traces.actions.deny_globs,
|
|
56
|
+
shell_patterns: cfg.traces.actions.shell_patterns,
|
|
57
|
+
shell_tools: cfg.guards.shell_tools,
|
|
58
|
+
write_tools: cfg.guards.write_tools,
|
|
59
|
+
owned_repos: cfg.traces.owned_repos,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Glob match for the config path lists: a double star followed by a slash is any directory
|
|
65
|
+
* prefix (including none), a bare double star is anything, a star is anything but a slash
|
|
66
|
+
* with leading dots included, a question mark is one non-slash. A leading tilde or `$HOME`
|
|
67
|
+
* on either side expands to the configured home.
|
|
68
|
+
*/
|
|
69
|
+
export function globMatch(pattern: string, candidate: string, home: string): boolean {
|
|
70
|
+
const expand = (p: string): string => {
|
|
71
|
+
if (p === "~" || p === "$HOME") return home;
|
|
72
|
+
if (p.startsWith("~/")) return home + p.slice(1);
|
|
73
|
+
if (p.startsWith("$HOME/")) return home + p.slice(5);
|
|
74
|
+
return p;
|
|
75
|
+
};
|
|
76
|
+
const pat = expand(pattern);
|
|
77
|
+
let re = "";
|
|
78
|
+
for (let i = 0; i < pat.length; i++) {
|
|
79
|
+
const c = pat[i]!;
|
|
80
|
+
if (c === "*") {
|
|
81
|
+
if (pat[i + 1] === "*") {
|
|
82
|
+
if (pat[i + 2] === "/") {
|
|
83
|
+
re += "(?:.*/)?";
|
|
84
|
+
i += 2;
|
|
85
|
+
} else {
|
|
86
|
+
re += ".*";
|
|
87
|
+
i += 1;
|
|
88
|
+
}
|
|
89
|
+
} else {
|
|
90
|
+
re += "[^/]*";
|
|
91
|
+
}
|
|
92
|
+
} else if (c === "?") {
|
|
93
|
+
re += "[^/]";
|
|
94
|
+
} else {
|
|
95
|
+
re += c.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return new RegExp(`^${re}$`).test(expand(candidate));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function expandHome(p: string, home: string): string {
|
|
102
|
+
if (p === "~" || p === "$HOME") return home;
|
|
103
|
+
if (p.startsWith("~/")) return home + p.slice(1);
|
|
104
|
+
if (p.startsWith("$HOME/")) return home + p.slice(5);
|
|
105
|
+
return p;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Trim shell noise (quotes, `;`, the `)` closing a `$(...)`) off a whitespace token without touching glob stars. */
|
|
109
|
+
function bareWord(raw: string): string {
|
|
110
|
+
return raw.replace(/^[\s'"`]+|[\s'"`;)]+$/g, "");
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Characters that never appear in a file path but do in code, jq/grep patterns and URL fragments. */
|
|
114
|
+
const NOT_A_PATH = /[()[\]{}|\\^<>"`]/;
|
|
115
|
+
|
|
116
|
+
/** Path-like words of one command string: with a slash, or dotfiles, or home-relative. */
|
|
117
|
+
function pathTokens(command: string): string[] {
|
|
118
|
+
const out: string[] = [];
|
|
119
|
+
for (const raw of command.split(/\s+/)) {
|
|
120
|
+
const tok = bareWord(raw.replace(/^\d+>&\d+$/, "")).replace(/^\d+>/, "").replace(/^</, "");
|
|
121
|
+
if (tok === "") continue;
|
|
122
|
+
if (tok.includes("/") || tok.startsWith(".") || tok.startsWith("~") || tok.startsWith("$HOME")) out.push(tok);
|
|
123
|
+
}
|
|
124
|
+
return out;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Every string an args object carries, nested arrays and objects included. */
|
|
128
|
+
function argStrings(args: Record<string, unknown> | undefined): string[] {
|
|
129
|
+
if (!args) return [];
|
|
130
|
+
const out: string[] = [];
|
|
131
|
+
const walk = (v: unknown): void => {
|
|
132
|
+
if (typeof v === "string") out.push(v);
|
|
133
|
+
else if (Array.isArray(v)) for (const x of v) walk(x);
|
|
134
|
+
else if (v && typeof v === "object") for (const x of Object.values(v as Record<string, unknown>)) walk(x);
|
|
135
|
+
};
|
|
136
|
+
for (const v of Object.values(args)) walk(v);
|
|
137
|
+
return out;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Absolute targets a write tool names: its `path`/`file`/`file_path` arguments (`;`-joined lists
|
|
142
|
+
* and `:N-M` selectors allowed) and `[path#TAG]` headers in patch text. Content strings are data,
|
|
143
|
+
* never targets. A relative target resolves against the call's `cwd`; without one it is skipped,
|
|
144
|
+
* since its real location is unknown.
|
|
145
|
+
*/
|
|
146
|
+
function writerPaths(args: Record<string, unknown> | undefined, home: string): string[] {
|
|
147
|
+
if (!args) return [];
|
|
148
|
+
const raw: string[] = [];
|
|
149
|
+
for (const key of ["path", "file", "file_path"]) {
|
|
150
|
+
const v = args[key];
|
|
151
|
+
if (typeof v === "string") raw.push(...v.split(";"));
|
|
152
|
+
}
|
|
153
|
+
for (const m of JSON.stringify(args).matchAll(/\[([^\]\s#"]+)#[0-9A-Fa-f]{4}\]/g)) raw.push(m[1] ?? "");
|
|
154
|
+
const cwd = typeof args.cwd === "string" ? expandHome(args.cwd, home) : "";
|
|
155
|
+
const out: string[] = [];
|
|
156
|
+
for (const r of raw) {
|
|
157
|
+
const p = expandHome(r.trim().replace(/(:raw)?(:[\d+\-,]+)?(:raw)?$/, ""), home);
|
|
158
|
+
if (p === "" || p.includes("://")) continue;
|
|
159
|
+
if (p.startsWith("/")) out.push(p);
|
|
160
|
+
else if (cwd.startsWith("/")) out.push(`${cwd.replace(/\/+$/, "")}/${p.replace(/^\.\//, "")}`);
|
|
161
|
+
}
|
|
162
|
+
return out;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Host out of a URL authority or a `user@host[:port][:path]` destination (path stripped). */
|
|
166
|
+
function hostOf(authority: string): string {
|
|
167
|
+
let h = authority;
|
|
168
|
+
const at = h.lastIndexOf("@");
|
|
169
|
+
if (at !== -1) h = h.slice(at + 1);
|
|
170
|
+
if (h.startsWith("[")) {
|
|
171
|
+
const end = h.indexOf("]");
|
|
172
|
+
return end === -1 ? h.slice(1) : h.slice(1, end);
|
|
173
|
+
}
|
|
174
|
+
return h.split(/[/:?#]/, 1)[0] ?? h;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Short options that take a separate value, so the value is never read as a host operand.
|
|
178
|
+
const VALUE_FLAGS: Record<string, true> = {
|
|
179
|
+
"-p": true, "-i": true, "-L": true, "-R": true, "-D": true, "-J": true, "-F": true,
|
|
180
|
+
"-w": true, "-W": true, "-b": true, "-c": true, "-e": true, "-m": true, "-o": true,
|
|
181
|
+
"-O": true, "-Q": true, "-B": true, "-S": true, "-s": true, "-l": true, "-P": true, "-T": true,
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
/** Non-flag operands of one simple command (given without its tool word). */
|
|
185
|
+
function operands(words: string[]): string[] {
|
|
186
|
+
const out: string[] = [];
|
|
187
|
+
let skipValue = false;
|
|
188
|
+
for (const raw of words) {
|
|
189
|
+
const w = bareWord(raw);
|
|
190
|
+
if (w === "") continue;
|
|
191
|
+
if (skipValue) {
|
|
192
|
+
skipValue = false;
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
if (w.startsWith("-")) {
|
|
196
|
+
if (!w.includes("=") && VALUE_FLAGS[w]) skipValue = true;
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
out.push(w);
|
|
200
|
+
}
|
|
201
|
+
return out;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// curl/wget options that carry a body or an upload: short clusters with a data letter
|
|
205
|
+
// (`-d@f`, `-sSd x`), long forms, and an explicit sending method.
|
|
206
|
+
const SENDS_DATA = /(?:^|[\s|;&("'])-(?:[a-z]*d[@=\s-]|F[@=\s-]|[a-z]*T[@=\s-]|X\s*(?:POST|PUT|PATCH)\b|--?data[\w-]*[@=\s]|--?form[\w-]*[@=\s]|--upload-file[@=\s]|--put[@=\s]|--post-[\w-]*[@=\s])/;
|
|
207
|
+
|
|
208
|
+
interface NetHit {
|
|
209
|
+
tool: string;
|
|
210
|
+
host: string;
|
|
211
|
+
exfil: boolean;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Network destinations in one command: every word-boundary occurrence of a net tool, the host
|
|
216
|
+
* it talks to, and whether the shape sends data (pipe into the tool, a body/upload option, a
|
|
217
|
+
* stdin redirect, or a local file as the scp source).
|
|
218
|
+
*/
|
|
219
|
+
function netHits(command: string, netTools: string[]): NetHit[] {
|
|
220
|
+
const hits: NetHit[] = [];
|
|
221
|
+
for (const tool of netTools) {
|
|
222
|
+
const word = tool.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
223
|
+
const re = new RegExp("(?:^|[\\s|;&(\"'`/])" + word + "(?=$|[\\s'\";&|)`])", "g");
|
|
224
|
+
for (const m of command.matchAll(re)) {
|
|
225
|
+
const at = (m.index ?? 0) + m[0].lastIndexOf(tool);
|
|
226
|
+
const rest = command.slice(at);
|
|
227
|
+
const brk = rest.search(/\n|;|&&/);
|
|
228
|
+
const seg = brk === -1 ? rest : rest.slice(0, brk);
|
|
229
|
+
let host = "";
|
|
230
|
+
let exfil = command.slice(0, at).trimEnd().endsWith("|");
|
|
231
|
+
const url = seg.match(/[A-Za-z][A-Za-z0-9+.-]*:\/\/([^\s'"`<>\\]+)/);
|
|
232
|
+
if (url) host = hostOf(url[1]!);
|
|
233
|
+
const ops = operands(seg.split(/\s+/).slice(1));
|
|
234
|
+
if (tool === "scp") {
|
|
235
|
+
// first remote (colon) operand is the other end; local operands before it are being sent
|
|
236
|
+
const first = ops.findIndex((t) => t.includes(":"));
|
|
237
|
+
if (first !== -1) {
|
|
238
|
+
if (host === "") host = hostOf(ops[first]!);
|
|
239
|
+
exfil = exfil || first > 0;
|
|
240
|
+
}
|
|
241
|
+
} else if (tool === "nc") {
|
|
242
|
+
if (/(?:^|\s)-(?:l|listen)\b/.test(seg)) continue;
|
|
243
|
+
if (host === "") host = hostOf(ops[0] ?? "");
|
|
244
|
+
if (/\s<\s*[^\s|;&]/.test(seg)) exfil = true;
|
|
245
|
+
} else if (tool === "ssh") {
|
|
246
|
+
if (host === "") host = hostOf(ops[0] ?? "");
|
|
247
|
+
} else if (SENDS_DATA.test(seg)) {
|
|
248
|
+
exfil = true;
|
|
249
|
+
}
|
|
250
|
+
if (host !== "") hits.push({ tool, host, exfil });
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return hits;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const WRITE_WORDS: Record<string, true> = { tee: true, touch: true, cp: true, mv: true, install: true, ln: true };
|
|
257
|
+
const OUT_WORDS: Record<string, true> = { "-o": true, "-O": true, "--output": true, "--output-document": true };
|
|
258
|
+
const DEV_TARGET = /^\/dev\/[\w.]+$/;
|
|
259
|
+
|
|
260
|
+
/** Absolute write targets of one command: redirections, `of=`, and the writing commands. */
|
|
261
|
+
function writeTargets(command: string): string[] {
|
|
262
|
+
const out: string[] = [];
|
|
263
|
+
for (const seg of command.split(/\n|;|&&|\|\|/)) {
|
|
264
|
+
for (const m of seg.matchAll(/\d*>>?>?|>&\d*/g)) {
|
|
265
|
+
const after = seg.slice((m.index ?? 0) + m[0].length).trim();
|
|
266
|
+
if (after !== "") out.push(after.split(/\s+/)[0]!);
|
|
267
|
+
}
|
|
268
|
+
for (const m of seg.matchAll(/\bof=([^\s;&|]+)/g)) out.push(m[1]!);
|
|
269
|
+
const words = seg.split(/\s+/);
|
|
270
|
+
for (let i = 0; i < words.length; i++) {
|
|
271
|
+
const w = bareWord(words[i]!);
|
|
272
|
+
const rest = operands(words.slice(i + 1));
|
|
273
|
+
if (rest.length === 0) continue;
|
|
274
|
+
if (WRITE_WORDS[w]) {
|
|
275
|
+
// tee/touch write every operand; cp/mv/install/ln write the destination (last)
|
|
276
|
+
if (w === "tee" || w === "touch") out.push(...rest);
|
|
277
|
+
else out.push(rest[rest.length - 1]!);
|
|
278
|
+
} else if (OUT_WORDS[w]) {
|
|
279
|
+
out.push(rest[0]!);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
return out
|
|
284
|
+
.map((t) => bareWord(t.replace(/^\d+>&?\d*$/, "")).replace(/^\d+>/, ""))
|
|
285
|
+
.filter((t) => t.startsWith("/") || t.startsWith("~") || t.startsWith("$HOME"))
|
|
286
|
+
.filter((t) => !DEV_TARGET.test(t));
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function hostAllowed(host: string, allowed: string[]): boolean {
|
|
290
|
+
const h = host.toLowerCase();
|
|
291
|
+
for (const a of allowed) {
|
|
292
|
+
const pat = a.toLowerCase();
|
|
293
|
+
if (pat.startsWith("*.")) {
|
|
294
|
+
if (h === pat.slice(2) || h.endsWith(pat.slice(1))) return true;
|
|
295
|
+
} else if (h === pat) {
|
|
296
|
+
return true;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
return false;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Every suspicious action in one run's trace, in event order, deduped on rule+target (the
|
|
304
|
+
* first occurrence carries the evidence). Read paths are checked against `secret_globs`,
|
|
305
|
+
* network commands against `allowed_hosts`, write targets against `deny_globs` and the
|
|
306
|
+
* `write_roots` scope (deny paths fire wherever the roots point), and commands against the
|
|
307
|
+
* pipe-to-shell patterns.
|
|
308
|
+
*/
|
|
309
|
+
export function suspiciousActions(events: TraceEvent[], rules: ActionsRules): SuspiciousAction[] {
|
|
310
|
+
const out: SuspiciousAction[] = [];
|
|
311
|
+
const seen = new Set<string>();
|
|
312
|
+
const add = (a: SuspiciousAction): void => {
|
|
313
|
+
const key = `${a.rule}:${a.target}`;
|
|
314
|
+
if (seen.has(key)) return;
|
|
315
|
+
seen.add(key);
|
|
316
|
+
out.push({ ...a, evidence: maskEvidence(a.evidence) });
|
|
317
|
+
};
|
|
318
|
+
for (const ev of events) {
|
|
319
|
+
if (ev.kind !== "toolCall") continue;
|
|
320
|
+
const tool = ev.tool ?? "?";
|
|
321
|
+
const shell = rules.shell_tools.includes(tool);
|
|
322
|
+
const command = shell && typeof ev.args?.command === "string" ? ev.args.command : "";
|
|
323
|
+
const writer = !shell && rules.write_tools.includes(tool);
|
|
324
|
+
// A write tool's content is data, not an action: only its path arguments are checked.
|
|
325
|
+
const scanArgs = command === "" && !writer;
|
|
326
|
+
const writes = new Set<string>([
|
|
327
|
+
...writeTargets(command).map((w) => expandHome(w, rules.home)),
|
|
328
|
+
...(writer ? writerPaths(ev.args, rules.home) : []),
|
|
329
|
+
]);
|
|
330
|
+
const evidence = command !== "" ? command : JSON.stringify(ev.args ?? {});
|
|
331
|
+
for (const w of writes) {
|
|
332
|
+
if (rules.deny_globs.some((g) => globMatch(g, w, rules.home))) {
|
|
333
|
+
add({ rule: "write-out-of-scope", severity: "medium", runId: ev.runId, ts: ev.ts, tool, target: w, summary: `writes ${w} — a deny path`, evidence });
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
const inScope =
|
|
337
|
+
rules.write_roots.length === 0 ||
|
|
338
|
+
rules.write_roots.some((r) => {
|
|
339
|
+
const root = expandHome(r, rules.home);
|
|
340
|
+
return w === root || w.startsWith(root.endsWith("/") ? root : `${root}/`);
|
|
341
|
+
});
|
|
342
|
+
if (!inScope) {
|
|
343
|
+
add({ rule: "write-out-of-scope", severity: "medium", runId: ev.runId, ts: ev.ts, tool, target: w, summary: `writes ${w} outside the allowed roots`, evidence });
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
const candidates = [
|
|
347
|
+
...pathTokens(command),
|
|
348
|
+
...(scanArgs ? argStrings(ev.args).filter((s) => s.includes("/") || s.startsWith(".") || s.startsWith("~")) : []),
|
|
349
|
+
].filter((c) => !c.includes("...") && !NOT_A_PATH.test(c));
|
|
350
|
+
for (const c of candidates) {
|
|
351
|
+
const full = expandHome(c, rules.home);
|
|
352
|
+
if (writes.has(full)) continue;
|
|
353
|
+
const glob = rules.secret_globs.find((g) => globMatch(g, c, rules.home));
|
|
354
|
+
if (glob === undefined) continue;
|
|
355
|
+
add({ rule: "secret-read", severity: "high", runId: ev.runId, ts: ev.ts, tool, target: full, summary: `reads ${c} (matches ${glob})`, evidence });
|
|
356
|
+
}
|
|
357
|
+
if (command === "") continue;
|
|
358
|
+
for (const h of netHits(command, rules.net_tools)) {
|
|
359
|
+
if (hostAllowed(h.host, rules.allowed_hosts)) continue;
|
|
360
|
+
add({ rule: "net-unknown-host", severity: h.exfil ? "high" : "low", runId: ev.runId, ts: ev.ts, tool, target: h.host, summary: `${h.tool} to unknown host ${h.host}${h.exfil ? " (sends data)" : ""}`, evidence: command });
|
|
361
|
+
}
|
|
362
|
+
for (const p of rules.shell_patterns) {
|
|
363
|
+
if (command.includes(p)) {
|
|
364
|
+
add({ rule: "pipe-to-shell", severity: "medium", runId: ev.runId, ts: ev.ts, tool, target: p, summary: `feeds a shell from a pipe (${p})`, evidence: command });
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
return out;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// ---- P4: owned-product reads reported as `Findings: none` ----
|
|
372
|
+
|
|
373
|
+
export interface OwnRun {
|
|
374
|
+
/** The run's plan repo, spelled like the `traces.owned_repos` entries. */
|
|
375
|
+
repo: string;
|
|
376
|
+
/** The plan the run reported into, carried onto the agent-score penalty event. */
|
|
377
|
+
plan: string;
|
|
378
|
+
/**
|
|
379
|
+
* True when the run's new Progress bullet claims `Findings: none` (live wiring, plan P6):
|
|
380
|
+
* the bullet is the claim source the owner named and the plan-edit guard has just verified
|
|
381
|
+
* it, so it replaces the final-text check below.
|
|
382
|
+
*/
|
|
383
|
+
claimedNone?: boolean;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
export interface UnreportedFinding {
|
|
387
|
+
/** The subagent run id — the agent name the score events use. */
|
|
388
|
+
agent: string;
|
|
389
|
+
/** The owned repo whose file was read. */
|
|
390
|
+
repo: string;
|
|
391
|
+
/** The expanded read target. */
|
|
392
|
+
target: string;
|
|
393
|
+
/** The plan context, passed through to the penalty event. */
|
|
394
|
+
plan: string;
|
|
395
|
+
summary: string;
|
|
396
|
+
/** Masked and capped call text. */
|
|
397
|
+
evidence: string;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** One path segment (npm scopes included) reduced for owned-repo matching: case, a leading `@` and `-_.` gone. */
|
|
401
|
+
function segKey(seg: string): string {
|
|
402
|
+
return seg.toLowerCase().replace(/^@/, "").replace(/[-_.]+/g, "");
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* The owned repo (config `traces.owned_repos`) a path belongs to, or null. A segment matches a
|
|
407
|
+
* repo when it equals the name once case and `-_.` are ignored — an `@scope` segment is the
|
|
408
|
+
* installed-copy shape under node_modules and global installs — or when the lowercased segment
|
|
409
|
+
* starts with the name at a word boundary. The longest name wins when several match.
|
|
410
|
+
*/
|
|
411
|
+
export function ownedRepoOf(path: string, repos: string[]): string | null {
|
|
412
|
+
let best: string | null = null;
|
|
413
|
+
for (const repo of repos) {
|
|
414
|
+
const key = segKey(repo);
|
|
415
|
+
if (key === "") continue;
|
|
416
|
+
for (const seg of path.split("/")) {
|
|
417
|
+
const s = seg.toLowerCase();
|
|
418
|
+
const hit = segKey(seg) === key ||
|
|
419
|
+
(s.startsWith(key) && (s.length === key.length || /^[-_./@]/.test(s.slice(key.length))));
|
|
420
|
+
if (hit && (best === null || key.length > segKey(best).length)) {
|
|
421
|
+
best = repo;
|
|
422
|
+
break;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
return best;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
const NONE_FINDINGS = /findings:\s*none\b[\s.!]*$/i;
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Cross-product reads a subagent run hid behind a `Findings: none` line (plan P4): the run read
|
|
433
|
+
* files of an owned repo other than its plan's own (`own.repo`), installed copies under
|
|
434
|
+
* node_modules included, while its final report claims no findings — or, with `own.claimedNone`,
|
|
435
|
+
* while its new Progress bullet does. Read tools count only their named path arguments (search
|
|
436
|
+
* text and intents are data) plus a shell command's path-like words; writes of its own repo,
|
|
437
|
+
* unowned paths, runs without the none-claim and the trace reader's main runs never fire.
|
|
438
|
+
* Evidence is masked like every rule's.
|
|
439
|
+
*/
|
|
440
|
+
export function unreportedFindings(events: TraceEvent[], rules: ActionsRules, own: OwnRun): UnreportedFinding[] {
|
|
441
|
+
if (rules.owned_repos.length === 0) return [];
|
|
442
|
+
const agent = events.find((e) => e.runId !== "")?.runId ?? "";
|
|
443
|
+
if (agent === "" || agent.startsWith("MAIN ")) return [];
|
|
444
|
+
let report: string | null = null;
|
|
445
|
+
for (let i = events.length - 1; i >= 0; i--) {
|
|
446
|
+
const e = events[i];
|
|
447
|
+
if (e?.kind === "assistantText" && e.text?.trim()) {
|
|
448
|
+
report = e.text;
|
|
449
|
+
break;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
if (own.claimedNone !== true && (report === null || !NONE_FINDINGS.test(report.trimEnd()))) return [];
|
|
453
|
+
const ownKey = segKey(own.repo);
|
|
454
|
+
const out: UnreportedFinding[] = [];
|
|
455
|
+
const seen = new Set<string>();
|
|
456
|
+
for (const ev of events) {
|
|
457
|
+
if (ev.kind !== "toolCall") continue;
|
|
458
|
+
const tool = ev.tool ?? "?";
|
|
459
|
+
const targets: string[] = [];
|
|
460
|
+
if (rules.shell_tools.includes(tool)) {
|
|
461
|
+
targets.push(...pathTokens(typeof ev.args?.command === "string" ? ev.args.command : ""));
|
|
462
|
+
} else if (!rules.write_tools.includes(tool)) {
|
|
463
|
+
for (const key of ["path", "file", "file_path"]) {
|
|
464
|
+
const v = ev.args?.[key];
|
|
465
|
+
if (typeof v === "string" && (v.includes("/") || v.startsWith(".") || v.startsWith("~"))) targets.push(v);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
for (const raw of targets) {
|
|
469
|
+
const t = expandHome(raw, rules.home);
|
|
470
|
+
const repo = ownedRepoOf(t, rules.owned_repos);
|
|
471
|
+
if (repo === null || segKey(repo) === ownKey) continue;
|
|
472
|
+
const id = `${repo}:${t}`;
|
|
473
|
+
if (seen.has(id)) continue;
|
|
474
|
+
seen.add(id);
|
|
475
|
+
const text = typeof ev.args?.command === "string" ? ev.args.command : JSON.stringify(ev.args ?? {});
|
|
476
|
+
out.push({
|
|
477
|
+
agent,
|
|
478
|
+
repo,
|
|
479
|
+
target: t,
|
|
480
|
+
plan: own.plan,
|
|
481
|
+
summary: `${agent} read ${repo} files (${t}) and reported Findings: none`,
|
|
482
|
+
evidence: maskEvidence(text),
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
return out;
|
|
487
|
+
}
|