neurastream 0.2.79 → 0.2.81
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 +10 -0
- package/package.json +1 -1
- package/src/adapters/index.ts +6 -0
- package/src/adapters/omp/adapter.ts +4 -1
- package/src/adapters/omp/doctor.ts +15 -0
- package/src/adapters/omp/index.ts +12 -6
- package/src/adapters/omp/launch.ts +3 -1
- package/src/adapters/omp/providers.ts +217 -0
- package/src/adapters/omp/traces.ts +12 -1
- package/src/cli/commands.ts +3 -1
- package/src/cli/diff-check.ts +30 -0
- package/src/cli/dispatch.ts +17 -0
- package/src/cli/labels.ts +110 -0
- package/src/core/agent-score.ts +26 -10
- package/src/core/config.ts +17 -0
- package/src/core/diff-check.ts +96 -0
- package/src/core/episodes.ts +54 -0
- package/src/core/guards.ts +23 -1
- package/src/core/label-import.ts +97 -0
- package/src/core/label-update.ts +114 -0
- package/src/core/labels.ts +253 -0
- package/src/core/main-start.ts +61 -2
- package/src/core/provider-state.ts +196 -2
- package/src/core/report.ts +85 -0
- package/src/core/watch.ts +30 -9
- package/templates/AGENTS.md +1 -0
- package/templates/config.yml +11 -0
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { readEvents } from "../core/agent-score.ts";
|
|
2
|
+
import { getAdapter } from "../adapters/index.ts";
|
|
3
|
+
import { ConfigError, loadConfig, type Config } from "../core/config.ts";
|
|
4
|
+
import { nowSec } from "../core/clock.ts";
|
|
5
|
+
import { goodSet, updateLabels } from "../core/label-update.ts";
|
|
6
|
+
import { importWhytrailLabels } from "../core/label-import.ts";
|
|
7
|
+
import { assignLabel } from "../core/labels.ts";
|
|
8
|
+
|
|
9
|
+
const USAGE = "usage: neurastream labels episodes [--since 30d] [--json]\n neurastream labels import --repo <dir> [--since 30d] [--json]\n neurastream labels update --repo <dir>\n neurastream labels export --good [--min-age-days 14] [--json]\n neurastream labels assign <episode> --party plan|implementer|both --why <text>";
|
|
10
|
+
const SINCE = /^(\d+)([dhm])$/;
|
|
11
|
+
|
|
12
|
+
export function runLabels(args: string[], opts: { home?: string } = {}): number {
|
|
13
|
+
if (args[0] !== "episodes" && args[0] !== "import" && args[0] !== "assign" && args[0] !== "update" && args[0] !== "export") {
|
|
14
|
+
console.error(USAGE);
|
|
15
|
+
return 2;
|
|
16
|
+
}
|
|
17
|
+
try {
|
|
18
|
+
const cfg = loadConfig(opts.home === undefined ? undefined : { home: opts.home });
|
|
19
|
+
if (args[0] === "assign") return runAssign(args.slice(1), cfg);
|
|
20
|
+
if (args[0] === "update") return runUpdate(args.slice(1), cfg);
|
|
21
|
+
if (args[0] === "export") return runExport(args.slice(1), cfg);
|
|
22
|
+
let windowSec = cfg.labels.episode_days * 86400;
|
|
23
|
+
let json = false;
|
|
24
|
+
let repo: string | undefined;
|
|
25
|
+
for (let i = 1; i < args.length; i++) {
|
|
26
|
+
const arg = args[i]!;
|
|
27
|
+
if (arg === "--json") json = true;
|
|
28
|
+
else if (arg === "--repo" && args[0] === "import") repo = args[++i];
|
|
29
|
+
else if (arg === "--since") {
|
|
30
|
+
const match = SINCE.exec(args[++i] ?? "");
|
|
31
|
+
if (!match) { console.error(USAGE); return 2; }
|
|
32
|
+
windowSec = Number(match[1]) * (match[2] === "d" ? 86400 : match[2] === "h" ? 3600 : 60);
|
|
33
|
+
} else { console.error(USAGE); return 2; }
|
|
34
|
+
}
|
|
35
|
+
const ts = nowSec();
|
|
36
|
+
const cutoff = ts - windowSec;
|
|
37
|
+
if (args[0] === "import") {
|
|
38
|
+
if (repo === undefined) { console.error(USAGE); return 2; }
|
|
39
|
+
const appended = importWhytrailLabels(repo, cfg.paths.score_state, getAdapter(cfg).episodes(cfg, cutoff), ts);
|
|
40
|
+
if (json) console.log(JSON.stringify(appended, null, 2));
|
|
41
|
+
else console.log(`imported ${appended.length} label line(s) from whytrail`);
|
|
42
|
+
return 0;
|
|
43
|
+
}
|
|
44
|
+
const episodes = getAdapter(cfg).episodes(cfg, cutoff);
|
|
45
|
+
if (json) console.log(JSON.stringify(episodes, null, 2));
|
|
46
|
+
else if (episodes.length === 0) console.log("no episodes in the window");
|
|
47
|
+
else for (const episode of episodes) console.log(`${episode.id} ${episode.agent} ${episode.model} ${episode.plan} ${episode.phase} ${episode.commits.join(",")}`);
|
|
48
|
+
return 0;
|
|
49
|
+
} catch (error) {
|
|
50
|
+
console.error(error instanceof ConfigError ? error.message : String(error));
|
|
51
|
+
return 1;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function runUpdate(args: string[], cfg: Config): number {
|
|
56
|
+
let repo: string | undefined;
|
|
57
|
+
for (let i = 0; i < args.length; i++) {
|
|
58
|
+
if (args[i] === "--repo") repo = args[++i];
|
|
59
|
+
else { console.error(USAGE); return 2; }
|
|
60
|
+
}
|
|
61
|
+
if (repo === undefined) { console.error(USAGE); return 2; }
|
|
62
|
+
const a = getAdapter(cfg);
|
|
63
|
+
const result = updateLabels(cfg, repo, {
|
|
64
|
+
episodesFor: cutoff => a.episodes(cfg, cutoff),
|
|
65
|
+
events: readEvents(cfg),
|
|
66
|
+
runs: a.runSource(cfg).listRuns(nowSec() - cfg.labels.episode_days * 86400),
|
|
67
|
+
}, nowSec());
|
|
68
|
+
console.log(`labels update ${repo}: ${result.labels.length} label(s), ${result.imported.length} imported, ${result.flips.length} flip(s)`);
|
|
69
|
+
if (result.importError) console.error(`labels update: whytrail import skipped: ${result.importError}`);
|
|
70
|
+
for (const f of result.flips) console.log(`flipped ${f.episode} (party ${f.party}, fix ${f.fixSha})`);
|
|
71
|
+
return 0;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function runExport(args: string[], cfg: Config): number {
|
|
75
|
+
let good = false;
|
|
76
|
+
let json = false;
|
|
77
|
+
let minAge = 14;
|
|
78
|
+
for (let i = 0; i < args.length; i++) {
|
|
79
|
+
const arg = args[i]!;
|
|
80
|
+
if (arg === "--good") good = true;
|
|
81
|
+
else if (arg === "--json") json = true;
|
|
82
|
+
else if (arg === "--min-age-days") minAge = Number(args[++i]);
|
|
83
|
+
else { console.error(USAGE); return 2; }
|
|
84
|
+
}
|
|
85
|
+
if (!good || !Number.isFinite(minAge) || minAge < 0) { console.error(USAGE); return 2; }
|
|
86
|
+
const a = getAdapter(cfg);
|
|
87
|
+
const episodes = a.episodes(cfg, nowSec() - cfg.labels.episode_days * 86400);
|
|
88
|
+
const rows = goodSet(cfg, episodes, a.scoreTraces(cfg), nowSec(), minAge);
|
|
89
|
+
if (json) console.log(JSON.stringify(rows, null, 2));
|
|
90
|
+
else if (rows.length === 0) console.log("no good episodes past the min age");
|
|
91
|
+
else for (const r of rows) console.log(`${r.runId} ${r.briefRef ?? "-"} ${r.commits.join(",") || "-"} wasted=[${r.wasted.join(",")}]`);
|
|
92
|
+
return 0;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function runAssign(args: string[], cfg: Config): number {
|
|
96
|
+
const episode = args[0];
|
|
97
|
+
if (!episode || episode.startsWith("-")) { console.error(USAGE); return 2; }
|
|
98
|
+
let party: string | undefined;
|
|
99
|
+
let why: string | undefined;
|
|
100
|
+
for (let i = 1; i < args.length; i++) {
|
|
101
|
+
const arg = args[i]!;
|
|
102
|
+
if (arg === "--party") party = args[++i];
|
|
103
|
+
else if (arg === "--why") why = args[++i];
|
|
104
|
+
else { console.error(USAGE); return 2; }
|
|
105
|
+
}
|
|
106
|
+
if ((party !== "plan" && party !== "implementer" && party !== "both") || !why) { console.error(USAGE); return 2; }
|
|
107
|
+
const line = assignLabel(cfg.paths.score_state, episode, party, why, nowSec());
|
|
108
|
+
console.log(`${line.episode} ${line.label} ${line.party}`);
|
|
109
|
+
return 0;
|
|
110
|
+
}
|
package/src/core/agent-score.ts
CHANGED
|
@@ -7,6 +7,7 @@ import { exitText, helpDoc, printText } from "./help.ts";
|
|
|
7
7
|
import { formatG, pyFixed, pyPercent0 } from "./pyfmt.ts";
|
|
8
8
|
import { PyFloat, pyDumps } from "./pyjson.ts";
|
|
9
9
|
import { gitRaw } from "./proc.ts";
|
|
10
|
+
import { flippedEpisodes } from "./labels.ts";
|
|
10
11
|
import { efficiencyRules, runEfficiency } from "./trace-efficiency.ts";
|
|
11
12
|
|
|
12
13
|
function opt(args: string[], name: string): string | undefined {
|
|
@@ -193,6 +194,12 @@ interface Row {
|
|
|
193
194
|
fp: number | null;
|
|
194
195
|
}
|
|
195
196
|
|
|
197
|
+
function blankRow(model: string): Row {
|
|
198
|
+
return {
|
|
199
|
+
model, runs: 0, done: 0, running: 0, cost: 0, steer: 0, hours: 0, pts: 0, acc: 0, first: 0, pen: 0, diag: 0, val: 0, calls: 0, wasted: 0,
|
|
200
|
+
net: 0, total: 0, ppd: null, pph: null, surv: null, fp: null,
|
|
201
|
+
};
|
|
202
|
+
}
|
|
196
203
|
function ocRuns(cfg: Config, cut: number): { agent: string; model: string; cost: number; hours: number; survived: boolean; running: boolean; end: string }[] {
|
|
197
204
|
const path = join(cfg.paths.score_state, "oc-runs.jsonl");
|
|
198
205
|
if (!existsSync(path)) return [];
|
|
@@ -222,7 +229,7 @@ function namedRunModel(cfg: Config, source: RunSource, agent: string): string |
|
|
|
222
229
|
const cut = nowSec() - cfg.score.board_days * 86400;
|
|
223
230
|
const sub = source.listRuns(cut).find(r => r.kind === "sub" && r.id === agent);
|
|
224
231
|
if (sub) return sub.scoreModel;
|
|
225
|
-
const oc = ocRuns(cfg, cut).
|
|
232
|
+
const oc = ocRuns(cfg, cut).findLast(r => r.agent === agent);
|
|
226
233
|
return oc ? oc.model : null;
|
|
227
234
|
}
|
|
228
235
|
|
|
@@ -231,7 +238,7 @@ function unnamedRefusal(agent: string): number {
|
|
|
231
238
|
}
|
|
232
239
|
|
|
233
240
|
function steering(runs: Run[], names: string[]): Record<string, number> {
|
|
234
|
-
const ordered = names.
|
|
241
|
+
const ordered = names.toSorted((a, b) => b.length - a.length);
|
|
235
242
|
const out: Record<string, number> = {};
|
|
236
243
|
for (const n of names) out[n] = 0;
|
|
237
244
|
for (const run of runs) {
|
|
@@ -270,12 +277,8 @@ function table(days: number, cfg: Config, source: RunSource): { rows: Row[]; byA
|
|
|
270
277
|
const agentModel = new Map<string, string>();
|
|
271
278
|
for (const [n, r] of byAgent) agentModel.set(n, r.model);
|
|
272
279
|
const rows = new Map<string, Row>();
|
|
273
|
-
const blank = (model: string): Row => ({
|
|
274
|
-
model, runs: 0, done: 0, running: 0, cost: 0, steer: 0, hours: 0, pts: 0, acc: 0, first: 0, pen: 0, diag: 0, val: 0, calls: 0, wasted: 0,
|
|
275
|
-
net: 0, total: 0, ppd: null, pph: null, surv: null, fp: null,
|
|
276
|
-
});
|
|
277
280
|
for (const r of byAgent.values()) {
|
|
278
|
-
const m = rows.get(r.model) ??
|
|
281
|
+
const m = rows.get(r.model) ?? blankRow(r.model);
|
|
279
282
|
m.runs += 1;
|
|
280
283
|
m.running += r.running ? 1 : 0;
|
|
281
284
|
m.done += r.survived ? 1 : 0;
|
|
@@ -287,12 +290,26 @@ function table(days: number, cfg: Config, source: RunSource): { rows: Row[]; byA
|
|
|
287
290
|
const m = rows.get(r.model)!;
|
|
288
291
|
m.steer += steer[n] ?? 0;
|
|
289
292
|
}
|
|
293
|
+
const flips = new Map(flippedEpisodes(cfg.paths.score_state).map(f => [f.episode, f.party]));
|
|
290
294
|
for (const e of evs) {
|
|
291
295
|
const agent = String(e.agent ?? "");
|
|
292
296
|
const model = (typeof e.model === "string" && e.model) || agentModel.get(agent) || "?";
|
|
293
|
-
const m = rows.get(model) ??
|
|
297
|
+
const m = rows.get(model) ?? blankRow(model);
|
|
294
298
|
if (e.type === "accept" || e.type === "diagnose" || e.type === "validate") {
|
|
295
299
|
m.pts += Number(e.weight);
|
|
300
|
+
if (e.type === "accept") {
|
|
301
|
+
const flipParty = flips.get(`${agent}:${String(e.plan ?? "")}:${String(e.phase ?? "")}`);
|
|
302
|
+
const loss = flipParty === undefined ? 0 : cfg.labels.flip_weight * Number(e.weight);
|
|
303
|
+
if (Number.isFinite(loss) && loss !== 0) {
|
|
304
|
+
// The episode loses its accept points. plan and both also count against MAIN.
|
|
305
|
+
m.pts -= loss;
|
|
306
|
+
if (flipParty === "plan" || flipParty === "both") {
|
|
307
|
+
const main = rows.get("MAIN") ?? blankRow("MAIN");
|
|
308
|
+
main.pts -= loss;
|
|
309
|
+
rows.set("MAIN", main);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
296
313
|
m.acc += 1;
|
|
297
314
|
m.first += e.rework ? 0 : 1;
|
|
298
315
|
m.diag += e.type === "diagnose" ? 1 : 0;
|
|
@@ -548,8 +565,7 @@ export function agentScore(args: string[], cfg: Config, source: RunSource, trace
|
|
|
548
565
|
// provider — known from its pin, accepted work or not — is named instead of the
|
|
549
566
|
// target; a later paid agent is never recommended while an earlier one is free.
|
|
550
567
|
const prefer = cfg.ledger.prefer;
|
|
551
|
-
const
|
|
552
|
-
const rankOf = (model: string): number => prefer.findIndex(p => lower(model).includes(lower(p)));
|
|
568
|
+
const rankOf = (model: string): number => prefer.findIndex(p => model.toLowerCase().includes(p.toLowerCase()));
|
|
553
569
|
const targetRank = rankOf(target);
|
|
554
570
|
let blocked: string | null = null;
|
|
555
571
|
for (let j = 0; j < (targetRank === -1 ? prefer.length : targetRank); j++) {
|
package/src/core/config.ts
CHANGED
|
@@ -275,6 +275,14 @@ export interface Config {
|
|
|
275
275
|
priority: { sleep_sec: number };
|
|
276
276
|
alerts: { temp_c: number; mem_psi: number; io_psi: number; cooldown_sec: number };
|
|
277
277
|
snapshot: { tmp_dest: string; git_repo: string; git_backup: string; excludes: string[] };
|
|
278
|
+
labels: {
|
|
279
|
+
episode_days: number;
|
|
280
|
+
flip_weight: number;
|
|
281
|
+
repos: string[];
|
|
282
|
+
/** Removal check (src/core/diff-check.ts, plan 20261024_1915): added comment lines matching one of these regexes are flagged by `neurastream diff-check` and the plan-guard commit gate; a commit subject matching removal_subjects flags every added non-blank line. A regex that does not compile is skipped, never blocks. */
|
|
283
|
+
removal_comment_patterns: string[];
|
|
284
|
+
removal_subjects: string[];
|
|
285
|
+
};
|
|
278
286
|
/** Trace rules: provider honesty (src/core/trace-provider.ts) and what a scanned run may read, dial and write (src/core/trace-actions.ts). */
|
|
279
287
|
traces: {
|
|
280
288
|
/** What an honest provider answer looks like. */
|
|
@@ -610,6 +618,15 @@ function check(cfg: Config): void {
|
|
|
610
618
|
if (!(cfg.guards.rate_limit.slack_s >= 0)) throw new ConfigError("guards.rate_limit.slack_s must be >= 0");
|
|
611
619
|
if (!(cfg.rollover.exit_grace_s > 0)) throw new ConfigError("rollover.exit_grace_s must be > 0");
|
|
612
620
|
if (!(cfg.metrics.report_days >= 1)) throw new ConfigError("metrics.report_days must be >= 1");
|
|
621
|
+
if (!(cfg.labels.episode_days >= 1)) throw new ConfigError("labels.episode_days must be >= 1");
|
|
622
|
+
if (!Array.isArray(cfg.labels.repos) || cfg.labels.repos.some(r => typeof r !== "string" || r === "")) throw new ConfigError("labels.repos must be a list of repo directories");
|
|
623
|
+
if (!(cfg.labels.flip_weight >= 0 && cfg.labels.flip_weight <= 1)) throw new ConfigError("labels.flip_weight must be >= 0 and <= 1");
|
|
624
|
+
// Structure only: a non-compiling pattern is skipped at scan time (diff-check.ts fail-open), never thrown here.
|
|
625
|
+
for (const key of ["removal_comment_patterns", "removal_subjects"] as const) {
|
|
626
|
+
const list = cfg.labels[key];
|
|
627
|
+
if (!Array.isArray(list) || list.some(p => typeof p !== "string" || p === ""))
|
|
628
|
+
throw new ConfigError(`labels.${key} must be a list of non-empty regex strings`);
|
|
629
|
+
}
|
|
613
630
|
if (!(cfg.queue.claim_ttl_min >= 1)) throw new ConfigError("queue.claim_ttl_min must be >= 1");
|
|
614
631
|
if (!(cfg.ui.port >= 1 && cfg.ui.port <= 65535)) throw new ConfigError("ui.port must be between 1 and 65535");
|
|
615
632
|
if (!Number.isInteger(cfg.pages.port) || cfg.pages.port < 1 || cfg.pages.port > 65535) throw new ConfigError("pages.port must be an integer between 1 and 65535");
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// P6 (plan 20261024_1915): the removal check. Comments that speak of removal ("removed", "no
|
|
2
|
+
// longer", "previously") lie once the code they describe is gone, so an added comment line
|
|
3
|
+
// matching labels.removal_comment_patterns is flagged, and a commit whose subject matches
|
|
4
|
+
// labels.removal_subjects flags every added non-blank line. Pure deletions pass. A config regex
|
|
5
|
+
// that does not compile is skipped (write-check.ts's fail-open note convention: a broken pattern
|
|
6
|
+
// never blocks a commit). The plan-guard commit gate (guards.ts subRules) scans the staged diff
|
|
7
|
+
// through here; `neurastream diff-check` (src/cli/diff-check.ts) scans --staged or one commit.
|
|
8
|
+
|
|
9
|
+
import { execFileSync } from "node:child_process";
|
|
10
|
+
import type { Config } from "./config.ts";
|
|
11
|
+
|
|
12
|
+
export interface RemovalFlag {
|
|
13
|
+
file: string;
|
|
14
|
+
line: number;
|
|
15
|
+
text: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// An added line that reads as a comment: //, # (shell/py/yaml/ruby), /* or a * block
|
|
19
|
+
// continuation, or an HTML comment.
|
|
20
|
+
const COMMENT_LINE = /^\s*(\/\/|#+|\/\*+|\*+|<!--)/;
|
|
21
|
+
// Hunk header: the new-file start of `@@ -a,b +c,d @@` (an extra @ covers combined diffs).
|
|
22
|
+
const HUNK = /^@+ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @+/;
|
|
23
|
+
|
|
24
|
+
// Every pattern that compiles; the rest are skipped silently (fail-open), never thrown.
|
|
25
|
+
function compiled(patterns: unknown): RegExp[] {
|
|
26
|
+
const out: RegExp[] = [];
|
|
27
|
+
if (!Array.isArray(patterns)) return out;
|
|
28
|
+
for (const p of patterns) {
|
|
29
|
+
if (typeof p !== "string" || p === "") continue;
|
|
30
|
+
try {
|
|
31
|
+
out.push(new RegExp(p));
|
|
32
|
+
} catch { /* a pattern that does not compile checks nothing (write-check.ts:126) */ }
|
|
33
|
+
}
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The added non-blank lines of a unified diff the removal check flags: comment lines matching
|
|
39
|
+
* labels.removal_comment_patterns, and — when `subject` matches labels.removal_subjects — every
|
|
40
|
+
* added non-blank line. Removed and context lines never flag; an empty subject (a staged diff has
|
|
41
|
+
* no commit yet) skips the subject match.
|
|
42
|
+
*/
|
|
43
|
+
export function removalFlags(diff: string, subject: string, cfg: Config): RemovalFlag[] {
|
|
44
|
+
const comments = compiled(cfg.labels.removal_comment_patterns);
|
|
45
|
+
const removal = subject !== "" && compiled(cfg.labels.removal_subjects).some(re => re.test(subject));
|
|
46
|
+
if (!removal && comments.length === 0) return [];
|
|
47
|
+
const flags: RemovalFlag[] = [];
|
|
48
|
+
let file = "";
|
|
49
|
+
let line = 0;
|
|
50
|
+
for (const raw of diff.split("\n")) {
|
|
51
|
+
if (raw.startsWith("diff --git ")) {
|
|
52
|
+
file = "";
|
|
53
|
+
line = 0;
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
// The post-image header names the file (renames included); /dev/null means a pure deletion.
|
|
57
|
+
// A content line that happens to start with "+++ " but names neither falls through to the
|
|
58
|
+
// added-line branch below.
|
|
59
|
+
if (raw.startsWith("+++ ")) {
|
|
60
|
+
const p = raw.slice(4);
|
|
61
|
+
if (p.startsWith("b/") || p === "/dev/null") {
|
|
62
|
+
file = p.startsWith("b/") ? p.slice(2) : p;
|
|
63
|
+
line = 0;
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const hunk = HUNK.exec(raw);
|
|
68
|
+
if (hunk) {
|
|
69
|
+
line = Number(hunk[1]) - 1;
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (!raw.startsWith("+")) {
|
|
73
|
+
// "-" removed lines and "\ No newline" carry no new-file line number; context (" ") does.
|
|
74
|
+
if (raw.startsWith(" ")) line += 1;
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
const text = raw.slice(1);
|
|
78
|
+
const isComment = COMMENT_LINE.test(text);
|
|
79
|
+
if (text.trim() !== "" && (removal || (isComment && comments.some(re => re.test(text)))))
|
|
80
|
+
flags.push({ file, line: line + 1, text });
|
|
81
|
+
line += 1;
|
|
82
|
+
}
|
|
83
|
+
return flags;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** `git diff --staged` in `dir`. Throws when git fails; callers pick their failure mode (the guard fails open, the CLI reports). maxBuffer is generous: a staged lockfile diff must not truncate the scan. */
|
|
87
|
+
export function stagedDiff(dir: string): string {
|
|
88
|
+
return execFileSync("git", ["diff", "--staged"], { cwd: dir, encoding: "utf8", maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "ignore"] });
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** One commit's patch (`git show`) with its subject line, for removalFlags. Throws when git fails. */
|
|
92
|
+
export function commitDiff(dir: string, rev: string): { diff: string; subject: string } {
|
|
93
|
+
const subject = execFileSync("git", ["log", "-1", "--format=%s", rev], { cwd: dir, encoding: "utf8", maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
94
|
+
const diff = execFileSync("git", ["show", "--format=", "--patch", "--no-ext-diff", rev], { cwd: dir, encoding: "utf8", maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "ignore"] });
|
|
95
|
+
return { diff, subject };
|
|
96
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { Run, RunSource } from "./adapter.ts";
|
|
2
|
+
import type { SpawnBrief } from "./trace-briefs.ts";
|
|
3
|
+
|
|
4
|
+
export interface Episode {
|
|
5
|
+
id: string;
|
|
6
|
+
agent: string;
|
|
7
|
+
model: string;
|
|
8
|
+
plan: string;
|
|
9
|
+
phase: string;
|
|
10
|
+
repo: string;
|
|
11
|
+
commits: string[];
|
|
12
|
+
runId: string;
|
|
13
|
+
briefRef: string | null;
|
|
14
|
+
acceptedAt: number | null;
|
|
15
|
+
rework: boolean;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export type EpisodeScoreEvent = Record<string, unknown>;
|
|
19
|
+
|
|
20
|
+
function failedRun(run: Run): boolean {
|
|
21
|
+
return run.status === "died" || /OVER-BUDGET\(/i.test(run.statusDetail);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function buildEpisodes(runs: RunSource, events: EpisodeScoreEvent[], briefs: SpawnBrief[], since: number): Episode[] {
|
|
25
|
+
const listed = runs.listRuns(since).filter(run => run.kind === "sub");
|
|
26
|
+
const output: Episode[] = [];
|
|
27
|
+
for (const run of listed) {
|
|
28
|
+
const runEvents = events.filter(event => event.agent === run.id && ["accept", "validate", "diagnose", "penalty"].includes(String(event.type)));
|
|
29
|
+
const acceptance = runEvents.find(event => event.type === "accept" || event.type === "validate");
|
|
30
|
+
if (runEvents.length === 0 && !failedRun(run)) continue;
|
|
31
|
+
const score = acceptance ?? runEvents[0];
|
|
32
|
+
const brief = briefs.reduce<SpawnBrief | undefined>((best, candidate) => {
|
|
33
|
+
if (candidate.agent !== run.id || (candidate.ts !== null && run.startedAt !== null && candidate.ts > run.startedAt)) return best;
|
|
34
|
+
if (!best || (candidate.ts !== null && (best.ts === null || candidate.ts > best.ts))) return candidate;
|
|
35
|
+
return best;
|
|
36
|
+
}, undefined);
|
|
37
|
+
output.push({
|
|
38
|
+
id: `${run.id}:${String(score?.plan ?? "")}:${String(score?.phase ?? "")}`,
|
|
39
|
+
agent: run.id,
|
|
40
|
+
model: run.model,
|
|
41
|
+
plan: String(score?.plan ?? ""),
|
|
42
|
+
phase: String(score?.phase ?? ""),
|
|
43
|
+
repo: String(score?.repo ?? ""),
|
|
44
|
+
commits: Array.isArray(acceptance?.commits) ? acceptance.commits.map(String) : [],
|
|
45
|
+
runId: run.id,
|
|
46
|
+
briefRef: brief ? `${brief.ts ?? ""}:${brief.agent}` : null,
|
|
47
|
+
acceptedAt: typeof acceptance?.ts === "number" ? acceptance.ts : null,
|
|
48
|
+
rework: acceptance?.rework === true,
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
return output;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
|
package/src/core/guards.ts
CHANGED
|
@@ -42,6 +42,7 @@ import { fileClaimStore, type Claim, type ClaimStore } from "./claims.ts";
|
|
|
42
42
|
import { nowSec, strftime } from "./clock.ts";
|
|
43
43
|
import { outUntil, pinModel, providerOfModel, readOut } from "./provider-state.ts";
|
|
44
44
|
import { lint } from "./brief-lint.ts";
|
|
45
|
+
import { removalFlags, stagedDiff, type RemovalFlag } from "./diff-check.ts";
|
|
45
46
|
const ALLOW: Decision = { allow: true, reason: "" };
|
|
46
47
|
|
|
47
48
|
/**
|
|
@@ -1264,10 +1265,12 @@ function landingCommand(input: Record<string, unknown>): boolean {
|
|
|
1264
1265
|
// write. Landing and commit commands produce no write targets, so this text filter — not
|
|
1265
1266
|
// writeTargets — is what keeps them out of the review lock's shell allow and the blocker skip.
|
|
1266
1267
|
// One predicate for both callers; reviewLockProblem denies it, subRules keeps the blockers on it.
|
|
1268
|
+
// The removal check uses the commit alternative only: `git add` stages; the check judges at commit.
|
|
1269
|
+
const GIT_ADD_OR_COMMIT = /\bgit\s+(add|commit)\b/;
|
|
1267
1270
|
function writesShellText(input: Record<string, unknown>, cfg: Config): boolean {
|
|
1268
1271
|
if (landingCommand(input)) return true;
|
|
1269
1272
|
const text = q.withoutQuotedRedirects(Object.values(input).filter((v): v is string => typeof v === "string").join("\n"));
|
|
1270
|
-
if (
|
|
1273
|
+
if (GIT_ADD_OR_COMMIT.test(text) || /\bnpm\s+publish\b/.test(text)) return true;
|
|
1271
1274
|
if (cfg.guards.bypass_spawn.some(entry => bypassRegExp(entry).test(text))) return true;
|
|
1272
1275
|
return q.MUTATING.test(text);
|
|
1273
1276
|
}
|
|
@@ -1299,6 +1302,25 @@ function pathArgs(input: Record<string, unknown>): Record<string, unknown> {
|
|
|
1299
1302
|
// Subagent half of a tool call (the original plan-guard checkCall without the main return).
|
|
1300
1303
|
// `cap` is the sub's hard call cap: its recorded per-spawn budget, else the global sub_max_calls.
|
|
1301
1304
|
function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[], writes: string[], cfg: Config, cap: number): string | null {
|
|
1305
|
+
// P6 (plan 20261024_1915): a sub's `git commit` is scanned first — its staged diff must not add
|
|
1306
|
+
// the removal comments diff-check flags. Detected through GIT_ADD_OR_COMMIT (the predicate
|
|
1307
|
+
// writesShellText carries); the refusal goes back through checkTool's deny(). Git that cannot
|
|
1308
|
+
// be read fails open (write-check.ts: a broken scan never blocks). Main is not gated: only
|
|
1309
|
+
// subRules sees this. A staged diff has no subject yet, so the subject rule is the CLI's <rev>.
|
|
1310
|
+
if (cfg.guards.shell_tools.includes(e.tool)) {
|
|
1311
|
+
const git = GIT_ADD_OR_COMMIT.exec(q.withoutQuotedRedirects(Object.values(input).filter((v): v is string => typeof v === "string").join("\n")));
|
|
1312
|
+
if (git?.[1] === "commit") {
|
|
1313
|
+
let flags: RemovalFlag[] = [];
|
|
1314
|
+
try {
|
|
1315
|
+
flags = removalFlags(stagedDiff(e.cwd), "", cfg);
|
|
1316
|
+
} catch { /* no readable repo in this cwd: nothing to flag */ }
|
|
1317
|
+
if (flags.length)
|
|
1318
|
+
return (
|
|
1319
|
+
"git commit refused: the staged diff adds removal comments (reword or drop them, then re-stage):\n" +
|
|
1320
|
+
flags.map(f => `${f.file}:${f.line}: ${f.text}`).join("\n")
|
|
1321
|
+
);
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1302
1324
|
// Closing and cancelling are Main's decisions: a shell that runs the tool is refused; one that only names its path is not.
|
|
1303
1325
|
if (cfg.guards.shell_tools.includes(e.tool) && runsCloser(input))
|
|
1304
1326
|
return 'queue-close and queue-cancel are Main\'s; report in your plan\'s "## Progress" instead.';
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { basename, join } from "node:path";
|
|
5
|
+
import type { Episode } from "./episodes.ts";
|
|
6
|
+
import { appendLabel, type EpisodeLabel } from "./labels.ts";
|
|
7
|
+
|
|
8
|
+
export type PlanLabelFlag = "bad" | "good" | "open";
|
|
9
|
+
|
|
10
|
+
/** One `whytrail labels --json` row (whytrail lineage.ts PlanLabel). */
|
|
11
|
+
export interface PlanLabel {
|
|
12
|
+
plan: string;
|
|
13
|
+
label: PlanLabelFlag;
|
|
14
|
+
by?: string;
|
|
15
|
+
goal?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** whytrail names plans by basename without .md; episode.plan holds the full accept --plan path. */
|
|
19
|
+
export function planKey(plan: string): string {
|
|
20
|
+
return basename(plan).replace(/\.md$/, "");
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** The cards.jsonl whytrail `labels` rewrites, resolved exactly like whytrail's repoContext (whytrail git.ts:45-51): the absolute git common dir with one trailing /.git (then one /) stripped. */
|
|
24
|
+
function cardsPathFor(repo: string): string {
|
|
25
|
+
const common = execFileSync("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], { cwd: repo, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
26
|
+
return join(common.replace(/\/\.git$/, "").replace(/\/$/, ""), ".whytrail", "cards.jsonl");
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface ImportOpts {
|
|
30
|
+
/** PATH for the whytrail lookup; defaults to the process PATH (tests pin a stub dir). */
|
|
31
|
+
path?: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Run `whytrail labels --json --repo <repo>` and append one ledger line per matching episode.
|
|
36
|
+
* The call is a pure read in effect: the child gets no provider key and an empty temp HOME (so
|
|
37
|
+
* whytrail classifies nothing), and the cards.jsonl whytrail always rewrites is snapshotted and
|
|
38
|
+
* restored in a finally that wraps the whole call — a write-then-throw restores too, and a file
|
|
39
|
+
* absent before stays absent after. Plans labelled open (or unmatched by any episode) append
|
|
40
|
+
* nothing: unknown is thrown away, not guessed.
|
|
41
|
+
*/
|
|
42
|
+
export function importWhytrailLabels(repo: string, scoreState: string, episodes: Episode[], ts: number, opts: ImportOpts = {}): EpisodeLabel[] {
|
|
43
|
+
const cards = cardsPathFor(repo);
|
|
44
|
+
const snapshot = existsSync(cards) ? readFileSync(cards) : null;
|
|
45
|
+
const home = mkdtempSync(join(tmpdir(), "whytrail-home-"));
|
|
46
|
+
const env = { ...process.env };
|
|
47
|
+
delete env.OPENROUTER_API_KEY;
|
|
48
|
+
env.HOME = home;
|
|
49
|
+
if (opts.path !== undefined) env.PATH = opts.path;
|
|
50
|
+
try {
|
|
51
|
+
let out: string;
|
|
52
|
+
try {
|
|
53
|
+
out = execFileSync("whytrail", ["labels", "--json", "--repo", repo], {
|
|
54
|
+
cwd: repo,
|
|
55
|
+
env,
|
|
56
|
+
encoding: "utf8",
|
|
57
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
58
|
+
});
|
|
59
|
+
} catch (error) {
|
|
60
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
61
|
+
throw new Error(`whytrail labels failed for ${repo}: ${detail}`, { cause: error });
|
|
62
|
+
}
|
|
63
|
+
const rows = JSON.parse(out) as PlanLabel[];
|
|
64
|
+
const byPlan = new Map<string, Episode[]>();
|
|
65
|
+
for (const episode of episodes) {
|
|
66
|
+
const key = planKey(episode.plan);
|
|
67
|
+
const same = byPlan.get(key);
|
|
68
|
+
if (same) same.push(episode);
|
|
69
|
+
else byPlan.set(key, [episode]);
|
|
70
|
+
}
|
|
71
|
+
const appended: EpisodeLabel[] = [];
|
|
72
|
+
for (const row of rows) {
|
|
73
|
+
// open (and anything else) is no line; every appended row is party "none" — real parties are P4.
|
|
74
|
+
if ((row.label !== "bad" && row.label !== "good") || !row.plan) continue;
|
|
75
|
+
const targets = byPlan.get(planKey(row.plan));
|
|
76
|
+
if (!targets) continue;
|
|
77
|
+
for (const episode of targets) {
|
|
78
|
+
const label: EpisodeLabel = {
|
|
79
|
+
ts,
|
|
80
|
+
episode: episode.id,
|
|
81
|
+
label: row.label,
|
|
82
|
+
reason: row.goal !== undefined && row.goal.trim() !== "" ? row.goal : `whytrail plan ${row.plan}: ${row.label}`,
|
|
83
|
+
party: "none",
|
|
84
|
+
evidence: `whytrail labels: plan ${row.plan} ${row.label}`,
|
|
85
|
+
};
|
|
86
|
+
if (row.by) label.found_by = row.by;
|
|
87
|
+
appendLabel(scoreState, label);
|
|
88
|
+
appended.push(label);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return appended;
|
|
92
|
+
} finally {
|
|
93
|
+
if (snapshot === null) rmSync(cards, { force: true });
|
|
94
|
+
else writeFileSync(cards, snapshot);
|
|
95
|
+
rmSync(home, { recursive: true, force: true });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// `labels update` and `labels export --good` (plan 20261024_1915 P5 + P5b). update runs the P2
|
|
2
|
+
// labeller and the P3 whytrail import over the episodes since the ledger's watermark line, rescans
|
|
3
|
+
// good episodes for flips (a later revert, a penalty) and opens one `work-turned-bad` incident
|
|
4
|
+
// per flip; export lists the good set. The watermark, the idempotency and the incident dedup all
|
|
5
|
+
// live in the ledger, so a quiet second run appends nothing.
|
|
6
|
+
|
|
7
|
+
import type { Run, TraceSource } from "./adapter.ts";
|
|
8
|
+
import type { Config } from "./config.ts";
|
|
9
|
+
import type { Episode, EpisodeScoreEvent } from "./episodes.ts";
|
|
10
|
+
import { addIncident } from "./incidents.ts";
|
|
11
|
+
import { importWhytrailLabels } from "./label-import.ts";
|
|
12
|
+
import type { EpisodeLabel, LabelParty } from "./labels.ts";
|
|
13
|
+
import { appendWatermark, appendLabel, flipAccepted, flippedEpisodes, labelAndAppend, labelEpisodes, readWatermark, readLabels } from "./labels.ts";
|
|
14
|
+
import { efficiencyRules, runEfficiency } from "./trace-efficiency.ts";
|
|
15
|
+
|
|
16
|
+
export interface LabelUpdateDeps {
|
|
17
|
+
/** Episodes whose runs started after the cutoff (the CLI's buildEpisodes window). */
|
|
18
|
+
episodesFor: (cutoff: number) => Episode[];
|
|
19
|
+
events: EpisodeScoreEvent[];
|
|
20
|
+
runs: Run[];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface LabelFlip {
|
|
24
|
+
episode: string;
|
|
25
|
+
party: LabelParty;
|
|
26
|
+
/** The commit that turned the work bad — the revert sha, or the labeller's reason when no sha exists. */
|
|
27
|
+
fixSha: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface UpdateResult {
|
|
31
|
+
/** P2 label lines appended for episodes new since the watermark. */
|
|
32
|
+
labels: EpisodeLabel[];
|
|
33
|
+
/** P3 whytrail lines appended for those episodes. */
|
|
34
|
+
imported: EpisodeLabel[];
|
|
35
|
+
/** Good episodes this run turned bad, one incident each. */
|
|
36
|
+
flips: LabelFlip[];
|
|
37
|
+
/** Why the P3 import did not run to completion; the update itself still lands. */
|
|
38
|
+
importError?: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* One update pass. New episodes (runs after the watermark) get their first P2/P3 lines; every
|
|
43
|
+
* rebuildable good episode is recomputed and flipped when the labeller now calls it bad. The
|
|
44
|
+
* watermark advances only when something was appended, so a run with nothing new appends nothing.
|
|
45
|
+
*/
|
|
46
|
+
export function updateLabels(cfg: Config, repo: string, deps: LabelUpdateDeps, now: number): UpdateResult {
|
|
47
|
+
const state = cfg.paths.score_state;
|
|
48
|
+
const windowStart = now - cfg.labels.episode_days * 86400;
|
|
49
|
+
const cutoff = readWatermark(state) ?? windowStart;
|
|
50
|
+
const fresh = deps.episodesFor(cutoff);
|
|
51
|
+
const labels = labelAndAppend(state, fresh, deps.events, deps.runs, now);
|
|
52
|
+
let imported: EpisodeLabel[] = [];
|
|
53
|
+
let importError: string | undefined;
|
|
54
|
+
if (fresh.length > 0) {
|
|
55
|
+
try {
|
|
56
|
+
imported = importWhytrailLabels(repo, state, fresh, now);
|
|
57
|
+
} catch (error) {
|
|
58
|
+
importError = error instanceof Error ? error.message : String(error);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
// Flip scan (P5b): the ledger's latest labels against a fresh labeller pass over the window.
|
|
62
|
+
const latest = new Map(readLabels(state).map(l => [l.episode, l]));
|
|
63
|
+
const windowed = deps.episodesFor(windowStart);
|
|
64
|
+
const computed = labelEpisodes(windowed, deps.events, deps.runs, now);
|
|
65
|
+
const flips: LabelFlip[] = [];
|
|
66
|
+
windowed.forEach((episode, i) => {
|
|
67
|
+
const c = computed[i]!;
|
|
68
|
+
if (latest.get(episode.id)?.label !== "good" || c.label !== "bad") return;
|
|
69
|
+
const fixSha = c.found_by ?? c.reason;
|
|
70
|
+
let party: LabelParty;
|
|
71
|
+
if (episode.acceptedAt !== null) {
|
|
72
|
+
party = flipAccepted(cfg, episode, fixSha, now).party;
|
|
73
|
+
} else {
|
|
74
|
+
// Good without an accept (a whytrail import) takes no P4 party/test pair: one plain flip line.
|
|
75
|
+
appendLabel(state, { ts: now, episode: episode.id, label: "bad", reason: `flipped by ${fixSha}`, party: "none", evidence: c.evidence, found_by: fixSha });
|
|
76
|
+
party = "none";
|
|
77
|
+
}
|
|
78
|
+
addIncident(cfg, {
|
|
79
|
+
source: "traces",
|
|
80
|
+
kind: "work-turned-bad",
|
|
81
|
+
summary: `work-turned-bad: agent ${episode.agent} plan ${episode.plan} phase ${episode.phase} fix ${fixSha} party ${party}`,
|
|
82
|
+
evidence: c.evidence,
|
|
83
|
+
fingerprint: `work-turned-bad:${episode.id}:${fixSha}`,
|
|
84
|
+
}, now);
|
|
85
|
+
flips.push({ episode: episode.id, party, fixSha });
|
|
86
|
+
});
|
|
87
|
+
if (labels.length + imported.length + flips.length > 0) appendWatermark(state, now);
|
|
88
|
+
return { labels, imported, flips, importError };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export interface GoodRow {
|
|
92
|
+
runId: string;
|
|
93
|
+
briefRef: string | null;
|
|
94
|
+
commits: string[];
|
|
95
|
+
/** Ordinals among the run's tool calls that traces 05 (trace-efficiency) marks wasted. */
|
|
96
|
+
wasted: number[];
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The good set: latest label good, older than the min age, never flipped. */
|
|
100
|
+
export function goodSet(cfg: Config, episodes: Episode[], traceSrc: TraceSource | null, now: number, minAgeDays: number): GoodRow[] {
|
|
101
|
+
const state = cfg.paths.score_state;
|
|
102
|
+
const latest = new Map(readLabels(state).map(l => [l.episode, l]));
|
|
103
|
+
const flipped = new Set(flippedEpisodes(state).map(f => f.episode));
|
|
104
|
+
const oldest = now - minAgeDays * 86400;
|
|
105
|
+
const out: GoodRow[] = [];
|
|
106
|
+
for (const e of episodes) {
|
|
107
|
+
if (latest.get(e.id)?.label !== "good") continue;
|
|
108
|
+
if (flipped.has(e.id)) continue;
|
|
109
|
+
if (e.acceptedAt === null || e.acceptedAt > oldest) continue;
|
|
110
|
+
const wasted = traceSrc ? runEfficiency(traceSrc.events(e.runId), efficiencyRules(cfg)).steps.map(s => s.index) : [];
|
|
111
|
+
out.push({ runId: e.runId, briefRef: e.briefRef, commits: e.commits, wasted });
|
|
112
|
+
}
|
|
113
|
+
return out;
|
|
114
|
+
}
|