neurastream 0.3.21 → 0.3.23

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.
@@ -1,6 +1,6 @@
1
1
  // Plan edit verification: subagent Progress-only / planner-body / Findings / review rules, and Main read-evidence checks.
2
2
 
3
- import { readFileSync, statSync } from "node:fs";
3
+ import { existsSync, readFileSync, statSync } from "node:fs";
4
4
  import path from "node:path";
5
5
  import type { PlanEditEvent } from "../adapter.ts";
6
6
  import { currentPlanner } from "../autonomy.ts";
@@ -9,6 +9,30 @@ import type { Config } from "../config.ts";
9
9
  import { MAIN_ONLY_LINE } from "../plan-approval.ts";
10
10
  import * as q from "../queue/lib.ts";
11
11
  import { claimStoreFor } from "../team-client.ts";
12
+ import {
13
+ MAX_TERMS,
14
+ NONE_TERMS_MIN,
15
+ SLOW_RETRY,
16
+ citeRoots,
17
+ citedQuotes,
18
+ freshGraph,
19
+ hasBareChecked,
20
+ isMapOrNoneLine,
21
+ mapLine,
22
+ normRel,
23
+ optionTermProblems,
24
+ parseMapLine,
25
+ parseNoneLine,
26
+ planTerms,
27
+ queryBudget,
28
+ readConfined,
29
+ realGraphify,
30
+ searchTerms,
31
+ versionProblem,
32
+ type CitedQuote,
33
+ type QueryBudget,
34
+ type ReuseGraph,
35
+ } from "../reuse-map.ts";
12
36
  import { plannerBody, plannerSpawnPlan } from "./planner.ts";
13
37
  import { codeReviewProblem, matchReviewSpawn, readReviewSpawns, recordReviews, REVIEW_LINE, REVIEW_LOOKALIKE } from "./review.ts";
