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
@@ -8,7 +8,6 @@
8
8
  // posts), `neurastream redact` and doctor all call this one module.
9
9
 
10
10
  import { readFileSync, readdirSync, statSync } from "node:fs";
11
- import { homedir } from "node:os";
12
11
  import { join } from "node:path";
13
12
  import type { Config } from "./config.ts";
14
13
 
@@ -187,7 +186,7 @@ interface CachedFile {
187
186
  values: string[];
188
187
  }
189
188
 
190
- type FileKind = "npmrc" | "env" | "text";
189
+ type FileKind = "npmrc" | "env-all" | "env-secret" | "text";
191
190
 
192
191
  const fileCache = new Map<string, CachedFile>();
193
192
  let discovered: { roots: string; atMs: number; files: string[] } | null = null;
@@ -211,16 +210,61 @@ function npmrcValues(text: string): string[] {
211
210
  return out;
212
211
  }
213
212
 
214
- /** `KEY=value` values of an env-style file (quotes stripped, comments ignored). */
215
- function envValues(text: string): string[] {
213
+ /**
214
+ * Parse one dotenv RHS value, handling quoted values (preserving `#` inside quotes and unescaping
215
+ * `\"`/`\\` inside double quotes) before stripping trailing inline `#` comments.
216
+ *
217
+ * Args:
218
+ * raw (string): Raw right-hand side of a `KEY=value` line
219
+ *
220
+ * Returns:
221
+ * string: Unquoted value with any trailing comment removed
222
+ */
223
+ function parseEnvValue(raw: string): string {
224
+ const trimmed = raw.trim();
225
+ if (trimmed.length === 0) return "";
226
+ if (trimmed[0] === '"') {
227
+ let out = "";
228
+ for (let i = 1; i < trimmed.length; i++) {
229
+ const ch = trimmed[i]!;
230
+ if (ch === "\\" && i + 1 < trimmed.length) {
231
+ const next = trimmed[i + 1]!;
232
+ if (next === '"' || next === "\\") {
233
+ out += next;
234
+ i++;
235
+ continue;
236
+ }
237
+ }
238
+ if (ch === '"') return out;
239
+ out += ch;
240
+ }
241
+ return out;
242
+ }
243
+ if (trimmed[0] === "'") {
244
+ const end = trimmed.indexOf("'", 1);
245
+ return end === -1 ? trimmed.slice(1) : trimmed.slice(1, end);
246
+ }
247
+ const hash = trimmed.search(/\s#/);
248
+ return (hash === -1 ? trimmed : trimmed.slice(0, hash)).trim();
249
+ }
250
+
251
+ /**
252
+ * Extract `KEY=value` values from an env-style file (quotes and inline comments parsed cleanly).
253
+ *
254
+ * Args:
255
+ * text (string): Full file contents
256
+ * secretKeysOnly (boolean): When true, keep only keys matching `SECRET_ENV_NAME`
257
+ *
258
+ * Returns:
259
+ * string[]: Extracted non-empty values
260
+ */
261
+ function envValues(text: string, secretKeysOnly: boolean): string[] {
216
262
  const out: string[] = [];
217
263
  for (const line of text.split("\n")) {
218
- const m = /^\s*(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*\s*=\s*(.+)$/.exec(line);
219
- if (!m?.[1]) continue;
220
- let value = m[1].trim();
221
- if (value.length >= 2 && (value[0] === '"' || value[0] === "'") && value.endsWith(value[0])) value = value.slice(1, -1);
222
- const hash = value.search(/\s#/);
223
- if (hash !== -1) value = value.slice(0, hash).trim();
264
+ const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.+)$/.exec(line);
265
+ if (!m?.[1] || !m[2]) continue;
266
+ if (secretKeysOnly && !SECRET_ENV_NAME.test(m[1])) continue;
267
+ const value = parseEnvValue(m[2]);
224
268
  if (value !== "") out.push(value);
225
269
  }
226
270
  return out;
@@ -247,7 +291,14 @@ function fileValues(path: string, kind: FileKind): string[] {
247
291
  } catch {
248
292
  return hit?.values ?? [];
249
293
  }
250
- const values = kind === "npmrc" ? npmrcValues(text) : kind === "env" ? envValues(text) : [text.trim()];
294
+ const values =
295
+ kind === "npmrc"
296
+ ? npmrcValues(text)
297
+ : kind === "env-all"
298
+ ? envValues(text, false)
299
+ : kind === "env-secret"
300
+ ? envValues(text, true)
301
+ : [text.trim()];
251
302
  fileCache.set(key, { mtimeMs, size, values });
252
303
  return values;
253
304
  }
@@ -309,9 +360,9 @@ export function loadKnownSecrets(cfg: Config, env: NodeJS.ProcessEnv = process.e
309
360
  for (const [name, value] of Object.entries(env)) {
310
361
  if (typeof value === "string" && SECRET_ENV_NAME.test(name)) add(value);
311
362
  }
312
- for (const value of fileValues(join(homedir(), ".npmrc"), "npmrc")) add(value);
313
- for (const file of cfg.secrets.known_value_files) for (const value of fileValues(file, "env")) add(value);
314
- for (const file of workRootEnvFiles(cfg.paths.work_roots)) for (const value of fileValues(file, "env")) add(value);
363
+ for (const value of fileValues(join(cfg.paths.home, ".npmrc"), "npmrc")) add(value);
364
+ for (const file of cfg.secrets.known_value_files) for (const value of fileValues(file, "env-all")) add(value);
365
+ for (const file of workRootEnvFiles(cfg.paths.work_roots)) for (const value of fileValues(file, "env-secret")) add(value);
315
366
  for (const file of notifyFiles(cfg)) for (const value of fileValues(file, "text")) add(value);
316
367
  return [...out];
317
368
  }
@@ -53,14 +53,19 @@ export interface SetupFacts {
53
53
  current: Config | null;
54
54
  }
55
55
 
56
- function hasRepoBelow(dir: string): boolean {
56
+ /** Direct children of dir that are git repositories (`.git` file = worktree), unsorted (plan 20261122_1828_reuse_map P3: the one walk `reuse on` candidates reuse). */
57
+ export function repoDirs(dir: string): string[] {
57
58
  try {
58
- return readdirSync(dir, { withFileTypes: true }).some(c => c.isDirectory() && existsSync(join(dir, c.name, ".git")));
59
+ return readdirSync(dir, { withFileTypes: true }).filter(c => c.isDirectory() && existsSync(join(dir, c.name, ".git"))).map(c => join(dir, c.name));
59
60
  } catch {
60
- return false;
61
+ return [];
61
62
  }
62
63
  }
63
64
 
65
+ function hasRepoBelow(dir: string): boolean {
66
+ return repoDirs(dir).length > 0;
67
+ }
68
+
64
69
  function workRoots(home: string): string[] {
65
70
  return readdirSync(home, { withFileTypes: true })
66
71
  .filter(d => d.isDirectory() && !d.name.startsWith("."))
@@ -72,6 +72,84 @@ export function parseBackendState(stdout: string): "running" | "stopped" {
72
72
  }
73
73
  }
74
74
 
75
+ /** How long a positive peer→login whois lookup stays cached (ms). */
76
+ export const WHOIS_TTL_MS = 30_000;
77
+
78
+ /** Maximum number of peer→login entries kept in the whois cache. */
79
+ export const WHOIS_MAX_ENTRIES = 256;
80
+
81
+ export interface CachedWhoisOptions {
82
+ ttlMs?: number;
83
+ maxEntries?: number;
84
+ now?: () => number;
85
+ }
86
+
87
+ export interface CachedWhois {
88
+ whois(peer: string): string | null;
89
+ clear(): void;
90
+ }
91
+
92
+ /**
93
+ * Wrap a synchronous peer→login lookup with a bounded, positive-only TTL cache.
94
+ * Transient `null` failures are never cached; expired entries are evicted on read;
95
+ * when capacity is reached, the oldest inserted entry is evicted.
96
+ *
97
+ * Args:
98
+ * lookup ((peer: string) => string | null): Underlying synchronous whois lookup
99
+ * opts (CachedWhoisOptions | undefined): Optional TTL, capacity, and clock overrides
100
+ *
101
+ * Returns:
102
+ * CachedWhois: Cached lookup function paired with a `clear()` reset helper
103
+ */
104
+ export function createCachedWhois(
105
+ lookup: (peer: string) => string | null,
106
+ opts: CachedWhoisOptions = {},
107
+ ): CachedWhois {
108
+ const ttlMs = opts.ttlMs ?? WHOIS_TTL_MS;
109
+ const maxEntries = opts.maxEntries ?? WHOIS_MAX_ENTRIES;
110
+ const now = opts.now ?? Date.now;
111
+ const cache = new Map<string, { login: string; expiresAt: number }>();
112
+
113
+ return {
114
+ whois(peer: string): string | null {
115
+ const nowMs = now();
116
+ const hit = cache.get(peer);
117
+ if (hit) {
118
+ if (nowMs < hit.expiresAt) return hit.login;
119
+ cache.delete(peer);
120
+ }
121
+ const login = lookup(peer);
122
+ if (login === null) return null;
123
+ if (ttlMs > 0 && maxEntries > 0) {
124
+ if (cache.has(peer)) cache.delete(peer);
125
+ while (cache.size >= maxEntries) {
126
+ const oldest = cache.keys().next().value;
127
+ if (oldest === undefined) break;
128
+ cache.delete(oldest);
129
+ }
130
+ cache.set(peer, { login, expiresAt: nowMs + ttlMs });
131
+ }
132
+ return login;
133
+ },
134
+ clear(): void {
135
+ cache.clear();
136
+ },
137
+ };
138
+ }
139
+
140
+ function rawWhois(peer: string): string | null {
141
+ const r = spawnSync("tailscale", ["whois", "--json", peer], { encoding: "utf8", timeout: 8000 });
142
+ if (r.error || r.status !== 0) return null;
143
+ return parseWhoisLogin(r.stdout ?? "");
144
+ }
145
+
146
+ const realWhoisCache = createCachedWhois(rawWhois);
147
+
148
+ /** Clear the process-wide `realTailscale.whois()` TTL cache (used by tests). */
149
+ export function clearWhoisCache(): void {
150
+ realWhoisCache.clear();
151
+ }
152
+
75
153
  export const realTailscale: Tailscale = {
76
154
  ip4() {
77
155
  return firstStdoutLine(["ip", "-4"]);
@@ -88,9 +166,7 @@ export const realTailscale: Tailscale = {
88
166
  }
89
167
  },
90
168
  whois(peer) {
91
- const r = spawnSync("tailscale", ["whois", "--json", peer], { encoding: "utf8", timeout: 8000 });
92
- if (r.error || r.status !== 0) return null;
93
- return parseWhoisLogin(r.stdout ?? "");
169
+ return realWhoisCache.whois(peer);
94
170
  },
95
171
  logins() {
96
172
  try {
@@ -162,9 +162,20 @@ if (import.meta.main) {
162
162
  );
163
163
  }
164
164
 
165
- /** The default transport: one synchronous child, JSON request on stdin, JSON answer on stdout. */
165
+ /**
166
+ * The default transport: one synchronous child, JSON request on stdin, JSON answer on stdout.
167
+ *
168
+ * Args:
169
+ * req (WireRequest): HTTP request parameters to execute in the child process
170
+ *
171
+ * Returns:
172
+ * WireResponse | null: Parsed response object or an error envelope
173
+ */
166
174
  function defaultSend(req: WireRequest): WireResponse | null {
167
- const r = spawnSync(process.execPath, [fileURLToPath(import.meta.url)], {
175
+ // Always invoke `bun` by name, never `process.execPath`: when core is loaded inside a
176
+ // compiled host harness, `process.execPath` points at the harness binary itself, so spawning
177
+ // it would recursively launch full host sessions instead of running this request script.
178
+ const r = spawnSync("bun", [fileURLToPath(import.meta.url)], {
168
179
  input: JSON.stringify(req),
169
180
  timeout: REQUEST_TIMEOUT_MS,
170
181
  encoding: "utf8",
@@ -11,6 +11,8 @@ import { fileURLToPath } from "node:url";
11
11
  import { stripBlock } from "./agents-md.ts";
12
12
  import { configFile, loadConfig, type Config } from "./config.ts";
13
13
  import { printText } from "./help.ts";
14
+ import { indexLockPath } from "./queue/lib.ts";
15
+ import { reuseOff } from "./reuse-map.ts";
14
16
 
15
17
  const HERE = dirname(fileURLToPath(import.meta.url));
16
18
  const PACKAGE_ROOT = resolve(HERE, "../..");
@@ -162,6 +164,7 @@ function purgeState(cfg: Config, out: UninstallTarget[]): void {
162
164
  const entries: [string, string, boolean][] = [
163
165
  [configFile(cfg.paths.home), "--purge: config file", false],
164
166
  [cfg.paths.queue_index, "--purge: index", false],
167
+ [indexLockPath(cfg.paths.queue_index), "--purge: index lock", false],
165
168
  [join(cfg.paths.agent_dir, "queue"), "--purge: queue dir", true],
166
169
  [cfg.paths.notes, "--purge: notes dir", true],
167
170
  [cfg.paths.blockers, "--purge: blockers dir", true],
@@ -246,6 +249,19 @@ export function runUninstall(args: string[]): number {
246
249
  printText("dry run: re-run with --yes to remove these");
247
250
  return 1;
248
251
  }
252
+ // Reuse map (plan 20261122_1828_reuse_map P3): uninstalling with the map on runs the off
253
+ // routine first (exclude lines, config); --purge passes through, so graphify-out/ goes and
254
+ // graphifyy is uninstalled too. A failed off stops the uninstall: the gate must not stay on
255
+ // while its config is being removed.
256
+ if (cfg.reuse_map.enabled) {
257
+ const off = reuseOff(args.filter((a) => a === "--purge"), { home: homedir(), env: process.env, terminal: false, ask: () => "n" });
258
+ for (const l of off.out) printText(l);
259
+ if (off.code !== 0) {
260
+ for (const l of off.err) printText(l);
261
+ printText("uninstall stopped: the reuse map could not be turned off");
262
+ return 1;
263
+ }
264
+ }
249
265
  applyUninstall(cfg, plan);
250
266
  printText(`uninstalled ${plan.targets.length} target${plan.targets.length === 1 ? "" : "s"}${purge ? " (purged)" : ""}`);
251
267
  return 0;
@@ -240,6 +240,13 @@ tuning: # the tuner steps existing rules down and back up (
240
240
  guards: false # guard ids are scored and stepped only when this is true
241
241
  keep_off: [] # rule ids probation never raises
242
242
 
243
+ reuse_map: # the opt-in Graphify code map gating new plans (src/core/reuse-map.ts)
244
+ enabled: false # off: no graphify/uv/pipx process, no graphify-out/ read, nothing changes
245
+ tool: graphify # the mapping tool; only "graphify" (PyPI: graphifyy) is implemented
246
+ min_cited: 2 # distinct matched files a plan's `## Reuse` map line must have cited
247
+ repos: [] # repos `neurastream reuse on` mapped; set only by `reuse on`/`reuse off`
248
+ exclude: [] # globs `graphify extract` skips in every mapped repo
249
+
243
250
  machine:
244
251
  load_over_cores: 4 # load above the core count that draws a warning (used when load_max is 0)
245
252
  load_max: 0 # load ceiling; 0 = core count + load_over_cores