neurastream 0.2.30 → 0.2.31

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.31",
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",
@@ -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|