neurastream 0.2.86 → 0.3.2
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 +22 -7
- package/package.json +1 -1
- package/src/adapters/omp/doctor.ts +10 -3
- package/src/adapters/omp/index.ts +21 -5
- package/src/cli/claim.ts +48 -17
- package/src/cli/dispatch.ts +23 -8
- package/src/cli/setup.ts +3 -3
- package/src/cli/team.ts +311 -0
- package/src/cli/workspace.ts +235 -0
- package/src/core/claims.ts +29 -11
- package/src/core/config.ts +16 -5
- package/src/core/guards.ts +182 -46
- package/src/core/incident-detectors.ts +1 -1
- package/src/core/mr-sweep.ts +33 -6
- package/src/core/owner-ui.ts +353 -132
- package/src/core/pages.ts +1 -1
- package/src/core/queue/lib.ts +23 -9
- package/src/core/queue-check.ts +5 -3
- package/src/core/queue-close.ts +3 -3
- package/src/core/team-client.ts +813 -0
- package/src/core/team-labels.ts +127 -0
- package/src/core/team-server.ts +1008 -0
- package/src/core/ui-setup.ts +186 -41
- package/templates/config.yml +5 -3
- package/templates/queue/TEMPLATE.md +2 -0
- package/templates/systemd/neurastream-workspace.service +17 -0
- package/src/cli/ui.ts +0 -104
- package/templates/systemd/neurastream-ui.service +0 -16
package/src/core/config.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { homedir } from "node:os";
|
|
|
6
6
|
import { dirname, join } from "node:path";
|
|
7
7
|
import { fileURLToPath } from "node:url";
|
|
8
8
|
import type { WriteCheckConfig } from "./write-check.ts";
|
|
9
|
+
import { teamConfigError } from "./team-labels.ts";
|
|
9
10
|
|
|
10
11
|
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
11
12
|
export const TEMPLATE_PATH = join(HERE, "../../templates/config.yml");
|
|
@@ -181,8 +182,10 @@ export interface Config {
|
|
|
181
182
|
/** The whole chat message that approves one push/merge in tier strict (default "go push"; matched case-insensitively with inner spaces collapsed). */
|
|
182
183
|
go_phrase: string;
|
|
183
184
|
};
|
|
184
|
-
/** The owner's phone page (`neurastream
|
|
185
|
-
|
|
185
|
+
/** The owner's phone page (`neurastream workspace`): binds the tailnet address only. */
|
|
186
|
+
workspace: { enabled: boolean; port: number; owner_login: string; allow_this_machine: boolean };
|
|
187
|
+
/** Repo labels: an origin matching `repos` may share plans that carry `Queue: team`. Empty = every repo is personal. max_share (optional, 0 < x <= 1) caps the team's share of today's model calls; absent = no cap. */
|
|
188
|
+
teams: { name: string; server: string; repos: string[]; max_share?: number }[];
|
|
186
189
|
/** Plan review gate (plan 20261028_1600): reuse lines and, from P2 on, the reviewer PASS lock. */
|
|
187
190
|
review: {
|
|
188
191
|
/** Agents a review spawn may run under: the PASS exemption needs one of these plus the brief's `Plan review: <plan>` line. An empty list turns only the `## Reuse` requirement off; the PASS gate follows `plan` (P6). */
|
|
@@ -638,7 +641,9 @@ function check(cfg: Config): void {
|
|
|
638
641
|
throw new ConfigError(`labels.${key} must be a list of non-empty regex strings`);
|
|
639
642
|
}
|
|
640
643
|
if (!(cfg.queue.claim_ttl_min >= 1)) throw new ConfigError("queue.claim_ttl_min must be >= 1");
|
|
641
|
-
if (!(cfg.
|
|
644
|
+
if (!(cfg.workspace.port >= 1 && cfg.workspace.port <= 65535)) throw new ConfigError("workspace.port must be between 1 and 65535");
|
|
645
|
+
const teamErr = teamConfigError(cfg.teams);
|
|
646
|
+
if (teamErr) throw new ConfigError(teamErr);
|
|
642
647
|
if (!Number.isInteger(cfg.pages.port) || cfg.pages.port < 1 || cfg.pages.port > 65535) throw new ConfigError("pages.port must be an integer between 1 and 65535");
|
|
643
648
|
if (typeof cfg.pages.dir !== "string" || cfg.pages.dir.length === 0) throw new ConfigError("pages.dir must be a non-empty path");
|
|
644
649
|
if (!Number.isInteger(cfg.pages.keep_days) || cfg.pages.keep_days < 1) throw new ConfigError("pages.keep_days must be an integer >= 1");
|
|
@@ -815,8 +820,9 @@ export interface LoadOptions {
|
|
|
815
820
|
template?: string;
|
|
816
821
|
}
|
|
817
822
|
|
|
818
|
-
// Old keys that still load, each with a notice to rename or delete it. "glm:" moves to "quota:"
|
|
819
|
-
//
|
|
823
|
+
// Old keys that still load, each with a notice to rename or delete it. "glm:" moves to "quota:" and
|
|
824
|
+
// "ui:" to "workspace:" only when the new key is absent; with both present, the old key stays and
|
|
825
|
+
// fails as an unknown key.
|
|
820
826
|
function migrateLegacy(user: Record<string, unknown>, file: string, notices: string[]): Record<string, unknown> {
|
|
821
827
|
const out = { ...user };
|
|
822
828
|
if ("glm" in out && !("quota" in out)) {
|
|
@@ -824,6 +830,11 @@ function migrateLegacy(user: Record<string, unknown>, file: string, notices: str
|
|
|
824
830
|
delete out.glm;
|
|
825
831
|
notices.push(`config "glm:" is now "quota:"; rename it in ${file}`);
|
|
826
832
|
}
|
|
833
|
+
if ("ui" in out && !("workspace" in out)) {
|
|
834
|
+
out.workspace = out.ui;
|
|
835
|
+
delete out.ui;
|
|
836
|
+
notices.push(`config "ui:" is now "workspace:"; rename it in ${file}`);
|
|
837
|
+
}
|
|
827
838
|
if ("pm" in out) {
|
|
828
839
|
delete out.pm;
|
|
829
840
|
notices.push(`config "pm:" was removed; delete it from ${file}`);
|
package/src/core/guards.ts
CHANGED
|
@@ -25,7 +25,7 @@ import { execFileSync } from "node:child_process";
|
|
|
25
25
|
import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
26
26
|
import { homedir } from "node:os";
|
|
27
27
|
import path from "node:path";
|
|
28
|
-
import type { Decision, InjectEvent, PlanEditEvent, SpawnEvent, StopEvent, ToolEvent } from "./adapter.ts";
|
|
28
|
+
import type { Decision, InjectEvent, PlanEditEvent, RunSource, SpawnEvent, StopEvent, ToolEvent } from "./adapter.ts";
|
|
29
29
|
import { currentPlanner, currentTier, takeGo } from "./autonomy.ts";
|
|
30
30
|
import { approvalProblem, MAIN_ONLY_LINE, reviewHash } from "./plan-approval.ts";
|
|
31
31
|
export { reviewHash };
|
|
@@ -38,7 +38,8 @@ import { unlandedRows } from "./wip-check.ts";
|
|
|
38
38
|
import * as q from "./queue/lib.ts";
|
|
39
39
|
import type { Plan } from "./queue/lib.ts";
|
|
40
40
|
|
|
41
|
-
import {
|
|
41
|
+
import { heldByOther, type Claim, type ClaimStore, type Unreachable } from "./claims.ts";
|
|
42
|
+
import { claimStoreFor, pathId, routeTeam, summaryHolder, teamDir, teamSummaryLines, teamViews, type TeamEntry } from "./team-client.ts";
|
|
42
43
|
import { nowSec, strftime } from "./clock.ts";
|
|
43
44
|
import { outUntil, pinModel, providerOfModel, readOut } from "./provider-state.ts";
|
|
44
45
|
import { lint } from "./brief-lint.ts";
|
|
@@ -307,7 +308,13 @@ function reviewRole(name: string | undefined, named: string[], brief: string, ag
|
|
|
307
308
|
const reviewed = named.filter(f => isReviewSpawn(f, brief, agent, cfg, spawner));
|
|
308
309
|
if (reviewed.length > 1) return { plan: null, problem: "a review spawn reviews one plan; split the spawn." };
|
|
309
310
|
if (reviewed.length && !name) return { plan: null, problem: "a review spawn needs a name (the task name keys its review lock)." };
|
|
310
|
-
|
|
311
|
+
const plan = reviewed[0] ?? null;
|
|
312
|
+
if (plan) {
|
|
313
|
+
const rec = readPlanReviews()[plan];
|
|
314
|
+
if (rec?.verdict === "PASS" && rec.hash === reviewHash(readPlanText(plan)))
|
|
315
|
+
return { plan: null, problem: `plan ${plan} already has a current reviewer PASS (by ${rec.by}); a second review is waste. Change the plan text, or spawn the implementer.` };
|
|
316
|
+
}
|
|
317
|
+
return { plan, problem: null };
|
|
311
318
|
}
|
|
312
319
|
|
|
313
320
|
/** P4f/P4k: the named review spawns, spawn name → its review role: the plan, the plan text and hash as the spawn first saw them, and the verdicts it wrote (review-spawns.json in the state dir). */
|
|
@@ -1205,11 +1212,12 @@ function shellText(input: Record<string, unknown>): string {
|
|
|
1205
1212
|
return out.join("\n");
|
|
1206
1213
|
}
|
|
1207
1214
|
|
|
1208
|
-
// True when a command segment starts the owner page (plan 20261024_2230 P3c): `neurastream
|
|
1209
|
-
// serves it and `systemctl --user start/restart/enable` of neurastream-
|
|
1210
|
-
// owner's systemd moves, never an agent's, unlocked or not. P5g: the text is
|
|
1211
|
-
// real shell commands, never prose. Segment splitting and launcher skipping
|
|
1212
|
-
// `sh -c "neurastream
|
|
1215
|
+
// True when a command segment starts the owner page (plan 20261024_2230 P3c): `neurastream
|
|
1216
|
+
// workspace` serves it and `systemctl --user start/restart/enable` of neurastream-workspace
|
|
1217
|
+
// relaunches it — the owner's systemd moves, never an agent's, unlocked or not. P5g: the text is
|
|
1218
|
+
// shellText's — only real shell commands, never prose. Segment splitting and launcher skipping
|
|
1219
|
+
// match runsCloser, so `sh -c "neurastream workspace"` and `sudo systemctl --user ...` are seen.
|
|
1220
|
+
// (The command and unit were `ui` before the workspace rename; that name is gone, no alias.)
|
|
1213
1221
|
function startsOwnerUi(input: Record<string, unknown>): boolean {
|
|
1214
1222
|
const text = shellText(input);
|
|
1215
1223
|
return text.split(/&&|\|\||;|\||\n|\$\(|`/).some(seg => {
|
|
@@ -1217,12 +1225,12 @@ function startsOwnerUi(input: Record<string, unknown>): boolean {
|
|
|
1217
1225
|
let i = 0;
|
|
1218
1226
|
while (i < words.length && (LAUNCHERS[words[i] ?? ""] === true || /^\w+=/.test(words[i] ?? "") || /(^|\/)main\.ts$/.test(words[i] ?? ""))) i++;
|
|
1219
1227
|
const cmd = bin(words[i]);
|
|
1220
|
-
if ((cmd === "
|
|
1228
|
+
if ((cmd === "workspace" && bin(words[i - 1]) === "neurastream") || (cmd === "neurastream" && bin(words[i + 1]) === "workspace")) return true;
|
|
1221
1229
|
return (
|
|
1222
1230
|
cmd === "systemctl" &&
|
|
1223
1231
|
words.some(w => w === "--user") &&
|
|
1224
1232
|
words.some(w => w === "start" || w === "restart" || w === "enable") &&
|
|
1225
|
-
words.some(w => bin(w) === "neurastream-
|
|
1233
|
+
words.some(w => bin(w) === "neurastream-workspace" || w.startsWith("neurastream-workspace."))
|
|
1226
1234
|
);
|
|
1227
1235
|
});
|
|
1228
1236
|
}
|
|
@@ -1480,7 +1488,7 @@ function incidentSpawnProblem(label: string, brief: string, namedPlans: string[]
|
|
|
1480
1488
|
* A `task` launch: the cancel check, the spawn gates, then the records. Main's and a sub's launch
|
|
1481
1489
|
* both come through here (plan 20261028_1600 P4i). Returns the refusal, or null.
|
|
1482
1490
|
*/
|
|
1483
|
-
function taskLaunch(input: Record<string, unknown>, cfg: Config, runningJobs: string[] | undefined, spawner: Spawner): string | null {
|
|
1491
|
+
function taskLaunch(input: Record<string, unknown>, cfg: Config, runningJobs: string[] | undefined, spawner: Spawner, runs?: RunSource): string | null {
|
|
1484
1492
|
const pending = q.cancelPending();
|
|
1485
1493
|
if (pending) {
|
|
1486
1494
|
log(cfg.paths.guard_log, `BLOCK spawn: cancel pending (${pending.words})`);
|
|
@@ -1498,7 +1506,13 @@ function taskLaunch(input: Record<string, unknown>, cfg: Config, runningJobs: st
|
|
|
1498
1506
|
}
|
|
1499
1507
|
const inc = incidentSpawnProblem("spawn", JSON.stringify(input), files, cfg);
|
|
1500
1508
|
if (inc) return inc;
|
|
1501
|
-
const
|
|
1509
|
+
const spawned: unknown[] = Array.isArray(input.tasks) ? input.tasks : [];
|
|
1510
|
+
const names = spawned.map((t) => (t as { name?: unknown } | null)?.name);
|
|
1511
|
+
const held = claimGate(files, cfg, {
|
|
1512
|
+
agentIds: names.filter((n): n is string => typeof n === "string" && n !== ""),
|
|
1513
|
+
unnamed: names.some((n) => typeof n !== "string" || n === ""),
|
|
1514
|
+
runs,
|
|
1515
|
+
});
|
|
1502
1516
|
if (held) {
|
|
1503
1517
|
log(cfg.paths.guard_log, `BLOCK spawn: ${held}`);
|
|
1504
1518
|
return held;
|
|
@@ -1512,7 +1526,7 @@ function taskLaunch(input: Record<string, unknown>, cfg: Config, runningJobs: st
|
|
|
1512
1526
|
* A shell launch of a bypass_spawn agent: the cancel check, the plan gate, the review PASS, the
|
|
1513
1527
|
* incidents, then the record. Main's and a sub's launch both come through here (plan 20261028_1600 P4i).
|
|
1514
1528
|
*/
|
|
1515
|
-
function bypassLaunch(command: string, cfg: Config, spawner: Spawner): string | null {
|
|
1529
|
+
function bypassLaunch(command: string, cfg: Config, spawner: Spawner, runs?: RunSource): string | null {
|
|
1516
1530
|
for (const entry of cfg.guards.bypass_spawn) {
|
|
1517
1531
|
if (!bypassRegExp(entry).test(command)) continue;
|
|
1518
1532
|
const pending = q.cancelPending();
|
|
@@ -1534,7 +1548,7 @@ function bypassLaunch(command: string, cfg: Config, spawner: Spawner): string |
|
|
|
1534
1548
|
if (inc) return inc;
|
|
1535
1549
|
// I-20261031-280: a bypass launch takes the claims like every other spawn, as its last
|
|
1536
1550
|
// refusal before the record.
|
|
1537
|
-
const held = claimGate(named, cfg);
|
|
1551
|
+
const held = claimGate(named, cfg, { agentIds: [], unnamed: true, runs });
|
|
1538
1552
|
if (held) {
|
|
1539
1553
|
log(cfg.paths.guard_log, `BLOCK bypass launch: ${held}`);
|
|
1540
1554
|
return held;
|
|
@@ -1544,9 +1558,9 @@ function bypassLaunch(command: string, cfg: Config, spawner: Spawner): string |
|
|
|
1544
1558
|
return null;
|
|
1545
1559
|
}
|
|
1546
1560
|
|
|
1547
|
-
function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config): Decision {
|
|
1561
|
+
function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config, runs?: RunSource): Decision {
|
|
1548
1562
|
if (e.tool === "task") {
|
|
1549
|
-
const why = taskLaunch(input, cfg, e.runningJobs, "main");
|
|
1563
|
+
const why = taskLaunch(input, cfg, e.runningJobs, "main", runs);
|
|
1550
1564
|
return why ? deny(`main-guard: ${why}`) : ALLOW;
|
|
1551
1565
|
}
|
|
1552
1566
|
if (cfg.guards.shell_tools.includes(e.tool)) {
|
|
@@ -1559,7 +1573,7 @@ function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config): De
|
|
|
1559
1573
|
return deny(`main-guard: tier strict — type "${cfg.autonomy.go_phrase}" to approve one push/merge`);
|
|
1560
1574
|
}
|
|
1561
1575
|
const command = String(input?.command ?? input?.code ?? "");
|
|
1562
|
-
const why = bypassLaunch(command, cfg, "main");
|
|
1576
|
+
const why = bypassLaunch(command, cfg, "main", runs);
|
|
1563
1577
|
if (why) return deny(`main-guard: ${why}`);
|
|
1564
1578
|
}
|
|
1565
1579
|
return editWindow(e, input, cfg);
|
|
@@ -1628,7 +1642,7 @@ export const MAIN_PLAN_FILE = /\/docs\/plans\/(?!archive\/)(?:[^/]+\/)*[^/]+\.md
|
|
|
1628
1642
|
* pre-tool: plan-guard checkCall for subs (protected files, budget, plan-edit rules, blockers)
|
|
1629
1643
|
* plus, for Main, the spawn gates and the project-file edit window.
|
|
1630
1644
|
*/
|
|
1631
|
-
export function checkTool(e: ToolEvent, cfg: Config): Decision {
|
|
1645
|
+
export function checkTool(e: ToolEvent, cfg: Config, runs?: RunSource): Decision {
|
|
1632
1646
|
const lock = e.agent === "sub" ? reviewLockProblem(e, cfg) : null;
|
|
1633
1647
|
if (lock) {
|
|
1634
1648
|
log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} review lock: ${lock}`);
|
|
@@ -1641,7 +1655,7 @@ export function checkTool(e: ToolEvent, cfg: Config): Decision {
|
|
|
1641
1655
|
if (cfg.guards.shell_tools.includes(e.tool) && startsOwnerUi(input)) {
|
|
1642
1656
|
log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} ui-start: ${String(input.command ?? "")}`);
|
|
1643
1657
|
return deny(
|
|
1644
|
-
"plan-guard: starting the owner page (neurastream
|
|
1658
|
+
"plan-guard: starting the owner page (neurastream workspace, or systemctl --user start/restart/enable of neurastream-workspace) is the owner's move, not an agent's.",
|
|
1645
1659
|
);
|
|
1646
1660
|
}
|
|
1647
1661
|
// claim release --force frees another Main's claim (plan 20261027_1300 P4): the owner's
|
|
@@ -1710,7 +1724,7 @@ export function checkTool(e: ToolEvent, cfg: Config): Decision {
|
|
|
1710
1724
|
log(cfg.paths.guard_log, `BLOCK tool=${e.tool} after ${readWindow().mainCalls} calls this turn`);
|
|
1711
1725
|
return deny(stop);
|
|
1712
1726
|
}
|
|
1713
|
-
const d = mainTool(e, input, cfg);
|
|
1727
|
+
const d = mainTool(e, input, cfg, runs);
|
|
1714
1728
|
if (!d.allow) return d;
|
|
1715
1729
|
const warn = mainCallWarn(e, cfg);
|
|
1716
1730
|
// A task brief names paths it does not read; only the other tools' paths count as reads.
|
|
@@ -1725,8 +1739,8 @@ export function checkTool(e: ToolEvent, cfg: Config): Decision {
|
|
|
1725
1739
|
}
|
|
1726
1740
|
// A sub's own launch passes the same spawn gates as Main's (plan 20261028_1600 P4i).
|
|
1727
1741
|
let launch: string | null = null;
|
|
1728
|
-
if (e.tool === "task") launch = taskLaunch(input, cfg, e.runningJobs, "sub");
|
|
1729
|
-
else if (cfg.guards.shell_tools.includes(e.tool)) launch = bypassLaunch(String(input?.command ?? input?.code ?? ""), cfg, "sub");
|
|
1742
|
+
if (e.tool === "task") launch = taskLaunch(input, cfg, e.runningJobs, "sub", runs);
|
|
1743
|
+
else if (cfg.guards.shell_tools.includes(e.tool)) launch = bypassLaunch(String(input?.command ?? input?.code ?? ""), cfg, "sub", runs);
|
|
1730
1744
|
if (launch) {
|
|
1731
1745
|
log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} ${launch}`);
|
|
1732
1746
|
return deny(`plan-guard: ${launch}`);
|
|
@@ -1826,16 +1840,10 @@ export function planReadNote(tool: string, input: Record<string, unknown>, cwd:
|
|
|
1826
1840
|
return `plan-guard: before you edit this plan, re-read: ${stale.join(", ")}`;
|
|
1827
1841
|
}
|
|
1828
1842
|
|
|
1829
|
-
/**
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
function claims(cfg: Config): ClaimStore {
|
|
1834
|
-
return fileClaimStore(cfg.paths.queue_state, nowSec, cfg.queue.claim_ttl_min);
|
|
1835
|
-
}
|
|
1836
|
-
|
|
1837
|
-
/** The held refusal (plan 20261027_1300 P3): "plan X is held by Main B since HH:MM" (HH:MM local). */
|
|
1838
|
-
function heldProblem(file: string, held: Claim): string {
|
|
1843
|
+
/** The held refusal (plan 20261027_1300 P3, widened 20261027_1305 P3): a down team server, another member's row, or today's "plan X is held by Main B since HH:MM" (HH:MM local). */
|
|
1844
|
+
function heldProblem(file: string, held: Claim | Unreachable): string {
|
|
1845
|
+
if ("unreachable" in held) return `team server ${held.unreachable} unreachable; plan ${file} is refused until it answers`;
|
|
1846
|
+
if (held.mine === false) return `plan ${file} is held by another member's Main ${held.main} since ${strftime(held.since, "%H:%M")}`;
|
|
1839
1847
|
return `plan ${file} is held by Main ${held.main} since ${strftime(held.since, "%H:%M")}`;
|
|
1840
1848
|
}
|
|
1841
1849
|
|
|
@@ -1844,29 +1852,142 @@ function heldProblem(file: string, held: Claim): string {
|
|
|
1844
1852
|
* another Main's live claim refuses the launch — a sub's launch too, once its Main no longer
|
|
1845
1853
|
* holds the claim. Returns the refusal, or null.
|
|
1846
1854
|
*/
|
|
1847
|
-
function claimGate(files: string[], cfg: Config): string | null {
|
|
1848
|
-
const
|
|
1855
|
+
function claimGate(files: string[], cfg: Config, spawn: SpawnIdent): string | null {
|
|
1856
|
+
const teams = routedTeams(files, cfg);
|
|
1857
|
+
const uncountable = teams.find(({ team }) => team.max_share !== undefined);
|
|
1858
|
+
if (spawn.unnamed && uncountable) {
|
|
1859
|
+
return `team ${uncountable.team.name} sets max_share: name this agent (tasks[].name) so its calls count against the team cap`;
|
|
1860
|
+
}
|
|
1849
1861
|
const mine = mainId();
|
|
1850
|
-
|
|
1862
|
+
// With the chooser each file has its own store; `fresh` carries the store beside each file,
|
|
1863
|
+
// so a fresh claim is released through the store that took it (a team claim released through
|
|
1864
|
+
// the file store would be a silent no-op that outlives the refusal until the TTL).
|
|
1865
|
+
const fresh: { file: string; store: ClaimStore }[] = [];
|
|
1866
|
+
// A refusal leaves the store as it found it: claims this call newly created are released
|
|
1867
|
+
// again through the store that took each one; a claim this Main already held before the
|
|
1868
|
+
// call stays.
|
|
1869
|
+
const releaseFresh = (): void => {
|
|
1870
|
+
for (const g of fresh) g.store.release(g.file, mine);
|
|
1871
|
+
};
|
|
1851
1872
|
for (const f of files) {
|
|
1852
|
-
const
|
|
1873
|
+
const store = claimStoreFor(f, cfg);
|
|
1874
|
+
const h = store.holder(f);
|
|
1875
|
+
// Fail closed: an unreachable server refuses the spawn and leaves no claim this call took.
|
|
1876
|
+
if (h !== null && "unreachable" in h) {
|
|
1877
|
+
releaseFresh();
|
|
1878
|
+
return heldProblem(f, h);
|
|
1879
|
+
}
|
|
1880
|
+
const heldBefore = h !== null && !heldByOther(h, mine);
|
|
1853
1881
|
const c = store.claim(f, mine);
|
|
1882
|
+
if ("unreachable" in c) {
|
|
1883
|
+
// The outage started between holder() and claim(): release what this call took.
|
|
1884
|
+
releaseFresh();
|
|
1885
|
+
return heldProblem(f, c);
|
|
1886
|
+
}
|
|
1854
1887
|
if ("heldBy" in c) {
|
|
1855
|
-
|
|
1856
|
-
// newly created are released again; a claim this Main already held before the call stays.
|
|
1857
|
-
for (const g of fresh) store.release(g, mine);
|
|
1888
|
+
releaseFresh();
|
|
1858
1889
|
return heldProblem(f, c.heldBy);
|
|
1859
1890
|
}
|
|
1860
|
-
if (!heldBefore) fresh.push(f);
|
|
1891
|
+
if (!heldBefore) fresh.push({ file: f, store });
|
|
1892
|
+
}
|
|
1893
|
+
const capped = teamCapProblem(teams, spawn, cfg);
|
|
1894
|
+
if (capped) {
|
|
1895
|
+
releaseFresh();
|
|
1896
|
+
return capped;
|
|
1861
1897
|
}
|
|
1898
|
+
recordTeamSpawns(teams, spawn.agentIds, cfg);
|
|
1862
1899
|
return null;
|
|
1863
1900
|
}
|
|
1864
1901
|
|
|
1902
|
+
/** A spawn's identity for the team cap: its named agents, and whether any spawned agent has no name (the cap cannot count it). */
|
|
1903
|
+
export interface SpawnIdent {
|
|
1904
|
+
agentIds: string[];
|
|
1905
|
+
unnamed: boolean;
|
|
1906
|
+
runs?: RunSource;
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
/** A plan file and the team it routes to. */
|
|
1910
|
+
export interface RoutedTeam {
|
|
1911
|
+
team: TeamEntry;
|
|
1912
|
+
file: string;
|
|
1913
|
+
}
|
|
1914
|
+
|
|
1915
|
+
function routedTeams(files: string[], cfg: Config): RoutedTeam[] {
|
|
1916
|
+
const out: RoutedTeam[] = [];
|
|
1917
|
+
for (const file of files) {
|
|
1918
|
+
const team = routeTeam(file, cfg, undefined, defaultRunner);
|
|
1919
|
+
if (team) out.push({ team, file });
|
|
1920
|
+
}
|
|
1921
|
+
return out;
|
|
1922
|
+
}
|
|
1923
|
+
|
|
1924
|
+
/** Epoch seconds at local midnight: the start of the cap's day. */
|
|
1925
|
+
function dayStartSec(): number {
|
|
1926
|
+
const d = new Date(nowSec() * 1000);
|
|
1927
|
+
d.setHours(0, 0, 0, 0);
|
|
1928
|
+
return d.getTime() / 1000;
|
|
1929
|
+
}
|
|
1930
|
+
|
|
1931
|
+
/** Agent ids recorded against a team's plans since `since`, from its spawns.jsonl rows; a corrupt row counts for nothing. */
|
|
1932
|
+
function teamAgentsSince(cfg: Config, team: TeamEntry, since: number): Set<string> {
|
|
1933
|
+
const ids = new Set<string>();
|
|
1934
|
+
let text: string;
|
|
1935
|
+
try {
|
|
1936
|
+
text = readFileSync(path.join(teamDir(cfg, team), "spawns.jsonl"), "utf8");
|
|
1937
|
+
} catch {
|
|
1938
|
+
return ids;
|
|
1939
|
+
}
|
|
1940
|
+
for (const line of text.split("\n")) {
|
|
1941
|
+
if (!line) continue;
|
|
1942
|
+
try {
|
|
1943
|
+
const row = JSON.parse(line) as { agentId?: unknown; at?: unknown };
|
|
1944
|
+
if (typeof row.agentId === "string" && typeof row.at === "number" && row.at >= since) ids.add(row.agentId);
|
|
1945
|
+
} catch {}
|
|
1946
|
+
}
|
|
1947
|
+
return ids;
|
|
1948
|
+
}
|
|
1949
|
+
|
|
1950
|
+
/** The team token cap (plan P6b2 d): a refusal when a capped team's calls today reach its max_share of all calls today. Null when no team is capped or it is under. */
|
|
1951
|
+
export function teamCapProblem(teams: RoutedTeam[], spawn: SpawnIdent, cfg: Config): string | null {
|
|
1952
|
+
const capped = teams.flatMap(({ team }) => (team.max_share === undefined ? [] : [{ team, cap: team.max_share }]));
|
|
1953
|
+
const [first] = capped;
|
|
1954
|
+
if (first === undefined) return null;
|
|
1955
|
+
if (!spawn.runs) return `team ${first.team.name} sets max_share: the cap cannot be computed without a run source`;
|
|
1956
|
+
const since = dayStartSec();
|
|
1957
|
+
const runs = spawn.runs.listRuns(since);
|
|
1958
|
+
const total = runs.reduce((sum, r) => sum + r.calls, 0);
|
|
1959
|
+
if (total === 0) return null;
|
|
1960
|
+
for (const { team, cap } of capped) {
|
|
1961
|
+
const ids = teamAgentsSince(cfg, team, since);
|
|
1962
|
+
const mine = runs.filter((r) => ids.has(r.id)).reduce((sum, r) => sum + r.calls, 0);
|
|
1963
|
+
if (mine / total >= cap) return `team ${team.name} cap reached: ${mine} of ${total} calls today (max_share ${cap}); team plans wait until local midnight`;
|
|
1964
|
+
}
|
|
1965
|
+
return null;
|
|
1966
|
+
}
|
|
1967
|
+
|
|
1968
|
+
/** Records each named agent against each team plan it spawned on, one spawns.jsonl row each, so the cap counts its calls. Rows are written only for team plans. */
|
|
1969
|
+
function recordTeamSpawns(teams: RoutedTeam[], agentIds: string[], cfg: Config): void {
|
|
1970
|
+
if (agentIds.length === 0) return;
|
|
1971
|
+
for (const { team, file } of teams) {
|
|
1972
|
+
const planId = pathId(team, cfg, file, defaultRunner);
|
|
1973
|
+
if (planId === null) continue;
|
|
1974
|
+
const dir = teamDir(cfg, team);
|
|
1975
|
+
const at = nowSec();
|
|
1976
|
+
const rows = agentIds.map((agentId) => `${JSON.stringify({ planId, agentId, at })}\n`).join("");
|
|
1977
|
+
try {
|
|
1978
|
+
mkdirSync(dir, { recursive: true });
|
|
1979
|
+
appendFileSync(path.join(dir, "spawns.jsonl"), rows);
|
|
1980
|
+
} catch (err) {
|
|
1981
|
+
log(cfg.paths.guard_log, `cannot record team spawn for ${team.name}: ${err}`);
|
|
1982
|
+
}
|
|
1983
|
+
}
|
|
1984
|
+
}
|
|
1985
|
+
|
|
1865
1986
|
/**
|
|
1866
1987
|
* spawn: the allow-list, task-only and open-plan gates for one implementer launch. Covers both
|
|
1867
1988
|
* original paths (the extension spawn event and a `task` tool call); the brief names the plan.
|
|
1868
1989
|
*/
|
|
1869
|
-
export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = defaultRunner): Decision {
|
|
1990
|
+
export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = defaultRunner, runs?: RunSource): Decision {
|
|
1870
1991
|
const pending = q.cancelPending();
|
|
1871
1992
|
if (pending) {
|
|
1872
1993
|
log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: cancel pending (${pending.words})`);
|
|
@@ -1914,7 +2035,7 @@ export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = d
|
|
|
1914
2035
|
}
|
|
1915
2036
|
return deny(`main-guard: ${verdict}`);
|
|
1916
2037
|
}
|
|
1917
|
-
const held = claimGate(named, cfg);
|
|
2038
|
+
const held = claimGate(named, cfg, { agentIds: e.name ? [e.name] : [], unnamed: !e.name, runs });
|
|
1918
2039
|
if (held) {
|
|
1919
2040
|
log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${held}`);
|
|
1920
2041
|
return deny(`main-guard: ${held}`);
|
|
@@ -1963,7 +2084,12 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
|
|
|
1963
2084
|
recordOwnerMessage(e.inject, cfg);
|
|
1964
2085
|
let summary: string;
|
|
1965
2086
|
try {
|
|
1966
|
-
|
|
2087
|
+
// P4 (20261027_1305): one GET /view per team, read once and handed to the holder and the
|
|
2088
|
+
// team lines, so the summary costs one request per team and never a second GET /claims.
|
|
2089
|
+
const views = teamViews(cfg);
|
|
2090
|
+
summary = q.queueSummary(undefined, cfg.review.agents, summaryHolder(cfg, {}, views));
|
|
2091
|
+
const teamLines = teamSummaryLines(cfg, views, q.SUMMARY_CAP);
|
|
2092
|
+
if (teamLines.length) summary += `\n${teamLines.join("\n")}`;
|
|
1967
2093
|
} catch (err) {
|
|
1968
2094
|
summary = `Queue unreadable (${q.INDEX}): ${err}`;
|
|
1969
2095
|
}
|
|
@@ -2144,9 +2270,19 @@ function checkMainPlan(e: PlanEditEvent, cfg: Config): PlanEditDecision {
|
|
|
2144
2270
|
};
|
|
2145
2271
|
}
|
|
2146
2272
|
// P3 (plan 20261027_1300): another Main's live claim on this plan refuses the edit, restored
|
|
2147
|
-
// like any refused plan edit. No claim — or this Main's own — edits freely.
|
|
2148
|
-
|
|
2149
|
-
|
|
2273
|
+
// like any refused plan edit. No claim — or this Main's own — edits freely. The chooser gets
|
|
2274
|
+
// `e.before` (the file on disk already holds the edit, so a team plan stays guarded while an
|
|
2275
|
+
// edit removes its header; the record rule covers it too).
|
|
2276
|
+
const holder = claimStoreFor(e.path, cfg, e.before).holder(e.path);
|
|
2277
|
+
if (holder !== null && "unreachable" in holder) {
|
|
2278
|
+
log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (team server ${holder.unreachable} unreachable)`);
|
|
2279
|
+
return {
|
|
2280
|
+
allow: false,
|
|
2281
|
+
reason: `plan-guard: ${heldProblem(e.path, holder)}; the file was restored.`,
|
|
2282
|
+
restore: { path: e.path, text: e.before || null },
|
|
2283
|
+
};
|
|
2284
|
+
}
|
|
2285
|
+
if (holder && heldByOther(holder, mainId())) {
|
|
2150
2286
|
log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (held by Main ${holder.main})`);
|
|
2151
2287
|
return {
|
|
2152
2288
|
allow: false,
|
|
@@ -141,7 +141,7 @@ export function blockLoop(blocks: GuardBlock[], now: number, repeat: number, win
|
|
|
141
141
|
const GUARD_BLOCK = /^(main|plan)-guard:/;
|
|
142
142
|
|
|
143
143
|
/** Token-set Jaccard similarity in [0, 1]. */
|
|
144
|
-
function jaccard(a: Set<string>, b: Set<string>): number {
|
|
144
|
+
export function jaccard(a: Set<string>, b: Set<string>): number {
|
|
145
145
|
let shared = 0;
|
|
146
146
|
for (const t of a) if (b.has(t)) shared++;
|
|
147
147
|
const union = a.size + b.size - shared;
|
package/src/core/mr-sweep.ts
CHANGED
|
@@ -80,6 +80,32 @@ export function remoteHost(url: string): string | null {
|
|
|
80
80
|
return null;
|
|
81
81
|
}
|
|
82
82
|
|
|
83
|
+
/** `host/path` of an origin URL (`git@host:path`, `ssh://`, `https://`), host lowercased, no `.git`. Null when it does not parse. */
|
|
84
|
+
export function remotePath(url: string): string | null {
|
|
85
|
+
const u = url.trim();
|
|
86
|
+
if (!u) return null;
|
|
87
|
+
let host: string | null = null;
|
|
88
|
+
let raw = "";
|
|
89
|
+
if (!u.includes("://")) {
|
|
90
|
+
const scp = /^[^@\s]+@([^:\s]+):(.+)$/.exec(u);
|
|
91
|
+
if (!scp?.[1] || !scp[2]) return null;
|
|
92
|
+
host = scp[1].toLowerCase();
|
|
93
|
+
raw = scp[2];
|
|
94
|
+
} else {
|
|
95
|
+
try {
|
|
96
|
+
const parsed = new URL(u);
|
|
97
|
+
host = parsed.hostname.toLowerCase() || null;
|
|
98
|
+
raw = parsed.pathname;
|
|
99
|
+
} catch {
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (!host) return null;
|
|
104
|
+
let p = raw.trim().replace(/^\/+/, "").replace(/\/+$/, "");
|
|
105
|
+
if (p.toLowerCase().endsWith(".git")) p = p.slice(0, -4).replace(/\/+$/, "");
|
|
106
|
+
return p ? `${host}/${p}` : null;
|
|
107
|
+
}
|
|
108
|
+
|
|
83
109
|
/** `gitlab` in the host → gitlab; `github` in the host → github; anything else is unknown. */
|
|
84
110
|
export function forgeOf(host: string): Forge | null {
|
|
85
111
|
const h = host.toLowerCase();
|
|
@@ -139,11 +165,11 @@ export function parseList(stdout: string): Record<string, unknown>[] | null {
|
|
|
139
165
|
interface Listed {
|
|
140
166
|
missing?: boolean;
|
|
141
167
|
fail?: boolean;
|
|
142
|
-
items: { number: number; branch: string }[];
|
|
168
|
+
items: { number: number; branch: string; title: string }[];
|
|
143
169
|
}
|
|
144
170
|
|
|
145
|
-
function takeItems(parsed: Record<string, unknown>[], numberKey: "iid" | "number", branchKeys: string[]): { number: number; branch: string }[] {
|
|
146
|
-
const items: { number: number; branch: string }[] = [];
|
|
171
|
+
function takeItems(parsed: Record<string, unknown>[], numberKey: "iid" | "number", branchKeys: string[]): { number: number; branch: string; title: string }[] {
|
|
172
|
+
const items: { number: number; branch: string; title: string }[] = [];
|
|
147
173
|
const seen = new Set<number>();
|
|
148
174
|
for (const item of parsed) {
|
|
149
175
|
const n = asNumber(item[numberKey] ?? item.number);
|
|
@@ -161,13 +187,13 @@ function takeItems(parsed: Record<string, unknown>[], numberKey: "iid" | "number
|
|
|
161
187
|
break;
|
|
162
188
|
}
|
|
163
189
|
}
|
|
164
|
-
items.push({ number: n, branch });
|
|
190
|
+
items.push({ number: n, branch, title: typeof item.title === "string" ? item.title : "" });
|
|
165
191
|
}
|
|
166
192
|
return items;
|
|
167
193
|
}
|
|
168
194
|
|
|
169
195
|
function listGitlab(repo: string, run: CommandRunner, env?: NodeJS.ProcessEnv): Listed {
|
|
170
|
-
const items: { number: number; branch: string }[] = [];
|
|
196
|
+
const items: { number: number; branch: string; title: string }[] = [];
|
|
171
197
|
const seen = new Set<number>();
|
|
172
198
|
for (let page = 1; page <= MAX_PAGES; page++) {
|
|
173
199
|
const r = run(["glab", "mr", "list", "-F", "json", "-P", String(PAGE), "-p", String(page)], { cwd: repo, env });
|
|
@@ -203,6 +229,7 @@ export interface OpenMr {
|
|
|
203
229
|
number: number;
|
|
204
230
|
token: string;
|
|
205
231
|
branch: string;
|
|
232
|
+
title: string;
|
|
206
233
|
}
|
|
207
234
|
|
|
208
235
|
/** `{ ok: false, why }` is the sweep's degrade: the caller logs it and never treats it as "no MRs". */
|
|
@@ -232,7 +259,7 @@ export function listOpenMrs(repo: string, run: CommandRunner = defaultRunner, en
|
|
|
232
259
|
return {
|
|
233
260
|
ok: true,
|
|
234
261
|
mrs: listed.items
|
|
235
|
-
.map(item => ({ forge, number: item.number, token: forge === "gitlab" ? `!${item.number}` : `#${item.number}`, branch: item.branch }))
|
|
262
|
+
.map(item => ({ forge, number: item.number, token: forge === "gitlab" ? `!${item.number}` : `#${item.number}`, branch: item.branch, title: item.title }))
|
|
236
263
|
.toSorted((a, b) => a.number - b.number),
|
|
237
264
|
};
|
|
238
265
|
}
|