neurastream 0.2.30 → 0.2.32

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.30",
3
+ "version": "0.2.32",
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",
@@ -0,0 +1,55 @@
1
+ // The one door from src/cli to a harness (plan 20261026_0010 P2). Every adapter import in the
2
+ // CLI goes through this file, and tests/host-neutral.test.ts holds that line. Adding a harness
3
+ // is one folder under src/adapters plus one entry in ADAPTERS below — zero core changes
4
+ // (docs/adapter.md, "Adding a harness").
5
+
6
+ import type { DumpRef, LaunchOptions, RelatedTrace, RunSource, TaskResult, TraceRun, TraceSource } from "../core/adapter.ts";
7
+ import type { Config } from "../core/config.ts";
8
+ import type { DumpParts, DumpTokens } from "../core/trace-bloat.ts";
9
+ import type { SpawnBrief } from "../core/trace-briefs.ts";
10
+ import { ompAdapter } from "./omp/adapter.ts";
11
+
12
+ export interface HarnessAdapter {
13
+ name: string;
14
+ /** Session reader: the runs and the main session (docs/adapter.md). */
15
+ runSource(cfg: Config): RunSource;
16
+ /** Completed subagent task-results announced in the newest main session file. */
17
+ completedResults(cfg: Config): TaskResult[];
18
+ /** TraceSource for agent-score, over the config's sessions root. */
19
+ scoreTraces(cfg: Config): TraceSource;
20
+ /** Every run id with a trace under the root, each mapped to its newest file. */
21
+ traceRuns(root: string): TraceRun[];
22
+ traceSource(root: string): TraceSource;
23
+ /** Read only the session banner at the start of a trace; null means it is unreadable. */
24
+ traceStart(file: string): number | null;
25
+ /** Every failed-request dump under the harness log dir, oldest first. */
26
+ dumps(home: string): DumpRef[];
27
+ /** Model requested by a failed request dump, if the JSON contains one. */
28
+ dumpModel(file: string): string | undefined;
29
+ /** What a dumped request's prompt is made of (src/core/trace-bloat.ts). */
30
+ dumpParts(file: string): DumpParts;
31
+ /** The prompt tokens a dump states itself, when it does. */
32
+ dumpPromptTokens(file: string): DumpTokens | null;
33
+ /** The spawn briefs in one session file. */
34
+ spawnBriefsIn(file: string, runId: string): SpawnBrief[];
35
+ /** The subagent runs of one main run. */
36
+ subagentTraces(root: string, mainRunId: string): RelatedTrace[];
37
+ launchMain(args: string[], cfg: Config, opts?: LaunchOptions): Promise<number>;
38
+ /** `neurastream adapter install <name>` — validates its own args. */
39
+ install(args: string[]): number;
40
+ /** `neurastream doctor`. */
41
+ doctor(): number;
42
+ }
43
+
44
+ const ADAPTERS: Record<string, HarnessAdapter> = {
45
+ [ompAdapter.name]: ompAdapter,
46
+ };
47
+
48
+ /** The adapter the config names (`harness:`; without a config, the shipped default). An unknown
49
+ * name throws, so a typo fails loudly instead of silently reading another harness's files. */
50
+ export function getAdapter(cfg?: Pick<Config, "harness">): HarnessAdapter {
51
+ const name = cfg?.harness ?? "omp";
52
+ const adapter = ADAPTERS[name];
53
+ if (!adapter) throw new Error(`unknown harness "${name}"; known: ${Object.keys(ADAPTERS).join(", ")}`);
54
+ return adapter;
55
+ }
@@ -0,0 +1,28 @@
1
+ // The shipped adapter's HarnessAdapter implementation: thin wiring over this folder's readers,
2
+ // launcher, installer and doctor. Only src/adapters may name the harness.
3
+
4
+ import type { HarnessAdapter } from "../index.ts";
5
+ import { runDoctor } from "./doctor.ts";
6
+ import { runAdapterInstall } from "./install.ts";
7
+ import { runMainLauncher } from "./launch.ts";
8
+ import { defaultCompletedResults, defaultRunSource } from "./sessions.ts";
9
+ import { dumpModel, dumpParts, dumpPromptTokens, ompDumps, ompScoreTraces, ompTraceRuns, ompTraceSource, ompTraceStart, spawnBriefsIn, subagentTraces } from "./traces.ts";
10
+
11
+ export const ompAdapter: HarnessAdapter = {
12
+ name: "omp",
13
+ runSource: defaultRunSource,
14
+ completedResults: defaultCompletedResults,
15
+ scoreTraces: ompScoreTraces,
16
+ traceRuns: ompTraceRuns,
17
+ traceSource: ompTraceSource,
18
+ traceStart: ompTraceStart,
19
+ dumps: ompDumps,
20
+ dumpModel,
21
+ dumpParts,
22
+ dumpPromptTokens,
23
+ spawnBriefsIn,
24
+ subagentTraces,
25
+ launchMain: runMainLauncher,
26
+ install: runAdapterInstall,
27
+ doctor: runDoctor,
28
+ };
@@ -35,6 +35,7 @@ import { mainStartText, runDailyCheck } from "../../core/main-start.ts";
35
35
  import { readBlocks } from "../../core/metrics.ts";
36
36
  import { buildHandoff, holdsBlock, notePath, noteRequest, OWNER_AWAY, ownerText, relaunchPath, rolloverState, spawnRefusal, type RolloverState } from "../../core/rollover.ts";
37
37
  import { defaultCompletedResults, defaultRunSource, runIdOf } from "./sessions.ts";
38
+ import { adapterLog } from "./launch.ts";
38
39
  import { parseTraceFile } from "./traces.ts";
39
40
  import { packageJsonPath, packageVersion } from "./package-root.ts";
40
41
  import * as q from "../../core/queue/lib.ts";
@@ -130,11 +131,7 @@ const PUSH_MERGE = /\bgit\b[^\n;|&]*\bpush\b|\b(glab\s+mr|gh\s+pr)\s+merge\b/;
130
131
 
131
132
  // The installed package and its version: see ./package-root.ts.
132
133
 
133
- export function adapterLog(cfg: Config, line: string): void {
134
- try {
135
- appendFileSync(cfg.paths.guard_log, `${new Date().toISOString()} ${line}\n`);
136
- } catch {}
137
- }
134
+ export { adapterLog };
138
135
 
