neurastream 0.1.23 → 0.1.25

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 +7 -3
  2. package/package.json +2 -3
  3. package/src/adapters/omp/doctor.ts +6 -2
  4. package/src/adapters/omp/index.ts +3 -3
  5. package/src/cli/commands.ts +4 -8
  6. package/src/cli/dispatch.ts +56 -3
  7. package/src/cli/init.ts +34 -14
  8. package/src/core/agents-md.ts +17 -0
  9. package/src/core/brief-lint.ts +9 -34
  10. package/src/core/config.ts +40 -2
  11. package/src/core/file-lock.ts +89 -0
  12. package/src/core/guards.ts +22 -6
  13. package/src/core/heavy-run.ts +37 -29
  14. package/src/core/host.ts +19 -0
  15. package/src/core/machine-guard.ts +5 -2
  16. package/src/core/main-start.ts +4 -1
  17. package/src/core/queue/lib.ts +21 -1
  18. package/src/core/queue-close.ts +5 -3
  19. package/src/core/quota-reset.ts +112 -0
  20. package/src/core/subagents.ts +83 -0
  21. package/src/core/tmp-snapshot.ts +26 -14
  22. package/src/core/uninstall.ts +228 -0
  23. package/templates/agents/example.md +32 -0
  24. package/templates/config.yml +27 -27
  25. package/templates/help/agent-score.txt +2 -2
  26. package/templates/help/brief-lint.txt +1 -1
  27. package/templates/help/uninstall.txt +14 -0
  28. package/templates/help/wip-backup.txt +14 -8
  29. package/templates/help/wip-check.txt +1 -1
  30. package/templates/help/wip-snapshot.txt +3 -2
  31. package/templates/machine-guard.sh +57 -16
  32. package/templates/notes/subagents.md +1 -11
  33. package/templates/queue/TEMPLATE.md +1 -1
  34. package/templates/tmp-snapshot.sh +21 -12
  35. package/bin/pm-fail-facts +0 -6
  36. package/src/adapters/omp/herdr-agent-state.ts +0 -440
  37. package/src/core/glm-reset.ts +0 -32
  38. package/src/core/pm-fail-facts.ts +0 -116
  39. package/templates/agents/apodex.md +0 -6
  40. package/templates/agents/bunny-user.md +0 -13
  41. package/templates/agents/bunny.md +0 -213
  42. package/templates/agents/composer.md +0 -9
  43. package/templates/agents/deepseek.md +0 -214
  44. package/templates/agents/gemini.md +0 -213
  45. package/templates/agents/glm.md +0 -214
  46. package/templates/agents/grok.md +0 -213
  47. package/templates/agents/haiku.md +0 -213
  48. package/templates/agents/hiko.md +0 -213
  49. package/templates/agents/ling.md +0 -213
  50. package/templates/agents/local-qwen.md +0 -220
  51. package/templates/agents/luna-medium.md +0 -211
  52. package/templates/agents/luna.md +0 -224
  53. package/templates/agents/muse.md +0 -214
  54. package/templates/agents/sol-xhigh.md +0 -217
  55. package/templates/agents/sol.md +0 -217
  56. package/templates/help/pm-fail-facts.txt +0 -6
  57. /package/bin/{glm-reset → quota-reset} +0 -0
package/README.md CHANGED
@@ -36,6 +36,7 @@ flowchart LR
36
36
  ## Requirements
37
37
 
