neurastream 0.2.64 → 0.2.65
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 +1 -1
- package/src/adapters/omp/index.ts +84 -16
- package/src/adapters/omp/launch.ts +105 -52
- package/src/cli/claim.ts +79 -0
- package/src/cli/commands.ts +4 -0
- package/src/cli/dispatch.ts +4 -0
- package/src/core/brief-lint.ts +13 -6
- package/src/core/claims.ts +140 -0
- package/src/core/config.ts +3 -0
- package/src/core/guards.ts +128 -9
- package/src/core/notify.ts +2 -1
- package/src/core/owner-ui.ts +59 -20
- package/src/core/queue/lib.ts +23 -4
- package/src/core/queue-check.ts +5 -2
- package/src/core/queue-close.ts +6 -0
- package/src/core/rollover.ts +3 -3
- package/src/core/trace-actions.ts +9 -0
- package/templates/config.yml +2 -0
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// The claim store behind "several Mains, one queue, never the same plan twice"
|
|
2
|
+
// (plan 20261027_1300 P1): one JSON file per plan under <queue_state>/claims/, named by the
|
|
3
|
+
// sha256 of the plan path. Every read-modify-write runs while holding the store's flock
|
|
4
|
+
// (src/core/file-lock.ts) and releases it in finally, so racing processes serialize; the
|
|
5
|
+
// kernel frees the lock when a holder dies. Claim files are written to a temp file in the
|
|
6
|
+
// same directory and renameSync over the target, so a reader never sees a half-written claim.
|
|
7
|
+
import { createHash } from "node:crypto";
|
|
8
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { hostname } from "node:os";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import { lock } from "./file-lock.ts";
|
|
12
|
+
|
|
13
|
+
/** A plan one Main is working on. */
|
|
14
|
+
export interface Claim {
|
|
15
|
+
/** The plan path the claim is for. */
|
|
16
|
+
plan: string;
|
|
17
|
+
/** The Main id holding it. */
|
|
18
|
+
main: string;
|
|
19
|
+
host: string;
|
|
20
|
+
pid: number;
|
|
21
|
+
/** Unix seconds when the claim was taken (unchanged by heartbeats and re-claims). */
|
|
22
|
+
since: number;
|
|
23
|
+
/** Unix seconds of the last heartbeat or claim. */
|
|
24
|
+
beat: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The plan answer when another Main holds a live claim. */
|
|
28
|
+
export interface Held {
|
|
29
|
+
heldBy: Claim;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface ClaimStore {
|
|
33
|
+
claim(plan: string, main: string): Claim | Held;
|
|
34
|
+
/** The live claim for a plan, or null when it is free (absent, unreadable or expired). Read-only: no claim is taken. */
|
|
35
|
+
holder(plan: string): Claim | null;
|
|
36
|
+
heartbeat(plan: string, main: string): boolean;
|
|
37
|
+
release(plan: string, main: string): void;
|
|
38
|
+
list(): Claim[];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Claim files are only ever written by temp+rename under the lock, so an unreadable one
|
|
42
|
+
// means outside tampering; treating it as absent lets the next claim replace it.
|
|
43
|
+
function readClaim(path: string): Claim | null {
|
|
44
|
+
if (!existsSync(path)) return null;
|
|
45
|
+
try {
|
|
46
|
+
const c = JSON.parse(readFileSync(path, "utf8")) as Claim;
|
|
47
|
+
if (typeof c.main !== "string" || typeof c.beat !== "number" || typeof c.since !== "number") return null;
|
|
48
|
+
return c;
|
|
49
|
+
} catch {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function writeClaim(path: string, claim: Claim): void {
|
|
55
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
56
|
+
writeFileSync(tmp, JSON.stringify(claim));
|
|
57
|
+
renameSync(tmp, path);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The local file claim store. `ttlMin` is `queue.claim_ttl_min` — required, every caller passes
|
|
62
|
+
* the configured value (P1 review I-20261031-189): a claim whose `beat` is that many minutes old
|
|
63
|
+
* is free for takeover. The clock is injected in unix seconds (src/core/clock.ts convention) so
|
|
64
|
+
* tests never use real time.
|
|
65
|
+
*/
|
|
66
|
+
export function fileClaimStore(stateDir: string, clock: () => number, ttlMin: number): ClaimStore {
|
|
67
|
+
const dir = join(stateDir, "claims");
|
|
68
|
+
const lockPath = join(dir, ".lock");
|
|
69
|
+
|
|
70
|
+
function run<T>(fn: () => T): T {
|
|
71
|
+
mkdirSync(dir, { recursive: true });
|
|
72
|
+
const held = lock(lockPath);
|
|
73
|
+
try {
|
|
74
|
+
return fn();
|
|
75
|
+
} finally {
|
|
76
|
+
held.release();
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function fileFor(plan: string): string {
|
|
81
|
+
return join(dir, `${createHash("sha256").update(plan).digest("hex")}.json`);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function expired(c: Claim, now: number): boolean {
|
|
85
|
+
return now - c.beat >= ttlMin * 60;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return {
|
|
89
|
+
claim(plan, main) {
|
|
90
|
+
return run(() => {
|
|
91
|
+
const path = fileFor(plan);
|
|
92
|
+
const now = clock();
|
|
93
|
+
const cur = readClaim(path);
|
|
94
|
+
if (cur && cur.main === main) {
|
|
95
|
+
// The same main again: idempotent — `since` unchanged, `beat` refreshed.
|
|
96
|
+
const next = { ...cur, beat: now };
|
|
97
|
+
writeClaim(path, next);
|
|
98
|
+
return next;
|
|
99
|
+
}
|
|
100
|
+
if (cur && !expired(cur, now)) return { heldBy: cur };
|
|
101
|
+
const fresh: Claim = { plan, main, host: hostname(), pid: process.pid, since: now, beat: now };
|
|
102
|
+
writeClaim(path, fresh);
|
|
103
|
+
return fresh;
|
|
104
|
+
});
|
|
105
|
+
},
|
|
106
|
+
heartbeat(plan, main) {
|
|
107
|
+
return run(() => {
|
|
108
|
+
const path = fileFor(plan);
|
|
109
|
+
const cur = readClaim(path);
|
|
110
|
+
if (!cur || cur.main !== main) return false;
|
|
111
|
+
writeClaim(path, { ...cur, beat: clock() });
|
|
112
|
+
return true;
|
|
113
|
+
});
|
|
114
|
+
},
|
|
115
|
+
holder(plan) {
|
|
116
|
+
return run(() => {
|
|
117
|
+
const cur = readClaim(fileFor(plan));
|
|
118
|
+
return cur && !expired(cur, clock()) ? cur : null;
|
|
119
|
+
});
|
|
120
|
+
},
|
|
121
|
+
release(plan, main) {
|
|
122
|
+
run(() => {
|
|
123
|
+
const path = fileFor(plan);
|
|
124
|
+
const cur = readClaim(path);
|
|
125
|
+
if (cur && cur.main === main) rmSync(path);
|
|
126
|
+
});
|
|
127
|
+
},
|
|
128
|
+
list() {
|
|
129
|
+
return run(() => {
|
|
130
|
+
// A crashed writer leaves <claim>.<pid>.tmp behind; the next list sweeps it (the lock
|
|
131
|
+
// guarantees no live writer is mid-rename).
|
|
132
|
+
for (const f of readdirSync(dir)) if (f.endsWith(".tmp")) rmSync(join(dir, f), { force: true });
|
|
133
|
+
return readdirSync(dir)
|
|
134
|
+
.filter(f => f.endsWith(".json"))
|
|
135
|
+
.map(f => readClaim(join(dir, f)))
|
|
136
|
+
.filter((c): c is Claim => c !== null);
|
|
137
|
+
});
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
}
|
package/src/core/config.ts
CHANGED
|
@@ -107,6 +107,8 @@ export interface Config {
|
|
|
107
107
|
auto_close_min: number;
|
|
108
108
|
repo_index: string;
|
|
109
109
|
cancelled_rel: string;
|
|
110
|
+
/** Minutes without a heartbeat before a Main's plan claim frees (multi-main claims, src/core/claims.ts). */
|
|
111
|
+
claim_ttl_min: number;
|
|
110
112
|
/** How long a hold's `still true if` result is reused (src/core/waiting-check.ts). */
|
|
111
113
|
waiting_check_ttl_sec: number;
|
|
112
114
|
/** One hold check may run this long; a timeout is "unknown", never "stale". */
|
|
@@ -584,6 +586,7 @@ function check(cfg: Config): void {
|
|
|
584
586
|
if (!(cfg.guards.rate_limit.slack_s >= 0)) throw new ConfigError("guards.rate_limit.slack_s must be >= 0");
|
|
585
587
|
if (!(cfg.rollover.exit_grace_s > 0)) throw new ConfigError("rollover.exit_grace_s must be > 0");
|
|
586
588
|
if (!(cfg.metrics.report_days >= 1)) throw new ConfigError("metrics.report_days must be >= 1");
|
|
589
|
+
if (!(cfg.queue.claim_ttl_min >= 1)) throw new ConfigError("queue.claim_ttl_min must be >= 1");
|
|
587
590
|
if (!(cfg.ui.port >= 1 && cfg.ui.port <= 65535)) throw new ConfigError("ui.port must be between 1 and 65535");
|
|
588
591
|
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");
|
|
589
592
|
if (typeof cfg.pages.dir !== "string" || cfg.pages.dir.length === 0) throw new ConfigError("pages.dir must be a non-empty path");
|
package/src/core/guards.ts
CHANGED
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
// the stop is refused; an incident with a plan no longer blocks
|
|
23
23
|
|
|
24
24
|
import { execFileSync } from "node:child_process";
|
|
25
|
-
import { appendFileSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
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
28
|
import type { Decision, InjectEvent, PlanEditEvent, SpawnEvent, StopEvent, ToolEvent } from "./adapter.ts";
|
|
@@ -35,11 +35,11 @@ import { UNANSWERED_PREFIX } from "./rollover.ts";
|
|
|
35
35
|
import { notifyProtectedPaths, notifySecretReadHit } from "./notify.ts";
|
|
36
36
|
import { defaultRunner, listOpenMrs, mentioned, type CommandRunner, type OpenMr } from "./mr-sweep.ts";
|
|
37
37
|
import { unlandedRows } from "./wip-check.ts";
|
|
38
|
-
import { recheckHolds, staleFiles } from "./waiting-check.ts";
|
|
39
38
|
import * as q from "./queue/lib.ts";
|
|
40
39
|
import type { Plan } from "./queue/lib.ts";
|
|
41
40
|
|
|
42
|
-
import {
|
|
41
|
+
import { fileClaimStore, type Claim, type ClaimStore } from "./claims.ts";
|
|
42
|
+
import { nowSec, strftime } from "./clock.ts";
|
|
43
43
|
import { outUntil, pinModel, providerOfModel, readOut } from "./provider-state.ts";
|
|
44
44
|
import { lint } from "./brief-lint.ts";
|
|
45
45
|
const ALLOW: Decision = { allow: true, reason: "" };
|
|
@@ -66,10 +66,10 @@ function isPlanName(raw: string): boolean {
|
|
|
66
66
|
}
|
|
67
67
|
const PLAN_WRITE_TOOLS: Record<string, true> = { edit: true, write: true, ast_edit: true };
|
|
68
68
|
|
|
69
|
-
/** Guard-log line, `<ISO UTC> <line>`; a failed append is swallowed. */
|
|
69
|
+
/** Guard-log line, `<ISO UTC> [<main id>] <line>`; a failed append is swallowed. */
|
|
70
70
|
export function log(file: string, line: string): void {
|
|
71
71
|
try {
|
|
72
|
-
appendFileSync(file, `${new Date().toISOString()} ${line}\n`);
|
|
72
|
+
appendFileSync(file, `${new Date().toISOString()} [${mainId()}] ${line}\n`);
|
|
73
73
|
} catch {}
|
|
74
74
|
}
|
|
75
75
|
|
|
@@ -91,8 +91,39 @@ interface EditWindow {
|
|
|
91
91
|
mainCallsStart?: number;
|
|
92
92
|
}
|
|
93
93
|
|
|
94
|
+
// --- this Main's identity (plan 20261027_1300_multi_main P2) ---
|
|
95
|
+
|
|
96
|
+
/** What `neurastream main --name` accepts and what `NEURASTREAM_MAIN_ID` may hold. */
|
|
97
|
+
export const MAIN_ID_RE = /^[a-z0-9-]{1,24}$/;
|
|
98
|
+
|
|
99
|
+
/** This Main's id: the launcher sets `NEURASTREAM_MAIN_ID` (default `main`); a bogus value falls back to `main`. */
|
|
100
|
+
export function mainId(): string {
|
|
101
|
+
const id = process.env.NEURASTREAM_MAIN_ID ?? "main";
|
|
102
|
+
return MAIN_ID_RE.test(id) ? id : "main";
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** One-time move of the pre-multi-main top-level state into `mains/main/` (renameSync, idempotent). */
|
|
106
|
+
function moveLegacyState(stateDir: string, dir: string): void {
|
|
107
|
+
if (existsSync(dir)) return;
|
|
108
|
+
mkdirSync(dir, { recursive: true });
|
|
109
|
+
for (const name of ["edit-window.json", "rollover"]) {
|
|
110
|
+
try {
|
|
111
|
+
renameSync(path.join(stateDir, name), path.join(dir, name));
|
|
112
|
+
} catch {}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** This Main's own state dir, `<queue_state>/mains/<id>/`: edit window, rollover notes, running lock. */
|
|
117
|
+
export function mainStateDir(cfg?: Config): string {
|
|
118
|
+
const stateDir = cfg ? cfg.paths.queue_state : q.stateDirPath();
|
|
119
|
+
const id = mainId();
|
|
120
|
+
const dir = path.join(stateDir, "mains", id);
|
|
121
|
+
if (id === "main") moveLegacyState(stateDir, dir);
|
|
122
|
+
return dir;
|
|
123
|
+
}
|
|
124
|
+
|
|
94
125
|
function windowFile(): string {
|
|
95
|
-
return path.join(
|
|
126
|
+
return path.join(mainStateDir(), "edit-window.json");
|
|
96
127
|
}
|
|
97
128
|
|
|
98
129
|
export function readWindow(): EditWindow {
|
|
@@ -106,7 +137,7 @@ export function readWindow(): EditWindow {
|
|
|
106
137
|
|
|
107
138
|
export function writeWindow(w: EditWindow): void {
|
|
108
139
|
try {
|
|
109
|
-
mkdirSync(
|
|
140
|
+
mkdirSync(path.dirname(windowFile()), { recursive: true });
|
|
110
141
|
writeFileSync(windowFile(), JSON.stringify(w, null, 1));
|
|
111
142
|
} catch (err) {
|
|
112
143
|
log(`${q.STATE_DIR}/../main-guard.log`, `cannot write ${windowFile()}: ${err}`);
|
|
@@ -1117,6 +1148,22 @@ function startsOwnerUi(input: Record<string, unknown>): boolean {
|
|
|
1117
1148
|
});
|
|
1118
1149
|
}
|
|
1119
1150
|
|
|
1151
|
+
// True when a command segment runs `claim release <plan> --force` (plan 20261027_1300 P4): it
|
|
1152
|
+
// frees another Main's claim, the owner's terminal move, refused for every agent. Segment
|
|
1153
|
+
// splitting and launcher skipping match startsOwnerUi, so `sh -c "neurastream claim release x
|
|
1154
|
+
// --force"` and `sudo neurastream claim release x --force` are seen too.
|
|
1155
|
+
function forceClaimRelease(input: Record<string, unknown>): boolean {
|
|
1156
|
+
const text = Object.values(input).filter((v): v is string => typeof v === "string").join("\n");
|
|
1157
|
+
return text.split(/&&|\|\||;|\||\n|\$\(|`/).some(seg => {
|
|
1158
|
+
const words = seg.trim().split(/\s+/).filter(Boolean).map(w => w.replace(/^["'(]+|["')]+$/g, ""));
|
|
1159
|
+
let i = 0;
|
|
1160
|
+
while (i < words.length && (LAUNCHERS[words[i] ?? ""] === true || /^\w+=/.test(words[i] ?? "") || /(^|\/)main\.ts$/.test(words[i] ?? ""))) i++;
|
|
1161
|
+
const seq = words.slice(i).map(bin);
|
|
1162
|
+
if (seq[0] === "neurastream") seq.shift();
|
|
1163
|
+
return seq[0] === "claim" && seq.includes("release") && seq.includes("--force");
|
|
1164
|
+
});
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1120
1167
|
// True when a command segment lands work on a remote (plan 20261025_1940 P2): `git push`,
|
|
1121
1168
|
// `glab mr merge`, `gh pr merge`. Segment splitting and launcher skipping match startsOwnerUi,
|
|
1122
1169
|
// so `sh -c "git push"`, `sudo git push` and chained pushes are seen too.
|
|
@@ -1321,6 +1368,13 @@ function taskLaunch(input: Record<string, unknown>, cfg: Config, runningJobs: st
|
|
|
1321
1368
|
log(cfg.paths.guard_log, `BLOCK spawn: ${why}`);
|
|
1322
1369
|
return why;
|
|
1323
1370
|
}
|
|
1371
|
+
const inc = incidentSpawnProblem("spawn", JSON.stringify(input), files, cfg);
|
|
1372
|
+
if (inc) return inc;
|
|
1373
|
+
const held = claimGate(files, cfg);
|
|
1374
|
+
if (held) {
|
|
1375
|
+
log(cfg.paths.guard_log, `BLOCK spawn: ${held}`);
|
|
1376
|
+
return held;
|
|
1377
|
+
}
|
|
1324
1378
|
recordSpawns(files, staffing);
|
|
1325
1379
|
recordBudgets(budgets);
|
|
1326
1380
|
return null;
|
|
@@ -1350,6 +1404,13 @@ function bypassLaunch(command: string, cfg: Config, spawner: Spawner): string |
|
|
|
1350
1404
|
}
|
|
1351
1405
|
const inc = incidentSpawnProblem("bypass launch", command, named, cfg);
|
|
1352
1406
|
if (inc) return inc;
|
|
1407
|
+
// I-20261031-280: a bypass launch takes the claims like every other spawn, as its last
|
|
1408
|
+
// refusal before the record.
|
|
1409
|
+
const held = claimGate(named, cfg);
|
|
1410
|
+
if (held) {
|
|
1411
|
+
log(cfg.paths.guard_log, `BLOCK bypass launch: ${held}`);
|
|
1412
|
+
return held;
|
|
1413
|
+
}
|
|
1353
1414
|
if (named.length) recordSpawns(named);
|
|
1354
1415
|
}
|
|
1355
1416
|
return null;
|
|
@@ -1455,6 +1516,12 @@ export function checkTool(e: ToolEvent, cfg: Config): Decision {
|
|
|
1455
1516
|
"plan-guard: starting the owner page (neurastream ui, or systemctl --user start/restart/enable of neurastream-ui) is the owner's move, not an agent's.",
|
|
1456
1517
|
);
|
|
1457
1518
|
}
|
|
1519
|
+
// claim release --force frees another Main's claim (plan 20261027_1300 P4): the owner's
|
|
1520
|
+
// terminal move, refused for every agent like the ui-start, plan-guard style.
|
|
1521
|
+
if (cfg.guards.shell_tools.includes(e.tool) && forceClaimRelease(input)) {
|
|
1522
|
+
log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} claim-force: ${String(input.command ?? "")}`);
|
|
1523
|
+
return deny("plan-guard: claim release --force frees another Main's claim; that is the owner's move, in a terminal.");
|
|
1524
|
+
}
|
|
1458
1525
|
// The caller may know paths the text search cannot see (structured edits); union, never shrink.
|
|
1459
1526
|
const paths: string[] = [];
|
|
1460
1527
|
for (const p of [...(e.paths ?? []), ...q.touchedPaths(e.tool, input, e.cwd)]) if (!paths.includes(p)) paths.push(p);
|
|
@@ -1484,7 +1551,7 @@ export function checkTool(e: ToolEvent, cfg: Config): Decision {
|
|
|
1484
1551
|
}
|
|
1485
1552
|
// Main writes its own rollover note unattended (the note turn has nobody to ask). Only a Write
|
|
1486
1553
|
// of a .md directly in <state>/rollover/ is exempt; shell writes, subagents and relaunch.json stay refused.
|
|
1487
|
-
const rolloverDir = path.join(
|
|
1554
|
+
const rolloverDir = path.join(mainStateDir(cfg), "rollover");
|
|
1488
1555
|
const openWrites =
|
|
1489
1556
|
e.agent === "main" && e.tool === "write"
|
|
1490
1557
|
? writes.filter(p => !(path.extname(p) === ".md" && path.dirname(path.resolve(p)) === rolloverDir))
|
|
@@ -1631,6 +1698,42 @@ export function planReadNote(tool: string, input: Record<string, unknown>, cwd:
|
|
|
1631
1698
|
return `plan-guard: before you edit this plan, re-read: ${stale.join(", ")}`;
|
|
1632
1699
|
}
|
|
1633
1700
|
|
|
1701
|
+
/**
|
|
1702
|
+
* P3 (plan 20261027_1300): the claim store behind the spawn and Main edit gates. Claims live under
|
|
1703
|
+
* `<queue_state>/claims/`; the free-after TTL is queue.claim_ttl_min (never the store's default).
|
|
1704
|
+
*/
|
|
1705
|
+
function claims(cfg: Config): ClaimStore {
|
|
1706
|
+
return fileClaimStore(cfg.paths.queue_state, nowSec, cfg.queue.claim_ttl_min);
|
|
1707
|
+
}
|
|
1708
|
+
|
|
1709
|
+
/** The held refusal (plan 20261027_1300 P3): "plan X is held by Main B since HH:MM" (HH:MM local). */
|
|
1710
|
+
function heldProblem(file: string, held: Claim): string {
|
|
1711
|
+
return `plan ${file} is held by Main ${held.main} since ${strftime(held.since, "%H:%M")}`;
|
|
1712
|
+
}
|
|
1713
|
+
|
|
1714
|
+
/**
|
|
1715
|
+
* The spawn claim gate (plan 20261027_1300 P3): a spawn on a plan claims it for this Main first;
|
|
1716
|
+
* another Main's live claim refuses the launch — a sub's launch too, once its Main no longer
|
|
1717
|
+
* holds the claim. Returns the refusal, or null.
|
|
1718
|
+
*/
|
|
1719
|
+
function claimGate(files: string[], cfg: Config): string | null {
|
|
1720
|
+
const store = claims(cfg);
|
|
1721
|
+
const mine = mainId();
|
|
1722
|
+
const fresh: string[] = [];
|
|
1723
|
+
for (const f of files) {
|
|
1724
|
+
const heldBefore = store.holder(f)?.main === mine;
|
|
1725
|
+
const c = store.claim(f, mine);
|
|
1726
|
+
if ("heldBy" in c) {
|
|
1727
|
+
// A refusal leaves the store as it found it (P3 review finding 2): claims this call
|
|
1728
|
+
// newly created are released again; a claim this Main already held before the call stays.
|
|
1729
|
+
for (const g of fresh) store.release(g, mine);
|
|
1730
|
+
return heldProblem(f, c.heldBy);
|
|
1731
|
+
}
|
|
1732
|
+
if (!heldBefore) fresh.push(f);
|
|
1733
|
+
}
|
|
1734
|
+
return null;
|
|
1735
|
+
}
|
|
1736
|
+
|
|
1634
1737
|
/**
|
|
1635
1738
|
* spawn: the allow-list, task-only and open-plan gates for one implementer launch. Covers both
|
|
1636
1739
|
* original paths (the extension spawn event and a `task` tool call); the brief names the plan.
|
|
@@ -1673,6 +1776,11 @@ export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = d
|
|
|
1673
1776
|
}
|
|
1674
1777
|
return deny(`main-guard: ${verdict}`);
|
|
1675
1778
|
}
|
|
1779
|
+
const held = claimGate(named, cfg);
|
|
1780
|
+
if (held) {
|
|
1781
|
+
log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${held}`);
|
|
1782
|
+
return deny(`main-guard: ${held}`);
|
|
1783
|
+
}
|
|
1676
1784
|
// The owner's pick order and live provider state (plan 20261025_1700 P3), before the spawn records.
|
|
1677
1785
|
const staffing: Record<string, string[]> = {};
|
|
1678
1786
|
for (const f of named) staffing[f] = [e.agent];
|
|
@@ -1715,7 +1823,7 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
|
|
|
1715
1823
|
recordOwnerMessage(e.inject, cfg);
|
|
1716
1824
|
let summary: string;
|
|
1717
1825
|
try {
|
|
1718
|
-
summary = q.queueSummary(undefined, cfg.review.agents,
|
|
1826
|
+
summary = q.queueSummary(undefined, cfg.review.agents, claims(cfg));
|
|
1719
1827
|
} catch (err) {
|
|
1720
1828
|
summary = `Queue unreadable (${q.INDEX}): ${err}`;
|
|
1721
1829
|
}
|
|
@@ -1843,6 +1951,17 @@ function codeReviewProblem(file: string, after: string, ids: string[]): string |
|
|
|
1843
1951
|
// Main's plan text outside "## Progress" must rest on files Main read itself (planReadProblems).
|
|
1844
1952
|
// An empty `before` means the plan file did not exist yet; a refusal then deletes it.
|
|
1845
1953
|
function checkMainPlan(e: PlanEditEvent, cfg: Config): PlanEditDecision {
|
|
1954
|
+
// P3 (plan 20261027_1300): another Main's live claim on this plan refuses the edit, restored
|
|
1955
|
+
// like any refused plan edit. No claim — or this Main's own — edits freely.
|
|
1956
|
+
const holder = claims(cfg).holder(e.path);
|
|
1957
|
+
if (holder && holder.main !== mainId()) {
|
|
1958
|
+
log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (held by Main ${holder.main})`);
|
|
1959
|
+
return {
|
|
1960
|
+
allow: false,
|
|
1961
|
+
reason: `plan-guard: ${heldProblem(e.path, holder)}; the file was restored.`,
|
|
1962
|
+
restore: { path: e.path, text: e.before || null },
|
|
1963
|
+
};
|
|
1964
|
+
}
|
|
1846
1965
|
// A PLAN REVIEW or CODE REVIEW line (P6) is a review spawn's verdict (P4k): Main writes none, so its edit is restored.
|
|
1847
1966
|
if (newProgressEntries(e.before, e.after).some(b => REVIEW_LINE.test(b))) {
|
|
1848
1967
|
log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (Main wrote a review line)`);
|
package/src/core/notify.ts
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
import { dirname } from "node:path";
|
|
7
7
|
import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
8
8
|
import { configFile, type Config } from "./config.ts";
|
|
9
|
+
import { mainId } from "./guards.ts";
|
|
9
10
|
import { strftime } from "./clock.ts";
|
|
10
11
|
import { recentOwnerMessages, type MessageRow } from "./owner-ui.ts";
|
|
11
12
|
import { stateDirPath } from "./queue/lib.ts";
|
|
@@ -213,7 +214,7 @@ const enqueuePost = <T>(operation: () => Promise<T>): Promise<T> => {
|
|
|
213
214
|
export function postReply(text: string, cfg: Config): Promise<NotifyPostResult[]> {
|
|
214
215
|
return enqueuePost(async () => {
|
|
215
216
|
const providers = notifyProviders(cfg);
|
|
216
|
-
const body = cfg.notify.prefix ? `${cfg.notify.prefix} ${text}` : text
|
|
217
|
+
const body = cfg.notify.prefix ? `${cfg.notify.prefix} [${mainId()}] ${text}` : `[${mainId()}] ${text}`;
|
|
217
218
|
if (body.trim() === "") return providers.map(p => ({ provider: p.name, posted: false, chunks: 0, error: "empty reply; nothing posted" }));
|
|
218
219
|
// The chat is where a secret does its damage (plan 20261025_2204): a reply can carry a value
|
|
219
220
|
// the owner pasted or one the redactor's tool_result pass never saw, so the post is scrubbed
|
package/src/core/owner-ui.ts
CHANGED
|
@@ -13,12 +13,14 @@ import os from "node:os";
|
|
|
13
13
|
import { basename, resolve } from "node:path";
|
|
14
14
|
import type { RunSource } from "./adapter.ts";
|
|
15
15
|
import { chatTier, currentTier, type Tier } from "./autonomy.ts";
|
|
16
|
+
import { fileClaimStore } from "./claims.ts";
|
|
16
17
|
import type { Config } from "./config.ts";
|
|
17
18
|
import { nowSec, strftime } from "./clock.ts";
|
|
18
19
|
import { cpuCount } from "./host.ts";
|
|
19
20
|
import { dismissIncident, isFindingKind, openIncidents } from "./incidents.ts";
|
|
20
21
|
import { byText, knowledgeManifest, readKnowledgeTopicFile, urlField, urlValue, type KnowledgeEntry } from "./knowledge.ts";
|
|
21
|
-
import {
|
|
22
|
+
import { isBusy } from "./file-lock.ts";
|
|
23
|
+
import { log, MAIN_ID_RE } from "./guards.ts";
|
|
22
24
|
import { publishedPages } from "./pages-expiry.ts";
|
|
23
25
|
import { readMetricEvents } from "./metrics.ts";
|
|
24
26
|
import { activePlans, chatUnlock, dependencyOrderProblems, expandHome, gitTop, stateDirPath, unlockPath, writeIndex, type Plan } from "./queue/lib.ts";
|
|
@@ -156,6 +158,8 @@ export interface QueueRow {
|
|
|
156
158
|
waiting: boolean;
|
|
157
159
|
/** `Summary:` header, else the first Goal bullet with a leading Owner/INCIDENT prefix cut off. */
|
|
158
160
|
summary: string | null;
|
|
161
|
+
/** The Main id holding this plan's claim, else null (P5 multi-main). */
|
|
162
|
+
holder: string | null;
|
|
159
163
|
/** Chip text: waits you, waits on a plan, not started, phase K of N, or all N done. */
|
|
160
164
|
state: string;
|
|
161
165
|
}
|
|
@@ -256,15 +260,20 @@ function queueState(p: Plan, plans: Plan[]): string {
|
|
|
256
260
|
|
|
257
261
|
export function queueRows(cfg: Config): QueueRow[] {
|
|
258
262
|
const plans = activePlans(cfg.paths.queue_index).filter(p => p.status === "open");
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
263
|
+
const claims = fileClaimStore(cfg.paths.queue_state, nowSec, cfg.queue.claim_ttl_min);
|
|
264
|
+
return plans.map(p => {
|
|
265
|
+
const holder = claims.holder(p.file)?.main ?? null;
|
|
266
|
+
return {
|
|
267
|
+
repo: basename(p.repo),
|
|
268
|
+
file: p.file,
|
|
269
|
+
title: p.title,
|
|
270
|
+
status: p.status ?? "?",
|
|
271
|
+
waiting: p.waiting,
|
|
272
|
+
summary: p.summary ?? (goalSummary(p.goal[0] ?? "") || null),
|
|
273
|
+
state: queueState(p, plans),
|
|
274
|
+
holder,
|
|
275
|
+
};
|
|
276
|
+
});
|
|
268
277
|
}
|
|
269
278
|
|
|
270
279
|
export function ciRows(cfg: Config): CiRow[] {
|
|
@@ -382,6 +391,29 @@ function ownerMessagesDir(): string {
|
|
|
382
391
|
return `${stateDirPath()}/owner-messages`;
|
|
383
392
|
}
|
|
384
393
|
|
|
394
|
+
/** Main ids with a live running.lock in their main state dir (P5 multi-main): the page's picker list and the @-routing target set. */
|
|
395
|
+
export function runningMains(cfg: Config): string[] {
|
|
396
|
+
let dirs: string[];
|
|
397
|
+
try {
|
|
398
|
+
dirs = readdirSync(`${cfg.paths.queue_state}/mains`);
|
|
399
|
+
} catch {
|
|
400
|
+
return [];
|
|
401
|
+
}
|
|
402
|
+
return dirs
|
|
403
|
+
.filter(d => MAIN_ID_RE.test(d) && isBusy(`${cfg.paths.queue_state}/mains/${d}/running.lock`))
|
|
404
|
+
.toSorted();
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** Resolves where a message goes (P5 multi-main): an `@<id> ` prefix or the picker's `to` field names one running Main; empty is every Main. A stale target is refused before anything is stored. */
|
|
408
|
+
export function ownerMessageTarget(text: string, cfg: Config, formTo = ""): { to: string } | { refuse: string } {
|
|
409
|
+
const at = /^@([a-z0-9-]{1,24})(?:\s|$)/.exec(text);
|
|
410
|
+
const target = (at ? at[1] : formTo) ?? "";
|
|
411
|
+
if (!target || !MAIN_ID_RE.test(target)) return { to: "" };
|
|
412
|
+
const running = runningMains(cfg);
|
|
413
|
+
if (running.includes(target)) return { to: target };
|
|
414
|
+
return { refuse: `Main ${target} is not running; running: ${running.length ? running.join(", ") : "none"}` };
|
|
415
|
+
}
|
|
416
|
+
|
|
385
417
|
export interface MessageRow {
|
|
386
418
|
id: string;
|
|
387
419
|
ts: number;
|
|
@@ -466,9 +498,10 @@ export function recentOwnerMessages(now: number): MessageRow[] {
|
|
|
466
498
|
// ---- rendering (consumes the rows above, never the readers directly) ----
|
|
467
499
|
|
|
468
500
|
/** The "Tell Main" card: one textarea, image picks, a Send button — no chat thread. Under it, "Sent today": this view's messages newer than the keep window, newest first, thumbnails served from /message-image. */
|
|
469
|
-
function messageCard(messages: MessageRow[] | null): string {
|
|
501
|
+
function messageCard(messages: MessageRow[] | null, running: string[]): string {
|
|
470
502
|
const form = `<form class="msgform" method="post" action="/message" enctype="multipart/form-data">
|
|
471
503
|
<textarea name="text" maxlength="${MESSAGE_MAX}" rows="3" placeholder="What Main should know — a fix, a link, a photo"></textarea>
|
|
504
|
+
<select name="to"><option value="">All</option>${running.map(id => `<option value="${esc(id)}">Main ${esc(id)}</option>`).join("")}</select>
|
|
472
505
|
<input type="file" name="images" accept="image/*" multiple>
|
|
473
506
|
<button class="btn pri" type="submit">Send</button>
|
|
474
507
|
</form>`;
|
|
@@ -553,7 +586,7 @@ function queueHtml(rows: QueueRow[], tab: string): string {
|
|
|
553
586
|
<span class="qhandle" title="Drag to reorder" aria-label="Drag ${esc(r.title)}">≡</span>
|
|
554
587
|
<span class="qrank">${i + 1}</span>
|
|
555
588
|
<span class="qtitle">${esc(r.title)}${r.summary ? `<span class="qsum">${esc(r.summary)}</span>` : ""}</span>
|
|
556
|
-
<span class="chip ${r.state.startsWith("waits") ? "c-wait" : "c-ready"}">${esc(r.state)}</span>
|
|
589
|
+
${r.holder ? `<span class="chip c-held">Main ${esc(r.holder)}</span>` : ""}<span class="chip ${r.state.startsWith("waits") ? "c-wait" : "c-ready"}">${esc(r.state)}</span>
|
|
557
590
|
<span class="qbtns"><button type="button" class="qmove" data-move="top">↑ top</button><button type="button" class="qmove" data-move="up">↑</button><button type="button" class="qmove" data-move="down">↓</button></span>
|
|
558
591
|
</li>`,
|
|
559
592
|
)
|
|
@@ -1255,7 +1288,7 @@ export function renderPage(cfg: Config, data: PageData, params: URLSearchParams,
|
|
|
1255
1288
|
const machine = data.machine === null ? na("Machine") : machineHtml(cfg, data.machine);
|
|
1256
1289
|
const body =
|
|
1257
1290
|
tab === "now"
|
|
1258
|
-
? `${messageCard(data.messages)}
|
|
1291
|
+
? `${messageCard(data.messages, runningMains(cfg))}
|
|
1259
1292
|
<h1>Today</h1>
|
|
1260
1293
|
<p class="sub">What your agents did in the last 24 hours.</p>
|
|
1261
1294
|
<div class="card">
|
|
@@ -1385,6 +1418,7 @@ details.bg ul{margin:4px 0 8px;padding-left:20px;color:var(--mut);font-size:13px
|
|
|
1385
1418
|
.c-wait{background:color-mix(in srgb,var(--warn) 18%,transparent);color:var(--warn)}
|
|
1386
1419
|
.c-run{background:color-mix(in srgb,var(--teal) 18%,transparent);color:var(--teal)}
|
|
1387
1420
|
.c-ready{background:color-mix(in srgb,var(--mut) 15%,transparent);color:var(--mut)}
|
|
1421
|
+
.c-held{background:color-mix(in srgb,var(--acc) 15%,transparent);color:var(--acc)}
|
|
1388
1422
|
.chip.bad{color:var(--red)}
|
|
1389
1423
|
.qbtns{display:flex;gap:4px;flex-wrap:wrap;margin-left:auto}
|
|
1390
1424
|
.qbtns button{min-height:32px;padding:2px 10px;font-size:12px;border-radius:999px;border:1px solid var(--bd);background:var(--card);color:var(--mut)}
|
|
@@ -1520,13 +1554,13 @@ function handleIncident(cfg: Config, fields: Record<string, string>, login: stri
|
|
|
1520
1554
|
if (wantsJson) return jsonSent("incident-closed", receiptText("incident-closed", new URLSearchParams()));
|
|
1521
1555
|
return redirect(sentTo(fields.tab ?? "", "sent=incident-closed"));
|
|
1522
1556
|
}
|
|
1523
|
-
storeOwnerMessage(`${id}: it's a bug — plan it`, login, []);
|
|
1557
|
+
storeOwnerMessage(`${id}: it's a bug — plan it`, login, [], "");
|
|
1524
1558
|
if (wantsJson) return jsonSent("incident-bug", receiptText("incident-bug", new URLSearchParams()));
|
|
1525
1559
|
return redirect(sentTo(fields.tab ?? "", "sent=incident-bug"));
|
|
1526
1560
|
}
|
|
1527
1561
|
|
|
1528
1562
|
/** Stores an owner message (text and images) under a new id and inboxes it for Main (P13/P14). */
|
|
1529
|
-
function storeOwnerMessage(text: string, login: string, images: { bytes: Uint8Array; kind: string }[]): void {
|
|
1563
|
+
function storeOwnerMessage(text: string, login: string, images: { bytes: Uint8Array; kind: string }[], to: string): void {
|
|
1530
1564
|
const ts = nowSec();
|
|
1531
1565
|
// The dir name starts with a whole-second ts: the sweep and the image route both parse it.
|
|
1532
1566
|
const id = `${Math.floor(ts)}-${randomUUID().slice(0, 6)}`;
|
|
@@ -1538,21 +1572,23 @@ function storeOwnerMessage(text: string, login: string, images: { bytes: Uint8Ar
|
|
|
1538
1572
|
writeFileSync(`${dir}/${name}`, images[i]!.bytes);
|
|
1539
1573
|
names.push(name);
|
|
1540
1574
|
}
|
|
1541
|
-
writeFileSync(`${dir}/message.json`, `${JSON.stringify({ ts, text, login, images: names })}\n`);
|
|
1575
|
+
writeFileSync(`${dir}/message.json`, `${JSON.stringify({ ts, text, login, to, images: names })}\n`);
|
|
1542
1576
|
mkdirSync(stateDirPath(), { recursive: true });
|
|
1543
1577
|
// The text stays out of owner-inbox.jsonl; Main reads message.json through the id (P14).
|
|
1544
|
-
appendFileSync(inboxPath(), `${JSON.stringify({ ts, kind: "message", id, login })}\n`);
|
|
1578
|
+
appendFileSync(inboxPath(), `${JSON.stringify({ ts, kind: "message", id, login, to })}\n`);
|
|
1545
1579
|
}
|
|
1546
1580
|
|
|
1547
1581
|
// ---- POST /message (plan P13): the owner's one-way note plus images, inboxed by id ----
|
|
1548
1582
|
|
|
1549
|
-
async function handleMessage(req: Request, login: string, wantsJson: boolean): Promise<Response> {
|
|
1583
|
+
async function handleMessage(req: Request, cfg: Config, login: string, wantsJson: boolean): Promise<Response> {
|
|
1550
1584
|
sweepOwnerMessages(nowSec());
|
|
1551
1585
|
const form = await req.formData();
|
|
1552
1586
|
let text = "";
|
|
1587
|
+
let toField = "";
|
|
1553
1588
|
const files: File[] = [];
|
|
1554
1589
|
for (const [key, value] of form.entries()) {
|
|
1555
1590
|
if (key === "text" && typeof value === "string") text = value.trim();
|
|
1591
|
+
else if (key === "to" && typeof value === "string") toField = value;
|
|
1556
1592
|
// A form sent with no file chosen still carries one empty, nameless file part (Bun parses it as a nameless Blob).
|
|
1557
1593
|
else if (key === "images" && (value as unknown) instanceof Blob) {
|
|
1558
1594
|
const part = value as unknown as File;
|
|
@@ -1571,7 +1607,10 @@ async function handleMessage(req: Request, login: string, wantsJson: boolean): P
|
|
|
1571
1607
|
if (!kind) return fail("attachments must be PNG, JPEG, GIF or WEBP images — the type is read from the file itself");
|
|
1572
1608
|
images.push({ bytes: data, kind });
|
|
1573
1609
|
}
|
|
1574
|
-
|
|
1610
|
+
// P5: an `@<id>` prefix or the picker's to field names one Main; a stale name is refused before anything is stored.
|
|
1611
|
+
const pick = ownerMessageTarget(text, cfg, toField);
|
|
1612
|
+
if ("refuse" in pick) return fail(pick.refuse);
|
|
1613
|
+
storeOwnerMessage(text, login, images, pick.to);
|
|
1575
1614
|
if (wantsJson) return jsonSent("message", receiptText("message", new URLSearchParams()));
|
|
1576
1615
|
return redirect("/?sent=message");
|
|
1577
1616
|
}
|
|
@@ -1816,7 +1855,7 @@ res = pageRes(cfg, source, url.searchParams, resultsBuild, pagesHost);
|
|
|
1816
1855
|
// The page's script asks for JSON on every POST (P11b); a no-JS form post gets today's 303s.
|
|
1817
1856
|
const wantsJson = (req.headers.get("accept") ?? "").includes("application/json");
|
|
1818
1857
|
if (url.pathname === "/message") {
|
|
1819
|
-
res = await handleMessage(req, login, wantsJson);
|
|
1858
|
+
res = await handleMessage(req, cfg, login, wantsJson);
|
|
1820
1859
|
code = res.status;
|
|
1821
1860
|
} else if (url.pathname === "/incident") {
|
|
1822
1861
|
res = handleIncident(cfg, await fieldsOf(req), login, wantsJson);
|