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 CHANGED
@@ -133,6 +133,10 @@ Green is both exiting 0.
133
133
 
134
134
  `neurastream traces briefs --since 30d` lists each spawn brief Main sent (shared context first, then the task's own text) with its features — length, a `file:line`, a verify command, a phase id, a plan path, a `Call budget` line, the number of acceptance lines — next to the spawned agent's waste and whether its work was accepted. `--json` gives the rows, `--report` compares the rows with and without each feature (a side with fewer than `traces.briefs.min_n` rows prints "n too small"). Brief text never prints. Read the report with care: a spawn without a plan is never accepted, and accept records exist only since scoring began, so all-time accept rates mostly measure when and for what an agent was spawned, not how good the brief was. Compare plan briefs from the same period before turning a gap into a rule; on 30 days of real briefs that comparison showed no feature strong enough for a brief-lint warning.
135
135
 
136
+ `neurastream labels episodes [--since 30d] [--json]` joins score events, subagent runs and the successful spawn brief that named each agent. Died or over-budget runs without an accept are included with no commits. The default window is `labels.episode_days` (30); `--since` overrides it for `labels episodes` only. `neurastream labels update --repo <dir>` takes no `--since` (the same `labels.episode_days` window, and only `--repo`). `neurastream labels assign <episode> --party plan|implementer|both --why <text>` appends a party override. A flipped episode loses `labels.flip_weight` (default 1) of its accept points on the board and the gate; a plan-party flip also counts against MAIN.
137
+
138
+ `neurastream diff-check [--staged | <rev>]` is the removal check: an added comment line matching `labels.removal_comment_patterns` is flagged, and a commit whose subject matches `labels.removal_subjects` flags every added non-blank line. It prints `file:line: text` and exits 1 on hits; pure deletions pass, and a config regex that does not compile is skipped (fail-open, never refused). The plan-guard runs the same scan when a subagent's shell calls `git commit` on its staged diff and refuses the commit listing the flagged lines; Main is not gated.
139
+
136
140
  `agent-score accept` records accepted work by commit; `agent-score validate <Agent> --plan <plan.md> --phase <P> --evidence <report.md> --section "<heading prefix>"` records a validation phase (checks/tests ran, report section written, no commits) with proof Main cannot fake by typing: the plan line must be ticked `- [x]`, the cited section body must name a heavy-run label run by that agent (from `paths.heavy_log`), and the phase must not be scored already. The ranking board counts it in `Accepted (diag/val)` as `N (d/v)`.
137
141
 
138
142
  ## Main reads the code for its plans
@@ -359,6 +363,8 @@ Who is rate-limited comes from recorded live data, not from memory (I-20261025-1
359
363
 
360
364
  The owner's pick order is enforced, not prose: config `ledger.prefer` names agents in order (first = preferred, empty = off). While a higher pick's provider is free, the spawn gates refuse a lower pick unless the brief carries `Pick note: <why>`, and a brief that claims a provider the recorded state shows free is rate-limited is refused outright. `agent-score gate` ranks inside the order: with an earlier pick free it names that one (`gate: glm is first in prefer and free → use it`) instead of recommending a later paid agent by score; with `ledger.prefer` empty the old score-only verdicts stand.
361
365
 
366
+ The harness feeds that file too. At every main-start, and again when `agent-ledger --cap` runs, the adapter reads which providers it can use now. A whole block is recorded with source `harness` and is cleared only when that same source says the provider is ready again, so a quota-reset or a task result is never wiped by a start. main-start prints `harness providers: ready N: …` (blocked, partly blocked and unusable parts follow when there are any) and `provider changes since …:` when something moved since the last start. The last picture is `<paths.queue_state>/harness-providers.json`. If the harness store cannot be read, the line is `harness providers: unreadable — run neurastream doctor` and the snapshot is left alone. Nothing new is refused: a blocked provider is still only skipped when a guard would otherwise nudge toward it.
367
+
362
368
  ## Suspicious actions (`neurastream traces actions`)
363
369
 
364
370
  `neurastream traces actions <runId|--since 24h> [--json]` lists the suspicious tool actions a run's trace shows: reads of secret paths (`traces.actions.secret_globs`), network commands (`net_tools`) to unknown hosts, pipes into a shell (`shell_patterns`), and writes outside `write_roots` (empty = `paths.work_roots`; both empty = off) or on `deny_globs`. The high ones also open realtime suspicious-action incidents.
@@ -417,6 +423,12 @@ A rejected call never wrote usage, so a run can carry a 1.17M-token prompt with
417
423
  Config (defaults):
418
424
 
419
425
  ```yaml
426
+ labels:
427
+ episode_days: 30
428
+ flip_weight: 1.0
429
+ repos: []
430
+ removal_comment_patterns: ['\bremoved\b', '\bno longer\b', '\bpreviously\b', '\bused to\b', '\bwas deleted\b']
431
+ removal_subjects: ['^(remove|drop|delete)\b', '^chore: remove']
420
432
  traces:
421
433
  bloat:
422
434
  first_call_max: 150000
@@ -425,6 +437,7 @@ traces:
425
437
  tool_group: '^_?mcp__([A-Za-z0-9]+)_'
426
438
  ```
427
439
 
440
+
428
441
  ## Self-metrics
429
442
 
430
443
  `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:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.80",
3
+ "version": "0.2.82",
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": [
6
6
  "ai-agents",
@@ -5,6 +5,8 @@
5
5
 
6
6
  import type { DumpRef, LaunchOptions, RelatedTrace, RunSource, TaskResult, TraceRun, TraceSource } from "../core/adapter.ts";
7
7
  import type { Config } from "../core/config.ts";
8
+ import type { ProviderStatus } from "../core/provider-state.ts";
9
+ import type { Episode } from "../core/episodes.ts";
8
10
  import type { DumpParts, DumpTokens } from "../core/trace-bloat.ts";
9
11
  import type { SpawnBrief } from "../core/trace-briefs.ts";
10
12
  import { ompAdapter } from "./omp/adapter.ts";
@@ -22,6 +24,8 @@ export interface HarnessAdapter {
22
24
  /** Every run id with a trace under the root, each mapped to its newest file. */
23
25
  traceRuns(root: string): TraceRun[];
24
26
  traceSource(root: string): TraceSource;
27
+ /** Episodes (P1) since the cutoff, for `labels` commands and the main-start daily labels update. */
28
+ episodes(cfg: Config, cutoff: number): Episode[];
25
29
  /** Read only the session banner at the start of a trace; null means it is unreadable. */
26
30
  traceStart(file: string): number | null;
27
31
  /** Every failed-request dump under the harness log dir, oldest first. */
@@ -41,6 +45,8 @@ export interface HarnessAdapter {
41
45
  install(args: string[]): number;
42
46
  /** `neurastream doctor`. */
43
47
  doctor(): number;
48
+ /** Providers the harness knows and their state now; null = its store could not be read (doctor names why); [] = the harness has no such data. */
49
+ providers(cfg: Config): ProviderStatus[] | null;
44
50
  }
45
51
 
46
52
  const ADAPTERS: Record<string, HarnessAdapter> = {
@@ -3,10 +3,11 @@
3
3
 
4
4
  import type { HarnessAdapter } from "../index.ts";
5
5
  import { runDoctor } from "./doctor.ts";
6
+ import { ompProviders } from "./providers.ts";
6
7
  import { runAdapterInstall } from "./install.ts";
7
8
  import { runMainLauncher } from "./launch.ts";
8
9
  import { defaultCompletedResults, defaultRunSource } from "./sessions.ts";
9
- import { dumpModel, dumpParts, dumpPromptTokens, ompDumps, ompScoreTraces, ompTraceRuns, ompTraceSource, ompTraceStart, spawnBriefsIn, subagentTraces } from "./traces.ts";
10
+ import { dumpModel, dumpParts, dumpPromptTokens, ompDumps, ompEpisodes, ompScoreTraces, ompTraceRuns, ompTraceSource, ompTraceStart, spawnBriefsIn, subagentTraces } from "./traces.ts";
10
11
 
11
12
  export const ompAdapter: HarnessAdapter = {
12
13
  name: "omp",
@@ -16,6 +17,7 @@ export const ompAdapter: HarnessAdapter = {
16
17
  scoreTraces: ompScoreTraces,
17
18
  traceRuns: ompTraceRuns,
18
19
  traceSource: ompTraceSource,
20
+ episodes: ompEpisodes,
19
21
  traceStart: ompTraceStart,
20
22
  dumps: ompDumps,
21
23
  dumpModel,
@@ -26,4 +28,5 @@ export const ompAdapter: HarnessAdapter = {
26
28
  launchMain: runMainLauncher,
27
29
  install: runAdapterInstall,
28
30
  doctor: runDoctor,
31
+ providers: ompProviders,
29
32
  };
@@ -18,6 +18,7 @@ import { systemRunner, type Runner } from "../../core/pages-setup.ts";
18
18
  import { packageJsonPath } from "./package-root.ts";
19
19
  import { realTailscale, type Tailscale } from "../../core/tailscale.ts";
20
20
  import { wipHealth } from "../../core/wip-setup.ts";
21
+ import { readOmpProviders } from "./providers.ts";
21
22
 
22
23
  const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
23
24
 
@@ -210,6 +211,20 @@ export function doctorReport(home: string, env: NodeJS.ProcessEnv = process.env,
210
211
  const agents = liveAgentsMd(home);
211
212
  const text = existsSync(agents) ? readFileSync(agents, "utf8") : "";
212
213
  const cfg = loadConfig({ home, env });
214
+ const agentDb = join(home, ".omp/agent/agent.db");
215
+ // A home with no omp login store is not a broken store: doctor stays ok (a fresh install has
216
+ // none). A present file that cannot be read is the schema-drift failure the line exists for.
217
+ if (!existsSync(agentDb)) {
218
+ ok.push("providers: 0 read from ~/.omp/agent/agent.db");
219
+ } else {
220
+ try {
221
+ const n = readOmpProviders(home, Date.now()).length;
222
+ ok.push(`providers: ${n} read from ~/.omp/agent/agent.db`);
223
+ } catch (err) {
224
+ const message = err instanceof Error ? err.message : String(err);
225
+ problems.push(`providers: cannot read ${agentDb}: ${message} — main-start prints "harness providers: unreadable"`);
226
+ }
227
+ }
213
228
  // P6 (plan 20261031_0917): a pages server started before the installed package changed keeps old
214
229
  // code — the owner's tap hit the pre-0.2.57 handler and the approval was lost (2026-10-31 09:34).
215
230
  if (cfg.pages.enabled) {
@@ -44,6 +44,7 @@ import { mainDetectors, mainStartText } from "../../core/main-start.ts";
44
44
 
45
45
  import { buildHandoff, holdsBlock, notePath, noteRequest, OWNER_AWAY, ownerText, relaunchPath, rolloverState, spawnRefusal, unansweredOwnerMessages, type RolloverState } from "../../core/rollover.ts";
46
46
  import { defaultCompletedResults, defaultRunSource, runIdOf } from "./sessions.ts";
47
+ import { ompProviders } from "./providers.ts";
47
48
  import { adapterLog, MAIN_ENV } from "./launch.ts";
48
49
  import { parseTraceFile } from "./traces.ts";
49
50
  import { packageJsonPath, packageVersion } from "./package-root.ts";
@@ -1381,7 +1382,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1381
1382
  try {
1382
1383
  c.notify(notice);
1383
1384
  const generated = [
1384
- await mainStartText([], cfg, { inheritStdin: false }, { source: defaultRunSource(cfg), results: defaultCompletedResults(cfg) }),
1385
+ await mainStartText([], cfg, { inheritStdin: false }, { source: defaultRunSource(cfg), results: defaultCompletedResults(cfg), providers: ompProviders(cfg) }),
1385
1386
  holdsBlock(q.ownerHolds()),
1386
1387
  ].join("\n");
1387
1388
  const note = readFileSync(path, "utf8");
@@ -19,6 +19,8 @@ import { buildHandoff, holdsBlock, MAX_NOTE_AGE_MS, OWNER_AWAY, relaunchPath, un
19
19
  import { PROXY_BIN, proxyOnPath } from "../../core/secret-redact.ts";
20
20
  import { PACKAGE_ROOT, packageJsonPath, packageVersion } from "./package-root.ts";
21
21
  import { defaultCompletedResults, defaultRunSource } from "./sessions.ts";
22
+ import { ompProviders } from "./providers.ts";
23
+ import { ompEpisodes } from "./traces.ts";
22
24
 
23
25
  /** One line in the guard log: the adapter's own trace of what it did (relaunches, detectors). */
24
26
  export function adapterLog(cfg: Config, line: string): void {
@@ -346,7 +348,7 @@ async function nextMessage(req: RelaunchRequest, cfg: Config, mainStart: typeof
346
348
  let generated: string;
347
349
  try {
348
350
  generated = [
349
- await mainStart([], cfg, { inheritStdin: false }, { source: defaultRunSource(cfg), results: defaultCompletedResults(cfg) }),
351
+ await mainStart([], cfg, { inheritStdin: false }, { source: defaultRunSource(cfg), results: defaultCompletedResults(cfg), providers: ompProviders(cfg), episodesFor: cutoff => ompEpisodes(cfg, cutoff) }),
350
352
  holdsBlock(q.ownerHolds()),
351
353
  ].join("\n");
352
354
  } catch (err) {
@@ -0,0 +1,217 @@
1
+ // omp's own picture of which providers it can use (plan 20261103_0955 P2). Sessions and traces
2
+ // live in session files; this reader is the only one that opens agent.db, and only to read.
3
+ // A schema change throws, and the caller turns that into null — never a guess that every
4
+ // provider is gone.
5
+
6
+ import { Database } from "bun:sqlite";
7
+ import { readFileSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import type { Config } from "../../core/config.ts";
10
+ import type { ProviderStatus } from "../../core/provider-state.ts";
11
+
12
+ const DISABLED_REASON = "disabledProviders in config.yml";
13
+
14
+ interface Cred {
15
+ id: number;
16
+ provider: string;
17
+ disabled_cause: string | null;
18
+ updated_at: number;
19
+ }
20
+
21
+ interface Block {
22
+ credential_id: number;
23
+ block_scope: string;
24
+ blocked_until_ms: number;
25
+ }
26
+
27
+ function requireNumber(value: unknown, field: string): number {
28
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new Error(`auth field ${field} has an unexpected type`);
29
+ return value;
30
+ }
31
+
32
+ function requireString(value: unknown, field: string): string {
33
+ if (typeof value !== "string") throw new Error(`auth field ${field} has an unexpected type`);
34
+ return value;
35
+ }
36
+
37
+ function isPartialScope(scope: string): boolean {
38
+ return scope === "spark" || scope.startsWith("tier:") || scope.startsWith("pool:") || scope.startsWith("counter:");
39
+ }
40
+
41
+ function shortCause(cause: string): string {
42
+ const head = (cause.split(":")[0] ?? "").trim();
43
+ return head.length <= 40 ? head : head.slice(0, 40);
44
+ }
45
+
46
+ function readCreds(db: Database): Cred[] {
47
+ const rows = db.query("SELECT id, provider, disabled_cause, updated_at FROM auth_credentials").all();
48
+ const out: Cred[] = [];
49
+ for (const row of rows) {
50
+ if (row === null || typeof row !== "object") throw new Error("auth_credentials: row is not an object");
51
+ const record = row as Record<string, unknown>;
52
+ const provider = requireString(record.provider, "provider");
53
+ if (provider.startsWith("mcp_oauth:")) continue;
54
+ if (record.disabled_cause !== null && typeof record.disabled_cause !== "string") {
55
+ throw new Error("auth field disabled_cause has an unexpected type");
56
+ }
57
+ out.push({
58
+ id: requireNumber(record.id, "id"),
59
+ provider,
60
+ disabled_cause: record.disabled_cause,
61
+ updated_at: requireNumber(record.updated_at, "updated_at"),
62
+ });
63
+ }
64
+ return out;
65
+ }
66
+
67
+ function readBlocks(db: Database, nowMs: number): Block[] {
68
+ const rows = db.query("SELECT credential_id, block_scope, blocked_until_ms FROM auth_credential_blocks WHERE blocked_until_ms > ?").all(nowMs);
69
+ const out: Block[] = [];
70
+ for (const row of rows) {
71
+ if (row === null || typeof row !== "object") throw new Error("auth_credential_blocks: row is not an object");
72
+ const record = row as Record<string, unknown>;
73
+ out.push({
74
+ credential_id: requireNumber(record.credential_id, "credential_id"),
75
+ block_scope: requireString(record.block_scope, "block_scope"),
76
+ blocked_until_ms: requireNumber(record.blocked_until_ms, "blocked_until_ms"),
77
+ });
78
+ }
79
+ return out;
80
+ }
81
+
82
+ function blocksFor(blocks: Block[], id: number): Block[] {
83
+ const out: Block[] = [];
84
+ for (const block of blocks) if (block.credential_id === id) out.push(block);
85
+ return out;
86
+ }
87
+
88
+ function latestEnd(blocks: Block[], want: (scope: string) => boolean): number | null {
89
+ let latest: number | null = null;
90
+ for (const block of blocks) {
91
+ if (!want(block.block_scope)) continue;
92
+ if (latest === null || block.blocked_until_ms > latest) latest = block.blocked_until_ms;
93
+ }
94
+ return latest;
95
+ }
96
+
97
+ function statusFor(provider: string, creds: Cred[], blocks: Block[]): ProviderStatus {
98
+ const active = creds.filter(cred => cred.disabled_cause === null);
99
+ if (active.length === 0) {
100
+ let newest = creds[0];
101
+ if (newest === undefined) throw new Error(`auth_credentials: ${provider} has no rows`);
102
+ for (const cred of creds) {
103
+ if (cred.updated_at > newest.updated_at || (cred.updated_at === newest.updated_at && cred.id > newest.id)) newest = cred;
104
+ }
105
+ if (newest.disabled_cause === null) throw new Error(`auth_credentials: ${provider} has no usable cause`);
106
+ return { provider, unusable: shortCause(newest.disabled_cause), blockedUntil: null, partial: [] };
107
+ }
108
+ let wholeMin: number | null = null;
109
+ for (const cred of active) {
110
+ const end = latestEnd(blocksFor(blocks, cred.id), scope => !isPartialScope(scope));
111
+ if (end === null) {
112
+ wholeMin = null;
113
+ break;
114
+ }
115
+ wholeMin = wholeMin === null ? end : Math.min(wholeMin, end);
116
+ }
117
+ const blockedUntil = wholeMin === null ? null : Math.floor(wholeMin / 1000);
118
+ const partial: { scope: string; until: number }[] = [];
119
+ if (blockedUntil === null) {
120
+ const scopes = new Set<string>();
121
+ for (const cred of active) {
122
+ for (const block of blocksFor(blocks, cred.id)) if (isPartialScope(block.block_scope)) scopes.add(block.block_scope);
123
+ }
124
+ for (const scope of [...scopes].toSorted()) {
125
+ let min: number | null = null;
126
+ let every = true;
127
+ for (const cred of active) {
128
+ const end = latestEnd(blocksFor(blocks, cred.id), candidate => candidate === scope);
129
+ if (end === null) {
130
+ every = false;
131
+ break;
132
+ }
133
+ min = min === null ? end : Math.min(min, end);
134
+ }
135
+ if (every && min !== null) partial.push({ scope, until: Math.floor(min / 1000) });
136
+ }
137
+ }
138
+ return { provider, unusable: null, blockedUntil, partial };
139
+ }
140
+
141
+ function readYaml(path: string): unknown {
142
+ let text: string;
143
+ try {
144
+ text = readFileSync(path, "utf8");
145
+ } catch (err) {
146
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return undefined;
147
+ throw err;
148
+ }
149
+ return Bun.YAML.parse(text);
150
+ }
151
+
152
+ function mapping(value: unknown, where: string): Record<string, unknown> | null {
153
+ if (value === undefined || value === null) return null;
154
+ if (typeof value !== "object" || Array.isArray(value)) throw new Error(`${where}: expected a mapping`);
155
+ return value as Record<string, unknown>;
156
+ }
157
+
158
+ function modelProviderNames(home: string): string[] {
159
+ const parsed = mapping(readYaml(join(home, ".omp/agent/models.yml")), "models.yml");
160
+ if (parsed === null) return [];
161
+ const providers = parsed.providers;
162
+ if (providers === undefined || providers === null) return [];
163
+ const map = mapping(providers, "models.yml providers");
164
+ return map === null ? [] : Object.keys(map);
165
+ }
166
+
167
+ function disabledProviderNames(home: string): string[] {
168
+ const parsed = mapping(readYaml(join(home, ".omp/agent/config.yml")), "config.yml");
169
+ if (parsed === null) return [];
170
+ const list = parsed.disabledProviders;
171
+ if (list === undefined || list === null) return [];
172
+ if (!Array.isArray(list)) throw new Error("disabledProviders: expected a list");
173
+ return list.map(item => {
174
+ if (typeof item !== "string") throw new Error("disabledProviders: expected strings");
175
+ return item;
176
+ });
177
+ }
178
+
179
+ /** Throws on any read or schema error. The secret column is never selected. */
180
+ export function readOmpProviders(home: string, nowMs: number): ProviderStatus[] {
181
+ const db = new Database(join(home, ".omp/agent/agent.db"), { readonly: true });
182
+ try {
183
+ const creds = readCreds(db);
184
+ const blocks = readBlocks(db, nowMs);
185
+ const byProvider = new Map<string, Cred[]>();
186
+ for (const cred of creds) {
187
+ const group = byProvider.get(cred.provider) ?? [];
188
+ group.push(cred);
189
+ byProvider.set(cred.provider, group);
190
+ }
191
+ const list: ProviderStatus[] = [];
192
+ for (const [provider, group] of byProvider) list.push(statusFor(provider, group, blocks));
193
+ for (const name of modelProviderNames(home)) {
194
+ if (!list.some(status => status.provider === name)) {
195
+ list.push({ provider: name, unusable: null, blockedUntil: null, partial: [] });
196
+ }
197
+ }
198
+ for (const name of disabledProviderNames(home)) {
199
+ const row: ProviderStatus = { provider: name, unusable: DISABLED_REASON, blockedUntil: null, partial: [] };
200
+ const at = list.findIndex(status => status.provider === name);
201
+ if (at >= 0) list[at] = row;
202
+ else list.push(row);
203
+ }
204
+ return list.toSorted((a, b) => (a.provider < b.provider ? -1 : a.provider > b.provider ? 1 : 0));
205
+ } finally {
206
+ db.close();
207
+ }
208
+ }
209
+
210
+ /** null when the store cannot be read; doctor names the error. */
211
+ export function ompProviders(cfg: Config, nowMs = Date.now()): ProviderStatus[] | null {
212
+ try {
213
+ return readOmpProviders(cfg.paths.home, nowMs);
214
+ } catch {
215
+ return null;
216
+ }
217
+ }
@@ -11,7 +11,9 @@ import type { Config } from "../../core/config.ts";
11
11
  import type { DumpRef, RelatedTrace, TraceEvent, TraceRun, TraceSource, TraceUsage } from "../../core/adapter.ts";
12
12
  import type { DumpParts, DumpTokens } from "../../core/trace-bloat.ts";
13
13
  import type { SpawnBrief } from "../../core/trace-briefs.ts";
14
- import { asObj, jsonlAt, parseTs, runIdOf } from "./sessions.ts";
14
+ import { asObj, jsonlAt, parseTs, runIdOf, defaultRunSource } from "./sessions.ts";
15
+ import { readEvents } from "../../core/agent-score.ts";
16
+ import { buildEpisodes, type Episode } from "../../core/episodes.ts";
15
17
 
16
18
  function str(v: unknown): string | undefined {
17
19
  return typeof v === "string" && v !== "" ? v : undefined;
@@ -372,3 +374,12 @@ export function spawnBriefsIn(file: string, runId: string): SpawnBrief[] {
372
374
  }
373
375
  return out;
374
376
  }
377
+
378
+ /** Episodes (P1) over the config's sessions root: the runs, their score events and spawn briefs since the cutoff — the builder `labels episodes/import/update/export` and the main-start daily update share. */
379
+ export function ompEpisodes(cfg: Config, cutoff: number): Episode[] {
380
+ const root = cfg.adapter?.sessions || join(cfg.paths.home, ".omp", "agent", "sessions");
381
+ const briefs = ompTraceRuns(root)
382
+ .filter(run => run.mtimeSec >= cutoff)
383
+ .flatMap(run => spawnBriefsIn(run.file, run.runId));
384
+ return buildEpisodes(defaultRunSource(cfg), readEvents(cfg), briefs, cutoff);
385
+ }
@@ -14,6 +14,7 @@ import { queueTrim } from "../core/queue-trim.ts";
14
14
  import { queueClose } from "../core/queue-close.ts";
15
15
  import { queueFinished } from "../core/queue-finished.ts";
16
16
  import { resourceAlerts } from "../core/resource-alerts.ts";
17
+ import { syncHarnessOut } from "../core/provider-state.ts";
17
18
  import { tmpSnapshot } from "../core/tmp-snapshot.ts";
18
19
  import { wipBackup } from "../core/wip-backup.ts";
19
20
  import { wipCheck } from "../core/wip-check.ts";
@@ -58,6 +59,7 @@ export async function runPorted(cmd: string, args: string[]): Promise<number> {
58
59
  case "agent-score":
59
60
  return agentScore(args, rt.cfg, rt.source, getAdapter(rt.cfg).scoreTraces(rt.cfg));
60
61
  case "agent-ledger":
62
+ if (args.includes("--cap")) syncHarnessOut(rt.cfg, getAdapter(rt.cfg).providers(rt.cfg));
61
63
  return agentLedger(args, rt.cfg, rt.source);
62
64
  case "brief-lint":
63
65
  return briefLint(args, rt.cfg);
@@ -85,7 +87,7 @@ export async function runPorted(cmd: string, args: string[]): Promise<number> {
85
87
  return claimCli(args, rt.cfg);
86
88
  case "main-start": {
87
89
  const a = getAdapter(rt.cfg);
88
- return mainStart(args, rt.cfg, { source: a.runSource(rt.cfg), results: a.completedResults(rt.cfg) });
90
+ return mainStart(args, rt.cfg, { source: a.runSource(rt.cfg), results: a.completedResults(rt.cfg), providers: a.providers(rt.cfg), episodesFor: cutoff => a.episodes(rt.cfg, cutoff) });
89
91
  }
90
92
  case "machine-guard":
91
93
  return machineGuard(args, rt.cfg);
@@ -0,0 +1,30 @@
1
+ // `neurastream diff-check [--staged | <rev>]` (P6, plan 20261024_1915): the removal check
2
+ // (src/core/diff-check.ts) as a CLI. --staged scans the staged diff (no commit, so no subject
3
+ // match); <rev> scans that commit's patch with its subject applied. Prints flagged
4
+ // `file:line: text` lines, exit 1 on hits, 0 clean, 2 on usage.
5
+
6
+ import { ConfigError, loadConfig } from "../core/config.ts";
7
+ import { commitDiff, removalFlags, stagedDiff } from "../core/diff-check.ts";
8
+
9
+ const USAGE = "usage: neurastream diff-check [--staged | <rev>] flag added removal comments (labels.removal_*); exit 1 on hits";
10
+
11
+ export function runDiffCheck(args: string[]): number {
12
+ const rev = args.length === 1 && args[0] !== "--staged" && !args[0]!.startsWith("-") ? args[0]! : null;
13
+ if (args.length !== 1 || (rev === null && args[0] !== "--staged")) {
14
+ console.error(USAGE);
15
+ return 2;
16
+ }
17
+ try {
18
+ const cfg = loadConfig();
19
+ const { diff, subject } = rev === null
20
+ ? { diff: stagedDiff(process.cwd()), subject: "" }
21
+ : commitDiff(process.cwd(), rev);
22
+ const flags = removalFlags(diff, subject, cfg);
23
+ for (const f of flags) console.log(`${f.file}:${f.line}: ${f.text}`);
24
+ return flags.length > 0 ? 1 : 0;
25
+ } catch (err) {
26
+ // A git failure (no repo, bad rev) must never read as clean: report and exit 1.
27
+ console.error(err instanceof ConfigError ? err.message : String(err));
28
+ return 1;
29
+ }
30
+ }
@@ -32,6 +32,8 @@ import { queueMigrate } from "../core/queue-migrate.ts";
32
32
  import { activePlans, allowedAgents, enforceReadOnlyIndex, gitTop, indexPath, readIndex, subagentsPath, writeIndex } from "../core/queue/lib.ts";
33
33
  import { defaultRunner } from "../core/mr-sweep.ts";
34
34
  import { allowAgents, denyAgents, invalidSlugs } from "../core/subagents.ts";
35
+ import { runLabels } from "./labels.ts";
36
+ import { runDiffCheck } from "./diff-check.ts";
35
37
 
36
38
  const BINS = [
37
39
  "agent-score",
@@ -99,6 +101,19 @@ export function helpText(): string {
99
101
  " neurastream main [args] run omp under the launcher (automatic session rollover)",
100
102
  " neurastream metrics <cmd> self-metrics: report, features, releases, ci, false-alarm, rule (see README)",
101
103
  " neurastream incident <cmd> incidents Main must act on: list, add, plan, dismiss (see README)",
104
+ " neurastream labels episodes [--since 30d] [--json]",
105
+ " join scored work, agent runs and spawn briefs",
106
+ " neurastream labels update --repo <dir>",
107
+ " label the episodes since the ledger's watermark (P2+P3),",
108
+ " flip good work a later commit turned bad; idempotent",
109
+ " neurastream labels export --good [--min-age-days 14] [--json]",
110
+ " good, old enough, never-flipped episodes with wasted",
111
+ " trace step indexes",
112
+ " neurastream labels assign <episode> --party plan|implementer|both --why <text>",
113
+ " append a party override; the last ledger line wins",
114
+ " neurastream diff-check [--staged | <rev>]",
115
+ " the removal check (labels.removal_*): prints flagged",
116
+ " file:line: text, exit 1 on hits",
102
117
  " neurastream traces claims <runId|--since 24h> [--json]",
103
118
  " check a run's final-report claims (test counts, exit codes,",
104
119
  " SHAs, heavy-run labels, changed paths) against the run's own",
@@ -142,6 +157,8 @@ export async function run(cmd: string, args: string[]): Promise<number> {
142
157
  if (cmd === "metrics") return runMetrics(args);
143
158
  if (cmd === "incident") return runIncident(args);
144
159
  if (cmd === "traces") return runTraces(args);
160
+ if (cmd === "labels") return runLabels(args);
161
+ if (cmd === "diff-check") return runDiffCheck(args);
145
162
  if (cmd === "ui") return runUi(args);
146
163
  if (cmd === "pages") return runPages(args);
147
164
  if (cmd === "notes") return runNotes(args);
@@ -0,0 +1,110 @@
1
+ import { readEvents } from "../core/agent-score.ts";
2
+ import { getAdapter } from "../adapters/index.ts";
3
+ import { ConfigError, loadConfig, type Config } from "../core/config.ts";
4
+ import { nowSec } from "../core/clock.ts";
5
+ import { goodSet, updateLabels } from "../core/label-update.ts";
6
+ import { importWhytrailLabels } from "../core/label-import.ts";
7
+ import { assignLabel } from "../core/labels.ts";
8
+
9
+ const USAGE = "usage: neurastream labels episodes [--since 30d] [--json]\n neurastream labels import --repo <dir> [--since 30d] [--json]\n neurastream labels update --repo <dir>\n neurastream labels export --good [--min-age-days 14] [--json]\n neurastream labels assign <episode> --party plan|implementer|both --why <text>";
10
+ const SINCE = /^(\d+)([dhm])$/;
11
+
12
+ export function runLabels(args: string[], opts: { home?: string } = {}): number {
13
+ if (args[0] !== "episodes" && args[0] !== "import" && args[0] !== "assign" && args[0] !== "update" && args[0] !== "export") {
14
+ console.error(USAGE);
15
+ return 2;
16
+ }
17
+ try {
18
+ const cfg = loadConfig(opts.home === undefined ? undefined : { home: opts.home });
19
+ if (args[0] === "assign") return runAssign(args.slice(1), cfg);
20
+ if (args[0] === "update") return runUpdate(args.slice(1), cfg);
21
+ if (args[0] === "export") return runExport(args.slice(1), cfg);
22
+ let windowSec = cfg.labels.episode_days * 86400;
23
+ let json = false;
24
+ let repo: string | undefined;
25
+ for (let i = 1; i < args.length; i++) {
26
+ const arg = args[i]!;
27
+ if (arg === "--json") json = true;
28
+ else if (arg === "--repo" && args[0] === "import") repo = args[++i];
29
+ else if (arg === "--since") {
30
+ const match = SINCE.exec(args[++i] ?? "");
31
+ if (!match) { console.error(USAGE); return 2; }
32
+ windowSec = Number(match[1]) * (match[2] === "d" ? 86400 : match[2] === "h" ? 3600 : 60);
33
+ } else { console.error(USAGE); return 2; }
34
+ }
35
+ const ts = nowSec();
36
+ const cutoff = ts - windowSec;
37
+ if (args[0] === "import") {
38
+ if (repo === undefined) { console.error(USAGE); return 2; }
39
+ const appended = importWhytrailLabels(repo, cfg.paths.score_state, getAdapter(cfg).episodes(cfg, cutoff), ts);
40
+ if (json) console.log(JSON.stringify(appended, null, 2));
41
+ else console.log(`imported ${appended.length} label line(s) from whytrail`);
42
+ return 0;
43
+ }
44
+ const episodes = getAdapter(cfg).episodes(cfg, cutoff);
45
+ if (json) console.log(JSON.stringify(episodes, null, 2));
46
+ else if (episodes.length === 0) console.log("no episodes in the window");
47
+ else for (const episode of episodes) console.log(`${episode.id} ${episode.agent} ${episode.model} ${episode.plan} ${episode.phase} ${episode.commits.join(",")}`);
48
+ return 0;
49
+ } catch (error) {
50
+ console.error(error instanceof ConfigError ? error.message : String(error));
51
+ return 1;
52
+ }
53
+ }
54
+
55
+ function runUpdate(args: string[], cfg: Config): number {
56
+ let repo: string | undefined;
57
+ for (let i = 0; i < args.length; i++) {
58
+ if (args[i] === "--repo") repo = args[++i];
59
+ else { console.error(USAGE); return 2; }
60
+ }
61
+ if (repo === undefined) { console.error(USAGE); return 2; }
62
+ const a = getAdapter(cfg);
63
+ const result = updateLabels(cfg, repo, {
64
+ episodesFor: cutoff => a.episodes(cfg, cutoff),
65
+ events: readEvents(cfg),
66
+ runs: a.runSource(cfg).listRuns(nowSec() - cfg.labels.episode_days * 86400),
67
+ }, nowSec());
68
+ console.log(`labels update ${repo}: ${result.labels.length} label(s), ${result.imported.length} imported, ${result.flips.length} flip(s)`);
69
+ if (result.importError) console.error(`labels update: whytrail import skipped: ${result.importError}`);
70
+ for (const f of result.flips) console.log(`flipped ${f.episode} (party ${f.party}, fix ${f.fixSha})`);
71
+ return 0;
72
+ }
73
+
74
+ function runExport(args: string[], cfg: Config): number {
75
+ let good = false;
76
+ let json = false;
77
+ let minAge = 14;
78
+ for (let i = 0; i < args.length; i++) {
79
+ const arg = args[i]!;
80
+ if (arg === "--good") good = true;
81
+ else if (arg === "--json") json = true;
82
+ else if (arg === "--min-age-days") minAge = Number(args[++i]);
83
+ else { console.error(USAGE); return 2; }
84
+ }
85
+ if (!good || !Number.isFinite(minAge) || minAge < 0) { console.error(USAGE); return 2; }
86
+ const a = getAdapter(cfg);
87
+ const episodes = a.episodes(cfg, nowSec() - cfg.labels.episode_days * 86400);
88
+ const rows = goodSet(cfg, episodes, a.scoreTraces(cfg), nowSec(), minAge);
89
+ if (json) console.log(JSON.stringify(rows, null, 2));
90
+ else if (rows.length === 0) console.log("no good episodes past the min age");
91
+ else for (const r of rows) console.log(`${r.runId} ${r.briefRef ?? "-"} ${r.commits.join(",") || "-"} wasted=[${r.wasted.join(",")}]`);
92
+ return 0;
93
+ }
94
+
95
+ function runAssign(args: string[], cfg: Config): number {
96
+ const episode = args[0];
97
+ if (!episode || episode.startsWith("-")) { console.error(USAGE); return 2; }
98
+ let party: string | undefined;
99
+ let why: string | undefined;
100
+ for (let i = 1; i < args.length; i++) {
101
+ const arg = args[i]!;
102
+ if (arg === "--party") party = args[++i];
103
+ else if (arg === "--why") why = args[++i];
104
+ else { console.error(USAGE); return 2; }
105
+ }
106
+ if ((party !== "plan" && party !== "implementer" && party !== "both") || !why) { console.error(USAGE); return 2; }
107
+ const line = assignLabel(cfg.paths.score_state, episode, party, why, nowSec());
108
+ console.log(`${line.episode} ${line.label} ${line.party}`);
109
+ return 0;
110
+ }