neurastream 0.1.12 → 0.1.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -0
- package/package.json +1 -1
- package/src/cli/dispatch.ts +3 -0
- package/src/cli/metrics.ts +131 -0
- package/src/core/agent-score.ts +1 -1
- package/src/core/config.ts +9 -0
- package/src/core/main-start.ts +13 -1
- package/src/core/metrics.ts +266 -0
- package/src/core/report.ts +179 -0
- package/templates/config.yml +5 -0
package/README.md
CHANGED
|
@@ -108,6 +108,20 @@ In both modes:
|
|
|
108
108
|
- The previous session file stays where it is.
|
|
109
109
|
- `rollover.enabled: false` turns the feature off.
|
|
110
110
|
|
|
111
|
+
## Self-metrics
|
|
112
|
+
|
|
113
|
+
`neurastream metrics report [--days N]` compares this window (the last `metrics.report_days`, default 7) with the one before it, writes `<paths.notes>/metrics.md`, and prints the same report. Worst change is marked `◀ worst`. The five numbers:
|
|
114
|
+
|
|
115
|
+
- M1 cost per merge: cost of sub and main runs written in the window, divided by accepts in the window. Worker-only and Main-only dollars are shown too.
|
|
116
|
+
- M2 idle calls: calls of finished or died sub runs in the window that never got an accept, diagnose or validate event. Top 3 shown.
|
|
117
|
+
- M3 CI tries: mean `tries` of `ci` events in the window, and the MRs at 3 or more tries. Tries come from `metrics.ci_pipelines_cmd` (see `docs/config.md`).
|
|
118
|
+
- M4 owner corrections: owner messages in main runs that match `metrics.correction_patterns`, and Main messages ending in `?`. The owner message count is shown but never ranked.
|
|
119
|
+
- M5 guard blocks: BLOCK lines in the guard logs in the window, with false alarms and the top 3 reasons.
|
|
120
|
+
|
|
121
|
+
Caveat: M4 is a whole-run measure. A main run counts entirely by its last write time, so a run that spans a window edge counts in the window it ends in.
|
|
122
|
+
|
|
123
|
+
Weekly loop: run `neurastream metrics report`, then propose ONE rule change to the owner. When the owner decides, record it with `neurastream metrics rule "<text>" --approved|--rejected`; approved rules get a before/after check once a full window has passed. Record CI with `neurastream metrics ci <repo-dir> <mr-id>` and guard false alarms with `neurastream metrics false-alarm <log-ts> --why "<text>"`. main-start shows the report as due when it is missing or older than `metrics.report_days`.
|
|
124
|
+
|
|
111
125
|
## Changing a script
|
|
112
126
|
|
|
113
127
|
Edit the script in this repo. Green is `bun run typecheck` and `bun test`, both exit 0. Main tags the release. The publish workflow puts that tag on npm. Then:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "neurastream",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.13",
|
|
4
4
|
"description": "Guardrails for running many AI coding agents at once: plan queue, blockers, call budgets, provider caps, scoring, merge-verified close.",
|
|
5
5
|
"keywords": ["ai-agents", "coding-agents", "orchestration", "guardrails", "omp", "bun", "cli"],
|
|
6
6
|
"homepage": "https://github.com/umiddey/neurastream#readme",
|
package/src/cli/dispatch.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { runDoctor } from "../adapters/omp/doctor.ts";
|
|
|
5
5
|
import { GUARD_USAGE, runGuard } from "./guard.ts";
|
|
6
6
|
import { runInit } from "./init.ts";
|
|
7
7
|
import { PORTED, runMain, runPorted } from "./commands.ts";
|
|
8
|
+
import { runMetrics } from "./metrics.ts";
|
|
8
9
|
|
|
9
10
|
const BINS = [
|
|
10
11
|
"agent-score",
|
|
@@ -44,6 +45,7 @@ export function helpText(): string {
|
|
|
44
45
|
" neurastream guard <event> --json",
|
|
45
46
|
` (${GUARD_USAGE.slice(GUARD_USAGE.indexOf("(") + 1, -1)})`,
|
|
46
47
|
" neurastream main [args] run omp under the launcher (automatic session rollover)",
|
|
48
|
+
" neurastream metrics <cmd> self-metrics: report, ci, false-alarm, rule (see README)",
|
|
47
49
|
"",
|
|
48
50
|
"Compatibility bins (same names as today; ports land in later phases):",
|
|
49
51
|
...BINS.map(b => ` ${b}`),
|
|
@@ -60,6 +62,7 @@ export async function run(cmd: string, args: string[]): Promise<number> {
|
|
|
60
62
|
}
|
|
61
63
|
if (cmd === "main") return runMain(args);
|
|
62
64
|
if (cmd === "init") return runInit(args);
|
|
65
|
+
if (cmd === "metrics") return runMetrics(args);
|
|
63
66
|
if (cmd === "adapter") return runAdapterInstall(args);
|
|
64
67
|
if (cmd === "config") {
|
|
65
68
|
try {
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// `neurastream metrics …`: records facts the owner and the CI command decide into
|
|
2
|
+
// metrics.jsonl (see src/core/metrics.ts). Each record* function takes the config and the
|
|
3
|
+
// clock as arguments so tests run against a temp home.
|
|
4
|
+
|
|
5
|
+
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { ConfigError, loadConfig, type Config } from "../core/config.ts";
|
|
8
|
+
import { appendMetric } from "../core/metrics.ts";
|
|
9
|
+
import { nowSec } from "../core/clock.ts";
|
|
10
|
+
import type { RunSource } from "../core/adapter.ts";
|
|
11
|
+
import { buildReport } from "../core/report.ts";
|
|
12
|
+
import { defaultRunSource } from "../adapters/omp/sessions.ts";
|
|
13
|
+
|
|
14
|
+
export const METRICS_USAGE = [
|
|
15
|
+
"usage: neurastream metrics ci <repo-dir> <mr-id>",
|
|
16
|
+
' neurastream metrics false-alarm <log-ts> --why "<text>"',
|
|
17
|
+
' neurastream metrics rule "<text>" --approved|--rejected',
|
|
18
|
+
" neurastream metrics report [--days N]",
|
|
19
|
+
].join("\n");
|
|
20
|
+
|
|
21
|
+
function flagValue(args: string[], name: string): string | undefined {
|
|
22
|
+
const i = args.indexOf(name);
|
|
23
|
+
return i >= 0 ? args[i + 1] : undefined;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Single-quotes a value for `sh -c`, so an MR id cannot inject shell syntax. */
|
|
27
|
+
function shellQuote(v: string): string {
|
|
28
|
+
return `'${v.replaceAll("'", "'\\''")}'`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Runs the configured CI command in the repo and records how many pipelines the MR needed. */
|
|
32
|
+
export function recordCi(cfg: Config, repoDir: string, mr: string, now: number): number {
|
|
33
|
+
if (!repoDir || !mr) {
|
|
34
|
+
console.error(METRICS_USAGE);
|
|
35
|
+
return 2;
|
|
36
|
+
}
|
|
37
|
+
const template = cfg.metrics.ci_pipelines_cmd;
|
|
38
|
+
if (!template) {
|
|
39
|
+
console.error("metrics.ci_pipelines_cmd not set");
|
|
40
|
+
return 2;
|
|
41
|
+
}
|
|
42
|
+
if (!existsSync(repoDir)) {
|
|
43
|
+
console.error(`repo-dir not found: ${repoDir}`);
|
|
44
|
+
return 2;
|
|
45
|
+
}
|
|
46
|
+
const proc = Bun.spawnSync(["sh", "-c", template.replaceAll("{mr}", shellQuote(mr))], {
|
|
47
|
+
cwd: repoDir,
|
|
48
|
+
stdout: "pipe",
|
|
49
|
+
stderr: "pipe",
|
|
50
|
+
});
|
|
51
|
+
if (proc.exitCode !== 0) {
|
|
52
|
+
console.error(`ci command exited ${proc.exitCode}: ${proc.stderr.toString().trim()}`);
|
|
53
|
+
return 1;
|
|
54
|
+
}
|
|
55
|
+
let pipelines: unknown;
|
|
56
|
+
try {
|
|
57
|
+
pipelines = JSON.parse(proc.stdout.toString());
|
|
58
|
+
} catch {
|
|
59
|
+
pipelines = undefined;
|
|
60
|
+
}
|
|
61
|
+
if (!Array.isArray(pipelines)) {
|
|
62
|
+
console.error("ci command must print a JSON array on stdout");
|
|
63
|
+
return 1;
|
|
64
|
+
}
|
|
65
|
+
appendMetric(cfg, { type: "ci", mr, repo: repoDir, tries: pipelines.length, ts: now });
|
|
66
|
+
console.log(`ci: ${mr} needed ${pipelines.length} pipeline(s)`);
|
|
67
|
+
return 0;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Marks one guard BLOCK line (by its ISO timestamp) as a false alarm. */
|
|
71
|
+
export function recordFalseAlarm(cfg: Config, logTs: string, why: string, now: number): number {
|
|
72
|
+
if (!logTs || !why) {
|
|
73
|
+
console.error(METRICS_USAGE);
|
|
74
|
+
return 2;
|
|
75
|
+
}
|
|
76
|
+
appendMetric(cfg, { type: "false-alarm", log_ts: logTs, why, ts: now });
|
|
77
|
+
console.log(`false-alarm recorded for ${logTs}`);
|
|
78
|
+
return 0;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Records the owner's decision on one proposed rule change. */
|
|
82
|
+
export function recordRule(cfg: Config, text: string, decision: "approved" | "rejected", now: number): number {
|
|
83
|
+
if (!text) {
|
|
84
|
+
console.error(METRICS_USAGE);
|
|
85
|
+
return 2;
|
|
86
|
+
}
|
|
87
|
+
appendMetric(cfg, { type: "rule", text, decision, ts: now });
|
|
88
|
+
console.log(`rule ${decision}: ${text}`);
|
|
89
|
+
return 0;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Writes notes/metrics.md and prints the same report: this window against the previous one. */
|
|
93
|
+
export function reportCmd(cfg: Config, source: RunSource, args: string[], now: number): number {
|
|
94
|
+
const raw = flagValue(args, "--days");
|
|
95
|
+
const days = raw === undefined ? cfg.metrics.report_days : Number(raw);
|
|
96
|
+
if (!Number.isInteger(days) || days < 1) {
|
|
97
|
+
console.error(METRICS_USAGE);
|
|
98
|
+
return 2;
|
|
99
|
+
}
|
|
100
|
+
const { md, text } = buildReport(cfg, source, days, now);
|
|
101
|
+
mkdirSync(cfg.paths.notes, { recursive: true });
|
|
102
|
+
writeFileSync(join(cfg.paths.notes, "metrics.md"), md);
|
|
103
|
+
console.log(text);
|
|
104
|
+
return 0;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export async function runMetrics(args: string[]): Promise<number> {
|
|
108
|
+
let cfg: Config;
|
|
109
|
+
try {
|
|
110
|
+
cfg = loadConfig();
|
|
111
|
+
} catch (err) {
|
|
112
|
+
console.error(err instanceof ConfigError ? err.message : String(err));
|
|
113
|
+
return 1;
|
|
114
|
+
}
|
|
115
|
+
const [sub = "", ...rest] = args;
|
|
116
|
+
const now = nowSec();
|
|
117
|
+
if (sub === "ci") return recordCi(cfg, rest[0] ?? "", rest[1] ?? "", now);
|
|
118
|
+
if (sub === "report") return reportCmd(cfg, defaultRunSource(cfg), rest, now);
|
|
119
|
+
if (sub === "false-alarm") return recordFalseAlarm(cfg, rest[0] ?? "", flagValue(rest, "--why") ?? "", now);
|
|
120
|
+
if (sub === "rule") {
|
|
121
|
+
const approved = rest.includes("--approved");
|
|
122
|
+
const rejected = rest.includes("--rejected");
|
|
123
|
+
if (approved === rejected) {
|
|
124
|
+
console.error(METRICS_USAGE);
|
|
125
|
+
return 2;
|
|
126
|
+
}
|
|
127
|
+
return recordRule(cfg, rest[0] ?? "", approved ? "approved" : "rejected", now);
|
|
128
|
+
}
|
|
129
|
+
console.error(METRICS_USAGE);
|
|
130
|
+
return 2;
|
|
131
|
+
}
|
package/src/core/agent-score.ts
CHANGED
|
@@ -28,7 +28,7 @@ function eventsPath(cfg: Config): string {
|
|
|
28
28
|
return join(cfg.paths.score_state, "events.jsonl");
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
-
function readEvents(cfg: Config): Record<string, unknown>[] {
|
|
31
|
+
export function readEvents(cfg: Config): Record<string, unknown>[] {
|
|
32
32
|
const path = eventsPath(cfg);
|
|
33
33
|
if (!existsSync(path)) return [];
|
|
34
34
|
return readFileSync(path, "utf8")
|
package/src/core/config.ts
CHANGED
|
@@ -112,6 +112,7 @@ export interface Config {
|
|
|
112
112
|
ledger_command: string;
|
|
113
113
|
};
|
|
114
114
|
rollover: { enabled: boolean; max_session_mb: number };
|
|
115
|
+
metrics: { report_days: number; correction_patterns: string[]; ci_pipelines_cmd: string };
|
|
115
116
|
machine: {
|
|
116
117
|
load_over_cores: number;
|
|
117
118
|
load_max: number;
|
|
@@ -260,6 +261,14 @@ function check(cfg: Config): void {
|
|
|
260
261
|
throw new ConfigError("guards.sub_warn_calls must be <= guards.sub_max_calls");
|
|
261
262
|
}
|
|
262
263
|
if (!(cfg.rollover.max_session_mb > 0)) throw new ConfigError("rollover.max_session_mb must be > 0");
|
|
264
|
+
if (!(cfg.metrics.report_days >= 1)) throw new ConfigError("metrics.report_days must be >= 1");
|
|
265
|
+
for (const p of cfg.metrics.correction_patterns) {
|
|
266
|
+
try {
|
|
267
|
+
new RegExp(p, "i");
|
|
268
|
+
} catch {
|
|
269
|
+
throw new ConfigError(`metrics.correction_patterns: not a valid regex: ${p}`);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
263
272
|
for (const [key, value] of Object.entries(cfg.paths)) {
|
|
264
273
|
if (key === "work_roots") {
|
|
265
274
|
if (!Array.isArray(value) || value.some(v => typeof v !== "string")) {
|
package/src/core/main-start.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { readFileSync } from "node:fs";
|
|
1
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
2
2
|
import { spawn } from "node:child_process";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
@@ -59,6 +59,9 @@ export async function mainStartText(args: string[], cfg: Config, opts: { inherit
|
|
|
59
59
|
const h = args[0] ?? String(cfg.health.default_hours);
|
|
60
60
|
const childStdin = opts.inheritStdin ? "inherit" : "ignore";
|
|
61
61
|
const childStderr = opts.inheritStdin ? "inherit" : "pipe";
|
|
62
|
+
// Weekly self-metrics: nudge the owner's report when notes/metrics.md is missing or older than the window.
|
|
63
|
+
const due = metricsDueLine(cfg, Date.now());
|
|
64
|
+
if (due) say(due);
|
|
62
65
|
say("=== machine");
|
|
63
66
|
const mg = await run(bin("machine-guard", cfg), [], { stderr: "ignore" });
|
|
64
67
|
const mgLines = mg.stdout.trim().split("\n");
|
|
@@ -107,3 +110,12 @@ export async function mainStart(args: string[], cfg: Config): Promise<number> {
|
|
|
107
110
|
process.stdout.write(await mainStartText(args, cfg, { inheritStdin: true }));
|
|
108
111
|
return 0;
|
|
109
112
|
}
|
|
113
|
+
|
|
114
|
+
// Due line for the weekly self-metrics report; null when notes/metrics.md is fresh.
|
|
115
|
+
export function metricsDueLine(cfg: Config, nowMs: number): string | null {
|
|
116
|
+
const reportFile = join(cfg.paths.notes, "metrics.md");
|
|
117
|
+
const stamp = existsSync(reportFile) ? statSync(reportFile).mtime : null;
|
|
118
|
+
if (stamp && nowMs - stamp.getTime() <= cfg.metrics.report_days * 86400 * 1000) return null;
|
|
119
|
+
const last = stamp ? stamp.toISOString().slice(0, 10) : "never";
|
|
120
|
+
return `metrics: report due (last: ${last}) — run neurastream metrics report, then propose ONE rule change to the owner`;
|
|
121
|
+
}
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
// Self-metrics: numbers about Neurastream's own work, per time window. Pure functions over
|
|
2
|
+
// runs (via RunSource), the score ledger (events.jsonl) and metrics.jsonl (ci, false-alarm,
|
|
3
|
+
// rule). No harness names, no literals beyond the event types; every knob comes from the
|
|
4
|
+
// `metrics:` config section.
|
|
5
|
+
|
|
6
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import type { Config } from "./config.ts";
|
|
9
|
+
import type { Run, RunSource } from "./adapter.ts";
|
|
10
|
+
import { readEvents } from "./agent-score.ts";
|
|
11
|
+
|
|
12
|
+
export type Ev = Record<string, unknown>;
|
|
13
|
+
|
|
14
|
+
/** Half-open window [from, to) in unix seconds. */
|
|
15
|
+
export interface Window {
|
|
16
|
+
from: number;
|
|
17
|
+
to: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface Inputs {
|
|
21
|
+
runs: Run[];
|
|
22
|
+
events: Ev[];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const DAY = 86400;
|
|
26
|
+
|
|
27
|
+
/** Current window [now-N, now) and the one before it [now-2N, now-N). */
|
|
28
|
+
export function windows(now: number, days: number): { cur: Window; prev: Window } {
|
|
29
|
+
const span = days * DAY;
|
|
30
|
+
return {
|
|
31
|
+
cur: { from: now - span, to: now },
|
|
32
|
+
prev: { from: now - 2 * span, to: now - span },
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function inWindow(t: number, w: Window): boolean {
|
|
37
|
+
return t >= w.from && t < w.to;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Loads every run touched in the last two windows plus the full event ledger. */
|
|
41
|
+
export function loadInputs(cfg: Config, source: RunSource, now: number, days: number): Inputs {
|
|
42
|
+
return {
|
|
43
|
+
runs: source.listRuns(now - 2 * days * DAY),
|
|
44
|
+
events: readEvents(cfg),
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// ---- metrics.jsonl: the facts the owner and the CI command record ----
|
|
49
|
+
|
|
50
|
+
export function metricsPath(cfg: Config): string {
|
|
51
|
+
return join(cfg.paths.score_state, "metrics.jsonl");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Appends one JSON line; the state directory is created on first use. */
|
|
55
|
+
export function appendMetric(cfg: Config, rec: Ev): void {
|
|
56
|
+
mkdirSync(cfg.paths.score_state, { recursive: true });
|
|
57
|
+
appendFileSync(metricsPath(cfg), `${JSON.stringify(rec)}\n`);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function readMetricEvents(cfg: Config): Ev[] {
|
|
61
|
+
const path = metricsPath(cfg);
|
|
62
|
+
if (!existsSync(path)) return [];
|
|
63
|
+
const out: Ev[] = [];
|
|
64
|
+
for (const line of readFileSync(path, "utf8").split("\n")) {
|
|
65
|
+
if (!line.trim()) continue;
|
|
66
|
+
try {
|
|
67
|
+
out.push(JSON.parse(line) as Ev);
|
|
68
|
+
} catch {
|
|
69
|
+
// A torn line from an interrupted append is skipped, not fatal.
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return out;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// ---- M1, M2: cost and idle calls per merge ----
|
|
76
|
+
|
|
77
|
+
export interface M1 {
|
|
78
|
+
accepts: number;
|
|
79
|
+
worker: number;
|
|
80
|
+
main: number;
|
|
81
|
+
/** null when nothing was merged in the window. */
|
|
82
|
+
perMerge: number | null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** M1: cost of sub and main runs written in the window, per accepted merge in the window. */
|
|
86
|
+
export function m1(inp: Inputs, w: Window): M1 {
|
|
87
|
+
let worker = 0;
|
|
88
|
+
let main = 0;
|
|
89
|
+
for (const r of inp.runs) {
|
|
90
|
+
if (!inWindow(r.lastWriteAt, w)) continue;
|
|
91
|
+
if (r.kind === "sub") worker += r.cost;
|
|
92
|
+
else if (r.kind === "main") main += r.cost;
|
|
93
|
+
}
|
|
94
|
+
const accepts = inp.events.filter((e) => e.type === "accept" && inWindow(Number(e.ts), w)).length;
|
|
95
|
+
return {
|
|
96
|
+
accepts,
|
|
97
|
+
worker,
|
|
98
|
+
main,
|
|
99
|
+
perMerge: accepts > 0 ? (worker + main) / accepts : null,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Event types that mean a worker's output was judged at some point. */
|
|
104
|
+
const JUDGED: Record<string, true> = { accept: true, diagnose: true, validate: true };
|
|
105
|
+
|
|
106
|
+
export interface M2 {
|
|
107
|
+
calls: number;
|
|
108
|
+
top: { id: string; calls: number }[];
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* M2: calls spent by finished-or-died sub runs written in the window that never got an
|
|
113
|
+
* accept, diagnose or validate event (checked over the whole ledger, not just the window).
|
|
114
|
+
*/
|
|
115
|
+
export function m2(inp: Inputs, w: Window): M2 {
|
|
116
|
+
const judged = new Set(inp.events.filter((e) => JUDGED[String(e.type)] === true).map((e) => String(e.agent)));
|
|
117
|
+
const idle = inp.runs.filter(
|
|
118
|
+
(r) =>
|
|
119
|
+
r.kind === "sub" &&
|
|
120
|
+
inWindow(r.lastWriteAt, w) &&
|
|
121
|
+
(r.status === "done" || r.status === "died") &&
|
|
122
|
+
!judged.has(r.id),
|
|
123
|
+
);
|
|
124
|
+
const top = idle
|
|
125
|
+
.map((r) => ({ id: r.id, calls: r.calls }))
|
|
126
|
+
.sort((a, b) => b.calls - a.calls || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
|
|
127
|
+
.slice(0, 3);
|
|
128
|
+
return { calls: idle.reduce((s, r) => s + r.calls, 0), top };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// ---- M3: CI tries ----
|
|
132
|
+
|
|
133
|
+
export interface M3 {
|
|
134
|
+
n: number;
|
|
135
|
+
/** null when no ci events fall in the window. */
|
|
136
|
+
mean: number | null;
|
|
137
|
+
/** MRs that needed 3 or more pipelines. */
|
|
138
|
+
big: string[];
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** M3: mean `tries` of `ci` events in the window, and the MRs that needed 3 or more. */
|
|
142
|
+
export function m3(events: Ev[], w: Window): M3 {
|
|
143
|
+
const ci = events.filter((e) => e.type === "ci" && inWindow(Number(e.ts), w));
|
|
144
|
+
const sum = ci.reduce((s, e) => s + Number(e.tries), 0);
|
|
145
|
+
return {
|
|
146
|
+
n: ci.length,
|
|
147
|
+
mean: ci.length > 0 ? sum / ci.length : null,
|
|
148
|
+
big: ci.filter((e) => Number(e.tries) >= 3).map((e) => String(e.mr)),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// ---- M4: owner corrections and Main's questions ----
|
|
153
|
+
|
|
154
|
+
interface Block {
|
|
155
|
+
type: string;
|
|
156
|
+
text: string;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Content blocks from RunMessage.text, which is a JSON dump of the message content. A plain
|
|
161
|
+
* string content counts as one text block; a dump that is not JSON is taken as plain text.
|
|
162
|
+
*/
|
|
163
|
+
function blocks(raw: string): Block[] {
|
|
164
|
+
let v: unknown;
|
|
165
|
+
try {
|
|
166
|
+
v = JSON.parse(raw);
|
|
167
|
+
} catch {
|
|
168
|
+
return [{ type: "text", text: raw }];
|
|
169
|
+
}
|
|
170
|
+
if (typeof v === "string") return [{ type: "text", text: v }];
|
|
171
|
+
if (!Array.isArray(v)) return [];
|
|
172
|
+
const out: Block[] = [];
|
|
173
|
+
for (const b of v) {
|
|
174
|
+
if (typeof b !== "object" || b === null) continue;
|
|
175
|
+
const o = b as Record<string, unknown>;
|
|
176
|
+
if (typeof o.text === "string") out.push({ type: String(o.type ?? ""), text: o.text });
|
|
177
|
+
}
|
|
178
|
+
return out;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export interface M4 {
|
|
182
|
+
users: number;
|
|
183
|
+
corrections: number;
|
|
184
|
+
questions: number;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* M4: user messages in main runs written in the window, how many match a correction pattern,
|
|
189
|
+
* and assistant messages whose last text block ends in "?". RunMessage has no timestamp, so
|
|
190
|
+
* a main run counts whole by its lastWriteAt.
|
|
191
|
+
*/
|
|
192
|
+
export function m4(runs: Run[], w: Window, patterns: RegExp[]): M4 {
|
|
193
|
+
const out: M4 = { users: 0, corrections: 0, questions: 0 };
|
|
194
|
+
for (const r of runs) {
|
|
195
|
+
if (r.kind !== "main" || !inWindow(r.lastWriteAt, w)) continue;
|
|
196
|
+
for (const m of r.messages) {
|
|
197
|
+
if (m.role === "user") {
|
|
198
|
+
out.users++;
|
|
199
|
+
const text = blocks(m.text)
|
|
200
|
+
.map((b) => b.text)
|
|
201
|
+
.join("\n");
|
|
202
|
+
if (patterns.some((p) => p.test(text))) out.corrections++;
|
|
203
|
+
} else if (m.role === "assistant") {
|
|
204
|
+
const last = blocks(m.text)
|
|
205
|
+
.filter((b) => b.type === "text")
|
|
206
|
+
.at(-1);
|
|
207
|
+
if (last?.text.trimEnd().endsWith("?")) out.questions++;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return out;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// ---- M5: guard BLOCK lines and false alarms ----
|
|
215
|
+
|
|
216
|
+
export interface GuardBlock {
|
|
217
|
+
ts: number;
|
|
218
|
+
reason: string;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Groups reasons by shape: paths cut to 40 chars, then digit runs collapsed to N. */
|
|
222
|
+
function reasonKey(text: string): string {
|
|
223
|
+
return text.replace(/\S*\/\S*/g, (p) => (p.length > 40 ? `${p.slice(0, 40)}…` : p)).replace(/\d+/g, "N");
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** BLOCK lines of one guard log, each `<ISO UTC> BLOCK <reason>`. Other lines are ignored. */
|
|
227
|
+
export function parseBlocks(text: string): GuardBlock[] {
|
|
228
|
+
const out: GuardBlock[] = [];
|
|
229
|
+
for (const line of text.split("\n")) {
|
|
230
|
+
const m = /^(\S+) BLOCK (.*)$/.exec(line);
|
|
231
|
+
if (!m) continue;
|
|
232
|
+
const ts = Date.parse(m[1] ?? "") / 1000;
|
|
233
|
+
if (Number.isNaN(ts)) continue;
|
|
234
|
+
out.push({ ts, reason: reasonKey(m[2] ?? "") });
|
|
235
|
+
}
|
|
236
|
+
return out;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** BLOCK lines from both guard logs named in config. A missing log counts as none. */
|
|
240
|
+
export function readBlocks(cfg: Config): GuardBlock[] {
|
|
241
|
+
return [cfg.paths.guard_log, cfg.paths.plan_guard_log].flatMap((p) =>
|
|
242
|
+
existsSync(p) ? parseBlocks(readFileSync(p, "utf8")) : [],
|
|
243
|
+
);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
export interface M5 {
|
|
247
|
+
blocks: number;
|
|
248
|
+
falseAlarms: number;
|
|
249
|
+
top: { reason: string; count: number }[];
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** M5: BLOCK lines in the window, false-alarm events in the window, and the 3 most common reasons. */
|
|
253
|
+
export function m5(blocks: GuardBlock[], events: Ev[], w: Window): M5 {
|
|
254
|
+
const inBlocks = blocks.filter((b) => inWindow(b.ts, w));
|
|
255
|
+
const counts = new Map<string, number>();
|
|
256
|
+
for (const b of inBlocks) counts.set(b.reason, (counts.get(b.reason) ?? 0) + 1);
|
|
257
|
+
const top = [...counts]
|
|
258
|
+
.map(([reason, count]) => ({ reason, count }))
|
|
259
|
+
.sort((a, b) => b.count - a.count || (a.reason < b.reason ? -1 : a.reason > b.reason ? 1 : 0))
|
|
260
|
+
.slice(0, 3);
|
|
261
|
+
return {
|
|
262
|
+
blocks: inBlocks.length,
|
|
263
|
+
falseAlarms: events.filter((e) => e.type === "false-alarm" && inWindow(Number(e.ts), w)).length,
|
|
264
|
+
top,
|
|
265
|
+
};
|
|
266
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
// The self-metrics report: this window against the previous one, the worst change, and a
|
|
2
|
+
// before/after check for each approved rule. Pure over RunSource, the ledger, metrics.jsonl
|
|
3
|
+
// and the guard logs; the caller decides where the text goes.
|
|
4
|
+
|
|
5
|
+
import type { Config } from "./config.ts";
|
|
6
|
+
import type { RunSource } from "./adapter.ts";
|
|
7
|
+
import {
|
|
8
|
+
m1,
|
|
9
|
+
m2,
|
|
10
|
+
m3,
|
|
11
|
+
m4,
|
|
12
|
+
m5,
|
|
13
|
+
readBlocks,
|
|
14
|
+
readMetricEvents,
|
|
15
|
+
windows,
|
|
16
|
+
loadInputs,
|
|
17
|
+
type Ev,
|
|
18
|
+
type GuardBlock,
|
|
19
|
+
type M1,
|
|
20
|
+
type M2,
|
|
21
|
+
type M3,
|
|
22
|
+
type M4,
|
|
23
|
+
type M5,
|
|
24
|
+
type Window,
|
|
25
|
+
} from "./metrics.ts";
|
|
26
|
+
|
|
27
|
+
const DAY = 86400;
|
|
28
|
+
|
|
29
|
+
const CAVEAT =
|
|
30
|
+
"M4 is a whole-run measure: a main run counts entirely by its last write time, so a run that spans a window edge counts in the window it ends in.";
|
|
31
|
+
|
|
32
|
+
interface Snap {
|
|
33
|
+
m1: M1;
|
|
34
|
+
m2: M2;
|
|
35
|
+
m3: M3;
|
|
36
|
+
m4: M4;
|
|
37
|
+
m5: M5;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function day(t: number): string {
|
|
41
|
+
return new Date(t * 1000).toISOString().slice(0, 10);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function snap(cfg: Config, source: RunSource, events: Ev[], blocks: GuardBlock[], w: Window): Snap {
|
|
45
|
+
const runs = source.listRuns(w.from);
|
|
46
|
+
const patterns = cfg.metrics.correction_patterns.map((p) => new RegExp(p, "i"));
|
|
47
|
+
return {
|
|
48
|
+
m1: m1({ runs, events }, w),
|
|
49
|
+
m2: m2({ runs, events }, w),
|
|
50
|
+
m3: m3(events, w),
|
|
51
|
+
m4: m4(runs, w, patterns),
|
|
52
|
+
m5: m5(blocks, events, w),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
interface Row {
|
|
57
|
+
name: string;
|
|
58
|
+
cur: number | null;
|
|
59
|
+
prev: number | null;
|
|
60
|
+
fmt: (v: number | null) => string;
|
|
61
|
+
/** M4 owner-message count is shown but never ranked: it measures volume, not quality. */
|
|
62
|
+
rank: boolean;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function rowsOf(c: Snap, p: Snap): Row[] {
|
|
66
|
+
const usd = (v: number | null) => (v === null ? "n/a (0 merged)" : `$${v.toFixed(2)}`);
|
|
67
|
+
const num = (v: number | null) => (v === null ? "n/a" : String(v));
|
|
68
|
+
const mean = (v: number | null) => (v === null ? "n/a" : v.toFixed(2));
|
|
69
|
+
return [
|
|
70
|
+
{ name: "M1 cost per merge", cur: c.m1.perMerge, prev: p.m1.perMerge, fmt: usd, rank: true },
|
|
71
|
+
{ name: "M2 idle calls", cur: c.m2.calls, prev: p.m2.calls, fmt: num, rank: true },
|
|
72
|
+
{ name: "M3 mean CI tries", cur: c.m3.mean, prev: p.m3.mean, fmt: mean, rank: true },
|
|
73
|
+
{ name: "M4 owner corrections", cur: c.m4.corrections, prev: p.m4.corrections, fmt: num, rank: true },
|
|
74
|
+
{ name: "M4 Main questions", cur: c.m4.questions, prev: p.m4.questions, fmt: num, rank: true },
|
|
75
|
+
{ name: "M4 owner messages", cur: c.m4.users, prev: p.m4.users, fmt: num, rank: false },
|
|
76
|
+
{ name: "M5 guard blocks", cur: c.m5.blocks, prev: p.m5.blocks, fmt: num, rank: true },
|
|
77
|
+
];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Percent change of this window against the previous one; null when either is missing or the base is 0. */
|
|
81
|
+
function change(r: Row): number | null {
|
|
82
|
+
if (r.cur === null || r.prev === null || r.prev === 0) return null;
|
|
83
|
+
return ((r.cur - r.prev) / r.prev) * 100;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function signed(d: number | null): string {
|
|
87
|
+
if (d === null) return "n/a";
|
|
88
|
+
return `${d >= 0 ? "+" : ""}${d.toFixed(1)}%`;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function detail(c: Snap): string[] {
|
|
92
|
+
const top2 = c.m2.top.map((t) => `${t.id} ${t.calls}`).join(", ") || "none";
|
|
93
|
+
const reasons = c.m5.top.map((t) => `${t.count}× ${t.reason}`).join("; ") || "none";
|
|
94
|
+
return [
|
|
95
|
+
`M1 worker $${c.m1.worker.toFixed(2)}, main $${c.m1.main.toFixed(2)}, accepts ${c.m1.accepts}`,
|
|
96
|
+
`M2 top idle runs: ${top2}`,
|
|
97
|
+
`M3 CI runs ${c.m3.n}; MRs at 3+ tries: ${c.m3.big.join(", ") || "none"}`,
|
|
98
|
+
`M4 owner messages ${c.m4.users}, corrections ${c.m4.corrections}, Main questions ${c.m4.questions}`,
|
|
99
|
+
`M5 guard blocks ${c.m5.blocks}, false alarms ${c.m5.falseAlarms}; top reasons: ${reasons}`,
|
|
100
|
+
];
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Before/after per approved rule. A rule younger than one window reads "measuring". */
|
|
104
|
+
function ruleLines(cfg: Config, source: RunSource, events: Ev[], blocks: GuardBlock[], days: number, now: number): string[] {
|
|
105
|
+
const out: string[] = [];
|
|
106
|
+
for (const e of events) {
|
|
107
|
+
if (e.type !== "rule" || e.decision !== "approved") continue;
|
|
108
|
+
const ts = Number(e.ts);
|
|
109
|
+
const head = `- ${String(e.text)} (approved ${day(ts)})`;
|
|
110
|
+
if (now - ts < days * DAY) {
|
|
111
|
+
out.push(`${head}: measuring`);
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
const before = snap(cfg, source, events, blocks, { from: ts - days * DAY, to: ts });
|
|
115
|
+
const after = snap(cfg, source, events, blocks, { from: ts, to: ts + days * DAY });
|
|
116
|
+
const perMerge = (s: Snap) => (s.m1.perMerge === null ? "n/a" : `$${s.m1.perMerge.toFixed(2)}`);
|
|
117
|
+
const tries = (s: Snap) => (s.m3.mean === null ? "n/a" : s.m3.mean.toFixed(2));
|
|
118
|
+
out.push(
|
|
119
|
+
`${head}: M1 ${perMerge(before)} → ${perMerge(after)}; M2 idle calls ${before.m2.calls} → ${after.m2.calls}; ` +
|
|
120
|
+
`M3 tries ${tries(before)} → ${tries(after)}; M5 blocks ${before.m5.blocks} → ${after.m5.blocks}`,
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
return out.length ? out : ["(none approved yet)"];
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export interface Report {
|
|
127
|
+
/** The full markdown written to notes/metrics.md. */
|
|
128
|
+
md: string;
|
|
129
|
+
/** The same content without the generated header, for stdout. */
|
|
130
|
+
text: string;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function buildReport(cfg: Config, source: RunSource, days: number, now: number): Report {
|
|
134
|
+
const inp = loadInputs(cfg, source, now, days);
|
|
135
|
+
const events = [...inp.events, ...readMetricEvents(cfg)];
|
|
136
|
+
const blocks = readBlocks(cfg);
|
|
137
|
+
const { cur, prev } = windows(now, days);
|
|
138
|
+
const c = snap(cfg, source, events, blocks, cur);
|
|
139
|
+
const p = snap(cfg, source, events, blocks, prev);
|
|
140
|
+
|
|
141
|
+
const rows = rowsOf(c, p);
|
|
142
|
+
let worst: Row | null = null;
|
|
143
|
+
let worstPct = 0;
|
|
144
|
+
for (const r of rows) {
|
|
145
|
+
const d = change(r);
|
|
146
|
+
if (r.rank && d !== null && d > worstPct) {
|
|
147
|
+
worst = r;
|
|
148
|
+
worstPct = d;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
const table = [
|
|
152
|
+
"| metric | this window | previous | change |",
|
|
153
|
+
"|---|---|---|---|",
|
|
154
|
+
...rows.map((r) => {
|
|
155
|
+
const mark = r === worst ? " ◀ worst" : "";
|
|
156
|
+
return `| ${r.name} | ${r.fmt(r.cur)} | ${r.fmt(r.prev)} | ${signed(change(r))}${mark} |`;
|
|
157
|
+
}),
|
|
158
|
+
];
|
|
159
|
+
const body = [
|
|
160
|
+
`Self-metrics: last ${days} days [${day(cur.from)} to ${day(cur.to)}) vs previous ${days} days.`,
|
|
161
|
+
"",
|
|
162
|
+
...table,
|
|
163
|
+
"",
|
|
164
|
+
...detail(c),
|
|
165
|
+
"",
|
|
166
|
+
"Approved rules, before vs after:",
|
|
167
|
+
...ruleLines(cfg, source, events, blocks, days, now),
|
|
168
|
+
].join("\n");
|
|
169
|
+
|
|
170
|
+
const md = [
|
|
171
|
+
"# Self-metrics (GENERATED by `neurastream metrics report`; do not hand-edit)",
|
|
172
|
+
"",
|
|
173
|
+
CAVEAT,
|
|
174
|
+
"",
|
|
175
|
+
body,
|
|
176
|
+
"",
|
|
177
|
+
].join("\n");
|
|
178
|
+
return { md, text: body };
|
|
179
|
+
}
|
package/templates/config.yml
CHANGED
|
@@ -118,6 +118,11 @@ rollover:
|
|
|
118
118
|
enabled: true
|
|
119
119
|
max_session_mb: 5
|
|
120
120
|
|
|
121
|
+
metrics:
|
|
122
|
+
report_days: 7
|
|
123
|
+
correction_patterns: ['\bno\b', 'wrong', 'why did', 'properly', 'not what', 'stop', 'bullshit', 'fuck']
|
|
124
|
+
ci_pipelines_cmd: "" # command run in the repo dir with {mr} replaced; stdout must be a JSON array; "" = not set
|
|
125
|
+
|
|
121
126
|
machine:
|
|
122
127
|
load_over_cores: 4
|
|
123
128
|
load_max: 0
|