14
38
  import {
@@ -67,8 +91,8 @@ function mainOnlyLines(text: string): string {
67
91
  * `restore` hands back the untouched text for the caller to write (the original restored the
68
92
  * file itself before reporting).
69
93
  */
70
- export function checkPlanEdit(e: PlanEditEvent, cfg: Config): PlanEditDecision {
71
- if (e.agent === "main") return checkMainPlan(e, cfg);
94
+ export function checkPlanEdit(e: PlanEditEvent, cfg: Config, graph: ReuseGraph = realGraphify): PlanEditDecision {
95
+ if (e.agent === "main") return checkMainPlan(e, cfg, graph);
72
96
  // planner mode P2 (b): the plan bound to this sub by its approved spawn (the `Planner role for`
73
97
  // line) is the planner agent's to write — body freedom, but never the Main-only lines, and the
74
98
  // header names its agent. Only while delegated: in main mode the spawn gate refused the
@@ -95,6 +119,17 @@ export function checkPlanEdit(e: PlanEditEvent, cfg: Config): PlanEditDecision {
95
119
  restore: { path: e.path, text: e.before || null },
96
120
  };
97
121
  }
122
+ // Reuse map (plan 20261122_1828_reuse_map P2): the planner's plan body carries the map
123
+ // line or none line too — the same write-time check Main's plan text faces.
124
+ const reuse = reuseMapWriteProblems(e.after, e.path, cfg, graph);
125
+ if (reuse.length) {
126
+ log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (reuse map)`);
127
+ return {
128
+ allow: false,
129
+ reason: `plan-guard: ${e.path} fails the reuse map gate:\n- ${reuse.join("\n- ")}\nThe file was restored.`,
130
+ restore: { path: e.path, text: e.before || null },
131
+ };
132
+ }
98
133
  } else if (q.outsideProgress(e.after) !== q.outsideProgress(e.before) || mainOnlyLines(e.after) !== mainOnlyLines(e.before)) {
99
134
  log(cfg.paths.plan_guard_log, `RESTORE ${e.path}`);
100
135
  return {
@@ -131,7 +166,7 @@ export function checkPlanEdit(e: PlanEditEvent, cfg: Config): PlanEditDecision {
131
166
 
132
167
  // Main's plan text outside "## Progress" must rest on files Main read itself (planReadProblems).
133
168
  // An empty `before` means the plan file did not exist yet; a refusal then deletes it.
134
- function checkMainPlan(e: PlanEditEvent, cfg: Config): PlanEditDecision {
169
+ function checkMainPlan(e: PlanEditEvent, cfg: Config, graph: ReuseGraph): PlanEditDecision {
135
170
  // planner mode P2 (a): while delegated, Main plans nothing — a new plan file or a rewrite of
136
171
  // the text outside "## Progress" is the planner agent's work. Main keeps its Progress entries,
137
172
  // the Main-only lines (Status / WAITING on owner / Waits on / Cancelled by owner / False
@@ -192,8 +227,16 @@ function checkMainPlan(e: PlanEditEvent, cfg: Config): PlanEditDecision {
192
227
  const fixed = fix ? fix.text : e.after;
193
228
  // Refuse only what this edit adds: a problem the plan already had is not Main's doing now.
194
229
  // The missing-section problem is always refused: a plan with no read list has no evidence behind its text.
230
+ // Reuse map (plan 20261122_1828_reuse_map P2b): its problems join the same refusal, likewise
231
+ // only the ones this edit adds. Both passes share one query budget (and memoised search results), so a slow
232
+ // check is never filtered as known: SLOW_RETRY always refuses.
233
+ const budget = queryBudget();
195
234
  const known = new Set(e.before ? planReadProblems(e.before, e.path, cfg) : []);
196
- const problems = planReadProblems(fixed, e.path, cfg).filter(p => p === NO_SECTION || !known.has(p));
235
+ const knownReuse = new Set(e.before ? reuseMapWriteProblems(e.before, e.path, cfg, graph, budget) : []);
236
+ const problems = [
237
+ ...planReadProblems(fixed, e.path, cfg).filter((p) => p === NO_SECTION || !known.has(p)),
238
+ ...reuseMapWriteProblems(fixed, e.path, cfg, graph, budget).filter((p) => p === SLOW_RETRY || !knownReuse.has(p)),
239
+ ];
197
240
  if (!problems.length) {
198
241
  if (!fix) return ALLOW;
199
242
  const list = fix.paths.join(", ");
@@ -213,6 +256,155 @@ function checkMainPlan(e: PlanEditEvent, cfg: Config): PlanEditDecision {
213
256
  };
214
257
  }
215
258
 
259
+ /**
260
+ * The write-time half of the reuse map gate (plan 20261122_1828_reuse_map P2b): the plan's
261
+ * map/none line is compared against a fresh `graphify` run, and every quoted citation against
262
+ * the cited file's actual line. Runs only at plan write (checkMainPlan and the delegated planner
263
+ * branch) — never on the parsePlan/queue-check/stop paths, and never inside planReadProblems
264
+ * (planReadNote runs that on every plan read, so a graphify call there would sit on the hot path).
265
+ * Every failure refuses with a one-line fix; a disabled feature never reaches the seam.
266
+ */
267
+ export function reuseMapWriteProblems(
268
+ text: string,
269
+ planPath: string,
270
+ cfg: Config,
271
+ graph: ReuseGraph = realGraphify,
272
+ budget: QueryBudget = queryBudget(),
273
+ ): string[] {
274
+ if (!cfg.reuse_map.enabled) return [];
275
+ const lines = (q.sections(text).get("reuse") ?? "").split("\n").map((l) => l.trim()).filter(Boolean);
276
+ const base = reuseMapBase(text, planPath, cfg, graph, lines, true);
277
+ if (base.problems.length) return base.problems;
278
+ return reuseMapLineProblems(lines, base.repo, cfg, graph, budget, "under ## Reuse", { planPath, text });
279
+ }
280
+
281
+ /**
282
+ * The spawn-time half (plan 20261122_1828_reuse_map P4b): a delegated planner's brief must carry
283
+ * its plan's map or none line, judged by the same re-run/compare as the write gate. It builds
284
+ * nothing (`build: false`): a stale or busy map is refused with the command that fixes it, so a
285
+ * spawn never waits on a 600 s graphify run. The brief carries no `new:` citations yet, so only
286
+ * the line itself is judged. Off: [].
287
+ */
288
+ export function reuseMapBriefProblems(
289
+ brief: string,
290
+ planPath: string,
291
+ cfg: Config,
292
+ graph: ReuseGraph = realGraphify,
293
+ budget: QueryBudget = queryBudget(),
294
+ ): string[] {
295
+ if (!cfg.reuse_map.enabled) return [];
296
+ const lines = brief.split("\n").map((l) => l.trim()).filter(Boolean);
297
+ const base = reuseMapBase(brief, planPath, cfg, graph, lines, false);
298
+ if (base.problems.length) return base.problems;
299
+ return reuseMapLineProblems(lines, base.repo, cfg, graph, budget, "in the brief");
300
+ }
301
+
302
+ /** The prelude both halves share: the plan's repo must be mapped, its terms well formed, graphify at the pin, and the graph fresh (`build` false: stale is refused, never rebuilt). */
303
+ function reuseMapBase(
304
+ text: string,
305
+ planPath: string,
306
+ cfg: Config,
307
+ graph: ReuseGraph,
308
+ lines: string[],
309
+ build: boolean,
310
+ ): { repo: string; problems: string[] } {
311
+ const roots = planRoots(planPath, text);
312
+ const repo = roots[roots.length - 1]!;
313
+ if (!cfg.reuse_map.repos.map((r) => path.resolve(q.expandHome(r))).includes(path.resolve(repo)))
314
+ return { repo, problems: [`reuse map: ${repo} is not mapped — run \`neurastream reuse on ${repo}\` first`] };
315
+ // A dashed term is refused before the seam runs: graphify would read it as an option.
316
+ const options = optionTermProblems(planTerms(lines));
317
+ if (options.length) return { repo, problems: options };
318
+ const vp = versionProblem(graph);
319
+ if (vp) return { repo, problems: [`reuse map: ${vp}`] };
320
+ return { repo, problems: freshGraph(repo, cfg.reuse_map.exclude, graph, { build }).map((p) => `reuse map: ${p}`) };
321
+ }
322
+
323
+ /** The map/none line half both checks share: the line is re-run against the fresh graph (a none line must not hit; a map line's files and cite: N must match). With `body`, the plan's own `new:` citations are judged too (each quoted, N matched files cited); the brief check passes none and stops at the line. */
324
+ function reuseMapLineProblems(
325
+ lines: string[],
326
+ repo: string,
327
+ cfg: Config,
328
+ graph: ReuseGraph,
329
+ budget: QueryBudget,
330
+ where: string,
331
+ body?: { planPath: string; text: string },
332
+ ): string[] {
333
+ const map = lines.map(parseMapLine).find((m) => m !== null) ?? null;
334
+ const none = lines.map(parseNoneLine).find((n) => n !== null) ?? null;
335
+ if (!map && !none) return [`reuse map: no map line ${where} — run \`neurastream reuse map <plan> "<term>"...\` and paste its - map: line`];
336
+ if (map && none) return [`reuse map: either a - map: line or a none-to-reuse line ${where}, not both`];
337
+ if (none) {
338
+ if (none.terms.length < NONE_TERMS_MIN)
339
+ return [`reuse map: the none line searches ${none.terms.length} terms (search at least ${NONE_TERMS_MIN} distinct terms)`];
340
+ if (none.terms.length > MAX_TERMS) return [`reuse map: ${none.terms.length} terms on the none line (at most ${MAX_TERMS})`];
341
+ const res = searchTerms(graph, repo, none.terms, undefined, budget);
342
+ if (res.some((r) => r.status === "slow")) return [SLOW_RETRY];
343
+ const bad = res.filter((r) => r.problem);
344
+ if (bad.length) return bad.map((r) => `reuse map: ${r.problem}`);
345
+ const hits = none.terms.map((t, i) => ({ term: t, r: res[i]! })).filter((x) => x.r.status === "hit");
346
+ const quote = body ? quoteProblems(lines, body.planPath, body.text, cfg) : null;
347
+ if (hits.length) {
348
+ const found = hits.map((x) => `"${x.term}" finds ${x.r.files.join(", ")}`).join("; ");
349
+ return [...(quote ? [quote] : []), `reuse map: not none to reuse — ${found}; cite it under ## Reuse instead`];
350
+ }
351
+ return quote ? [quote] : [];
352
+ }
353
+ // A map line: re-run its terms; the fresh files and cite: N must match what the line wrote.
354
+ // (Unreachable when map is null — both-null and none-only already returned — but it narrows.)
355
+ if (!map) return [];
356
+ if (map.terms.length > MAX_TERMS) return [`reuse map: ${map.terms.length} terms on the map line (at most ${MAX_TERMS})`];
357
+ const res = searchTerms(graph, repo, map.terms, undefined, budget);
358
+ if (res.some((r) => r.status === "slow")) return [SLOW_RETRY];
359
+ const bad = res.filter((r) => r.problem);
360
+ if (bad.length) return bad.map((r) => `reuse map: ${r.problem}`);
361
+ const files = [...new Set(res.flatMap((r) => r.files))];
362
+ const wantCite = Math.min(cfg.reuse_map.min_cited, files.length);
363
+ if (map.cite !== wantCite || [...map.files].map(normRel).toSorted().join("\n") !== [...files].map(normRel).toSorted().join("\n"))
364
+ return [`reuse map: the map moved — replace the map line ${where} with: ${mapLine(map.terms, files, cfg.reuse_map.min_cited)}`];
365
+ if (!body) return [];
366
+ const quote = quoteProblems(lines, body.planPath, body.text, cfg);
367
+ if (quote) return [quote];
368
+ const cited = new Set<string>();
369
+ const matched = new Set(files.map(normRel));
370
+ for (const line of lines) {
371
+ if (isMapOrNoneLine(line) || !line.includes("new:")) continue;
372
+ for (const c of citedQuotes(line)) if (matched.has(normRel(c.file))) cited.add(normRel(c.file));
373
+ }
374
+ if (cited.size < wantCite)
375
+ return [`reuse map: ${cited.size} of ${wantCite} matched files cited — cite ${wantCite} of ${files.join(", ")} with quoted lines`];
376
+ return [];
377
+ }
378
+
379
+ /** Every `new:` citation carries a quote equal to the cited file's line; the file is read only through readConfined. */
380
+ function quoteProblems(lines: string[], planPath: string, text: string, cfg: Config): string | null {
381
+ const scope = {
382
+ roots: citeRoots(path.dirname(planPath), cfg.reuse_map.repos.map((r) => q.expandHome(r))),
383
+ repo: planRoots(planPath, text).at(-1) ?? "",
384
+ };
385
+ for (const line of lines) {
386
+ if (isMapOrNoneLine(line) || !line.includes("new:")) continue;
387
+ if (hasBareChecked(line))
388
+ return `reuse map: citation without a quoted line ("checked: <path>:<n> \\"the file's text at that line\\""): ${line.slice(0, 80)}`;
389
+ for (const c of citedQuotes(line)) {
390
+ const problem = quoteMismatch(c, planPath, text, scope);
391
+ if (problem) return problem;
392
+ }
393
+ }
394
+ return null;
395
+ }
396
+
397
+ function quoteMismatch(c: CitedQuote, planPath: string, text: string, scope: { roots: string[]; repo: string }): string | null {
398
+ const abs = planFile(c.file, planPath, text);
399
+ if (!existsSync(abs)) return `reuse map: cited file ${c.file} does not exist — rerun \`neurastream reuse map\` and re-cite`;
400
+ const body = readConfined(abs, scope.roots);
401
+ if (body === null) return `reuse map: cited file ${c.file} is outside ${scope.repo} or not committed — cite a committed path inside the plan's repo`;
402
+ const actual = (body.split("\n")[c.n - 1] ?? "").trim();
403
+ if (!actual) return `reuse map: ${c.file} has no line ${c.n} — rerun \`neurastream reuse map\` and re-cite`;
404
+ if (actual !== c.quote) return `reuse map: ${c.file}:${c.n} is not "${c.quote.slice(0, 60)}" — quote that line exactly as the file has it`;
405
+ return null;
406
+ }
407
+
216
408
  const READ_SECTION = /^## Code read by Main[^\n]*\n([\s\S]*?)(?=^## |(?![\s\S]))/m;
217
409
  const LISTED_PATH = /`([^`\s]+)`/g;
218
410
  const CITED_PATH = /((?:~\/|\/|\.{1,2}\/)?[\w@.-]+(?:\/[\w@.-]+)*\.[A-Za-z0-9]+):\d+/g;
@@ -242,7 +434,7 @@ function planReadProblems(text: string, planPath: string, cfg: Config): string[]
242
434
  }
243
435
 
244
436
  /** A plan-cited path: absolute, else under the plan's Worktree (when set) or its repo root. */
245
- function planFile(p: string, planPath: string, text: string): string {
437
+ export function planFile(p: string, planPath: string, text: string): string {
246
438
  const home = q.expandHome(p);
247
439
  if (path.isAbsolute(home)) return home;
248
440
  const roots = planRoots(planPath, text);
@@ -250,8 +442,8 @@ function planFile(p: string, planPath: string, text: string): string {
250
442
  return path.join(root, home);
251
443
  }
252
444
 
253
- /** 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>). */
254
- function planRoots(planPath: string, text: string): string[] {
445
+ /** 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>). Exported for `neurastream reuse map`, which resolves the plan's repo exactly like the write gate. */
446
+ export function planRoots(planPath: string, text: string): string[] {
255
447
  const wt = /^Worktree:\s*(\S+)/m.exec(text)?.[1];
256
448
  const cut = planPath.indexOf("/docs/plans/");
257
449
  const repo = cut >= 0 ? planPath.slice(0, cut) : path.dirname(path.dirname(path.dirname(planPath)));
@@ -14,8 +14,10 @@ import { approvalProblem } from "../plan-approval.ts";
14
14
  import { outUntil, pinModel, providerOfModel, readOut } from "../provider-state.ts";
15
15
  import * as q from "../queue/lib.ts";
16
16
  import type { Plan } from "../queue/lib.ts";
17
+ import { realGraphify, type ReuseGraph } from "../reuse-map.ts";
17
18
  import { claimStoreFor, pathId, routeTeam, teamDir, type TeamEntry } from "../team-client.ts";
18
19
  import { plannerPlanProblem, plannerRolePlan, recordPlannerSpawn } from "./planner.ts";
20
+ import { reuseMapBriefProblems } from "./plan-edit.ts";
19
21
  import { isReviewSpawn, pendingWorkProblem, readMrCache, recordReviewSpawn, reviewPassProblem, reviewRole } from "./review.ts";
20
22
  import {
21
23
  ALLOW,
@@ -439,6 +441,7 @@ export function spawnProblem(
439
441
  runningJobs?: string[],
440
442
  runner: CommandRunner = defaultRunner,
441
443
  spawner: Spawner = "main",
444
+ graph: ReuseGraph = realGraphify,
442
445
  ): string | null {
443
446
  const roles: Record<string, string | null> = {};
444
447
  const plannerRoles: Record<string, string> = {};
@@ -477,6 +480,9 @@ export function spawnProblem(
477
480
  problems.push(`${label}: agent "${agent}" is not in "## Allowed" of ${cfg.paths.subagents} (no expensive or unpinned models).`);
478
481
  continue;
479
482
  }
483
+ // Reuse map (plan 20261122_1828_reuse_map P4b): the brief carries its plan's map or none
484
+ // line — the write gate's re-run/compare judges it before the planner ever runs.
485
+ for (const p of reuseMapBriefProblems(text, plannerFor, cfg, graph)) problems.push(`${label}: ${p}`);
480
486
  plannerRoles[label] = plannerFor;
481
487
  continue;
482
488
  }
@@ -631,11 +637,11 @@ export function bypassLaunch(command: string, cfg: Config, spawner: Spawner, run
631
637
  * spawn: the allow-list, task-only and open-plan gates for one implementer launch. Covers both
632
638
  * original paths (the extension spawn event and a `task` tool call); the brief names the plan.
633
639
  */
634
- export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = defaultRunner, runs?: RunSource): Decision {
635
- return tuned(checkSpawnRules(e, cfg, runner, runs), cfg);
640
+ export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = defaultRunner, runs?: RunSource, graph: ReuseGraph = realGraphify): Decision {
641
+ return tuned(checkSpawnRules(e, cfg, runner, runs, graph), cfg);
636
642
  }
637
643
 
638
- function checkSpawnRules(e: SpawnEvent, cfg: Config, runner: CommandRunner = defaultRunner, runs?: RunSource): Decision {
644
+ function checkSpawnRules(e: SpawnEvent, cfg: Config, runner: CommandRunner = defaultRunner, runs?: RunSource, graph: ReuseGraph = realGraphify): Decision {
639
645
  const pending = q.cancelPending(cfg.paths);
640
646
  if (pending) {
641
647
  log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: cancel pending (${pending.words}) rule=spawn.cancel-pending`);
