neurastream 0.3.20 → 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.
Files changed (57) hide show
  1. package/README.md +1 -0
  2. package/package.json +1 -1
  3. package/src/adapters/index.ts +3 -2
  4. package/src/adapters/omp/adapter.ts +2 -1
  5. package/src/adapters/omp/auto-close.ts +64 -0
  6. package/src/adapters/omp/chat-commands.ts +161 -0
  7. package/src/adapters/omp/doctor.ts +6 -0
  8. package/src/adapters/omp/inbox.ts +221 -0
  9. package/src/adapters/omp/index.ts +115 -1039
  10. package/src/adapters/omp/launch.ts +31 -3
  11. package/src/adapters/omp/rate-limit-controller.ts +196 -0
  12. package/src/adapters/omp/rollover-controller.ts +334 -0
  13. package/src/adapters/omp/types.ts +143 -0
  14. package/src/cli/commands.ts +33 -2
  15. package/src/cli/dispatch.ts +44 -16
  16. package/src/cli/recall.ts +3 -2
  17. package/src/cli/results-build.ts +1 -1
  18. package/src/cli/reuse.ts +109 -0
  19. package/src/cli/setup.ts +25 -1
  20. package/src/cli/workspace.ts +13 -2
  21. package/src/core/adapter.ts +16 -0
  22. package/src/core/blockers.ts +326 -30
  23. package/src/core/config.ts +29 -0
  24. package/src/core/file-lock.ts +71 -12
  25. package/src/core/guards/plan-edit.ts +530 -0
  26. package/src/core/guards/planner.ts +70 -0
  27. package/src/core/guards/review.ts +391 -0
  28. package/src/core/guards/spawn.ts +709 -0
  29. package/src/core/guards/state.ts +581 -0
  30. package/src/core/guards/stop.ts +235 -0
  31. package/src/core/guards/tool.ts +541 -0
  32. package/src/core/guards.ts +12 -2658
  33. package/src/core/incidents.ts +125 -91
  34. package/src/core/machine-guard.ts +23 -5
  35. package/src/core/main-start.ts +10 -8
  36. package/src/core/owner-topics.ts +2 -13
  37. package/src/core/owner-ui/auth.ts +164 -0
  38. package/src/core/owner-ui/data.ts +437 -0
  39. package/src/core/owner-ui/handlers.ts +250 -0
  40. package/src/core/owner-ui/messages.ts +209 -0
  41. package/src/core/owner-ui/render.ts +714 -0
  42. package/src/core/owner-ui/results.ts +266 -0
  43. package/src/core/owner-ui/server.ts +142 -0
  44. package/src/core/owner-ui.ts +11 -2121
  45. package/src/core/page-notes.ts +25 -0
  46. package/src/core/pages.ts +452 -77
  47. package/src/core/plan-approval.ts +12 -14
  48. package/src/core/queue/lib.ts +146 -43
  49. package/src/core/queue-cancel.ts +21 -17
  50. package/src/core/queue-close.ts +48 -23
  51. package/src/core/reuse-map.ts +742 -0
  52. package/src/core/secret-redact.ts +65 -14
  53. package/src/core/setup-detect.ts +8 -3
  54. package/src/core/tailscale.ts +79 -3
  55. package/src/core/team-client.ts +13 -2
  56. package/src/core/uninstall.ts +16 -0
  57. package/templates/config.yml +7 -0
