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.
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.23",
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)) {
@@ -47,6 +47,7 @@ import { registerChatCommands } from "./chat-commands.ts";
47
47
  import { CLAIM_BEAT_MS, deliverOwnerInbox, OWNER_INBOX_POLL_MS, ownerInboxCursorPath, ownerInboxMessage, pendingInboxRecords, pressureTick, seedInboxFloor } from "./inbox.ts";
48
48
  import { adapterLog, MAIN_ENV } from "./launch.ts";
49
49
  // Registers the plugin-command matcher into core's writeTargets (side effect).
50
+ import { createLimitWake } from "./limit-wake.ts";
50
51
  import "./package-ops.ts";
51
52
  import { createRateLimitController, limitProbeSpawn, recordProviderOutFromRateLimit, recordProviderOutFromTask } from "./rate-limit-controller.ts";
52
53
  import { createRolloverController } from "./rollover-controller.ts";
@@ -272,6 +273,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
272
273
  const mainRules = renderBlock(cfg);
273
274
 
274
275
  const rateLimit = createRateLimitController(pi, getCfg);
276
+ const limitWake = createLimitWake(pi, getCfg);
275
277
  const rollover = createRolloverController(pi, getCfg, { doctor: opts.doctor });
276
278
 
277
279
  // Clear the previous adapter's armed grace timer before this one overwrites the pointer (P3c).
@@ -281,6 +283,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
281
283
  activeAdapterReset = (): void => {
282
284
  rollover.clearState();
283
285
  rateLimit.stopTick();
286
+ limitWake.cancel();
284
287
  };
285
288
 
286
289
  let callsSinceStop = 0;
@@ -528,6 +531,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
528
531
  return content ? { message: { customType: "main-guard.rules", content, display: false } } : undefined;
529
532
  }
530
533
  rateLimit.onOwnerPrompt();
534
+ limitWake.cancel();
531
535
  const d = checkInject({ inject: prompt, agent: "main" }, cfg);
532
536
  callsSinceStop = d.state?.callsSinceStop ?? callsSinceStop;
533
537
  idleStops = d.state?.idleStops ?? idleStops;
@@ -829,6 +833,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
829
833
  idleStops = d.state?.idleStops ?? idleStops;
830
834
  if (d.allow) {
831
835
  recordTurnAnswer(reply);
836
+ limitWake.arm(asCtx(ctx));
832
837
  notifyHandback(reply, "allowed session_stop");
833
838
  return undefined;
834
839
  }
@@ -844,7 +849,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
844
849
  // posts from the event's own messages. omp also sets willContinue after a BLOCKED stop
845
850
  // (sessionStopWillContinue) and for todo/plan-mode/rewind continuations, so a post here needs
846
851
  // both: no blocked stop just decided (the flag), and an async job really pending. A terminal
847
- // end (willContinue unset) is not a hand-back: the session_stop that follows it decides. A
852
+ // end (willContinue unset) is not a hand-back: session_stop runs first and has already decided. A
848
853
  // mid-run continuation — tool calls, or a non-"stop" reason such as an auto-retry — posts
849
854
  // nothing.