@@ -659,6 +665,10 @@ function checkSpawnRules(e: SpawnEvent, cfg: Config, runner: CommandRunner = def
659
665
  problems.push(`${e.agent}: planner mode is main — a Planner-role spawn needs the owner's \`planner delegated\` switch.`);
660
666
  else if (delegatedPlanner && plannerPlanProblem(plannerFor)) problems.push(`${e.agent}: ${plannerPlanProblem(plannerFor)}`);
661
667
  else if (delegatedPlanner && !e.name) problems.push(`${e.agent}: a planner spawn needs a name (the task name keys its planner role).`);
668
+ // Reuse map (plan 20261122_1828_reuse_map P4b): a delegated planner's brief carries its plan's
669
+ // map or none line; judged here, not in the else-if chain, so an earlier refusal never hides it.
670
+ if (delegatedPlanner && plannerFor)
671
+ for (const p of reuseMapBriefProblems(e.brief, plannerFor, cfg, graph)) problems.push(`${e.agent}: ${p}`);
662
672
  const [why, named] = delegatedPlanner ? [null, [] as string[]] : planGate(e.brief, e.agent, cfg);
663
673
  if (why) problems.push(why);
664
674
  const gate = priorityGate(named, e.runningJobs, e.brief, cfg, e.agent, e.agent, "main");
@@ -66,6 +66,11 @@ export interface EditWindow {
66
66
  mainCallsStart?: number;
67
67
  }
68
68
 
69
+ /** When the edit window's `used` list clears (ms since epoch): main_window_min after windowStart. */
70
+ export function editWindowEndMs(w: EditWindow, cfg: Config): number {
71
+ return w.windowStart + cfg.guards.main_window_min * 60_000;
72
+ }
73
+
69
74
  // --- this Main's identity (plan 20261027_1300_multi_main P2) ---
70
75
 
71
76
  /** What `neurastream main --name` accepts and what `NEURASTREAM_MAIN_ID` may hold. */
@@ -157,6 +162,22 @@ export function mainCallsExpired(w: EditWindow): boolean {
157
162
  return w.mainCalls > 0 && nowSec() - (w.mainCallsStart ?? 0) >= MAIN_CALLS_RESET_SEC;
158
163
  }
159
164
 
165
+ /** The edit cap per window for a tier: Infinity in tier full (no cap). */
166
+ export function mainEditLimit(cfg: Config, tier: string): number {
167
+ if (tier === "full") return Infinity;
168
+ return tier === "strict" ? cfg.autonomy.strict_edit_limit : cfg.guards.main_edit_limit;
169
+ }
170
+
171
+ /** The per-turn call cap is on: main_max_calls set and not tier full (exempt tools are the caller's check). */
172
+ export function mainCallsCapOn(cfg: Config, tier: string): boolean {
173
+ return cfg.guards.main_max_calls > 0 && tier !== "full";
174
+ }
175
+
176
+ /** When the counted calls expire, in ms since epoch (the wake arms on this clock); null when none are counted. */
177
+ export function mainCallsResetMs(w: EditWindow): number | null {
178
+ return w.mainCalls > 0 ? ((w.mainCallsStart ?? 0) + MAIN_CALLS_RESET_SEC) * 1000 : null;
179
+ }
180
+
160
181
  /** Main's terminal hand-back (the adapter's agent_end without willContinue): the turn is over, so
161
182
  * the next one starts at 0 calls. The edit window keeps its own reset rules. */
162
183
  export function resetMainCalls(paths: Pick<q.QueuePaths, "queue_state">): void {
@@ -1,5 +1,6 @@
1
1
  // Prompt injection, cancel-word flagging, and keep-working stop rules.
2
2
 
3
+ import path from "node:path";
3
4
  import type { Decision, InjectEvent, StopEvent } from "../adapter.ts";
4
5
  import { currentTier } from "../autonomy.ts";
5
6
  import type { Config } from "../config.ts";
@@ -12,6 +13,7 @@ import {
12
13
  incidentLine,
13
14
  isOwnerProse,
14
15
  log,
16
+ mainCallsCapOn,
15
17
  mainCallsExpired,
16
18
  openIncidentList,
17
19
  readStaffing,
@@ -42,6 +44,15 @@ export function flagCancel(text: string, cfg: Config): string {
42
44
  return `\nmain-guard: ${CANCEL_TODO} Flagged: "${words}"`;
43
45
  }
44
46
 
47
+ /** The owner prompt's Tools-and-limits card: the call cap and the open plans' deny-command blockers, three lines at most. */
48
+ function toolsCard(cfg: Config, tier: string, plans: q.Plan[]): string[] {
49
+ const calls = mainCallsCapOn(cfg, tier) ? `Calls: ${cfg.guards.main_max_calls} per turn (warn at ${cfg.guards.main_warn_calls})` : "Calls: off";
50
+ const denies = plans.flatMap(p => p.blockers.filter(b => path.basename(b.script) === "deny-command").map(b => `${path.basename(p.file)}: ${b.args.join(" ")}`));
51
+ if (!denies.length) return ["Tools and limits", calls];
52
+ const more = denies.length > 3 ? ` | +${denies.length - 3} more` : "";
53
+ return ["Tools and limits", calls, `Deny-commands (open plans): ${denies.slice(0, 3).join(" | ")}${more}`];
54
+ }
55
+
45
56
  /**
46
57
  * prompt/owner message: inject the queue summary, flag cancel wording, list open incidents, reset
47
58
  * Main's edit window and the stop counters (the original resets them at every user message). A
@@ -57,6 +68,7 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
57
68
  if (!continuation) writeWindow({ used: [], windowStart: 0, mainCalls: 0 }, cfg.paths);
58
69
  recordOwnerMessage(e.inject, cfg);
59
70
  let summary: string;
71
+ let open: q.Plan[] = [];
60
72
  try {
61
73
  // P4 (20261027_1305): one GET /view per team, read once and handed to the holder and the
62
74
  // team lines, so the summary costs one request per team and never a second GET /claims.
@@ -64,6 +76,7 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
64
76
  summary = q.queueSummary(cfg.paths, cfg.review.agents, summaryHolder(cfg, {}, views));
65
77
  const teamLines = teamSummaryLines(cfg, views, q.SUMMARY_CAP);
66
78
  if (teamLines.length) summary += `\n${teamLines.join("\n")}`;
79
+ open = q.activePlans(cfg.paths).filter(p => !p.waiting && !q.awaitingMerge(p, cfg.paths));
67
80
  } catch (err) {
68
81
  summary = `Queue unreadable (${cfg.paths.queue_index}): ${err}`;
69
82
  }
@@ -85,10 +98,11 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
85
98
  const unlockNote = continuation ? "" : unlockLine(cfg);
86
99
  const mayNote = ` Main may edit Status/WAITING/Waits on/False positive lines. Test before saying "cannot".`;
87
100
  const editLimit = continuation ? "" : `\nautonomy: ${tier} — ${tierNote}${mayNote}${unlockNote}`;
101
+ const card = continuation ? "" : `\n${toolsCard(cfg, tier, open).join("\n")}`;
88
102
  return {
89
103
  allow: true,
90
104
  reason: "",
91
- 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}`,
105
+ 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}${card}${cancel}${incidentText}`,
92
106
  ...(continuation ? {} : { state: { callsSinceStop: 0, idleStops: 0 } }),
93
107
  };
94
108
  }
@@ -18,10 +18,13 @@ import {
18
18
  bypassRegExp,
19
19
  changedProjectFiles,
20
20
  deny,
21
+ editWindowEndMs,
21
22
  log,
22
23
  MAIN_CALLS_RESET_SEC,
23
24
  MAIN_PLAN_FILE,
25
+ mainCallsCapOn,
24
26
  mainCallsExpired,
27
+ mainEditLimit,
25
28
  mainStateDir,
26
29
  readStaffing,
27
30
  readWindow,
@@ -320,13 +323,13 @@ function editWindow(e: ToolEvent, input: Record<string, unknown>, cfg: Config):
320
323
  if (!files.length) return ALLOW;
321
324
  const tier = currentTier(cfg);
322
325
  if (tier === "full") return ALLOW; // no cap: Main works unattended
323
- const limit = tier === "strict" ? cfg.autonomy.strict_edit_limit : cfg.guards.main_edit_limit;
326
+ const limit = mainEditLimit(cfg, tier);
324
327
  const limitName = tier === "strict" ? "autonomy.strict_edit_limit" : "owner limit";
325
328
  const now = Date.now();
326
329
  return updateWindow(cfg.paths, (w) => {
327
- if (w.used.length && now - w.windowStart >= cfg.guards.main_window_min * 60_000) w.used = [];
330
+ if (w.used.length && now >= editWindowEndMs(w, cfg)) w.used = [];
328
331
  if (w.used.length >= limit) {
329
- const mins = Math.ceil((w.windowStart + cfg.guards.main_window_min * 60_000 - now) / 60_000);
332
+ const mins = Math.ceil((editWindowEndMs(w, cfg) - now) / 60_000);
330
333
  log(cfg.paths.guard_log, `BLOCK tool=${e.tool} after ${w.used.length} edits (tier ${tier}): ${files.join(",")} rule=main.edit-window`);
331
334
  return {
332
335
  write: false,
@@ -385,7 +388,7 @@ function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config, run
385
388
 
386
389
  /** The per-turn call cap applies to this call: on, not tier full, and the tool is not exempt. */
387
390
  function mainCallApplies(e: ToolEvent, cfg: Config): boolean {
388
- return cfg.guards.main_max_calls > 0 && currentTier(cfg) !== "full" && !cfg.guards.main_call_exempt_tools.includes(e.tool);
391
+ return mainCallsCapOn(cfg, currentTier(cfg)) && !cfg.guards.main_call_exempt_tools.includes(e.tool);
389
392
  }
390
393
 
391
394
  /** Refusal once this turn has spent main_max_calls, or null. */
@@ -9,6 +9,7 @@ import type { Config } from "../config.ts";
9
9
  import type { ClaimStore } from "../claims.ts";
10
10
  import { strftime } from "../clock.ts";
11
11
  import { withFileLock, writeAtomicSync } from "../file-lock.ts";
12
+ import { MAX_TERMS, NONE_TERMS_MIN, citedQuotes, hasBareChecked, isMapOrNoneLine, normRel, parseMapLine, parseNoneLine, type ParsedMapLine, type ParsedNoneLine } from "../reuse-map.ts";
12
13
 
13
14
  // --- landing detection (plan 20261031_0911 P4/P5): lives here, not queue-close.ts, because
14
15
  // queueProblems' landed lock needs it and lib must not import the closer that imports lib ---
@@ -403,18 +404,64 @@ export function headerField(text: string, name: string): string | null {
403
404
  * P1 (plan 20261028_1600): every new thing a plan adds carries a reuse line with a checked
404
405
  * `path:line` citation that exists relative to the plan's repo. Applies to every plan (P5
405
406
  * removed the cutover); an empty `review.agents` list turns the gate off (P5c).
407
+ *
408
+ * P2 (plan 20261122_1828_reuse_map): text only. When a map or none line is present the section
409
+ * follows the map rule instead: those lines skip the plain `checked:` rule, every `new:` citation
410
+ * carries a quoted line, the map's matched files are cited on >= N distinct lines, a none line
411
+ * searches >= 3 and at most MAX_TERMS distinct terms. Quote equality and the graphify re-run live
412
+ * in plan-edit's reuseMapWriteProblems — this function stays on the hot path, so it never reads
413
+ * a graph or runs graphify.
406
414
  */
407
415
  function reuseProblems(repo: string, file: string, secs: Map<string, string>, reviewAgents: string[]): string[] {
408
416
  if (!reviewAgents.length) return [];
409
417
  const lines = items(secs.get("reuse") ?? "");
410
418
  if (!lines.length)
411
419
  return [`missing or empty "## Reuse" section (one line per new thing: - new: <thing> — checked: <path>:<line> — reuse: <how, or why not>; "- new: none — ..." when nothing is new)`];
420
+ const map = lines.map(parseMapLine).find((m) => m !== null) ?? null;
421
+ const none = lines.map(parseNoneLine).find((n) => n !== null) ?? null;
422
+ if (!map && !none) {
423
+ const probs: string[] = [];
424
+ for (const line of lines) {
425
+ const m = /checked:\s*`?([^`\s—]+):(\d+)(?:-\d+)?`?/.exec(line);
426
+ if (!m) probs.push(`reuse line without "checked: <path>:<line>": ${line.slice(0, 80)}`);
427
+ else if (!existsSync(path.resolve(repo, m[1]!))) probs.push(`reuse citation does not exist: ${m[1]}`);
428
+ }
429
+ return probs;
430
+ }
431
+ return mapGateProblems(repo, lines, map, none);
432
+ }
433
+
434
+ /** Text half of the map gate (plan 20261122_1828_reuse_map P2a): shapes only, never a graphify run. */
435
+ function mapGateProblems(repo: string, lines: string[], map: ParsedMapLine | null, none: ParsedNoneLine | null): string[] {
412
436
  const probs: string[] = [];
437
+ if (map && none) probs.push("either a - map: line or a none-to-reuse line under ## Reuse, not both");
413
438
  for (const line of lines) {
414
- const m = /checked:\s*`?([^`\s—]+):(\d+)(?:-\d+)?`?/.exec(line);
415
- if (!m) probs.push(`reuse line without "checked: <path>:<line>": ${line.slice(0, 80)}`);
416
- else if (!existsSync(path.resolve(repo, m[1]!))) probs.push(`reuse citation does not exist: ${m[1]}`);
439
+ if (isMapOrNoneLine(line) || !/map:|none to reuse/.test(line)) continue;
440
+ probs.push(`a "- map:" or "none to reuse" line that does not parse — rerun \`neurastream reuse map\`: ${line.slice(0, 80)}`);
441
+ }
442
+ if (map && map.terms.length > MAX_TERMS)
443
+ probs.push(`${map.terms.length} terms on the map line (at most ${MAX_TERMS} — each term is one graphify query)`);
444
+ if (none) {
445
+ if (none.terms.length < NONE_TERMS_MIN)
446
+ probs.push(`the none line searches ${none.terms.length} terms (search at least ${NONE_TERMS_MIN} distinct terms: - new: none to reuse — searched: "t1", "t2", "t3")`);
447
+ if (none.terms.length > MAX_TERMS)
448
+ probs.push(`${none.terms.length} terms on the none line (at most ${MAX_TERMS} — each term is one graphify query)`);
417
449
  }
450
+ const matched = map ? new Set(map.files.map(normRel)) : null;
451
+ const cited = new Set<string>();
452
+ for (const line of lines) {
453
+ if (isMapOrNoneLine(line) || !line.includes("new:")) continue;
454
+ if (hasBareChecked(line)) {
455
+ probs.push(`reuse citation without a quoted line ("checked: <path>:<n> \\"the file's text at that line\\""): ${line.slice(0, 80)}`);
456
+ continue;
457
+ }
458
+ for (const c of citedQuotes(line)) {
459
+ if (!existsSync(path.resolve(repo, c.file))) probs.push(`reuse citation does not exist: ${c.file}`);
460
+ if (matched) cited.add(normRel(c.file));
461
+ }
462
+ }
463
+ if (matched && cited.size < map!.cite)
464
+ probs.push(`${cited.size} of the map's ${map!.cite} matched files cited — cite ${map!.cite} of ${[...matched].join(", ")} as "checked: <path>:<n> \\"the file's text at that line\\""`);
418
465
  return probs;
419
466
  }
420
467
 
@@ -939,9 +986,16 @@ export function chatUnlock(text: string, cfg: Config, source: string, word: "cha
939
986
  return { applied: true, command: "unlock", minutes: n, until: Math.floor(past + minutes * 60) };
940
987
  }
941
988
 
989
+ // P2b (plan 20261122_1828_reuse_map): the reuse map's own directory and the worktree registry are
990
+ // protected in any repo, the directory itself included (`rm -rf graphify-out`, `ln -s … graphify-out`).
991
+ const PROTECTED_SEGMENTS = [/(^|\/)graphify-out(\/|$)/, /(^|\/)\.git\/worktrees(\/|$)/];
992
+
942
993
  export function protectedHit(targetPaths: string[], paths: QueuePaths): string | null {
943
994
  const guarded = protectedPaths(paths);
944
- for (const p of targetPaths) for (const g of guarded) if (g.endsWith("/") ? p.startsWith(g) || `${p}/` === g : p === g) return p;
995
+ for (const p of targetPaths) {
996
+ if (PROTECTED_SEGMENTS.some((re) => re.test(p))) return p;
997
+ for (const g of guarded) if (g.endsWith("/") ? p.startsWith(g) || `${p}/` === g : p === g) return p;
998
+ }
945
999
  return null;
946
1000
  }
947
1001