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.
- package/README.md +31 -1
- package/package.json +1 -1
- package/src/adapters/omp/index.ts +130 -9
- package/src/adapters/omp/install.ts +14 -7
- package/src/adapters/omp/sessions.ts +10 -4
- package/src/adapters/omp/traces.ts +167 -0
- package/src/cli/dispatch.ts +11 -0
- package/src/cli/guard.ts +7 -1
- package/src/cli/traces.ts +157 -0
- package/src/core/adapter.ts +36 -0
- package/src/core/agent-score.ts +7 -0
- package/src/core/config.ts +36 -0
- package/src/core/guards.ts +136 -14
- package/src/core/incident-detectors.ts +88 -1
- package/src/core/incidents.ts +2 -2
- package/src/core/owner-ui.ts +586 -100
- package/src/core/queue/lib.ts +18 -12
- package/src/core/rate-limit.ts +63 -0
- package/src/core/trace-actions.ts +487 -0
- package/src/core/trace-claims.ts +239 -0
- package/templates/AGENTS.md +1 -0
- package/templates/config.yml +29 -0
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
// `neurastream traces claims …` (plan 20261024_0300 P3): check what a run's final report CLAIMS
|
|
2
|
+
// against what the same run's tool activity shows. Claims come from the run's last assistant
|
|
3
|
+
// message; a claim with no backing toolResult line, git output, heavy-run call or edit/write is
|
|
4
|
+
// reported as a claim-unbacked finding (src/core/incident-detectors.ts D5).
|
|
5
|
+
// `neurastream traces actions …` (plan 20261024_0301 P2): list the suspicious tool actions a
|
|
6
|
+
// run's trace shows (src/core/trace-actions.ts); the high ones fold into the incident store as
|
|
7
|
+
// realtime `suspicious-action` incidents (D6). Read-only over the sessions root; --json prints
|
|
8
|
+
// machine-readable records.
|
|
9
|
+
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import { nowSec } from "../core/clock.ts";
|
|
12
|
+
import type { TraceSource } from "../core/adapter.ts";
|
|
13
|
+
import { ConfigError, loadConfig, type Config } from "../core/config.ts";
|
|
14
|
+
import { claimUnbacked } from "../core/incident-detectors.ts";
|
|
15
|
+
import { claimsFromEvents, type RelatedRun } from "../core/trace-claims.ts";
|
|
16
|
+
import { actionsRules, suspiciousActions, type ActionsRules, type SuspiciousAction } from "../core/trace-actions.ts";
|
|
17
|
+
import { ompTraceRuns, ompTraceSource, subagentTraces } from "../adapters/omp/traces.ts";
|
|
18
|
+
|
|
19
|
+
export const TRACES_USAGE = [
|
|
20
|
+
"usage: neurastream traces claims <runId> [--json]",
|
|
21
|
+
" neurastream traces claims --since <N m|h|d> [--json]",
|
|
22
|
+
" neurastream traces actions <runId> [--json]",
|
|
23
|
+
" neurastream traces actions --since <N m|h|d> [--json]",
|
|
24
|
+
].join("\n");
|
|
25
|
+
|
|
26
|
+
const SINCE = /^(\d+)(m|h|d)$/;
|
|
27
|
+
|
|
28
|
+
export interface RunClaimsReport {
|
|
29
|
+
runId: string;
|
|
30
|
+
claims: number;
|
|
31
|
+
backed: number;
|
|
32
|
+
unbacked: { kind: string; summary: string; evidence?: string }[];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Verify one run: claims from its final report, findings for the ones no tool output backs. A
|
|
36
|
+
* Main run's report also checks the toolResult text of the subagent runs under its session dir
|
|
37
|
+
* (`related`, INCIDENT I-20261025-23): the evidence for a cited subagent result lives in the
|
|
38
|
+
* subagent's own session, and a match there backs the claim as `subagent:<name>`. */
|
|
39
|
+
export function claimsReport(src: TraceSource, runId: string, related: RelatedRun[] = []): RunClaimsReport {
|
|
40
|
+
const events = src.events(runId);
|
|
41
|
+
const claims = claimsFromEvents(events);
|
|
42
|
+
const findings = claimUnbacked(claims, events, related);
|
|
43
|
+
return {
|
|
44
|
+
runId,
|
|
45
|
+
claims: claims.length,
|
|
46
|
+
backed: claims.length - findings.length,
|
|
47
|
+
unbacked: findings.map((f) => ({ kind: f.kind, summary: f.summary, evidence: f.evidence })),
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface RunActionsReport {
|
|
52
|
+
runId: string;
|
|
53
|
+
/** Every suspicious tool action the run's trace shows, evidence masked and capped. */
|
|
54
|
+
actions: SuspiciousAction[];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Scan one run: every suspicious tool action its trace shows, under the config's rules. */
|
|
58
|
+
export function actionsReport(src: TraceSource, runId: string, rules: ActionsRules): RunActionsReport {
|
|
59
|
+
return { runId, actions: suspiciousActions(src.events(runId), rules) };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** `neurastream traces claims|actions`: one run by id, or every run touched inside a --since window. */
|
|
63
|
+
export async function runTraces(args: string[], opts: { home?: string } = {}): Promise<number> {
|
|
64
|
+
const sub = args[0];
|
|
65
|
+
if (sub !== "claims" && sub !== "actions") {
|
|
66
|
+
console.error(TRACES_USAGE);
|
|
67
|
+
return 2;
|
|
68
|
+
}
|
|
69
|
+
let cfg: Config;
|
|
70
|
+
try {
|
|
71
|
+
cfg = loadConfig(opts.home === undefined ? undefined : { home: opts.home });
|
|
72
|
+
} catch (err) {
|
|
73
|
+
console.error(err instanceof ConfigError ? err.message : String(err));
|
|
74
|
+
return 1;
|
|
75
|
+
}
|
|
76
|
+
const root = cfg.adapter?.sessions || join(cfg.paths.home, ".omp", "agent", "sessions");
|
|
77
|
+
const rest = args.slice(1);
|
|
78
|
+
let runId: string | undefined;
|
|
79
|
+
let windowSec: number | undefined;
|
|
80
|
+
let json = false;
|
|
81
|
+
for (let i = 0; i < rest.length; i++) {
|
|
82
|
+
const a = rest[i]!;
|
|
83
|
+
if (a === "--json") {
|
|
84
|
+
json = true;
|
|
85
|
+
} else if (a === "--since") {
|
|
86
|
+
const m = SINCE.exec(rest[++i] ?? "");
|
|
87
|
+
if (!m) {
|
|
88
|
+
console.error(TRACES_USAGE);
|
|
89
|
+
return 2;
|
|
90
|
+
}
|
|
91
|
+
// SINCE only matches digits followed by m, h or d, so the unit is one of the three.
|
|
92
|
+
windowSec = Number(m[1]) * (m[2] === "h" ? 3600 : m[2] === "d" ? 86400 : 60);
|
|
93
|
+
} else if (runId !== undefined) {
|
|
94
|
+
console.error(TRACES_USAGE);
|
|
95
|
+
return 2;
|
|
96
|
+
} else {
|
|
97
|
+
runId = a;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if ((runId !== undefined) === (windowSec !== undefined)) {
|
|
101
|
+
console.error(TRACES_USAGE);
|
|
102
|
+
return 2;
|
|
103
|
+
}
|
|
104
|
+
const runs = ompTraceRuns(root);
|
|
105
|
+
const src = ompTraceSource(root);
|
|
106
|
+
const rules = sub === "actions" ? actionsRules(cfg) : null;
|
|
107
|
+
// A Main run's report cites its subagents' results: their traces under the Main session dir
|
|
108
|
+
// back the pure result-line claims (P5). No time filter — the text match is the guard, and
|
|
109
|
+
// a sub's file keeps being written while its Main run lives, inside whatever window.
|
|
110
|
+
const relatedOf = (id: string): RelatedRun[] =>
|
|
111
|
+
sub === "claims" ? subagentTraces(root, id).map(({ name, events }) => ({ name, events })) : [];
|
|
112
|
+
const reports: (RunClaimsReport | RunActionsReport)[] = [];
|
|
113
|
+
const reportOf = (id: string): RunClaimsReport | RunActionsReport =>
|
|
114
|
+
sub === "claims" ? claimsReport(src, id, relatedOf(id)) : actionsReport(src, id, rules!);
|
|
115
|
+
if (windowSec !== undefined) {
|
|
116
|
+
const cutoff = nowSec() - windowSec;
|
|
117
|
+
for (const r of runs) {
|
|
118
|
+
if (r.mtimeSec < cutoff) continue;
|
|
119
|
+
reports.push(reportOf(r.runId));
|
|
120
|
+
}
|
|
121
|
+
} else {
|
|
122
|
+
if (!runs.some((r) => r.runId === runId)) {
|
|
123
|
+
console.error(`no trace for run ${runId}`);
|
|
124
|
+
return 1;
|
|
125
|
+
}
|
|
126
|
+
reports.push(reportOf(runId!));
|
|
127
|
+
}
|
|
128
|
+
if (json) {
|
|
129
|
+
console.log(JSON.stringify(reports, null, 2));
|
|
130
|
+
return 0;
|
|
131
|
+
}
|
|
132
|
+
for (const r of reports) {
|
|
133
|
+
if ("claims" in r) {
|
|
134
|
+
if (r.claims === 0) {
|
|
135
|
+
console.log(`${r.runId}: no verifiable claims in the final report`);
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
console.log(`${r.runId}: ${r.claims} claims, ${r.backed} backed, ${r.unbacked.length} unbacked`);
|
|
139
|
+
for (const u of r.unbacked) {
|
|
140
|
+
console.log(` ${u.kind}: ${u.summary}`);
|
|
141
|
+
if (u.evidence) console.log(` evidence: ${u.evidence}`);
|
|
142
|
+
}
|
|
143
|
+
} else {
|
|
144
|
+
if (r.actions.length === 0) {
|
|
145
|
+
console.log(`${r.runId}: no suspicious actions in the trace`);
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
const high = r.actions.filter((a) => a.severity === "high").length;
|
|
149
|
+
console.log(`${r.runId}: ${r.actions.length} suspicious actions (${high} high)`);
|
|
150
|
+
for (const a of r.actions) {
|
|
151
|
+
console.log(` [${a.severity}] ${a.rule}: ${a.summary}`);
|
|
152
|
+
if (a.evidence) console.log(` evidence: ${a.evidence}`);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return 0;
|
|
157
|
+
}
|
package/src/core/adapter.ts
CHANGED
|
@@ -42,6 +42,38 @@ export interface RunSource {
|
|
|
42
42
|
mainSession(file?: string): MainSession | null;
|
|
43
43
|
}
|
|
44
44
|
|
|
45
|
+
// Trace events: the raw activity of one run, used for claimed-vs-done checks and cross-run
|
|
46
|
+
// questions. Harness-specific parsing lives in the adapters; core only defines the shape.
|
|
47
|
+
|
|
48
|
+
export interface TraceUsage {
|
|
49
|
+
input: number;
|
|
50
|
+
output: number;
|
|
51
|
+
cacheRead: number;
|
|
52
|
+
cacheWrite: number;
|
|
53
|
+
totalTokens: number;
|
|
54
|
+
cost: number;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export type TraceEventKind = "toolCall" | "toolResult" | "usage" | "modelChange" | "assistantText";
|
|
58
|
+
|
|
59
|
+
export interface TraceEvent {
|
|
60
|
+
kind: TraceEventKind;
|
|
61
|
+
/** Unix seconds; null when the source line carries no readable timestamp. */
|
|
62
|
+
ts: number | null;
|
|
63
|
+
runId: string;
|
|
64
|
+
tool?: string;
|
|
65
|
+
args?: Record<string, unknown>;
|
|
66
|
+
isError?: boolean;
|
|
67
|
+
text?: string;
|
|
68
|
+
model?: string;
|
|
69
|
+
provider?: string;
|
|
70
|
+
usage?: TraceUsage;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export interface TraceSource {
|
|
74
|
+
events(runId: string): TraceEvent[];
|
|
75
|
+
}
|
|
76
|
+
|
|
45
77
|
export interface Decision {
|
|
46
78
|
allow: boolean;
|
|
47
79
|
reason: string;
|
|
@@ -61,12 +93,16 @@ export interface ToolEvent {
|
|
|
61
93
|
paths: string[];
|
|
62
94
|
writes: string[];
|
|
63
95
|
command: string;
|
|
96
|
+
/** Labels of the harness's own running background jobs at call time; undefined when the caller has no job info (CLI without it). */
|
|
97
|
+
runningJobs?: string[];
|
|
64
98
|
}
|
|
65
99
|
|
|
66
100
|
export interface SpawnEvent {
|
|
67
101
|
agent: string;
|
|
68
102
|
invocationKind: string;
|
|
69
103
|
brief: string;
|
|
104
|
+
/** Labels of the harness's own running background jobs; undefined when the caller has no job info. */
|
|
105
|
+
runningJobs?: string[];
|
|
70
106
|
}
|
|
71
107
|
|
|
72
108
|
export interface InjectEvent {
|
package/src/core/agent-score.ts
CHANGED
|
@@ -45,6 +45,13 @@ function record(ev: Record<string, unknown>, cfg: Config): void {
|
|
|
45
45
|
printText(`recorded: ${pyDumps(ev)}`);
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
+
/** Append a penalty event silently: detector folds record these; the score CLI prints its own. */
|
|
49
|
+
export function recordPenalty(cfg: Config, p: { agent: string; kind: string; plan: string; note: string }): void {
|
|
50
|
+
const ev: Record<string, unknown> = { type: "penalty", agent: p.agent, kind: p.kind, plan: p.plan, note: p.note, ts: new PyFloat(nowSec()) };
|
|
51
|
+
mkdirSync(dirname(eventsPath(cfg)), { recursive: true });
|
|
52
|
+
appendFileSync(eventsPath(cfg), `${pyDumps(ev)}\n`);
|
|
53
|
+
}
|
|
54
|
+
|
|
48
55
|
function expandCommits(repo: string, spec: string): string[] {
|
|
49
56
|
const out: string[] = [];
|
|
50
57
|
for (const raw of spec.split(",")) {
|
package/src/core/config.ts
CHANGED
|
@@ -109,6 +109,18 @@ export interface Config {
|
|
|
109
109
|
chat_unlock: boolean;
|
|
110
110
|
plan_read_max_hours: number;
|
|
111
111
|
idle_stops: number;
|
|
112
|
+
/** Provider rate limits (src/core/rate-limit.ts): a turn that ends on one waits it out instead of
|
|
113
|
+
* asking again straight into the limit. The words and the waits come from here. */
|
|
114
|
+
rate_limit: {
|
|
115
|
+
/** Case-insensitive substrings in the error text that mark a rate limit. */
|
|
116
|
+
patterns: string[];
|
|
117
|
+
/** Wait when the error text names no retry-after. */
|
|
118
|
+
default_wait_s: number;
|
|
119
|
+
/** Cap for the parsed (or doubled) wait, before slack. */
|
|
120
|
+
max_wait_s: number;
|
|
121
|
+
/** Added on top of every wait. */
|
|
122
|
+
slack_s: number;
|
|
123
|
+
};
|
|
112
124
|
blocker_timeout_ms: number;
|
|
113
125
|
skip_tools: string[];
|
|
114
126
|
read_tools: string[];
|
|
@@ -156,6 +168,19 @@ export interface Config {
|
|
|
156
168
|
priority: { sleep_sec: number };
|
|
157
169
|
alerts: { temp_c: number; mem_psi: number; io_psi: number; cooldown_sec: number };
|
|
158
170
|
snapshot: { tmp_dest: string; git_repo: string; git_backup: string; excludes: string[] };
|
|
171
|
+
/** Trace action rules (src/core/trace-actions.ts): what a scanned run may read, dial and write. */
|
|
172
|
+
traces: {
|
|
173
|
+
allowed_hosts: string[];
|
|
174
|
+
/** Product names (docs/config.md) whose files another product's run may not read quietly. */
|
|
175
|
+
owned_repos: string[];
|
|
176
|
+
actions: {
|
|
177
|
+
secret_globs: string[];
|
|
178
|
+
net_tools: string[];
|
|
179
|
+
shell_patterns: string[];
|
|
180
|
+
write_roots: string[];
|
|
181
|
+
deny_globs: string[];
|
|
182
|
+
};
|
|
183
|
+
};
|
|
159
184
|
/** Optional overlay written by adapter install. Absent until an adapter is installed. */
|
|
160
185
|
adapter?: { name: string; sessions: string; pins: string; extensions: string };
|
|
161
186
|
/** Notices about legacy keys in the user's config file; empty when there are none. */
|
|
@@ -293,6 +318,12 @@ function check(cfg: Config): void {
|
|
|
293
318
|
throw new ConfigError("guards.sub_max_calls_cap must be >= guards.sub_max_calls");
|
|
294
319
|
}
|
|
295
320
|
if (!(cfg.rollover.max_session_mb > 0)) throw new ConfigError("rollover.max_session_mb must be > 0");
|
|
321
|
+
if (!Array.isArray(cfg.guards.rate_limit.patterns) || cfg.guards.rate_limit.patterns.some(p => typeof p !== "string" || p === "")) {
|
|
322
|
+
throw new ConfigError("guards.rate_limit.patterns must be a list of non-empty strings");
|
|
323
|
+
}
|
|
324
|
+
if (!(cfg.guards.rate_limit.default_wait_s >= 1)) throw new ConfigError("guards.rate_limit.default_wait_s must be >= 1");
|
|
325
|
+
if (!(cfg.guards.rate_limit.max_wait_s >= 1)) throw new ConfigError("guards.rate_limit.max_wait_s must be >= 1");
|
|
326
|
+
if (!(cfg.guards.rate_limit.slack_s >= 0)) throw new ConfigError("guards.rate_limit.slack_s must be >= 0");
|
|
296
327
|
if (!(cfg.rollover.exit_grace_s > 0)) throw new ConfigError("rollover.exit_grace_s must be > 0");
|
|
297
328
|
if (!(cfg.metrics.report_days >= 1)) throw new ConfigError("metrics.report_days must be >= 1");
|
|
298
329
|
if (!(cfg.ui.port >= 1 && cfg.ui.port <= 65535)) throw new ConfigError("ui.port must be between 1 and 65535");
|
|
@@ -315,6 +346,11 @@ function check(cfg: Config): void {
|
|
|
315
346
|
}
|
|
316
347
|
if (!rule.message) throw new ConfigError("brief.repo_rules.message must be a non-empty string");
|
|
317
348
|
}
|
|
349
|
+
for (const list of [cfg.traces.allowed_hosts, cfg.traces.owned_repos, cfg.traces.actions.secret_globs, cfg.traces.actions.net_tools, cfg.traces.actions.shell_patterns, cfg.traces.actions.write_roots, cfg.traces.actions.deny_globs]) {
|
|
350
|
+
if (list.some((v) => typeof v !== "string" || v === "")) {
|
|
351
|
+
throw new ConfigError("traces lists must be non-empty strings");
|
|
352
|
+
}
|
|
353
|
+
}
|
|
318
354
|
for (const [key, value] of Object.entries(cfg.paths)) {
|
|
319
355
|
if (key === "work_roots") {
|
|
320
356
|
if (!Array.isArray(value) || value.some(v => typeof v !== "string")) {
|
package/src/core/guards.ts
CHANGED
|
@@ -79,6 +79,23 @@ function spawnsFile(): string {
|
|
|
79
79
|
return path.join(q.STATE_DIR, "spawns.json");
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
+
function staffingFile(): string {
|
|
83
|
+
return path.join(q.STATE_DIR, "staffing.json");
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** plan → the task names of its newest spawn (staffing.json); read for the staffed check. */
|
|
87
|
+
export function readStaffing(): Record<string, string[]> {
|
|
88
|
+
try {
|
|
89
|
+
const raw: unknown = JSON.parse(readFileSync(staffingFile(), "utf8"));
|
|
90
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
|
|
91
|
+
const out: Record<string, string[]> = {};
|
|
92
|
+
for (const [k, v] of Object.entries(raw)) if (Array.isArray(v)) out[k] = v.map(String);
|
|
93
|
+
return out;
|
|
94
|
+
} catch {
|
|
95
|
+
return {};
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
82
99
|
function readSpawns(): Record<string, string> {
|
|
83
100
|
try {
|
|
84
101
|
const raw: unknown = JSON.parse(readFileSync(spawnsFile(), "utf8"));
|
|
@@ -91,8 +108,8 @@ function readSpawns(): Record<string, string> {
|
|
|
91
108
|
}
|
|
92
109
|
}
|
|
93
110
|
|
|
94
|
-
/** Remember the "## Progress" hash of the plans an agent was just spawned on. */
|
|
95
|
-
export function recordSpawns(files: string[]): void {
|
|
111
|
+
/** Remember the "## Progress" hash of the plans an agent was just spawned on. With `staffing`, also record the spawn's task names per plan (staffing.json); a plan's entry is replaced by the newest spawn that names it. */
|
|
112
|
+
export function recordSpawns(files: string[], staffing: Record<string, string[]> = {}): void {
|
|
96
113
|
const s = readSpawns();
|
|
97
114
|
for (const f of files) {
|
|
98
115
|
try {
|
|
@@ -105,6 +122,23 @@ export function recordSpawns(files: string[]): void {
|
|
|
105
122
|
} catch (err) {
|
|
106
123
|
log(`${q.STATE_DIR}/../main-guard.log`, `cannot write ${spawnsFile()}: ${err}`);
|
|
107
124
|
}
|
|
125
|
+
if (!Object.keys(staffing).length) return;
|
|
126
|
+
const st = readStaffing();
|
|
127
|
+
for (const [f, names] of Object.entries(staffing)) if (names.length) st[f] = [...names];
|
|
128
|
+
try {
|
|
129
|
+
mkdirSync(q.STATE_DIR, { recursive: true });
|
|
130
|
+
writeFileSync(staffingFile(), JSON.stringify(st, null, 1));
|
|
131
|
+
} catch (err) {
|
|
132
|
+
log(`${q.STATE_DIR}/../main-guard.log`, `cannot write ${staffingFile()}: ${err}`);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Plans with a running subagent: one of the plan's staffing names equals a running job label, or the label is that name with the spawner's uniqueness suffix ("-2", "-3", …; real snapshot 2026-10-25: `allocate()` keeps the exact name first, then appends). Pure; no job info staffs nothing. */
|
|
137
|
+
export function staffedPlans(staffing: Record<string, string[]>, runningJobs: string[] | undefined): string[] {
|
|
138
|
+
if (!runningJobs?.length) return [];
|
|
139
|
+
return Object.entries(staffing)
|
|
140
|
+
.filter(([, names]) => names.some(n => runningJobs.some(j => j === n || j.startsWith(`${n}-`))))
|
|
141
|
+
.map(([file]) => file);
|
|
108
142
|
}
|
|
109
143
|
|
|
110
144
|
/** Re-key a plan's spawn hash after its Progress body was trimmed. Only a hash that matched the old body moves. Pure. */
|
|
@@ -253,7 +287,10 @@ export function planGate(text: string, label: string): [string | null, string[]]
|
|
|
253
287
|
`${label}: ${unclosed.map(p => `${p.file} (${p.status})`).join(", ")} is still indexed. Verify it and run \`queue-close <plan>\` before any new spawn.`,
|
|
254
288
|
[],
|
|
255
289
|
];
|
|
256
|
-
|
|
290
|
+
// A `Priority skip: <path> — <why>` line names a plan it does NOT run on (20261025_0215 P3);
|
|
291
|
+
// only the remaining text decides which plans this brief targets.
|
|
292
|
+
const body = text.replace(/^\s*(?:[-*]\s+)?priority skip:.*$/gim, "");
|
|
293
|
+
const named = plans.filter(p => body.includes(p.file));
|
|
257
294
|
if (!named.length)
|
|
258
295
|
return [
|
|
259
296
|
`${label}: an implementer needs an open plan. Name the plan's absolute path in the brief; the plan must be listed in ${q.INDEX}.`,
|
|
@@ -285,12 +322,76 @@ export function planGate(text: string, label: string): [string | null, string[]]
|
|
|
285
322
|
return [null, named.map(p => p.file)];
|
|
286
323
|
}
|
|
287
324
|
|
|
288
|
-
|
|
325
|
+
// --- priority: index order is priority (plan 20261025_0215_index_priority) ---
|
|
326
|
+
|
|
327
|
+
export interface PrioritySkip {
|
|
328
|
+
plan: string;
|
|
329
|
+
why: string;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
export interface PriorityOutcome {
|
|
333
|
+
/** Refusal text, without the caller's label prefix. */
|
|
334
|
+
problem?: string;
|
|
335
|
+
/** Skip lines the brief justified; the caller logs each, then allows. */
|
|
336
|
+
skips?: PrioritySkip[];
|
|
337
|
+
/** No job info was available: the gate never refuses. */
|
|
338
|
+
unknown?: boolean;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
const SKIP_LINE = /^\s*(?:[-*]\s+)?priority skip:\s*(.+?)\s+[—–-]\s*(.+?)\s*$/gim;
|
|
342
|
+
|
|
343
|
+
/** One plan is idle when a subagent could start on it right now: open, no owner hold, not awaiting merge, no template errors, and an unticked phase left. */
|
|
344
|
+
function priorityIdle(p: Plan): boolean {
|
|
345
|
+
return p.status === "open" && !p.waiting && !q.awaitingMerge(p) && !p.errors.length && unticked(p).length > 0;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Pure priority gate: for the brief's named plans, every higher plan in index order that is idle
|
|
350
|
+
* and unstaffed needs a `Priority skip: <path> — <why>` line (non-empty why) in the brief;
|
|
351
|
+
* otherwise the spawn is refused. `staffed === undefined` means the caller had no running-job
|
|
352
|
+
* info (CLI spawn without it): never refuse. Plans already named by this call never block it.
|
|
353
|
+
*/
|
|
354
|
+
export function priorityProblem(plans: Plan[], named: string[], staffed: string[] | undefined, brief: string): PriorityOutcome | null {
|
|
355
|
+
if (staffed === undefined) return { unknown: true };
|
|
356
|
+
const namedRanks = named.map(f => plans.findIndex(p => p.file === f)).filter(n => n >= 0);
|
|
357
|
+
if (!namedRanks.length) return null;
|
|
358
|
+
const higher = plans.slice(0, Math.min(...namedRanks));
|
|
359
|
+
const skipLines: Record<string, string> = {};
|
|
360
|
+
for (const m of brief.matchAll(SKIP_LINE)) {
|
|
361
|
+
const plan = (m[1] ?? "").trim();
|
|
362
|
+
const why = (m[2] ?? "").trim();
|
|
363
|
+
if (plan && why) skipLines[plan] = why;
|
|
364
|
+
}
|
|
365
|
+
const skips: PrioritySkip[] = [];
|
|
366
|
+
for (let i = 0; i < higher.length; i++) {
|
|
367
|
+
const p = higher[i]!;
|
|
368
|
+
if (!priorityIdle(p) || staffed.includes(p.file)) continue;
|
|
369
|
+
const why = skipLines[p.file];
|
|
370
|
+
if (why) {
|
|
371
|
+
skips.push({ plan: p.file, why });
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
return { problem: `higher plan ${p.file} (rank ${i + 1}) is idle; spawn on it first or add "Priority skip: ${p.file} — <why>"` };
|
|
375
|
+
}
|
|
376
|
+
return skips.length ? { skips } : null;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** Load staffing, run the pure priority gate and log its outcome; the refusal comes back with the caller's label, or null. */
|
|
380
|
+
function priorityGate(named: string[], runningJobs: string[] | undefined, brief: string, cfg: Config, label: string): string | null {
|
|
381
|
+
const outcome = priorityProblem(q.activePlans(), named, runningJobs === undefined ? undefined : staffedPlans(readStaffing(), runningJobs), brief);
|
|
382
|
+
if (outcome?.unknown) log(cfg.paths.guard_log, "PRIORITY unknown jobs");
|
|
383
|
+
for (const s of outcome?.skips ?? []) log(cfg.paths.guard_log, `PRIORITY skip ${s.plan}: ${s.why}`);
|
|
384
|
+
return outcome?.problem ? `${label}: ${outcome.problem}` : null;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** Reason to refuse a `task` brief, or null; `files` receives the plans to record, `budgets` every named task's call budget (null = none), `staffing` each plan's named tasks of this call, `runningJobs` the caller's running job labels (undefined = no job info). */
|
|
289
388
|
export function spawnProblem(
|
|
290
389
|
input: Record<string, unknown>,
|
|
291
390
|
cfg: Config,
|
|
292
391
|
files: string[] = [],
|
|
293
392
|
budgets: Record<string, number | null> = {},
|
|
393
|
+
staffing: Record<string, string[]> = {},
|
|
394
|
+
runningJobs?: string[],
|
|
294
395
|
): string | null {
|
|
295
396
|
const tasks = Array.isArray(input?.tasks) ? input.tasks : [];
|
|
296
397
|
const context = String(input?.context ?? "");
|
|
@@ -310,11 +411,23 @@ export function spawnProblem(
|
|
|
310
411
|
if (budget < 10 || budget > cfg.guards.sub_max_calls_cap)
|
|
311
412
|
return `${label}: call budget ${budget} is outside the allowed range 10..${cfg.guards.sub_max_calls_cap}.`;
|
|
312
413
|
}
|
|
313
|
-
if (t?.name)
|
|
414
|
+
if (t?.name) {
|
|
415
|
+
named[label] = budget;
|
|
416
|
+
for (const f of plans) staffing[f] = [...(staffing[f] ?? []), label];
|
|
417
|
+
}
|
|
314
418
|
files.push(...plans);
|
|
315
419
|
}
|
|
316
420
|
Object.assign(budgets, named);
|
|
317
|
-
|
|
421
|
+
// Priority gate (20261025_0215 P3): once per `task` call, over the plans this call names; the
|
|
422
|
+
// skip lines may sit in the shared context or any task text.
|
|
423
|
+
const gate = priorityGate(
|
|
424
|
+
files,
|
|
425
|
+
runningJobs,
|
|
426
|
+
`${context}\n${tasks.map(t => String(t?.task ?? "")).join("\n")}`,
|
|
427
|
+
cfg,
|
|
428
|
+
String((tasks[0] && (tasks[0].name ?? tasks[0].agent)) ?? "task"),
|
|
429
|
+
);
|
|
430
|
+
return gate;
|
|
318
431
|
}
|
|
319
432
|
|
|
320
433
|
function runBlockers(plan: Plan, hit: string[], e: ToolEvent, cfg: Config): string | null {
|
|
@@ -492,14 +605,15 @@ function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config): De
|
|
|
492
605
|
}
|
|
493
606
|
const files: string[] = [];
|
|
494
607
|
const budgets: Record<string, number | null> = {};
|
|
495
|
-
const
|
|
608
|
+
const staffing: Record<string, string[]> = {};
|
|
609
|
+
const why = spawnProblem(input, cfg, files, budgets, staffing, e.runningJobs);
|
|
496
610
|
if (why) {
|
|
497
611
|
log(cfg.paths.guard_log, `BLOCK spawn: ${why}`);
|
|
498
612
|
return deny(`main-guard: ${why}`);
|
|
499
613
|
}
|
|
500
614
|
const inc = incidentSpawnProblem("spawn", JSON.stringify(input), files, cfg);
|
|
501
615
|
if (inc) return deny(`main-guard: ${inc}`);
|
|
502
|
-
recordSpawns(files);
|
|
616
|
+
recordSpawns(files, staffing);
|
|
503
617
|
recordBudgets(budgets);
|
|
504
618
|
return ALLOW;
|
|
505
619
|
}
|
|
@@ -676,9 +790,16 @@ export function checkSpawn(e: SpawnEvent, cfg: Config): Decision {
|
|
|
676
790
|
log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${why}`);
|
|
677
791
|
return deny(`main-guard: ${why}`);
|
|
678
792
|
}
|
|
793
|
+
const gate = priorityGate(named, e.runningJobs, e.brief, cfg, e.agent);
|
|
794
|
+
if (gate) {
|
|
795
|
+
log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${gate}`);
|
|
796
|
+
return deny(`main-guard: ${gate}`);
|
|
797
|
+
}
|
|
679
798
|
const inc = incidentSpawnProblem(`spawn ${e.agent}`, e.brief, named, cfg);
|
|
680
799
|
if (inc) return deny(`main-guard: ${inc}`);
|
|
681
|
-
|
|
800
|
+
const staffing: Record<string, string[]> = {};
|
|
801
|
+
for (const f of named) staffing[f] = [e.agent];
|
|
802
|
+
recordSpawns(named, staffing);
|
|
682
803
|
return ALLOW;
|
|
683
804
|
}
|
|
684
805
|
|
|
@@ -808,16 +929,17 @@ function progressEntries(text: string): string[] {
|
|
|
808
929
|
}
|
|
809
930
|
|
|
810
931
|
/** Entries an edit adds or rewrites: blocks whose text was not in the Progress section before. */
|
|
811
|
-
function newProgressEntries(before: string, after: string): string[] {
|
|
932
|
+
export function newProgressEntries(before: string, after: string): string[] {
|
|
812
933
|
const old = new Set(progressEntries(before));
|
|
813
934
|
return progressEntries(after).filter(b => !old.has(b));
|
|
814
935
|
}
|
|
815
936
|
|
|
816
|
-
/** The value after "Findings:"
|
|
817
|
-
|
|
818
|
-
|
|
937
|
+
/** The value after the entry's last "Findings:", or null when it has no Findings line with content. A "Findings:"
|
|
938
|
+
* quoted earlier in the entry (e.g. inside resume steps) is entry text, never the findings (I-20261025-51). */
|
|
939
|
+
export function findingsValue(block: string): string | null {
|
|
940
|
+
const line = block.split("\n").findLast(l => l.includes("Findings:"));
|
|
819
941
|
if (!line) return null;
|
|
820
|
-
return line.slice(line.
|
|
942
|
+
return line.slice(line.lastIndexOf("Findings:") + "Findings:".length).trim() || null;
|
|
821
943
|
}
|
|
822
944
|
|
|
823
945
|
// Main's plan text outside "## Progress" must rest on files Main read itself (planReadProblems).
|
|
@@ -11,16 +11,26 @@
|
|
|
11
11
|
// D3 block-loop: the same guard BLOCK reason (keyed like M5) logged incidents.block_repeat
|
|
12
12
|
// times within one hour.
|
|
13
13
|
// D4 owner-correction: an owner message matching the M4 correction patterns.
|
|
14
|
+
// D5 claim-unbacked: a run's final report claims something its own tool output never
|
|
15
|
+
// showed (gathered by the traces claims CLI, src/cli/traces.ts).
|
|
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.
|
|
14
21
|
|
|
15
22
|
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
16
23
|
import { dirname, join } from "node:path";
|
|
17
24
|
import { fileURLToPath } from "node:url";
|
|
18
|
-
import type { Run } from "./adapter.ts";
|
|
25
|
+
import type { Run, TraceEvent } from "./adapter.ts";
|
|
19
26
|
import type { Config } from "./config.ts";
|
|
20
27
|
import { nowSec, strftime } from "./clock.ts";
|
|
21
28
|
import { log } from "./guards.ts";
|
|
22
29
|
import { addIncident, type IncidentView } from "./incidents.ts";
|
|
23
30
|
import type { GuardBlock } from "./metrics.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";
|
|
24
34
|
|
|
25
35
|
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
26
36
|
|
|
@@ -141,6 +151,51 @@ export function ownerCorrection(text: string, patterns: RegExp[], now: number):
|
|
|
141
151
|
};
|
|
142
152
|
}
|
|
143
153
|
|
|
154
|
+
// ---- D5: the final report claims something the run's own tool output never showed ----
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Final-report claims (src/core/trace-claims.ts) with no backing activity in the same run's
|
|
158
|
+
* trace: a "13 passed" no toolResult shows, a SHA no git command printed, a label never passed
|
|
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.
|
|
163
|
+
*/
|
|
164
|
+
export function claimUnbacked(claims: Claim[], events: TraceEvent[], related: RelatedRun[] = []): Finding[] {
|
|
165
|
+
const out: Finding[] = [];
|
|
166
|
+
for (const v of verifyClaims(claims, events, related)) {
|
|
167
|
+
if (v.backed) continue;
|
|
168
|
+
const c = v.claim;
|
|
169
|
+
const what = c.count !== undefined ? `${c.kind} ${c.count}` : `${c.kind} ${c.value ?? ""}`;
|
|
170
|
+
out.push({
|
|
171
|
+
kind: "claim-unbacked",
|
|
172
|
+
summary: `final report claims ${what.trim()} but the run's tool output never shows it`,
|
|
173
|
+
evidence: c.evidence,
|
|
174
|
+
fingerprint: `claim-unbacked:${c.kind}:${c.count ?? c.value ?? ""}`,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
return out;
|
|
178
|
+
}
|
|
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
|
+
|
|
144
199
|
// ---- the runner ----
|
|
145
200
|
|
|
146
201
|
/** The plain inputs the callers gather; a detector without its input does not run. */
|
|
@@ -154,6 +209,13 @@ export interface DetectorInput {
|
|
|
154
209
|
bash?: { command: string; output: string };
|
|
155
210
|
/** D4: the owner prompt at before_agent_start; never a main-guard continuation. */
|
|
156
211
|
prompt?: string;
|
|
212
|
+
/** D5: one run's final-report claims plus the same run's trace events (the traces CLI gathers both). */
|
|
213
|
+
claims?: Claim[];
|
|
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[];
|
|
157
219
|
}
|
|
158
220
|
|
|
159
221
|
/**
|
|
@@ -198,6 +260,31 @@ export function runDetectors(cfg: Config, input: DetectorInput, now = nowSec()):
|
|
|
198
260
|
return f ? [f] : [];
|
|
199
261
|
});
|
|
200
262
|
}
|
|
263
|
+
if (input.claims && input.events) {
|
|
264
|
+
attempt("claim-unbacked", () => claimUnbacked(input.claims!, input.events!));
|
|
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
|
+
}
|
|
201
288
|
return out;
|
|
202
289
|
}
|
|
203
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,
|