neurastream 0.3.21 → 0.3.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -99,6 +99,7 @@ Put your own Main-only instructions in `MAIN.md` inside `paths.agent_dir` (defau
99
99
  | **WIP safety net** (`neurastream wip`) | Hourly hidden-ref git snapshots (`refs/wip/...`) and nightly push to a verified-private backup repo. | [docs/operations.md](docs/operations.md#saving-unsaved-work-wip) |
100
100
  | **Trace forensics, metrics & self-pruning** (`traces`, `labels`, `metrics`, `incident`, `rules`) | Audits unbacked claims, suspicious actions, provider honesty, prompt bloat, and wasted calls; tracks weekly `M1`–`M5` metrics, opens incidents, and tunes noisy rules down automatically. | [docs/traces-and-metrics.md](docs/traces-and-metrics.md) |
101
101
  | **Conversation recall** (`neurastream recall`) | Append-only redacted log of owner messages and Main answers with word search and optional LLM topic segmentation. | [docs/operations.md](docs/operations.md#recall) |
102
+ | **Reuse map** (`neurastream reuse on`, `map`, `off`, `status`) | Opt-in per-repo graphify map that the plan write gate reads, so a `## Reuse` section cites existing code or a none-to-reuse search before a plan is written. Off by default. | [docs/guards.md](docs/guards.md#review-read-and-brief-gates) |
102
103
 
103
104
  ## CLI & compatibility bins
104
105
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.3.21",
3
+ "version": "0.3.22",
4
4
  "description": "Guardrails for running many AI coding agents at once: plan queue, blockers, call budgets, provider caps, scoring, merge-verified close.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -13,6 +13,7 @@ import { stripBlock } from "../../core/agents-md.ts";
13
13
  import { loadConfig } from "../../core/config.ts";
14
14
  import { notifyFindings } from "../../core/notify.ts";
15
15
  import { loadKnownSecrets, proxyOnPath } from "../../core/secret-redact.ts";
16
+ import { reuseMapDoctor } from "../../core/reuse-map.ts";
16
17
  import { allowedAgents, readIndex, reviewAgentsProblem } from "../../core/queue/lib.ts";
17
18
  import { systemRunner, type Runner } from "../../core/pages-setup.ts";
18
19
  import { packageJsonPath } from "./package-root.ts";
@@ -243,6 +244,11 @@ export function doctorReport(home: string, env: NodeJS.ProcessEnv = process.env,
243
244
  if (!cfg.workspace.owner_login) problems.push("workspace.enabled but workspace.owner_login is empty");
244
245
  else if (state === "running") ok.push(`workspace owner page: login ${cfg.workspace.owner_login}`);
245
246
  }
247
+ // Reuse map (plan 20261122_1828_reuse_map P3): the map's health beside tailscale's; off is one
248
+ // ok line and never runs graphify, a version other than the pin is a problem.
249
+ const reuse = reuseMapDoctor(cfg);
250
+ ok.push(...reuse.ok);
251
+ problems.push(...reuse.problems);
246
252
  // Teams (plan 20261027_1305 P6): each teams: entry must answer its view for this login. A team that
247
253
  // is down, or refuses this login (not a member), is a problem; a reachable one shows the claims held here.
248
254
  for (const [teamName, view] of teamViews(cfg)) {
@@ -29,6 +29,7 @@ import { runNotes } from "./notes.ts";
29
29
  import { runPages } from "./pages.ts";
30
30
  import { watchOn, watchOff } from "./watch-setup.ts";
31
31
  import { runWip } from "./wip.ts";
32
+ import { runReuse } from "./reuse.ts";
32
33
  import { runUninstall } from "../core/uninstall.ts";
33
34
  import { queueMigrate } from "../core/queue-migrate.ts";
34
35
  import { activePlans, allowedAgents, enforceReadOnlyIndex, gitTop, parseIndex, updateIndex } from "../core/queue/lib.ts";
@@ -103,6 +104,11 @@ export function helpText(): string {
103
104
  " neurastream wip add|remove|list [path] add or remove a root in wip.roots, or list them",
104
105
  " neurastream wip on [--backup-url <url>]|off hourly snapshot (+ nightly private backup) on or off",
105
106
  " neurastream wip restore [<worktree>] [--pick N] list the hidden saves, or put one back",
107
+ " neurastream reuse on [<repo>...]|off [--purge]|status [--json]|map <plan.md> <term>...",
108
+ " opt-in Graphify code map: `on` installs graphifyy (uv or pipx) and",
109
+ " builds a code map per chosen repo (asks y/N per repo on a terminal);",
110
+ " from then on new plans in mapped repos must cite the map under ## Reuse;",
111
+ " `off --purge` also deletes graphify-out/ and uninstalls graphifyy",
106
112
  " neurastream guard <event> --json",
107
113
  ` (${GUARD_USAGE.slice(GUARD_USAGE.indexOf("(") + 1, -1)})`,
108
114
  " neurastream main [args] run omp under the launcher (automatic session rollover)",
@@ -192,6 +198,7 @@ export async function run(cmd: string, args: string[]): Promise<number> {
192
198
  if (cmd === "setup") return runSetup(args, realSetupDeps(async () => runNotify(["test"])));
193
199
  if (cmd === "config" && ["set", "get", "list"].includes(args[0] ?? "")) return runConfigKeys(args);
194
200
  if (cmd === "wip") return runWip(args);
201
+ if (cmd === "reuse") return runReuse(args);
195
202
  if (cmd === "config") {
196
203
  try {
197
204
  const cfg = loadConfig();
@@ -0,0 +1,109 @@
1
+ // `neurastream reuse` (plan 20261122_1828_reuse_map P3): the opt-in Graphify code map CLI.
2
+ // The routines live in src/core/reuse-map.ts (uninstall runs the off routine too); this file
3
+ // speaks to the user: args, the real deps (HOME, env, terminal), exit codes, streams.
4
+
5
+ import { existsSync, readFileSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import path from "node:path";
8
+ import { loadConfig } from "../core/config.ts";
9
+ import { MAX_TERMS, NONE_TERMS_MIN, SLOW_RETRY, freshGraph, mapLine, noneLine, optionTermProblems, realGraphify, reuseOff, reuseOn, reuseStatus, searchTerms, versionProblem, type ReuseDeps, type ReuseOutcome } from "../core/reuse-map.ts";
10
+ import { planRoots } from "../core/guards/plan-edit.ts";
11
+ import { expandHome } from "../core/queue/lib.ts";
12
+ import { askLine } from "./init.ts";
13
+
14
+ const USAGE = "usage: neurastream reuse on [<repo>...] | off [--purge] | status [--json] | map <plan.md> <term>...";
15
+
16
+ /** The production deps: the real home, env, terminal, askLine. */
17
+ function realDeps(): ReuseDeps {
18
+ return {
19
+ home: homedir(),
20
+ env: process.env,
21
+ terminal: process.stdin.isTTY === true && process.stdout.isTTY === true,
22
+ ask: askLine,
23
+ };
24
+ }
25
+
26
+ function emit(r: ReuseOutcome): number {
27
+ for (const l of r.out) console.log(l);
28
+ for (const l of r.err) console.error(l);
29
+ return r.code;
30
+ }
31
+
32
+ /**
33
+ * `reuse map <plan.md> <term>...`: freshens the plan repo's map, then prints the ## Reuse line —
34
+ * the - map: line when any term hits, else the none line (which needs >= NONE_TERMS_MIN terms) —
35
+ * plus up to 5 `path:line "text"` candidates per matched file for the `new:` citations. The
36
+ * plan's repo is resolved exactly like the write gate resolves it (planRoots' last root). The
37
+ * command writes nothing but the map's own graph and stamp.
38
+ */
39
+ function runMap(plan: string, terms: string[], deps: ReuseDeps): ReuseOutcome {
40
+ const out: string[] = [];
41
+ const err: string[] = [];
42
+ if (!plan || !terms.length) return { code: 2, out, err: ['usage: neurastream reuse map <plan.md> "<term>"...'] };
43
+ if (terms.length > MAX_TERMS) return { code: 1, out, err: [`reuse map: ${terms.length} terms (at most ${MAX_TERMS} — each term is one graphify query)`] };
44
+ const options = optionTermProblems(terms);
45
+ if (options.length) return { code: 1, out, err: options };
46
+ const planPath = path.resolve(plan);
47
+ const repo = planRoots(planPath, existsSync(planPath) ? readFileSync(planPath, "utf8") : "").at(-1)!;
48
+ const cfg = loadConfig({ home: deps.home, env: deps.env }).reuse_map;
49
+ if (!cfg.enabled) return { code: 1, out, err: [`reuse map: the reuse map is off — run \`neurastream reuse on ${repo}\` first`] };
50
+ if (!cfg.repos.map((r) => path.resolve(expandHome(r))).includes(repo))
51
+ return { code: 1, out, err: [`reuse map: ${repo} is not mapped — run \`neurastream reuse on ${repo}\` first`] };
52
+ const vp = versionProblem();
53
+ if (vp) return { code: 1, out, err: [`reuse map: ${vp}`] };
54
+ const fresh = freshGraph(repo, cfg.exclude);
55
+ if (fresh.length) return { code: 1, out, err: fresh.map((p) => `reuse map: ${p}`) };
56
+ const res = searchTerms(realGraphify, repo, terms);
57
+ if (res.some((r) => r.status === "slow")) return { code: 1, out, err: [SLOW_RETRY] };
58
+ const bad = res.filter((r) => r.problem);
59
+ if (bad.length) return { code: 1, out, err: bad.map((r) => `reuse map: ${r.problem}`) };
60
+ const files = [...new Set(res.flatMap((r) => r.files))];
61
+ if (!files.length) {
62
+ if (terms.length < NONE_TERMS_MIN)
63
+ return { code: 1, out, err: [`reuse map: nothing matched — a none line needs ${NONE_TERMS_MIN} distinct terms, search more and rerun`] };
64
+ out.push(noneLine(terms));
65
+ return { code: 0, out, err };
66
+ }
67
+ out.push(mapLine(terms, files, cfg.min_cited));
68
+ for (const file of files) {
69
+ let text: string;
70
+ try {
71
+ text = readFileSync(path.join(repo, file), "utf8");
72
+ } catch {
73
+ out.push(`${file}: unreadable`);
74
+ continue;
75
+ }
76
+ let shown = 0;
77
+ const lower = terms.map((t) => t.toLowerCase());
78
+ for (const [i, line] of text.split("\n").entries()) {
79
+ if (!lower.some((t) => line.toLowerCase().includes(t))) continue;
80
+ out.push(`${file}:${i + 1} "${line.trim()}"`);
81
+ if (++shown >= 5) break;
82
+ }
83
+ if (!shown) out.push(`${file}: no line names the terms (cite its defining line anyway)`);
84
+ }
85
+ return { code: 0, out, err };
86
+ }
87
+
88
+ /** `neurastream reuse <sub> ...` — exits: 0 ok, 1 failure, 2 usage. */
89
+ export function runReuse(args: string[]): number {
90
+ const [sub, ...rest] = args;
91
+ try {
92
+ switch (sub) {
93
+ case "on":
94
+ return emit(reuseOn(rest, realDeps()));
95
+ case "off":
96
+ return emit(reuseOff(rest, realDeps()));
97
+ case "status":
98
+ return emit(reuseStatus(rest, realDeps()));
99
+ case "map":
100
+ return emit(runMap(rest[0] ?? "", rest.slice(1), realDeps()));
101
+ default:
102
+ console.error(USAGE);
103
+ return 2;
104
+ }
105
+ } catch (e) {
106
+ console.error(e instanceof Error ? e.message : String(e));
107
+ return 1;
108
+ }
109
+ }
package/src/cli/setup.ts CHANGED
@@ -12,6 +12,7 @@ import { isPlannerModeKey, stampPlannerMode, verifyPlannerMode } from "../core/a
12
12
  import { TEMPLATE_PATH, configFile } from "../core/config.ts";
13
13
  import { checkEdited, leafKeys, setConfigKeys, valueAt, yamlValue } from "../core/config-edit.ts";
14
14
  import { pagesDoctor } from "../core/pages-doctor.ts";
15
+ import { reuseOn, type ReuseOutcome } from "../core/reuse-map.ts";
15
16
  import { detect, realSeams, type SetupFacts, type SetupSeams } from "../core/setup-detect.ts";
16
17
  import { invalidSlugs } from "../core/subagents.ts";
17
18
  import { TAILSCALE_MISSING, TAILSCALE_STOPPED } from "../core/ui-setup.ts";
@@ -45,6 +46,9 @@ export interface SetupDeps {
45
46
  say: (line: string) => void;
46
47
  // `neurastream notify test`, injected by dispatch (setup.ts does not import dispatch.ts).
47
48
  notifyTest: () => Promise<number>;
49
+ // The P3 on-routine (`reuse on` with no args: install, per-repo y/N, build, config last),
50
+ // injected so tests never install or build anything (plan 20261122_1828_reuse_map P4a).
51
+ reuseOn: () => ReuseOutcome;
48
52
  }
49
53
 
50
54
  /** The production deps: the real home, terminal, PATH, Tailscale, adapter install and doctor. */
@@ -64,6 +68,7 @@ export function realSetupDeps(notifyTest: () => Promise<number>): SetupDeps {
64
68
  },
65
69
  say: (line) => console.log(line),
66
70
  notifyTest,
71
+ reuseOn: () => reuseOn([], { home, env: process.env, terminal: process.stdin.isTTY === true, ask: askLine }),
67
72
  };
68
73
  }
69
74
 
@@ -149,11 +154,13 @@ export async function runSetup(args: string[], deps: SetupDeps): Promise<number>
149
154
  if (runGroup(ctx, group.name, group.keys) !== 0) return 1;
150
155
  }
151
156
  if (ctx.auto === "none") {
152
- const advanced = VALID_KEYS.filter((k) => !GROUPS.some((g) => g.keys.includes(k)));
157
+ // reuse_map.* is never asked here: `reuse on`/`reuse off` write it (plan 20261122_1828_reuse_map P4a).
158
+ const advanced = VALID_KEYS.filter((k) => !GROUPS.some((g) => g.keys.includes(k)) && !k.startsWith("reuse_map."));
153
159
  const open = deps.ask(`Show the ${advanced.length} advanced settings? [y/N]: `).trim();
154
160
  if (/^y(es)?$/i.test(open) && runGroup(ctx, "Advanced", advanced) !== 0) return 1;
155
161
  }
156
162
  if (ctx.testOffer) await offerTest(ctx);
163
+ offerReuse(ctx, yes);
157
164
  const installed = deps.install();
158
165
  if (installed !== 0) {
159
166
  deps.say("adapter install failed");
@@ -238,6 +245,23 @@ async function offerTest(ctx: Ctx): Promise<void> {
238
245
  if (/^y(es)?$/i.test(answer)) await ctx.deps.notifyTest();
239
246
  }
240
247
 
248
+ // The reuse-map offer (plan 20261122_1828_reuse_map P4a), after the notify test offer: asked only
249
+ // at a terminal (never --yes) and only while the feature is off — `reuse on`/`reuse off` own the
250
+ // keys. A yes runs the P3 on-routine through the injected seam, which asks y/N per candidate repo
251
+ // itself; a failure prints and setup continues with the feature off (the doctor reports it).
252
+ function offerReuse(ctx: Ctx, yes: boolean): void {
253
+ if (yes) return;
254
+ const now = Bun.YAML.parse(ctx.text) as { reuse_map?: { enabled?: boolean } } | null;
255
+ if (now?.reuse_map?.enabled === true) return;
256
+ const answer = ctx.deps
257
+ .ask("Check every new plan against a Graphify code map? It installs graphifyy (uv) and builds a code map in each chosen repo. [y/N] ")
258
+ .trim();
259
+ if (!/^y(es)?$/i.test(answer)) return;
260
+ const r = ctx.deps.reuseOn();
261
+ for (const line of r.out) ctx.deps.say(line);
262
+ for (const line of r.err) ctx.deps.say(line);
263
+ }
264
+
241
265
  // The value offered for Enter. A fresh home offers what this machine has; a re-run offers the
242
266
  // current config, so a setting the owner already chose never moves on its own.
243
267
  function proposal(ctx: Ctx, key: string, current: unknown): unknown {
@@ -262,6 +262,19 @@ export interface Config {
262
262
  /** Rule ids probation never raises. */
263
263
  keep_off: string[];
264
264
  };
265
+ /** Reuse map (plan 20261122_1828_reuse_map): the opt-in Graphify code map a new plan's `## Reuse` must cite. Off changes nothing. */
266
+ reuse_map: {
267
+ /** The whole feature runs only when this is true. */
268
+ enabled: boolean;
269
+ /** The mapping tool; only "graphify" is implemented. */
270
+ tool: string;
271
+ /** Distinct matched files a map line must have cited (plan owner: 2). */
272
+ min_cited: number;
273
+ /** Repos `reuse on` mapped (set only by `reuse on`/`reuse off`); a plan outside them is refused. */
274
+ repos: string[];
275
+ /** Globs `graphify extract` skips in every mapped repo. */
276
+ exclude: string[];
277
+ };
265
278
  machine: {
266
279
  load_over_cores: number;
267
280
  load_max: number;
@@ -719,6 +732,22 @@ function check(cfg: Config): void {
719
732
  if (!Array.isArray(cfg.tuning.keep_off) || cfg.tuning.keep_off.some((id) => typeof id !== "string")) {
720
733
  throw new ConfigError("tuning.keep_off must be a list of strings");
721
734
  }
735
+ if (cfg.reuse_map.tool !== "graphify") throw new ConfigError('reuse_map.tool must be "graphify" (PyPI: graphifyy; the only implemented mapping tool)');
736
+ if (!Number.isInteger(cfg.reuse_map.min_cited) || cfg.reuse_map.min_cited < 1) {
737
+ throw new ConfigError("reuse_map.min_cited must be an integer >= 1 (distinct matched files a map line must have cited)");
738
+ }
739
+ if (!Array.isArray(cfg.reuse_map.repos) || cfg.reuse_map.repos.some((r) => typeof r !== "string" || !r.trim())) {
740
+ throw new ConfigError("reuse_map.repos must be a list of repo paths (set by `neurastream reuse on`, never by hand)");
741
+ }
742
+ if (!Array.isArray(cfg.reuse_map.exclude) || cfg.reuse_map.exclude.some((e) => typeof e !== "string" || !e.trim())) {
743
+ throw new ConfigError("reuse_map.exclude must be a list of non-empty glob strings");
744
+ }
745
+ if (cfg.reuse_map.enabled && !cfg.reuse_map.repos.length) {
746
+ throw new ConfigError("reuse_map.enabled is true with an empty reuse_map.repos — run `neurastream reuse on <repo>` first, or set reuse_map.enabled: false");
747
+ }
748
+ if (cfg.reuse_map.enabled && !cfg.review.agents.length) {
749
+ throw new ConfigError("reuse_map.enabled is true but review.agents is empty, which turns the ## Reuse gate off — name an agent in review.agents or set reuse_map.enabled: false");
750
+ }
722
751
  for (const p of cfg.metrics.correction_patterns) {
723
752
  try {
724
753
  new RegExp(p, "i");
@@ -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");