@@ -0,0 +1,143 @@
1
+ // Shared omp extension host types and runtime-checked payload accessors.
2
+
3
+ import type { Decision } from "../../core/adapter.ts";
4
+
5
+ /** Subset of the harness extension host the adapter needs. */
6
+ export interface ExtensionHost {
7
+ on(event: string, cb: (...args: unknown[]) => unknown): void;
8
+ registerCommand(name: string, opts: { description?: string; handler: (args: unknown, ctx: unknown) => unknown }): void;
9
+ sendUserMessage(content: string | ({ type: "text"; text: string } | { type: "image"; data: string; mimeType: string })[]): void;
10
+ sendMessage(message: { customType: string; content: string; display: boolean }, options: { triggerTurn: boolean; deliverAs: "nextTurn" }): void;
11
+ }
12
+
13
+ /** The parts of a harness call context the handlers look at. */
14
+ export interface HostCtx {
15
+ hasAgent: boolean;
16
+ kind?: string;
17
+ id?: string;
18
+ cwd?: string;
19
+ setInterval?: (cb: () => void, ms: number) => unknown;
20
+ spawnLimitProbe?: () => void;
21
+ }
22
+
23
+ /** The last assistant message of an omp event's `messages` array, as the adapter needs it: its
24
+ * joined text-block text and the shape that tells a real hand-back from a mid-run continuation
25
+ * (plan 20261025_0130). omp sends the reply in `session_stop.last_assistant_message` (falling
26
+ * back to the last assistant entry of `messages`) and in `agent_end.messages`; reading the
27
+ * session file instead lags a whole turn because session_stop fires BEFORE agent_end. */
28
+ export interface EventReply {
29
+ text: string;
30
+ stopReason: string | null;
31
+ toolCalls: number;
32
+ /** The provider's error text on a turn that ended on one (`429 … retry-after-ms=…`); null otherwise. */
33
+ errorMessage: string | null;
34
+ /** The provider and model fields of the assistant message, when the event carries them; the provider-out recording keys on the provider. */
35
+ provider: string | null;
36
+ model: string | null;
37
+ }
38
+
39
+ export interface RolloverCtx {
40
+ sessionId: string;
41
+ sessionFile: string;
42
+ runningJobs(): string[];
43
+ waitForIdle(): unknown;
44
+ newSession(opts: { parentSession: string }): unknown;
45
+ notify(message: string): void;
46
+ draft(): string;
47
+ shutdown(): void;
48
+ }
49
+
50
+ export function asRecord(v: unknown): Record<string, unknown> {
51
+ return v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
52
+ }
53
+
54
+ export function asString(v: unknown, fallback = ""): string {
55
+ return typeof v === "string" ? v : fallback;
56
+ }
57
+
58
+ /** Call a method on a harness object by name; undefined when it is not a function. */
59
+ export function call(obj: Record<string, unknown>, key: string, args: unknown[] = []): unknown {
60
+ const fn = obj[key];
61
+ return typeof fn === "function" ? Reflect.apply(fn, obj, args) : undefined;
62
+ }
63
+
64
+ export function lastAssistantIn(messages: unknown): EventReply | null {
65
+ const arr = Array.isArray(messages) ? messages : [];
66
+ for (let i = arr.length - 1; i >= 0; i--) {
67
+ const m = asRecord(arr[i]);
68
+ if (m.role !== "assistant") continue;
69
+ const content = Array.isArray(m.content) ? m.content : [];
70
+ const text = content
71
+ .filter(c => asRecord(c).type === "text")
72
+ .map(c => asString(asRecord(c).text))
73
+ .join("\n")
74
+ .trim();
75
+ return {
76
+ text,
77
+ stopReason: typeof m.stopReason === "string" ? m.stopReason : null,
78
+ toolCalls: content.filter(c => asRecord(c).type === "toolCall").length,
79
+ errorMessage: typeof m.errorMessage === "string" ? m.errorMessage : null,
80
+ provider: typeof m.provider === "string" ? m.provider : null,
81
+ model: typeof m.model === "string" ? m.model : null,
82
+ };
83
+ }
84
+ return null;
85
+ }
86
+
87
+ export function asCtx(v: unknown): HostCtx {
88
+ const r = asRecord(v);
89
+ // The agent envelope only ever carries kind/id strings (original extensions read just those);
90
+ // cast fixes the envelope, every field below is checked before use.
91
+ const agent = r.agent as { kind?: unknown; id?: unknown } | null | undefined;
92
+ const out: HostCtx = { hasAgent: agent !== null && agent !== undefined };
93
+ if (agent) {
94
+ if (typeof agent.kind === "string") out.kind = agent.kind;
95
+ if (typeof agent.id === "string") out.id = agent.id;
96
+ }
97
+ if (typeof r.cwd === "string") out.cwd = r.cwd;
98
+ // Harness-injected timer with the original main-guard signature (ctx.setInterval).
99
+ const interval = r.setInterval as ((cb: () => void, ms: number) => unknown) | undefined;
100
+ if (typeof interval === "function") out.setInterval = interval;
101
+ // Harness-injected probe spawner (tests); the default starts the niced probe child.
102
+ const probe = r.spawnLimitProbe as (() => void) | undefined;
103
+ if (typeof probe === "function") out.spawnLimitProbe = probe;
104
+ return out;
105
+ }
106
+
107
+ export function asRolloverCtx(v: unknown): RolloverCtx | null {
108
+ const r = asRecord(v);
109
+ const sm = asRecord(r.sessionManager);
110
+ const sessionId = call(sm, "getSessionId");
111
+ const sessionFile = call(sm, "getSessionFile");
112
+ if (typeof sessionId !== "string" || typeof sessionFile !== "string") return null;
113
+ return {
114
+ sessionId,
115
+ sessionFile,
116
+ runningJobs: () => {
117
+ const running = asRecord(call(r, "getAsyncJobSnapshot")).running;
118
+ return Array.isArray(running) ? running.map(j => asString(asRecord(j).label, "job")) : [];
119
+ },
120
+ waitForIdle: () => call(r, "waitForIdle"),
121
+ newSession: opts => call(r, "newSession", [opts]),
122
+ notify: message => call(asRecord(r.ui), "notify", [message]),
123
+ draft: () => {
124
+ const text = call(asRecord(r.ui), "getEditorText");
125
+ return typeof text === "string" ? text : "";
126
+ },
127
+ shutdown: () => {
128
+ call(r, "shutdown");
129
+ },
130
+ };
131
+ }
132
+
133
+ export function isMain(ctx: unknown): boolean {
134
+ const c = asCtx(ctx);
135
+ return !c.hasAgent || c.kind === "main";
136
+ }
137
+
138
+ /** Map a core decision onto the extension return shapes. */
139
+ export function toExtensionResult(d: Decision): Record<string, unknown> {
140
+ if (!d.allow) return { block: true, reason: d.reason, decision: "block" };
141
+ if (d.inject) return { additionalContext: d.inject };
142
+ return {};
143
+ }
@@ -1,3 +1,6 @@
1
+ import { spawn } from "node:child_process";
2
+ import { dirname, join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
1
4
  import { agentLedger } from "../core/agent-ledger.ts";
2
5
  import { agentScore } from "../core/agent-score.ts";
3
6
  import { briefLint } from "../core/brief-lint.ts";
@@ -48,6 +51,34 @@ export const PORTED = [
48
51
  "heavy-run",
49
52
  ] as const;
50
53
 
54
+ const CLI_MAIN = join(dirname(fileURLToPath(import.meta.url)), "main.ts");
55
+
56
+ /**
57
+ * Runs the CLI `doctor` command asynchronously and returns its combined stdout and stderr.
58
+ *
59
+ * Returns:
60
+ * Promise<string>: Output produced by `neurastream doctor`, including any spawn error message
61
+ */
62
+ function runCliDoctor(): Promise<string> {
63
+ const { promise, resolve } = Promise.withResolvers<string>();
64
+ const child = spawn(CLI_MAIN, ["doctor"], { stdio: ["ignore", "pipe", "pipe"] });
65
+ let stdout = "";
66
+ let stderr = "";
67
+ child.stdout?.setEncoding("utf8").on("data", (chunk: string) => {
68
+ stdout += chunk;
69
+ });
70
+ child.stderr?.setEncoding("utf8").on("data", (chunk: string) => {
71
+ stderr += chunk;
72
+ });
73
+ child.on("error", err => {
74
+ const text = `${stdout}${stderr}`;
75
+ const body = text.endsWith("\n") || text === "" ? text : `${text}\n`;
76
+ resolve(`${body}${err.message}\n`);
77
+ });
78
+ child.on("close", () => resolve(`${stdout}${stderr}`));
79
+ return promise;
80
+ }
81
+
51
82
  export async function runMain(args: string[]): Promise<number> {
52
83
  const cfg = runtime().cfg;
53
84
  return getAdapter(cfg).launchMain(args, cfg);
@@ -87,10 +118,10 @@ export async function runPorted(cmd: string, args: string[]): Promise<number> {
87
118
  return claimCli(args, rt.cfg);
88
119
  case "main-start": {
89
120
  const a = getAdapter(rt.cfg);
90
- return mainStart(args, rt.cfg, { source: a.runSource(rt.cfg), results: a.completedResults(rt.cfg), providers: a.providers(rt.cfg), episodesFor: cutoff => a.episodes(rt.cfg, cutoff) });
121
+ return mainStart(args, rt.cfg, { source: a.runSource(rt.cfg), results: a.completedResults(rt.cfg), providers: a.providers(rt.cfg), episodesFor: cutoff => a.episodes(rt.cfg, cutoff), doctor: runCliDoctor });
91
122
  }
92
123
  case "machine-guard":
93
- return machineGuard(args, rt.cfg);
124
+ return machineGuard(args, rt.cfg, { heavyMain: CLI_MAIN, heavyStatus: process.execPath });
94
125
  case "quota-reset":
95
126
  return quotaReset(args, rt.cfg);
96
127
  case "priority-watch":
@@ -29,9 +29,10 @@ 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
- import { activePlans, allowedAgents, enforceReadOnlyIndex, gitTop, readIndex, writeIndex } from "../core/queue/lib.ts";
35
+ import { activePlans, allowedAgents, enforceReadOnlyIndex, gitTop, parseIndex, updateIndex } from "../core/queue/lib.ts";
35
36
  import { defaultRunner } from "../core/mr-sweep.ts";
36
37
  import { allowAgents, denyAgents, invalidSlugs } from "../core/subagents.ts";
37
38
  import { runLabels } from "./labels.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();
@@ -339,15 +346,27 @@ function runQueueAdd(args: string[], cfg: Config): number {
339
346
  return 1;
340
347
  }
341
348
  const index = cfg.paths.queue_index;
342
- const lines = readIndex(index);
343
- if (lines.includes(abs)) {
344
- console.error(`queue add: ${abs} is already listed at rank ${lines.indexOf(abs) + 1} (queue move reorders it)`);
349
+ let existingRank = -1;
350
+ let insertedAt = -1;
351
+ let total = 0;
352
+ const wrote = updateIndex(index, undefined, (currentText) => {
353
+ const lines = parseIndex(currentText);
354
+ const found = lines.indexOf(abs);
355
+ if (found !== -1) {
356
+ existingRank = found + 1;
357
+ return null;
358
+ }
359
+ const at = rank === null ? lines.length : Math.min(rank - 1, lines.length);
360
+ lines.splice(at, 0, abs);
361
+ insertedAt = at + 1;
362
+ total = lines.length;
363
+ return lines;
364
+ });
365
+ if (!wrote) {
366
+ console.error(`queue add: ${abs} is already listed at rank ${existingRank} (queue move reorders it)`);
345
367
  return 1;
346
368
  }
347
- const at = rank === null ? lines.length : Math.min(rank - 1, lines.length);
348
- lines.splice(at, 0, abs);
349
- writeIndex(lines, undefined, index);
350
- console.log(`queue add: ${abs} at rank ${at + 1} of ${lines.length} in ${index}`);
369
+ console.log(`queue add: ${abs} at rank ${insertedAt} of ${total} in ${index}`);
351
370
  return 0;
352
371
  }
353
372
 
@@ -361,17 +380,26 @@ function runQueueMove(args: string[], cfg: Config): number {
361
380
  }
362
381
  const abs = path.resolve(fileArg!);
363
382
  const index = cfg.paths.queue_index;
364
- const lines = readIndex(index);
365
- const from = lines.indexOf(abs);
366
- if (from === -1) {
383
+ let fromRank = -1;
384
+ let toRank = -1;
385
+ let total = 0;
386
+ const wrote = updateIndex(index, undefined, (currentText) => {
387
+ const lines = parseIndex(currentText);
388
+ const from = lines.indexOf(abs);
389
+ if (from === -1) return null;
390
+ lines.splice(from, 1);
391
+ const to = Math.min(rank - 1, lines.length);
392
+ lines.splice(to, 0, abs);
393
+ fromRank = from + 1;
394
+ toRank = to + 1;
395
+ total = lines.length;
396
+ return lines;
397
+ });
398
+ if (!wrote) {
367
399
  console.error(`queue move: ${abs} is not in ${index}`);
368
400
  return 1;
369
401
  }
370
- lines.splice(from, 1);
371
- const to = Math.min(rank - 1, lines.length);
372
- lines.splice(to, 0, abs);
373
- writeIndex(lines, undefined, index);
374
- console.log(`queue move: ${abs} rank ${from + 1} → ${to + 1} of ${lines.length} in ${index}`);
402
+ console.log(`queue move: ${abs} rank ${fromRank} → ${toRank} of ${total} in ${index}`);
375
403
  return 0;
376
404
  }
377
405
 
package/src/cli/recall.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // `neurastream recall`: searches the owner's messages and Main's answers (the recall log, see
2
2
  // core/owner-log.ts) and shows an entry with the entry it pairs with. Read-only.
3
3
 
4
- import { getAdapter, ompComplete } from "../adapters/index.ts";
4
+ import { getAdapter } from "../adapters/index.ts";
5
5
  import { nowSec } from "../core/clock.ts";
6
6
  import { ConfigError, loadConfig, type Config } from "../core/config.ts";
7
7
  import { helpDoc, printText } from "../core/help.ts";
@@ -116,7 +116,8 @@ async function topicsCli(args: string[], cfg: Config): Promise<number> {
116
116
  return 2;
117
117
  }
118
118
  try {
119
- const run: TopicsRun = await runTopics(cfg, ompComplete, { close: args.includes("--close") });
119
+ const adapter = getAdapter(cfg);
120
+ const run: TopicsRun = await runTopics(cfg, req => adapter.complete(req), { close: args.includes("--close") });
120
121
  for (const line of run.lines) console.log(line);
121
122
  return run.failures === 0 ? 0 : 1;
122
123
  } catch {
@@ -1,4 +1,4 @@
1
- // The owner page's Results build, run as its own process by spawnResultsBuild (src/core/owner-ui.ts):
1
+ // The owner page's Results build, run as its own process by spawnResultsBuild (src/cli/workspace.ts):
2
2
  // it parses months of sessions (over a minute, GBs of memory), which froze the page when the server
3
3
  // did it itself (I-20261030-121). Writes the numbers to resultsCachePath(); the page only reads them.
4
4
 
@@ -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 {
@@ -14,7 +14,7 @@ import { homedir } from "node:os";
14
14
  import { getAdapter } from "../adapters/index.ts";
15
15
  import { ConfigError, loadConfig, type Config } from "../core/config.ts";
16
16
  import { beat, errorLine } from "../core/heartbeat.ts";
17
- import { startOwnerUi, type OwnerUiOptions, type OwnerUiServer } from "../core/owner-ui.ts";
17
+ import { startOwnerUi, type OwnerUiOptions, type OwnerUiServer, type ResultsBuild } from "../core/owner-ui.ts";
18
18
  import { realTailscale, type Tailscale, untilIp4Changes } from "../core/tailscale.ts";
19
19
  import { TEAM_NAME_HINT, TEAM_NAME_RE } from "../core/team-labels.ts";
20
20
  import { addTeamMember, listTeamMembers, removeTeamMember, startTeamServer, type TeamServer, type TeamServerConfig, type TeamServerOptions } from "../core/team-server.ts";
@@ -92,6 +92,17 @@ function runWorkspaceSetup(args: string[], deps: WorkspaceDeps): number {
92
92
  return uiOn({ ...setup, login, admin, repos, port, terminal });
93
93
  }
94
94
 
95
+ /**
96
+ * Spawns the standalone Results cache builder process at low CPU priority and notifies `done` on exit.
97
+ *
98
+ * Args:
99
+ * done (() => void): Callback invoked when the child build process finishes or fails
100
+ */
101
+ export const spawnResultsBuild: ResultsBuild = done => {
102
+ const proc = Bun.spawn(["nice", "-n", "19", process.execPath, `${import.meta.dir}/results-build.ts`], { stdout: "ignore", stderr: "inherit" });
103
+ void proc.exited.then(done, done);
104
+ };
105
+
95
106
  export async function runWorkspace(args: string[] = [], deps: WorkspaceDeps = {}): Promise<number> {
96
107
  if (args[0] === "on" || args[0] === "off") return runWorkspaceSetup(args, deps);
97
108
  if (args[0] === "members") return runMembers(args.slice(1), deps);
@@ -120,7 +131,7 @@ export async function runWorkspace(args: string[] = [], deps: WorkspaceDeps = {}
120
131
  const tailscale = deps.tailscale ?? realTailscale;
121
132
  let server: OwnerUiServer;
122
133
  try {
123
- server = (deps.start ?? startOwnerUi)({ cfg, tailscale, source: getAdapter(cfg).runSource(cfg) });
134
+ server = (deps.start ?? startOwnerUi)({ cfg, tailscale, source: getAdapter(cfg).runSource(cfg), resultsBuild: spawnResultsBuild });
124
135
  } catch (e) {
125
136
  beat(cfg, "workspace", { ok: false, detail: errorLine(e) });
126
137
  throw e;
@@ -185,6 +185,22 @@ export interface TaskResult {
185
185
  ts: number;
186
186
  }
187
187
 
188
+ /** One completion request sent through the active harness adapter's completion gateway. */
189
+ export interface CompleteRequest {
190
+ model: string;
191
+ system: string;
192
+ prompt: string;
193
+ maxTokens: number;
194
+ /** Reasoning effort for the model ("" or absent = none). */
195
+ effort?: string;
196
+ }
197
+
198
+ /** Plain-text result and token usage returned by a harness adapter's completion call. */
199
+ export interface CompleteResult {
200
+ text: string;
201
+ usage: { prompt_tokens: number; completion_tokens: number };
202
+ }
203
+
188
204
  /** Options for launching the harness binary; tests inject another path and a failing generator. */
189
205
  export interface LaunchOptions {
190
206
  harness?: string;