139
136
  /**
140
137
  * Real-time incident detectors (plan 20261022_2330 P3) at Main's prompt and after each Main bash
@@ -4,18 +4,25 @@
4
4
  // flags (carriedArgs) and the handoff as its message. Plain `omp` never gets the flag, so it never relaunches.
5
5
 
6
6
  import { spawn } from "node:child_process";
7
- import { mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
7
+ import { appendFileSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
8
8
  import { basename, dirname, join } from "node:path";
9
+ import type { LaunchOptions } from "../../core/adapter.ts";
9
10
  import type { Config } from "../../core/config.ts";
10
11
  import { mainStartText } from "../../core/main-start.ts";
11
12
  import { applyQueueEnv } from "../../core/queue/env.ts";
12
13
  import * as q from "../../core/queue/lib.ts";
13
14
  import { buildHandoff, holdsBlock, MAX_NOTE_AGE_MS, OWNER_AWAY, relaunchPath } from "../../core/rollover.ts";
14
15
  import { PROXY_BIN, proxyOnPath } from "../../core/secret-redact.ts";
15
- import { adapterLog } from "./index.ts";
16
16
  import { PACKAGE_ROOT, packageJsonPath, packageVersion } from "./package-root.ts";
17
17
  import { defaultCompletedResults, defaultRunSource } from "./sessions.ts";
18
18
 
19
+ /** One line in the guard log: the adapter's own trace of what it did (relaunches, detectors). */
20
+ export function adapterLog(cfg: Config, line: string): void {
21
+ try {
22
+ appendFileSync(cfg.paths.guard_log, `${new Date().toISOString()} ${line}\n`);
23
+ } catch {}
24
+ }
25
+
19
26
  /** The harness the launcher runs. Tests pass another path through LaunchOptions. */
20
27
  export const OMP_BIN = "omp";
21
28
 
@@ -111,12 +118,6 @@ function hasPositional(args: string[]): boolean {
111
118
  return false;
112
119
  }
113
120
 
