neurastream 0.2.80 → 0.2.82
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 +13 -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 +2 -1
- 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/src/core/wip-roots.ts +6 -1
- package/templates/AGENTS.md +1 -0
- package/templates/config.yml +11 -0
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import { appendFileSync, mkdirSync, readFileSync, existsSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { execFileSync } from "node:child_process";
|
|
4
|
+
import type { Run } from "./adapter.ts";
|
|
5
|
+
import type { Config } from "./config.ts";
|
|
6
|
+
import type { Episode, EpisodeScoreEvent } from "./episodes.ts";
|
|
7
|
+
import { addIncident } from "./incidents.ts";
|
|
8
|
+
|
|
9
|
+
export type WorkLabel = "good" | "bad" | "unknown";
|
|
10
|
+
export type LabelParty = "plan" | "implementer" | "both" | "test" | "none";
|
|
11
|
+
|
|
12
|
+
export interface EpisodeLabel {
|
|
13
|
+
ts: number;
|
|
14
|
+
episode: string;
|
|
15
|
+
label: WorkLabel;
|
|
16
|
+
reason: string;
|
|
17
|
+
party: LabelParty;
|
|
18
|
+
evidence: string;
|
|
19
|
+
found_by?: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function labelEpisodes(episodes: Episode[], events: EpisodeScoreEvent[], runs: Run[], ts: number): EpisodeLabel[] {
|
|
23
|
+
const byRun = new Map(runs.map(run => [run.id, run]));
|
|
24
|
+
return episodes.map(episode => {
|
|
25
|
+
const relevant = events.filter(event => event.agent === episode.agent && (event.plan === undefined || event.plan === episode.plan) && (event.phase === undefined || event.phase === episode.phase));
|
|
26
|
+
const acceptance = relevant.find(event => event.type === "accept" || event.type === "validate");
|
|
27
|
+
const penalty = relevant.find(event => event.type === "penalty");
|
|
28
|
+
if (penalty) return { ts, episode: episode.id, label: "bad", reason: "penalty", party: "none", evidence: `penalty event: ${String(penalty.kind ?? penalty.note ?? "recorded")}` };
|
|
29
|
+
const reverted = revertedCommit(episode);
|
|
30
|
+
if (reverted) return { ts, episode: episode.id, label: "bad", reason: "episode commit later reverted", party: "none", evidence: `revert commit ${reverted.revert} reverts ${reverted.commit}`, found_by: reverted.revert };
|
|
31
|
+
if (acceptance && episode.rework) return { ts, episode: episode.id, label: "bad", reason: "accepted with rework", party: "implementer", evidence: `accept event for ${episode.agent} recorded rework` };
|
|
32
|
+
if (acceptance) return { ts, episode: episode.id, label: "good", reason: "accepted without rework", party: "none", evidence: `accept event for ${episode.agent} without rework` };
|
|
33
|
+
const run = byRun.get(episode.runId);
|
|
34
|
+
if (run?.status === "died") return { ts, episode: episode.id, label: "bad", reason: "run died without accept", party: "implementer", evidence: `run status: ${run.statusDetail}` };
|
|
35
|
+
if (run && /OVER-BUDGET\(/i.test(run.statusDetail)) return { ts, episode: episode.id, label: "bad", reason: "run over budget without accept", party: "implementer", evidence: `run status: ${run.statusDetail}` };
|
|
36
|
+
return { ts, episode: episode.id, label: "unknown", reason: "no recorded outcome", party: "none", evidence: "no qualifying score event, failed run, or revert found" };
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
function revertedCommit(episode: Episode): { commit: string; revert: string } | null {
|
|
40
|
+
if (!episode.repo || episode.commits.length === 0) return null;
|
|
41
|
+
try {
|
|
42
|
+
const log = execFileSync("git", ["-C", episode.repo, "log", "--all", "--format=%H%x00%B%x00"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
|
|
43
|
+
const rows = log.split("\0");
|
|
44
|
+
for (let i = 0; i + 1 < rows.length; i += 2) {
|
|
45
|
+
const sha = rows[i]!;
|
|
46
|
+
const message = rows[i + 1]!;
|
|
47
|
+
for (const commit of episode.commits) if (message.includes(`This reverts commit ${commit}.`)) return { commit, revert: sha };
|
|
48
|
+
}
|
|
49
|
+
} catch { /* An unavailable/non-git repository provides no revert evidence. */ }
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function labelLedgerPath(scoreState: string): string {
|
|
54
|
+
return join(scoreState, "labels.jsonl");
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function appendLabel(scoreState: string, label: EpisodeLabel): void {
|
|
58
|
+
mkdirSync(scoreState, { recursive: true });
|
|
59
|
+
appendFileSync(labelLedgerPath(scoreState), `${JSON.stringify(label)}\n`);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
export function labelAndAppend(scoreState: string, episodes: Episode[], events: EpisodeScoreEvent[], runs: Run[], ts: number): EpisodeLabel[] {
|
|
64
|
+
const labels = labelEpisodes(episodes, events, runs, ts);
|
|
65
|
+
for (const label of labels) appendLabel(scoreState, label);
|
|
66
|
+
return labels;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function readLabelHistory(scoreState: string): EpisodeLabel[] {
|
|
70
|
+
const path = labelLedgerPath(scoreState);
|
|
71
|
+
if (!existsSync(path)) return [];
|
|
72
|
+
const out: EpisodeLabel[] = [];
|
|
73
|
+
for (const line of readFileSync(path, "utf8").split("\n")) {
|
|
74
|
+
if (!line.trim()) continue;
|
|
75
|
+
const rec = JSON.parse(line) as EpisodeLabel;
|
|
76
|
+
if ("kind" in rec) continue; // a watermark line (P5) marks progress, it is not a label
|
|
77
|
+
out.push(rec);
|
|
78
|
+
}
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The ledger's update watermark (P5): how far `labels update` has processed, or null before the first run. */
|
|
83
|
+
export function readWatermark(scoreState: string): number | null {
|
|
84
|
+
const path = labelLedgerPath(scoreState);
|
|
85
|
+
if (!existsSync(path)) return null;
|
|
86
|
+
let until: number | null = null;
|
|
87
|
+
for (const line of readFileSync(path, "utf8").split("\n")) {
|
|
88
|
+
if (!line.trim()) continue;
|
|
89
|
+
const rec = JSON.parse(line) as { kind?: string; until?: unknown };
|
|
90
|
+
if (rec.kind === "watermark" && typeof rec.until === "number") until = rec.until;
|
|
91
|
+
}
|
|
92
|
+
return until;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Appends the watermark line; the caller writes it only when the run appended something, so a quiet run appends nothing at all. */
|
|
96
|
+
export function appendWatermark(scoreState: string, until: number): void {
|
|
97
|
+
mkdirSync(scoreState, { recursive: true });
|
|
98
|
+
appendFileSync(labelLedgerPath(scoreState), `${JSON.stringify({ kind: "watermark", until })}\n`);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function readLabels(scoreState: string): EpisodeLabel[] {
|
|
102
|
+
const latest = new Map<string, EpisodeLabel>();
|
|
103
|
+
for (const label of readLabelHistory(scoreState)) latest.set(label.episode, label);
|
|
104
|
+
return [...latest.values()];
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** A flip is a good line followed by a later bad line, unless a newer good line cleared it. Party is the latest non-test line of that flip: the automatic test-party line is extra history, not the attribution. `ts` is the flipping bad line's time — the week a flip counts in. */
|
|
108
|
+
export function flipRecords(scoreState: string): { episode: string; party: LabelParty; ts: number }[] {
|
|
109
|
+
const state = new Map<string, { seenGood: boolean; flipped: boolean; party: LabelParty; ts: number }>();
|
|
110
|
+
for (const line of readLabelHistory(scoreState)) {
|
|
111
|
+
const st = state.get(line.episode) ?? { seenGood: false, flipped: false, party: "none" as const, ts: 0 };
|
|
112
|
+
if (line.label === "good") {
|
|
113
|
+
st.seenGood = true;
|
|
114
|
+
st.flipped = false;
|
|
115
|
+
st.party = "none";
|
|
116
|
+
} else if (line.label === "bad" && st.seenGood) {
|
|
117
|
+
if (!st.flipped) st.ts = line.ts;
|
|
118
|
+
st.flipped = true;
|
|
119
|
+
if (line.party !== "test") st.party = line.party;
|
|
120
|
+
}
|
|
121
|
+
state.set(line.episode, st);
|
|
122
|
+
}
|
|
123
|
+
return [...state.entries()].filter(([, st]) => st.flipped).map(([episode, st]) => ({ episode, party: st.party, ts: st.ts }));
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Flipped episodes as the score board reads them: episode and party only. */
|
|
127
|
+
export function flippedEpisodes(scoreState: string): { episode: string; party: LabelParty }[] {
|
|
128
|
+
return flipRecords(scoreState).map(({ episode, party }) => ({ episode, party }));
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** `git -C <repo> <args>` stdout, null when git fails (missing repo, bad sha); the labels/reports helpers treat null as "no evidence". */
|
|
132
|
+
export function gitOut(repo: string, args: string[]): string | null {
|
|
133
|
+
try {
|
|
134
|
+
return execFileSync("git", ["-C", repo, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
|
|
135
|
+
} catch {
|
|
136
|
+
return null;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function planNamesFile(plan: string, file: string): boolean {
|
|
141
|
+
const escaped = file.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
142
|
+
if (new RegExp(`(?:^|[^\\w./-])${escaped}(?:$|[^\\w./-])`).test(plan)) return true;
|
|
143
|
+
const base = file.split("/").pop() ?? file;
|
|
144
|
+
for (const match of plan.matchAll(/`([^`]+)`/g)) {
|
|
145
|
+
const bare = match[1]!.replace(/:\d+(?::\d+)?$/, "");
|
|
146
|
+
if (bare === file || bare === base || file.endsWith(`/${bare}`)) return true;
|
|
147
|
+
}
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function blamedLines(repo: string, sha: string): { file: string; text: string }[] {
|
|
152
|
+
const diff = gitOut(repo, ["show", "--format=", "--unified=0", sha]);
|
|
153
|
+
if (diff === null) return [];
|
|
154
|
+
const out: { file: string; text: string }[] = [];
|
|
155
|
+
let file = "";
|
|
156
|
+
for (const line of diff.split("\n")) {
|
|
157
|
+
if (line.startsWith("+++ ")) {
|
|
158
|
+
const raw = line.slice(4);
|
|
159
|
+
file = raw === "/dev/null" ? "" : raw.replace(/^b\//, "");
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(line);
|
|
163
|
+
if (!hunk || !file) continue;
|
|
164
|
+
const start = Number(hunk[1]);
|
|
165
|
+
const count = hunk[2] === undefined ? 1 : Number(hunk[2]);
|
|
166
|
+
if (count <= 0) continue;
|
|
167
|
+
const blame = gitOut(repo, ["blame", "-L", `${start},${start + count - 1}`, "--line-porcelain", sha, "--", file]);
|
|
168
|
+
if (blame === null) continue;
|
|
169
|
+
let blamed = file;
|
|
170
|
+
for (const row of blame.split("\n")) {
|
|
171
|
+
if (row.startsWith("filename ")) blamed = row.slice("filename ".length);
|
|
172
|
+
else if (row.startsWith("\t")) out.push({ file: blamed, text: row.slice(1) });
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return out;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Party of the episode's own changed lines. A backticked identifier or path from the phase
|
|
180
|
+
* line or Background in those lines is `plan`; a blamed file the plan never names is
|
|
181
|
+
* `implementer`. Both true → `both`. Neither true is what the plan calls "unclear":
|
|
182
|
+
* LabelParty has no "unclear", so it is recorded as `none`.
|
|
183
|
+
*/
|
|
184
|
+
export function blameParty(episode: Episode): LabelParty {
|
|
185
|
+
if (!episode.repo || episode.commits.length === 0) return "none";
|
|
186
|
+
let plan = "";
|
|
187
|
+
try {
|
|
188
|
+
if (episode.plan) plan = readFileSync(episode.plan, "utf8");
|
|
189
|
+
} catch { /* A missing plan names nothing, so it cannot be the plan party. */ }
|
|
190
|
+
const phaseRe = new RegExp(`^- \\[[ xX]\\] ${episode.phase.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`);
|
|
191
|
+
const lines = plan.split("\n");
|
|
192
|
+
const phaseLine = lines.find(l => phaseRe.test(l)) ?? "";
|
|
193
|
+
const start = lines.findIndex(l => l.trim() === "## Background");
|
|
194
|
+
const body: string[] = [];
|
|
195
|
+
if (start >= 0) {
|
|
196
|
+
for (let i = start + 1; i < lines.length; i++) {
|
|
197
|
+
if (lines[i]!.startsWith("## ")) break;
|
|
198
|
+
body.push(lines[i]!);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
const needles = new Set<string>();
|
|
202
|
+
for (const match of `${phaseLine}\n${body.join("\n")}`.matchAll(/`([^`]+)`/g)) {
|
|
203
|
+
const bare = match[1]!.replace(/:\d+(?::\d+)?$/, "");
|
|
204
|
+
if (/^[A-Za-z_][A-Za-z0-9_$.]*$/.test(bare) || bare.includes("/") || /\.[A-Za-z0-9]+$/.test(bare)) needles.add(bare);
|
|
205
|
+
}
|
|
206
|
+
let planHit = false;
|
|
207
|
+
let implementerHit = false;
|
|
208
|
+
for (const sha of episode.commits) {
|
|
209
|
+
for (const line of blamedLines(episode.repo, sha)) {
|
|
210
|
+
if ([...needles].some(n => line.text.includes(n))) planHit = true;
|
|
211
|
+
if (!planNamesFile(plan, line.file)) implementerHit = true;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
if (planHit && implementerHit) return "both";
|
|
215
|
+
if (planHit) return "plan";
|
|
216
|
+
if (implementerHit) return "implementer";
|
|
217
|
+
return "none";
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function testHole(fixSha: string): string {
|
|
221
|
+
return `test hole: ${fixSha} changed lines no check caught`;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Flip an accepted episode: append the blame party, then a test-party line, and open one incident. A repeat of the same fix appends nothing; the fingerprint dedupes the incident. */
|
|
225
|
+
export function flipAccepted(cfg: Config, episode: Episode, fixSha: string, ts: number): { party: LabelParty; appended: boolean } {
|
|
226
|
+
if (episode.acceptedAt === null) return { party: "none", appended: false };
|
|
227
|
+
const party = blameParty(episode);
|
|
228
|
+
const already = readLabelHistory(cfg.paths.score_state).some(l => l.episode === episode.id && l.party === "test" && l.found_by === fixSha);
|
|
229
|
+
if (!already) {
|
|
230
|
+
appendLabel(cfg.paths.score_state, {
|
|
231
|
+
ts, episode: episode.id, label: "bad", reason: `flipped by ${fixSha}`, party,
|
|
232
|
+
evidence: `git blame of ${episode.commits.join(",") || "no commits"}`, found_by: fixSha,
|
|
233
|
+
});
|
|
234
|
+
appendLabel(cfg.paths.score_state, {
|
|
235
|
+
ts, episode: episode.id, label: "bad", reason: testHole(fixSha), party: "test", evidence: testHole(fixSha), found_by: fixSha,
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
addIncident(cfg, {
|
|
239
|
+
source: "traces", kind: "test-hole", summary: testHole(fixSha), evidence: episode.id,
|
|
240
|
+
fingerprint: `test-hole:${episode.id}:${fixSha}`,
|
|
241
|
+
}, ts);
|
|
242
|
+
return { party, appended: !already };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** Main's party override. Appends; the previous label value is kept, never rewritten. */
|
|
246
|
+
export function assignLabel(scoreState: string, episode: string, party: "plan" | "implementer" | "both", why: string, ts: number): EpisodeLabel {
|
|
247
|
+
const latest = readLabels(scoreState).find(l => l.episode === episode);
|
|
248
|
+
const line: EpisodeLabel = {
|
|
249
|
+
ts, episode, label: latest?.label ?? "unknown", reason: why, party, evidence: "labels assign",
|
|
250
|
+
};
|
|
251
|
+
appendLabel(scoreState, line);
|
|
252
|
+
return line;
|
|
253
|
+
}
|
package/src/core/main-start.ts
CHANGED
|
@@ -6,13 +6,15 @@ import type { RunSource, TraceEvent } from "./adapter.ts";
|
|
|
6
6
|
import { readEvents } from "./agent-score.ts";
|
|
7
7
|
import type { Config } from "./config.ts";
|
|
8
8
|
import { nowSec, strftime } from "./clock.ts";
|
|
9
|
+
import type { Episode } from "./episodes.ts";
|
|
10
|
+
import { updateLabels } from "./label-update.ts";
|
|
9
11
|
import { runDetectors, runDetectorsGated, type GatedInputs, type TaskResult } from "./incident-detectors.ts";
|
|
10
12
|
import { addIncident, type IncidentView } from "./incidents.ts";
|
|
11
13
|
import { log as logGuard } from "./guards.ts";
|
|
12
14
|
import { dailyChecks, readBlocks, readMetricEvents, worseThanMean } from "./metrics.ts";
|
|
13
15
|
import { buildReport } from "./report.ts";
|
|
14
16
|
import { loadavgLine } from "./host.ts";
|
|
15
|
-
import { providersLine } from "./provider-state.ts";
|
|
17
|
+
import { harnessProviderLines, providersLine, syncHarnessOut, type ProviderStatus } from "./provider-state.ts";
|
|
16
18
|
import { mrSweep } from "./mr-sweep.ts";
|
|
17
19
|
import { watchHealth } from "./watch.ts";
|
|
18
20
|
import { wipAlerts } from "./wip-alerts.ts";
|
|
@@ -70,6 +72,10 @@ function run(file: string, args: string[], opts: RunOpts = {}): Promise<RunResul
|
|
|
70
72
|
export interface MainStartDeps {
|
|
71
73
|
/** Runs for the ledger-contradiction detector; null/absent skips what needs one. */
|
|
72
74
|
source?: RunSource | null;
|
|
75
|
+
/** The harness's provider report; undefined skips the harness lines and the feed. */
|
|
76
|
+
providers?: ProviderStatus[] | null;
|
|
77
|
+
/** Episode builder (P1) for the daily labels update over labels.repos; absent skips that update. */
|
|
78
|
+
episodesFor?: (cutoff: number) => Episode[];
|
|
73
79
|
/** Finished task results parsed from Main's session file (the adapter's format knowledge). */
|
|
74
80
|
results?: TaskResult[];
|
|
75
81
|
}
|
|
@@ -101,6 +107,11 @@ export async function mainStartText(args: string[], cfg: Config, opts: { inherit
|
|
|
101
107
|
} catch (err) {
|
|
102
108
|
logGuard(cfg.paths.guard_log, `daily check failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
103
109
|
}
|
|
110
|
+
try {
|
|
111
|
+
for (const line of runDailyLabelsUpdate(cfg, deps, nowSec())) say(line);
|
|
112
|
+
} catch (err) {
|
|
113
|
+
logGuard(cfg.paths.guard_log, `daily labels update failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
114
|
+
}
|
|
104
115
|
try {
|
|
105
116
|
const weekly = runWeeklyCheck(cfg, deps.source, nowSec());
|
|
106
117
|
if (weekly) say(weekly);
|
|
@@ -167,9 +178,15 @@ export async function mainStartText(args: string[], cfg: Config, opts: { inherit
|
|
|
167
178
|
if (/^(PRIORITY IDLE|FULL)/.test(line)) say(line);
|
|
168
179
|
}
|
|
169
180
|
// Who is rate-limited comes from live data (plan 20261025_1700 P2): printed from the running
|
|
170
|
-
// code, not the installed agent-ledger bin, so a stale install cannot hide the state.
|
|
181
|
+
// code, not the installed agent-ledger bin, so a stale install cannot hide the state. The
|
|
182
|
+
// harness feed (plan 20261103_0955 P3) lands first, so a block this start found is already
|
|
183
|
+
// in that line. No `providers` key means a caller that has not opted in: nothing is recorded.
|
|
184
|
+
if (deps.providers !== undefined) syncHarnessOut(cfg, deps.providers);
|
|
171
185
|
const providers = providersLine(cfg);
|
|
172
186
|
if (providers) say(providers);
|
|
187
|
+
if (deps.providers !== undefined) {
|
|
188
|
+
for (const line of harnessProviderLines(cfg, deps.providers)) say(line);
|
|
189
|
+
}
|
|
173
190
|
say("");
|
|
174
191
|
say("=== main thread");
|
|
175
192
|
const health = await run(bin("main-health", cfg), [], { stdin: childStdin, stderr: childStderr });
|
|
@@ -322,6 +339,48 @@ export function runDailyCheck(cfg: Config, source: RunSource, now: number): Inci
|
|
|
322
339
|
return out;
|
|
323
340
|
}
|
|
324
341
|
|
|
342
|
+
function labelsUpdateStateFile(cfg: Config): string {
|
|
343
|
+
return join(cfg.paths.queue_state, "labels-update-daily.json");
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Once per calendar day, the P5 labels update for each repo in labels.repos (default []): new
|
|
348
|
+
* episodes labelled, flips found and their work-turned-bad incidents opened. A repo is marked
|
|
349
|
+
* done only after its update ran without throwing, so a failed repo retries at the next
|
|
350
|
+
* main-start. Returns the report lines for the main-start text; [] with no repos configured.
|
|
351
|
+
*/
|
|
352
|
+
export function runDailyLabelsUpdate(cfg: Config, deps: MainStartDeps, now: number): string[] {
|
|
353
|
+
if (cfg.labels.repos.length === 0 || !deps.episodesFor || !deps.source) return [];
|
|
354
|
+
const today = strftime(now, "%Y-%m-%d");
|
|
355
|
+
const file = labelsUpdateStateFile(cfg);
|
|
356
|
+
let done = new Set<string>();
|
|
357
|
+
try {
|
|
358
|
+
const st = JSON.parse(readFileSync(file, "utf8")) as { date?: string; repos?: string[] };
|
|
359
|
+
if (st.date === today && Array.isArray(st.repos)) done = new Set(st.repos);
|
|
360
|
+
} catch {}
|
|
361
|
+
const out: string[] = [];
|
|
362
|
+
for (const repo of cfg.labels.repos) {
|
|
363
|
+
if (done.has(repo)) continue;
|
|
364
|
+
try {
|
|
365
|
+
const r = updateLabels(cfg, repo, {
|
|
366
|
+
episodesFor: deps.episodesFor,
|
|
367
|
+
events: readEvents(cfg),
|
|
368
|
+
runs: deps.source.listRuns(now - cfg.labels.episode_days * DAY),
|
|
369
|
+
}, now);
|
|
370
|
+
const n = r.labels.length + r.imported.length + r.flips.length;
|
|
371
|
+
out.push(n > 0
|
|
372
|
+
? `labels update ${repo}: ${n} new line(s), ${r.flips.length} flip(s)`
|
|
373
|
+
: `labels update ${repo}: up to date`);
|
|
374
|
+
done.add(repo);
|
|
375
|
+
} catch (err) {
|
|
376
|
+
out.push(`labels update ${repo} failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
380
|
+
writeFileSync(file, `${JSON.stringify({ date: today, repos: [...done] })}\n`);
|
|
381
|
+
return out;
|
|
382
|
+
}
|
|
383
|
+
|
|
325
384
|
/**
|
|
326
385
|
* When the weekly report is due, the code writes notes/metrics.md itself (as `metrics report`
|
|
327
386
|
* does) and the worst ranked metric becomes an incident (source "weekly"). Returns the due line
|
|
@@ -4,9 +4,12 @@
|
|
|
4
4
|
// {provider, until, at, source} object per line; the newest record per provider wins. Decisions
|
|
5
5
|
// read it (agent-ledger --cap, the guards, the score gate); recordings come from
|
|
6
6
|
// `quota-reset --provider`, from task results that quote a reset time, and from rate-limited
|
|
7
|
-
// turn ends (the adapter wires those; this file stays harness-free).
|
|
7
|
+
// turn ends (the adapter wires those; this file stays harness-free). A harness status list is
|
|
8
|
+
// recorded here too, source `harness`, because this file already owns who is out — an adapter
|
|
9
|
+
// must not grow a second out-until store. Only a record this feed wrote is cleared when the
|
|
10
|
+
// list says that provider is ready again.
|
|
8
11
|
|
|
9
|
-
import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
|
|
12
|
+
import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
10
13
|
import { join } from "node:path";
|
|
11
14
|
import type { Config } from "./config.ts";
|
|
12
15
|
import { nowSec, strftime } from "./clock.ts";
|
|
@@ -153,3 +156,194 @@ export function resetEpochFromText(text: string, rule: { pattern: string; zone:
|
|
|
153
156
|
return null;
|
|
154
157
|
}
|
|
155
158
|
}
|
|
159
|
+
|
|
160
|
+
/** What a harness reports for one provider. `partial` is display-only and never an out-until. */
|
|
161
|
+
export interface ProviderStatus {
|
|
162
|
+
provider: string;
|
|
163
|
+
/** null = the harness can use it; otherwise a short reason it cannot. */
|
|
164
|
+
unusable: string | null;
|
|
165
|
+
/** Epoch seconds nothing is routed here until; null = not blocked. */
|
|
166
|
+
blockedUntil: number | null;
|
|
167
|
+
partial: { scope: string; until: number }[];
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
interface HarnessSnapshot {
|
|
171
|
+
at: number;
|
|
172
|
+
providers: ProviderStatus[];
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function harnessSnapshotFile(cfg: Config): string {
|
|
176
|
+
return join(cfg.paths.queue_state, "harness-providers.json");
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Record harness blocks into provider-out, and clear only the blocks this feed wrote once the
|
|
181
|
+
* harness says the provider is ready. null does nothing. A failed write is swallowed by recordOut.
|
|
182
|
+
*/
|
|
183
|
+
export function syncHarnessOut(cfg: Config, list: ProviderStatus[] | null, now = nowSec()): void {
|
|
184
|
+
if (list === null) return;
|
|
185
|
+
for (const status of list) {
|
|
186
|
+
if (status.blockedUntil !== null && status.blockedUntil > now) {
|
|
187
|
+
const current = outUntil(cfg, status.provider, now);
|
|
188
|
+
if (current === null || current < status.blockedUntil) {
|
|
189
|
+
recordOut(cfg, status.provider, status.blockedUntil, "harness", now);
|
|
190
|
+
}
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
if (status.unusable !== null || status.blockedUntil !== null) continue;
|
|
194
|
+
let newest: OutRecord | null = null;
|
|
195
|
+
for (const row of readOut(cfg)) if (row.provider === status.provider) newest = row;
|
|
196
|
+
if (newest !== null && newest.source === "harness" && newest.until > now) {
|
|
197
|
+
recordOut(cfg, status.provider, now, "harness", now);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function sameLocalDay(t: number, now: number): boolean {
|
|
203
|
+
const a = new Date(t * 1000);
|
|
204
|
+
const b = new Date(now * 1000);
|
|
205
|
+
return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function fmtWhen(t: number, now: number): string {
|
|
209
|
+
return strftime(t, sameLocalDay(t, now) ? "%H:%M" : "%m-%d %H:%M");
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
type ListedKind = "ready" | "blocked" | "unusable";
|
|
213
|
+
|
|
214
|
+
function listedKind(status: ProviderStatus): ListedKind {
|
|
215
|
+
if (status.unusable !== null) return "unusable";
|
|
216
|
+
if (status.blockedUntil !== null) return "blocked";
|
|
217
|
+
return "ready";
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function byProvider(a: ProviderStatus, b: ProviderStatus): number {
|
|
221
|
+
if (a.provider < b.provider) return -1;
|
|
222
|
+
if (a.provider > b.provider) return 1;
|
|
223
|
+
return 0;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function statusLine(list: ProviderStatus[], now: number): string | null {
|
|
227
|
+
if (list.length === 0) return null;
|
|
228
|
+
const sorted = list.toSorted(byProvider);
|
|
229
|
+
const ready = sorted.filter(s => listedKind(s) === "ready");
|
|
230
|
+
const blocked = sorted.filter(s => listedKind(s) === "blocked");
|
|
231
|
+
const unusable = sorted.filter(s => listedKind(s) === "unusable");
|
|
232
|
+
const partials: { provider: string; scope: string; until: number }[] = [];
|
|
233
|
+
for (const status of sorted) {
|
|
234
|
+
const scopes = status.partial.toSorted((a, b) => (a.scope < b.scope ? -1 : a.scope > b.scope ? 1 : 0));
|
|
235
|
+
for (const part of scopes) partials.push({ provider: status.provider, scope: part.scope, until: part.until });
|
|
236
|
+
}
|
|
237
|
+
const parts: string[] = [];
|
|
238
|
+
if (ready.length > 0) parts.push(`ready ${ready.length}: ${ready.map(s => s.provider).join(", ")}`);
|
|
239
|
+
if (blocked.length > 0) {
|
|
240
|
+
parts.push(`blocked: ${blocked.map(s => `${s.provider} until ${fmtWhen(s.blockedUntil ?? 0, now)}`).join(", ")}`);
|
|
241
|
+
}
|
|
242
|
+
if (partials.length > 0) {
|
|
243
|
+
parts.push(`partly blocked: ${partials.map(p => `${p.provider} ${p.scope} until ${fmtWhen(p.until, now)}`).join(", ")}`);
|
|
244
|
+
}
|
|
245
|
+
if (unusable.length > 0) parts.push(`unusable: ${unusable.map(s => `${s.provider} (${s.unusable})`).join(", ")}`);
|
|
246
|
+
return `harness providers: ${parts.join(" · ")}`;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function changePhrase(name: string, from: ListedKind | "absent", to: ListedKind | "absent", next: ProviderStatus | undefined, now: number): string | null {
|
|
250
|
+
if (from === "absent" && to === "ready") return `${name} new`;
|
|
251
|
+
if (from === "absent" && to === "blocked" && next?.blockedUntil != null) return `${name} new, blocked until ${fmtWhen(next.blockedUntil, now)}`;
|
|
252
|
+
if (from === "ready" && to === "blocked" && next?.blockedUntil != null) return `${name} blocked until ${fmtWhen(next.blockedUntil, now)}`;
|
|
253
|
+
if ((from === "blocked" || from === "unusable") && to === "ready") return `${name} BACK`;
|
|
254
|
+
if (from === "unusable" && to === "blocked" && next?.blockedUntil != null) return `${name} BACK, blocked until ${fmtWhen(next.blockedUntil, now)}`;
|
|
255
|
+
if ((from === "ready" || from === "blocked") && to === "unusable") return `${name} unusable (${next?.unusable ?? ""})`;
|
|
256
|
+
if (from !== "absent" && to === "absent") return `${name} gone`;
|
|
257
|
+
if (to === "unusable") return `${name} unusable (${next?.unusable ?? ""})`;
|
|
258
|
+
return null;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function changeLine(prev: ProviderStatus[], next: ProviderStatus[], prevAt: number, now: number): string | null {
|
|
262
|
+
const before = new Map<string, ProviderStatus>();
|
|
263
|
+
const after = new Map<string, ProviderStatus>();
|
|
264
|
+
for (const status of prev) before.set(status.provider, status);
|
|
265
|
+
for (const status of next) after.set(status.provider, status);
|
|
266
|
+
const names = [...new Set([...before.keys(), ...after.keys()])].toSorted();
|
|
267
|
+
const parts: string[] = [];
|
|
268
|
+
for (const name of names) {
|
|
269
|
+
const from = before.has(name) ? listedKind(before.get(name)!) : "absent";
|
|
270
|
+
const to = after.has(name) ? listedKind(after.get(name)!) : "absent";
|
|
271
|
+
if (from === to) continue;
|
|
272
|
+
const phrase = changePhrase(name, from, to, after.get(name), now);
|
|
273
|
+
if (phrase !== null) parts.push(phrase);
|
|
274
|
+
}
|
|
275
|
+
if (parts.length === 0) return null;
|
|
276
|
+
return `provider changes since ${fmtWhen(prevAt, now)}: ${parts.join(" · ")}`;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function isProviderStatus(v: unknown): v is ProviderStatus {
|
|
280
|
+
if (v === null || typeof v !== "object") return false;
|
|
281
|
+
const row = v as Record<string, unknown>;
|
|
282
|
+
if (typeof row.provider !== "string") return false;
|
|
283
|
+
if (row.unusable !== null && typeof row.unusable !== "string") return false;
|
|
284
|
+
if (row.blockedUntil !== null && (typeof row.blockedUntil !== "number" || !Number.isFinite(row.blockedUntil))) return false;
|
|
285
|
+
if (!Array.isArray(row.partial)) return false;
|
|
286
|
+
for (const part of row.partial) {
|
|
287
|
+
if (part === null || typeof part !== "object") return false;
|
|
288
|
+
const scope = (part as Record<string, unknown>).scope;
|
|
289
|
+
const until = (part as Record<string, unknown>).until;
|
|
290
|
+
if (typeof scope !== "string" || typeof until !== "number" || !Number.isFinite(until)) return false;
|
|
291
|
+
}
|
|
292
|
+
return true;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function readHarnessSnapshot(cfg: Config): HarnessSnapshot | null {
|
|
296
|
+
let text: string;
|
|
297
|
+
try {
|
|
298
|
+
text = readFileSync(harnessSnapshotFile(cfg), "utf8");
|
|
299
|
+
} catch {
|
|
300
|
+
return null;
|
|
301
|
+
}
|
|
302
|
+
try {
|
|
303
|
+
const parsed = JSON.parse(text) as Record<string, unknown>;
|
|
304
|
+
if (typeof parsed.at !== "number" || !Number.isFinite(parsed.at) || !Array.isArray(parsed.providers)) return null;
|
|
305
|
+
const providers: ProviderStatus[] = [];
|
|
306
|
+
for (const item of parsed.providers) {
|
|
307
|
+
if (!isProviderStatus(item)) return null;
|
|
308
|
+
providers.push({
|
|
309
|
+
provider: item.provider,
|
|
310
|
+
unusable: item.unusable,
|
|
311
|
+
blockedUntil: item.blockedUntil,
|
|
312
|
+
partial: item.partial.map(part => ({ scope: part.scope, until: part.until })),
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
return { at: parsed.at, providers };
|
|
316
|
+
} catch {
|
|
317
|
+
return null;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function writeHarnessSnapshot(cfg: Config, snap: HarnessSnapshot): void {
|
|
322
|
+
try {
|
|
323
|
+
mkdirSync(cfg.paths.queue_state, { recursive: true });
|
|
324
|
+
writeFileSync(harnessSnapshotFile(cfg), `${JSON.stringify(snap)}\n`);
|
|
325
|
+
} catch {}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* The harness lines for a start: the current picture, then what moved since the last snapshot.
|
|
330
|
+
* null means the harness store could not be read — the snapshot and provider-out stay untouched.
|
|
331
|
+
* Never throws.
|
|
332
|
+
*/
|
|
333
|
+
export function harnessProviderLines(cfg: Config, list: ProviderStatus[] | null, now = nowSec()): string[] {
|
|
334
|
+
try {
|
|
335
|
+
if (list === null) return ["harness providers: unreadable — run neurastream doctor"];
|
|
336
|
+
const prev = readHarnessSnapshot(cfg);
|
|
337
|
+
writeHarnessSnapshot(cfg, { at: now, providers: list });
|
|
338
|
+
const lines: string[] = [];
|
|
339
|
+
const picture = statusLine(list, now);
|
|
340
|
+
if (picture !== null) lines.push(picture);
|
|
341
|
+
if (prev !== null) {
|
|
342
|
+
const changes = changeLine(prev.providers, list, prev.at, now);
|
|
343
|
+
if (changes !== null) lines.push(changes);
|
|
344
|
+
}
|
|
345
|
+
return lines;
|
|
346
|
+
} catch {
|
|
347
|
+
return [];
|
|
348
|
+
}
|
|
349
|
+
}
|
package/src/core/report.ts
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
|
|
5
5
|
import type { Config } from "./config.ts";
|
|
6
6
|
import type { RunSource } from "./adapter.ts";
|
|
7
|
+
import { readEvents } from "./agent-score.ts";
|
|
8
|
+
import { flipRecords, gitOut, readLabels } from "./labels.ts";
|
|
7
9
|
import { readIncidents, type IncidentView } from "./incidents.ts";
|
|
8
10
|
import {
|
|
9
11
|
m1,
|
|
@@ -131,6 +133,78 @@ export function kindStats(incidents: IncidentView[], w: Window): KindStat[] {
|
|
|
131
133
|
.toSorted((a, b) => b.opened - a.opened || (a.kind < b.kind ? -1 : a.kind > b.kind ? 1 : 0));
|
|
132
134
|
}
|
|
133
135
|
|
|
136
|
+
// P5b: the label ledger in the report — bad flips this week / episodes per agent and per plan,
|
|
137
|
+
// and the files bad work touched.
|
|
138
|
+
|
|
139
|
+
export interface EpisodeKey {
|
|
140
|
+
id: string;
|
|
141
|
+
agent: string;
|
|
142
|
+
plan: string;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export interface FlipRow {
|
|
146
|
+
key: string;
|
|
147
|
+
/** Flips whose flipping bad line falls in the window. */
|
|
148
|
+
flips: number;
|
|
149
|
+
/** Episodes of this agent/plan in the ledger — the ratio's denominator. */
|
|
150
|
+
episodes: number;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Episode id -> {id, agent, plan}: the id is `${runId}:${plan}:${phase}` (episodes.ts), so the agent is the first segment, the phase the last segment (dropped here), and the plan everything between. */
|
|
154
|
+
function episodeKey(id: string): EpisodeKey {
|
|
155
|
+
const parts = id.split(":");
|
|
156
|
+
const agent = parts.shift() ?? id;
|
|
157
|
+
parts.pop();
|
|
158
|
+
return { id, agent, plan: parts.join(":") };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Bad flips this week over episodes, per agent and per plan. Rows sort by flips, then episodes, then key. */
|
|
162
|
+
export function flipRows(flips: { episode: string; ts: number }[], episodes: EpisodeKey[], w: Window): { agents: FlipRow[]; plans: FlipRow[] } {
|
|
163
|
+
const rows = (keyOf: (e: EpisodeKey) => string): FlipRow[] => {
|
|
164
|
+
const byKey = new Map<string, FlipRow>();
|
|
165
|
+
const add = (key: string): FlipRow => {
|
|
166
|
+
const r = byKey.get(key) ?? { key, flips: 0, episodes: 0 };
|
|
167
|
+
byKey.set(key, r);
|
|
168
|
+
return r;
|
|
169
|
+
};
|
|
170
|
+
for (const e of episodes) add(keyOf(e)).episodes += 1;
|
|
171
|
+
for (const f of flips) {
|
|
172
|
+
if (!inWindow(f.ts, w)) continue;
|
|
173
|
+
const e = episodes.find(x => x.id === f.episode);
|
|
174
|
+
if (e) add(keyOf(e)).flips += 1;
|
|
175
|
+
}
|
|
176
|
+
return [...byKey.values()].toSorted((a, b) => b.flips - a.flips || b.episodes - a.episodes || (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
|
|
177
|
+
};
|
|
178
|
+
return { agents: rows(e => e.agent), plans: rows(e => e.plan) };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** The files flipped (bad) work touched: `git show --name-only` over each flip episode's accept commits, most-touched first, at most `limit`. */
|
|
182
|
+
export function topFlipFiles(flips: { episode: string }[], events: Record<string, unknown>[], limit = 3): string[] {
|
|
183
|
+
const byEpisode = new Map<string, { repo: string; commits: string[] }>();
|
|
184
|
+
for (const e of events) {
|
|
185
|
+
if (e.type !== "accept" && e.type !== "validate") continue;
|
|
186
|
+
byEpisode.set(`${String(e.agent)}:${String(e.plan ?? "")}:${String(e.phase ?? "")}`, {
|
|
187
|
+
repo: String(e.repo ?? ""),
|
|
188
|
+
commits: Array.isArray(e.commits) ? e.commits.map(String) : [],
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
const counts = new Map<string, number>();
|
|
192
|
+
for (const f of flips) {
|
|
193
|
+
const src = byEpisode.get(f.episode);
|
|
194
|
+
if (!src || src.repo === "") continue;
|
|
195
|
+
for (const sha of src.commits) {
|
|
196
|
+
for (const file of (gitOut(src.repo, ["show", "--format=", "--name-only", sha]) ?? "").split("\n")) {
|
|
197
|
+
if (file.trim() === "") continue;
|
|
198
|
+
counts.set(file, (counts.get(file) ?? 0) + 1);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return [...counts.entries()]
|
|
203
|
+
.toSorted((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
|
|
204
|
+
.slice(0, limit)
|
|
205
|
+
.map(([file]) => file);
|
|
206
|
+
}
|
|
207
|
+
|
|
134
208
|
/** A noisy detector (P6): the finding the weekly check turns into one "noisy-detector" incident. */
|
|
135
209
|
export interface NoisyFinding {
|
|
136
210
|
kind: "noisy-detector";
|
|
@@ -307,6 +381,17 @@ export function buildReport(cfg: Config, source: RunSource, days: number, now: n
|
|
|
307
381
|
"Dismiss rate by kind (opened, planned, dismissed):",
|
|
308
382
|
...kindStats(incidents, cur).map((k) => `- ${k.kind}: ${k.opened}, ${k.planned}, ${k.dismissed} (${Math.round(k.dismissRate * 100)}% dismissed)`),
|
|
309
383
|
];
|
|
384
|
+
// P5b: the label ledger's flips in the report. An empty ledger adds no lines at all, so
|
|
385
|
+
// byte-identical output on a machine that never ran labels.
|
|
386
|
+
const ledgerEpisodes = readLabels(cfg.paths.score_state);
|
|
387
|
+
if (ledgerEpisodes.length > 0) {
|
|
388
|
+
const flips = flipRecords(cfg.paths.score_state);
|
|
389
|
+
const fr = flipRows(flips, ledgerEpisodes.map(l => episodeKey(l.episode)), cur);
|
|
390
|
+
if (fr.agents.length > 0) quality.push(`Bad flips this week / episodes (agent): ${fr.agents.map(r => `${r.key} ${r.flips}/${r.episodes}`).join(", ")}`);
|
|
391
|
+
if (fr.plans.length > 0) quality.push(`Bad flips this week / episodes (plan): ${fr.plans.map(r => `${r.key} ${r.flips}/${r.episodes}`).join(", ")}`);
|
|
392
|
+
const files = topFlipFiles(flips.filter(f => inWindow(f.ts, cur)), readEvents(cfg));
|
|
393
|
+
if (files.length > 0) quality.push(`Files bad work touched: ${files.join(", ")}`);
|
|
394
|
+
}
|
|
310
395
|
const body = [
|
|
311
396
|
`Self-metrics: last ${days} days [${day(cur.from)} to ${day(cur.to)}) vs previous ${days} days.`,
|
|
312
397
|
"",
|