neurastream 0.3.20 → 0.3.21
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/index.ts +3 -2
- package/src/adapters/omp/adapter.ts +2 -1
- package/src/adapters/omp/auto-close.ts +64 -0
- package/src/adapters/omp/chat-commands.ts +161 -0
- package/src/adapters/omp/inbox.ts +221 -0
- package/src/adapters/omp/index.ts +115 -1039
- package/src/adapters/omp/launch.ts +31 -3
- package/src/adapters/omp/rate-limit-controller.ts +196 -0
- package/src/adapters/omp/rollover-controller.ts +334 -0
- package/src/adapters/omp/types.ts +143 -0
- package/src/cli/commands.ts +33 -2
- package/src/cli/dispatch.ts +37 -16
- package/src/cli/recall.ts +3 -2
- package/src/cli/results-build.ts +1 -1
- package/src/cli/workspace.ts +13 -2
- package/src/core/adapter.ts +16 -0
- package/src/core/blockers.ts +326 -30
- package/src/core/file-lock.ts +71 -12
- package/src/core/guards/plan-edit.ts +338 -0
- package/src/core/guards/planner.ts +70 -0
- package/src/core/guards/review.ts +391 -0
- package/src/core/guards/spawn.ts +699 -0
- package/src/core/guards/state.ts +581 -0
- package/src/core/guards/stop.ts +235 -0
- package/src/core/guards/tool.ts +541 -0
- package/src/core/guards.ts +12 -2658
- package/src/core/incidents.ts +125 -91
- package/src/core/machine-guard.ts +23 -5
- package/src/core/main-start.ts +10 -8
- package/src/core/owner-topics.ts +2 -13
- package/src/core/owner-ui/auth.ts +164 -0
- package/src/core/owner-ui/data.ts +437 -0
- package/src/core/owner-ui/handlers.ts +250 -0
- package/src/core/owner-ui/messages.ts +209 -0
- package/src/core/owner-ui/render.ts +714 -0
- package/src/core/owner-ui/results.ts +266 -0
- package/src/core/owner-ui/server.ts +142 -0
- package/src/core/owner-ui.ts +11 -2121
- package/src/core/page-notes.ts +25 -0
- package/src/core/pages.ts +452 -77
- package/src/core/plan-approval.ts +12 -14
- package/src/core/queue/lib.ts +88 -39
- package/src/core/queue-cancel.ts +21 -17
- package/src/core/queue-close.ts +48 -23
- package/src/core/secret-redact.ts +65 -14
- package/src/core/tailscale.ts +79 -3
- package/src/core/team-client.ts +13 -2
- package/src/core/uninstall.ts +2 -0
package/src/core/guards.ts
CHANGED
|
@@ -1,2658 +1,12 @@
|
|
|
1
|
-
// Guard rules
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
// through the same plan gate, cancel-pending blocks spawns and stops, keep-working stop rule;
|
|
14
|
-
// tier strict additionally refuses `git push` / `glab mr merge` / `gh pr merge` until the
|
|
15
|
-
// owner's one-shot `go`, and tier full lets a `Priority skip: <plan> — Main: "<reason>"` line
|
|
16
|
-
// past the priority gate
|
|
17
|
-
// - incidents: while an incident is open (src/core/incidents.ts: no plan/dismiss/fixed record)
|
|
18
|
-
// every Main prompt lists it, a spawn must be fix work (its plan cites `INCIDENT <id>`), and
|
|
19
|
-
// the stop is refused; an incident with a plan no longer blocks
|
|
20
|
-
|
|
21
|
-
import { execFileSync } from "node:child_process";
|
|
22
|
-
import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
23
|
-
import { homedir } from "node:os";
|
|
24
|
-
import path from "node:path";
|
|
25
|
-
import type { Decision, InjectEvent, PlanEditEvent, RunSource, SpawnEvent, StopEvent, ToolEvent } from "./adapter.ts";
|
|
26
|
-
import { currentPlanner, currentTier, takeGo } from "./autonomy.ts";
|
|
27
|
-
import { approvalProblem, MAIN_ONLY_LINE, reviewHash } from "./plan-approval.ts";
|
|
28
|
-
export { reviewHash };
|
|
29
|
-
import type { Config } from "./config.ts";
|
|
30
|
-
import { openIncidents, ownerMessagesFile, ownerSaid, readOwnerAnswers, readOwnerMessages, type IncidentView, type OwnerMessage, writeOwnerStore } from "./incidents.ts";
|
|
31
|
-
import { ownerText, UNANSWERED_PREFIX } from "./rollover.ts";
|
|
32
|
-
import { ownerLogFile, recordOwnerLog } from "./owner-log.ts";
|
|
33
|
-
import { levelFor, readLevels } from "./rule-levels.ts";
|
|
34
|
-
import { notifyProtectedPaths, notifySecretReadHit } from "./notify.ts";
|
|
35
|
-
import { defaultRunner, listOpenMrs, mentioned, type CommandRunner, type OpenMr } from "./mr-sweep.ts";
|
|
36
|
-
import { unlandedRows } from "./wip-check.ts";
|
|
37
|
-
import * as q from "./queue/lib.ts";
|
|
38
|
-
import type { Plan } from "./queue/lib.ts";
|
|
39
|
-
|
|
40
|
-
import { heldByOther, type Claim, type ClaimStore, type Unreachable } from "./claims.ts";
|
|
41
|
-
import { claimStoreFor, pathId, routeTeam, summaryHolder, teamDir, teamSummaryLines, teamViews, type TeamEntry } from "./team-client.ts";
|
|
42
|
-
import { nowSec, strftime } from "./clock.ts";
|
|
43
|
-
import { outUntil, pinModel, providerOfModel, readOut } from "./provider-state.ts";
|
|
44
|
-
import { lint } from "./brief-lint.ts";
|
|
45
|
-
import { removalFlags, stagedDiff, type RemovalFlag } from "./diff-check.ts";
|
|
46
|
-
const ALLOW: Decision = { allow: true, reason: "" };
|
|
47
|
-
|
|
48
|
-
/**
|
|
49
|
-
* The plan-edit decision: a Decision plus the allow-with-amendment fields of the plan-read guard
|
|
50
|
-
* (I-20261025-208). On allow, `rewrite` names the file the caller writes back (the auto-listed
|
|
51
|
-
* read section) and `note` is the receipt for the tool result; both travel through the guard
|
|
52
|
-
* CLI's JSON output. They live here, not on the shared Decision, so every other check keeps the
|
|
53
|
-
* plain shape.
|
|
54
|
-
*/
|
|
55
|
-
export interface PlanEditDecision extends Decision {
|
|
56
|
-
rewrite?: { path: string; text: string };
|
|
57
|
-
note?: string;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/** Every refusal names its guard rule id (plan 20261110_1746 P8a); the id ends the text as ` [rule <id>]`. */
|
|
61
|
-
function deny(reason: string, rule: string): Decision {
|
|
62
|
-
return { allow: false, reason: `${reason} [rule ${rule}]` };
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
/** A raw target that names a plan: under a docs/plans/ directory, or a plan file name (YYYYMMDD_HHMM_*.md). */
|
|
66
|
-
function isPlanName(raw: string): boolean {
|
|
67
|
-
return /(^|\/)docs\/plans\//.test(raw) || /^\d{8}_\d{4}_[^/]*\.md$/.test(raw.split("/").pop() ?? "");
|
|
68
|
-
}
|
|
69
|
-
const PLAN_WRITE_TOOLS: Record<string, true> = { edit: true, write: true, ast_edit: true };
|
|
70
|
-
|
|
71
|
-
/** Guard-log line, `<ISO UTC> [<main id>] <line>`; a failed append is swallowed. */
|
|
72
|
-
export function log(file: string, line: string): void {
|
|
73
|
-
try {
|
|
74
|
-
appendFileSync(file, `${new Date().toISOString()} [${mainId()}] ${line}\n`);
|
|
75
|
-
} catch {}
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
// Owner message that may call work off ("don't do X" must hold even if no plan
|
|
79
|
-
// exists yet). Flagged until Main records it with queue-cancel; no spawn and no stop until then.
|
|
80
|
-
export const CANCEL_TODO =
|
|
81
|
-
'the owner\'s message may call work off. Record it first: an indexed plan → `queue-cancel <plan> "<owner words>"`; ' +
|
|
82
|
-
'work with no plan (yet) → `queue-cancel --never "<what must not be done>" "<owner words>" [--repo <repo>]`; ' +
|
|
83
|
-
'nothing was called off → `queue-cancel --not-a-cancel "<why>"`.';
|
|
84
|
-
|
|
85
|
-
// --- state the decisions keep in the queue state dir (survives one-shot CLI calls) ---
|
|
86
|
-
|
|
87
|
-
interface EditWindow {
|
|
88
|
-
used: string[];
|
|
89
|
-
windowStart: number;
|
|
90
|
-
/** Main tool calls since the last owner prompt or terminal hand-back (main_call_exempt_tools never count). */
|
|
91
|
-
mainCalls: number;
|
|
92
|
-
/** When the first of those calls was counted; the count expires MAIN_CALLS_RESET_SEC later. */
|
|
93
|
-
mainCallsStart?: number;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
// --- this Main's identity (plan 20261027_1300_multi_main P2) ---
|
|
97
|
-
|
|
98
|
-
/** What `neurastream main --name` accepts and what `NEURASTREAM_MAIN_ID` may hold. */
|
|
99
|
-
export const MAIN_ID_RE = /^[a-z0-9-]{1,24}$/;
|
|
100
|
-
|
|
101
|
-
/** This Main's id: the launcher sets `NEURASTREAM_MAIN_ID` (default `main`); a bogus value falls back to `main`. */
|
|
102
|
-
export function mainId(): string {
|
|
103
|
-
const id = process.env.NEURASTREAM_MAIN_ID ?? "main";
|
|
104
|
-
return MAIN_ID_RE.test(id) ? id : "main";
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
/** One-time move of the pre-multi-main top-level state into `mains/main/` (renameSync, idempotent). */
|
|
108
|
-
function moveLegacyState(stateDir: string, dir: string): void {
|
|
109
|
-
if (existsSync(dir)) return;
|
|
110
|
-
mkdirSync(dir, { recursive: true });
|
|
111
|
-
for (const name of ["edit-window.json", "rollover"]) {
|
|
112
|
-
try {
|
|
113
|
-
renameSync(path.join(stateDir, name), path.join(dir, name));
|
|
114
|
-
} catch {}
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
/** This Main's own state dir, `<queue_state>/mains/<id>/`: edit window, rollover notes, running lock. */
|
|
119
|
-
export function mainStateDir(cfgOrPaths: Config | Pick<q.QueuePaths, "queue_state">): string {
|
|
120
|
-
const stateDir = "paths" in cfgOrPaths ? cfgOrPaths.paths.queue_state : cfgOrPaths.queue_state;
|
|
121
|
-
const id = mainId();
|
|
122
|
-
const dir = path.join(stateDir, "mains", id);
|
|
123
|
-
if (id === "main") moveLegacyState(stateDir, dir);
|
|
124
|
-
return dir;
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
function windowFile(paths: Pick<q.QueuePaths, "queue_state">): string {
|
|
128
|
-
return path.join(mainStateDir(paths), "edit-window.json");
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
export function readWindow(paths: Pick<q.QueuePaths, "queue_state">): EditWindow {
|
|
132
|
-
try {
|
|
133
|
-
const w = JSON.parse(readFileSync(windowFile(paths), "utf8")) as Partial<EditWindow>;
|
|
134
|
-
if (Array.isArray(w.used) && typeof w.windowStart === "number")
|
|
135
|
-
return { used: w.used, windowStart: w.windowStart, mainCalls: typeof w.mainCalls === "number" ? w.mainCalls : 0, mainCallsStart: typeof w.mainCallsStart === "number" ? w.mainCallsStart : 0 };
|
|
136
|
-
} catch {}
|
|
137
|
-
return { used: [], windowStart: 0, mainCalls: 0 };
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
export function writeWindow(w: EditWindow, paths: Pick<q.QueuePaths, "queue_state">): void {
|
|
141
|
-
const file = windowFile(paths);
|
|
142
|
-
try {
|
|
143
|
-
mkdirSync(path.dirname(file), { recursive: true });
|
|
144
|
-
writeFileSync(file, JSON.stringify(w, null, 1));
|
|
145
|
-
} catch (err) {
|
|
146
|
-
log(`${paths.queue_state}/../main-guard.log`, `cannot write ${file}: ${err}`);
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
// --- plan review gate state (plan 20261028_1600): the open-MR cache beside the edit window ---
|
|
151
|
-
|
|
152
|
-
interface MrCache {
|
|
153
|
-
at: number;
|
|
154
|
-
repos: Record<string, OpenMr[]>;
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
function mrCacheFile(paths: Pick<q.QueuePaths, "queue_state">): string {
|
|
158
|
-
return path.join(paths.queue_state, "mr-cache.json");
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
function readMrCache(paths: Pick<q.QueuePaths, "queue_state">): MrCache {
|
|
162
|
-
try {
|
|
163
|
-
const c = JSON.parse(readFileSync(mrCacheFile(paths), "utf8")) as MrCache;
|
|
164
|
-
if (typeof c.at === "number" && c.repos && typeof c.repos === "object") return c;
|
|
165
|
-
} catch {}
|
|
166
|
-
return { at: 0, repos: {} };
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
function writeMrCache(c: MrCache, cfg: Config): void {
|
|
170
|
-
try {
|
|
171
|
-
mkdirSync(cfg.paths.queue_state, { recursive: true });
|
|
172
|
-
writeFileSync(mrCacheFile(cfg.paths), JSON.stringify(c, null, 1));
|
|
173
|
-
} catch (err) {
|
|
174
|
-
log(cfg.paths.guard_log, `cannot write ${mrCacheFile(cfg.paths)}: ${err}`);
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
// --- plan review gate state (plan 20261028_1600): the reviewer PASS record beside the edit window ---
|
|
179
|
-
|
|
180
|
-
interface PlanReview {
|
|
181
|
-
verdict: "PASS" | "FAIL";
|
|
182
|
-
hash: string;
|
|
183
|
-
finding: string;
|
|
184
|
-
at: number;
|
|
185
|
-
by?: string;
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
/** A CODE REVIEW record (P6): the plan phase ids (P1, P4a, …) the entry names, for the tick gate. */
|
|
189
|
-
interface CodeReview extends PlanReview {
|
|
190
|
-
phases: string[];
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
function planReviewsFile(paths: Pick<q.QueuePaths, "queue_state">): string {
|
|
194
|
-
return path.join(paths.queue_state, "plan-reviews.json");
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
function readPlanReviews(paths: Pick<q.QueuePaths, "queue_state">): Record<string, PlanReview> {
|
|
198
|
-
try {
|
|
199
|
-
const r = JSON.parse(readFileSync(planReviewsFile(paths), "utf8")) as { reviews?: Record<string, PlanReview> };
|
|
200
|
-
if (r.reviews && typeof r.reviews === "object") return r.reviews;
|
|
201
|
-
} catch {}
|
|
202
|
-
return {};
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
function readCodeReviews(paths: Pick<q.QueuePaths, "queue_state">): Record<string, CodeReview> {
|
|
206
|
-
try {
|
|
207
|
-
const r = JSON.parse(readFileSync(planReviewsFile(paths), "utf8")) as { code?: Record<string, CodeReview> };
|
|
208
|
-
if (r.code && typeof r.code === "object") return r.code;
|
|
209
|
-
} catch {}
|
|
210
|
-
return {};
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
function writePlanReviews(reviews: Record<string, PlanReview>, code: Record<string, CodeReview>, cfg: Config): void {
|
|
214
|
-
try {
|
|
215
|
-
mkdirSync(cfg.paths.queue_state, { recursive: true });
|
|
216
|
-
writeFileSync(planReviewsFile(cfg.paths), JSON.stringify({ reviews, code }, null, 1));
|
|
217
|
-
} catch (err) {
|
|
218
|
-
log(cfg.paths.plan_guard_log, `cannot write ${planReviewsFile(cfg.paths)}: ${err}`);
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
/** The progress entry that records a review — PLAN for the spawn gate, CODE for the phase tick gate (P6); only a subagent's edit can carry one. The verdict is the match, never a substring. The time may carry a `~` and a zone word (`~23:35 CET`); the author segment may carry a note (`Rev (re-verify): `) because the recorded name comes from the spawn, never from the line. */
|
|
223
|
-
const REVIEW_LINE = /^- (?:\d{4}-\d{2}-\d{2} ~?\d{2}:\d{2}(?: [A-Z]{2,5})? [^:\n]+?: )?(PLAN|CODE) REVIEW: (PASS|FAIL)\b/;
|
|
224
|
-
/** Any entry that opens like a review line; one that REVIEW_LINE does not match is restored, not recorded. */
|
|
225
|
-
const REVIEW_LOOKALIKE = /^- (?:\d{4}-\d{2}-\d{2} ~?\d{2}:\d{2}(?: [A-Z]{2,5})? [^:\n]+?: )?(PLAN|CODE) REVIEW\b/;
|
|
226
|
-
|
|
227
|
-
/** Who launches an agent: Main's launch may use a plan review's exemption, a sub's never may (plan 20261028_1600 P4i). */
|
|
228
|
-
export type Spawner = "main" | "sub";
|
|
229
|
-
|
|
230
|
-
/**
|
|
231
|
-
* P2 (plan 20261028_1600): a spawn on a plan needs a recorded reviewer PASS whose hash still
|
|
232
|
-
* matches the plan text — progress-only edits keep a PASS valid, any other change expires it,
|
|
233
|
-
* a FAIL is denied with its first finding. A review spawn itself — an agent from review.agents
|
|
234
|
-
* whose brief has the `Plan review: <plan>` line — is exempt when Main launches it. P5 removed
|
|
235
|
-
* the cutover: every named plan is gated. review.plan: false skips the gate (P6); an empty
|
|
236
|
-
* review.agents list no longer turns it off.
|
|
237
|
-
*/
|
|
238
|
-
export function reviewPassProblem(named: string[], brief: string, agent: string, cfg: Config, spawner: Spawner): string | null {
|
|
239
|
-
if (!cfg.review.plan) return null; // P6: review.plan: false skips the PASS gate; an empty review.agents list no longer does
|
|
240
|
-
const reviews = readPlanReviews(cfg.paths);
|
|
241
|
-
for (const file of named) {
|
|
242
|
-
if (isReviewSpawn(file, brief, agent, cfg, spawner)) continue;
|
|
243
|
-
const rec = reviews[file];
|
|
244
|
-
if (!rec) return `plan ${file} has no current reviewer PASS. Spawn a reviewer with templates/plan-review-brief.md.`;
|
|
245
|
-
if (rec.verdict === "FAIL")
|
|
246
|
-
return `plan ${file} has no current reviewer PASS (FAIL: ${rec.finding || "no finding recorded"}). Spawn a reviewer with templates/plan-review-brief.md.`;
|
|
247
|
-
let text = "";
|
|
248
|
-
try {
|
|
249
|
-
text = readFileSync(file, "utf8");
|
|
250
|
-
} catch {}
|
|
251
|
-
if (rec.hash !== reviewHash(text))
|
|
252
|
-
return `plan ${file} has no current reviewer PASS (changed since review). Spawn a reviewer with templates/plan-review-brief.md.`;
|
|
253
|
-
}
|
|
254
|
-
return null;
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
/** A subagent's `PLAN REVIEW` or `CODE REVIEW` (P6) entry records the review of the plan it edited; Main's edit path never reaches this. */
|
|
258
|
-
function recordReviews(e: PlanEditEvent, cfg: Config): void {
|
|
259
|
-
const entries = newProgressEntries(e.before, e.after).filter(b => REVIEW_LINE.test(b));
|
|
260
|
-
if (!entries.length) return;
|
|
261
|
-
const spawns = readReviewSpawns(cfg.paths);
|
|
262
|
-
const found = matchReviewSpawn(spawns, e.agentId ?? "");
|
|
263
|
-
if (!found) return;
|
|
264
|
-
const { name, spawn } = found;
|
|
265
|
-
const reviews = readPlanReviews(cfg.paths);
|
|
266
|
-
const code = readCodeReviews(cfg.paths);
|
|
267
|
-
for (const block of entries) {
|
|
268
|
-
const kind = REVIEW_LINE.exec(block)![1];
|
|
269
|
-
const repeat = spawn.verdicts > 0;
|
|
270
|
-
spawn.verdicts++;
|
|
271
|
-
const at = nowSec();
|
|
272
|
-
// Judged against the plan as the spawn first saw it (P4k): a plan that moved during the review cannot pass.
|
|
273
|
-
const record: PlanReview = repeat
|
|
274
|
-
? { verdict: "FAIL", hash: spawn.hash, finding: "review spawn wrote 2 verdicts", at, by: name }
|
|
275
|
-
: reviewHash(e.after) !== spawn.hash
|
|
276
|
-
? { verdict: "FAIL", hash: spawn.hash, finding: "plan changed during review", at, by: name }
|
|
277
|
-
: { verdict: REVIEW_LINE.exec(block)![2] === "PASS" ? "PASS" : "FAIL", hash: spawn.hash, finding: findingsValue(block) ?? "", at, by: name };
|
|
278
|
-
// A CODE REVIEW record covers only the phases the verdict names before its Findings line: a phase in the Findings text ("see P2") is a reference, not coverage; an entry without a Findings line covers nothing.
|
|
279
|
-
if (kind === "CODE") {
|
|
280
|
-
const head = block.slice(0, Math.max(block.indexOf("Findings:"), 0));
|
|
281
|
-
code[e.path] = { ...record, phases: [...new Set([...head.matchAll(/\bP\d+[a-z]?\b/g)].map(m => m[0]))] };
|
|
282
|
-
} else reviews[e.path] = record;
|
|
283
|
-
}
|
|
284
|
-
writePlanReviews(reviews, code, cfg);
|
|
285
|
-
writeReviewSpawns(spawns, cfg.paths);
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
/** P4k backstop, at a sub agent's end: a named review spawn whose PLAN REVIEW line reached no edit (a path the write targets miss) is recorded here. Returns Main's note when the spawn wrote no verdict at all. */
|
|
289
|
-
export function reviewSpawnEnd(agentId: string, cfg: Config): string | null {
|
|
290
|
-
const found = matchReviewSpawn(readReviewSpawns(cfg.paths), agentId);
|
|
291
|
-
if (!found || found.spawn.verdicts > 0) return null;
|
|
292
|
-
const { name, spawn } = found;
|
|
293
|
-
const after = readPlanText(spawn.plan);
|
|
294
|
-
if (newProgressEntries(spawn.text, after).some(b => REVIEW_LINE.test(b))) {
|
|
295
|
-
recordReviews({ path: spawn.plan, before: spawn.text, after, agent: "sub", agentId: name }, cfg);
|
|
296
|
-
return null;
|
|
297
|
-
}
|
|
298
|
-
return `${name} wrote no verdict on ${spawn.plan}.`;
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
/** P4f: a `Plan review: <plan>` brief from Main, by a configured review agent (the exemption from the plan gate). */
|
|
302
|
-
function isReviewSpawn(file: string, brief: string, agent: string, cfg: Config, spawner: Spawner): boolean {
|
|
303
|
-
const reviewLines = brief.split("\n").filter(l => l.startsWith("Plan review:"));
|
|
304
|
-
return spawner === "main" && cfg.review.agents.includes(agent) && reviewLines.some(l => l.slice("Plan review:".length).trim() === file);
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
/** P4f: the review role of one task: the plan it reviews (null for other spawns). A review spawn needs a name, the name keys its lock, and it reviews one plan. */
|
|
308
|
-
function reviewRole(name: string | undefined, named: string[], brief: string, agent: string, cfg: Config, spawner: Spawner): { plan: string | null; problem: string | null } {
|
|
309
|
-
const reviewed = named.filter(f => isReviewSpawn(f, brief, agent, cfg, spawner));
|
|
310
|
-
if (reviewed.length > 1) return { plan: null, problem: "a review spawn reviews one plan; split the spawn." };
|
|
311
|
-
if (reviewed.length && !name) return { plan: null, problem: "a review spawn needs a name (the task name keys its review lock)." };
|
|
312
|
-
if (reviewed.length && !/^Scope: whole plan\s*$/m.test(brief)) return { plan: null, problem: "a review spawn reviews the whole plan: add the line `Scope: whole plan` to the brief (every unticked phase, one pass; no per-phase reviews)." };
|
|
313
|
-
const plan = reviewed[0] ?? null;
|
|
314
|
-
if (plan) {
|
|
315
|
-
const rec = readPlanReviews(cfg.paths)[plan];
|
|
316
|
-
if (rec?.verdict === "PASS" && rec.hash === reviewHash(readPlanText(plan)))
|
|
317
|
-
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.` };
|
|
318
|
-
}
|
|
319
|
-
return { plan, problem: null };
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
/** 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). */
|
|
323
|
-
interface ReviewSpawn {
|
|
324
|
-
plan: string;
|
|
325
|
-
text: string;
|
|
326
|
-
hash: string;
|
|
327
|
-
verdicts: number;
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
function reviewSpawnsFile(paths: Pick<q.QueuePaths, "queue_state">): string {
|
|
331
|
-
return path.join(paths.queue_state, "review-spawns.json");
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
function readReviewSpawns(paths: Pick<q.QueuePaths, "queue_state">): Record<string, ReviewSpawn> {
|
|
335
|
-
try {
|
|
336
|
-
const parsed = JSON.parse(readFileSync(reviewSpawnsFile(paths), "utf8"));
|
|
337
|
-
return parsed && typeof parsed === "object" ? parsed : {};
|
|
338
|
-
} catch {
|
|
339
|
-
return {};
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
function writeReviewSpawns(spawns: Record<string, ReviewSpawn>, paths: Pick<q.QueuePaths, "queue_state">): void {
|
|
344
|
-
mkdirSync(paths.queue_state, { recursive: true });
|
|
345
|
-
writeFileSync(reviewSpawnsFile(paths), `${JSON.stringify(spawns, null, 2)}\n`);
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
function readPlanText(file: string): string {
|
|
349
|
-
try {
|
|
350
|
-
return readFileSync(file, "utf8");
|
|
351
|
-
} catch {
|
|
352
|
-
return "";
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
|
|
356
|
-
/** Set (plan) or drop (null) a named spawn's review role; a non-review spawn under the same name drops it. */
|
|
357
|
-
function recordReviewSpawn(name: string, plan: string | null, paths: Pick<q.QueuePaths, "queue_state">): void {
|
|
358
|
-
const spawns = readReviewSpawns(paths);
|
|
359
|
-
if (plan) {
|
|
360
|
-
const text = readPlanText(plan);
|
|
361
|
-
spawns[name] = { plan, text, hash: reviewHash(text), verdicts: 0 };
|
|
362
|
-
} else delete spawns[name];
|
|
363
|
-
writeReviewSpawns(spawns, paths);
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
/** The review role an agent id belongs to: its spawn name, or the name without a -<digits> suffix (a sub agent's id, plan P4f gap). */
|
|
367
|
-
function matchReviewSpawn(spawns: Record<string, ReviewSpawn>, agentId: string): { name: string; spawn: ReviewSpawn } | null {
|
|
368
|
-
for (const name of [agentId, agentId.replace(/-\d+$/, "")]) {
|
|
369
|
-
const spawn = Object.hasOwn(spawns, name) ? spawns[name] : undefined;
|
|
370
|
-
if (spawn && typeof spawn.plan === "string") return { name, spawn };
|
|
371
|
-
}
|
|
372
|
-
return null;
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
// --- planner mode (plan 20261102_1515 P2): the named planner spawns ---
|
|
376
|
-
|
|
377
|
-
/** The plan path a brief's `Planner role for <plan path>` line names (its first word, trailing `.,;:` dropped, so text after the path never joins it), or null. */
|
|
378
|
-
export function plannerRolePlan(text: string): string | null {
|
|
379
|
-
const p = (/^[ \t]*Planner role for[ \t]+(\S+)/im.exec(text)?.[1] ?? "").replace(/[.,;:]+$/, "");
|
|
380
|
-
return p || null;
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
/** Spawn-time check of a bound planner plan path: absolute, `.md`, under a `docs/plans` dir that exists (the planner may create a subfolder). Returns the refusal text, or null when fine. */
|
|
384
|
-
export function plannerPlanProblem(plan: string): string | null {
|
|
385
|
-
const cut = plan.indexOf("/docs/plans/");
|
|
386
|
-
const ok = path.isAbsolute(plan) && plan.endsWith(".md") && cut >= 0 && existsSync(plan.slice(0, cut + "/docs/plans".length));
|
|
387
|
-
return ok
|
|
388
|
-
? null
|
|
389
|
-
: `the \`Planner role for\` path "${plan}" must be an absolute .md path in an existing docs/plans dir, alone as the first word after "for" (e.g. \`Planner role for /path/to/repo/docs/plans/20261103_1015_x.md\`).`;
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
/** P2(b): the named planner spawns, spawn name → the one plan path its brief may create and edit (planner-spawns.json in the state dir). Recorded only on an approved spawn: in main mode the spawn gate refused the brief, so a binding exists only for a delegated planner. */
|
|
393
|
-
function plannerSpawnsFile(paths: Pick<q.QueuePaths, "queue_state">): string {
|
|
394
|
-
return path.join(paths.queue_state, "planner-spawns.json");
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
function readPlannerSpawns(paths: Pick<q.QueuePaths, "queue_state">): Record<string, string> {
|
|
398
|
-
try {
|
|
399
|
-
const parsed: unknown = JSON.parse(readFileSync(plannerSpawnsFile(paths), "utf8"));
|
|
400
|
-
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, string>) : {};
|
|
401
|
-
} catch {
|
|
402
|
-
return {};
|
|
403
|
-
}
|
|
404
|
-
}
|
|
405
|
-
|
|
406
|
-
function recordPlannerSpawn(name: string, plan: string, paths: Pick<q.QueuePaths, "queue_state">): void {
|
|
407
|
-
const spawns = readPlannerSpawns(paths);
|
|
408
|
-
spawns[name] = plan;
|
|
409
|
-
mkdirSync(paths.queue_state, { recursive: true });
|
|
410
|
-
writeFileSync(plannerSpawnsFile(paths), `${JSON.stringify(spawns, null, 2)}\n`);
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
/** The plan path the agent's brief named in its `Planner role for` line: its spawn name, or the name without a -<digits> suffix (the P4f id rule); null when no planner role is bound. */
|
|
414
|
-
export function plannerSpawnPlan(agentId: string, paths: Pick<q.QueuePaths, "queue_state">): string | null {
|
|
415
|
-
const spawns = readPlannerSpawns(paths);
|
|
416
|
-
for (const name of [agentId, agentId.replace(/-\d+$/, "")]) {
|
|
417
|
-
const plan = Object.hasOwn(spawns, name) ? spawns[name] : undefined;
|
|
418
|
-
if (typeof plan === "string" && plan) return plan;
|
|
419
|
-
}
|
|
420
|
-
return null;
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
/** P4f: the secret-read deny: credential dirs under a home, and env files. Shell text expands `~` to the process home (queue lib) while config points at the sandbox home in tests, so both roots are judged; they are the same directory in production. */
|
|
424
|
-
function secretPath(p: string, cfg: Config, cwd: string): boolean {
|
|
425
|
-
const abs = path.resolve(cwd, p.startsWith("~/") ? path.join(cfg.paths.home, p.slice(2)) : p);
|
|
426
|
-
const base = path.basename(abs);
|
|
427
|
-
if (base.startsWith(".env") || base.endsWith(".env")) return true;
|
|
428
|
-
return [cfg.paths.home, homedir()].some(home =>
|
|
429
|
-
[".config", ".ssh", ".gnupg", ".aws"].some(d => abs.startsWith(path.join(path.resolve(home), d) + path.sep)),
|
|
430
|
-
);
|
|
431
|
-
}
|
|
432
|
-
|
|
433
|
-
// P7 (plan 20261028_1600): option tokens that write or execute on an otherwise allowed command;
|
|
434
|
-
// `-w`/`--web` are denied on gh/glab segments only (they open a browser), `-c` only right after
|
|
435
|
-
// `git` (config injection, e.g. core.pager=sh).
|
|
436
|
-
const SHELL_DENY_OPTS = ["--output", "--pre", "--ext-diff", "--textconv", "--open-files-in-pager", "--exec", "-O"];
|
|
437
|
-
|
|
438
|
-
/** P7 (plan 20261028_1600): why a review spawn's bash command is not allowed, or null. Single
|
|
439
|
-
* line, no `$(`/backtick/`<(`/`>(`, no `>` outside quotes (quoted text stripped the way
|
|
440
|
-
* withoutQuotedRedirects does), and every `|`/`&&`/`||`/`;`/`&` segment starts with a
|
|
441
|
-
* review.shell_allow entry followed by a word boundary. */
|
|
442
|
-
function reviewShellProblem(command: string, cfg: Config): string | null {
|
|
443
|
-
if (/[\r\n]/.test(command)) return "a multi-line command";
|
|
444
|
-
if (command.includes("`") || command.includes("$(") || command.includes("<(") || command.includes(">(")) return "command substitution";
|
|
445
|
-
if (q.withoutQuotedRedirects(command).includes(">")) return "a shell redirect";
|
|
446
|
-
for (const raw of command.split(/&&|\|\||[|;&]/)) {
|
|
447
|
-
const seg = raw.trim();
|
|
448
|
-
const toks = seg.split(/\s+/);
|
|
449
|
-
const pre = cfg.review.shell_allow.find(p => seg.startsWith(p) && (seg.length === p.length || /\s/.test(seg.charAt(p.length))));
|
|
450
|
-
if (!pre) return `${toks[0] || "an empty segment"} is not a review.shell_allow command`;
|
|
451
|
-
const opt = toks.find(t => SHELL_DENY_OPTS.some(o => t === o || t.startsWith(`${o}=`)));
|
|
452
|
-
if (opt) return `the writing/executing option ${opt}`;
|
|
453
|
-
if ((toks[0] === "gh" || toks[0] === "glab") && toks.some(t => t === "-w" || t === "--web")) return "gh/glab --web opens a browser";
|
|
454
|
-
if (toks.some((t, i) => i > 0 && t === "-c" && toks[i - 1] === "git")) return "git -c config injection";
|
|
455
|
-
}
|
|
456
|
-
return null;
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
/** P4f: a named review spawn may read, use todo, and edit only its own plan. Shell, spawn, cancel and MCP tools are denied; so are secret reads. */
|
|
460
|
-
function reviewLockProblem(e: ToolEvent, cfg: Config): string | null {
|
|
461
|
-
const plan = matchReviewSpawn(readReviewSpawns(cfg.paths), e.agentId ?? "")?.spawn.plan ?? null;
|
|
462
|
-
if (!plan) return null;
|
|
463
|
-
const input = e.input ?? {};
|
|
464
|
-
if (cfg.guards.write_tools.includes(e.tool)) {
|
|
465
|
-
const writes = [...(e.writes ?? []), ...q.writeTargets(e.tool, input, e.cwd, cfg.paths, [])];
|
|
466
|
-
if (writes.length && writes.every(w => path.resolve(e.cwd, w) === path.resolve(plan))) return null;
|
|
467
|
-
return `review spawn ${e.agentId} may edit only its plan ${plan}.`;
|
|
468
|
-
}
|
|
469
|
-
if (cfg.guards.read_tools.includes(e.tool) || e.tool === "todo") {
|
|
470
|
-
const reads = [...(e.paths ?? []), ...q.touchedPaths(e.tool, input, e.cwd)];
|
|
471
|
-
return reads.some(p => secretPath(p, cfg, e.cwd)) ? `review spawn ${e.agentId} may not read credentials or env files.` : null;
|
|
472
|
-
}
|
|
473
|
-
// P7 (plan 20261028_1600): the reviewer's shell is an allow list, not a ban list — eval never
|
|
474
|
-
// (it runs code), and bash only when every |/&&/||/;/& segment starts with a review.shell_allow
|
|
475
|
-
// command: single-line, no substitution or redirect characters, no writing/executing option
|
|
476
|
-
// tokens. The secret-path deny stays. (I-20261031-348: the old MUTATING ban missed
|
|
477
|
-
// fs.renameSync-style writes; I-20261031-350: a reviewer's shell ran anything unlisted.)
|
|
478
|
-
if (cfg.guards.shell_tools.includes(e.tool)) {
|
|
479
|
-
if (e.tool === "eval")
|
|
480
|
-
return `review spawn ${e.agentId} may not run eval; use the read tools or a bash command from review.shell_allow.`;
|
|
481
|
-
const problem = reviewShellProblem(String(input.command ?? ""), cfg);
|
|
482
|
-
if (problem) return `review spawn ${e.agentId} may run only review.shell_allow commands: ${problem}.`;
|
|
483
|
-
const reads = [...(e.paths ?? []), ...q.touchedPaths(e.tool, input, e.cwd)];
|
|
484
|
-
return reads.some(p => secretPath(p, cfg, e.cwd)) ? `review spawn ${e.agentId} may not read credentials or env files.` : null;
|
|
485
|
-
}
|
|
486
|
-
return `review spawn ${e.agentId} may only read, use todo, and edit its plan; ${e.tool} is denied.`;
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
function spawnsFile(paths: Pick<q.QueuePaths, "queue_state">): string {
|
|
490
|
-
return path.join(paths.queue_state, "spawns.json");
|
|
491
|
-
}
|
|
492
|
-
|
|
493
|
-
function staffingFile(paths: Pick<q.QueuePaths, "queue_state">): string {
|
|
494
|
-
return path.join(paths.queue_state, "staffing.json");
|
|
495
|
-
}
|
|
496
|
-
|
|
497
|
-
// The owner-message store (owner-messages.jsonl) and its matcher live in src/core/incidents.ts
|
|
498
|
-
// (20261028_0900 P3): dismissIncident needs them too, and guards already imports incidents.
|
|
499
|
-
|
|
500
|
-
/** P3 (plan 20261031_1207): the text is owner prose — not Main's own guard output, a system notice, a task result — so its words are the owner's. Gates both the owner-message store and the cancel flag. The P5b resume prefix makes a wrapped machine prompt owner-shaped, so it is excluded here like its unwrapped form. */
|
|
501
|
-
export function isOwnerProse(text: string): boolean {
|
|
502
|
-
const t = text.trimStart();
|
|
503
|
-
return !(t.startsWith("main-guard:") || t.startsWith(UNANSWERED_PREFIX) || t.startsWith("<system-notice>") || text.includes("<task-result"));
|
|
504
|
-
}
|
|
505
|
-
|
|
506
|
-
function recordOwnerMessage(text: string, cfg: Config): void {
|
|
507
|
-
if (!isOwnerProse(text)) return;
|
|
508
|
-
const owner = ownerText(text);
|
|
509
|
-
if (owner) {
|
|
510
|
-
try {
|
|
511
|
-
recordOwnerLog(cfg, "owner", owner);
|
|
512
|
-
} catch (err) {
|
|
513
|
-
log(cfg.paths.guard_log, `cannot write ${ownerLogFile(cfg.paths)}: ${err}`);
|
|
514
|
-
}
|
|
515
|
-
}
|
|
516
|
-
try {
|
|
517
|
-
writeOwnerStore([...readOwnerMessages(cfg.paths), { at: nowSec(), text }], readOwnerAnswers(cfg.paths), cfg.paths);
|
|
518
|
-
} catch (err) {
|
|
519
|
-
log(cfg.paths.guard_log, `cannot write ${ownerMessagesFile(cfg.paths)}: ${err}`);
|
|
520
|
-
}
|
|
521
|
-
}
|
|
522
|
-
|
|
523
|
-
/** One staffing.json entry: the task names of a plan's newest spawn and when it was spawned (epoch sec). An old bare-array entry has no spawn time and reads as at 0. */
|
|
524
|
-
export interface StaffingEntry {
|
|
525
|
-
names: string[];
|
|
526
|
-
at: number;
|
|
527
|
-
}
|
|
528
|
-
|
|
529
|
-
/** plan → its staffing entry (staffing.json). */
|
|
530
|
-
export function readStaffingEntries(paths: Pick<q.QueuePaths, "queue_state">): Record<string, StaffingEntry> {
|
|
531
|
-
try {
|
|
532
|
-
const raw: unknown = JSON.parse(readFileSync(staffingFile(paths), "utf8"));
|
|
533
|
-
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
|
|
534
|
-
const out: Record<string, StaffingEntry> = {};
|
|
535
|
-
for (const [k, v] of Object.entries(raw)) {
|
|
536
|
-
if (Array.isArray(v)) out[k] = { names: v.map(String), at: 0 };
|
|
537
|
-
else if (v && typeof v === "object" && "names" in v && Array.isArray(v.names)) {
|
|
538
|
-
out[k] = { names: v.names.map(String), at: "at" in v ? Number(v.at) || 0 : 0 };
|
|
539
|
-
}
|
|
540
|
-
}
|
|
541
|
-
return out;
|
|
542
|
-
} catch {
|
|
543
|
-
return {};
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
/** plan → the task names of its newest spawn (staffing.json); read for the staffed check. */
|
|
548
|
-
export function readStaffing(paths: Pick<q.QueuePaths, "queue_state">): Record<string, string[]> {
|
|
549
|
-
return Object.fromEntries(Object.entries(readStaffingEntries(paths)).map(([f, e]) => [f, e.names]));
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
function readSpawns(paths: Pick<q.QueuePaths, "queue_state">): Record<string, string> {
|
|
553
|
-
try {
|
|
554
|
-
const raw: unknown = JSON.parse(readFileSync(spawnsFile(paths), "utf8"));
|
|
555
|
-
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
|
|
556
|
-
const out: Record<string, string> = {};
|
|
557
|
-
for (const [k, v] of Object.entries(raw)) out[k] = String(v);
|
|
558
|
-
return out;
|
|
559
|
-
} catch {
|
|
560
|
-
return {};
|
|
561
|
-
}
|
|
562
|
-
}
|
|
563
|
-
|
|
564
|
-
/** Remember the "## Progress" hash of the plans an agent was just spawned on. With `staffing`, also record the spawn's task names per plan (staffing.json); a plan's entry is replaced by the newest spawn that names it. */
|
|
565
|
-
export function recordSpawns(files: string[], paths: Pick<q.QueuePaths, "queue_state">, staffing: Record<string, string[]> = {}): void {
|
|
566
|
-
const s = readSpawns(paths);
|
|
567
|
-
for (const f of files) {
|
|
568
|
-
try {
|
|
569
|
-
s[f] = q.sha(q.progressBody(readFileSync(f, "utf8")));
|
|
570
|
-
} catch {}
|
|
571
|
-
}
|
|
572
|
-
try {
|
|
573
|
-
mkdirSync(paths.queue_state, { recursive: true });
|
|
574
|
-
writeFileSync(spawnsFile(paths), JSON.stringify(s, null, 1));
|
|
575
|
-
} catch (err) {
|
|
576
|
-
log(`${paths.queue_state}/../main-guard.log`, `cannot write ${spawnsFile(paths)}: ${err}`);
|
|
577
|
-
}
|
|
578
|
-
if (!Object.keys(staffing).length) return;
|
|
579
|
-
const st = readStaffingEntries(paths);
|
|
580
|
-
const at = nowSec();
|
|
581
|
-
for (const [f, names] of Object.entries(staffing)) if (names.length) st[f] = { names: [...names], at };
|
|
582
|
-
try {
|
|
583
|
-
mkdirSync(paths.queue_state, { recursive: true });
|
|
584
|
-
writeFileSync(staffingFile(paths), JSON.stringify(st, null, 1));
|
|
585
|
-
} catch (err) {
|
|
586
|
-
log(`${paths.queue_state}/../main-guard.log`, `cannot write ${staffingFile(paths)}: ${err}`);
|
|
587
|
-
}
|
|
588
|
-
}
|
|
589
|
-
|
|
590
|
-
/** Plans with a running subagent: one of the plan's staffing names equals a running job label, or the label is that name with the spawner's uniqueness suffix ("-2", "-3", …; real snapshot 2026-10-25: `allocate()` keeps the exact name first, then appends). Pure; no job info staffs nothing. */
|
|
591
|
-
export function staffedPlans(staffing: Record<string, string[]>, runningJobs: string[] | undefined): string[] {
|
|
592
|
-
if (!runningJobs?.length) return [];
|
|
593
|
-
return Object.entries(staffing)
|
|
594
|
-
.filter(([, names]) => names.some(n => runningJobs.some(j => j === n || j.startsWith(`${n}-`))))
|
|
595
|
-
.map(([file]) => file);
|
|
596
|
-
}
|
|
597
|
-
|
|
598
|
-
/** Re-key a plan's spawn hash after its Progress body was trimmed. Only a hash that matched the old body moves. Pure. */
|
|
599
|
-
export function rekeySpawns(spawns: Record<string, string>, file: string, before: string, after: string): boolean {
|
|
600
|
-
if (spawns[file] !== q.sha(before)) return false;
|
|
601
|
-
spawns[file] = q.sha(after);
|
|
602
|
-
return true;
|
|
603
|
-
}
|
|
604
|
-
|
|
605
|
-
/** Apply rekeySpawns to the stored spawn hashes. */
|
|
606
|
-
export function rekeySpawnFile(file: string, before: string, after: string, paths: Pick<q.QueuePaths, "queue_state">): void {
|
|
607
|
-
const s = readSpawns(paths);
|
|
608
|
-
if (!rekeySpawns(s, file, before, after)) return;
|
|
609
|
-
try {
|
|
610
|
-
writeFileSync(spawnsFile(paths), JSON.stringify(s, null, 1));
|
|
611
|
-
} catch (err) {
|
|
612
|
-
log(`${paths.queue_state}/../main-guard.log`, `cannot write ${spawnsFile(paths)}: ${err}`);
|
|
613
|
-
}
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
// A per-spawn call budget: `Call budget: <N>` on its own line in a task brief (the task's own
|
|
617
|
-
// text wins over the shared context). Main sets it at spawn time; the run's hard stop is N and
|
|
618
|
-
// its warning band has the global width (sub_max_calls - sub_warn_calls), floored at 1.
|
|
619
|
-
const BUDGET_LINE = /^\s*(?:[-*]\s+)?call budget:\s*(\d{1,4})\s*$/im;
|
|
620
|
-
|
|
621
|
-
/** The first `Call budget: <N>` line of a brief, or null. */
|
|
622
|
-
export function briefBudget(brief: string): number | null {
|
|
623
|
-
const m = BUDGET_LINE.exec(brief);
|
|
624
|
-
return m ? Number(m[1]) : null;
|
|
625
|
-
}
|
|
626
|
-
|
|
627
|
-
function budgetsFile(paths: Pick<q.QueuePaths, "queue_state">): string {
|
|
628
|
-
return path.join(paths.queue_state, "spawn-budgets.json");
|
|
629
|
-
}
|
|
630
|
-
|
|
631
|
-
/** The budgets recorded at spawn: task name → calls (next to the spawn hashes). */
|
|
632
|
-
export function readBudgets(dir: string): Record<string, number> {
|
|
633
|
-
try {
|
|
634
|
-
const raw: unknown = JSON.parse(readFileSync(path.join(dir, "spawn-budgets.json"), "utf8"));
|
|
635
|
-
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
|
|
636
|
-
const out: Record<string, number> = {};
|
|
637
|
-
for (const [k, v] of Object.entries(raw)) if (typeof v === "number" && Number.isFinite(v)) out[k] = v;
|
|
638
|
-
return out;
|
|
639
|
-
} catch {
|
|
640
|
-
return {};
|
|
641
|
-
}
|
|
642
|
-
}
|
|
643
|
-
|
|
644
|
-
/** Remember the named tasks' call budgets; a name's old budget is replaced, a null one removed. */
|
|
645
|
-
export function recordBudgets(entries: Record<string, number | null>, paths: Pick<q.QueuePaths, "queue_state">): void {
|
|
646
|
-
const names = Object.keys(entries);
|
|
647
|
-
if (!names.length) return;
|
|
648
|
-
const budgets = readBudgets(paths.queue_state);
|
|
649
|
-
for (const n of names) {
|
|
650
|
-
const b = entries[n];
|
|
651
|
-
if (b == null) delete budgets[n];
|
|
652
|
-
else budgets[n] = b;
|
|
653
|
-
}
|
|
654
|
-
try {
|
|
655
|
-
mkdirSync(paths.queue_state, { recursive: true });
|
|
656
|
-
writeFileSync(budgetsFile(paths), JSON.stringify(budgets, null, 1));
|
|
657
|
-
} catch (err) {
|
|
658
|
-
log(`${paths.queue_state}/../main-guard.log`, `cannot write ${budgetsFile(paths)}: ${err}`);
|
|
659
|
-
}
|
|
660
|
-
}
|
|
661
|
-
|
|
662
|
-
/** A sub's hard call cap: the budget recorded for its task name at spawn, else the global cap. */
|
|
663
|
-
export function subCallCap(agentId: string, cfg: Config): number {
|
|
664
|
-
return readBudgets(cfg.paths.queue_state)[agentId] ?? cfg.guards.sub_max_calls;
|
|
665
|
-
}
|
|
666
|
-
|
|
667
|
-
// --- shared pieces ---
|
|
668
|
-
|
|
669
|
-
/** Epoch ms when the owner's open unlock window closes, or null when the guard is locked. */
|
|
670
|
-
function unlockUntilMs(cfg: Config): number | null {
|
|
671
|
-
try {
|
|
672
|
-
const until = statSync(cfg.paths.unlock).mtimeMs + cfg.guards.unlock_minutes * 60_000;
|
|
673
|
-
return Date.now() < until ? until : null;
|
|
674
|
-
} catch {
|
|
675
|
-
return null;
|
|
676
|
-
}
|
|
677
|
-
}
|
|
678
|
-
|
|
679
|
-
/**
|
|
680
|
-
* One line for Main's prompt while the owner's unlock is open. A chat "unlock" is swallowed by the
|
|
681
|
-
* input handler (the model never sees the message), so the adapter also wakes Main with a message.
|
|
682
|
-
*/
|
|
683
|
-
function unlockLine(cfg: Config): string {
|
|
684
|
-
const until = unlockUntilMs(cfg);
|
|
685
|
-
if (until === null) return "";
|
|
686
|
-
const hhmm = new Date(until).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" });
|
|
687
|
-
return `\nguards: UNLOCKED until ${hhmm} — guard files are open; do the step that waited on the unlock now.`;
|
|
688
|
-
}
|
|
689
|
-
|
|
690
|
-
function protectedHit(paths: string[], cfg: Config): string | null {
|
|
691
|
-
const hit = q.protectedHit(paths, cfg.paths);
|
|
692
|
-
if (hit) return hit;
|
|
693
|
-
for (const p of paths) {
|
|
694
|
-
for (const raw of cfg.guards.protected) {
|
|
695
|
-
const g = q.expandHome(raw);
|
|
696
|
-
if (g.endsWith("/") ? p.startsWith(g) || `${p}/` === g : p === g) return p;
|
|
697
|
-
}
|
|
698
|
-
// The user's config file and the configured notify secret files are guard surface too:
|
|
699
|
-
// an agent that could rewrite them could point notify at its own webhook.
|
|
700
|
-
if (notifyProtectedPaths(cfg).includes(p)) return p;
|
|
701
|
-
}
|
|
702
|
-
return null;
|
|
703
|
-
}
|
|
704
|
-
|
|
705
|
-
// Text files never count: only files apart from .md or .txt do.
|
|
706
|
-
function freeExt(cfg: Config): RegExp {
|
|
707
|
-
return new RegExp(cfg.guards.free_ext, "i");
|
|
708
|
-
}
|
|
709
|
-
|
|
710
|
-
export function isProjectPath(p: string, cfg: Config): boolean {
|
|
711
|
-
const roots = cfg.paths.work_roots.map(r => q.expandHome(r));
|
|
712
|
-
const free = cfg.guards.free_prefixes.map(f => q.expandHome(f));
|
|
713
|
-
return (
|
|
714
|
-
roots.some(r => p.startsWith(r) && p.length > r.length) &&
|
|
715
|
-
!free.some(f => p.startsWith(f) || `${p}/` === f) &&
|
|
716
|
-
!q.isOrchestrationPath(p, q.activePlans(cfg.paths), cfg.paths.queue_index)
|
|
717
|
-
);
|
|
718
|
-
}
|
|
719
|
-
|
|
720
|
-
// Project files this call would change; empty = the call does not count toward the limit.
|
|
721
|
-
// Only real write targets count: reads, git landing commands (commit, push, merge, pull, rebase,
|
|
722
|
-
// cherry-pick, worktree) and paths merely mentioned in a body or command are free.
|
|
723
|
-
export function changedProjectFiles(toolName: string, input: Record<string, unknown>, cwd: string, cfg: Config): string[] {
|
|
724
|
-
return q
|
|
725
|
-
.writeTargets(toolName, input ?? {}, cwd, cfg.paths)
|
|
726
|
-
.filter(p => !freeExt(cfg).test(p) && isProjectPath(p, cfg));
|
|
727
|
-
}
|
|
728
|
-
|
|
729
|
-
// A bypass launch goes around the harness guards (today's config entry names a CLI runner), so it
|
|
730
|
-
// needs an open plan: first word ... last word of the config entry must appear in the command line.
|
|
731
|
-
export function bypassRegExp(entry: string): RegExp {
|
|
732
|
-
const words = entry.trim().split(/\s+/).filter(Boolean);
|
|
733
|
-
if (words.length === 1) return new RegExp(`\\b${(words[0] ?? "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`);
|
|
734
|
-
const head = (words[0] ?? "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
735
|
-
const tail = (words[words.length - 1] ?? "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
736
|
-
return new RegExp(`\\b${head}\\b[^\\n]*\\b${tail}\\b`);
|
|
737
|
-
}
|
|
738
|
-
|
|
739
|
-
const RESEARCH_ASK = /\b(research|investigate|find where|map the code|read the code for)\b/i;
|
|
740
|
-
const PLAN_WRITE = /\b(write|writing|draft|drafting|author)\b[^\n]*\bplan\b/i;
|
|
741
|
-
|
|
742
|
-
// Phase ids (P1, P2, P4a ...) in the plan's Phases section that are not ticked yet.
|
|
743
|
-
function unticked(p: Plan): string[] {
|
|
744
|
-
const phases = q.sections(p.text).get("phases") ?? "";
|
|
745
|
-
return [...phases.matchAll(/^\s*[-*]\s+\[ \]\s+(P\d+[a-z]?)\b/gm)].map(m => m[1]!);
|
|
746
|
-
}
|
|
747
|
-
|
|
748
|
-
/** Phase ids an edit newly ticks: `[ ]` in `before`, `[x]` in `after` (P6, read from the Phases section like unticked). */
|
|
749
|
-
function newlyTicked(before: string, after: string): string[] {
|
|
750
|
-
const was = new Set([...(q.sections(before).get("phases") ?? "").matchAll(/^\s*[-*]\s+\[ \]\s+(P\d+[a-z]?)\b/gm)].map(m => m[1]!));
|
|
751
|
-
return [...(q.sections(after).get("phases") ?? "").matchAll(/^\s*[-*]\s+\[[xX]\]\s+(P\d+[a-z]?)\b/gm)].map(m => m[1]!).filter(id => was.has(id));
|
|
752
|
-
}
|
|
753
|
-
|
|
754
|
-
/** The open plans the text names — a `Priority skip: <path> — <why>` line names a plan it does NOT run on (20261025_0215 P3), so only the remaining text decides. planGate's targeting, shared with the spawn verdict's brief-lint and cap notes (plan 20261031_1207 P4). */
|
|
755
|
-
function briefPlans(text: string, cfg: Config): Plan[] {
|
|
756
|
-
const body = text.replace(/^\s*(?:[-*]\s+)?priority skip:.*$/gim, "");
|
|
757
|
-
return q.activePlans(cfg.paths, cfg.review.agents).filter(p => body.includes(p.file));
|
|
758
|
-
}
|
|
759
|
-
|
|
760
|
-
// Plans an implementer brief may run on; returns [reason, null] or [null, plan files].
|
|
761
|
-
export function planGate(text: string, label: string, cfg: Config): [string | null, string[]] {
|
|
762
|
-
const plans = q.activePlans(cfg.paths, cfg.review.agents);
|
|
763
|
-
const unclosed = plans.filter(p => (p.status === "complete" || p.status === "cancelled") && !q.awaitingMerge(p, cfg.paths));
|
|
764
|
-
if (unclosed.length)
|
|
765
|
-
return [
|
|
766
|
-
`${label}: ${unclosed.map(p => `${p.file} (${p.status})`).join(", ")} is still indexed. Verify it and run \`queue-close <plan>\` before any new spawn.`,
|
|
767
|
-
[],
|
|
768
|
-
];
|
|
769
|
-
const named = briefPlans(text, cfg);
|
|
770
|
-
if (!named.length)
|
|
771
|
-
return [
|
|
772
|
-
`${label}: an implementer needs an open plan. Name the plan's absolute path in the brief; the plan must be listed in ${cfg.paths.queue_index}.`,
|
|
773
|
-
[],
|
|
774
|
-
];
|
|
775
|
-
if (RESEARCH_ASK.test(text) && PLAN_WRITE.test(text))
|
|
776
|
-
return [
|
|
777
|
-
`${label}: a brief must not ask for research for a plan to be written. Please never ever ever write a plan when another agent is doing the research or reading for you. Main reads the code for its plans itself.`,
|
|
778
|
-
[],
|
|
779
|
-
];
|
|
780
|
-
// P5 (plan 20261031_0911): a landed open plan whose auto-close failed locks the queue — every
|
|
781
|
-
// brief must name it, so the next spawn works on closing it instead of around it. A named
|
|
782
|
-
// locked plan skips the unticked-phase checks below: its work has landed, the job is the close.
|
|
783
|
-
const locked = plans.filter(p => p.status === "open" && q.autoCloseCandidate(p) && q.lastCloseFailed(p.file, cfg.paths));
|
|
784
|
-
for (const s of locked) {
|
|
785
|
-
if (named.some(n => n.file === s.file)) continue;
|
|
786
|
-
return [
|
|
787
|
-
`${label}: ${s.file} landed but its auto-close failed (${(q.lastCloseResult(s.file, cfg.paths) ?? "").replace(/^queue-close: /, "")}). The queue is locked on it: name this plan in the brief and fix the close before any other spawn.`,
|
|
788
|
-
[],
|
|
789
|
-
];
|
|
790
|
-
}
|
|
791
|
-
const spawns = readSpawns(cfg.paths);
|
|
792
|
-
for (const p of named) {
|
|
793
|
-
if (p.errors.length) return [`${label}: plan ${p.file} is not ready (${p.errors.join("; ")}).`, []];
|
|
794
|
-
if (p.waiting) return [`${label}: plan ${p.file} is parked "WAITING on owner".`, []];
|
|
795
|
-
if (p.status !== "open") return [`${label}: plan ${p.file} says "Status: ${p.status}".`, []];
|
|
796
|
-
const cancelled = q.cancelledMatches(p, cfg.paths);
|
|
797
|
-
if (cancelled.length) return [`${label}: plan ${p.file} ${q.cancelledProblem(p, cancelled[0]!, cfg.paths)}`, []];
|
|
798
|
-
const before = spawns[p.file];
|
|
799
|
-
if (before && before === q.sha(q.progressBody(p.text)))
|
|
800
|
-
return [
|
|
801
|
-
`${label}: plan ${p.file} has no new "## Progress" entry since the last agent ran on it. Write that run's progress (from its report) into the plan first.`,
|
|
802
|
-
[],
|
|
803
|
-
];
|
|
804
|
-
const approval = approvalProblem(p.text, p.file, cfg.pages.dir, cfg.approval.since, cfg.paths);
|
|
805
|
-
if (approval) return [approval, []];
|
|
806
|
-
const open = unticked(p);
|
|
807
|
-
// A locked plan's work has landed: closing it is the job, there is no phase left to tick.
|
|
808
|
-
if (locked.some(l => l.file === p.file)) continue;
|
|
809
|
-
if (!open.length) return [`${label}: plan ${p.file} has no unticked phase left.`, []];
|
|
810
|
-
if (!open.some(id => new RegExp(`\\b${id}\\b`).test(text)))
|
|
811
|
-
return [`${label}: the brief must name an unticked phase of ${p.file} (${open.join(", ")}).`, []];
|
|
812
|
-
}
|
|
813
|
-
return [null, named.map(p => p.file)];
|
|
814
|
-
}
|
|
815
|
-
|
|
816
|
-
// --- priority: index order is priority (plan 20261025_0215_index_priority) ---
|
|
817
|
-
|
|
818
|
-
export interface PrioritySkip {
|
|
819
|
-
plan: string;
|
|
820
|
-
why: string;
|
|
821
|
-
}
|
|
822
|
-
|
|
823
|
-
export interface PriorityOutcome {
|
|
824
|
-
/** Refusal text, without the caller's label prefix. */
|
|
825
|
-
problem?: string;
|
|
826
|
-
/** Skip lines the brief justified; the caller logs each, then allows. */
|
|
827
|
-
skips?: PrioritySkip[];
|
|
828
|
-
/** No job info was available: the gate never refuses. */
|
|
829
|
-
unknown?: boolean;
|
|
830
|
-
}
|
|
831
|
-
|
|
832
|
-
const SKIP_LINE = /^\s*(?:[-*]\s+)?priority skip:\s*(.+?)\s+[—–-]\s*(.+?)\s*$/gim;
|
|
833
|
-
|
|
834
|
-
/** One plan is idle when a subagent could start on it right now: open, no owner hold, not awaiting merge, no template errors, an unticked phase left, and not waiting on another open plan of the active index. */
|
|
835
|
-
function priorityIdle(p: Plan, plans: Plan[], paths?: Pick<q.QueuePaths, "queue_state">): boolean {
|
|
836
|
-
if (p.waitsOn.some(f => plans.some(w => w.file === f && w.status === "open"))) return false;
|
|
837
|
-
return p.status === "open" && !p.waiting && !(paths ? q.awaitingMerge(p, paths) : false) && !p.errors.length && unticked(p).length > 0;
|
|
838
|
-
}
|
|
839
|
-
|
|
840
|
-
/**
|
|
841
|
-
* Pure priority gate: for the brief's named plans, every higher plan in index order that is idle
|
|
842
|
-
* and unstaffed needs proof before a lower plan takes a free slot; otherwise the spawn is refused.
|
|
843
|
-
* Proof is either the higher plan's own `Waits on: <plan>` line for a plan still open in the index
|
|
844
|
-
* (then it is not idle at all) or a `Priority skip: <path> — owner: "<words>"` line whose quoted
|
|
845
|
-
* words (≥ 4, normalised) appear in one of `messages` (the owner's recorded words of the last
|
|
846
|
-
* 24 h; `now` is the current unix seconds). A higher plan whose branch carries an open MR in the
|
|
847
|
-
* cached forge list (fresh within `review.mr_cache_minutes`; the one list the main-start sweep
|
|
848
|
-
* and pendingWorkProblem maintain — never queried here) is landing, not idle: no proof needed.
|
|
849
|
-
* A stale cache proves nothing, so the refusal stands (I-20261029-435). In tier full (`cfg`) a
|
|
850
|
-
* `Priority skip: <path> — Main: "<reason>"` line with ≥ 4 words is proof too; without `cfg` the
|
|
851
|
-
* refusal behaviour is the pre-tier one. Any other skip line is refused.
|
|
852
|
-
* `staffed === undefined` means the caller had no running-job info (CLI spawn without it): never
|
|
853
|
-
* refuse. Plans already named by this call never block it.
|
|
854
|
-
*/
|
|
855
|
-
export function priorityProblem(plans: Plan[], named: string[], staffed: string[] | undefined, brief: string, messages: OwnerMessage[] = [], now: number = nowSec(), cfg?: Config): PriorityOutcome | null {
|
|
856
|
-
if (staffed === undefined) return { unknown: true };
|
|
857
|
-
const namedRanks = named.map(f => plans.findIndex(p => p.file === f)).filter(n => n >= 0);
|
|
858
|
-
if (!namedRanks.length) return null;
|
|
859
|
-
const higher = plans.slice(0, Math.min(...namedRanks));
|
|
860
|
-
const tier = cfg ? currentTier(cfg) : "opinionated";
|
|
861
|
-
const skipLines: Record<string, string> = {};
|
|
862
|
-
for (const m of brief.matchAll(SKIP_LINE)) {
|
|
863
|
-
const plan = (m[1] ?? "").trim();
|
|
864
|
-
const why = (m[2] ?? "").trim();
|
|
865
|
-
if (plan && why) skipLines[plan] = why;
|
|
866
|
-
}
|
|
867
|
-
const skips: PrioritySkip[] = [];
|
|
868
|
-
const cache = cfg ? readMrCache(cfg.paths) : { at: 0, repos: {} };
|
|
869
|
-
const fresh = cfg ? now - cache.at < cfg.review.mr_cache_minutes * 60 : false;
|
|
870
|
-
for (let i = 0; i < higher.length; i++) {
|
|
871
|
-
const p = higher[i]!;
|
|
872
|
-
if (!priorityIdle(p, plans, cfg?.paths) || staffed.includes(p.file)) continue;
|
|
873
|
-
if (fresh && p.branch && (cache.repos[p.repo] ?? []).some(mr => mr.branch === p.branch)) continue;
|
|
874
|
-
const why = skipLines[p.file];
|
|
875
|
-
// Tier full (20261025_1940 P2): Main's own >= 4-word reason is proof enough; every other
|
|
876
|
-
// tier refuses it exactly as before — only the owner's recorded words let a skip through.
|
|
877
|
-
const mainWhy = tier === "full" ? why?.match(/^Main:\s*"(.+)"\s*$/) : undefined;
|
|
878
|
-
if (why && mainWhy && mainWhy[1]!.trim().split(/\s+/).length >= 4) {
|
|
879
|
-
skips.push({ plan: p.file, why });
|
|
880
|
-
continue;
|
|
881
|
-
}
|
|
882
|
-
const quote = why?.match(/^owner:\s*"(.+)"\s*$/);
|
|
883
|
-
if (why && quote && ownerSaid(quote[1]!, messages, now)) {
|
|
884
|
-
skips.push({ plan: p.file, why });
|
|
885
|
-
continue;
|
|
886
|
-
}
|
|
887
|
-
return { problem: `higher plan ${p.file} (rank ${i + 1}) is idle; a skip needs the owner's words (Priority skip: ${p.file} — owner: "<quote>") or a "Waits on: ${p.file}" line in that plan` };
|
|
888
|
-
}
|
|
889
|
-
return skips.length ? { skips } : null;
|
|
890
|
-
}
|
|
891
|
-
|
|
892
|
-
/** Load staffing and the owner's recorded words, run the pure priority gate and log its outcome; the refusal comes back with the caller's label, or null. P8 (I-20261031-353): the plans a Main-authored brief reviews drop out first — a plan waiting for its reviewer is not a priority slot, so a call naming only reviewed plans passes with no skip line; implementer plans keep the gate. */
|
|
893
|
-
function priorityGate(named: string[], runningJobs: string[] | undefined, brief: string, cfg: Config, label: string, agent: string, spawner: Spawner): string | null {
|
|
894
|
-
const implementer = named.filter(f => !isReviewSpawn(f, brief, agent, cfg, spawner));
|
|
895
|
-
const outcome = priorityProblem(q.activePlans(cfg.paths), implementer, runningJobs === undefined ? undefined : staffedPlans(readStaffing(cfg.paths), runningJobs), brief, readOwnerMessages(cfg.paths), nowSec(), cfg);
|
|
896
|
-
if (outcome?.unknown) log(cfg.paths.guard_log, "PRIORITY unknown jobs");
|
|
897
|
-
for (const s of outcome?.skips ?? []) log(cfg.paths.guard_log, `PRIORITY skip ${s.plan}: ${s.why}`);
|
|
898
|
-
return outcome?.problem ? `${label}: ${outcome.problem}` : null;
|
|
899
|
-
}
|
|
900
|
-
|
|
901
|
-
/** The brief names pending work the P3 way: `MR !N: <what it holds> — this task: <why not overlapping>` (GitHub `#N`), `Branch <name>: …`. */
|
|
902
|
-
export function briefNamesPending(brief: string, prefix: "MR" | "Branch", token: string): boolean {
|
|
903
|
-
const esc = token.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
904
|
-
return new RegExp(`^[ \\t]*(?:[-*][ \\t]+)?${prefix} ${esc}:[^\\n]*this task:`, "im").test(brief);
|
|
905
|
-
}
|
|
906
|
-
|
|
907
|
-
/** The branch a linked worktree has checked out, or null. */
|
|
908
|
-
function worktreeBranch(wt: string | null, run: CommandRunner): string | null {
|
|
909
|
-
if (!wt) return null;
|
|
910
|
-
const r = run(["git", "-C", wt, "rev-parse", "--abbrev-ref", "HEAD"], {});
|
|
911
|
-
return r.code === 0 ? r.stdout.trim() || null : null;
|
|
912
|
-
}
|
|
913
|
-
|
|
914
|
-
/**
|
|
915
|
-
* P3 (plan 20261028_1600): done-but-not-merged work must be named by the brief before a spawn
|
|
916
|
-
* runs on its plan. (a) open MRs of the plan's repo that the plan mentions (mr-sweep's lister and
|
|
917
|
-
* `mentioned`; the list is cached `review.mr_cache_minutes`); (b) the plan's `Branch:` line or its
|
|
918
|
-
* worktree's checked-out branch when wip-check reports it UNLANDED — still enforced when the forge
|
|
919
|
-
* is unreachable, whose degrade skips only (a), like the sweep. A repo with no origin remote has
|
|
920
|
-
* no merge target: both checks skip it with one guard-log line.
|
|
921
|
-
*/
|
|
922
|
-
export function pendingWorkProblem(named: string[], brief: string, cfg: Config, run: CommandRunner = defaultRunner): string | null {
|
|
923
|
-
const plans = q.activePlans(cfg.paths).filter(p => named.includes(p.file));
|
|
924
|
-
if (!plans.length) return null;
|
|
925
|
-
const cache = readMrCache(cfg.paths);
|
|
926
|
-
const fresh = nowSec() - cache.at < cfg.review.mr_cache_minutes * 60;
|
|
927
|
-
const openMrs = new Map<string, OpenMr[]>();
|
|
928
|
-
const hasOrigin = new Set<string>();
|
|
929
|
-
let cacheDirty = false;
|
|
930
|
-
for (const repo of new Set(plans.map(p => p.repo))) {
|
|
931
|
-
if (fresh && cache.repos[repo]) {
|
|
932
|
-
openMrs.set(repo, cache.repos[repo]);
|
|
933
|
-
hasOrigin.add(repo);
|
|
934
|
-
continue;
|
|
935
|
-
}
|
|
936
|
-
const listed = listOpenMrs(repo, run);
|
|
937
|
-
if (!listed.ok) {
|
|
938
|
-
log(cfg.paths.guard_log, `pending-work: ${repo}: ${listed.why}; the open-MR check is skipped`);
|
|
939
|
-
if (listed.why !== "no origin remote") hasOrigin.add(repo); // forge down still enforces (b)
|
|
940
|
-
continue;
|
|
941
|
-
}
|
|
942
|
-
openMrs.set(repo, listed.mrs);
|
|
943
|
-
hasOrigin.add(repo);
|
|
944
|
-
cache.repos[repo] = listed.mrs;
|
|
945
|
-
cacheDirty = true;
|
|
946
|
-
}
|
|
947
|
-
if (cacheDirty) writeMrCache({ at: nowSec(), repos: cache.repos }, cfg);
|
|
948
|
-
const unlanded = hasOrigin.size ? new Set(unlandedRows(run(["wip-check"], {}).stdout).map(r => r.branch)) : null;
|
|
949
|
-
for (const p of plans) {
|
|
950
|
-
// (a) only MRs the plan itself mentions are pending work here: the sweep already flags
|
|
951
|
-
// unmentioned open MRs as UNTRACKED for the whole queue.
|
|
952
|
-
for (const mr of openMrs.get(p.repo) ?? []) {
|
|
953
|
-
if (!mentioned(mr.token, mr.branch, [p.text]) || briefNamesPending(brief, "MR", mr.token)) continue;
|
|
954
|
-
return `plan ${p.file} has pending work MR ${mr.token} not merged; say in the brief what it already holds and why this task does not redo it ("MR ${mr.token}: <what it holds> — this task: <why not overlapping>").`;
|
|
955
|
-
}
|
|
956
|
-
if (!unlanded || !hasOrigin.has(p.repo)) continue;
|
|
957
|
-
for (const b of [p.branch, worktreeBranch(p.worktree, run)]) {
|
|
958
|
-
if (!b || !unlanded.has(b) || briefNamesPending(brief, "Branch", b)) continue;
|
|
959
|
-
return `plan ${p.file} has pending work branch ${b} not merged; say in the brief what it already holds and why this task does not redo it ("Branch ${b}: <what it holds> — this task: <why not overlapping>").`;
|
|
960
|
-
}
|
|
961
|
-
}
|
|
962
|
-
return null;
|
|
963
|
-
}
|
|
964
|
-
|
|
965
|
-
/**
|
|
966
|
-
* The owner's pick order (plan 20261025_1700 P3): refuse a later `ledger.prefer` agent while an
|
|
967
|
-
* earlier one is free and under its provider cap, unless the brief carries "Pick note: <why>".
|
|
968
|
-
* Free comes from the pin's provider and provider-out.jsonl (absence of a record is free);
|
|
969
|
-
* "under its cap" counts the caller's running jobs whose label embeds the higher agent's name —
|
|
970
|
-
* a caller without job info counts 0, erring toward the owner's order, which Pick note unlocks.
|
|
971
|
-
*/
|
|
972
|
-
export function preferProblem(agent: string, brief: string, runningJobs: readonly string[] | undefined, cfg: Config): string | null {
|
|
973
|
-
const prefer = cfg.ledger.prefer;
|
|
974
|
-
if (!prefer.length) return null;
|
|
975
|
-
const mine = prefer.indexOf(agent);
|
|
976
|
-
if (mine <= 0) return null; // the first pick, or an agent the order does not name
|
|
977
|
-
if (/\bPick note:/i.test(brief)) return null;
|
|
978
|
-
for (let j = 0; j < mine; j++) {
|
|
979
|
-
const higher = prefer[j]!;
|
|
980
|
-
const provider = providerOfModel(pinModel(cfg, higher));
|
|
981
|
-
if (provider === null || outUntil(cfg, provider) !== null) continue; // unknown or out
|
|
982
|
-
const running = (runningJobs ?? []).filter(l => l.toLowerCase().includes(higher.toLowerCase())).length;
|
|
983
|
-
if (running >= cfg.ledger.max_running_per_provider) continue; // the higher pick is at its provider cap
|
|
984
|
-
return `${higher} is ahead of ${agent} in ledger.prefer and free (under its provider cap) — spawn ${higher}, or add "Pick note: <why>" to the brief.`;
|
|
985
|
-
}
|
|
986
|
-
return null;
|
|
987
|
-
}
|
|
988
|
-
|
|
989
|
-
/** P4 (plan 20261031_1207): `agent-ledger --cap`'s FULL line at spawn time — the agent's provider already runs its full share of live subagents. Counted from the caller's running job labels, the live data preferProblem counts (a caller without job info counts 0). */
|
|
990
|
-
function ledgerCapProblem(agent: string, runningJobs: readonly string[] | undefined, cfg: Config): string | null {
|
|
991
|
-
const provider = providerOfModel(pinModel(cfg, agent));
|
|
992
|
-
if (provider === null || outUntil(cfg, provider) !== null) return null;
|
|
993
|
-
const sharers = [agent, ...cfg.ledger.prefer.filter(a => providerOfModel(pinModel(cfg, a)) === provider)];
|
|
994
|
-
const running = (runningJobs ?? []).filter(l => sharers.some(n => l.toLowerCase().includes(n.toLowerCase()))).length;
|
|
995
|
-
if (running < cfg.ledger.max_running_per_provider) return null;
|
|
996
|
-
return `provider ${provider} is at its cap (${running} live of ${cfg.ledger.max_running_per_provider} running); stop or wait for one before spawning more.`;
|
|
997
|
-
}
|
|
998
|
-
|
|
999
|
-
/**
|
|
1000
|
-
* The one spawn verdict (plan 20261031_1207 P4): every refusal in one numbered list, so Main fixes
|
|
1001
|
-
* all of them in one round trip. The named plans' brief-lint errors and the provider-cap note (the
|
|
1002
|
-
* advice Main gathered by hand through `brief-lint` and `agent-ledger --cap`) ride along on an
|
|
1003
|
-
* already-refused spawn — alone they never refuse: real plans carry lint nits, and a full provider
|
|
1004
|
-
* is the prefer order's to weigh, not a gate of its own.
|
|
1005
|
-
*/
|
|
1006
|
-
function spawnVerdict(agent: string, problems: string[], lintFiles: string[], runningJobs: readonly string[] | undefined, cfg: Config): string | null {
|
|
1007
|
-
if (!problems.length) return null;
|
|
1008
|
-
const advice: string[] = [];
|
|
1009
|
-
for (const f of new Set(lintFiles)) {
|
|
1010
|
-
try {
|
|
1011
|
-
for (const e of lint(f, cfg).errs) advice.push(`${f}: ${e}`);
|
|
1012
|
-
} catch {} // an unreadable plan's refusal is planGate's to name
|
|
1013
|
-
}
|
|
1014
|
-
const cap = ledgerCapProblem(agent, runningJobs, cfg);
|
|
1015
|
-
if (cap) advice.push(cap);
|
|
1016
|
-
const all = [...problems, ...advice];
|
|
1017
|
-
return `${agent}: ${all.length} ${all.length === 1 ? "problem" : "problems"}:\n${all.map((p, i) => `${i + 1}. ${p}`).join("\n")}`;
|
|
1018
|
-
}
|
|
1019
|
-
|
|
1020
|
-
/**
|
|
1021
|
-
* Who is rate-limited comes from live data (plan 20261025_1700 P1): refuse a brief that asserts a
|
|
1022
|
-
* provider shown free by providerStatus is rate-limited — named directly or through a prefer
|
|
1023
|
-
* agent's pin. providerStatus lists only providers with a record, so a never-recorded provider is
|
|
1024
|
-
* not protected here; a past-tense mention does not match, because the claim must say "is …".
|
|
1025
|
-
*/
|
|
1026
|
-
export function providerClaimProblem(text: string, cfg: Config): string | null {
|
|
1027
|
-
const recorded = new Set(readOut(cfg).map(r => r.provider));
|
|
1028
|
-
const free = (provider: string | null): boolean => provider !== null && recorded.has(provider) && outUntil(cfg, provider) === null;
|
|
1029
|
-
const names = new Map<string, string>();
|
|
1030
|
-
for (const p of cfg.ledger.providers) if (free(p)) names.set(p, p);
|
|
1031
|
-
for (const agent of cfg.ledger.prefer) {
|
|
1032
|
-
const provider = providerOfModel(pinModel(cfg, agent));
|
|
1033
|
-
if (free(provider) && !names.has(agent) && provider !== null) names.set(agent, provider);
|
|
1034
|
-
}
|
|
1035
|
-
if (!names.size || !/\bis\b/i.test(text)) return null;
|
|
1036
|
-
|
|
1037
|
-
const m = new RegExp(`\\b(${[...names.keys()].map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})\\b[^.\\n]{0,80}?\\b(?:is|are)\\s+(?:still\\s+|now\\s+)?(?:rate[ -]?limited|rate limiting|throttled|out until|limited)`, "i").exec(text);
|
|
1038
|
-
if (!m) return null;
|
|
1039
|
-
const hit = [...names.entries()].find(([n]) => n.toLowerCase() === (m[1] ?? "").toLowerCase());
|
|
1040
|
-
if (hit === undefined) return null;
|
|
1041
|
-
const [name, provider] = hit;
|
|
1042
|
-
return `${name === provider ? provider : `${name} (provider ${provider})`} is free per the recorded provider state — do not claim it is rate-limited; read the providers line from agent-ledger --cap.`;
|
|
1043
|
-
}
|
|
1044
|
-
|
|
1045
|
-
/** Reason to refuse a `task` brief, or null; `files` receives the plans to record, `budgets` every named task's call budget (null = none), `staffing` each plan's named tasks of this call, `runningJobs` the caller's running job labels (undefined = no job info). Every refusal lands in one numbered verdict (plan 20261031_1207 P4). */
|
|
1046
|
-
export function spawnProblem(
|
|
1047
|
-
input: Record<string, unknown>,
|
|
1048
|
-
cfg: Config,
|
|
1049
|
-
files: string[] = [],
|
|
1050
|
-
budgets: Record<string, number | null> = {},
|
|
1051
|
-
staffing: Record<string, string[]> = {},
|
|
1052
|
-
runningJobs?: string[],
|
|
1053
|
-
runner: CommandRunner = defaultRunner,
|
|
1054
|
-
spawner: Spawner = "main",
|
|
1055
|
-
): string | null {
|
|
1056
|
-
const roles: Record<string, string | null> = {};
|
|
1057
|
-
const plannerRoles: Record<string, string> = {};
|
|
1058
|
-
const tasks = Array.isArray(input?.tasks) ? input.tasks : [];
|
|
1059
|
-
const context = String(input?.context ?? "");
|
|
1060
|
-
const allowed = q.allowedAgents(cfg.paths.subagents);
|
|
1061
|
-
const shared = briefBudget(context);
|
|
1062
|
-
const problems: string[] = [];
|
|
1063
|
-
const named: Record<string, number | null> = {};
|
|
1064
|
-
for (const t of tasks) {
|
|
1065
|
-
const agent = String(t?.agent ?? "task");
|
|
1066
|
-
const label = String(t?.name ?? agent);
|
|
1067
|
-
const text = `${context}\n${String(t?.task ?? "")}`;
|
|
1068
|
-
// The role line belongs to the task's own brief (the adapter keys the spawn's brief by it);
|
|
1069
|
-
// a mention in the shared context names no one's role.
|
|
1070
|
-
const plannerFor = plannerRolePlan(String(t?.task ?? ""));
|
|
1071
|
-
// planner mode P2 (c): a Planner-role brief is refused while the mode is main — the switch
|
|
1072
|
-
// is the owner's (`planner delegated`). While delegated the planner spawn skips the open-plan
|
|
1073
|
-
// gates below (the plan it names does not exist yet — writing it is the spawn's job), but the
|
|
1074
|
-
// ## Allowed deny still holds, and it needs a name to key its role.
|
|
1075
|
-
if (plannerFor && currentPlanner(cfg) === "main") {
|
|
1076
|
-
problems.push(`${label}: planner mode is main — a Planner-role spawn needs the owner's \`planner delegated\` switch.`);
|
|
1077
|
-
continue;
|
|
1078
|
-
}
|
|
1079
|
-
const plannerBad = plannerFor ? plannerPlanProblem(plannerFor) : null;
|
|
1080
|
-
if (plannerBad) {
|
|
1081
|
-
problems.push(`${label}: ${plannerBad}`);
|
|
1082
|
-
continue;
|
|
1083
|
-
}
|
|
1084
|
-
if (plannerFor && !t?.name) {
|
|
1085
|
-
problems.push(`${label}: a planner spawn needs a name (the task name keys its planner role).`);
|
|
1086
|
-
continue;
|
|
1087
|
-
}
|
|
1088
|
-
if (plannerFor) {
|
|
1089
|
-
if (!allowed.has(agent)) {
|
|
1090
|
-
problems.push(`${label}: agent "${agent}" is not in "## Allowed" of ${cfg.paths.subagents} (no expensive or unpinned models).`);
|
|
1091
|
-
continue;
|
|
1092
|
-
}
|
|
1093
|
-
plannerRoles[label] = plannerFor;
|
|
1094
|
-
continue;
|
|
1095
|
-
}
|
|
1096
|
-
if (!allowed.has(agent)) {
|
|
1097
|
-
problems.push(`${label}: agent "${agent}" is not in "## Allowed" of ${cfg.paths.subagents} (no expensive or unpinned models).`);
|
|
1098
|
-
continue;
|
|
1099
|
-
}
|
|
1100
|
-
const [why, plans] = planGate(text, label, cfg);
|
|
1101
|
-
if (why) {
|
|
1102
|
-
problems.push(why);
|
|
1103
|
-
continue;
|
|
1104
|
-
}
|
|
1105
|
-
// P3 (plan 20261028_1600): the task tool is the live spawn path; every task carries its own
|
|
1106
|
-
// pending-work check, before the call-wide gates below. The task's own `Call budget:` line
|
|
1107
|
-
// wins over the shared context's.
|
|
1108
|
-
const role = reviewRole(t?.name, plans, text, agent, cfg, spawner);
|
|
1109
|
-
const taskProblems = [
|
|
1110
|
-
pendingWorkProblem(plans, text, cfg, runner),
|
|
1111
|
-
role.problem,
|
|
1112
|
-
reviewPassProblem(plans, text, agent, cfg, spawner),
|
|
1113
|
-
];
|
|
1114
|
-
const budget = briefBudget(String(t?.task ?? "")) ?? shared;
|
|
1115
|
-
if (budget !== null) {
|
|
1116
|
-
if (!t?.name) taskProblems.push(`${label}: "Call budget: ${budget}" needs a task name (the budget is keyed by it).`);
|
|
1117
|
-
else if (budget < 10 || budget > cfg.guards.sub_max_calls_cap)
|
|
1118
|
-
taskProblems.push(`call budget ${budget} is outside the allowed range 10..${cfg.guards.sub_max_calls_cap}.`);
|
|
1119
|
-
}
|
|
1120
|
-
const own = taskProblems.filter((p): p is string => p !== null).map(p => (p.startsWith(`${label}:`) ? p : `${label}: ${p}`));
|
|
1121
|
-
if (own.length) {
|
|
1122
|
-
problems.push(...own);
|
|
1123
|
-
continue;
|
|
1124
|
-
}
|
|
1125
|
-
if (t?.name) {
|
|
1126
|
-
roles[label] = role.plan;
|
|
1127
|
-
named[label] = budget;
|
|
1128
|
-
for (const f of plans) staffing[f] = [...(staffing[f] ?? []), label];
|
|
1129
|
-
}
|
|
1130
|
-
files.push(...plans);
|
|
1131
|
-
}
|
|
1132
|
-
Object.assign(budgets, named);
|
|
1133
|
-
// Who is limited and who goes first come from live data and ledger.prefer (plan 20261025_1700
|
|
1134
|
-
// P3): the same rules checkSpawn applies to single-spawn events, per task.
|
|
1135
|
-
const joined = `${context}\n${tasks.map(t => String(t?.task ?? "")).join("\n")}`;
|
|
1136
|
-
const claim = providerClaimProblem(joined, cfg);
|
|
1137
|
-
if (claim) problems.push(claim);
|
|
1138
|
-
for (const t of tasks) {
|
|
1139
|
-
const pick = preferProblem(String(t?.agent ?? "task"), `${context}\n${String(t?.task ?? "")}`, runningJobs, cfg);
|
|
1140
|
-
if (pick) problems.push(`${String(t?.name ?? t?.agent ?? "task")}: ${pick}`);
|
|
1141
|
-
}
|
|
1142
|
-
// Priority gate (20261025_0215 P3): once per `task` call, over the plans this call names; the
|
|
1143
|
-
// skip lines may sit in the shared context or any task text.
|
|
1144
|
-
const gate = priorityGate(
|
|
1145
|
-
files,
|
|
1146
|
-
runningJobs,
|
|
1147
|
-
joined,
|
|
1148
|
-
cfg,
|
|
1149
|
-
String((tasks[0] && (tasks[0].name ?? tasks[0].agent)) ?? "task"),
|
|
1150
|
-
String((tasks[0] && tasks[0].agent) ?? "task"),
|
|
1151
|
-
spawner,
|
|
1152
|
-
);
|
|
1153
|
-
if (gate) problems.push(gate);
|
|
1154
|
-
const inc = incidentSpawnProblem("spawn", JSON.stringify(input), files, cfg);
|
|
1155
|
-
if (inc) problems.push(inc);
|
|
1156
|
-
const verdict = spawnVerdict(
|
|
1157
|
-
String((tasks[0] && (tasks[0].name ?? tasks[0].agent)) ?? "task"),
|
|
1158
|
-
problems,
|
|
1159
|
-
files.length ? files : briefPlans(joined, cfg).map(p => p.file),
|
|
1160
|
-
runningJobs,
|
|
1161
|
-
cfg,
|
|
1162
|
-
);
|
|
1163
|
-
if (verdict) return verdict;
|
|
1164
|
-
for (const [name, plan] of Object.entries(roles)) recordReviewSpawn(name, plan, cfg.paths);
|
|
1165
|
-
for (const [name, plan] of Object.entries(plannerRoles)) recordPlannerSpawn(name, plan, cfg.paths);
|
|
1166
|
-
return null;
|
|
1167
|
-
}
|
|
1168
|
-
|
|
1169
|
-
function runBlockers(plan: Plan, hit: string[], e: ToolEvent, cfg: Config): string | null {
|
|
1170
|
-
// A caller staffed on a different plan (staffing.json holds the task names, keyed by agentId)
|
|
1171
|
-
// only grazes this plan (I-20261028-111): its path blockers must judge the covered paths,
|
|
1172
|
-
// not every path the command names.
|
|
1173
|
-
const staffing = readStaffing(cfg.paths);
|
|
1174
|
-
const foreign = !(staffing[plan.file] ?? []).includes(e.agentId) && Object.entries(staffing).some(([f, names]) => f !== plan.file && names.includes(e.agentId));
|
|
1175
|
-
for (const b of plan.blockers) {
|
|
1176
|
-
try {
|
|
1177
|
-
execFileSync(b.script, b.args, {
|
|
1178
|
-
input: JSON.stringify({ tool: e.tool, input: e.input, cwd: e.cwd, agent: e.agent, repo: plan.repo, plan: plan.file, paths: hit, ...(foreign ? { foreign: true } : {}) }),
|
|
1179
|
-
encoding: "utf8",
|
|
1180
|
-
timeout: cfg.guards.blocker_timeout_ms,
|
|
1181
|
-
stdio: ["pipe", "pipe", "pipe"],
|
|
1182
|
-
});
|
|
1183
|
-
} catch (err) {
|
|
1184
|
-
// P5c (plan 20261031_1207): the deny names the hit paths and the script's own output
|
|
1185
|
-
// (stdout+stderr, first 300 chars) so the worker can fix the named file instead of
|
|
1186
|
-
// retrying blind; the Error message is the last resort for a script with no output.
|
|
1187
|
-
const stdout = typeof err === "object" && err !== null && "stdout" in err && typeof err.stdout === "string" ? err.stdout.trim() : "";
|
|
1188
|
-
const stderr = typeof err === "object" && err !== null && "stderr" in err && typeof err.stderr === "string" ? err.stderr.trim() : "";
|
|
1189
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
1190
|
-
const detail = `${stdout}\n${stderr}`.trim().slice(0, 300);
|
|
1191
|
-
const why = detail || `${path.basename(b.script)} failed (${message})`;
|
|
1192
|
-
return `blocked by plan ${path.basename(plan.file)} (${hit.join(", ")}): ${why}`;
|
|
1193
|
-
}
|
|
1194
|
-
}
|
|
1195
|
-
return null;
|
|
1196
|
-
}
|
|
1197
|
-
|
|
1198
|
-
// Words a shell line may put before the tool: launchers, shells with -c, VAR=value, and a script path ending in main.ts.
|
|
1199
|
-
const LAUNCHERS: Record<string, true> = { bun: true, run: true, neurastream: true, node: true, npx: true, bunx: true, env: true, sudo: true, nohup: true, exec: true, bash: true, sh: true, zsh: true, "-c": true };
|
|
1200
|
-
|
|
1201
|
-
// True when a command segment runs queue-close or queue-cancel: the tool is the segment's first word after launchers.
|
|
1202
|
-
// Segments also split at $( and backticks, so substitutions and `sh -c "..."` bodies are checked too.
|
|
1203
|
-
function runsCloser(input: Record<string, unknown>): boolean {
|
|
1204
|
-
const text = Object.values(input).filter((v): v is string => typeof v === "string").join("\n");
|
|
1205
|
-
return text.split(/&&|\|\||;|\||\n|\$\(|`/).some(seg => {
|
|
1206
|
-
const words = seg.trim().split(/\s+/).filter(Boolean).map(w => w.replace(/^["'(]+|["')]+$/g, ""));
|
|
1207
|
-
let i = 0;
|
|
1208
|
-
while (i < words.length && (LAUNCHERS[words[i] ?? ""] === true || /^\w+=/.test(words[i] ?? "") || /(^|\/)main\.ts$/.test(words[i] ?? ""))) i++;
|
|
1209
|
-
const cmd = (words[i] ?? "").split("/").pop() ?? "";
|
|
1210
|
-
return /^queue-(close|cancel)$/.test(cmd);
|
|
1211
|
-
});
|
|
1212
|
-
}
|
|
1213
|
-
|
|
1214
|
-
const bin = (w: string | undefined) => (w ?? "").replace(/^["']+|["']+$/g, "").split("/").pop() ?? "";
|
|
1215
|
-
|
|
1216
|
-
// P5g (plan 20261027_0915): the shell text a call would really run — bash's command line, eval's
|
|
1217
|
-
// !cmd shell-escape lines and the Bun.$/spawn arguments inside its code. Everything else in an
|
|
1218
|
-
// input is prose or string data (a task brief, plan text, an eval cell that only names the page's
|
|
1219
|
-
// words), and prose runs nothing.
|
|
1220
|
-
function shellText(input: Record<string, unknown>): string {
|
|
1221
|
-
if (typeof input.command === "string") return input.command;
|
|
1222
|
-
const code = input.code;
|
|
1223
|
-
if (typeof code !== "string") return "";
|
|
1224
|
-
const out: string[] = [];
|
|
1225
|
-
for (const m of code.matchAll(/^[ \t]*!(.+)$/gm)) out.push(m[1] ?? "");
|
|
1226
|
-
for (const m of code.matchAll(/(?<!\w)(?:Bun\.)?\$[ \t]*`((?:[^`\\]|\\.)*)`/g)) out.push(m[1] ?? "");
|
|
1227
|
-
for (const m of code.matchAll(/\b(?:Bun\.)?spawn(?:Sync)?[ \t]*\(([^)]*)/g))
|
|
1228
|
-
out.push(
|
|
1229
|
-
[...(m[1] ?? "").matchAll(/[`"']([^`"']*)[`"']/g)]
|
|
1230
|
-
.map(s => s[1] ?? "")
|
|
1231
|
-
.join(" "),
|
|
1232
|
-
);
|
|
1233
|
-
return out.join("\n");
|
|
1234
|
-
}
|
|
1235
|
-
|
|
1236
|
-
// True when a command segment starts the owner page (plan 20261024_2230 P3c): `neurastream
|
|
1237
|
-
// workspace` serves it and `systemctl --user start/restart/enable` of neurastream-workspace
|
|
1238
|
-
// relaunches it — the owner's systemd moves, never an agent's, unlocked or not. P5g: the text is
|
|
1239
|
-
// shellText's — only real shell commands, never prose. Segment splitting and launcher skipping
|
|
1240
|
-
// match runsCloser, so `sh -c "neurastream workspace"` and `sudo systemctl --user ...` are seen.
|
|
1241
|
-
// (The command and unit were `ui` before the workspace rename; that name is gone, no alias.)
|
|
1242
|
-
function startsOwnerUi(input: Record<string, unknown>): boolean {
|
|
1243
|
-
const text = shellText(input);
|
|
1244
|
-
return text.split(/&&|\|\||;|\||\n|\$\(|`/).some(seg => {
|
|
1245
|
-
const words = seg.trim().split(/\s+/).filter(Boolean).map(w => w.replace(/^["'(]+|["')]+$/g, ""));
|
|
1246
|
-
let i = 0;
|
|
1247
|
-
while (i < words.length && (LAUNCHERS[words[i] ?? ""] === true || /^\w+=/.test(words[i] ?? "") || /(^|\/)main\.ts$/.test(words[i] ?? ""))) i++;
|
|
1248
|
-
const cmd = bin(words[i]);
|
|
1249
|
-
if ((cmd === "workspace" && bin(words[i - 1]) === "neurastream") || (cmd === "neurastream" && bin(words[i + 1]) === "workspace")) return true;
|
|
1250
|
-
return (
|
|
1251
|
-
cmd === "systemctl" &&
|
|
1252
|
-
words.some(w => w === "--user") &&
|
|
1253
|
-
words.some(w => w === "start" || w === "restart" || w === "enable") &&
|
|
1254
|
-
words.some(w => bin(w) === "neurastream-workspace" || w.startsWith("neurastream-workspace."))
|
|
1255
|
-
);
|
|
1256
|
-
});
|
|
1257
|
-
}
|
|
1258
|
-
|
|
1259
|
-
// True when a command segment runs `claim release <plan> --force` (plan 20261027_1300 P4): it
|
|
1260
|
-
// frees another Main's claim, the owner's terminal move, refused for every agent. Segment
|
|
1261
|
-
// splitting and launcher skipping match startsOwnerUi, so `sh -c "neurastream claim release x
|
|
1262
|
-
// --force"` and `sudo neurastream claim release x --force` are seen too.
|
|
1263
|
-
function forceClaimRelease(input: Record<string, unknown>): boolean {
|
|
1264
|
-
const text = Object.values(input).filter((v): v is string => typeof v === "string").join("\n");
|
|
1265
|
-
return text.split(/&&|\|\||;|\||\n|\$\(|`/).some(seg => {
|
|
1266
|
-
const words = seg.trim().split(/\s+/).filter(Boolean).map(w => w.replace(/^["'(]+|["')]+$/g, ""));
|
|
1267
|
-
let i = 0;
|
|
1268
|
-
while (i < words.length && (LAUNCHERS[words[i] ?? ""] === true || /^\w+=/.test(words[i] ?? "") || /(^|\/)main\.ts$/.test(words[i] ?? ""))) i++;
|
|
1269
|
-
const seq = words.slice(i).map(bin);
|
|
1270
|
-
if (seq[0] === "neurastream") seq.shift();
|
|
1271
|
-
return seq[0] === "claim" && seq.includes("release") && seq.includes("--force");
|
|
1272
|
-
});
|
|
1273
|
-
}
|
|
1274
|
-
|
|
1275
|
-
// True when a command segment lands work on a remote (plan 20261025_1940 P2): `git push`,
|
|
1276
|
-
// `glab mr merge`, `gh pr merge`. Segment splitting and launcher skipping match startsOwnerUi,
|
|
1277
|
-
// so `sh -c "git push"`, `sudo git push` and chained pushes are seen too.
|
|
1278
|
-
function landingCommand(input: Record<string, unknown>): boolean {
|
|
1279
|
-
const text = Object.values(input).filter((v): v is string => typeof v === "string").join("\n");
|
|
1280
|
-
return text.split(/&&|\|\||;|\||\n|\$\(|`/).some(seg => {
|
|
1281
|
-
const words = seg.trim().split(/\s+/).filter(Boolean).map(w => w.replace(/^["'(]+|["')]+$/g, ""));
|
|
1282
|
-
let i = 0;
|
|
1283
|
-
while (i < words.length && (LAUNCHERS[words[i] ?? ""] === true || /^\w+=/.test(words[i] ?? "") || /(^|\/)main\.ts$/.test(words[i] ?? ""))) i++;
|
|
1284
|
-
const cmd = (words[i] ?? "").split("/").pop() ?? "";
|
|
1285
|
-
if (cmd === "git" && words[i + 1] === "push") return true;
|
|
1286
|
-
if (cmd === "glab" && words[i + 1] === "mr" && words[i + 2] === "merge") return true;
|
|
1287
|
-
if (cmd === "gh" && words[i + 1] === "pr" && words[i + 2] === "merge") return true;
|
|
1288
|
-
return false;
|
|
1289
|
-
});
|
|
1290
|
-
}
|
|
1291
|
-
|
|
1292
|
-
// P5/P5c (plan 20261031_1207): the shell text a read-only fast path may never carry — a landing
|
|
1293
|
-
// command (push / MR merge), git add or commit, npm publish, a bypass_spawn launch, or a MUTATING
|
|
1294
|
-
// write. Landing and commit commands produce no write targets, so this text filter — not
|
|
1295
|
-
// writeTargets — is what keeps them out of the review lock's shell allow and the blocker skip.
|
|
1296
|
-
// One predicate for both callers; reviewLockProblem denies it, subRules keeps the blockers on it.
|
|
1297
|
-
// The removal check uses the commit alternative only: `git add` stages; the check judges at commit.
|
|
1298
|
-
const GIT_ADD_OR_COMMIT = /\bgit\s+(add|commit)\b/;
|
|
1299
|
-
function writesShellText(input: Record<string, unknown>, cfg: Config): boolean {
|
|
1300
|
-
if (landingCommand(input)) return true;
|
|
1301
|
-
const text = q.withoutQuotedRedirects(Object.values(input).filter((v): v is string => typeof v === "string").join("\n"));
|
|
1302
|
-
if (GIT_ADD_OR_COMMIT.test(text) || /\bnpm\s+publish\b/.test(text)) return true;
|
|
1303
|
-
if (cfg.guards.bypass_spawn.some(entry => bypassRegExp(entry).test(text))) return true;
|
|
1304
|
-
return q.MUTATING.test(text);
|
|
1305
|
-
}
|
|
1306
|
-
|
|
1307
|
-
// The read tool's stand-in for a value it hid. A file may hold one only where it is produced
|
|
1308
|
-
// (secret-redact.ts) or exercised (its tests).
|
|
1309
|
-
const PLACEHOLDER = "[REDACTED:";
|
|
1310
|
-
const PLACEHOLDER_FILES = [/\/src\/core\/secret-redact\.ts$/, /\/tests\/secret-redact[^/]*\.test\.ts$/];
|
|
1311
|
-
/** What a write/edit/ast_edit call would add: every text argument but the targets and the replaced text. */
|
|
1312
|
-
function addedText(input: Record<string, unknown>): string {
|
|
1313
|
-
const skip = new Set(["path", "file", "cwd", "old_string", "old", "oldText", "i"]);
|
|
1314
|
-
return Object.entries(input)
|
|
1315
|
-
.filter(([key, value]) => typeof value === "string" && !skip.has(key))
|
|
1316
|
-
.map(([, value]) => value as string)
|
|
1317
|
-
.join("\n");
|
|
1318
|
-
}
|
|
1319
|
-
|
|
1320
|
-
// P5g: tools whose string fields are content — a task brief, the text a write or edit adds — are
|
|
1321
|
-
// prose, never reads; the notify-secret check scans only their path argument.
|
|
1322
|
-
const PROSE_TOOLS: Record<string, true> = { task: true, write: true, edit: true, ast_edit: true };
|
|
1323
|
-
|
|
1324
|
-
// Only a tool call's path arguments — the paths it names as targets, not its prose fields.
|
|
1325
|
-
function pathArgs(input: Record<string, unknown>): Record<string, unknown> {
|
|
1326
|
-
const out: Record<string, unknown> = {};
|
|
1327
|
-
for (const key of ["path", "file"]) if (typeof input[key] === "string") out[key] = input[key];
|
|
1328
|
-
return out;
|
|
1329
|
-
}
|
|
1330
|
-
|
|
1331
|
-
// Subagent half of a tool call (the original plan-guard checkCall without the main return).
|
|
1332
|
-
// `cap` is the sub's hard call cap: its recorded per-spawn budget, else the global sub_max_calls.
|
|
1333
|
-
function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[], writes: string[], cfg: Config, cap: number): string | null {
|
|
1334
|
-
// P6 (plan 20261024_1915): a sub's `git commit` is scanned first — its staged diff must not add
|
|
1335
|
-
// the removal comments diff-check flags. Detected through GIT_ADD_OR_COMMIT (the predicate
|
|
1336
|
-
// writesShellText carries); the refusal goes back through checkTool's deny(). Git that cannot
|
|
1337
|
-
// be read fails open (write-check.ts: a broken scan never blocks). Main is not gated: only
|
|
1338
|
-
// subRules sees this. A staged diff has no subject yet, so the subject rule is the CLI's <rev>.
|
|
1339
|
-
if (cfg.guards.shell_tools.includes(e.tool)) {
|
|
1340
|
-
const git = GIT_ADD_OR_COMMIT.exec(q.withoutQuotedRedirects(Object.values(input).filter((v): v is string => typeof v === "string").join("\n")));
|
|
1341
|
-
if (git?.[1] === "commit") {
|
|
1342
|
-
let flags: RemovalFlag[] = [];
|
|
1343
|
-
try {
|
|
1344
|
-
flags = removalFlags(stagedDiff(e.cwd), "", cfg);
|
|
1345
|
-
} catch { /* no readable repo in this cwd: nothing to flag */ }
|
|
1346
|
-
if (flags.length)
|
|
1347
|
-
return (
|
|
1348
|
-
"git commit refused: the staged diff adds removal comments (reword or drop them, then re-stage):\n" +
|
|
1349
|
-
flags.map(f => `${f.file}:${f.line}: ${f.text}`).join("\n")
|
|
1350
|
-
);
|
|
1351
|
-
}
|
|
1352
|
-
}
|
|
1353
|
-
// Closing and cancelling are Main's decisions: a shell that runs the tool is refused; one that only names its path is not.
|
|
1354
|
-
if (cfg.guards.shell_tools.includes(e.tool) && runsCloser(input))
|
|
1355
|
-
return 'queue-close and queue-cancel are Main\'s; report in your plan\'s "## Progress" instead.';
|
|
1356
|
-
// The read tool prints a placeholder for a value it hid, never the value (I-20261027-158,
|
|
1357
|
-
// I-20261027-160: one copy silently broke the shipped config template). Writing that text back
|
|
1358
|
-
// is refused; the file that produces one and the tests that exercise it are the exceptions.
|
|
1359
|
-
if ((e.tool === "write" || e.tool === "edit" || e.tool === "ast_edit") && addedText(input).includes(PLACEHOLDER)) {
|
|
1360
|
-
const keeper = writes.length > 0 && writes.every(p => PLACEHOLDER_FILES.some(rx => rx.test(p)));
|
|
1361
|
-
if (!keeper)
|
|
1362
|
-
return "this is the read tool's redaction placeholder, not the real value; re-read the file raw or keep the original line";
|
|
1363
|
-
}
|
|
1364
|
-
// planner mode P2 (b): while delegated, every sub write to a plan path is refused except the
|
|
1365
|
-
// plan its brief named in the approved spawn's `Planner role for <plan path>` line (the
|
|
1366
|
-
// planner-spawns binding). A NEW plan file is invisible to the indexed-plan gate below
|
|
1367
|
-
// (isOrchestrationPath + planAt both false), so the refusal fires here — never by accident of
|
|
1368
|
-
// indexing — and covers shell redirects through writeTargets too.
|
|
1369
|
-
const delegatedPlanner = currentPlanner(cfg) === "delegated" ? plannerSpawnPlan(e.agentId, cfg.paths) : null;
|
|
1370
|
-
// I-20261102-27: the seam above also refused the REVIEW spawn, and a review spawn's only write
|
|
1371
|
-
// is its own PLAN REVIEW / CODE REVIEW line — so in delegated mode no plan could ever record a
|
|
1372
|
-
// PASS and no implementer could spawn. The named review spawn of a plan may still write that
|
|
1373
|
-
// plan; the REVIEW_LINE rule below then decides whether the line is its verdict.
|
|
1374
|
-
const delegatedReview = currentPlanner(cfg) === "delegated" ? (matchReviewSpawn(readReviewSpawns(cfg.paths), e.agentId ?? "")?.spawn.plan ?? null) : null;
|
|
1375
|
-
if (currentPlanner(cfg) === "delegated") {
|
|
1376
|
-
for (const p of writes) {
|
|
1377
|
-
if (!MAIN_PLAN_FILE.test(p) || p === delegatedPlanner) continue;
|
|
1378
|
-
if (delegatedReview && path.resolve(e.cwd, p) === path.resolve(delegatedReview)) continue;
|
|
1379
|
-
if (delegatedPlanner) return `planner is delegated — your Planner role names ${delegatedPlanner} only; ${p} is not yours to write.`;
|
|
1380
|
-
return `planner is delegated — plan files are the planner agent's; your brief carries no "Planner role for <plan path>" line, so ${p} is refused.`;
|
|
1381
|
-
}
|
|
1382
|
-
}
|
|
1383
|
-
const plans = q.activePlans(cfg.paths);
|
|
1384
|
-
if (e.calls >= cap) {
|
|
1385
|
-
// Plan edit targets come from writeTargets (write and structured/hashline edit)
|
|
1386
|
-
// with touchedPaths as fallback; plan reads match any read tool.
|
|
1387
|
-
const planEdit =
|
|
1388
|
-
(e.tool === "write" || e.tool === "edit") &&
|
|
1389
|
-
(writes.length > 0 ? writes.every(p => q.planAt(p, plans)) : paths.length > 0 && paths.every(p => q.planAt(p, plans)));
|
|
1390
|
-
const planRead = cfg.guards.read_tools.includes(e.tool) && paths.length > 0 && paths.every(p => q.planAt(p, plans));
|
|
1391
|
-
if (!planEdit && !planRead)
|
|
1392
|
-
return `call budget spent (${e.calls}/${cap}). Only reading and editing your plan's "## Progress" is allowed now: write what you did, what is verified, what is next, then end your run.`;
|
|
1393
|
-
}
|
|
1394
|
-
if (!plans.length || !paths.length) return null;
|
|
1395
|
-
for (const p of writes) {
|
|
1396
|
-
if (!q.isOrchestrationPath(p, plans, cfg.paths.queue_index)) continue;
|
|
1397
|
-
if (!q.planAt(p, plans)) {
|
|
1398
|
-
// planner mode P2 (b): the bound planner plan routes into checkPlanEdit (Planner header,
|
|
1399
|
-
// Main-only lines), it is not Main's — but only that path, and only while delegated.
|
|
1400
|
-
if (currentPlanner(cfg) === "delegated" && p === delegatedPlanner) continue;
|
|
1401
|
-
return `${p} belongs to Main (main index / blocker script); read it, never change it. Report instead.`;
|
|
1402
|
-
}
|
|
1403
|
-
if (e.tool !== "write" && e.tool !== "edit")
|
|
1404
|
-
return `${p} is a plan file: change its "## Progress" section only with the edit or write tool.`;
|
|
1405
|
-
}
|
|
1406
|
-
for (const plan of plans) {
|
|
1407
|
-
const hit = paths.filter(p => !q.isOrchestrationPath(p, plans, cfg.paths.queue_index) && q.planCovers(plan, p, plans));
|
|
1408
|
-
if (!hit.length) continue;
|
|
1409
|
-
// An invalid plan stops code writes, not reads and not the repair of plan files: refusing those
|
|
1410
|
-
// too left a planner unable to fix the very errors the guard named (writes are checked before
|
|
1411
|
-
// the file is valid, so no valid text could ever land).
|
|
1412
|
-
const readOnly = cfg.guards.read_tools.includes(e.tool) || (cfg.guards.shell_tools.includes(e.tool) && !writes.length && !writesShellText(input, cfg));
|
|
1413
|
-
const planRepair = writes.length > 0 && writes.every(w => q.planAt(w, plans));
|
|
1414
|
-
if (plan.errors.length && !readOnly && !planRepair) return `plan ${plan.file} is invalid (${plan.errors.join("; ")}). Stop and report to Main.`;
|
|
1415
|
-
// P5c (plan 20261031_1207): reads and read-only shell calls skip the phase-0 blockers — a
|
|
1416
|
-
// failing blocker used to deny every read of a covered path and send the worker back blind.
|
|
1417
|
-
// The shell filter is the review lock's (writesShellText), so landing text keeps its blocker.
|
|
1418
|
-
if (!readOnly && !planRepair) {
|
|
1419
|
-
const why = runBlockers(plan, hit, e, cfg);
|
|
1420
|
-
if (why) return why;
|
|
1421
|
-
}
|
|
1422
|
-
}
|
|
1423
|
-
return null;
|
|
1424
|
-
}
|
|
1425
|
-
|
|
1426
|
-
// Main's edit limit (20261025_1940 P2): the cap follows the autonomy tier — autonomy.strict_edit_limit
|
|
1427
|
-
// in strict, guards.main_edit_limit in opinionated, none in full. Window starts at the first counted
|
|
1428
|
-
// change, resets after main_window_min minutes and at every owner message. State lives in the queue
|
|
1429
|
-
// state dir so one-shot CLI processes share the window (the original kept it in extension memory for
|
|
1430
|
-
// one session).
|
|
1431
|
-
function editWindow(e: ToolEvent, input: Record<string, unknown>, cfg: Config): Decision {
|
|
1432
|
-
const files = changedProjectFiles(e.tool, input, e.cwd, cfg);
|
|
1433
|
-
if (!files.length) return ALLOW;
|
|
1434
|
-
const tier = currentTier(cfg);
|
|
1435
|
-
if (tier === "full") return ALLOW; // no cap: Main works unattended
|
|
1436
|
-
const limit = tier === "strict" ? cfg.autonomy.strict_edit_limit : cfg.guards.main_edit_limit;
|
|
1437
|
-
const limitName = tier === "strict" ? "autonomy.strict_edit_limit" : "owner limit";
|
|
1438
|
-
const now = Date.now();
|
|
1439
|
-
const w = readWindow(cfg.paths);
|
|
1440
|
-
if (w.used.length && now - w.windowStart >= cfg.guards.main_window_min * 60_000) w.used = [];
|
|
1441
|
-
if (w.used.length >= limit) {
|
|
1442
|
-
const mins = Math.ceil((w.windowStart + cfg.guards.main_window_min * 60_000 - now) / 60_000);
|
|
1443
|
-
log(cfg.paths.guard_log, `BLOCK tool=${e.tool} after ${w.used.length} edits (tier ${tier}): ${files.join(",")} rule=main.edit-window`);
|
|
1444
|
-
return deny(
|
|
1445
|
-
`main-guard: tier ${tier} — Main already changed project files ${w.used.length} times in this ${cfg.guards.main_window_min}-minute window ` +
|
|
1446
|
-
`(${limitName} ${limit}; resets in ${mins} min). Main writes plans, not code: put the work in a plan ` +
|
|
1447
|
-
`(listed in ${cfg.paths.queue_index}, phase-0 blockers first) and spawn an implementer. Changes so far: ${w.used.join(", ")}`,
|
|
1448
|
-
"main.edit-window",
|
|
1449
|
-
);
|
|
1450
|
-
}
|
|
1451
|
-
if (!w.used.length) w.windowStart = now;
|
|
1452
|
-
w.used.push(`${e.tool}:${files[0]!}`);
|
|
1453
|
-
writeWindow(w, cfg.paths);
|
|
1454
|
-
const left = limit - w.used.length;
|
|
1455
|
-
if (left <= 2)
|
|
1456
|
-
return {
|
|
1457
|
-
allow: true,
|
|
1458
|
-
reason: "",
|
|
1459
|
-
inject: `main-guard: tier ${tier} — ${left} project-file change(s) left in this ${cfg.guards.main_window_min}-minute window; then delegate.`,
|
|
1460
|
-
};
|
|
1461
|
-
return ALLOW;
|
|
1462
|
-
}
|
|
1463
|
-
|
|
1464
|
-
// --- incidents (src/core/incidents.ts): open ones push Main until each has a plan or dismissal ---
|
|
1465
|
-
|
|
1466
|
-
function openIncidentList(cfg: Config): IncidentView[] {
|
|
1467
|
-
try {
|
|
1468
|
-
return openIncidents(cfg);
|
|
1469
|
-
} catch (err) {
|
|
1470
|
-
log(cfg.paths.guard_log, `cannot read incidents: ${err}`);
|
|
1471
|
-
return [];
|
|
1472
|
-
}
|
|
1473
|
-
}
|
|
1474
|
-
|
|
1475
|
-
/** The injected prompt line for one open incident, with the two ways to clear it. */
|
|
1476
|
-
export function incidentLine(i: IncidentView): string {
|
|
1477
|
-
return (
|
|
1478
|
-
`INCIDENT ${i.id} [${i.source}/${i.kind}]: ${i.summary} — plan the fix: \`neurastream incident plan ${i.id} <plan.md>\`` +
|
|
1479
|
-
` (the plan must contain "INCIDENT ${i.id}"), or dismiss: \`neurastream incident dismiss ${i.id} --why "<text>"\``
|
|
1480
|
-
);
|
|
1481
|
-
}
|
|
1482
|
-
|
|
1483
|
-
/**
|
|
1484
|
-
* While an owner-correction incident (source "realtime") is open, a launch must be fix work: its
|
|
1485
|
-
* brief (or a plan the brief names) cites `INCIDENT <id>` of an open one. Notes from worker
|
|
1486
|
-
* findings/traces never refuse a spawn (plan 20261031_1207 P2). Returns the refusal reason, or
|
|
1487
|
-
* null; `label` names the log line.
|
|
1488
|
-
*/
|
|
1489
|
-
function incidentSpawnProblem(label: string, brief: string, namedPlans: string[], cfg: Config): string | null {
|
|
1490
|
-
const open = openIncidentList(cfg).filter(i => i.source === "realtime");
|
|
1491
|
-
if (!open.length) return null;
|
|
1492
|
-
const texts = [brief];
|
|
1493
|
-
for (const f of namedPlans) {
|
|
1494
|
-
try {
|
|
1495
|
-
texts.push(readFileSync(f, "utf8"));
|
|
1496
|
-
} catch {}
|
|
1497
|
-
}
|
|
1498
|
-
const remaining = open.filter(i => !texts.some(t => t.includes(`INCIDENT ${i.id}`)));
|
|
1499
|
-
if (!remaining.length) return null;
|
|
1500
|
-
const ids = remaining.map(i => i.id).join(", ");
|
|
1501
|
-
log(cfg.paths.guard_log, `BLOCK ${label}: open incidents: ${ids}`);
|
|
1502
|
-
return (
|
|
1503
|
-
`open incident(s) ${ids} must be acted on before other work. Write a plan that contains "INCIDENT <id>" ` +
|
|
1504
|
-
`(listed in ${cfg.paths.queue_index}) and record it: \`neurastream incident plan <id> <plan.md>\`, or dismiss the ` +
|
|
1505
|
-
'incident: `neurastream incident dismiss <id> --why "<text>"`. Fix work goes through: name that plan in the brief.'
|
|
1506
|
-
);
|
|
1507
|
-
}
|
|
1508
|
-
|
|
1509
|
-
/**
|
|
1510
|
-
* A `task` launch: the cancel check, the spawn gates, then the records. Main's and a sub's launch
|
|
1511
|
-
* both come through here (plan 20261028_1600 P4i). Returns the refusal, or null.
|
|
1512
|
-
*/
|
|
1513
|
-
function taskLaunch(input: Record<string, unknown>, cfg: Config, runningJobs: string[] | undefined, spawner: Spawner, runs?: RunSource): string | null {
|
|
1514
|
-
const pending = q.cancelPending(cfg.paths);
|
|
1515
|
-
if (pending) {
|
|
1516
|
-
log(cfg.paths.guard_log, `BLOCK spawn: cancel pending (${pending.words})`);
|
|
1517
|
-
return `${CANCEL_TODO} Flagged: "${pending.words}"`;
|
|
1518
|
-
}
|
|
1519
|
-
// P4 (plan 20261031_1207): spawnProblem's verdict now carries the incident check too, so one
|
|
1520
|
-
// deny lists every problem.
|
|
1521
|
-
const files: string[] = [];
|
|
1522
|
-
const budgets: Record<string, number | null> = {};
|
|
1523
|
-
const staffing: Record<string, string[]> = {};
|
|
1524
|
-
const why = spawnProblem(input, cfg, files, budgets, staffing, runningJobs, defaultRunner, spawner);
|
|
1525
|
-
if (why) {
|
|
1526
|
-
log(cfg.paths.guard_log, `BLOCK spawn: ${why}`);
|
|
1527
|
-
return why;
|
|
1528
|
-
}
|
|
1529
|
-
const inc = incidentSpawnProblem("spawn", JSON.stringify(input), files, cfg);
|
|
1530
|
-
if (inc) return inc;
|
|
1531
|
-
const spawned: unknown[] = Array.isArray(input.tasks) ? input.tasks : [];
|
|
1532
|
-
const names = spawned.map((t) => (t as { name?: unknown } | null)?.name);
|
|
1533
|
-
const held = claimGate(files, cfg, {
|
|
1534
|
-
agentIds: names.filter((n): n is string => typeof n === "string" && n !== ""),
|
|
1535
|
-
unnamed: names.some((n) => typeof n !== "string" || n === ""),
|
|
1536
|
-
runs,
|
|
1537
|
-
});
|
|
1538
|
-
if (held) {
|
|
1539
|
-
log(cfg.paths.guard_log, `BLOCK spawn: ${held}`);
|
|
1540
|
-
return held;
|
|
1541
|
-
}
|
|
1542
|
-
recordSpawns(files, cfg.paths, staffing);
|
|
1543
|
-
recordBudgets(budgets, cfg.paths);
|
|
1544
|
-
return null;
|
|
1545
|
-
}
|
|
1546
|
-
|
|
1547
|
-
/**
|
|
1548
|
-
* A shell launch of a bypass_spawn agent: the cancel check, the plan gate, the review PASS, the
|
|
1549
|
-
* incidents, then the record. Main's and a sub's launch both come through here (plan 20261028_1600 P4i).
|
|
1550
|
-
*/
|
|
1551
|
-
function bypassLaunch(command: string, cfg: Config, spawner: Spawner, runs?: RunSource): string | null {
|
|
1552
|
-
for (const entry of cfg.guards.bypass_spawn) {
|
|
1553
|
-
if (!bypassRegExp(entry).test(command)) continue;
|
|
1554
|
-
const pending = q.cancelPending(cfg.paths);
|
|
1555
|
-
if (pending) {
|
|
1556
|
-
log(cfg.paths.guard_log, `BLOCK bypass launch: cancel pending (${pending.words})`);
|
|
1557
|
-
return `${CANCEL_TODO} Flagged: "${pending.words}"`;
|
|
1558
|
-
}
|
|
1559
|
-
const [why, named] = planGate(command, entry, cfg);
|
|
1560
|
-
if (why) {
|
|
1561
|
-
log(cfg.paths.guard_log, `BLOCK bypass launch: ${why}`);
|
|
1562
|
-
return why;
|
|
1563
|
-
}
|
|
1564
|
-
const review = reviewPassProblem(named, command, "", cfg, spawner);
|
|
1565
|
-
if (review) {
|
|
1566
|
-
log(cfg.paths.guard_log, `BLOCK bypass launch: ${review}`);
|
|
1567
|
-
return review;
|
|
1568
|
-
}
|
|
1569
|
-
const inc = incidentSpawnProblem("bypass launch", command, named, cfg);
|
|
1570
|
-
if (inc) return inc;
|
|
1571
|
-
// I-20261031-280: a bypass launch takes the claims like every other spawn, as its last
|
|
1572
|
-
// refusal before the record.
|
|
1573
|
-
const held = claimGate(named, cfg, { agentIds: [], unnamed: true, runs });
|
|
1574
|
-
if (held) {
|
|
1575
|
-
log(cfg.paths.guard_log, `BLOCK bypass launch: ${held}`);
|
|
1576
|
-
return held;
|
|
1577
|
-
}
|
|
1578
|
-
if (named.length) recordSpawns(named, cfg.paths);
|
|
1579
|
-
}
|
|
1580
|
-
return null;
|
|
1581
|
-
}
|
|
1582
|
-
|
|
1583
|
-
function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config, runs?: RunSource): Decision {
|
|
1584
|
-
if (e.tool === "task") {
|
|
1585
|
-
const why = taskLaunch(input, cfg, e.runningJobs, "main", runs);
|
|
1586
|
-
return why ? deny(`main-guard: ${why}`, "main.task-launch") : ALLOW;
|
|
1587
|
-
}
|
|
1588
|
-
if (cfg.guards.shell_tools.includes(e.tool)) {
|
|
1589
|
-
// Strict landing gate (20261025_1940 P2, P5): in tier strict every push/merge waits for the
|
|
1590
|
-
// owner's approve phrase (autonomy.go_phrase, default "go push"); the landing that consumes
|
|
1591
|
-
// it goes through. Opinionated and full keep today's allowance. Owner-only rules above are
|
|
1592
|
-
// untouched.
|
|
1593
|
-
if (landingCommand(input) && currentTier(cfg) === "strict" && !takeGo(cfg)) {
|
|
1594
|
-
log(cfg.paths.guard_log, "BLOCK landing: tier strict, no approve phrase rule=main.push-merge");
|
|
1595
|
-
return deny(`main-guard: tier strict — type "${cfg.autonomy.go_phrase}" to approve one push/merge`, "main.push-merge");
|
|
1596
|
-
}
|
|
1597
|
-
const command = String(input?.command ?? input?.code ?? "");
|
|
1598
|
-
const why = bypassLaunch(command, cfg, "main", runs);
|
|
1599
|
-
if (why) return deny(`main-guard: ${why}`, "main.bypass-launch");
|
|
1600
|
-
}
|
|
1601
|
-
return editWindow(e, input, cfg);
|
|
1602
|
-
}
|
|
1603
|
-
|
|
1604
|
-
// Main's per-turn call cap (plan 20261028_1545 P2): the sub call-cap shape — warn at
|
|
1605
|
-
// main_warn_calls, hard stop at main_max_calls — over calls counted in the window state file
|
|
1606
|
-
// since the last real owner prompt or Main's terminal hand-back. The file, not the adapter's
|
|
1607
|
-
// session memory, is the counter: one-shot CLI calls and a reloaded plugin must see the same
|
|
1608
|
-
// count, and the reset points (checkInject here, the adapter's terminal agent_end) already write
|
|
1609
|
-
// this file. Off in tier full (same gate as editWindow) and at main_max_calls 0.
|
|
1610
|
-
|
|
1611
|
-
/** The per-turn call cap applies to this call: on, not tier full, and the tool is not exempt. */
|
|
1612
|
-
function mainCallApplies(e: ToolEvent, cfg: Config): boolean {
|
|
1613
|
-
return cfg.guards.main_max_calls > 0 && currentTier(cfg) !== "full" && !cfg.guards.main_call_exempt_tools.includes(e.tool);
|
|
1614
|
-
}
|
|
1615
|
-
|
|
1616
|
-
/**
|
|
1617
|
-
* A count older than this starts over, even with no owner message or hand-back: a blocked stop is
|
|
1618
|
-
* a continuation, not a hand-back, so without it a capped Main with no owner awake stays refused
|
|
1619
|
-
* all night.
|
|
1620
|
-
*/
|
|
1621
|
-
const MAIN_CALLS_RESET_SEC = 15 * 60;
|
|
1622
|
-
|
|
1623
|
-
function mainCallsExpired(w: EditWindow): boolean {
|
|
1624
|
-
return w.mainCalls > 0 && nowSec() - (w.mainCallsStart ?? 0) >= MAIN_CALLS_RESET_SEC;
|
|
1625
|
-
}
|
|
1626
|
-
|
|
1627
|
-
/** Refusal once this turn has spent main_max_calls, or null. */
|
|
1628
|
-
function mainCallStop(e: ToolEvent, cfg: Config): string | null {
|
|
1629
|
-
if (!mainCallApplies(e, cfg)) return null;
|
|
1630
|
-
const w = readWindow(cfg.paths);
|
|
1631
|
-
if (w.mainCalls >= cfg.guards.main_max_calls && !mainCallsExpired(w))
|
|
1632
|
-
return `main-guard: call ${w.mainCalls}/${cfg.guards.main_max_calls} since the owner's last message or your last hand-back (guards.main_max_calls); the count starts over ${Math.ceil((MAIN_CALLS_RESET_SEC - (nowSec() - (w.mainCallsStart ?? 0))) / 60)} min from now. End your turn with the answer, or spawn an implementer.`;
|
|
1633
|
-
return null;
|
|
1634
|
-
}
|
|
1635
|
-
|
|
1636
|
-
/** Count one allowed, non-exempt call; returns the warn-band inject at main_warn_calls, "" below it. */
|
|
1637
|
-
function mainCallWarn(e: ToolEvent, cfg: Config): string {
|
|
1638
|
-
if (!mainCallApplies(e, cfg)) return "";
|
|
1639
|
-
const w = readWindow(cfg.paths);
|
|
1640
|
-
if (w.mainCalls === 0 || mainCallsExpired(w)) {
|
|
1641
|
-
w.mainCalls = 0;
|
|
1642
|
-
w.mainCallsStart = nowSec();
|
|
1643
|
-
}
|
|
1644
|
-
w.mainCalls += 1;
|
|
1645
|
-
writeWindow(w, cfg.paths);
|
|
1646
|
-
if (w.mainCalls >= cfg.guards.main_warn_calls)
|
|
1647
|
-
return `main-guard: call ${w.mainCalls}/${cfg.guards.main_max_calls} this turn (guards.main_warn_calls). End your turn with the answer, or spawn an implementer.`;
|
|
1648
|
-
return "";
|
|
1649
|
-
}
|
|
1650
|
-
|
|
1651
|
-
/** Main's terminal hand-back (the adapter's agent_end without willContinue): the turn is over, so
|
|
1652
|
-
* the next one starts at 0 calls. The edit window keeps its own reset rules. */
|
|
1653
|
-
export function resetMainCalls(paths: Pick<q.QueuePaths, "queue_state">): void {
|
|
1654
|
-
const w = readWindow(paths);
|
|
1655
|
-
if (w.mainCalls === 0) return;
|
|
1656
|
-
w.mainCalls = 0;
|
|
1657
|
-
writeWindow(w, paths);
|
|
1658
|
-
}
|
|
1659
|
-
|
|
1660
|
-
/** A live plan file (archived plans excluded); Main's plan-text checks run on these. Subfolders like docs/plans/immediate/ hold live plans too. */
|
|
1661
|
-
export const MAIN_PLAN_FILE = /\/docs\/plans\/(?!archive\/)(?:[^/]+\/)*[^/]+\.md$/;
|
|
1662
|
-
|
|
1663
|
-
/**
|
|
1664
|
-
* pre-tool: plan-guard checkCall for subs (protected files, budget, plan-edit rules, blockers)
|
|
1665
|
-
* plus, for Main, the spawn gates and the project-file edit window.
|
|
1666
|
-
*/
|
|
1667
|
-
export function checkTool(e: ToolEvent, cfg: Config, runs?: RunSource): Decision {
|
|
1668
|
-
return tuned(checkToolRules(e, cfg, runs), cfg);
|
|
1669
|
-
}
|
|
1670
|
-
|
|
1671
|
-
/** Applies the owner's rule level to a refusal. Only with `tuning.guards` on; a refusal with no `[rule <id>]` suffix, or a pinned, unset or corrupt id, stays `block`. */
|
|
1672
|
-
function tuned(d: Decision, cfg: Config): Decision {
|
|
1673
|
-
if (d.allow || !cfg.tuning.guards) return d;
|
|
1674
|
-
const id = /\[rule ([\w.-]+)\]$/.exec(d.reason)?.[1];
|
|
1675
|
-
if (!id) return d;
|
|
1676
|
-
const level = levelFor(readLevels(cfg), id);
|
|
1677
|
-
if (level === "block") return d;
|
|
1678
|
-
return { allow: true, reason: level === "tell" ? d.reason : "" };
|
|
1679
|
-
}
|
|
1680
|
-
|
|
1681
|
-
function checkToolRules(e: ToolEvent, cfg: Config, runs?: RunSource): Decision {
|
|
1682
|
-
const lock = e.agent === "sub" ? reviewLockProblem(e, cfg) : null;
|
|
1683
|
-
if (lock) {
|
|
1684
|
-
log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} review lock: ${lock} rule=tool.review-lock`);
|
|
1685
|
-
return deny(`plan-guard: ${lock}`, "tool.review-lock");
|
|
1686
|
-
}
|
|
1687
|
-
if (cfg.guards.skip_tools.includes(e.tool)) return ALLOW;
|
|
1688
|
-
const input = e.input ?? {};
|
|
1689
|
-
// Starting the owner page (plan 20261024_2230 P3c) is the owner's systemd move, never an
|
|
1690
|
-
// agent's, unlocked or not: refused plan-guard style like a protected-file write.
|
|
1691
|
-
if (cfg.guards.shell_tools.includes(e.tool) && startsOwnerUi(input)) {
|
|
1692
|
-
log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} ui-start: ${String(input.command ?? "")} rule=tool.ui-start`);
|
|
1693
|
-
return deny(
|
|
1694
|
-
"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.",
|
|
1695
|
-
"tool.ui-start",
|
|
1696
|
-
);
|
|
1697
|
-
}
|
|
1698
|
-
// claim release --force frees another Main's claim (plan 20261027_1300 P4): the owner's
|
|
1699
|
-
// terminal move, refused for every agent like the ui-start, plan-guard style.
|
|
1700
|
-
if (cfg.guards.shell_tools.includes(e.tool) && forceClaimRelease(input)) {
|
|
1701
|
-
log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} claim-force: ${String(input.command ?? "")} rule=tool.claim-force`);
|
|
1702
|
-
return deny("plan-guard: claim release --force frees another Main's claim; that is the owner's move, in a terminal.", "tool.claim-force");
|
|
1703
|
-
}
|
|
1704
|
-
// The caller may know paths the text search cannot see (structured edits); union, never shrink.
|
|
1705
|
-
const paths: string[] = [];
|
|
1706
|
-
for (const p of [...(e.paths ?? []), ...q.touchedPaths(e.tool, input, e.cwd)]) if (!paths.includes(p)) paths.push(p);
|
|
1707
|
-
const writes: string[] = [];
|
|
1708
|
-
const relative: string[] = [];
|
|
1709
|
-
for (const p of [...(e.writes ?? []), ...q.writeTargets(e.tool, input, e.cwd, cfg.paths, relative)]) if (!writes.includes(p)) writes.push(p);
|
|
1710
|
-
// A relative plan path resolves against cwd to a file that does not exist, so the plan gate never
|
|
1711
|
-
// sees the edit (plan 20261028_1600 P4j). A plan is named by its absolute path, for every agent.
|
|
1712
|
-
const relPlan = PLAN_WRITE_TOOLS[e.tool] ? relative.find(isPlanName) : undefined;
|
|
1713
|
-
if (relPlan) {
|
|
1714
|
-
log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} relative plan path: ${relPlan} rule=tool.relative-plan`);
|
|
1715
|
-
return deny(`plan-guard: use the absolute plan path, not ${relPlan}. The plan gate cannot see a relative one.`, "tool.relative-plan");
|
|
1716
|
-
}
|
|
1717
|
-
// Notify secrets: no agent, main or sub, reads a webhook URL — with or without the unlock.
|
|
1718
|
-
// A call that changes a secret is not a read: its target goes through the protected-write
|
|
1719
|
-
// rule above, so the owner's unlock covers it like any guard file. P5g: the scan reads real
|
|
1720
|
-
// read targets only — naming a secret-shaped glob in a task brief or in plan text is prose,
|
|
1721
|
-
// not a read — so prose tools (task, write/edit) scan just their path argument, while every
|
|
1722
|
-
// other tool keeps the whole-input scan (glob/grep patterns arrive through it).
|
|
1723
|
-
const secretPaths: string[] = [];
|
|
1724
|
-
for (const p of [...(e.paths ?? []), ...q.touchedPaths(e.tool, PROSE_TOOLS[e.tool] === true ? pathArgs(input) : input, e.cwd)])
|
|
1725
|
-
if (!secretPaths.includes(p)) secretPaths.push(p);
|
|
1726
|
-
const secretHit = notifySecretReadHit(secretPaths.filter(p => !writes.includes(p)), cfg);
|
|
1727
|
-
if (secretHit) {
|
|
1728
|
-
log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} notify secret: ${secretHit} rule=tool.notify-secret`);
|
|
1729
|
-
return deny(`plan-guard: ${secretHit} is a notify secret path. Only the owner touches the webhook files, in a terminal.`, "tool.notify-secret");
|
|
1730
|
-
}
|
|
1731
|
-
// Main writes its own rollover note unattended (the note turn has nobody to ask). Only a Write
|
|
1732
|
-
// of a .md directly in <state>/rollover/ is exempt; shell writes, subagents and relaunch.json stay refused.
|
|
1733
|
-
const rolloverDir = path.join(mainStateDir(cfg), "rollover");
|
|
1734
|
-
const openWrites =
|
|
1735
|
-
e.agent === "main" && e.tool === "write"
|
|
1736
|
-
? writes.filter(p => !(path.extname(p) === ".md" && path.dirname(path.resolve(p)) === rolloverDir))
|
|
1737
|
-
: writes;
|
|
1738
|
-
const hit = protectedHit(openWrites, cfg);
|
|
1739
|
-
if (hit && unlockUntilMs(cfg) === null) {
|
|
1740
|
-
log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} protected: ${hit} rule=tool.protected`);
|
|
1741
|
-
// The plan index (plan 20261031_0911 P2) is guard surface like the rest, but unlike the
|
|
1742
|
-
// others an agent has a sanctioned way to change it: the queue add/move CLI through
|
|
1743
|
-
// writeIndex. Name it, so the refusal says what to do instead of naming the unlock.
|
|
1744
|
-
const viaQueue = hit === cfg.paths.queue_index ? ` Plans enter the index or move within it through \`neurastream queue add\` / \`neurastream queue move\`.` : "";
|
|
1745
|
-
return deny(
|
|
1746
|
-
`plan-guard: ${hit} is a protected guard file. Only the owner changes it (unlock: \`touch ${cfg.paths.unlock}\` in a terminal${
|
|
1747
|
-
cfg.guards.chat_unlock ? `, or type \`unlock ${cfg.guards.unlock_minutes}\` in chat` : ""
|
|
1748
|
-
}, valid ${cfg.guards.unlock_minutes} min).${viaQueue}`,
|
|
1749
|
-
"tool.protected",
|
|
1750
|
-
);
|
|
1751
|
-
}
|
|
1752
|
-
if (e.agent === "main") {
|
|
1753
|
-
// The plan-text checks (checkPlanEdit) see only edit/write results; a shell redirect,
|
|
1754
|
-
// sed -i or heredoc into a plan would skip them, so plans change through edit/write only.
|
|
1755
|
-
const shellPlan = e.tool !== "write" && e.tool !== "edit" ? writes.find(p => MAIN_PLAN_FILE.test(p)) : undefined;
|
|
1756
|
-
if (shellPlan) {
|
|
1757
|
-
log(cfg.paths.plan_guard_log, `BLOCK main tool=${e.tool} shell write to plan ${shellPlan} rule=tool.shell-plan`);
|
|
1758
|
-
return deny(`plan-guard: ${shellPlan} is a plan file: change it with the edit or write tool (close or cancel it with queue-close / queue-cancel).`, "tool.shell-plan");
|
|
1759
|
-
}
|
|
1760
|
-
const stop = mainCallStop(e, cfg);
|
|
1761
|
-
if (stop) {
|
|
1762
|
-
log(cfg.paths.guard_log, `BLOCK tool=${e.tool} after ${readWindow(cfg.paths).mainCalls} calls this turn rule=main.call-budget`);
|
|
1763
|
-
return deny(stop, "main.call-budget");
|
|
1764
|
-
}
|
|
1765
|
-
const d = mainTool(e, input, cfg, runs);
|
|
1766
|
-
if (!d.allow) return d;
|
|
1767
|
-
const warn = mainCallWarn(e, cfg);
|
|
1768
|
-
// A task brief names paths it does not read; only the other tools' paths count as reads.
|
|
1769
|
-
if (e.tool !== "task") recordMainReads(paths.filter(p => !writes.includes(p)), cfg.paths);
|
|
1770
|
-
return warn ? { ...d, inject: d.inject ? `${d.inject}\n${warn}` : warn } : d;
|
|
1771
|
-
}
|
|
1772
|
-
const cap = subCallCap(e.agentId, cfg);
|
|
1773
|
-
const why = subRules(e, input, paths, writes, cfg, cap);
|
|
1774
|
-
if (why) {
|
|
1775
|
-
log(cfg.paths.plan_guard_log, `BLOCK sub:${e.agentId} tool=${e.tool} ${why} rule=sub.rule`);
|
|
1776
|
-
return deny(`plan-guard: ${why}`, "sub.rule");
|
|
1777
|
-
}
|
|
1778
|
-
// A sub's own launch passes the same spawn gates as Main's (plan 20261028_1600 P4i).
|
|
1779
|
-
let launch: string | null = null;
|
|
1780
|
-
if (e.tool === "task") launch = taskLaunch(input, cfg, e.runningJobs, "sub", runs);
|
|
1781
|
-
else if (cfg.guards.shell_tools.includes(e.tool)) launch = bypassLaunch(String(input?.command ?? input?.code ?? ""), cfg, "sub", runs);
|
|
1782
|
-
if (launch) {
|
|
1783
|
-
log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} ${launch} rule=sub.launch`);
|
|
1784
|
-
return deny(`plan-guard: ${launch}`, "sub.launch");
|
|
1785
|
-
}
|
|
1786
|
-
const n = e.calls + 1;
|
|
1787
|
-
// The warn band has the global width (sub_max_calls - sub_warn_calls) ending at the cap;
|
|
1788
|
-
// unbudgeted subs keep sub_warn_calls exactly.
|
|
1789
|
-
const warn = cap === cfg.guards.sub_max_calls ? cfg.guards.sub_warn_calls : Math.max(1, cap - (cfg.guards.sub_max_calls - cfg.guards.sub_warn_calls));
|
|
1790
|
-
if (n >= warn && n < cap)
|
|
1791
|
-
return {
|
|
1792
|
-
allow: true,
|
|
1793
|
-
reason: "",
|
|
1794
|
-
inject: `plan-guard: call ${n}/${cap}. Update your plan's "## Progress" now (done, verified, next); at ${cap} only that edit is allowed.`,
|
|
1795
|
-
};
|
|
1796
|
-
return ALLOW;
|
|
1797
|
-
}
|
|
1798
|
-
|
|
1799
|
-
// --- Main's read log (`main-reads.json` in the queue state dir): files Main has read itself ---
|
|
1800
|
-
|
|
1801
|
-
const MAIN_READ_KEEP_MS = 7 * 86_400_000;
|
|
1802
|
-
const GREP_LINE = /^([^\s:]+):\d+:/gm;
|
|
1803
|
-
/** Logs existing files as read now; entries older than 7 days are dropped on each write. */
|
|
1804
|
-
function recordMainReads(files: string[], paths: Pick<q.QueuePaths, "queue_state">, now = Date.now()): void {
|
|
1805
|
-
const file = path.join(paths.queue_state, "main-reads.json");
|
|
1806
|
-
const existing = files.filter(f => {
|
|
1807
|
-
try {
|
|
1808
|
-
return statSync(f).isFile();
|
|
1809
|
-
} catch {
|
|
1810
|
-
return false;
|
|
1811
|
-
}
|
|
1812
|
-
});
|
|
1813
|
-
if (existing.length === 0) return;
|
|
1814
|
-
let reads: Record<string, string> = {};
|
|
1815
|
-
try {
|
|
1816
|
-
const parsed = JSON.parse(readFileSync(file, "utf8")) as unknown;
|
|
1817
|
-
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) reads = parsed as Record<string, string>;
|
|
1818
|
-
} catch {}
|
|
1819
|
-
const stamp = new Date(now).toISOString();
|
|
1820
|
-
for (const f of existing) reads[f] = stamp;
|
|
1821
|
-
const cutoff = now - MAIN_READ_KEEP_MS;
|
|
1822
|
-
for (const [f, t] of Object.entries(reads)) if (!(Date.parse(t) >= cutoff)) delete reads[f];
|
|
1823
|
-
try {
|
|
1824
|
-
mkdirSync(paths.queue_state, { recursive: true });
|
|
1825
|
-
writeFileSync(file, JSON.stringify(reads, null, 2));
|
|
1826
|
-
} catch {}
|
|
1827
|
-
}
|
|
1828
|
-
|
|
1829
|
-
/**
|
|
1830
|
-
* Main's tool result: each `path:line:` at a line start (grep -n / grep -rn output) names a file
|
|
1831
|
-
* Main read. Paths resolve against the directory the call ran in (its `cwd`, then any `cd`).
|
|
1832
|
-
*/
|
|
1833
|
-
export function revertMainEdit(tool: string, input: Record<string, unknown>, cwd: string, cfg: Config): void {
|
|
1834
|
-
const files = changedProjectFiles(tool, input, cwd, cfg);
|
|
1835
|
-
if (!files.length) return;
|
|
1836
|
-
const w = readWindow(cfg.paths);
|
|
1837
|
-
const entry = `${tool}:${files[0]!}`;
|
|
1838
|
-
const idx = w.used.lastIndexOf(entry);
|
|
1839
|
-
if (idx >= 0) {
|
|
1840
|
-
w.used.splice(idx, 1);
|
|
1841
|
-
writeWindow(w, cfg.paths);
|
|
1842
|
-
}
|
|
1843
|
-
}
|
|
1844
|
-
|
|
1845
|
-
export function recordMainResult(tool: string, input: Record<string, unknown>, cwd: string, text: string, paths: Pick<q.QueuePaths, "queue_state">): void {
|
|
1846
|
-
const base = typeof input.cwd === "string" ? path.resolve(cwd, q.expandHome(input.cwd)) : cwd;
|
|
1847
|
-
const dir = q.shellCwd(String(input.command ?? input.code ?? ""), base);
|
|
1848
|
-
recordMainReads([...text.matchAll(GREP_LINE)].map(m => path.resolve(dir, m[1] ?? "")), paths);
|
|
1849
|
-
}
|
|
1850
|
-
|
|
1851
|
-
/**
|
|
1852
|
-
* The pre-draft warning (I-20261025-208): when Main reads a plan file (the read tool, or a result
|
|
1853
|
-
* whose first `path:line:` hit is the plan), the tool result gains one note naming the plan's
|
|
1854
|
-
* listed files that would fail the read check right now — before Main drafts an edit the guard
|
|
1855
|
-
* would refuse and throw away. Silence when every listed file is fresh in some checkout.
|
|
1856
|
-
*/
|
|
1857
|
-
export function planReadNote(tool: string, input: Record<string, unknown>, cwd: string, text: string, cfg: Config): string | undefined {
|
|
1858
|
-
let planPath = "";
|
|
1859
|
-
if (tool === "read" && typeof input.path === "string") planPath = path.resolve(cwd, q.expandHome(input.path));
|
|
1860
|
-
else {
|
|
1861
|
-
const first = [...text.matchAll(GREP_LINE)][0];
|
|
1862
|
-
if (first) {
|
|
1863
|
-
const base = typeof input.cwd === "string" ? path.resolve(cwd, q.expandHome(input.cwd)) : cwd;
|
|
1864
|
-
planPath = path.resolve(q.shellCwd(String(input.command ?? input.code ?? ""), base), first[1] ?? "");
|
|
1865
|
-
}
|
|
1866
|
-
}
|
|
1867
|
-
if (!planPath || !MAIN_PLAN_FILE.test(planPath)) return undefined;
|
|
1868
|
-
let plan: string;
|
|
1869
|
-
try {
|
|
1870
|
-
plan = readFileSync(planPath, "utf8");
|
|
1871
|
-
} catch {
|
|
1872
|
-
return undefined;
|
|
1873
|
-
}
|
|
1874
|
-
const stale = planReadProblems(plan, planPath, cfg)
|
|
1875
|
-
.filter(p => p.includes(" was not read by Main within "))
|
|
1876
|
-
.map(p => p.slice(0, p.indexOf(" was not read by Main within ")));
|
|
1877
|
-
if (!stale.length) return undefined;
|
|
1878
|
-
return `plan-guard: before you edit this plan, re-read: ${stale.join(", ")}`;
|
|
1879
|
-
}
|
|
1880
|
-
|
|
1881
|
-
/** 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). */
|
|
1882
|
-
function heldProblem(file: string, held: Claim | Unreachable): string {
|
|
1883
|
-
if ("unreachable" in held) return `team server ${held.unreachable} unreachable; plan ${file} is refused until it answers`;
|
|
1884
|
-
if (held.mine === false) return `plan ${file} is held by another member's Main ${held.main} since ${strftime(held.since, "%H:%M")}`;
|
|
1885
|
-
return `plan ${file} is held by Main ${held.main} since ${strftime(held.since, "%H:%M")}`;
|
|
1886
|
-
}
|
|
1887
|
-
|
|
1888
|
-
/**
|
|
1889
|
-
* The spawn claim gate (plan 20261027_1300 P3): a spawn on a plan claims it for this Main first;
|
|
1890
|
-
* another Main's live claim refuses the launch — a sub's launch too, once its Main no longer
|
|
1891
|
-
* holds the claim. Returns the refusal, or null.
|
|
1892
|
-
*/
|
|
1893
|
-
function claimGate(files: string[], cfg: Config, spawn: SpawnIdent): string | null {
|
|
1894
|
-
const teams = routedTeams(files, cfg);
|
|
1895
|
-
const uncountable = teams.find(({ team }) => team.max_share !== undefined);
|
|
1896
|
-
if (spawn.unnamed && uncountable) {
|
|
1897
|
-
return `team ${uncountable.team.name} sets max_share: name this agent (tasks[].name) so its calls count against the team cap`;
|
|
1898
|
-
}
|
|
1899
|
-
const mine = mainId();
|
|
1900
|
-
// With the chooser each file has its own store; `fresh` carries the store beside each file,
|
|
1901
|
-
// so a fresh claim is released through the store that took it (a team claim released through
|
|
1902
|
-
// the file store would be a silent no-op that outlives the refusal until the TTL).
|
|
1903
|
-
const fresh: { file: string; store: ClaimStore }[] = [];
|
|
1904
|
-
// A refusal leaves the store as it found it: claims this call newly created are released
|
|
1905
|
-
// again through the store that took each one; a claim this Main already held before the
|
|
1906
|
-
// call stays.
|
|
1907
|
-
const releaseFresh = (): void => {
|
|
1908
|
-
for (const g of fresh) g.store.release(g.file, mine);
|
|
1909
|
-
};
|
|
1910
|
-
for (const f of files) {
|
|
1911
|
-
const store = claimStoreFor(f, cfg);
|
|
1912
|
-
const h = store.holder(f);
|
|
1913
|
-
// Fail closed: an unreachable server refuses the spawn and leaves no claim this call took.
|
|
1914
|
-
if (h !== null && "unreachable" in h) {
|
|
1915
|
-
releaseFresh();
|
|
1916
|
-
return heldProblem(f, h);
|
|
1917
|
-
}
|
|
1918
|
-
const heldBefore = h !== null && !heldByOther(h, mine);
|
|
1919
|
-
const c = store.claim(f, mine);
|
|
1920
|
-
if ("unreachable" in c) {
|
|
1921
|
-
// The outage started between holder() and claim(): release what this call took.
|
|
1922
|
-
releaseFresh();
|
|
1923
|
-
return heldProblem(f, c);
|
|
1924
|
-
}
|
|
1925
|
-
if ("heldBy" in c) {
|
|
1926
|
-
releaseFresh();
|
|
1927
|
-
return heldProblem(f, c.heldBy);
|
|
1928
|
-
}
|
|
1929
|
-
if (!heldBefore) fresh.push({ file: f, store });
|
|
1930
|
-
}
|
|
1931
|
-
const capped = teamCapProblem(teams, spawn, cfg);
|
|
1932
|
-
if (capped) {
|
|
1933
|
-
releaseFresh();
|
|
1934
|
-
return capped;
|
|
1935
|
-
}
|
|
1936
|
-
recordTeamSpawns(teams, spawn.agentIds, cfg);
|
|
1937
|
-
return null;
|
|
1938
|
-
}
|
|
1939
|
-
|
|
1940
|
-
/** A spawn's identity for the team cap: its named agents, and whether any spawned agent has no name (the cap cannot count it). */
|
|
1941
|
-
export interface SpawnIdent {
|
|
1942
|
-
agentIds: string[];
|
|
1943
|
-
unnamed: boolean;
|
|
1944
|
-
runs?: RunSource;
|
|
1945
|
-
}
|
|
1946
|
-
|
|
1947
|
-
/** A plan file and the team it routes to. */
|
|
1948
|
-
export interface RoutedTeam {
|
|
1949
|
-
team: TeamEntry;
|
|
1950
|
-
file: string;
|
|
1951
|
-
}
|
|
1952
|
-
|
|
1953
|
-
function routedTeams(files: string[], cfg: Config): RoutedTeam[] {
|
|
1954
|
-
const out: RoutedTeam[] = [];
|
|
1955
|
-
for (const file of files) {
|
|
1956
|
-
const team = routeTeam(file, cfg, undefined, defaultRunner);
|
|
1957
|
-
if (team) out.push({ team, file });
|
|
1958
|
-
}
|
|
1959
|
-
return out;
|
|
1960
|
-
}
|
|
1961
|
-
|
|
1962
|
-
/** Epoch seconds at local midnight: the start of the cap's day. */
|
|
1963
|
-
function dayStartSec(): number {
|
|
1964
|
-
const d = new Date(nowSec() * 1000);
|
|
1965
|
-
d.setHours(0, 0, 0, 0);
|
|
1966
|
-
return d.getTime() / 1000;
|
|
1967
|
-
}
|
|
1968
|
-
|
|
1969
|
-
/** Agent ids recorded against a team's plans since `since`, from its spawns.jsonl rows; a corrupt row counts for nothing. */
|
|
1970
|
-
function teamAgentsSince(cfg: Config, team: TeamEntry, since: number): Set<string> {
|
|
1971
|
-
const ids = new Set<string>();
|
|
1972
|
-
let text: string;
|
|
1973
|
-
try {
|
|
1974
|
-
text = readFileSync(path.join(teamDir(cfg, team), "spawns.jsonl"), "utf8");
|
|
1975
|
-
} catch {
|
|
1976
|
-
return ids;
|
|
1977
|
-
}
|
|
1978
|
-
for (const line of text.split("\n")) {
|
|
1979
|
-
if (!line) continue;
|
|
1980
|
-
try {
|
|
1981
|
-
const row = JSON.parse(line) as { agentId?: unknown; at?: unknown };
|
|
1982
|
-
if (typeof row.agentId === "string" && typeof row.at === "number" && row.at >= since) ids.add(row.agentId);
|
|
1983
|
-
} catch {}
|
|
1984
|
-
}
|
|
1985
|
-
return ids;
|
|
1986
|
-
}
|
|
1987
|
-
|
|
1988
|
-
/** 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. */
|
|
1989
|
-
export function teamCapProblem(teams: RoutedTeam[], spawn: SpawnIdent, cfg: Config): string | null {
|
|
1990
|
-
const capped = teams.flatMap(({ team }) => (team.max_share === undefined ? [] : [{ team, cap: team.max_share }]));
|
|
1991
|
-
const [first] = capped;
|
|
1992
|
-
if (first === undefined) return null;
|
|
1993
|
-
if (!spawn.runs) return `team ${first.team.name} sets max_share: the cap cannot be computed without a run source`;
|
|
1994
|
-
const since = dayStartSec();
|
|
1995
|
-
const runs = spawn.runs.listRuns(since);
|
|
1996
|
-
const total = runs.reduce((sum, r) => sum + r.calls, 0);
|
|
1997
|
-
if (total === 0) return null;
|
|
1998
|
-
for (const { team, cap } of capped) {
|
|
1999
|
-
const ids = teamAgentsSince(cfg, team, since);
|
|
2000
|
-
const mine = runs.filter((r) => ids.has(r.id)).reduce((sum, r) => sum + r.calls, 0);
|
|
2001
|
-
if (mine / total >= cap) return `team ${team.name} cap reached: ${mine} of ${total} calls today (max_share ${cap}); team plans wait until local midnight`;
|
|
2002
|
-
}
|
|
2003
|
-
return null;
|
|
2004
|
-
}
|
|
2005
|
-
|
|
2006
|
-
/** 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. */
|
|
2007
|
-
function recordTeamSpawns(teams: RoutedTeam[], agentIds: string[], cfg: Config): void {
|
|
2008
|
-
if (agentIds.length === 0) return;
|
|
2009
|
-
for (const { team, file } of teams) {
|
|
2010
|
-
const planId = pathId(team, cfg, file, defaultRunner);
|
|
2011
|
-
if (planId === null) continue;
|
|
2012
|
-
const dir = teamDir(cfg, team);
|
|
2013
|
-
const at = nowSec();
|
|
2014
|
-
const rows = agentIds.map((agentId) => `${JSON.stringify({ planId, agentId, at })}\n`).join("");
|
|
2015
|
-
try {
|
|
2016
|
-
mkdirSync(dir, { recursive: true });
|
|
2017
|
-
appendFileSync(path.join(dir, "spawns.jsonl"), rows);
|
|
2018
|
-
} catch (err) {
|
|
2019
|
-
log(cfg.paths.guard_log, `cannot record team spawn for ${team.name}: ${err}`);
|
|
2020
|
-
}
|
|
2021
|
-
}
|
|
2022
|
-
}
|
|
2023
|
-
|
|
2024
|
-
/**
|
|
2025
|
-
* spawn: the allow-list, task-only and open-plan gates for one implementer launch. Covers both
|
|
2026
|
-
* original paths (the extension spawn event and a `task` tool call); the brief names the plan.
|
|
2027
|
-
*/
|
|
2028
|
-
export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = defaultRunner, runs?: RunSource): Decision {
|
|
2029
|
-
return tuned(checkSpawnRules(e, cfg, runner, runs), cfg);
|
|
2030
|
-
}
|
|
2031
|
-
|
|
2032
|
-
function checkSpawnRules(e: SpawnEvent, cfg: Config, runner: CommandRunner = defaultRunner, runs?: RunSource): Decision {
|
|
2033
|
-
const pending = q.cancelPending(cfg.paths);
|
|
2034
|
-
if (pending) {
|
|
2035
|
-
log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: cancel pending (${pending.words}) rule=spawn.cancel-pending`);
|
|
2036
|
-
return deny(`main-guard: ${CANCEL_TODO} Flagged: "${pending.words}"`, "spawn.cancel-pending");
|
|
2037
|
-
}
|
|
2038
|
-
const allowed = q.allowedAgents(cfg.paths.subagents);
|
|
2039
|
-
if (!allowed.has(e.agent))
|
|
2040
|
-
return deny(`main-guard: ${e.agent}: agent "${e.agent}" is not in "## Allowed" of ${cfg.paths.subagents} (no expensive or unpinned models).`, "spawn.agent-allowed");
|
|
2041
|
-
if (e.invocationKind !== "task")
|
|
2042
|
-
return deny("main-guard: spawn implementers with the task tool (the plan gate checks its brief).", "spawn.task-tool");
|
|
2043
|
-
// P4 (plan 20261031_1207): every gate's refusal lands in one numbered verdict; nothing
|
|
2044
|
-
// short-circuits, so Main sees all the problems in one round trip.
|
|
2045
|
-
const problems: string[] = [];
|
|
2046
|
-
// planner mode P2 (c): a Planner-role brief is refused while the mode is main — the switch is
|
|
2047
|
-
// the owner's (`planner delegated`). While delegated the planner spawn skips the open-plan
|
|
2048
|
-
// gates (the plan it names does not exist yet — writing it is the spawn's job) and its role
|
|
2049
|
-
// binds to the spawn name at the tail; a planner spawn needs that name.
|
|
2050
|
-
const plannerFor = plannerRolePlan(e.brief);
|
|
2051
|
-
const delegatedPlanner = plannerFor !== null && currentPlanner(cfg) === "delegated";
|
|
2052
|
-
if (plannerFor && !delegatedPlanner)
|
|
2053
|
-
problems.push(`${e.agent}: planner mode is main — a Planner-role spawn needs the owner's \`planner delegated\` switch.`);
|
|
2054
|
-
else if (delegatedPlanner && plannerPlanProblem(plannerFor)) problems.push(`${e.agent}: ${plannerPlanProblem(plannerFor)}`);
|
|
2055
|
-
else if (delegatedPlanner && !e.name) problems.push(`${e.agent}: a planner spawn needs a name (the task name keys its planner role).`);
|
|
2056
|
-
const [why, named] = delegatedPlanner ? [null, [] as string[]] : planGate(e.brief, e.agent, cfg);
|
|
2057
|
-
if (why) problems.push(why);
|
|
2058
|
-
const gate = priorityGate(named, e.runningJobs, e.brief, cfg, e.agent, e.agent, "main");
|
|
2059
|
-
if (gate) problems.push(gate);
|
|
2060
|
-
const pendingWork = pendingWorkProblem(named, e.brief, cfg, runner);
|
|
2061
|
-
if (pendingWork) problems.push(pendingWork);
|
|
2062
|
-
const role = reviewRole(e.name, named, e.brief, e.agent, cfg, "main");
|
|
2063
|
-
if (role.problem) problems.push(role.problem);
|
|
2064
|
-
const review = reviewPassProblem(named, e.brief, e.agent, cfg, "main");
|
|
2065
|
-
if (review) problems.push(review);
|
|
2066
|
-
const inc = incidentSpawnProblem(`spawn ${e.agent}`, e.brief, named, cfg);
|
|
2067
|
-
if (inc) problems.push(inc);
|
|
2068
|
-
const claim = providerClaimProblem(e.brief, cfg);
|
|
2069
|
-
if (claim) problems.push(`${e.agent}: ${claim}`);
|
|
2070
|
-
const pick = preferProblem(e.agent, e.brief, e.runningJobs, cfg);
|
|
2071
|
-
if (pick) problems.push(`${e.agent}: ${pick}`);
|
|
2072
|
-
const verdict = spawnVerdict(e.agent, problems, named.length ? named : briefPlans(e.brief, cfg).map(p => p.file), e.runningJobs, cfg);
|
|
2073
|
-
if (verdict) {
|
|
2074
|
-
for (const p of problems) {
|
|
2075
|
-
if (p === role.problem) log(cfg.paths.plan_guard_log, `BLOCK ${e.agent} ${e.name ?? "(unnamed)"} review spawn: ${p} rule=spawn.verdict`);
|
|
2076
|
-
else log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${p} rule=spawn.verdict`);
|
|
2077
|
-
}
|
|
2078
|
-
return deny(`main-guard: ${verdict}`, "spawn.verdict");
|
|
2079
|
-
}
|
|
2080
|
-
const held = claimGate(named, cfg, { agentIds: e.name ? [e.name] : [], unnamed: !e.name, runs });
|
|
2081
|
-
if (held) {
|
|
2082
|
-
log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${held} rule=spawn.claim-held`);
|
|
2083
|
-
return deny(`main-guard: ${held}`, "spawn.claim-held");
|
|
2084
|
-
}
|
|
2085
|
-
// The owner's pick order and live provider state (plan 20261025_1700 P3), before the spawn records.
|
|
2086
|
-
const staffing: Record<string, string[]> = {};
|
|
2087
|
-
for (const f of named) staffing[f] = [e.agent];
|
|
2088
|
-
recordSpawns(named, cfg.paths, staffing);
|
|
2089
|
-
if (e.name) recordReviewSpawn(e.name, role.plan, cfg.paths);
|
|
2090
|
-
// planner mode P2 (b): the approved planner spawn binds its name to the plan its brief named.
|
|
2091
|
-
if (delegatedPlanner && e.name && plannerFor) recordPlannerSpawn(e.name, plannerFor, cfg.paths);
|
|
2092
|
-
return ALLOW;
|
|
2093
|
-
}
|
|
2094
|
-
|
|
2095
|
-
// Owner message that may call work off: flag it; until Main records it with queue-cancel, no
|
|
2096
|
-
// spawn and no stop. Returns the text appended to the injected summary.
|
|
2097
|
-
export function flagCancel(text: string, cfg: Config): string {
|
|
2098
|
-
const m = text.match(q.CANCEL_WORDS);
|
|
2099
|
-
if (!m) return "";
|
|
2100
|
-
const at = m.index ?? 0;
|
|
2101
|
-
const words = text.slice(Math.max(0, at - 60), at + 80).replace(/\s+/g, " ").trim();
|
|
2102
|
-
const prev = q.cancelPending(cfg.paths);
|
|
2103
|
-
const pendingFile = q.cancelPendingPath(cfg.paths);
|
|
2104
|
-
try {
|
|
2105
|
-
mkdirSync(cfg.paths.queue_state, { recursive: true });
|
|
2106
|
-
writeFileSync(pendingFile, JSON.stringify({ at: new Date().toISOString(), words: prev ? `${prev.words} … ${words}` : words }));
|
|
2107
|
-
} catch (err) {
|
|
2108
|
-
log(cfg.paths.guard_log, `cannot write ${pendingFile}: ${err}`);
|
|
2109
|
-
}
|
|
2110
|
-
log(cfg.paths.guard_log, `cancel flagged: ${words}`);
|
|
2111
|
-
return `\nmain-guard: ${CANCEL_TODO} Flagged: "${words}"`;
|
|
2112
|
-
}
|
|
2113
|
-
|
|
2114
|
-
/**
|
|
2115
|
-
* prompt/owner message: inject the queue summary, flag cancel wording, list open incidents, reset
|
|
2116
|
-
* Main's edit window and the stop counters (the original resets them at every user message). A
|
|
2117
|
-
* turn the harness
|
|
2118
|
-
* starts from this guard's own stop continuation ("main-guard: …") is not an owner message: it
|
|
2119
|
-
* keeps the counters and the edit window, else every continuation reset the idle streak and a
|
|
2120
|
-
* model that only answers text was nudged again forever (2026-10-21 OOM: ~205 agent starts in one
|
|
2121
|
-
* non-interactive session).
|
|
2122
|
-
*/
|
|
2123
|
-
export function checkInject(e: InjectEvent, cfg: Config): Decision {
|
|
2124
|
-
if (e.agent !== "main") return ALLOW;
|
|
2125
|
-
const continuation = e.inject.trimStart().startsWith("main-guard:");
|
|
2126
|
-
if (!continuation) writeWindow({ used: [], windowStart: 0, mainCalls: 0 }, cfg.paths);
|
|
2127
|
-
recordOwnerMessage(e.inject, cfg);
|
|
2128
|
-
let summary: string;
|
|
2129
|
-
try {
|
|
2130
|
-
// P4 (20261027_1305): one GET /view per team, read once and handed to the holder and the
|
|
2131
|
-
// team lines, so the summary costs one request per team and never a second GET /claims.
|
|
2132
|
-
const views = teamViews(cfg);
|
|
2133
|
-
summary = q.queueSummary(cfg.paths, cfg.review.agents, summaryHolder(cfg, {}, views));
|
|
2134
|
-
const teamLines = teamSummaryLines(cfg, views, q.SUMMARY_CAP);
|
|
2135
|
-
if (teamLines.length) summary += `\n${teamLines.join("\n")}`;
|
|
2136
|
-
} catch (err) {
|
|
2137
|
-
summary = `Queue unreadable (${cfg.paths.queue_index}): ${err}`;
|
|
2138
|
-
}
|
|
2139
|
-
// P3 (plan 20261031_1207): only owner prose flags cancel, and incident lines pasted into a
|
|
2140
|
-
// prompt (guard output quoting "stop …") never do — their words are not the owner's.
|
|
2141
|
-
const cancel = continuation || !isOwnerProse(e.inject)
|
|
2142
|
-
? ""
|
|
2143
|
-
: flagCancel(e.inject.split("\n").filter(l => !l.startsWith("INCIDENT I-")).join("\n"), cfg);
|
|
2144
|
-
const incidents = openIncidentList(cfg);
|
|
2145
|
-
const incidentText = incidents.length ? `\n${incidents.map(incidentLine).join("\n")}` : "";
|
|
2146
|
-
// 20261025_1940 P2: the injected line names the autonomy tier and what Main does without asking in it.
|
|
2147
|
-
const tier = currentTier(cfg);
|
|
2148
|
-
const tierNote =
|
|
2149
|
-
tier === "strict"
|
|
2150
|
-
? `Main changes at most ${cfg.autonomy.strict_edit_limit} project files per ${cfg.guards.main_window_min} min, and every git push / glab mr merge / gh pr merge waits for your "${cfg.autonomy.go_phrase}" (one landing, valid ${cfg.autonomy.go_minutes} min).`
|
|
2151
|
-
: tier === "full"
|
|
2152
|
-
? `Main works unattended: no edit cap, its own "Priority skip: <plan> — Main: \\"<reason>\\"" skips pass, pushes and merges go through. Owner-only moves (guard files, the phone page, notify secrets, the unlock) stay locked.`
|
|
2153
|
-
: `Main changes at most ${cfg.guards.main_edit_limit} project files per ${cfg.guards.main_window_min} min; pushes and merges go through.`;
|
|
2154
|
-
const unlockNote = continuation ? "" : unlockLine(cfg);
|
|
2155
|
-
const mayNote = ` Main may edit Status/WAITING/Waits on/False positive lines. Test before saying "cannot".`;
|
|
2156
|
-
const editLimit = continuation ? "" : `\nautonomy: ${tier} — ${tierNote}${mayNote}${unlockNote}`;
|
|
2157
|
-
return {
|
|
2158
|
-
allow: true,
|
|
2159
|
-
reason: "",
|
|
2160
|
-
inject: `${summary}\n(main-guard: read ${cfg.paths.queue_index}; the listed plans are summarised above; work the open plans, close finished ones with queue-close.)${editLimit}${cancel}${incidentText}`,
|
|
2161
|
-
...(continuation ? {} : { state: { callsSinceStop: 0, idleStops: 0 } }),
|
|
2162
|
-
};
|
|
2163
|
-
}
|
|
2164
|
-
|
|
2165
|
-
function mainOnlyLines(text: string): string {
|
|
2166
|
-
return text.split("\n").filter(l => MAIN_ONLY_LINE.test(l)).join("\n");
|
|
2167
|
-
}
|
|
2168
|
-
|
|
2169
|
-
/**
|
|
2170
|
-
* plan-edit: after a subagent changed a plan, everything outside "## Progress" and every
|
|
2171
|
-
* Main-only line must be unchanged, and every Progress entry the edit adds must carry a
|
|
2172
|
-
* "Findings:" line (2026-10-24: a finding buried in a Progress note never became a plan);
|
|
2173
|
-
* `restore` hands back the untouched text for the caller to write (the original restored the
|
|
2174
|
-
* file itself before reporting).
|
|
2175
|
-
*/
|
|
2176
|
-
export function checkPlanEdit(e: PlanEditEvent, cfg: Config): PlanEditDecision {
|
|
2177
|
-
if (e.agent === "main") return checkMainPlan(e, cfg);
|
|
2178
|
-
// planner mode P2 (b): the plan bound to this sub by its approved spawn (the `Planner role for`
|
|
2179
|
-
// line) is the planner agent's to write — body freedom, but never the Main-only lines, and the
|
|
2180
|
-
// header names its agent. Only while delegated: in main mode the spawn gate refused the
|
|
2181
|
-
// Planner-role brief, and the plain Progress-only rule holds.
|
|
2182
|
-
if (currentPlanner(cfg) === "delegated" && e.agentId !== undefined && plannerSpawnPlan(e.agentId, cfg.paths) === e.path) {
|
|
2183
|
-
if (mainOnlyLines(e.after) !== mainOnlyLines(e.before)) {
|
|
2184
|
-
log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (planner wrote a Main-only line)`);
|
|
2185
|
-
return {
|
|
2186
|
-
allow: false,
|
|
2187
|
-
reason: `plan-guard: the Main-only lines ("Status:", "WAITING on owner:", "Waits on:", "Cancelled by owner:", "False positive:") of ${e.path} are never a planner agent's. The file was restored.`,
|
|
2188
|
-
restore: { path: e.path, text: e.before || null },
|
|
2189
|
-
};
|
|
2190
|
-
}
|
|
2191
|
-
const name = e.agentId ?? "";
|
|
2192
|
-
// The header records the agent the owner picked, not the spawn instance: a `glm-3` spawn
|
|
2193
|
-
// satisfies `Planner: glm`, and the spawn form still works for plans written before this.
|
|
2194
|
-
const names = new Set([name, name.replace(/-\d+$/, "")]);
|
|
2195
|
-
const head = e.after.split(/^## /m)[0] ?? "";
|
|
2196
|
-
if (!head.split("\n").some((l) => l.trim().startsWith("Planner: ") && names.has(l.trim().slice("Planner: ".length).trim()))) {
|
|
2197
|
-
log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (no Planner header)`);
|
|
2198
|
-
return {
|
|
2199
|
-
allow: false,
|
|
2200
|
-
reason: `plan-guard: ${e.path} carries no "Planner: ${name}" header — a planner agent's plan names its agent above the first section. The file was restored.`,
|
|
2201
|
-
restore: { path: e.path, text: e.before || null },
|
|
2202
|
-
};
|
|
2203
|
-
}
|
|
2204
|
-
} else if (q.outsideProgress(e.after) !== q.outsideProgress(e.before) || mainOnlyLines(e.after) !== mainOnlyLines(e.before)) {
|
|
2205
|
-
log(cfg.paths.plan_guard_log, `RESTORE ${e.path}`);
|
|
2206
|
-
return {
|
|
2207
|
-
allow: false,
|
|
2208
|
-
reason: `plan-guard: you changed ${e.path} outside your progress entries (only "## Progress" entries are yours; the "Status:", "WAITING on owner:", "Waits on:", "Cancelled by owner:" and "False positive:" lines are Main's, it marks a plan complete after reviewing your work). The file was restored.`,
|
|
2209
|
-
restore: { path: e.path, text: e.before },
|
|
2210
|
-
};
|
|
2211
|
-
}
|
|
2212
|
-
const missing = newProgressEntries(e.before, e.after).filter(b => !findingsValue(b));
|
|
2213
|
-
if (missing.length) {
|
|
2214
|
-
log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (no Findings line)`);
|
|
2215
|
-
return {
|
|
2216
|
-
allow: false,
|
|
2217
|
-
reason: `plan-guard: ${missing.length === 1 ? "your new entry in" : `${missing.length} of your new entries in`} ${e.path} ${missing.length === 1 ? "has" : "have"} no "Findings:" line. End every new "## Progress" entry with "Findings: none", or "Findings: <one item per finding (bug, workaround, improvement — any repo), each with file:line evidence>", items separated by ";". The file was restored.`,
|
|
2218
|
-
restore: { path: e.path, text: e.before },
|
|
2219
|
-
};
|
|
2220
|
-
}
|
|
2221
|
-
const loose = newProgressEntries(e.before, e.after).filter(b => REVIEW_LOOKALIKE.test(b) && !REVIEW_LINE.test(b));
|
|
2222
|
-
if (loose.length) {
|
|
2223
|
-
log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (review line)`);
|
|
2224
|
-
return {
|
|
2225
|
-
allow: false,
|
|
2226
|
-
reason: `plan-guard: a PLAN REVIEW or CODE REVIEW line in ${e.path} does not match "- [<date> <time> <name>: ]PLAN REVIEW|CODE REVIEW: PASS|FAIL — …". The file was restored.`,
|
|
2227
|
-
restore: { path: e.path, text: e.before },
|
|
2228
|
-
};
|
|
2229
|
-
}
|
|
2230
|
-
if (e.agent === "sub" && newProgressEntries(e.before, e.after).some(b => REVIEW_LINE.test(b)) && matchReviewSpawn(readReviewSpawns(cfg.paths), e.agentId ?? "")?.spawn.plan !== e.path) {
|
|
2231
|
-
log(cfg.paths.plan_guard_log, `RESTORE ${e.path} review line from a spawn that is not its named review spawn`);
|
|
2232
|
-
return { allow: false, reason: `plan-guard: a PLAN REVIEW or CODE REVIEW line counts only from the named review spawn of ${e.path}; the file was restored.`, restore: { path: e.path, text: e.before } };
|
|
2233
|
-
}
|
|
2234
|
-
recordReviews(e, cfg);
|
|
2235
|
-
return ALLOW;
|
|
2236
|
-
}
|
|
2237
|
-
|
|
2238
|
-
/** One "## Progress" entry: its "- " line plus indented continuation lines (trimProgressBody's entry rule). */
|
|
2239
|
-
function progressEntries(text: string): string[] {
|
|
2240
|
-
const blocks: string[] = [];
|
|
2241
|
-
const lines = q.progressBody(text).split("\n");
|
|
2242
|
-
for (let i = 0; i < lines.length; i++) {
|
|
2243
|
-
const head = lines[i];
|
|
2244
|
-
if (head === undefined || !head.startsWith("- ") || MAIN_ONLY_LINE.test(head)) continue;
|
|
2245
|
-
const block = [head];
|
|
2246
|
-
while (i + 1 < lines.length) {
|
|
2247
|
-
const cont = lines[i + 1];
|
|
2248
|
-
if (cont === undefined || !/^[ \t]/.test(cont)) break;
|
|
2249
|
-
block.push(cont);
|
|
2250
|
-
i++;
|
|
2251
|
-
}
|
|
2252
|
-
blocks.push(block.join("\n"));
|
|
2253
|
-
}
|
|
2254
|
-
return blocks;
|
|
2255
|
-
}
|
|
2256
|
-
|
|
2257
|
-
/** Entries an edit adds or rewrites: blocks whose text was not in the Progress section before. */
|
|
2258
|
-
export function newProgressEntries(before: string, after: string): string[] {
|
|
2259
|
-
const old = new Set(progressEntries(before));
|
|
2260
|
-
return progressEntries(after).filter(b => !old.has(b));
|
|
2261
|
-
}
|
|
2262
|
-
|
|
2263
|
-
/** The value after the entry's last "Findings:", or null when it has no Findings line with content. A "Findings:"
|
|
2264
|
-
* quoted earlier in the entry (e.g. inside resume steps) is entry text, never the findings (I-20261025-51). */
|
|
2265
|
-
export function findingsValue(block: string): string | null {
|
|
2266
|
-
const line = block.split("\n").findLast(l => l.includes("Findings:"));
|
|
2267
|
-
if (!line) return null;
|
|
2268
|
-
return line.slice(line.lastIndexOf("Findings:") + "Findings:".length).trim() || null;
|
|
2269
|
-
}
|
|
2270
|
-
|
|
2271
|
-
/** P6 (plan 20261028_1600): the refusal for ticking `ids` with review.code on. Each phase needs a recorded CODE REVIEW: PASS from a named review spawn (the `code` map of plan-reviews.json), and its entry must still be the plan's last Progress entry naming the phase — last by the entry's `<YYYY-MM-DD HH:MM>` stamp, not file order (live plans are newest-first or appended): implementer work after the review voids it. */
|
|
2272
|
-
function codeReviewProblem(file: string, after: string, ids: string[], paths: Pick<q.QueuePaths, "queue_state">): string | null {
|
|
2273
|
-
const rec = readCodeReviews(paths)[file];
|
|
2274
|
-
// toSorted is stable: ties and unstamped entries ("") keep file order.
|
|
2275
|
-
const entries = progressEntries(after)
|
|
2276
|
-
.map(b => [b, /^\s*-\s*(\d{4}-\d{2}-\d{2} \d{2}:\d{2})/.exec(b)?.[1] ?? ""] as const)
|
|
2277
|
-
.toSorted((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0))
|
|
2278
|
-
.map(([b]) => b);
|
|
2279
|
-
for (const id of ids) {
|
|
2280
|
-
const last = entries.findLast(b => new RegExp(`\\b${id}\\b`).test(b));
|
|
2281
|
-
const valid = last !== undefined && REVIEW_LINE.test(last) && REVIEW_LINE.exec(last)![1] === "CODE" && REVIEW_LINE.exec(last)![2] === "PASS";
|
|
2282
|
-
if (!(rec?.verdict === "PASS" && rec.phases.includes(id) && valid))
|
|
2283
|
-
return `plan-guard: phase ${id} was ticked but has no current CODE REVIEW: PASS from a review spawn after its last implementer entry — spawn a code reviewer or set review.code: false. The file was restored.`;
|
|
2284
|
-
}
|
|
2285
|
-
return null;
|
|
2286
|
-
}
|
|
2287
|
-
|
|
2288
|
-
/** The plan text a planner agent owns: everything outside "## Progress" and the Main-only lines (planner mode P2a, plan 20261102_1515) — minus the two zones Main may still correct (punch list, plan 20261102_2315): a "## Done check" section's body, and the backticked `verify:` span on a "## Phases" checkbox line. */
|
|
2289
|
-
export function plannerBody(text: string): string {
|
|
2290
|
-
const body = q.outsideProgress(text).split("\n");
|
|
2291
|
-
let section = "";
|
|
2292
|
-
// Dropped lines are removed, not blanked: adding or deleting a Main-only line must not change the body.
|
|
2293
|
-
return body
|
|
2294
|
-
.flatMap((l) => {
|
|
2295
|
-
if (l.startsWith("## ")) section = l;
|
|
2296
|
-
if (/^## +Done check\b/i.test(section) || MAIN_ONLY_LINE.test(l)) return [];
|
|
2297
|
-
if (/^## +Phases\b/i.test(section) && /^- \[[ x]\]/.test(l)) return [l.replace(/`verify:[^`]*`/g, "`verify:`")];
|
|
2298
|
-
return [l];
|
|
2299
|
-
})
|
|
2300
|
-
.join("\n");
|
|
2301
|
-
}
|
|
2302
|
-
|
|
2303
|
-
// Main's plan text outside "## Progress" must rest on files Main read itself (planReadProblems).
|
|
2304
|
-
// An empty `before` means the plan file did not exist yet; a refusal then deletes it.
|
|
2305
|
-
function checkMainPlan(e: PlanEditEvent, cfg: Config): PlanEditDecision {
|
|
2306
|
-
// planner mode P2 (a): while delegated, Main plans nothing — a new plan file or a rewrite of
|
|
2307
|
-
// the text outside "## Progress" is the planner agent's work. Main keeps its Progress entries,
|
|
2308
|
-
// the Main-only lines (Status / WAITING on owner / Waits on / Cancelled by owner / False
|
|
2309
|
-
// positive) and the index; running the queue stays Main's.
|
|
2310
|
-
if (currentPlanner(cfg) === "delegated" && e.path !== cfg.paths.queue_index && plannerBody(e.after) !== plannerBody(e.before)) {
|
|
2311
|
-
log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (planner delegated)`);
|
|
2312
|
-
return {
|
|
2313
|
-
allow: false,
|
|
2314
|
-
reason: `plan-guard: planner is delegated — route the ask to the planner agent. ${e.before ? "The file was restored." : "The new file was removed."}`,
|
|
2315
|
-
restore: { path: e.path, text: e.before || null },
|
|
2316
|
-
};
|
|
2317
|
-
}
|
|
2318
|
-
// P3 (plan 20261027_1300): another Main's live claim on this plan refuses the edit, restored
|
|
2319
|
-
// like any refused plan edit. No claim — or this Main's own — edits freely. The chooser gets
|
|
2320
|
-
// `e.before` (the file on disk already holds the edit, so a team plan stays guarded while an
|
|
2321
|
-
// edit removes its header; the record rule covers it too).
|
|
2322
|
-
const holder = claimStoreFor(e.path, cfg, e.before).holder(e.path);
|
|
2323
|
-
if (holder !== null && "unreachable" in holder) {
|
|
2324
|
-
log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (team server ${holder.unreachable} unreachable)`);
|
|
2325
|
-
return {
|
|
2326
|
-
allow: false,
|
|
2327
|
-
reason: `plan-guard: ${heldProblem(e.path, holder)}; the file was restored.`,
|
|
2328
|
-
restore: { path: e.path, text: e.before || null },
|
|
2329
|
-
};
|
|
2330
|
-
}
|
|
2331
|
-
if (holder && heldByOther(holder, mainId())) {
|
|
2332
|
-
log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (held by Main ${holder.main})`);
|
|
2333
|
-
return {
|
|
2334
|
-
allow: false,
|
|
2335
|
-
reason: `plan-guard: ${heldProblem(e.path, holder)}; the file was restored.`,
|
|
2336
|
-
restore: { path: e.path, text: e.before || null },
|
|
2337
|
-
};
|
|
2338
|
-
}
|
|
2339
|
-
// A PLAN REVIEW or CODE REVIEW line (P6) is a review spawn's verdict (P4k): Main writes none, so its edit is restored.
|
|
2340
|
-
if (newProgressEntries(e.before, e.after).some(b => REVIEW_LINE.test(b))) {
|
|
2341
|
-
log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (Main wrote a review line)`);
|
|
2342
|
-
return {
|
|
2343
|
-
allow: false,
|
|
2344
|
-
reason: `plan-guard: a PLAN REVIEW or CODE REVIEW line is written only by the named review spawn of ${e.path}, never by Main. The file was restored.`,
|
|
2345
|
-
restore: { path: e.path, text: e.before || null },
|
|
2346
|
-
};
|
|
2347
|
-
}
|
|
2348
|
-
// P6 (plan 20261028_1600): with review.code on, ticking a phase needs a named review spawn's CODE REVIEW: PASS behind it — the recorded verdict counts, never Main's own line.
|
|
2349
|
-
if (cfg.review.code) {
|
|
2350
|
-
const ticks = newlyTicked(e.before, e.after);
|
|
2351
|
-
const problem = ticks.length ? codeReviewProblem(e.path, e.after, ticks, cfg.paths) : null;
|
|
2352
|
-
if (problem) {
|
|
2353
|
-
log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (code review: ${ticks.join(", ")})`);
|
|
2354
|
-
return { allow: false, reason: problem, restore: { path: e.path, text: e.before || null } };
|
|
2355
|
-
}
|
|
2356
|
-
}
|
|
2357
|
-
if (q.outsideProgress(e.after) === q.outsideProgress(e.before)) {
|
|
2358
|
-
return ALLOW;
|
|
2359
|
-
}
|
|
2360
|
-
// A cited file Main did read lands in the list instead of the refusal (I-20261025-208): fix the
|
|
2361
|
-
// text first, then judge the fixed text like any other edit.
|
|
2362
|
-
const fix = autoListReads(e.after, e.path, cfg);
|
|
2363
|
-
const fixed = fix ? fix.text : e.after;
|
|
2364
|
-
// Refuse only what this edit adds: a problem the plan already had is not Main's doing now.
|
|
2365
|
-
// The missing-section problem is always refused: a plan with no read list has no evidence behind its text.
|
|
2366
|
-
const known = new Set(e.before ? planReadProblems(e.before, e.path, cfg) : []);
|
|
2367
|
-
const problems = planReadProblems(fixed, e.path, cfg).filter(p => p === NO_SECTION || !known.has(p));
|
|
2368
|
-
if (!problems.length) {
|
|
2369
|
-
if (!fix) return ALLOW;
|
|
2370
|
-
const list = fix.paths.join(", ");
|
|
2371
|
-
log(cfg.paths.plan_guard_log, `AUTO-LIST ${e.path}: ${list}`);
|
|
2372
|
-
return {
|
|
2373
|
-
allow: true,
|
|
2374
|
-
reason: "",
|
|
2375
|
-
rewrite: { path: e.path, text: fix.text },
|
|
2376
|
-
note: `plan-guard: added ${fix.paths.length} file(s) to "## Code read by Main": ${list}`,
|
|
2377
|
-
};
|
|
2378
|
-
}
|
|
2379
|
-
log(cfg.paths.plan_guard_log, `REFUSE-READ ${e.path}: ${problems.join("; ")}`);
|
|
2380
|
-
return {
|
|
2381
|
-
allow: false,
|
|
2382
|
-
reason: `plan-guard: ${e.path} cites code Main has not read for this plan:\n- ${problems.join("\n- ")}\nRead each file (read or grep it), list it under "## Code read by Main", then edit again. ${e.before ? "The file was restored." : "The new file was removed."}`,
|
|
2383
|
-
restore: { path: e.path, text: e.before || null },
|
|
2384
|
-
};
|
|
2385
|
-
}
|
|
2386
|
-
|
|
2387
|
-
const READ_SECTION = /^## Code read by Main[^\n]*\n([\s\S]*?)(?=^## |(?![\s\S]))/m;
|
|
2388
|
-
const LISTED_PATH = /`([^`\s]+)`/g;
|
|
2389
|
-
const CITED_PATH = /((?:~\/|\/|\.{1,2}\/)?[\w@.-]+(?:\/[\w@.-]+)*\.[A-Za-z0-9]+):\d+/g;
|
|
2390
|
-
|
|
2391
|
-
const NO_SECTION = `no "## Code read by Main" section lists a file (list each file you read for this plan as a backticked path)`;
|
|
2392
|
-
|
|
2393
|
-
/** Read evidence behind a plan edit: section present, each listed path read within the window, no unlisted cited path. */
|
|
2394
|
-
function planReadProblems(text: string, planPath: string, cfg: Config): string[] {
|
|
2395
|
-
const listed = [...(READ_SECTION.exec(text)?.[1] ?? "").matchAll(LISTED_PATH)].map(m => (m[1] ?? "").replace(/:[\d,+\- ]+$/, ""));
|
|
2396
|
-
if (!listed.length) return [NO_SECTION];
|
|
2397
|
-
const reads = readMainReads(cfg.paths);
|
|
2398
|
-
const maxMs = cfg.guards.plan_read_max_hours * 3_600_000;
|
|
2399
|
-
const problems: string[] = [];
|
|
2400
|
-
const named = new Set<string>();
|
|
2401
|
-
for (const p of listed) {
|
|
2402
|
-
const abs = planFile(p, planPath, text);
|
|
2403
|
-
named.add(abs);
|
|
2404
|
-
if (!isFile(abs)) problems.push(`${p} does not exist`);
|
|
2405
|
-
else if (!readWithin(abs, planPath, text, reads, maxMs)) problems.push(`${p} was not read by Main within ${cfg.guards.plan_read_max_hours} h`);
|
|
2406
|
-
}
|
|
2407
|
-
for (const [, cited = ""] of q.outsideProgress(text).matchAll(CITED_PATH)) {
|
|
2408
|
-
const abs = planFile(cited, planPath, text);
|
|
2409
|
-
if (abs.includes("/docs/plans/") || namedOrTwin(named, abs, planPath, text) || !isFile(abs)) continue;
|
|
2410
|
-
problems.push(`${cited} is cited but not listed under "## Code read by Main"`);
|
|
2411
|
-
}
|
|
2412
|
-
return problems;
|
|
2413
|
-
}
|
|
2414
|
-
|
|
2415
|
-
/** A plan-cited path: absolute, else under the plan's Worktree (when set) or its repo root. */
|
|
2416
|
-
function planFile(p: string, planPath: string, text: string): string {
|
|
2417
|
-
const home = q.expandHome(p);
|
|
2418
|
-
if (path.isAbsolute(home)) return home;
|
|
2419
|
-
const roots = planRoots(planPath, text);
|
|
2420
|
-
const root = roots.find(r => isFile(path.join(r, home))) ?? roots[roots.length - 1]!;
|
|
2421
|
-
return path.join(root, home);
|
|
2422
|
-
}
|
|
2423
|
-
|
|
2424
|
-
/** The roots a plan-relative path resolves against: the plan's Worktree (when set), then its repo (the text before /docs/plans/, so a docs/plans/<subdir>/ plan still resolves repo-relative paths against <repo>). */
|
|
2425
|
-
function planRoots(planPath: string, text: string): string[] {
|
|
2426
|
-
const wt = /^Worktree:\s*(\S+)/m.exec(text)?.[1];
|
|
2427
|
-
const cut = planPath.indexOf("/docs/plans/");
|
|
2428
|
-
const repo = cut >= 0 ? planPath.slice(0, cut) : path.dirname(path.dirname(path.dirname(planPath)));
|
|
2429
|
-
return wt && wt !== "-" ? [wt, repo] : [repo];
|
|
2430
|
-
}
|
|
2431
|
-
|
|
2432
|
-
/** The same repo-relative file under the plan's other root (Worktree ↔ main checkout), or null when `abs` sits under neither. */
|
|
2433
|
-
function twinFile(abs: string, planPath: string, text: string): string | null {
|
|
2434
|
-
const roots = planRoots(planPath, text);
|
|
2435
|
-
for (const root of roots) {
|
|
2436
|
-
const prefixed = root.endsWith("/") ? root : `${root}/`;
|
|
2437
|
-
if (!abs.startsWith(prefixed)) continue;
|
|
2438
|
-
for (const other of roots) {
|
|
2439
|
-
if (other === root) continue;
|
|
2440
|
-
return `${other.endsWith("/") ? other : `${other}/`}${abs.slice(prefixed.length)}`;
|
|
2441
|
-
}
|
|
2442
|
-
}
|
|
2443
|
-
return null;
|
|
2444
|
-
}
|
|
2445
|
-
|
|
2446
|
-
/** Main read this file within the window — at the resolved path or at its twin under the plan's other root (I-20261025-208 evidence: the same file read in the main checkout must cover its Worktree copy). */
|
|
2447
|
-
function readWithin(abs: string, planPath: string, text: string, reads: Record<string, string>, maxMs: number): boolean {
|
|
2448
|
-
const cutoff = Date.now() - maxMs;
|
|
2449
|
-
const fresh = (f: string) => Date.parse(reads[f] ?? "") >= cutoff;
|
|
2450
|
-
if (fresh(abs)) return true;
|
|
2451
|
-
const twin = twinFile(abs, planPath, text);
|
|
2452
|
-
return twin !== null && fresh(twin);
|
|
2453
|
-
}
|
|
2454
|
-
|
|
2455
|
-
/** The resolved path, or its twin under the plan's other root, is already in the set (cited-vs-listed matches files, not spellings). */
|
|
2456
|
-
function namedOrTwin(named: Set<string>, abs: string, planPath: string, text: string): boolean {
|
|
2457
|
-
if (named.has(abs)) return true;
|
|
2458
|
-
const twin = twinFile(abs, planPath, text);
|
|
2459
|
-
return twin !== null && named.has(twin);
|
|
2460
|
-
}
|
|
2461
|
-
|
|
2462
|
-
/**
|
|
2463
|
-
* Cited paths (outside Progress) Main read within the window but the list omits: returns the plan
|
|
2464
|
-
* text with one `- \`<path as cited>\`` line appended to "## Code read by Main" (the section is
|
|
2465
|
-
* created before "## Progress" when missing), or null when nothing qualifies. Never-read citations
|
|
2466
|
-
* stay out: they are refused like today.
|
|
2467
|
-
*/
|
|
2468
|
-
function autoListReads(text: string, planPath: string, cfg: Config): { text: string; paths: string[] } | null {
|
|
2469
|
-
const reads = readMainReads(cfg.paths);
|
|
2470
|
-
const maxMs = cfg.guards.plan_read_max_hours * 3_600_000;
|
|
2471
|
-
const covered = new Set<string>();
|
|
2472
|
-
for (const p of [...(READ_SECTION.exec(text)?.[1] ?? "").matchAll(LISTED_PATH)].map(m => (m[1] ?? "").replace(/:[\d,+\- ]+$/, "")))
|
|
2473
|
-
covered.add(planFile(p, planPath, text));
|
|
2474
|
-
const added: string[] = [];
|
|
2475
|
-
const seen = new Set<string>();
|
|
2476
|
-
for (const [, cited = ""] of q.outsideProgress(text).matchAll(CITED_PATH)) {
|
|
2477
|
-
const abs = planFile(cited, planPath, text);
|
|
2478
|
-
if (abs.includes("/docs/plans/") || seen.has(cited) || !isFile(abs)) continue;
|
|
2479
|
-
if (namedOrTwin(covered, abs, planPath, text)) continue;
|
|
2480
|
-
if (!readWithin(abs, planPath, text, reads, maxMs)) continue;
|
|
2481
|
-
seen.add(cited);
|
|
2482
|
-
covered.add(abs);
|
|
2483
|
-
added.push(cited);
|
|
2484
|
-
}
|
|
2485
|
-
if (!added.length) return null;
|
|
2486
|
-
const lines = added.map(p => `- \`${p}\``);
|
|
2487
|
-
const m = READ_SECTION.exec(text);
|
|
2488
|
-
let out: string;
|
|
2489
|
-
if (m && m[1] !== undefined) {
|
|
2490
|
-
// Append after the section's last entry, ahead of the blank lines before the next heading.
|
|
2491
|
-
const bodyStart = m.index + m[0].length - m[1].length;
|
|
2492
|
-
const at = bodyStart + m[1].replace(/\s+$/, "").length;
|
|
2493
|
-
out = `${text.slice(0, at)}\n${lines.join("\n")}${text.slice(at)}`;
|
|
2494
|
-
} else {
|
|
2495
|
-
// No section yet: create it right before "## Progress" (or at the end when that is missing too).
|
|
2496
|
-
const at = text.search(/^## Progress\b/m);
|
|
2497
|
-
const block = `## Code read by Main\n${lines.join("\n")}\n\n`;
|
|
2498
|
-
out = at === -1 ? `${text}${block}` : `${text.slice(0, at)}${block}${text.slice(at)}`;
|
|
2499
|
-
}
|
|
2500
|
-
return { text: out, paths: added };
|
|
2501
|
-
}
|
|
2502
|
-
|
|
2503
|
-
function isFile(file: string): boolean {
|
|
2504
|
-
try {
|
|
2505
|
-
return statSync(file).isFile();
|
|
2506
|
-
} catch {
|
|
2507
|
-
return false;
|
|
2508
|
-
}
|
|
2509
|
-
}
|
|
2510
|
-
|
|
2511
|
-
function readMainReads(paths: Pick<q.QueuePaths, "queue_state">): Record<string, string> {
|
|
2512
|
-
try {
|
|
2513
|
-
return JSON.parse(readFileSync(path.join(paths.queue_state, "main-reads.json"), "utf8")) as Record<string, string>;
|
|
2514
|
-
} catch {
|
|
2515
|
-
return {};
|
|
2516
|
-
}
|
|
2517
|
-
}
|
|
2518
|
-
|
|
2519
|
-
// Plans still responsible for: open plans (parked "WAITING on owner" excluded) plus queue problems.
|
|
2520
|
-
export function openQueue(paths: q.QueuePaths, reviewAgents: string[] = []): string[] {
|
|
2521
|
-
const open = q
|
|
2522
|
-
.activePlans(paths)
|
|
2523
|
-
.filter(p => !p.waiting && !q.awaitingMerge(p, paths))
|
|
2524
|
-
.map(p => p.file);
|
|
2525
|
-
for (const prob of q.queueProblems(paths, reviewAgents)) open.push(`${prob.where}: ${prob.problem}`);
|
|
2526
|
-
const unique: string[] = [];
|
|
2527
|
-
for (const item of open) if (!unique.includes(item)) unique.push(item);
|
|
2528
|
-
return unique;
|
|
2529
|
-
}
|
|
2530
|
-
|
|
2531
|
-
// Agent names from a ledger line that are alive (RUNNING or WAITING, idle under an hour).
|
|
2532
|
-
export function liveSubagents(ledgerOut: string): string[] {
|
|
2533
|
-
return ledgerOut
|
|
2534
|
-
.split("\n")
|
|
2535
|
-
.filter(l => !l.startsWith("MAIN ") && /\s(RUNNING|WAITING)\b/.test(l))
|
|
2536
|
-
.filter(l => {
|
|
2537
|
-
const m = l.match(/idle (\d+)m/);
|
|
2538
|
-
return !m || Number(m[1]) < 60;
|
|
2539
|
-
})
|
|
2540
|
-
.map(l => l.split(/\s+/)[0] ?? "");
|
|
2541
|
-
}
|
|
2542
|
-
|
|
2543
|
-
export const STOP_PLAN_OFFER_REFUSAL = "main-guard: don't promise it — do it now, or write the plan and index it";
|
|
2544
|
-
|
|
2545
|
-
/**
|
|
2546
|
-
* stop: Main may not stop while an open plan is not parked "WAITING on owner" (or the queue has a
|
|
2547
|
-
* problem) and no subagent is alive to wake it; an open owner-correction incident (source
|
|
2548
|
-
* "realtime", no plan, no dismissal) blocks the stop regardless of live subagents. Three stop
|
|
2549
|
-
* attempts in a row with zero tool calls
|
|
2550
|
-
* in between are let through. Returns the next counters in `state`.
|
|
2551
|
-
*/
|
|
2552
|
-
export function checkStop(e: StopEvent, cfg: Config): Decision {
|
|
2553
|
-
if (e.agent !== "main") return ALLOW;
|
|
2554
|
-
const state = { callsSinceStop: e.callsSinceStop, idleStops: e.idleStops };
|
|
2555
|
-
// 20261028_0900 P2: a reply that offers to plan instead of planning is refused for the offer
|
|
2556
|
-
// itself; the two-empty-stops valves below never release this block.
|
|
2557
|
-
if (e.reply && new RegExp(cfg.guards.plan_offer, "i").test(e.reply)) {
|
|
2558
|
-
log(cfg.paths.guard_log, "BLOCK stop: reply offers or promises instead of doing it");
|
|
2559
|
-
return { allow: false, reason: STOP_PLAN_OFFER_REFUSAL, state };
|
|
2560
|
-
}
|
|
2561
|
-
// P5 (plan 20261031_1207): once the turn spent its call budget, the stop is the release —
|
|
2562
|
-
// refusing it would order a capped Main to keep making calls the cap itself refuses. The
|
|
2563
|
-
// 15-min window expiry restarts the count, and the keep-working rule with it.
|
|
2564
|
-
if (cfg.guards.main_max_calls > 0) {
|
|
2565
|
-
const w = readWindow(cfg.paths);
|
|
2566
|
-
if (w.mainCalls >= cfg.guards.main_max_calls && !mainCallsExpired(w)) {
|
|
2567
|
-
log(cfg.paths.guard_log, `ALLOW stop: turn spent ${w.mainCalls}/${cfg.guards.main_max_calls} calls`);
|
|
2568
|
-
return { ...ALLOW, state };
|
|
2569
|
-
}
|
|
2570
|
-
}
|
|
2571
|
-
let open: string[];
|
|
2572
|
-
try {
|
|
2573
|
-
open = openQueue(cfg.paths, cfg.review.agents);
|
|
2574
|
-
} catch (err) {
|
|
2575
|
-
log(cfg.paths.guard_log, `BLOCK stop: cannot read queue: ${err}`);
|
|
2576
|
-
open = [`queue unreadable (${cfg.paths.queue_index}): ${err}`];
|
|
2577
|
-
}
|
|
2578
|
-
const pending = q.cancelPending(cfg.paths);
|
|
2579
|
-
if (pending && state.idleStops < 2) {
|
|
2580
|
-
if (state.callsSinceStop === 0) state.idleStops++;
|
|
2581
|
-
state.callsSinceStop = 0;
|
|
2582
|
-
log(cfg.paths.guard_log, `BLOCK stop: cancel pending (${pending.words})`);
|
|
2583
|
-
return { allow: false, reason: `main-guard: ${CANCEL_TODO} Flagged: "${pending.words}"`, state };
|
|
2584
|
-
}
|
|
2585
|
-
// Same release valve as cancel-pending: an idle Main that cannot act is let out after two
|
|
2586
|
-
// empty stop attempts instead of looping forever. Live subagents do not clear this block.
|
|
2587
|
-
// Findings/traces stay notes: only owner corrections (source "realtime") block the stop.
|
|
2588
|
-
const incidents = openIncidentList(cfg).filter(i => i.source === "realtime");
|
|
2589
|
-
if (incidents.length && state.idleStops < 2) {
|
|
2590
|
-
if (state.callsSinceStop === 0) state.idleStops++;
|
|
2591
|
-
state.callsSinceStop = 0;
|
|
2592
|
-
const ids = incidents.map(i => i.id).join(", ");
|
|
2593
|
-
log(cfg.paths.guard_log, `BLOCK stop: open incidents: ${ids}`);
|
|
2594
|
-
return {
|
|
2595
|
-
allow: false,
|
|
2596
|
-
reason:
|
|
2597
|
-
`main-guard: ${incidents.length} open incident(s) with no plan and no dismissal: ${ids}. Plan the fix: ` +
|
|
2598
|
-
"`neurastream incident plan <id> <plan.md>` (the plan must contain \"INCIDENT <id>\"), or dismiss it: " +
|
|
2599
|
-
'`neurastream incident dismiss <id> --why "<text>"`. The stop stays refused while an incident is open.',
|
|
2600
|
-
state,
|
|
2601
|
-
};
|
|
2602
|
-
}
|
|
2603
|
-
// P5 (plan 20261031_0911): a landed open plan whose auto-close failed holds the stop until a
|
|
2604
|
-
// running subagent's brief names it (staffing ∩ live ledger); unrelated live subagents release
|
|
2605
|
-
// nothing. Valve (20261031_2320): like the incident block above, empty stops count toward
|
|
2606
|
-
// cfg.guards.idle_stops; a stop with calls in between resets the count and re-locks.
|
|
2607
|
-
const locked = q.activePlans(cfg.paths).filter(p => p.status === "open" && q.autoCloseCandidate(p) && q.lastCloseFailed(p.file, cfg.paths));
|
|
2608
|
-
if (locked.length) {
|
|
2609
|
-
const staffed = staffedPlans(readStaffing(cfg.paths), liveSubagents(e.ledgerText));
|
|
2610
|
-
const unworked = locked.filter(s => !staffed.includes(s.file));
|
|
2611
|
-
if (unworked.length) {
|
|
2612
|
-
if (state.callsSinceStop === 0) state.idleStops++;
|
|
2613
|
-
else state.idleStops = 0;
|
|
2614
|
-
state.callsSinceStop = 0;
|
|
2615
|
-
if (state.idleStops >= cfg.guards.idle_stops) {
|
|
2616
|
-
log(cfg.paths.guard_log, `ALLOW stop after ${state.idleStops} idle stop attempts; locked: ${unworked.map(s => s.file).join(", ")}`);
|
|
2617
|
-
return { allow: true, reason: "", state: { callsSinceStop: 0, idleStops: 0 } };
|
|
2618
|
-
}
|
|
2619
|
-
const left = cfg.guards.idle_stops - state.idleStops;
|
|
2620
|
-
log(cfg.paths.guard_log, `BLOCK stop: landed but not closed: ${unworked.map(s => s.file).join(", ")}`);
|
|
2621
|
-
return {
|
|
2622
|
-
allow: false,
|
|
2623
|
-
reason:
|
|
2624
|
-
`main-guard: ${unworked.map(s => `${s.file} landed but its auto-close failed (${(q.lastCloseResult(s.file, cfg.paths) ?? "").replace(/^queue-close: /, "")})`).join("; ")}. ` +
|
|
2625
|
-
"The stop stays locked: spawn an agent whose brief names the plan, or fix the close. " +
|
|
2626
|
-
`${left} idle stop ${left === 1 ? "attempt" : "attempts"} left before the stop is allowed.`,
|
|
2627
|
-
state,
|
|
2628
|
-
};
|
|
2629
|
-
}
|
|
2630
|
-
}
|
|
2631
|
-
if (open.length === 0) return { ...ALLOW, state };
|
|
2632
|
-
const live = liveSubagents(e.ledgerText);
|
|
2633
|
-
if (live.length > 0) {
|
|
2634
|
-
log(cfg.paths.guard_log, `ALLOW stop: live subagents: ${live.join(", ")}`);
|
|
2635
|
-
return { ...ALLOW, state };
|
|
2636
|
-
}
|
|
2637
|
-
if (state.callsSinceStop === 0) state.idleStops++;
|
|
2638
|
-
else state.idleStops = 0;
|
|
2639
|
-
state.callsSinceStop = 0;
|
|
2640
|
-
if (state.idleStops >= cfg.guards.idle_stops) {
|
|
2641
|
-
log(cfg.paths.guard_log, `ALLOW stop after ${state.idleStops} idle stop attempts; open: ${open.join(" | ")}`);
|
|
2642
|
-
return { allow: true, reason: "", state: { callsSinceStop: 0, idleStops: 0 } };
|
|
2643
|
-
}
|
|
2644
|
-
// P5b (plan 20261031_1207): the refusal repeats on every blocked stop; name the first 10 only.
|
|
2645
|
-
const listed = open.slice(0, q.SUMMARY_CAP);
|
|
2646
|
-
const moreOpen = open.length - listed.length;
|
|
2647
|
-
log(cfg.paths.guard_log, `BLOCK stop; open: ${open.join(" | ")}`);
|
|
2648
|
-
return {
|
|
2649
|
-
allow: false,
|
|
2650
|
-
reason:
|
|
2651
|
-
`main-guard: the queue has ${open.length} open item${open.length === 1 ? "" : "s"} and no subagent is ` +
|
|
2652
|
-
`running to wake you. Owner rule: keep working while the queue has items. Start the next step (spawn an ` +
|
|
2653
|
-
`agent), close a finished plan with queue-close, or, if a plan truly waits on the owner, add a line ` +
|
|
2654
|
-
`"WAITING on owner: <what>" to that plan. Open: ${listed.join(" | ")}` +
|
|
2655
|
-
(moreOpen > 0 ? ` … ${moreOpen} more (queue-check lists all)` : ""),
|
|
2656
|
-
state,
|
|
2657
|
-
};
|
|
2658
|
-
}
|
|
1
|
+
// Guard rules barrel: re-exports the decomposed modules under src/core/guards/.
|
|
2
|
+
// `guards/state.ts` MUST be exported first (zero imports from team-client.ts or sibling guards/*)
|
|
3
|
+
// so cyclic imports via `team-client.ts` (`mainId`) and `blockers.ts` (`MAIN_PLAN_FILE`) are TDZ-safe.
|
|
4
|
+
|
|
5
|
+
export * from "./guards/state.ts";
|
|
6
|
+
export * from "./guards/review.ts";
|
|
7
|
+
export * from "./guards/planner.ts";
|
|
8
|
+
export * from "./guards/spawn.ts";
|
|
9
|
+
export * from "./guards/tool.ts";
|
|
10
|
+
export * from "./guards/plan-edit.ts";
|
|
11
|
+
export * from "./guards/stop.ts";
|
|
12
|
+
export { reviewHash } from "./plan-approval.ts";
|