neurastream 0.2.63 → 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 +97 -20
- 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 +6 -1
- package/src/core/guards.ts +171 -14
- package/src/core/notify.ts +76 -6
- 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/src/core/watch.ts +14 -2
- package/templates/config.yml +3 -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". */
|
|
@@ -243,7 +245,7 @@ export interface Config {
|
|
|
243
245
|
quota: { reset_tz: string; reset_pattern: string; label: string };
|
|
244
246
|
/** Chat notify (src/core/notify.ts): Main's final reply goes to these webhooks at session_stop.
|
|
245
247
|
* The values are paths to secret files holding the webhook URLs — never the URLs themselves. */
|
|
246
|
-
notify: { discord_webhook_file: string; slack_webhook_file: string; prefix: string };
|
|
248
|
+
notify: { discord_webhook_file: string; slack_webhook_file: string; prefix: string; /** Minutes a phone-page owner message may wait before the answer steer (P9; 0 = off). */ answer_within_min: number };
|
|
247
249
|
/** Content redaction (src/core/secret-redact.ts, plan 20261025_2204): every tool result, every
|
|
248
250
|
* notify post and `neurastream redact` go through it. Detection is by content, not file name. */
|
|
249
251
|
secrets: {
|
|
@@ -525,6 +527,8 @@ function check(cfg: Config): void {
|
|
|
525
527
|
}
|
|
526
528
|
const wc = cfg.write_check;
|
|
527
529
|
if (wc.applies_to !== "sub" && wc.applies_to !== "all") throw new ConfigError('write_check.applies_to must be "sub" or "all"');
|
|
530
|
+
if (!(Number.isFinite(cfg.notify.answer_within_min) && cfg.notify.answer_within_min >= 0))
|
|
531
|
+
throw new ConfigError("notify.answer_within_min must be a number >= 0 (minutes an owner message may wait; 0 = off)");
|
|
528
532
|
if (!(wc.timeout_ms > 0)) throw new ConfigError("write_check.timeout_ms must be > 0");
|
|
529
533
|
if (!Array.isArray(wc.linters)) throw new ConfigError("write_check.linters must be a list");
|
|
530
534
|
if (!Array.isArray(wc.defer_rules) || wc.defer_rules.some((r) => typeof r !== "string" || r === ""))
|
|
@@ -582,6 +586,7 @@ function check(cfg: Config): void {
|
|
|
582
586
|
if (!(cfg.guards.rate_limit.slack_s >= 0)) throw new ConfigError("guards.rate_limit.slack_s must be >= 0");
|
|
583
587
|
if (!(cfg.rollover.exit_grace_s > 0)) throw new ConfigError("rollover.exit_grace_s must be > 0");
|
|
584
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");
|
|
585
590
|
if (!(cfg.ui.port >= 1 && cfg.ui.port <= 65535)) throw new ConfigError("ui.port must be between 1 and 65535");
|
|
586
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");
|
|
587
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}`);
|
|
@@ -1075,12 +1106,33 @@ function runsCloser(input: Record<string, unknown>): boolean {
|
|
|
1075
1106
|
|
|
1076
1107
|
const bin = (w: string | undefined) => (w ?? "").replace(/^["']+|["']+$/g, "").split("/").pop() ?? "";
|
|
1077
1108
|
|
|
1109
|
+
// P5g (plan 20261027_0915): the shell text a call would really run — bash's command line, eval's
|
|
1110
|
+
// !cmd shell-escape lines and the Bun.$/spawn arguments inside its code. Everything else in an
|
|
1111
|
+
// input is prose or string data (a task brief, plan text, an eval cell that only names the page's
|
|
1112
|
+
// words), and prose runs nothing.
|
|
1113
|
+
function shellText(input: Record<string, unknown>): string {
|
|
1114
|
+
if (typeof input.command === "string") return input.command;
|
|
1115
|
+
const code = input.code;
|
|
1116
|
+
if (typeof code !== "string") return "";
|
|
1117
|
+
const out: string[] = [];
|
|
1118
|
+
for (const m of code.matchAll(/^[ \t]*!(.+)$/gm)) out.push(m[1] ?? "");
|
|
1119
|
+
for (const m of code.matchAll(/(?<!\w)(?:Bun\.)?\$[ \t]*`((?:[^`\\]|\\.)*)`/g)) out.push(m[1] ?? "");
|
|
1120
|
+
for (const m of code.matchAll(/\b(?:Bun\.)?spawn(?:Sync)?[ \t]*\(([^)]*)/g))
|
|
1121
|
+
out.push(
|
|
1122
|
+
[...(m[1] ?? "").matchAll(/[`"']([^`"']*)[`"']/g)]
|
|
1123
|
+
.map(s => s[1] ?? "")
|
|
1124
|
+
.join(" "),
|
|
1125
|
+
);
|
|
1126
|
+
return out.join("\n");
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1078
1129
|
// True when a command segment starts the owner page (plan 20261024_2230 P3c): `neurastream ui`
|
|
1079
1130
|
// serves it and `systemctl --user start/restart/enable` of neurastream-ui relaunches it — the
|
|
1080
|
-
// owner's systemd moves, never an agent's, unlocked or not.
|
|
1081
|
-
//
|
|
1131
|
+
// owner's systemd moves, never an agent's, unlocked or not. P5g: the text is shellText's — only
|
|
1132
|
+
// real shell commands, never prose. Segment splitting and launcher skipping match runsCloser, so
|
|
1133
|
+
// `sh -c "neurastream ui"` and `sudo systemctl --user ...` are seen.
|
|
1082
1134
|
function startsOwnerUi(input: Record<string, unknown>): boolean {
|
|
1083
|
-
const text =
|
|
1135
|
+
const text = shellText(input);
|
|
1084
1136
|
return text.split(/&&|\|\||;|\||\n|\$\(|`/).some(seg => {
|
|
1085
1137
|
const words = seg.trim().split(/\s+/).filter(Boolean).map(w => w.replace(/^["'(]+|["')]+$/g, ""));
|
|
1086
1138
|
let i = 0;
|
|
@@ -1096,6 +1148,22 @@ function startsOwnerUi(input: Record<string, unknown>): boolean {
|
|
|
1096
1148
|
});
|
|
1097
1149
|
}
|
|
1098
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
|
+
|
|
1099
1167
|
// True when a command segment lands work on a remote (plan 20261025_1940 P2): `git push`,
|
|
1100
1168
|
// `glab mr merge`, `gh pr merge`. Segment splitting and launcher skipping match startsOwnerUi,
|
|
1101
1169
|
// so `sh -c "git push"`, `sudo git push` and chained pushes are seen too.
|
|
@@ -1139,6 +1207,17 @@ function addedText(input: Record<string, unknown>): string {
|
|
|
1139
1207
|
.join("\n");
|
|
1140
1208
|
}
|
|
1141
1209
|
|
|
1210
|
+
// P5g: tools whose string fields are content — a task brief, the text a write or edit adds — are
|
|
1211
|
+
// prose, never reads; the notify-secret check scans only their path argument.
|
|
1212
|
+
const PROSE_TOOLS: Record<string, true> = { task: true, write: true, edit: true, ast_edit: true };
|
|
1213
|
+
|
|
1214
|
+
// Only a tool call's path arguments — the paths it names as targets, not its prose fields.
|
|
1215
|
+
function pathArgs(input: Record<string, unknown>): Record<string, unknown> {
|
|
1216
|
+
const out: Record<string, unknown> = {};
|
|
1217
|
+
for (const key of ["path", "file"]) if (typeof input[key] === "string") out[key] = input[key];
|
|
1218
|
+
return out;
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1142
1221
|
// Subagent half of a tool call (the original plan-guard checkCall without the main return).
|
|
1143
1222
|
// `cap` is the sub's hard call cap: its recorded per-spawn budget, else the global sub_max_calls.
|
|
1144
1223
|
function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[], writes: string[], cfg: Config, cap: number): string | null {
|
|
@@ -1289,6 +1368,13 @@ function taskLaunch(input: Record<string, unknown>, cfg: Config, runningJobs: st
|
|
|
1289
1368
|
log(cfg.paths.guard_log, `BLOCK spawn: ${why}`);
|
|
1290
1369
|
return why;
|
|
1291
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
|
+
}
|
|
1292
1378
|
recordSpawns(files, staffing);
|
|
1293
1379
|
recordBudgets(budgets);
|
|
1294
1380
|
return null;
|
|
@@ -1318,6 +1404,13 @@ function bypassLaunch(command: string, cfg: Config, spawner: Spawner): string |
|
|
|
1318
1404
|
}
|
|
1319
1405
|
const inc = incidentSpawnProblem("bypass launch", command, named, cfg);
|
|
1320
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
|
+
}
|
|
1321
1414
|
if (named.length) recordSpawns(named);
|
|
1322
1415
|
}
|
|
1323
1416
|
return null;
|
|
@@ -1423,6 +1516,12 @@ export function checkTool(e: ToolEvent, cfg: Config): Decision {
|
|
|
1423
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.",
|
|
1424
1517
|
);
|
|
1425
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
|
+
}
|
|
1426
1525
|
// The caller may know paths the text search cannot see (structured edits); union, never shrink.
|
|
1427
1526
|
const paths: string[] = [];
|
|
1428
1527
|
for (const p of [...(e.paths ?? []), ...q.touchedPaths(e.tool, input, e.cwd)]) if (!paths.includes(p)) paths.push(p);
|
|
@@ -1438,15 +1537,21 @@ export function checkTool(e: ToolEvent, cfg: Config): Decision {
|
|
|
1438
1537
|
}
|
|
1439
1538
|
// Notify secrets: no agent, main or sub, reads a webhook URL — with or without the unlock.
|
|
1440
1539
|
// A call that changes a secret is not a read: its target goes through the protected-write
|
|
1441
|
-
// rule above, so the owner's unlock covers it like any guard file.
|
|
1442
|
-
|
|
1540
|
+
// rule above, so the owner's unlock covers it like any guard file. P5g: the scan reads real
|
|
1541
|
+
// read targets only — naming a secret-shaped glob in a task brief or in plan text is prose,
|
|
1542
|
+
// not a read — so prose tools (task, write/edit) scan just their path argument, while every
|
|
1543
|
+
// other tool keeps the whole-input scan (glob/grep patterns arrive through it).
|
|
1544
|
+
const secretPaths: string[] = [];
|
|
1545
|
+
for (const p of [...(e.paths ?? []), ...q.touchedPaths(e.tool, PROSE_TOOLS[e.tool] === true ? pathArgs(input) : input, e.cwd)])
|
|
1546
|
+
if (!secretPaths.includes(p)) secretPaths.push(p);
|
|
1547
|
+
const secretHit = notifySecretReadHit(secretPaths.filter(p => !writes.includes(p)), cfg);
|
|
1443
1548
|
if (secretHit) {
|
|
1444
1549
|
log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} notify secret: ${secretHit}`);
|
|
1445
1550
|
return deny(`plan-guard: ${secretHit} is a notify secret path. Only the owner touches the webhook files, in a terminal.`);
|
|
1446
1551
|
}
|
|
1447
1552
|
// Main writes its own rollover note unattended (the note turn has nobody to ask). Only a Write
|
|
1448
1553
|
// of a .md directly in <state>/rollover/ is exempt; shell writes, subagents and relaunch.json stay refused.
|
|
1449
|
-
const rolloverDir = path.join(
|
|
1554
|
+
const rolloverDir = path.join(mainStateDir(cfg), "rollover");
|
|
1450
1555
|
const openWrites =
|
|
1451
1556
|
e.agent === "main" && e.tool === "write"
|
|
1452
1557
|
? writes.filter(p => !(path.extname(p) === ".md" && path.dirname(path.resolve(p)) === rolloverDir))
|
|
@@ -1593,6 +1698,42 @@ export function planReadNote(tool: string, input: Record<string, unknown>, cwd:
|
|
|
1593
1698
|
return `plan-guard: before you edit this plan, re-read: ${stale.join(", ")}`;
|
|
1594
1699
|
}
|
|
1595
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
|
+
|
|
1596
1737
|
/**
|
|
1597
1738
|
* spawn: the allow-list, task-only and open-plan gates for one implementer launch. Covers both
|
|
1598
1739
|
* original paths (the extension spawn event and a `task` tool call); the brief names the plan.
|
|
@@ -1635,6 +1776,11 @@ export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = d
|
|
|
1635
1776
|
}
|
|
1636
1777
|
return deny(`main-guard: ${verdict}`);
|
|
1637
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
|
+
}
|
|
1638
1784
|
// The owner's pick order and live provider state (plan 20261025_1700 P3), before the spawn records.
|
|
1639
1785
|
const staffing: Record<string, string[]> = {};
|
|
1640
1786
|
for (const f of named) staffing[f] = [e.agent];
|
|
@@ -1677,7 +1823,7 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
|
|
|
1677
1823
|
recordOwnerMessage(e.inject, cfg);
|
|
1678
1824
|
let summary: string;
|
|
1679
1825
|
try {
|
|
1680
|
-
summary = q.queueSummary(undefined, cfg.review.agents,
|
|
1826
|
+
summary = q.queueSummary(undefined, cfg.review.agents, claims(cfg));
|
|
1681
1827
|
} catch (err) {
|
|
1682
1828
|
summary = `Queue unreadable (${q.INDEX}): ${err}`;
|
|
1683
1829
|
}
|
|
@@ -1805,6 +1951,17 @@ function codeReviewProblem(file: string, after: string, ids: string[]): string |
|
|
|
1805
1951
|
// Main's plan text outside "## Progress" must rest on files Main read itself (planReadProblems).
|
|
1806
1952
|
// An empty `before` means the plan file did not exist yet; a refusal then deletes it.
|
|
1807
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
|
+
}
|
|
1808
1965
|
// A PLAN REVIEW or CODE REVIEW line (P6) is a review spawn's verdict (P4k): Main writes none, so its edit is restored.
|
|
1809
1966
|
if (newProgressEntries(e.before, e.after).some(b => REVIEW_LINE.test(b))) {
|
|
1810
1967
|
log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (Main wrote a review line)`);
|
package/src/core/notify.ts
CHANGED
|
@@ -4,8 +4,12 @@
|
|
|
4
4
|
// from them (guard rules in guards.ts), and does the posting. Plain TypeScript, no harness here.
|
|
5
5
|
|
|
6
6
|
import { dirname } from "node:path";
|
|
7
|
-
import { readFileSync, statSync } from "node:fs";
|
|
7
|
+
import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
8
8
|
import { configFile, type Config } from "./config.ts";
|
|
9
|
+
import { mainId } from "./guards.ts";
|
|
10
|
+
import { strftime } from "./clock.ts";
|
|
11
|
+
import { recentOwnerMessages, type MessageRow } from "./owner-ui.ts";
|
|
12
|
+
import { stateDirPath } from "./queue/lib.ts";
|
|
9
13
|
import { loadKnownSecrets, redactSecrets } from "./secret-redact.ts";
|
|
10
14
|
|
|
11
15
|
export type NotifyProviderName = "discord" | "slack";
|
|
@@ -42,10 +46,14 @@ function hitsSecret(p: string, file: string): boolean {
|
|
|
42
46
|
const m = GLOB_META.exec(p);
|
|
43
47
|
if (!m) return false;
|
|
44
48
|
const base = p.slice(0, m.index).replace(/\/+$/, "");
|
|
45
|
-
|
|
46
|
-
//
|
|
47
|
-
|
|
48
|
-
|
|
49
|
+
// The glob's literal prefix is the secrets dir or sits inside it: every match it can name is a
|
|
50
|
+
// secret (or reveals the directory listing).
|
|
51
|
+
if (base && (base === dir || base.startsWith(`${dir}/`))) return true;
|
|
52
|
+
// P5g: a wider glob refuses only when it actually matches a secret file or the secrets dir
|
|
53
|
+
// (Bun.Glob, filesystem-free, asked once per secret file and once per its directory), never
|
|
54
|
+
// by its prefix alone — a home-wide glob hunting an unrelated folder passes, and the cost
|
|
55
|
+
// stays bounded by the number of secret files, not by what the glob would expand to.
|
|
56
|
+
return new Bun.Glob(p).match(file) || new Bun.Glob(p).match(dir);
|
|
49
57
|
}
|
|
50
58
|
|
|
51
59
|
/** The first touched read path that hits a configured secret file, its directory, or a glob over
|
|
@@ -206,7 +214,7 @@ const enqueuePost = <T>(operation: () => Promise<T>): Promise<T> => {
|
|
|
206
214
|
export function postReply(text: string, cfg: Config): Promise<NotifyPostResult[]> {
|
|
207
215
|
return enqueuePost(async () => {
|
|
208
216
|
const providers = notifyProviders(cfg);
|
|
209
|
-
const body = cfg.notify.prefix ? `${cfg.notify.prefix} ${text}` : text
|
|
217
|
+
const body = cfg.notify.prefix ? `${cfg.notify.prefix} [${mainId()}] ${text}` : `[${mainId()}] ${text}`;
|
|
210
218
|
if (body.trim() === "") return providers.map(p => ({ provider: p.name, posted: false, chunks: 0, error: "empty reply; nothing posted" }));
|
|
211
219
|
// The chat is where a secret does its damage (plan 20261025_2204): a reply can carry a value
|
|
212
220
|
// the owner pasted or one the redactor's tool_result pass never saw, so the post is scrubbed
|
|
@@ -225,3 +233,65 @@ export function postReply(text: string, cfg: Config): Promise<NotifyPostResult[]
|
|
|
225
233
|
return out;
|
|
226
234
|
});
|
|
227
235
|
}
|
|
236
|
+
|
|
237
|
+
// ---- Owner answer steer (plan 20261027_1430 P9): a phone-page owner message must be answered
|
|
238
|
+
// by the next hand-back within notify.answer_within_min. The rule is host-neutral: core decides
|
|
239
|
+
// who is waiting and keeps the once-per-message markers; the harness adapter injects the steer
|
|
240
|
+
// at its tool_result hook and records the hand-back at its turn end. The markers live in a file
|
|
241
|
+
// under the queue state, not in session memory: one-shot CLI calls and a reloaded plugin must
|
|
242
|
+
// agree, like the guard window file.
|
|
243
|
+
|
|
244
|
+
function ownerAnswerStatePath(): string {
|
|
245
|
+
return `${stateDirPath()}/owner-answer.json`;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
interface OwnerAnswerState {
|
|
249
|
+
/** Unix seconds of the last hand-back; a message older than this was answered by it. */
|
|
250
|
+
lastHandBack: number;
|
|
251
|
+
/** Message ids this turn already steered, so a message steers once per turn. */
|
|
252
|
+
steered: string[];
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function readOwnerAnswerState(): OwnerAnswerState {
|
|
256
|
+
try {
|
|
257
|
+
const s = JSON.parse(readFileSync(ownerAnswerStatePath(), "utf8")) as Partial<OwnerAnswerState>;
|
|
258
|
+
return {
|
|
259
|
+
lastHandBack: Number(s.lastHandBack) || 0,
|
|
260
|
+
steered: Array.isArray(s.steered) ? s.steered.filter((x): x is string => typeof x === "string") : [],
|
|
261
|
+
};
|
|
262
|
+
} catch {
|
|
263
|
+
return { lastHandBack: 0, steered: [] };
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function writeOwnerAnswerState(state: OwnerAnswerState): void {
|
|
268
|
+
mkdirSync(stateDirPath(), { recursive: true });
|
|
269
|
+
writeFileSync(ownerAnswerStatePath(), `${JSON.stringify(state)}\n`);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** Phone-page owner messages waiting past notify.answer_within_min with no hand-back after them; none when the limit is 0. */
|
|
273
|
+
export function waitingOwnerMessages(cfg: Config, now: number): MessageRow[] {
|
|
274
|
+
const limit = cfg.notify.answer_within_min * 60;
|
|
275
|
+
if (!(limit > 0)) return [];
|
|
276
|
+
const { lastHandBack } = readOwnerAnswerState();
|
|
277
|
+
return recentOwnerMessages(now).filter((m) => now - m.ts > limit && m.ts > lastHandBack);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** The steer for every waiting message this turn has not steered yet — one line per message, so
|
|
281
|
+
* each owner ask lands once — or null when nobody is waiting. Marks the messages steered. */
|
|
282
|
+
export function ownerAnswerSteer(cfg: Config, now: number): string | null {
|
|
283
|
+
const limit = cfg.notify.answer_within_min * 60;
|
|
284
|
+
if (!(limit > 0)) return null;
|
|
285
|
+
const state = readOwnerAnswerState();
|
|
286
|
+
const due = recentOwnerMessages(now).filter((m) => now - m.ts > limit && m.ts > state.lastHandBack && !state.steered.includes(m.id));
|
|
287
|
+
if (due.length === 0) return null;
|
|
288
|
+
state.steered.push(...due.map((m) => m.id));
|
|
289
|
+
writeOwnerAnswerState(state);
|
|
290
|
+
return due.map((m) => `Owner asked at ${strftime(m.ts, "%H:%M")}; end your turn with the answer now`).join("\n");
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** A hand-back ends the wait: the reply just posted answers whatever waited, so the wait clears
|
|
294
|
+
* and the next owner message starts fresh. */
|
|
295
|
+
export function ownerAnswerHandback(now: number): void {
|
|
296
|
+
writeOwnerAnswerState({ lastHandBack: now, steered: [] });
|
|
297
|
+
}
|