850
855
  const onDeferredHandback = (e: unknown, ctx: unknown): void => {
@@ -0,0 +1,83 @@
1
+ // Main's limit wake (plan 20261127_1005 P2). When a counted Main call cap or edit window resets
2
+ // while plans are still open, Main gets ONE continuation at the reset instead of sitting parked
3
+ // until the owner speaks. The wake lives in memory only: a restart or reload drops it, and the
4
+ // next owner prompt or stop re-evaluates the limits anyway.
5
+
6
+ import { currentTier } from "../../core/autonomy.ts";
7
+ import type { Config } from "../../core/config.ts";
8
+ import { editWindowEndMs, mainCallsCapOn, mainCallsResetMs, mainEditLimit, openQueue, readWindow } from "../../core/guards.ts";
9
+ import { adapterLog } from "./launch.ts";
10
+ import { LIMIT_TICK_MS } from "./rate-limit-controller.ts";
11
+ import type { ExtensionHost, HostCtx } from "./types.ts";
12
+
13
+ const WAKE_TEXT = "main-guard: the call/edit limit has reset — continue the queue where you stopped.";
14
+
15
+ export interface LimitWake {
16
+ /** At session_stop's allow: one tick at the latest reset still holding Main, when plans are open. */
17
+ arm(c: HostCtx): void;
18
+ /** An owner prompt, or a reset of the adapter, drops the wake. */
19
+ cancel(): void;
20
+ }
21
+
22
+ /** The latest reset (ms since epoch) of a limit still holding Main at `now`; null when none does. */
23
+ function pendingResetMs(cfg: Config, now: number): number | null {
24
+ const w = readWindow(cfg.paths);
25
+ const tier = currentTier(cfg);
26
+ const resets: number[] = [];
27
+ const calls = mainCallsResetMs(w);
28
+ if (mainCallsCapOn(cfg, tier) && w.mainCalls >= cfg.guards.main_max_calls && calls !== null && calls > now) resets.push(calls);
29
+ const edits = editWindowEndMs(w, cfg);
30
+ if (w.used.length >= mainEditLimit(cfg, tier) && edits > now) resets.push(edits);
31
+ return resets.length > 0 ? Math.max(...resets) : null;
32
+ }
33
+
34
+ /** Plans still open; none when the queue cannot be read (logged: the stop path reports that itself). */
35
+ function openPlans(cfg: Config): string[] {
36
+ try {
37
+ return openQueue(cfg.paths, cfg.review.agents);
38
+ } catch (err) {
39
+ adapterLog(cfg, `LIMIT-WAKE skipped: queue unreadable: ${err}`);
40
+ return [];
41
+ }
42
+ }
43
+
44
+ export function createLimitWake(pi: ExtensionHost, getCfg: () => Config): LimitWake {
45
+ // The arm snapshots the reset time; the tick only compares the clock with it and never re-reads
46
+ // the window, because the terminal hand-back zeroes mainCalls right after session_stop.
47
+ let wakeAt: number | null = null;
48
+ let tick: NodeJS.Timeout | null = null;
49
+
50
+ const cancel = (): void => {
51
+ wakeAt = null;
52
+ if (tick !== null) {
53
+ clearInterval(tick);
54
+ tick = null;
55
+ }
56
+ };
57
+
58
+ const fire = (): void => {
59
+ if (wakeAt === null || Date.now() < wakeAt) return;
60
+ const cfg = getCfg();
61
+ cancel();
62
+ if (openPlans(cfg).length === 0) {
63
+ adapterLog(cfg, "LIMIT-WAKE none: the limit reset with no open plan");
64
+ return;
65
+ }
66
+ adapterLog(cfg, "LIMIT-WAKE sent: the limit reset with plans open");
67
+ pi.sendUserMessage(WAKE_TEXT);
68
+ };
69
+
70
+ return {
71
+ arm(c) {
72
+ cancel();
73
+ const cfg = getCfg();
74
+ const reset = pendingResetMs(cfg, Date.now());
75
+ if (reset === null || openPlans(cfg).length === 0) return;
76
+ wakeAt = reset;
77
+ const t: unknown = c.setInterval ? c.setInterval(fire, LIMIT_TICK_MS) : setInterval(fire, LIMIT_TICK_MS);
78
+ if (t && typeof t === "object" && "unref" in t && typeof t.unref === "function") t.unref();
79
+ tick = t as NodeJS.Timeout;
80
+ },
81
+ cancel,
82
+ };
83
+ }
@@ -53,7 +53,7 @@ export function recordProviderOutFromRateLimit(reply: EventReply | null, untilMs
53
53
  }
54
54
 
55
55
  /** The limit tick: one check of the open episode every 30 s (plan 20261027_1500 P3). */
56
- const LIMIT_TICK_MS = 30_000;
56
+ export const LIMIT_TICK_MS = 30_000;
57
57
 
58
58
  /** The probe's command line and env. Never process.execPath: inside the harness that is the omp
59
59
  * binary, so the child was a full Main session (2026-11-03: stray Mains). bun comes from PATH, as
@@ -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");