neurastream 0.1.11 → 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 +15 -1
- 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/blockers.ts +434 -26
- 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
|
@@ -24,7 +24,7 @@ flowchart LR
|
|
|
24
24
|
| Part | What it enforces |
|
|
25
25
|
|---|---|
|
|
26
26
|
| Queue (`queue-check`, `queue-close`, `queue-cancel`) | Every open plan is listed in an index and follows a template. A plan leaves the queue only when its branch is merged into remote main and its done check passes; a failing check reopens it. A cancelled plan's unmerged work is saved under `refs/queue-archive/`. |
|
|
27
|
-
| Blockers | Each plan's phase 0 lists what helpers may not do: push, touch a path, run a command, or write a text. The guard
|
|
27
|
+
| Blockers | Each plan's phase 0 lists what helpers may not do: push, touch a path, run a command, or write a text. The guard judges the command that runs and the files it changes, not words inside commit messages, quoted text or heredoc bodies: `git commit -m "... push ..."` is allowed, `git push` is refused. |
|
|
28
28
|
| Guards | Helpers may only edit their plan's `## Progress`; they get a warning at call 90 and are stopped at call 100. Protected files need an owner unlock (a file the owner touches, valid 30 minutes). |
|
|
29
29
|
| Ledger (`agent-ledger`) | Tokens, cost, state and exit reason per agent; `--cap` refuses a spawn when a provider already runs 2. |
|
|
30
30
|
| Scoring (`agent-score`) | Points only for work Main accepted by commit, times the phase difficulty. Ranked per dollar and per hour. |
|
|
@@ -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/blockers.ts
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
import { readFileSync, statSync } from "node:fs";
|
|
12
12
|
import path from "node:path";
|
|
13
13
|
import { expandHome } from "./queue/lib.ts";
|
|
14
|
+
import { MAIN_PLAN_FILE } from "./guards.ts";
|
|
14
15
|
|
|
15
16
|
export interface BlockerCall {
|
|
16
17
|
tool: string;
|
|
@@ -45,11 +46,11 @@ function isDir(p: string): boolean {
|
|
|
45
46
|
}
|
|
46
47
|
}
|
|
47
48
|
|
|
48
|
-
//
|
|
49
|
-
const
|
|
49
|
+
// Eval code (JS or Python) keeps the whole-text test; shell commands are judged per command.
|
|
50
|
+
const CODE_MUTATING =
|
|
50
51
|
/(\brm\b|\bmv\b|\bcp\b|\btruncate\b|\bsed\s+-i|\btee\b|>{1,2}\s*\S|\bgit\s+(rm|mv|checkout|restore)\b|writeFile|Bun\.write|unlink|\bpatch\b)/;
|
|
51
52
|
|
|
52
|
-
function blockerEnv(call: BlockerCall, args: string[]): BlockerEnv {
|
|
53
|
+
export function blockerEnv(call: BlockerCall, args: string[]): BlockerEnv {
|
|
53
54
|
const shell = call.tool === "bash" || call.tool === "eval";
|
|
54
55
|
const writes = call.tool === "write" || call.tool === "edit" || call.tool === "ast_edit";
|
|
55
56
|
const command = shell ? String(call.input?.command || call.input?.code || "") : "";
|
|
@@ -136,11 +137,399 @@ function matchesPath(p: string, glob: string, call: BlockerCall): boolean {
|
|
|
136
137
|
return fnmatchToRegExp(glob).test(r) || fnmatchToRegExp(`${bare}/*`).test(r) || r === bare;
|
|
137
138
|
}
|
|
138
139
|
|
|
139
|
-
//
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
140
|
+
// ---- Shell: a quote-aware splitter, not a shell parser ---------------------------------------
|
|
141
|
+
// Splits on `;`, `&&`, `||`, `|`, `&`, `(`, `)` and newlines outside quotes. Each word keeps its
|
|
142
|
+
// quote-removed text and whether any part was quoted; output-redirection targets are kept apart
|
|
143
|
+
// from the words; heredoc bodies are dropped; the inside of `$(…)` and backticks becomes segments.
|
|
144
|
+
|
|
145
|
+
export interface ShellWord {
|
|
146
|
+
/** Text with quotes and escapes removed; a substitution contributes nothing (its segments are listed). */
|
|
147
|
+
text: string;
|
|
148
|
+
/** Source text, quotes included. */
|
|
149
|
+
raw: string;
|
|
150
|
+
/** Any part of the word was quoted or escaped. */
|
|
151
|
+
quoted: boolean;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export interface ShellSegment {
|
|
155
|
+
/** Command words in order; redirections and their targets are not words. */
|
|
156
|
+
words: ShellWord[];
|
|
157
|
+
/** Targets of output redirections: `>`, `>>`, `>|`, `&>`, `&>>`, `<>`, and `>&file`. */
|
|
158
|
+
writes: string[];
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
type WordBuf = { text: string; quoted: boolean; start: number };
|
|
162
|
+
type RedirKind = "write" | "dup" | "skip" | "heredoc";
|
|
163
|
+
|
|
164
|
+
/** Segments of a command in source order; a substitution's segments come before their parent's. */
|
|
165
|
+
export function splitShell(command: string): ShellSegment[] {
|
|
166
|
+
const out: ShellSegment[] = [];
|
|
167
|
+
scan(command, out);
|
|
168
|
+
return out;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function scan(src: string, out: ShellSegment[]): void {
|
|
172
|
+
const n = src.length;
|
|
173
|
+
const st: {
|
|
174
|
+
seg: ShellSegment;
|
|
175
|
+
word: WordBuf | null;
|
|
176
|
+
redir: RedirKind | null;
|
|
177
|
+
tabs: boolean;
|
|
178
|
+
heredocs: { delim: string; tabs: boolean }[];
|
|
179
|
+
} = { seg: { words: [], writes: [] }, word: null, redir: null, tabs: false, heredocs: [] };
|
|
180
|
+
let i = 0;
|
|
181
|
+
|
|
182
|
+
const ensure = (): WordBuf => {
|
|
183
|
+
if (!st.word) st.word = { text: "", quoted: false, start: i };
|
|
184
|
+
return st.word;
|
|
185
|
+
};
|
|
186
|
+
const endWord = (end: number): void => {
|
|
187
|
+
const w = st.word;
|
|
188
|
+
if (!w) return;
|
|
189
|
+
st.word = null;
|
|
190
|
+
if (w.text === "" && !w.quoted) return; // an unquoted empty word only comes from a $() substitution
|
|
191
|
+
const word: ShellWord = { text: w.text, raw: src.slice(w.start, end), quoted: w.quoted };
|
|
192
|
+
const kind = st.redir;
|
|
193
|
+
if (!kind) {
|
|
194
|
+
st.seg.words.push(word);
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
st.redir = null;
|
|
198
|
+
if (kind === "write" || (kind === "dup" && !/^(\d+|-)$/.test(word.text))) st.seg.writes.push(word.text);
|
|
199
|
+
else if (kind === "heredoc") st.heredocs.push({ delim: word.text, tabs: st.tabs });
|
|
200
|
+
};
|
|
201
|
+
const endSeg = (end: number): void => {
|
|
202
|
+
endWord(end);
|
|
203
|
+
st.redir = null;
|
|
204
|
+
if (st.seg.words.length || st.seg.writes.length) out.push(st.seg);
|
|
205
|
+
st.seg = { words: [], writes: [] };
|
|
206
|
+
};
|
|
207
|
+
// Skips the bodies of the heredocs opened on the line before `from`; returns the index after them.
|
|
208
|
+
const skipHeredocs = (from: number): number => {
|
|
209
|
+
let j = from;
|
|
210
|
+
for (const h of st.heredocs) {
|
|
211
|
+
while (j < n) {
|
|
212
|
+
const e = src.indexOf("\n", j);
|
|
213
|
+
const line = src.slice(j, e < 0 ? n : e);
|
|
214
|
+
j = e < 0 ? n : e + 1;
|
|
215
|
+
if ((h.tabs ? line.replace(/^\t+/, "") : line) === h.delim) break;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
st.heredocs = [];
|
|
219
|
+
return j;
|
|
220
|
+
};
|
|
221
|
+
// Double-quoted text from `from` (after the opening quote); returns the index after the closing quote.
|
|
222
|
+
const readDouble = (from: number, w: WordBuf): number => {
|
|
223
|
+
let j = from;
|
|
224
|
+
while (j < n && src.charAt(j) !== '"') {
|
|
225
|
+
const d = src.charAt(j);
|
|
226
|
+
const nx = src.charAt(j + 1);
|
|
227
|
+
if (d === "\\" && nx === "\n") j += 2;
|
|
228
|
+
else if (d === "\\" && nx !== "" && '"\\$`'.includes(nx)) {
|
|
229
|
+
w.text += nx;
|
|
230
|
+
j += 2;
|
|
231
|
+
} else if (d === "$" && nx === "(") {
|
|
232
|
+
const end = matchParen(src, j + 2);
|
|
233
|
+
scan(src.slice(j + 2, end), out);
|
|
234
|
+
j = end + 1;
|
|
235
|
+
} else if (d === "`") {
|
|
236
|
+
const end = closeTick(src, j + 1);
|
|
237
|
+
scan(src.slice(j + 1, end), out);
|
|
238
|
+
j = end + 1;
|
|
239
|
+
} else {
|
|
240
|
+
w.text += d;
|
|
241
|
+
j++;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
return j + 1;
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
while (i < n) {
|
|
248
|
+
const c = src.charAt(i);
|
|
249
|
+
if (c === " " || c === "\t" || c === "\r") {
|
|
250
|
+
endWord(i);
|
|
251
|
+
i++;
|
|
252
|
+
} else if (c === "\\") {
|
|
253
|
+
if (src.charAt(i + 1) === "\n") i += 2;
|
|
254
|
+
else {
|
|
255
|
+
const w = ensure();
|
|
256
|
+
w.quoted = true;
|
|
257
|
+
w.text += src.charAt(i + 1);
|
|
258
|
+
i += 2;
|
|
259
|
+
}
|
|
260
|
+
} else if (c === "'") {
|
|
261
|
+
const w = ensure();
|
|
262
|
+
w.quoted = true;
|
|
263
|
+
const close = src.indexOf("'", i + 1);
|
|
264
|
+
const end = close < 0 ? n : close;
|
|
265
|
+
w.text += src.slice(i + 1, end);
|
|
266
|
+
i = end + 1;
|
|
267
|
+
} else if (c === '"') {
|
|
268
|
+
const w = ensure();
|
|
269
|
+
w.quoted = true;
|
|
270
|
+
i = readDouble(i + 1, w);
|
|
271
|
+
} else if (c === "$" && src.charAt(i + 1) === "(") {
|
|
272
|
+
ensure();
|
|
273
|
+
const end = matchParen(src, i + 2);
|
|
274
|
+
scan(src.slice(i + 2, end), out);
|
|
275
|
+
i = end + 1;
|
|
276
|
+
} else if (c === "`") {
|
|
277
|
+
ensure();
|
|
278
|
+
const end = closeTick(src, i + 1);
|
|
279
|
+
scan(src.slice(i + 1, end), out);
|
|
280
|
+
i = end + 1;
|
|
281
|
+
} else if (c === "#" && !st.word) {
|
|
282
|
+
while (i < n && src.charAt(i) !== "\n") i++;
|
|
283
|
+
} else if (c === "\n") {
|
|
284
|
+
endSeg(i);
|
|
285
|
+
i = skipHeredocs(i + 1);
|
|
286
|
+
} else if (c === ";" || c === "(" || c === ")") {
|
|
287
|
+
endSeg(i);
|
|
288
|
+
i++;
|
|
289
|
+
} else if (c === "|") {
|
|
290
|
+
endSeg(i);
|
|
291
|
+
i += src.charAt(i + 1) === "|" ? 2 : 1;
|
|
292
|
+
} else if (c === "&") {
|
|
293
|
+
if (src.charAt(i + 1) === ">") {
|
|
294
|
+
endWord(i);
|
|
295
|
+
st.redir = "write";
|
|
296
|
+
i += src.charAt(i + 2) === ">" ? 3 : 2;
|
|
297
|
+
} else {
|
|
298
|
+
endSeg(i);
|
|
299
|
+
i += src.charAt(i + 1) === "&" ? 2 : 1;
|
|
300
|
+
}
|
|
301
|
+
} else if (c === ">" || c === "<") {
|
|
302
|
+
const pending = st.word;
|
|
303
|
+
// A bare fd number before a redirection (the 2 in 2>file) is not a word.
|
|
304
|
+
if (pending && !pending.quoted && /^\d+$/.test(pending.text)) st.word = null;
|
|
305
|
+
else endWord(i);
|
|
306
|
+
let j = i + 1;
|
|
307
|
+
const nx = src.charAt(j);
|
|
308
|
+
if (c === ">") {
|
|
309
|
+
if (nx === ">" || nx === "|") {
|
|
310
|
+
st.redir = "write";
|
|
311
|
+
j++;
|
|
312
|
+
} else if (nx === "&") {
|
|
313
|
+
st.redir = "dup";
|
|
314
|
+
j++;
|
|
315
|
+
} else st.redir = "write";
|
|
316
|
+
} else if (nx === "<" && src.charAt(j + 1) === "<") {
|
|
317
|
+
st.redir = "skip";
|
|
318
|
+
j += 2;
|
|
319
|
+
} else if (nx === "<") {
|
|
320
|
+
st.redir = "heredoc";
|
|
321
|
+
j++;
|
|
322
|
+
st.tabs = src.charAt(j) === "-";
|
|
323
|
+
if (st.tabs) j++;
|
|
324
|
+
} else if (nx === ">") {
|
|
325
|
+
st.redir = "write";
|
|
326
|
+
j++;
|
|
327
|
+
} else if (nx === "&") {
|
|
328
|
+
st.redir = "dup";
|
|
329
|
+
j++;
|
|
330
|
+
} else st.redir = "skip";
|
|
331
|
+
i = j;
|
|
332
|
+
} else {
|
|
333
|
+
ensure().text += c;
|
|
334
|
+
i++;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
endSeg(n);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// Index of the `)` closing a `$(` whose body starts at `from`; src.length when unclosed.
|
|
341
|
+
function matchParen(src: string, from: number): number {
|
|
342
|
+
let depth = 1;
|
|
343
|
+
let j = from;
|
|
344
|
+
while (j < src.length) {
|
|
345
|
+
const c = src.charAt(j);
|
|
346
|
+
if (c === "\\") j += 2;
|
|
347
|
+
else if (c === "'") {
|
|
348
|
+
const close = src.indexOf("'", j + 1);
|
|
349
|
+
j = close < 0 ? src.length : close + 1;
|
|
350
|
+
} else if (c === '"') {
|
|
351
|
+
j++;
|
|
352
|
+
while (j < src.length && src.charAt(j) !== '"') j += src.charAt(j) === "\\" ? 2 : 1;
|
|
353
|
+
j++;
|
|
354
|
+
} else {
|
|
355
|
+
if (c === "(") depth++;
|
|
356
|
+
else if (c === ")" && --depth === 0) return j;
|
|
357
|
+
j++;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
return src.length;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// Index of the backtick closing one opened before `from`; src.length when unclosed.
|
|
364
|
+
function closeTick(src: string, from: number): number {
|
|
365
|
+
let j = from;
|
|
366
|
+
while (j < src.length && src.charAt(j) !== "`") j += src.charAt(j) === "\\" ? 2 : 1;
|
|
367
|
+
return Math.min(j, src.length);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// ---- Shell commands ---------------------------------------------------------------------------
|
|
371
|
+
const ASSIGN = /^[A-Za-z_]\w*=/;
|
|
372
|
+
// Words that only run another command: skipped to reach the command they run.
|
|
373
|
+
const WRAPPERS: Record<string, true> = {
|
|
374
|
+
env: true,
|
|
375
|
+
nohup: true,
|
|
376
|
+
command: true,
|
|
377
|
+
builtin: true,
|
|
378
|
+
exec: true,
|
|
379
|
+
time: true,
|
|
380
|
+
nice: true,
|
|
381
|
+
sudo: true,
|
|
382
|
+
xargs: true,
|
|
383
|
+
timeout: true,
|
|
384
|
+
"!": true,
|
|
385
|
+
"{": true,
|
|
386
|
+
"}": true,
|
|
387
|
+
};
|
|
388
|
+
const SHELLS: Record<string, true> = { bash: true, sh: true, zsh: true, dash: true };
|
|
389
|
+
// Interpreters whose arguments may be code that writes files (bun -e 'writeFileSync(...)').
|
|
390
|
+
const INTERPRETERS: Record<string, true> = {
|
|
391
|
+
...SHELLS,
|
|
392
|
+
bun: true,
|
|
393
|
+
node: true,
|
|
394
|
+
deno: true,
|
|
395
|
+
python: true,
|
|
396
|
+
python3: true,
|
|
397
|
+
perl: true,
|
|
398
|
+
ruby: true,
|
|
399
|
+
};
|
|
400
|
+
const GIT_VALUE_OPTS: Record<string, true> = { "-C": true, "-c": true, "--git-dir": true, "--work-tree": true, "--namespace": true };
|
|
401
|
+
const MUTATING_NAMES: Record<string, true> = { rm: true, mv: true, truncate: true, tee: true, patch: true };
|
|
402
|
+
const GIT_MUTATING: Record<string, true> = { rm: true, mv: true, checkout: true, restore: true };
|
|
403
|
+
const CODE_WRITE = /writeFile|Bun\.write|unlink/;
|
|
404
|
+
|
|
405
|
+
interface ShellCommand {
|
|
406
|
+
name: string;
|
|
407
|
+
args: ShellWord[];
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
// The command a segment runs: leading assignments, wrapper words, options and durations are skipped.
|
|
411
|
+
function commandOf(seg: ShellSegment): ShellCommand | null {
|
|
412
|
+
let k = 0;
|
|
413
|
+
for (; k < seg.words.length; k++) {
|
|
414
|
+
const w = seg.words[k];
|
|
415
|
+
if (!w) break;
|
|
416
|
+
const skippable = ASSIGN.test(w.raw) || WRAPPERS[w.text] === true || w.text.startsWith("-") || /^[\d.]+[smhd]?$/.test(w.text);
|
|
417
|
+
if (!skippable) break;
|
|
418
|
+
}
|
|
419
|
+
const head = seg.words[k];
|
|
420
|
+
return head ? { name: path.basename(head.text), args: seg.words.slice(k + 1) } : null;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// git's subcommand and the words after it, skipping global options (-C <dir>, --git-dir=...).
|
|
424
|
+
function gitSub(args: ShellWord[]): { sub: string; rest: ShellWord[] } | null {
|
|
425
|
+
for (let k = 0; k < args.length; k++) {
|
|
426
|
+
const t = args[k]?.text ?? "";
|
|
427
|
+
if (GIT_VALUE_OPTS[t] === true) {
|
|
428
|
+
k++;
|
|
429
|
+
continue;
|
|
430
|
+
}
|
|
431
|
+
if (!t.startsWith("-")) return { sub: t, rest: args.slice(k + 1) };
|
|
432
|
+
}
|
|
433
|
+
return null;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// A `-c` script as shell source: its quotes removed.
|
|
437
|
+
function scriptText(w: ShellWord): string {
|
|
438
|
+
const r = w.raw;
|
|
439
|
+
if (r.length >= 2 && r.startsWith("'") && r.endsWith("'")) return r.slice(1, -1);
|
|
440
|
+
if (r.length >= 2 && r.startsWith('"') && r.endsWith('"')) return r.slice(1, -1).replace(/\\(["\\$`])/g, "$1");
|
|
441
|
+
return w.text;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// Scripts a segment runs through `bash|sh|zsh|dash -c <script>`.
|
|
445
|
+
function shellScripts(seg: ShellSegment): string[] {
|
|
446
|
+
const cmd = commandOf(seg);
|
|
447
|
+
if (!cmd || SHELLS[cmd.name] !== true) return [];
|
|
448
|
+
for (let k = 0; k < cmd.args.length; k++) {
|
|
449
|
+
const w = cmd.args[k];
|
|
450
|
+
if (!w) break;
|
|
451
|
+
if (w.text === "-o" || w.text === "+o") {
|
|
452
|
+
k++;
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
if (/^-[a-zA-Z]*c/.test(w.text)) {
|
|
456
|
+
const script = cmd.args[k + 1];
|
|
457
|
+
return script ? [scriptText(script)] : [];
|
|
458
|
+
}
|
|
459
|
+
if (!w.text.startsWith("-") && !w.text.startsWith("+")) break;
|
|
460
|
+
}
|
|
461
|
+
return [];
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
// Every segment that runs, in order: the splitter's segments, each followed by the segments of
|
|
465
|
+
// any `bash -c` script it runs.
|
|
466
|
+
function executed(command: string): ShellSegment[] {
|
|
467
|
+
const out: ShellSegment[] = [];
|
|
468
|
+
for (const seg of splitShell(command)) {
|
|
469
|
+
out.push(seg);
|
|
470
|
+
for (const script of shellScripts(seg)) out.push(...executed(script));
|
|
471
|
+
}
|
|
472
|
+
return out;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
// Words a segment changes: its output redirections, the operands of mutating commands, the last
|
|
476
|
+
// operand of cp (its destination; the source is only read), and the file arguments of code an
|
|
477
|
+
// interpreter runs.
|
|
478
|
+
function mutationTargets(seg: ShellSegment): string[] {
|
|
479
|
+
const out = [...seg.writes];
|
|
480
|
+
const cmd = commandOf(seg);
|
|
481
|
+
if (!cmd) return out;
|
|
482
|
+
let args = cmd.args;
|
|
483
|
+
let mutating = MUTATING_NAMES[cmd.name] === true;
|
|
484
|
+
if (cmd.name === "git") {
|
|
485
|
+
const g = gitSub(cmd.args);
|
|
486
|
+
args = g?.rest ?? [];
|
|
487
|
+
mutating = g !== null && GIT_MUTATING[g.sub] === true;
|
|
488
|
+
}
|
|
489
|
+
const ops = args.filter((w) => w.text !== "" && !w.text.startsWith("-")).map((w) => w.text);
|
|
490
|
+
if (mutating) out.push(...ops);
|
|
491
|
+
else if (cmd.name === "cp" && ops.length) out.push(ops[ops.length - 1] ?? "");
|
|
492
|
+
else if (cmd.name === "sed" && cmd.args.some((a) => /^-[a-zA-Z]*i|^--in-place/.test(a.text))) out.push(...ops.slice(1));
|
|
493
|
+
const raw = seg.words.map((w) => w.raw).join(" ");
|
|
494
|
+
if (INTERPRETERS[cmd.name] === true && CODE_WRITE.test(raw)) {
|
|
495
|
+
out.push(...raw.split(/[\s;&|<>(),'"]+/).filter((t) => t !== "" && !t.startsWith("-")));
|
|
496
|
+
}
|
|
497
|
+
return out;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
// Directories a command may run in: the call's cwd and every directory a `cd` reaches. Subshells
|
|
501
|
+
// and `&&` chains are not tracked, so each relative target is checked against all of them.
|
|
502
|
+
function shellDirs(segs: ShellSegment[], base: string): string[] {
|
|
503
|
+
const dirs = [base];
|
|
504
|
+
let last = base;
|
|
505
|
+
for (const seg of segs) {
|
|
506
|
+
const cmd = commandOf(seg);
|
|
507
|
+
if (cmd?.name !== "cd") continue;
|
|
508
|
+
const dir = cmd.args.find((w) => !w.text.startsWith("-"))?.text ?? "~";
|
|
509
|
+
last = path.resolve(last, expandHome(dir));
|
|
510
|
+
dirs.push(last);
|
|
511
|
+
}
|
|
512
|
+
return dirs;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
// Absolute targets of a shell command, each resolved against every directory it may run in.
|
|
516
|
+
function shellTargets(env: BlockerEnv): string[] {
|
|
517
|
+
const base = expandHome(String(env.call.input?.cwd || env.call.cwd || "/"));
|
|
518
|
+
const segs = executed(env.command);
|
|
519
|
+
const dirs = shellDirs(segs, base);
|
|
520
|
+
const out: string[] = [];
|
|
521
|
+
for (const seg of segs) {
|
|
522
|
+
for (const t of mutationTargets(seg)) {
|
|
523
|
+
if (t === "") continue;
|
|
524
|
+
for (const d of dirs) out.push(path.resolve(d, expandHome(t)));
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
return out;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
// eval code keeps the old whole-text rule: every word of the code counts as a path.
|
|
531
|
+
function evalPaths(env: BlockerEnv): string[] {
|
|
532
|
+
const base = expandHome(String(env.call.input?.cwd || env.call.cwd || "/"));
|
|
144
533
|
const out: string[] = [];
|
|
145
534
|
for (const w of env.command.split(/[\s;&|<>()'"]+/)) {
|
|
146
535
|
const t = w.trim();
|
|
@@ -149,6 +538,18 @@ function shellPaths(env: BlockerEnv): string[] {
|
|
|
149
538
|
return out;
|
|
150
539
|
}
|
|
151
540
|
|
|
541
|
+
// A segment that pushes (git push) or merges an MR/PR (glab mr merge, gh pr merge), as a command.
|
|
542
|
+
function pushesOrMerges(seg: ShellSegment): boolean {
|
|
543
|
+
const cmd = commandOf(seg);
|
|
544
|
+
if (!cmd) return false;
|
|
545
|
+
if (cmd.name === "git") return gitSub(cmd.args)?.sub === "push";
|
|
546
|
+
const words = cmd.args.map((w) => w.text);
|
|
547
|
+
return (
|
|
548
|
+
(cmd.name === "glab" && words[0] === "mr" && words[1] === "merge") ||
|
|
549
|
+
(cmd.name === "gh" && words[0] === "pr" && words[1] === "merge")
|
|
550
|
+
);
|
|
551
|
+
}
|
|
552
|
+
|
|
152
553
|
// The text a call would write: write content, the added lines of an edit, the whole input of an
|
|
153
554
|
// ast_edit, and the command itself for shell/eval.
|
|
154
555
|
function writtenText(env: BlockerEnv): string {
|
|
@@ -164,24 +565,31 @@ function writtenText(env: BlockerEnv): string {
|
|
|
164
565
|
return env.command;
|
|
165
566
|
}
|
|
166
567
|
|
|
167
|
-
/** deny-command <regex>...: refuse shell
|
|
568
|
+
/** deny-command <regex>...: refuse shell commands matching any regex (use \s for spaces). Each command is matched by its unquoted words, so quoted arguments and heredoc bodies never match; eval code is matched whole. */
|
|
168
569
|
export function denyCommand(env: BlockerEnv): void {
|
|
169
570
|
if (!env.args.length) block("deny-command needs at least one regex in the plan");
|
|
170
|
-
if (env.shell)
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
571
|
+
if (!env.shell) return;
|
|
572
|
+
const texts =
|
|
573
|
+
env.call.tool === "eval"
|
|
574
|
+
? [env.command]
|
|
575
|
+
: executed(env.command).map((seg) => seg.words.filter((w) => !w.quoted).map((w) => w.text).join(" "));
|
|
576
|
+
for (const rx of env.args) {
|
|
577
|
+
const re = new RegExp(rx);
|
|
578
|
+
if (texts.some((t) => re.test(t))) block(`command matches forbidden pattern /${rx}/ (plan Forbidden list)`);
|
|
174
579
|
}
|
|
175
580
|
}
|
|
176
581
|
|
|
177
|
-
/** deny-path <glob>...: refuse
|
|
582
|
+
/** deny-path <glob>...: refuse changes to matching paths: write/edit/ast_edit targets (live plan files excepted: plan-edit governs them), shell redirections and mutating commands. */
|
|
178
583
|
export function denyPath(env: BlockerEnv): void {
|
|
179
584
|
if (!env.args.length) block("deny-path needs at least one glob in the plan");
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
585
|
+
let targets: string[] = [];
|
|
586
|
+
if (env.writes) targets = (env.call.paths ?? []).filter((p) => !MAIN_PLAN_FILE.test(p));
|
|
587
|
+
else if (env.call.tool === "eval") {
|
|
588
|
+
if (CODE_MUTATING.test(env.command)) targets = [...(env.call.paths ?? []), ...evalPaths(env)];
|
|
589
|
+
} else if (env.shell) targets = shellTargets(env);
|
|
590
|
+
for (const p of targets) {
|
|
591
|
+
for (const g of env.args) {
|
|
592
|
+
if (matchesPath(p, g, env.call)) block(`${p} is forbidden by the plan (deny-path ${g})`);
|
|
185
593
|
}
|
|
186
594
|
}
|
|
187
595
|
}
|
|
@@ -197,12 +605,12 @@ export function denyText(env: BlockerEnv): void {
|
|
|
197
605
|
}
|
|
198
606
|
}
|
|
199
607
|
|
|
200
|
-
/** no-push: subagents
|
|
608
|
+
/** no-push: subagents never push or merge (Main pushes and merges). Matched as commands, never as words inside arguments. */
|
|
201
609
|
export function noPush(env: BlockerEnv): void {
|
|
202
|
-
if (
|
|
203
|
-
|
|
204
|
-
env.call.
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
610
|
+
if (!env.shell || env.call.agent === "main") return;
|
|
611
|
+
const hit =
|
|
612
|
+
env.call.tool === "eval"
|
|
613
|
+
? /\bgit\b[^;&|\n]*\bpush\b|\bglab\s+mr\s+merge\b|\bgh\s+pr\s+merge\b/.test(env.command)
|
|
614
|
+
: executed(env.command).some(pushesOrMerges);
|
|
615
|
+
if (hit) block("subagents never push or merge; commit on the feature branch and report");
|
|
208
616
|
}
|
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
|