114
- export interface LaunchOptions {
115
- harness?: string;
116
- /** The main-start text generator for the handoff (default: src/core/main-start.ts). Tests inject a failing one. */
117
- mainStart?: typeof mainStartText;
118
- }
119
-
120
121
  interface RelaunchRequest {
121
122
  previousSessionFile: string;
122
123
  notePath: string;
@@ -1,7 +1,7 @@
1
1
  import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
2
2
  import { basename, join } from "node:path";
3
3
  import type { Config } from "../../core/config.ts";
4
- import type { MainSession, Run, RunMessage, RunSource, RunStatus } from "../../core/adapter.ts";
4
+ import type { MainSession, Run, RunMessage, RunSource, RunStatus, TaskResult } from "../../core/adapter.ts";
5
5
  import { nowSec } from "../../core/clock.ts";
6
6
  import { readBudgets } from "../../core/guards.ts";
7
7
  import { pyDumps } from "../../core/pyjson.ts";
@@ -312,8 +312,8 @@ export function defaultRunSource(cfg: Config): RunSource {
312
312
  * wait were invisible here, so D1 never saw them). A line without a readable timestamp is
313
313
  * skipped — without one the contradiction grace cannot be aged.
314
314
  */
315
- export function completedResults(text: string): { agent: string; ts: number }[] {
316
- const out: { agent: string; ts: number }[] = [];
315
+ export function completedResults(text: string): TaskResult[] {
316
+ const out: TaskResult[] = [];
317
317
  for (const line of text.split("\n")) {
318
318
  const isAsync = line.includes('"async-result"');
319
319
  const isWait = line.includes('"toolName":"wait"');
@@ -349,7 +349,7 @@ export function completedResults(text: string): { agent: string; ts: number }[]
349
349
  }
350
350
 
351
351
  /** `completedResults` of the newest Main session file (the one `mainSession()` picks). */
352
- export function defaultCompletedResults(cfg: Config): { agent: string; ts: number }[] {
352
+ export function defaultCompletedResults(cfg: Config): TaskResult[] {
353
353
  try {
354
354
  const s = defaultRunSource(cfg).mainSession();
355
355
  return s ? completedResults(readFileSync(s.file, "utf8")) : [];
@@ -8,7 +8,7 @@
8
8
  import { closeSync, openSync, readFileSync, readSync, readdirSync, statSync } from "node:fs";
9
9
  import { dirname, join } from "node:path";
10
10
  import type { Config } from "../../core/config.ts";
11
- import type { TraceEvent, TraceSource, TraceUsage } from "../../core/adapter.ts";
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
14
  import { asObj, jsonlAt, parseTs, runIdOf } from "./sessions.ts";
@@ -135,7 +135,7 @@ export function parseTraceFile(file: string, runId: string): TraceEvent[] {
135
135
  }
136
136
 
137
137
  /** Every run id with a trace under the root, each mapped to its newest file. */
138
- export function ompTraceRuns(root: string): { runId: string; file: string; mtimeSec: number }[] {
138
+ export function ompTraceRuns(root: string): TraceRun[] {
139
139
  const newest: Record<string, { file: string; mtimeSec: number }> = {};
140
140
  for (const file of [...jsonlAt(root, 1), ...jsonlAt(root, 2)]) {
141
141
  let mt: number;
@@ -208,14 +208,14 @@ export function ompDumpDir(home: string): string {
208
208
  * Every request dump under the harness log dir, oldest first. Dumps are named
209
209
  * `<epoch ms of the failed request>-<request id>.json`; anything else in the dir is not a dump.
210
210
  */
211
- export function ompDumps(home: string): { file: string; ms: number }[] {
211
+ export function ompDumps(home: string): DumpRef[] {
212
212
  let names: string[];
213
213
  try {
214
214
  names = readdirSync(ompDumpDir(home));
215
215
  } catch {
216
216
  return [];
217
217
  }
218
- const out: { file: string; ms: number }[] = [];
218
+ const out: DumpRef[] = [];
219
219
  for (const name of names) {
220
220
  const m = /^(\d+)-[A-Za-z0-9]+\.json$/.exec(name);
221
221
  if (m) out.push({ file: join(ompDumpDir(home), name), ms: Number(m[1]) });
@@ -318,13 +318,6 @@ export function ompScoreTraces(cfg: Config): TraceSource {
318
318
  return ompTraceSource(cfg.adapter?.sessions || join(cfg.paths.home, ".omp", "agent", "sessions"));
319
319
  }
320
320
 
321
- export interface RelatedTrace {
322
- /** The subagent run's trace run id — the agent name. */
323
- name: string;
324
- mtimeSec: number;
325
- events: TraceEvent[];
326
- }
327
-
328
321
  /**
329
322
  * The subagent runs of one Main run: the depth-2 session files under the Main file's session
330
323
  * dir (plan 20261024_0301 P5) — the runs Main spawned there, whose results Main's report cites.
@@ -18,9 +18,7 @@ import { wipBackup } from "../core/wip-backup.ts";
18
18
  import { wipCheck } from "../core/wip-check.ts";
19
19
  import { wipSnapshot } from "../core/wip-snapshot.ts";
20
20
  import { runtime } from "./runtime.ts";
21
- import { runMainLauncher } from "../adapters/omp/launch.ts";
22
- import { defaultCompletedResults, defaultRunSource } from "../adapters/omp/sessions.ts";
23
- import { ompScoreTraces } from "../adapters/omp/traces.ts";
21
+ import { getAdapter } from "../adapters/index.ts";
24
22
 
25
23
  export const PORTED = [
26
24
  "agent-score",
@@ -45,14 +43,15 @@ export const PORTED = [
45
43
  ] as const;
46
44
 
47
45
  export async function runMain(args: string[]): Promise<number> {
48
- return runMainLauncher(args, runtime().cfg);
46
+ const cfg = runtime().cfg;
47
+ return getAdapter(cfg).launchMain(args, cfg);
49
48
  }
50
49
 
51
50
  export async function runPorted(cmd: string, args: string[]): Promise<number> {
52
51
  const rt = runtime();
53
52
  switch (cmd) {
54
53
  case "agent-score":
55
- return agentScore(args, rt.cfg, rt.source, ompScoreTraces(rt.cfg));
54
+ return agentScore(args, rt.cfg, rt.source, getAdapter(rt.cfg).scoreTraces(rt.cfg));
56
55
  case "agent-ledger":
57
56
  return agentLedger(args, rt.cfg, rt.source);
58
57
  case "brief-lint":
@@ -75,8 +74,10 @@ export async function runPorted(cmd: string, args: string[]): Promise<number> {
75
74
  return queueClose(args, rt.cfg);
76
75
  case "queue-cancel":
77
76
  return queueCancel(args, rt.cfg);
78
- case "main-start":
79
- return mainStart(args, rt.cfg, { source: defaultRunSource(rt.cfg), results: defaultCompletedResults(rt.cfg) });
77
+ case "main-start": {
78
+ const a = getAdapter(rt.cfg);
79
+ return mainStart(args, rt.cfg, { source: a.runSource(rt.cfg), results: a.completedResults(rt.cfg) });
80
+ }
80
81
  case "machine-guard":
81
82
  return machineGuard(args, rt.cfg);
82
83
  case "quota-reset":
@@ -4,8 +4,7 @@ import { ConfigError, configFile, loadConfig, type Config } from "../core/config
4
4
  import { postReply } from "../core/notify.ts";
5
5
  import { loadKnownSecrets, redactSecrets, redactSummary } from "../core/secret-redact.ts";
6
6
  import { applyQueueEnv } from "../core/queue/env.ts";
7
- import { runAdapterInstall } from "../adapters/omp/install.ts";
8
- import { runDoctor } from "../adapters/omp/doctor.ts";
7
+ import { getAdapter } from "../adapters/index.ts";
9
8
  import { GUARD_USAGE, runGuard } from "./guard.ts";
10
9
  import { runInit } from "./init.ts";
11
10
  import { PORTED, runMain, runPorted } from "./commands.ts";
@@ -110,7 +109,7 @@ export async function run(cmd: string, args: string[]): Promise<number> {
110
109
  if (cmd === "traces") return runTraces(args);
111
110
  if (cmd === "ui") return runUi(args);
112
111
  if (cmd === "pages") return runPages(args);
113
- if (cmd === "adapter") return runAdapterInstall(args);
112
+ if (cmd === "adapter") return getAdapter().install(args);
114
113
  if (cmd === "config") {
115
114
  try {
116
115
  const cfg = loadConfig();
@@ -123,7 +122,7 @@ export async function run(cmd: string, args: string[]): Promise<number> {
123
122
  }
124
123
  if (cmd === "doctor") {
125
124
  for (const warning of pagesDoctor()) console.warn(`warning: ${warning}`);
126
- return runDoctor();
125
+ return getAdapter().doctor();
127
126
  }
128
127
  if (cmd === "notify") return runNotify(args);
129
128
  if (cmd === "redact") return runRedact(args);
@@ -11,8 +11,7 @@ import type { RunSource } from "../core/adapter.ts";
11
11
  import { buildReport, type BloatSummary, type ProviderSummary } from "../core/report.ts";
12
12
  import { providerFindings } from "../core/trace-provider.ts";
13
13
  import { bloatRules } from "../core/trace-bloat.ts";
14
- import { defaultRunSource } from "../adapters/omp/sessions.ts";
15
- import { ompDumps, ompTraceRuns, ompTraceSource } from "../adapters/omp/traces.ts";
14
+ import { getAdapter } from "../adapters/index.ts";
16
15
  import { assignDumps, bloatReport } from "./traces.ts";
17
16
 
18
17
  export const METRICS_USAGE = [
@@ -97,12 +96,13 @@ export function recordRule(cfg: Config, text: string, decision: "approved" | "re
97
96
  * rules of src/core/trace-provider.ts under the config's provider rules and price table. */
98
97
  function providerSummary(cfg: Config, now: number, days: number): ProviderSummary {
99
98
  const root = cfg.adapter?.sessions || join(cfg.paths.home, ".omp", "agent", "sessions");
99
+ const a = getAdapter(cfg);
100
100
  const cutoff = now - days * 86400;
101
- const src = ompTraceSource(root);
101
+ const src = a.traceSource(root);
102
102
  const rules = cfg.traces.provider;
103
103
  const byKind: Record<string, number> = {};
104
104
  let runs = 0;
105
- for (const r of ompTraceRuns(root)) {
105
+ for (const r of a.traceRuns(root)) {
106
106
  if (r.mtimeSec < cutoff) continue;
107
107
  runs++;
108
108
  for (const f of providerFindings(src.events(r.runId), rules, rules.prices)) byKind[f.kind] = (byKind[f.kind] ?? 0) + 1;
@@ -115,20 +115,21 @@ function providerSummary(cfg: Config, now: number, days: number): ProviderSummar
115
115
  * rejected call flags only through its dump). */
116
116
  function bloatSummary(cfg: Config, now: number, days: number): BloatSummary {
117
117
  const root = cfg.adapter?.sessions || join(cfg.paths.home, ".omp", "agent", "sessions");
118
+ const a = getAdapter(cfg);
118
119
  const cutoff = now - days * 86400;
119
- const src = ompTraceSource(root);
120
+ const src = a.traceSource(root);
120
121
  const rules = bloatRules(cfg);
121
- const dumps = ompDumps(cfg.paths.home);
122
+ const dumps = a.dumps(cfg.paths.home);
122
123
  let runs = 0;
123
124
  let flagged = 0;
124
125
  let largest: BloatSummary["largest"] = null;
125
- const allRuns = ompTraceRuns(root);
126
- const { owners, events: assignmentEvents } = assignDumps(allRuns, src, dumps);
126
+ const allRuns = a.traceRuns(root);
127
+ const { owners, events: assignmentEvents } = assignDumps(allRuns, src, dumps, a);
127
128
  for (const r of allRuns) {
128
129
  if (r.mtimeSec < cutoff) continue;
129
130
  runs++;
130
131
  const owned = dumps.filter((dump) => owners.get(dump.file) === r.runId);
131
- const rep = bloatReport(src, r.runId, rules, cfg.traces.bloat.tool_group, owned, r.mtimeSec, assignmentEvents.get(r.runId));
132
+ const rep = bloatReport(src, r.runId, rules, cfg.traces.bloat.tool_group, owned, r.mtimeSec, a, assignmentEvents.get(r.runId));
132
133
  if (rep.findings.length === 0) continue;
133
134
  flagged++;
134
135
  const firstCall = Math.max(rep.firstPrompt ?? 0, rep.dumpPrompt?.tokens ?? 0);
@@ -163,7 +164,7 @@ export async function runMetrics(args: string[]): Promise<number> {
163
164
  const [sub = "", ...rest] = args;
164
165
  const now = nowSec();
165
166
  if (sub === "ci") return recordCi(cfg, rest[0] ?? "", rest[1] ?? "", now);
166
- if (sub === "report") return reportCmd(cfg, defaultRunSource(cfg), rest, now);
167
+ if (sub === "report") return reportCmd(cfg, getAdapter(cfg).runSource(cfg), rest, now);
167
168
  if (sub === "false-alarm") return recordFalseAlarm(cfg, rest[0] ?? "", flagValue(rest, "--why") ?? "", now);
168
169
  if (sub === "rule") {
169
170
  const approved = rest.includes("--approved");
package/src/cli/pages.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { readdirSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
- import { defaultRunSource } from "../adapters/omp/sessions.ts";
3
+ import { getAdapter } from "../adapters/index.ts";
4
4
  import { loadConfig } from "../core/config.ts";
5
5
  import { readExpiry, sweepPages } from "../core/pages-expiry.ts";
6
6
  import { startPagesServer } from "../core/pages.ts";
@@ -19,7 +19,7 @@ export async function runPages(args: string[] = [], deps: PagesDeps = {}): Promi
19
19
  if (args[0] === "serve" && args.length === 1) {
20
20
  if (!cfg.pages.enabled) throw new Error("pages.enabled is false");
21
21
  sweepPages(cfg.pages.dir, cfg.pages.keep_days, clock());
22
- startPagesServer({ cfg, tailscale: deps.tailscale ?? realTailscale, source: defaultRunSource(cfg) });
22
+ startPagesServer({ cfg, tailscale: deps.tailscale ?? realTailscale, source: getAdapter(cfg).runSource(cfg) });
23
23
  setInterval(() => { try { sweepPages(cfg.pages.dir, cfg.pages.keep_days, clock()); } catch (e) { console.error(e instanceof Error ? e.message : String(e)); } }, HOUR_MS);
24
24
  return new Promise<number>(() => {});
25
25
  }
@@ -1,6 +1,6 @@
1
1
  import { loadConfig, type Config } from "../core/config.ts";
2
2
  import type { RunSource } from "../core/adapter.ts";
3
- import { defaultRunSource } from "../adapters/omp/sessions.ts";
3
+ import { getAdapter } from "../adapters/index.ts";
4
4
 
5
5
  export interface Runtime {
6
6
  cfg: Config;
@@ -9,5 +9,5 @@ export interface Runtime {
9
9
 
10
10
  export function runtime(): Runtime {
11
11
  const cfg = loadConfig();
12
- return { cfg, source: defaultRunSource(cfg) };
12
+ return { cfg, source: getAdapter(cfg).runSource(cfg) };
13
13
  }
package/src/cli/traces.ts CHANGED
@@ -14,7 +14,8 @@
14
14
 
15
15
  import { join } from "node:path";
16
16
  import { nowSec } from "../core/clock.ts";
17
- import type { TraceEvent, TraceSource } from "../core/adapter.ts";
17
+ import type { DumpRef, TraceEvent, TraceSource } from "../core/adapter.ts";
18
+ import { getAdapter, type HarnessAdapter } from "../adapters/index.ts";
18
19
  import { ConfigError, loadConfig, type Config } from "../core/config.ts";
19
20
  import { claimUnbacked } from "../core/incident-detectors.ts";
20
21
  import { claimsFromEvents, type RelatedRun } from "../core/trace-claims.ts";
@@ -22,7 +23,6 @@ import { actionsRules, suspiciousActions, type ActionsRules, type SuspiciousActi
22
23
  import { bloatBreakdown, bloatFindings, bloatRules, callSizes, dumpFinding, type BloatBreakdown, type BloatRules } from "../core/trace-bloat.ts";
23
24
  import { efficiencyRules, runEfficiency, RULE_ORDER, type EfficiencyRules, type WasteRule } from "../core/trace-efficiency.ts";
24
25
  import { pyPercent0 } from "../core/pyfmt.ts";
25
- import { dumpModel, dumpParts, dumpPromptTokens, ompDumps, ompTraceRuns, ompTraceSource, ompTraceStart, spawnBriefsIn, subagentTraces } from "../adapters/omp/traces.ts";
26
26
  import { briefReport, briefRows, type SideStat } from "../core/trace-briefs.ts";
27
27
  import { readEvents } from "../core/agent-score.ts";
28
28
 
@@ -111,16 +111,16 @@ export interface DumpAssignmentRun { runId: string; file: string; mtimeSec: numb
111
111
  export interface DumpAssignment { owners: Map<string, string>; unmatched: { file: string; ms: number }[]; events: Map<string, TraceEvent[]> }
112
112
 
113
113
  /** Assign each dump once, parsing only traces whose session start and mtime contain it. */
114
- export function assignDumps(runs: DumpAssignmentRun[], src: TraceSource, dumps: { file: string; ms: number }[]): DumpAssignment {
114
+ export function assignDumps(runs: DumpAssignmentRun[], src: TraceSource, dumps: DumpRef[], a: Pick<HarnessAdapter, "dumpModel" | "traceStart"> = getAdapter()): DumpAssignment {
115
115
  const owners = new Map<string, string>();
116
- const unmatched: { file: string; ms: number }[] = [];
116
+ const unmatched: DumpRef[] = [];
117
117
  const cached = new Map<string, ReturnType<TraceSource["events"]>>();
118
118
  for (const dump of dumps) {
119
- const model = dumpModel(dump.file);
119
+ const model = a.dumpModel(dump.file);
120
120
  const eligible: { ts: number; runId: string }[] = [];
121
121
  for (const run of runs) {
122
122
  if (dump.ms > Math.round(run.mtimeSec * 1000)) continue;
123
- const start = ompTraceStart(run.file);
123
+ const start = a.traceStart(run.file);
124
124
  if (start !== null && dump.ms < start * 1000) continue;
125
125
  let events = cached.get(run.runId);
126
126
  if (!events) {
@@ -144,7 +144,7 @@ export function assignDumps(runs: DumpAssignmentRun[], src: TraceSource, dumps:
144
144
  return { owners, unmatched, events: cached };
145
145
  }
146
146
 
147
- export function bloatReport(src: TraceSource, runId: string, rules: BloatRules, groupRegex: string, dumps: { file: string; ms: number }[], mtimeSec: number, parsedEvents?: TraceEvent[]): RunBloatReport {
147
+ export function bloatReport(src: TraceSource, runId: string, rules: BloatRules, groupRegex: string, dumps: DumpRef[], mtimeSec: number, a: Pick<HarnessAdapter, "dumpParts" | "dumpPromptTokens"> = getAdapter(), parsedEvents?: TraceEvent[]): RunBloatReport {
148
148
  const events = parsedEvents ?? src.events(runId);
149
149
  const sizes = callSizes(events, rules.aggregate_apis);
150
150
  const findings = bloatFindings(events, rules);
@@ -161,8 +161,8 @@ export function bloatReport(src: TraceSource, runId: string, rules: BloatRules,
161
161
  if (first !== undefined) {
162
162
  const dump = dumps.find((d) => d.ms >= first * 1000 && d.ms <= Math.round(mtimeSec * 1000));
163
163
  if (dump) {
164
- breakdown = bloatBreakdown(dumpParts(dump.file), groupRegex);
165
- const stated = dumpPromptTokens(dump.file);
164
+ breakdown = bloatBreakdown(a.dumpParts(dump.file), groupRegex);
165
+ const stated = a.dumpPromptTokens(dump.file);
166
166
  if (stated) {
167
167
  dumpPrompt = { tokens: stated.tokens, ...(stated.limit !== undefined ? { limit: stated.limit } : {}) };
168
168
  if (findings.length === 0) {
@@ -208,10 +208,11 @@ function briefsCommand(cfg: Config, root: string, rest: string[]): number {
208
208
  }
209
209
  }
210
210
  const cutoff = nowSec() - windowSec;
211
- const briefs = ompTraceRuns(root)
211
+ const a = getAdapter(cfg);
212
+ const briefs = a.traceRuns(root)
212
213
  .filter((r) => r.mtimeSec >= cutoff)
213
- .flatMap((r) => spawnBriefsIn(r.file, r.runId));
214
- const rows = briefRows(briefs, ompTraceSource(root), readEvents(cfg), { brief: cfg.traces.briefs, efficiency: efficiencyRules(cfg) });
214
+ .flatMap((r) => a.spawnBriefsIn(r.file, r.runId));
215
+ const rows = briefRows(briefs, a.traceSource(root), readEvents(cfg), { brief: cfg.traces.briefs, efficiency: efficiencyRules(cfg) });
215
216
  const summary = briefReport(rows, { min_n: cfg.traces.briefs.min_n, char_buckets: cfg.traces.briefs.char_buckets });
216
217
  if (json) {
217
218
  console.log(JSON.stringify(report ? summary : rows, null, 2));
@@ -279,15 +280,16 @@ export async function runTraces(args: string[], opts: { home?: string } = {}): P
279
280
  console.error(TRACES_USAGE);
280
281
  return 2;
281
282
  }
282
- const runs = ompTraceRuns(root);
283
- const src = ompTraceSource(root);
283
+ const a = getAdapter(cfg);
284
+ const runs = a.traceRuns(root);
285
+ const src = a.traceSource(root);
284
286
  const rules: ActionsRules | EfficiencyRules | BloatRules | null = sub === "actions" ? actionsRules(cfg) : sub === "efficiency" ? efficiencyRules(cfg) : sub === "bloat" ? bloatRules(cfg) : null;
285
287
  // A Main run's report cites its subagents' results: their traces under the Main session dir
286
288
  // back the pure result-line claims (P5). No time filter — the text match is the guard, and
287
289
  // a sub's file keeps being written while its Main run lives, inside whatever window.
288
290
  const relatedOf = (id: string): RelatedRun[] =>
289
- sub === "claims" ? subagentTraces(root, id).map(({ name, events }) => ({ name, events })) : [];
290
- const dumps = sub === "bloat" ? ompDumps(cfg.paths.home) : [];
291
+ sub === "claims" ? a.subagentTraces(root, id).map(({ name, events }) => ({ name, events })) : [];
292
+ const dumps = sub === "bloat" ? a.dumps(cfg.paths.home) : [];
291
293
  const assignment = sub === "bloat" ? assignDumps(runs, src, dumps) : { owners: new Map<string, string>(), unmatched: [] as { file: string; ms: number }[], events: new Map<string, TraceEvent[]>() };
292
294
  const dumpOwners = assignment.owners;
293
295
  const unmatchedDumps = assignment.unmatched;
@@ -298,7 +300,7 @@ export async function runTraces(args: string[], opts: { home?: string } = {}): P
298
300
  if (sub === "claims") return claimsReport(src, id, relatedOf(id));
299
301
  if (sub === "actions") return actionsReport(src, id, rules as ActionsRules);
300
302
  if (sub === "efficiency") return efficiencyReport(src, id, rules as EfficiencyRules);
301
- return bloatReport(src, id, rules as BloatRules, cfg.traces.bloat.tool_group, assignedDumps(id), mtimeOf(id), assignment.events.get(id));
303
+ return bloatReport(src, id, rules as BloatRules, cfg.traces.bloat.tool_group, assignedDumps(id), mtimeOf(id), a, assignment.events.get(id));
302
304
  };
303
305
  if (windowSec !== undefined) {
304
306
  const cutoff = nowSec() - windowSec;
package/src/cli/ui.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  // `ui on --login <email> [--port N]` / `ui off` set up and undo that whole setup in one command
5
5
  // (the core lives in src/core/ui-setup.ts); plain `neurastream ui` keeps serving as today.
6
6
 
7
- import { defaultRunSource } from "../adapters/omp/sessions.ts";
7
+ import { getAdapter } from "../adapters/index.ts";
8
8
  import { ConfigError, loadConfig, type Config } from "../core/config.ts";
9
9
  import { startOwnerUi, type OwnerUiOptions, type OwnerUiServer } from "../core/owner-ui.ts";
10
10
  import { applyQueueEnv } from "../core/queue/env.ts";
@@ -84,7 +84,7 @@ export async function runUi(args: string[] = [], deps: UiDeps = {}): Promise<num
84
84
  console.error("neurastream ui: ui.owner_login is empty — set the tailscale login that may open the page");
85
85
  return 1;
86
86
  }
87
- (deps.start ?? startOwnerUi)({ cfg, tailscale: realTailscale, source: defaultRunSource(cfg) });
87
+ (deps.start ?? startOwnerUi)({ cfg, tailscale: realTailscale, source: getAdapter(cfg).runSource(cfg) });
88
88
  // src/cli/main.ts exits with the code this returns, which would kill the server: serving
89
89
  // never resolves, and the process runs until systemd or a signal stops it.
90
90
  return new Promise<number>(() => {});
@@ -1,5 +1,7 @@
1
1
  // Guard decisions and run data. No harness names. See docs/adapter.md.
2
2
 
3
+ import type { mainStartText } from "./main-start.ts";
4
+
3
5
  export type RunStatus = "running" | "waiting" | "done" | "died";
4
6
 
5
7
  export interface RunMessage {
@@ -137,3 +139,40 @@ export interface StopEvent {
137
139
 
138
140
  export const GUARD_EVENTS = ["pre-tool", "inject", "spawn", "plan-edit", "stop"] as const;
139
141
  export type GuardEvent = (typeof GUARD_EVENTS)[number];
142
+
143
+ // Shapes the registry (src/adapters/index.ts) and the CLI share. No harness names — only
144
+ // src/adapters may name one.
145
+
146
+ /** Every run id with a trace under a sessions root, each mapped to its newest file. */
147
+ export interface TraceRun {
148
+ runId: string;
149
+ file: string;
150
+ mtimeSec: number;
151
+ }
152
+
153
+ /** One failed-request dump file: its path plus the epoch-ms stamp in its name. */
154
+ export interface DumpRef {
155
+ file: string;
156
+ ms: number;
157
+ }
158
+
159
+ /** One subagent run's trace under one main run's session dir. */
160
+ export interface RelatedTrace {
161
+ /** The subagent run's trace run id — the agent name. */
162
+ name: string;
163
+ mtimeSec: number;
164
+ events: TraceEvent[];
165
+ }
166
+
167
+ /** One finished subagent task-result announced in the newest main session file. */
168
+ export interface TaskResult {
169
+ agent: string;
170
+ ts: number;
171
+ }
172
+
173
+ /** Options for launching the harness binary; tests inject another path and a failing generator. */
174
+ export interface LaunchOptions {
175
+ harness?: string;
176
+ /** The main-start text generator for the handoff (default: src/core/main-start.ts). Tests inject a failing one. */
177
+ mainStart?: typeof mainStartText;
178
+ }
@@ -17,6 +17,8 @@ export class ConfigError extends Error {
17
17
  }
18
18
 
19
19
  export interface Config {
20
+ /** Which adapter (src/adapters/index.ts) serves runs, traces, launch, install and doctor. The template ships the only one; a second harness adds its name here (docs/adapter.md). */
21
+ harness: string;
20
22
  paths: {
21
23
  home: string;
22
24
  work_roots: string[];
@@ -387,6 +389,7 @@ function applyEnv(cfg: Record<string, unknown>, env: NodeJS.ProcessEnv): void {
387
389
  }
388
390
 
389
391
  function check(cfg: Config): void {
392
+ if (typeof cfg.harness !== "string" || cfg.harness === "") throw new ConfigError("harness must be a non-empty string");
390
393
  try {
391
394
  const pattern = cfg.quota.reset_pattern;
392
395
  new RegExp(pattern);
@@ -12,6 +12,7 @@ import { log as logGuard } from "./guards.ts";
12
12
  import { dailyChecks, readBlocks, readMetricEvents, worseThanMean } from "./metrics.ts";
13
13
  import { buildReport } from "./report.ts";
14
14
  import { loadavgLine } from "./host.ts";
15
+ import { mrSweep } from "./mr-sweep.ts";
15
16
 
16
17
  function bin(name: string, cfg: Config): string {
17
18
  return join(cfg.paths.home, ".local/bin", name);
@@ -134,7 +135,7 @@ export async function mainStartText(args: string[], cfg: Config, opts: { inherit
134
135
  out.push(health.stdout + health.stderr);
135
136
  say("");
136
137
  say("=== queue");
137
- const check = await run(bin("queue-check", cfg), [], { stdin: childStdin, stderr: childStderr });
138
+ const check = await run(bin("queue-check", cfg), ["--no-mr-sweep"], { stdin: childStdin, stderr: childStderr });
138
139
  out.push(check.stdout + check.stderr);
139
140
  say("");
140
141
  say("=== heavy-run lock");
@@ -151,6 +152,15 @@ export async function mainStartText(args: string[], cfg: Config, opts: { inherit
151
152
  const text = `${doctor.stdout}${doctor.stderr}`;
152
153
  out.push(text.endsWith("\n") || text === "" ? text : `${text}\n`);
153
154
  if (doctor.error) say(doctor.error.message);
155
+ try {
156
+ const sweep = mrSweep({ index: cfg.paths.queue_index });
157
+ if (sweep.lines.length) {
158
+ say("=== mr-sweep");
159
+ for (const line of sweep.lines) say(line);
160
+ }
161
+ } catch {
162
+ say("mr-sweep: skipped (forge unreachable)");
163
+ }
154
164
  return out.join("");
155
165
  }
156
166
 
@@ -0,0 +1,266 @@
1
+ // Reconcile open forge MRs with open plans. The forge is the source of truth; a missing CLI,
2
+ // auth failure, unknown host or absent origin skips that repo and never fails the sweep.
3
+ // Host-neutral: forge CLIs are invoked through a command runner. No harness imports.
4
+
5
+ import { spawnSync } from "node:child_process";
6
+ import path from "node:path";
7
+ import { cmd } from "./proc.ts";
8
+ import { activePlans, gitTop } from "./queue/lib.ts";
9
+
10
+ export const MR_SWEEP_NO_CLI = "mr-sweep: skipped (no forge CLI)";
11
+ const UNTRACKED_TAIL = "— no open plan mentions it";
12
+ const PAGE = 100;
13
+ const MAX_PAGES = 20;
14
+
15
+ export type Forge = "gitlab" | "github";
16
+
17
+ export interface CommandResult {
18
+ code: number;
19
+ stdout: string;
20
+ stderr: string;
21
+ /** The executable was not on PATH. Distinct from a non-zero exit (auth, network, usage). */
22
+ missing?: boolean;
23
+ }
24
+
25
+ export type CommandRunner = (args: string[], opts: { cwd?: string; env?: NodeJS.ProcessEnv }) => CommandResult;
26
+
27
+ export interface SweepMr {
28
+ forge: Forge;
29
+ number: number;
30
+ token: string;
31
+ branch: string;
32
+ repo: string;
33
+ tracked: boolean;
34
+ }
35
+
36
+ export interface SweepResult {
37
+ lines: string[];
38
+ mrs: SweepMr[];
39
+ /** True only when a reachable forge listed at least one untracked MR. A skip is never a failure. */
40
+ fail: boolean;
41
+ }
42
+
43
+ export interface SweepOpts {
44
+ index?: string;
45
+ env?: NodeJS.ProcessEnv;
46
+ runner?: CommandRunner;
47
+ }
48
+
49
+ export function defaultRunner(args: string[], opts: { cwd?: string; env?: NodeJS.ProcessEnv } = {}): CommandResult {
50
+ const bin = args[0];
51
+ if (!bin) return { code: 127, stdout: "", stderr: "missing command", missing: true };
52
+ const r = spawnSync(bin, args.slice(1), {
53
+ cwd: opts.cwd,
54
+ env: opts.env ?? process.env,
55
+ encoding: "utf8",
56
+ timeout: 20_000,
57
+ maxBuffer: 8 * 1024 * 1024,
58
+ });
59
+ const err = r.error as NodeJS.ErrnoException | undefined;
60
+ if (err?.code === "ENOENT") return { code: 127, stdout: "", stderr: err.message, missing: true };
61
+ if (err) return { code: 1, stdout: r.stdout ?? "", stderr: `${r.stderr ?? ""}${err.message}` };
62
+ return { code: r.status ?? 1, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
63
+ }
64
+
65
+ /** Host of an origin URL (`git@host:path`, `ssh://`, `https://`). Null when it does not parse. */
66
+ export function remoteHost(url: string): string | null {
67
+ const u = url.trim();
68
+ if (!u.includes("://")) {
69
+ const scp = /^[^@\s]+@([^:\s]+):/.exec(u);
70
+ if (scp?.[1]) return scp[1].toLowerCase();
71
+ }
72
+ try {
73
+ if (u.includes("://")) {
74
+ const host = new URL(u).hostname.toLowerCase();
75
+ return host || null;
76
+ }
77
+ } catch {
78
+ return null;
79
+ }
80
+ return null;
81
+ }
82
+
83
+ /** `gitlab` in the host → gitlab; `github` in the host → github; anything else is unknown. */
84
+ export function forgeOf(host: string): Forge | null {
85
+ const h = host.toLowerCase();
86
+ if (h.includes("gitlab")) return "gitlab";
87
+ if (h.includes("github")) return "github";
88
+ return null;
89
+ }
90
+
91
+ /** `!N` / `#N` as a whole token, or the source branch name, in any of the texts. `MR !N: ignored` matches the token. */
92
+ export function mentioned(token: string, branch: string, texts: string[]): boolean {
93
+ const re = new RegExp(`(?:^|[^0-9])${token.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![0-9])`);
94
+ for (const text of texts) {
95
+ if (re.test(text)) return true;
96
+ if (branch && text.includes(branch)) return true;
97
+ }
98
+ return false;
99
+ }
100
+
101
+ function asRecord(v: unknown): Record<string, unknown> | null {
102
+ return v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : null;
103
+ }
104
+
105
+ function asNumber(v: unknown): number | null {
106
+ if (typeof v === "number" && Number.isInteger(v) && v > 0) return v;
107
+ if (typeof v === "string" && /^[0-9]+$/.test(v)) return Number(v);
108
+ return null;
109
+ }
110
+
111
+ /** Parse a JSON list. Null means the CLI answered but not with a list — treat as unreachable, never as "no MRs". */
112
+ function parseList(stdout: string): Record<string, unknown>[] | null {
113
+ const t = stdout.trim();
114
+ if (!t) return [];
115
+ const from = (v: unknown): Record<string, unknown>[] | null => {
116
+ if (Array.isArray(v)) return v.map(asRecord).filter((x): x is Record<string, unknown> => x !== null);
117
+ const rec = asRecord(v);
118
+ if (!rec) return null;
119
+ for (const key of ["merge_requests", "items", "pull_requests"]) {
120
+ const inner = rec[key];
121
+ if (Array.isArray(inner)) return inner.map(asRecord).filter((x): x is Record<string, unknown> => x !== null);
122
+ }
123
+ return null;
124
+ };
125
+ try {
126
+ return from(JSON.parse(t));
127
+ } catch {
128
+ const at = t.indexOf("[");
129
+ const end = t.lastIndexOf("]");
130
+ if (at < 0 || end <= at) return null;
131
+ try {
132
+ return from(JSON.parse(t.slice(at, end + 1)));
133
+ } catch {
134
+ return null;
135
+ }
136
+ }
137
+ }
138
+
139
+ interface Listed {
140
+ missing?: boolean;
141
+ fail?: boolean;
142
+ items: { number: number; branch: string }[];
143
+ }
144
+
145
+ function takeItems(parsed: Record<string, unknown>[], numberKey: "iid" | "number", branchKeys: string[]): { number: number; branch: string }[] {
146
+ const items: { number: number; branch: string }[] = [];
147
+ const seen = new Set<number>();
148
+ for (const item of parsed) {
149
+ const n = asNumber(item[numberKey] ?? item.number);
150
+ if (n === null || seen.has(n)) continue;
151
+ const state = typeof item.state === "string" ? item.state : "";
152
+ // The list command already asks for open MRs. Skip only an explicit closed/merged row,
153
+ // so an unexpected state label cannot hide an open MR.
154
+ if (state === "closed" || state === "merged") continue;
155
+ seen.add(n);
156
+ let branch = "";
157
+ for (const key of branchKeys) {
158
+ const value = item[key];
159
+ if (typeof value === "string") {
160
+ branch = value;
161
+ break;
162
+ }
163
+ }
164
+ items.push({ number: n, branch });
165
+ }
166
+ return items;
167
+ }
168
+
169
+ function listGitlab(repo: string, run: CommandRunner, env?: NodeJS.ProcessEnv): Listed {
170
+ const items: { number: number; branch: string }[] = [];
171
+ const seen = new Set<number>();
172
+ for (let page = 1; page <= MAX_PAGES; page++) {
173
+ const r = run(["glab", "mr", "list", "-F", "json", "-P", String(PAGE), "-p", String(page)], { cwd: repo, env });
174
+ if (r.missing) return { missing: true, items: [] };
175
+ if (r.code !== 0) return { fail: true, items: [] };
176
+ const parsed = parseList(r.stdout);
177
+ if (parsed === null) return { fail: true, items: [] };
178
+ for (const item of takeItems(parsed, "iid", ["source_branch", "sourceBranch"])) {
179
+ if (seen.has(item.number)) continue;
180
+ seen.add(item.number);
181
+ items.push(item);
182
+ }
183
+ if (parsed.length < PAGE) break;
184
+ }
185
+ return { items };
186
+ }
187
+
188
+ function listGithub(repo: string, run: CommandRunner, env?: NodeJS.ProcessEnv): Listed {
189
+ const r = run(["gh", "pr", "list", "--state", "open", "--limit", "1000", "--json", "number,headRefName,title"], { cwd: repo, env });
190
+ if (r.missing) return { missing: true, items: [] };
191
+ if (r.code !== 0) return { fail: true, items: [] };
192
+ const parsed = parseList(r.stdout);
193
+ if (parsed === null) return { fail: true, items: [] };
194
+ return { items: takeItems(parsed, "number", ["headRefName", "head_ref_name"]) };
195
+ }
196
+
197
+ function skip(repo: string, why: string): string {
198
+ return `mr-sweep: skipped ${repo} (${why})`;
199
+ }
200
+
201
+ /**
202
+ * Open MRs of every repo in the index, marked tracked when an open plan of that repo contains
203
+ * the `!N` / `#N` token (including `MR !N: ignored`) or the source branch name.
204
+ */
205
+ export function mrSweep(opts: SweepOpts = {}): SweepResult {
206
+ const run = opts.runner ?? defaultRunner;
207
+ const plans = activePlans(opts.index);
208
+ const repos: string[] = [];
209
+ for (const p of plans) if (!repos.includes(p.repo)) repos.push(p.repo);
210
+ const lines: string[] = [];
211
+ const mrs: SweepMr[] = [];
212
+ let missingCli = false;
213
+ let fail = false;
214
+ for (const repo of repos) {
215
+ if (!gitTop(repo)) {
216
+ lines.push(skip(repo, "not a git repo"));
217
+ continue;
218
+ }
219
+ const remote = cmd(["git", "-C", repo, "remote", "get-url", "origin"], { env: opts.env });
220
+ const url = remote.code === 0 ? remote.stdout.trim() : "";
221
+ if (!url) {
222
+ lines.push(skip(repo, "no origin remote"));
223
+ continue;
224
+ }
225
+ const host = remoteHost(url);
226
+ const forge = host ? forgeOf(host) : null;
227
+ if (!forge) {
228
+ lines.push(skip(repo, "unknown forge"));
229
+ continue;
230
+ }
231
+ const listed = forge === "gitlab" ? listGitlab(repo, run, opts.env) : listGithub(repo, run, opts.env);
232
+ if (listed.missing) {
233
+ missingCli = true;
234
+ continue;
235
+ }
236
+ if (listed.fail) {
237
+ lines.push(skip(repo, "forge unreachable"));
238
+ continue;
239
+ }
240
+ const texts = plans.filter(p => p.repo === repo && p.status === "open").map(p => p.text);
241
+ const found = listed.items
242
+ .map(item => {
243
+ const token = forge === "gitlab" ? `!${item.number}` : `#${item.number}`;
244
+ const mr: SweepMr = {
245
+ forge,
246
+ number: item.number,
247
+ token,
248
+ branch: item.branch,
249
+ repo,
250
+ tracked: mentioned(token, item.branch, texts),
251
+ };
252
+ return mr;
253
+ })
254
+ .sort((a, b) => a.number - b.number);
255
+ for (const mr of found) {
256
+ mrs.push(mr);
257
+ if (mr.tracked) lines.push(`tracked MR ${mr.token} ${path.basename(mr.repo)} ${mr.repo} (${mr.branch})`);
258
+ else {
259
+ lines.push(`UNTRACKED MR ${mr.token} ${path.basename(mr.repo)} ${mr.repo} (${mr.branch}) ${UNTRACKED_TAIL}`);
260
+ fail = true;
261
+ }
262
+ }
263
+ }
264
+ if (missingCli) lines.unshift(MR_SWEEP_NO_CLI);
265
+ return { lines, mrs, fail };
266
+ }
@@ -1,6 +1,7 @@
1
1
  import type { Config } from "./config.ts";
2
2
  import { applyQueueEnv } from "./queue/env.ts";
3
3
  import { activePlans, queueProblems, queueSummary } from "./queue/lib.ts";
4
+ import { mrSweep } from "./mr-sweep.ts";
4
5
 
5
6
  // One index (20261024_1400_one_index): the main index lists plan files directly, so there are no
6
7
  // repo INDEX.md files to git-check and no work_roots scan; the queue problems carry the
@@ -12,5 +13,16 @@ export function queueCheck(args: string[], cfg: Config): number {
12
13
  return 0;
13
14
  }
14
15
  console.log(queueSummary());
15
- return queueProblems().length ? 1 : 0;
16
+ // main-start prints the sweep itself and passes this so the child bin does not print it twice.
17
+ let fail = queueProblems().length > 0;
18
+ if (!args.includes("--no-mr-sweep")) {
19
+ try {
20
+ const sweep = mrSweep();
21
+ for (const line of sweep.lines) console.log(line);
22
+ if (sweep.fail) fail = true;
23
+ } catch {
24
+ console.log("mr-sweep: skipped (forge unreachable)");
25
+ }
26
+ }
27
+ return fail ? 1 : 0;
16
28
  }
@@ -15,8 +15,8 @@ You are Main, the orchestrator. Main plans, delegates, reviews and lands; implem
15
15
  ## Scripts (run at the stated moment)
16
16
  |Script|When|
17
17
  |---|---|
18
- |`main-start`|session start, after an abort, before every status report|
19
- |`queue-check`|after changing a plan or an index, before every spawn; exit 1 = fix first|
18
+ |`main-start`|session start, after an abort, before every status report; prints the MR sweep (open forge MRs vs open plans)|
19
+ |`queue-check`|after changing a plan or an index, before every spawn; exit 1 = fix first; also fails when a reachable forge lists an open MR no open plan mentions (`MR !N: ignored <reason>` in a plan marks it tracked)|
20
20
  |`agent-ledger --cap`|before every spawn|
21
21
  |`agent-score`|`gate <agent>` before every spawn; `accept`/`diagnose`/`penalty` after reviewing a result; `check` after every merge; `board` after a score change|
22
22
  |`brief-lint <plan.md>`|before every spawn on that plan|
@@ -21,6 +21,9 @@ paths:
21
21
  alert_state: "~/.cache/resource-alerts"
22
22
  snapshot_lock: "~/.cache/tmp-snapshot.lock"
23
23
 
24
+ # Which adapter (docs/adapter.md) serves runs, traces, launch, install and doctor.
25
+ harness: omp
26
+
24
27
  score:
25
28
  default_repo: ""
26
29
  default_branch: "" # no default: pass --branch (agent-score refuses to guess a branch)