38
38
  - [Bun](https://bun.sh) 1.x
39
+ - Runs on Linux and macOS.
39
40
  - git
40
41
  - omp, for the guards and rollover (the command-line tools work without it)
41
42
 
@@ -46,11 +47,14 @@ bun add -g neurastream
46
47
  neurastream init
47
48
  neurastream adapter install omp
48
49
  neurastream doctor
50
+ neurastream uninstall --purge # the inverse: removes it all again
49
51
  ```
50
52
 
51
- `init` writes `~/.config/neurastream/config.yml` from the defaults in [docs/config.md](docs/config.md), plus an empty index, notes, the queue template, blocker wrappers, and the state directories. A second run changes nothing. `adapter install omp` links the extension (`~/.omp/agent/extensions` and `omp plugin link`). `doctor` exits 0 when the install matches the package.
53
+ `init` writes `~/.config/neurastream/config.yml` from the defaults in [docs/config.md](docs/config.md), plus an empty index, notes, the queue template, blocker wrappers, and the state directories. A second run changes nothing. `adapter install omp` links the extension (`~/.omp/agent/extensions` and `omp plugin link`). `doctor` exits 0 when the install matches the package. `uninstall` removes the installed bins, the plugin link, template-identical pins and the AGENTS.md block; `--purge` adds the config file and the agent-dir state. It prints the list first and refuses anything outside your HOME.
52
54
 
53
- The defaults are the author's setup (paths, the backup repo, provider names). Edit `config.yml` before relying on them. To try it without touching your real home, set `HOME=/tmp/neurastream-home-dev` first.
55
+ `init` also sets the subagent allow-list (`notes/subagents.md`, the `## Allowed` section). `neurastream init --allow a,b` adds those slugs on the first run and on later runs, and never removes one. Without `--allow`, a terminal run asks once: `Subagents allowed to spawn (comma-separated names, empty = none):`; a blank answer, or no terminal, leaves the list as it is. While the list is empty, init prints `no subagents allowed yet: neurastream agents allow <name>`. `neurastream agents list|allow|deny` changes it later. A slug must match `[a-z0-9-]+`; a bad one exits 2 and writes nothing.
56
+
57
+ The defaults are neutral (empty work roots, no backup remote, no default branch); set your own in `config.yml`. To try it without touching your real home, set `HOME=/tmp/neurastream-home-dev` first.
54
58
 
55
59
  Check the merged result:
56
60
 
@@ -58,7 +62,7 @@ Check the merged result:
58
62
  neurastream config --json
59
63
  ```
60
64
 
61
- Every tool is one program, selected by the name it was called with: `agent-score`, `agent-ledger`, `brief-lint`, `oc-run`, `wip-check`, `wip-backup`, `wip-snapshot`, `pm-fail-facts`, `main-health`, `queue-check`, `queue-close`, `queue-cancel`, `queue-trim`, `main-start`, `machine-guard`, `glm-reset`, `priority-watch`, `resource-alerts`, `tmp-snapshot`, `heavy-run`.
65
+ Every tool is one program, selected by the name it was called with: `agent-score`, `agent-ledger`, `brief-lint`, `oc-run`, `wip-check`, `wip-backup`, `wip-snapshot`, `main-health`, `queue-check`, `queue-close`, `queue-cancel`, `queue-trim`, `main-start`, `machine-guard`, `quota-reset`, `priority-watch`, `resource-alerts`, `tmp-snapshot`, `heavy-run`.
62
66
 
63
67
  ## Develop
64
68
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.1.23",
3
+ "version": "0.1.25",
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": ["ai-agents", "coding-agents", "orchestration", "guardrails", "omp", "bun", "cli"],
6
6
  "homepage": "https://github.com/umiddey/neurastream#readme",
@@ -34,7 +34,6 @@
34
34
  "wip-check": "bin/wip-check",
35
35
  "wip-backup": "bin/wip-backup",
36
36
  "wip-snapshot": "bin/wip-snapshot",
37
- "pm-fail-facts": "bin/pm-fail-facts",
38
37
  "main-health": "bin/main-health",
39
38
  "queue-check": "bin/queue-check",
40
39
  "queue-trim": "bin/queue-trim",
@@ -42,7 +41,7 @@
42
41
  "queue-cancel": "bin/queue-cancel",
43
42
  "main-start": "bin/main-start",
44
43
  "machine-guard": "bin/machine-guard",
45
- "glm-reset": "bin/glm-reset",
44
+ "quota-reset": "bin/quota-reset",
46
45
  "priority-watch": "bin/priority-watch",
47
46
  "resource-alerts": "bin/resource-alerts",
48
47
  "tmp-snapshot": "bin/tmp-snapshot",
@@ -135,6 +135,8 @@ export interface DoctorReport {
135
135
  ok: string[];
136
136
  problems: string[];
137
137
  warnings: string[];
138
+ /** Legacy config keys loadConfig renamed or dropped; informational, not problems. */
139
+ notices: string[];
138
140
  installed: string;
139
141
  registry: string | null;
140
142
  }
@@ -172,7 +174,8 @@ export function doctorReport(home: string, env: NodeJS.ProcessEnv = process.env)
172
174
  }
173
175
  const agents = liveAgentsMd(home);
174
176
  const text = existsSync(agents) ? readFileSync(agents, "utf8") : "";
175
- const state = blockState(text, renderBlock(loadConfig({ home, env })));
177
+ const cfg = loadConfig({ home, env });
178
+ const state = blockState(text, renderBlock(cfg));
176
179
  if (state === "ok") ok.push(`${agents} neurastream block`);
177
180
  else problems.push(`${state}: ${agents} neurastream block`);
178
181
  const warnings: string[] = [];
@@ -183,7 +186,7 @@ export function doctorReport(home: string, env: NodeJS.ProcessEnv = process.env)
183
186
  registry = viewed.version;
184
187
  if (registry !== installed) problems.push(`stale version: installed ${installed}, registry ${registry}`);
185
188
  }
186
- return { ok, problems, warnings, installed, registry };
189
+ return { ok, problems, warnings, installed, registry, notices: cfg.notices };
187
190
  }
188
191
 
189
192
  export function formatDoctor(report: DoctorReport): string {
@@ -191,6 +194,7 @@ export function formatDoctor(report: DoctorReport): string {
191
194
  if (report.problems.length === 0) lines.push("neurastream doctor: ok");
192
195
  else lines.push(`neurastream doctor: ${report.problems.length} problem(s)`);
193
196
  for (const p of report.problems) lines.push(p);
197
+ for (const n of report.notices) lines.push(`notice: ${n}`);
194
198
  lines.push(`installed ${report.installed}`);
195
199
  if (report.registry !== null) lines.push(`registry ${report.registry}`);
196
200
  for (const w of report.warnings) lines.push(`warning: ${w}`);
@@ -1,6 +1,6 @@
1
1
  // omp adapter: one extension translating the harness events the originals used into the core
2
2
  // guard calls (src/core/guards.ts), plus the auto-close scheduler from main-guard. The harness
3
- // name appears only here and in herdr-agent-state.ts; core never imports this file.
3
+ // name appears only here; core never imports this file.
4
4
  //
5
5
  // Event map (docs/adapter.md, docs/inventory.md):
6
6
  // session_start (main only) auto-close now + every queue.auto_close_min minutes
@@ -33,7 +33,7 @@ import * as q from "../../core/queue/lib.ts";
33
33
  // Registers the plugin-command matcher into core's writeTargets (side effect).
34
34
  import "./package-ops.ts";
35
35
 
36
- /** Subset of the harness extension host the adapter needs (pi.on; herdr also uses pi.events). */
36
+ /** Subset of the harness extension host the adapter needs. */
37
37
  export interface ExtensionHost {
38
38
  on(event: string, cb: (...args: unknown[]) => unknown): void;
39
39
  registerCommand(name: string, opts: { description?: string; handler: (args: unknown, ctx: unknown) => unknown }): void;
@@ -128,7 +128,7 @@ function mainDetectors(cfg: Config, extra: { prompt?: string; bash?: { command:
128
128
  }
129
129
  }
130
130
 
131
- // Background queue-close for every plan Main marked complete (owner 2026-10-15). Ported from the
131
+ // Background queue-close for every plan Main marked complete. Ported from the
132
132
  // original autoClose: same filter, same "--- auto-close attempt" log line, detached child with
133
133
  // stdio on the per-plan close log. QUEUE_CLOSE_BIN overrides the binary (tests); without it the
134
134
  // package's own executable bin/queue-close runs (its `#!/usr/bin/env bun` shebang picks bun).
@@ -1,13 +1,12 @@
1
1
  import { agentLedger } from "../core/agent-ledger.ts";
2
2
  import { agentScore } from "../core/agent-score.ts";
3
3
  import { briefLint } from "../core/brief-lint.ts";
4
- import { glmReset } from "../core/glm-reset.ts";
4
+ import { quotaReset } from "../core/quota-reset.ts";
5
5
  import { heavyRun } from "../core/heavy-run.ts";
6
6
  import { mainHealth } from "../core/main-health.ts";
7
7
  import { mainStart } from "../core/main-start.ts";
8
8
  import { machineGuard } from "../core/machine-guard.ts";
9
9
  import { ocRun } from "../core/oc-run.ts";
10
- import { pmFailFacts } from "../core/pm-fail-facts.ts";
11
10
  import { priorityWatch } from "../core/priority-watch.ts";
12
11
  import { queueCancel } from "../core/queue-cancel.ts";
13
12
  import { queueCheck } from "../core/queue-check.ts";
@@ -30,7 +29,6 @@ export const PORTED = [
30
29
  "wip-check",
31
30
  "wip-backup",
32
31
  "wip-snapshot",
33
- "pm-fail-facts",
34
32
  "main-health",
35
33
  "queue-check",
36
34
  "queue-trim",
@@ -38,7 +36,7 @@ export const PORTED = [
38
36
  "queue-cancel",
39
37
  "main-start",
40
38
  "machine-guard",
41
- "glm-reset",
39
+ "quota-reset",
42
40
  "priority-watch",
43
41
  "resource-alerts",
44
42
  "tmp-snapshot",
@@ -66,8 +64,6 @@ export async function runPorted(cmd: string, args: string[]): Promise<number> {
66
64
  return wipBackup(args, rt.cfg);
67
65
  case "wip-snapshot":
68
66
  return wipSnapshot(args, rt.cfg);
69
- case "pm-fail-facts":
70
- return pmFailFacts(args, rt.cfg);
71
67
  case "main-health":
72
68
  return mainHealth(args, rt.cfg, rt.source);
73
69
  case "queue-check":
@@ -82,8 +78,8 @@ export async function runPorted(cmd: string, args: string[]): Promise<number> {
82
78
  return mainStart(args, rt.cfg, { source: defaultRunSource(rt.cfg), results: defaultCompletedResults(rt.cfg) });
83
79
  case "machine-guard":
84
80
  return machineGuard(args, rt.cfg);
85
- case "glm-reset":
86
- return glmReset(args, rt.cfg);
81
+ case "quota-reset":
82
+ return quotaReset(args, rt.cfg);
87
83
  case "priority-watch":
88
84
  return priorityWatch(args, rt.cfg);
89
85
  case "resource-alerts":
@@ -7,6 +7,9 @@ import { runInit } from "./init.ts";
7
7
  import { PORTED, runMain, runPorted } from "./commands.ts";
8
8
  import { runMetrics } from "./metrics.ts";
9
9
  import { runIncident } from "./incident.ts";
10
+ import { runUninstall } from "../core/uninstall.ts";
11
+ import { allowedAgents, subagentsPath } from "../core/queue/lib.ts";
12
+ import { allowAgents, denyAgents, invalidSlugs } from "../core/subagents.ts";
10
13
 
11
14
  const BINS = [
12
15
  "agent-score",
@@ -16,7 +19,6 @@ const BINS = [
16
19
  "wip-check",
17
20
  "wip-backup",
18
21
  "wip-snapshot",
19
- "pm-fail-facts",
20
22
  "main-health",
21
23
  "queue-check",
22
24
  "queue-trim",
@@ -24,7 +26,7 @@ const BINS = [
24
26
  "queue-cancel",
25
27
  "main-start",
26
28
  "machine-guard",
27
- "glm-reset",
29
+ "quota-reset",
28
30
  "priority-watch",
29
31
  "resource-alerts",
30
32
  "tmp-snapshot",
@@ -37,11 +39,16 @@ export function helpText(): string {
37
39
  "",
38
40
  "Usage:",
39
41
  " neurastream --help",
40
- " neurastream init [--agent-dir <dir>]",
42
+ " neurastream init [--agent-dir <dir>] [--allow a,b]",
41
43
  " create config, index, notes, blockers, queue template, state dirs",
42
44
  " (--agent-dir: keep an existing index/notes/blockers dir)",
45
+ " (--allow a,b: subagents allowed to spawn; on a terminal init asks instead)",
43
46
  " neurastream adapter install omp",
44
47
  " link the omp extension under this HOME",
48
+ " neurastream uninstall [--purge] [--yes]",
49
+ " inverse of init/install: removes our bins, the plugin link,",
50
+ " template-identical pins and the AGENTS.md block (--purge adds",
51
+ " config + agent-dir state); prints the list, refuses outside HOME",
45
52
  " neurastream doctor report hand-edited live files and a stale install",
46
53
  " neurastream config [--json] print the merged config (defaults + file + env)",
47
54
  " neurastream guard <event> --json",
@@ -49,6 +56,8 @@ export function helpText(): string {
49
56
  " neurastream main [args] run omp under the launcher (automatic session rollover)",
50
57
  " neurastream metrics <cmd> self-metrics: report, ci, false-alarm, rule (see README)",
51
58
  " neurastream incident <cmd> incidents Main must act on: list, add, plan, dismiss (see README)",
59
+ " neurastream agents list | allow <slug>... | deny <slug>...",
60
+ " the subagent allow-list (## Allowed in notes/subagents.md)",
52
61
  "",
53
62
  "Compatibility bins (same names as today; ports land in later phases):",
54
63
  ...BINS.map(b => ` ${b}`),
@@ -79,9 +88,11 @@ export async function run(cmd: string, args: string[]): Promise<number> {
79
88
  }
80
89
  }
81
90
  if (cmd === "doctor") return runDoctor();
91
+ if (cmd === "uninstall") return runUninstall(args);
82
92
  if (cmd === "guard") {
83
93
  return runGuard(args[0] ?? "");
84
94
  }
95
+ if (cmd === "agents") return runAgents(args);
85
96
  if ((PORTED as readonly string[]).includes(cmd)) {
86
97
  try {
87
98
  applyQueueEnv(loadConfig());
@@ -94,3 +105,45 @@ export async function run(cmd: string, args: string[]): Promise<number> {
94
105
  console.error(`unknown command ${cmd}\n${helpText()}`);
95
106
  return 2;
96
107
  }
108
+
109
+ const AGENTS_USAGE = "usage: neurastream agents list | allow <slug>... | deny <slug>...";
110
+
111
+ function runAgents(args: string[]): number {
112
+ const [action, ...slugs] = args;
113
+ if (action !== "list" && action !== "allow" && action !== "deny") {
114
+ console.error(AGENTS_USAGE);
115
+ return 2;
116
+ }
117
+ if (action !== "list" && slugs.length === 0) {
118
+ console.error(AGENTS_USAGE);
119
+ return 2;
120
+ }
121
+ const bad = invalidSlugs(slugs);
122
+ if (bad.length) {
123
+ console.error(`invalid slug: ${bad.join(", ")} (allowed: a-z, 0-9, -)`);
124
+ return 2;
125
+ }
126
+ try {
127
+ applyQueueEnv(loadConfig());
128
+ } catch (err) {
129
+ console.error(err instanceof ConfigError ? err.message : String(err));
130
+ return 1;
131
+ }
132
+ const file = subagentsPath();
133
+ if (action === "list") {
134
+ for (const slug of allowedAgents(file)) console.log(slug);
135
+ console.log(`file: ${file}`);
136
+ return 0;
137
+ }
138
+ if (action === "allow") {
139
+ const { added, kept } = allowAgents(file, slugs);
140
+ for (const slug of added) console.log(`allowed: ${slug}`);
141
+ for (const slug of kept) console.log(`already allowed: ${slug}`);
142
+ } else {
143
+ const { removed, absent } = denyAgents(file, slugs);
144
+ for (const slug of removed) console.log(`removed: ${slug}`);
145
+ for (const slug of absent) console.log(`not listed: ${slug}`);
146
+ }
147
+ console.log(`file: ${file}`);
148
+ return 0;
149
+ }
package/src/cli/init.ts CHANGED
@@ -2,11 +2,13 @@
2
2
  // and rewrites nothing (docs/config.md). Paths come from the loaded config, not literals in core.
3
3
 
4
4
  import { createHash } from "node:crypto";
5
- import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, writeFileSync } from "node:fs";
5
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, readSync, writeFileSync } from "node:fs";
6
6
  import { homedir } from "node:os";
7
7
  import { dirname, join, relative, resolve } from "node:path";
8
8
  import { fileURLToPath } from "node:url";
9
9
  import { configFile, loadConfig, TEMPLATE_PATH, type Config } from "../core/config.ts";
10
+ import { allowedAgents } from "../core/queue/lib.ts";
11
+ import { allowAgents, invalidSlugs, InvalidSlugError } from "../core/subagents.ts";
10
12
 
11
13
  const HERE = dirname(fileURLToPath(import.meta.url));
12
14
  export const PACKAGE_ROOT = resolve(HERE, "../..");
@@ -21,6 +23,7 @@ const BLOCKERS: { name: string; fn: string }[] = [
21
23
  export interface InitResult {
22
24
  created: string[];
23
25
  unchanged: string[];
26
+ allowed: string[];
24
27
  }
25
28
 
26
29
  function tilde(home: string, p: string): string {
@@ -59,10 +62,6 @@ const AGENT_DIR_KEYS = /^( (?:agent_dir|queue_index|blockers|notes|ranking_boar
59
62
  function configText(home: string, invoked: string, agentDir?: string): string {
60
63
  let text = readFileSync(TEMPLATE_PATH, "utf8");
61
64
  if (!text.endsWith("\n")) text += "\n";
62
- if (existsSync(join(home, "Work", "pm-counts"))) {
63
- if (!text.includes('default_repo: ""')) throw new Error("templates/config.yml has no default_repo placeholder");
64
- text = text.replace('default_repo: ""', 'default_repo: "~/Work/pm-counts"');
65
- }
66
65
  // An existing machine keeps its index, notes, blockers and unlock where they are today.
67
66
  const agent = agentDir ? tilde(home, resolve(home, agentDir.replace(/^~(?=\/|$)/, home))) : "~/.config/neurastream";
68
67
  if (agentDir) {
@@ -106,10 +105,14 @@ Empty until \`agent-score board\` writes this file. Do not hand-edit after that.
106
105
  `;
107
106
 
108
107
  /** Create the layout. Existing files are left byte-for-byte alone. */
109
- export function initHome(home: string, opts: { invoked?: string; env?: NodeJS.ProcessEnv; agentDir?: string } = {}): InitResult {
108
+ export function initHome(home: string, opts: { invoked?: string; env?: NodeJS.ProcessEnv; agentDir?: string; allow?: string[]; ask?: () => string } = {}): InitResult {
110
109
  const created: string[] = [];
111
110
  const unchanged: string[] = [];
112
111
  const invoked = opts.invoked ?? "";
112
+ // The allow-list is settled before anything is written, so a bad slug leaves no trace.
113
+ const slugs = opts.allow ?? (opts.ask ? opts.ask().split(",").map(s => s.trim()).filter(s => s !== "") : undefined);
114
+ const bad = invalidSlugs(slugs ?? []);
115
+ if (bad.length) throw new InvalidSlugError(`invalid slug: ${bad.join(", ")} (use a-z, 0-9 and -)`);
113
116
  const cfgPath = configFile(home);
114
117
  putFile(cfgPath, configText(home, invoked, opts.agentDir), 0o644, created, unchanged);
115
118
 
@@ -142,29 +145,46 @@ export function initHome(home: string, opts: { invoked?: string; env?: NodeJS.Pr
142
145
  for (const b of BLOCKERS) {
143
146
  putFile(join(cfg.paths.blockers, b.name), blockerWrapper(b.fn), 0o755, created, unchanged);
144
147
  }
145
- return { created, unchanged };
148
+ if (slugs?.length) allowAgents(cfg.paths.subagents, slugs);
149
+ return { created, unchanged, allowed: [...allowedAgents(cfg.paths.subagents)] };
146
150
  }
147
151
 
148
152
  export function printInit(result: InitResult): void {
149
153
  if (result.created.length === 0) {
150
154
  console.log("neurastream init: unchanged");
151
- return;
155
+ } else {
156
+ console.log("neurastream init: created");
157
+ for (const p of result.created) console.log(` ${p}`);
158
+ if (result.unchanged.length) console.log(`neurastream init: left ${result.unchanged.length} existing file(s) alone`);
152
159
  }
153
- console.log("neurastream init: created");
154
- for (const p of result.created) console.log(` ${p}`);
155
- if (result.unchanged.length) console.log(`neurastream init: left ${result.unchanged.length} existing file(s) alone`);
160
+ if (result.allowed.length === 0) console.log("no subagents allowed yet: neurastream agents allow <name>");
161
+ }
162
+
163
+ /** One line from stdin, read synchronously; a terminal hands over a line at a time. */
164
+ function askLine(prompt: string): string {
165
+ process.stdout.write(prompt);
166
+ const buf = Buffer.alloc(4096);
167
+ const n = readSync(0, buf, 0, buf.length, null);
168
+ return buf.toString("utf8", 0, n).split(/\r?\n/)[0] ?? "";
156
169
  }
157
170
 
158
171
  export function runInit(args: string[] = []): number {
159
172
  try {
160
173
  const i = args.indexOf("--agent-dir");
161
174
  const agentDir = i >= 0 ? args[i + 1] : undefined;
162
- if (i >= 0 && !agentDir) throw new Error("usage: neurastream init [--agent-dir <dir>]");
163
- printInit(initHome(homedir(), { invoked: process.argv[1] ?? "", env: process.env, agentDir }));
175
+ const a = args.indexOf("--allow");
176
+ const allowArg = a >= 0 ? args[a + 1] : undefined;
177
+ if ((i >= 0 && !agentDir) || (a >= 0 && allowArg === undefined)) {
178
+ throw new Error("usage: neurastream init [--agent-dir <dir>] [--allow a,b]");
179
+ }
180
+ const allow = allowArg?.split(",").map(s => s.trim()).filter(s => s !== "");
181
+ const interactive = allow === undefined && Boolean(process.stdin.isTTY && process.stdout.isTTY);
182
+ const ask = interactive ? () => askLine("Subagents allowed to spawn (comma-separated names, empty = none): ") : undefined;
183
+ printInit(initHome(homedir(), { invoked: process.argv[1] ?? "", env: process.env, agentDir, allow, ask }));
164
184
  return 0;
165
185
  } catch (err) {
166
186
  console.error(err instanceof Error ? err.message : String(err));
167
- return 1;
187
+ return err instanceof InvalidSlugError ? 2 : 1;
168
188
  }
169
189
  }
170
190
 
@@ -56,3 +56,20 @@ export function blockState(fileText: string, block: string): "ok" | "stale" | "m
56
56
  if (!at) return "missing";
57
57
  return fileText.slice(at.start, at.end) === block ? "ok" : "stale";
58
58
  }
59
+
60
+ // Remove the marked block, keeping every byte outside the markers (uninstall's inverse of
61
+ // upsertBlock). "missing": there was no block. "stale": the markers are malformed — the text
62
+ // comes back untouched.
63
+ export function stripBlock(fileText: string): { text: string; state: "ok" | "stale" | "missing" } {
64
+ let at: { start: number; end: number } | null;
65
+ try {
66
+ at = span(fileText);
67
+ } catch {
68
+ return { text: fileText, state: "stale" };
69
+ }
70
+ if (!at) return { text: fileText, state: "missing" };
71
+ let text = fileText.slice(0, at.start) + fileText.slice(at.end);
72
+ if (text.trim() === "") text = "";
73
+ else text = `${text.replace(/\n+$/, "")}\n`;
74
+ return { text, state: "ok" };
75
+ }
@@ -20,50 +20,25 @@ function lint(path: string, cfg: Config): { errs: string[]; warns: string[] } {
20
20
  if (!cond) errs.push(msg);
21
21
  };
22
22
 
23
- need(text.includes(cfg.brief.method_marker), `missing: 'Read ${cfg.brief.method_read} first'`);
23
+ // The method read is opt-in: only a config that sets brief.method_marker requires it.
24
+ if (cfg.brief.method_marker) need(text.includes(cfg.brief.method_marker), `missing: 'Read ${cfg.brief.method_read} first'`);
24
25
  need(
25
26
  /^#+[^\n]*(acceptance|done|report)|acceptance:|^done\s*=|^\d+\.\s*report\b/im.test(text),
26
27
  "missing: Acceptance/Done/Report section (observable result on the real target)",
27
28
  );
28
29
  need(/never push|no push|not push|never `?git push/.test(low), "missing: 'never push' line");
29
- need(low.includes("find") && low.includes("broken"), "missing: '`find` is broken: use grep/glob/read' note");
30
30
 
31
- const heavy = /pytest|vitest|playwright|run-raw|run-batch|full suite|\bsuite\b/.test(low);
31
+ const heavy = /pytest|vitest|playwright|full suite|\bsuite\b/.test(low);
32
32
  if (heavy) need(text.includes(cfg.brief.heavy_marker), `runs tests/suites but never names ${cfg.brief.heavy_path}`);
33
33
 
34
- const vitestLines = low.split(/\r?\n/).filter(l => l.includes("vitest") && !/not needed|no vitest/.test(l));
35
- if (vitestLines.length && /gateforge|witness|\bgf-/i.test(first)) {
36
- need(low.includes("typecheck"), "Gateforge green = vitest exit 0 AND `npm run typecheck` exit 0: typecheck missing");
34
+ // Repo-specific rules are config-driven (brief.repo_rules); the shipped default list is empty.
35
+ for (const rule of cfg.brief.repo_rules) {
36
+ if (!new RegExp(rule.match, "i").test(low)) continue;
37
+ if (rule.first && !new RegExp(rule.first, "i").test(first)) continue;
38
+ if (rule.unless && new RegExp(rule.unless, "i").test(first)) continue;
39
+ need(new RegExp(rule.require, "i").test(low), rule.message);
37
40
  }
38
41
 
39
- const planOnly = /plan only|read-only review|CI fix|\bdelete\b/i.test(first);
40
- if (low.includes("test-map") && !planOnly) {
41
- const m = text.match(/^Probe:\s*(\S+)/m);
42
- if (/^#+\s*probe first/im.test(text) && !m) {
43
- // the agent runs the probe itself and must stop on 0 satisfied
44
- } else if (!m) {
45
- errs.push("coverage batch without 'Probe: <log>' line: run ONE witnessed probe that SATISFIES its claims first (lesson 2026-10-10: 0/255)");
46
- } else if (!existsSync(m[1]!)) {
47
- errs.push(`Probe log does not exist: ${m[1]}`);
48
- } else if (!readFileSync(m[1]!, "utf8").toLowerCase().includes("satisfied")) {
49
- errs.push(`Probe log shows no 'satisfied' claim: ${m[1]}`);
50
- }
51
- }
52
-
53
- if (
54
- /aetherios-property-management|pm-pr01|\bPR01\b|contractor.portal|cp-/.test(text) &&
55
- !planOnly &&
56
- /test-map|obligation|gateforge check|coverage/.test(low)
57
- ) {
58
- need(
59
- /^Gate before:\s*\d+\s+missing/im.test(text),
60
- "PM/CP coverage brief without 'Gate before: <N> missing' line from `gateforge check` (green tests are not progress)",
61
- );
62
- need(
63
- /gate missing.*before.*after|before\s*->\s*after/.test(low),
64
- "report must state gate missing before->after; a round that does not lower it stops",
65
- );
66
- }
67
42
 
68
43
  const paths = new Set<string>();
69
44
  for (const prefix of cfg.brief.path_prefixes) {
@@ -67,6 +67,10 @@ export interface Config {
67
67
  path_prefixes: string[];
68
68
  method_read: string;
69
69
  heavy_path: string;
70
+ /** Repo-specific brief rules; the shipped default list is empty. A rule fires when `match`
71
+ * (regex on the whole brief) hits and the body lacks `require`; optional `first`/`unless`
72
+ * gate the rule on the plan's title line. */
73
+ repo_rules: { match: string; require: string; message: string; first?: string; unless?: string }[];
70
74
  };
71
75
  oc: { model_prefix: string; tail_lines: number; tail_chars: number };
72
76
  wip: {
@@ -139,12 +143,14 @@ export interface Config {
139
143
  watch_sec: number;
140
144
  watch_streak: number;
141
145
  };
142
- glm: { reset_tz: string; label: string };
146
+ quota: { reset_tz: string; label: string };
143
147
  priority: { sleep_sec: number };
144
148
  alerts: { temp_c: number; mem_psi: number; io_psi: number; cooldown_sec: number };
145
149
  snapshot: { tmp_dest: string; git_repo: string; git_backup: string; excludes: string[] };
146
150
  /** Optional overlay written by adapter install. Absent until an adapter is installed. */
147
151
  adapter?: { name: string; sessions: string; pins: string; extensions: string };
152
+ /** Notices about legacy keys in the user's config file; empty when there are none. */
153
+ notices: string[];
148
154
  }
149
155
 
150
156
  type EnvKind = "string" | "number" | "csv";
@@ -283,6 +289,18 @@ function check(cfg: Config): void {
283
289
  throw new ConfigError(`metrics.correction_patterns: not a valid regex: ${p}`);
284
290
  }
285
291
  }
292
+ for (const rule of cfg.brief.repo_rules) {
293
+ for (const key of ["match", "require", "first", "unless"] as const) {
294
+ const pattern = rule[key];
295
+ if (pattern === undefined) continue;
296
+ try {
297
+ new RegExp(pattern, "i");
298
+ } catch {
299
+ throw new ConfigError(`brief.repo_rules.${key}: not a valid regex: ${pattern}`);
300
+ }
301
+ }
302
+ if (!rule.message) throw new ConfigError("brief.repo_rules.message must be a non-empty string");
303
+ }
286
304
  for (const [key, value] of Object.entries(cfg.paths)) {
287
305
  if (key === "work_roots") {
288
306
  if (!Array.isArray(value) || value.some(v => typeof v !== "string")) {
@@ -301,17 +319,37 @@ export interface LoadOptions {
301
319
  template?: string;
302
320
  }
303
321
 
322
+ // Old keys that still load, each with a notice to rename or delete it. "glm:" moves to "quota:" only
323
+ // when "quota:" is absent; with both present, "glm:" stays and fails as an unknown key.
324
+ function migrateLegacy(user: Record<string, unknown>, file: string, notices: string[]): Record<string, unknown> {
325
+ const out = { ...user };
326
+ if ("glm" in out && !("quota" in out)) {
327
+ out.quota = out.glm;
328
+ delete out.glm;
329
+ notices.push(`config "glm:" is now "quota:"; rename it in ${file}`);
330
+ }
331
+ if ("pm" in out) {
332
+ delete out.pm;
333
+ notices.push(`config "pm:" was removed; delete it from ${file}`);
334
+ }
335
+ return out;
336
+ }
337
+
304
338
  export function loadConfig(opts: LoadOptions = {}): Config {
305
339
  const home = opts.home ?? homedir();
306
340
  const template = parseYaml(readFileSync(opts.template ?? TEMPLATE_PATH, "utf8"), "defaults");
307
341
  const file = opts.file ?? configFile(home);
342
+ const notices: string[] = [];
308
343
  let merged: unknown = template;
309
344
  if (existsSync(file)) {
310
- merged = merge(template, parseYaml(readFileSync(file, "utf8"), file), "");
345
+ let user = parseYaml(readFileSync(file, "utf8"), file);
346
+ if (isObj(user)) user = migrateLegacy(user, file, notices);
347
+ merged = merge(template, user, "");
311
348
  }
312
349
  if (!isObj(merged)) throw new ConfigError("config must be an object");
313
350
  applyEnv(merged, opts.env ?? process.env);
314
351
  const expanded = expand(merged, home) as Config;
352
+ expanded.notices = notices;
315
353
  check(expanded);
316
354
  return expanded;
317
355
  }
@@ -0,0 +1,89 @@
1
+ import { closeSync, mkdirSync, openSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import { dlopen, FFIType, read, type Pointer } from "bun:ffi";
4
+
5
+ // flock(2) through libc, so the package needs no util-linux `flock` binary (macOS does not ship one).
6
+ const LOCK_EX = 2;
7
+ const LOCK_NB = 4;
8
+ const LOCK_UN = 8;
9
+ const EINTR = 4;
10
+ const EWOULDBLOCK = process.platform === "darwin" ? 35 : 11;
11
+
12
+ // errno is thread-local; __error (Darwin) and __errno_location (glibc) return its address.
13
+ const errnoFn = process.platform === "darwin" ? "__error" : "__errno_location";
14
+ const LIBC_NAME = process.platform === "darwin" ? "libc.dylib" : "libc.so.6";
15
+
16
+ /** The libc symbols this module calls. */
17
+ export interface LibcSymbols {
18
+ flock(fd: number, op: number): number;
19
+ [symbol: string]: unknown;
20
+ }
21
+
22
+ export interface Libc {
23
+ symbols: LibcSymbols;
24
+ }
25
+
26
+ // libc opens on first lock use, not at import: a failed load throws from the lock call, naming the
27
+ // library tried, instead of breaking every importer of this module.
28
+ let libcHandle: Libc | undefined;
29
+ function libc(): Libc {
30
+ if (libcHandle) return libcHandle;
31
+ try {
32
+ libcHandle = dlopen(LIBC_NAME, {
33
+ flock: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 },
34
+ [errnoFn]: { args: [], returns: FFIType.ptr },
35
+ });
36
+ return libcHandle;
37
+ } catch (e) {
38
+ throw new Error(`file-lock: cannot load ${LIBC_NAME}: ${(e as Error).message}`);
39
+ }
40
+ }
41
+
42
+ function errno(lib: Libc): number {
43
+ const ptr = (lib.symbols[errnoFn] as () => Pointer)();
44
+ return read.i32(ptr, 0);
45
+ }
46
+
47
+ export interface HeldLock {
48
+ release(): void;
49
+ }
50
+
51
+ function acquire(path: string, op: number): HeldLock | null {
52
+ const lib = libc();
53
+ mkdirSync(dirname(path), { recursive: true });
54
+ const fd = openSync(path, "a");
55
+ for (;;) {
56
+ if (lib.symbols.flock(fd, op) === 0) break;
57
+ const err = errno(lib);
58
+ if (err === EINTR) continue;
59
+ closeSync(fd);
60
+ if (err === EWOULDBLOCK && (op & LOCK_NB) !== 0) return null;
61
+ throw new Error(`flock(${path}) failed: errno ${err}`);
62
+ }
63
+ return {
64
+ release() {
65
+ lib.symbols.flock(fd, LOCK_UN);
66
+ closeSync(fd);
67
+ },
68
+ };
69
+ }
70
+
71
+ /** Non-blocking exclusive lock; null when another holder has it. */
72
+ export function tryLock(path: string): HeldLock | null {
73
+ return acquire(path, LOCK_EX | LOCK_NB);
74
+ }
75
+
76
+ /** Blocking exclusive lock; waits for the holder to release. */
77
+ export function lock(path: string): HeldLock {
78
+ const held = acquire(path, LOCK_EX);
79
+ if (!held) throw new Error(`could not lock ${path}`);
80
+ return held;
81
+ }
82
+
83
+ /** True when another open file description holds the lock right now. */
84
+ export function isBusy(path: string): boolean {
85
+ const held = tryLock(path);
86
+ if (!held) return true;
87
+ held.release();
88
+ return false;
89
+ }