neurastream 0.1.22 → 0.1.24

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 (39) hide show
  1. package/README.md +13 -3
  2. package/package.json +1 -1
  3. package/src/adapters/omp/doctor.ts +15 -3
  4. package/src/adapters/omp/install.ts +18 -3
  5. package/src/cli/dispatch.ts +6 -0
  6. package/src/cli/init.ts +0 -4
  7. package/src/core/agents-md.ts +75 -0
  8. package/src/core/brief-lint.ts +6 -18
  9. package/src/core/config.ts +16 -0
  10. package/src/core/guards.ts +2 -1
  11. package/src/core/uninstall.ts +228 -0
  12. package/templates/AGENTS.md +27 -0
  13. package/templates/agents/example.md +32 -0
  14. package/templates/config.yml +23 -18
  15. package/templates/help/agent-score.txt +1 -1
  16. package/templates/help/pm-fail-facts.txt +1 -1
  17. package/templates/help/uninstall.txt +14 -0
  18. package/templates/help/wip-backup.txt +14 -8
  19. package/templates/help/wip-snapshot.txt +2 -1
  20. package/templates/notes/subagents.md +1 -11
  21. package/templates/queue/TEMPLATE.md +1 -1
  22. package/templates/tmp-snapshot.sh +9 -6
  23. package/templates/agents/apodex.md +0 -6
  24. package/templates/agents/bunny-user.md +0 -13
  25. package/templates/agents/bunny.md +0 -213
  26. package/templates/agents/composer.md +0 -9
  27. package/templates/agents/deepseek.md +0 -214
  28. package/templates/agents/gemini.md +0 -213
  29. package/templates/agents/glm.md +0 -214
  30. package/templates/agents/grok.md +0 -213
  31. package/templates/agents/haiku.md +0 -213
  32. package/templates/agents/hiko.md +0 -213
  33. package/templates/agents/ling.md +0 -213
  34. package/templates/agents/local-qwen.md +0 -220
  35. package/templates/agents/luna-medium.md +0 -211
  36. package/templates/agents/luna.md +0 -224
  37. package/templates/agents/muse.md +0 -214
  38. package/templates/agents/sol-xhigh.md +0 -217
  39. package/templates/agents/sol.md +0 -217
package/README.md CHANGED
@@ -46,11 +46,12 @@ bun add -g neurastream
46
46
  neurastream init
47
47
  neurastream adapter install omp
48
48
  neurastream doctor
49
+ neurastream uninstall --purge # the inverse: removes it all again
49
50
  ```
50
51
 
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.
52
+ `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
53
 
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.
54
+ 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
55
 
55
56
  Check the merged result:
56
57
 
@@ -147,7 +148,16 @@ bun add -g neurastream@latest
147
148
  neurastream adapter install omp
148
149
  ```
149
150
 
150
- Live copies are never hand-edited. `neurastream doctor` names each hand-edited or foreign installed file, and a stale install (the installed version is not `npm view neurastream version`). If the registry cannot be reached, that check is a warning, not a failure.
151
+ Live copies are never hand-edited. `neurastream doctor` names each hand-edited installed file and each missing one (`missing:`), and a stale install (the installed version is not `npm view neurastream version`). If the registry cannot be reached, that check is a warning, not a failure.
152
+
153
+ ## AGENTS.md block
154
+
155
+ `adapter install omp` writes the neurastream orchestrator rules into `~/.omp/agent/AGENTS.md`, between the markers `<!-- neurastream:begin (managed by neurastream; edit the package, not this block) -->` and `<!-- neurastream:end -->`. The rules come from `templates/AGENTS.md`; the agent dir comes from your config.
156
+
157
+ - Managed: the text between the markers. Install replaces it. A second install changes nothing.
158
+ - Yours: every line outside the markers. Install keeps it byte for byte. A file with no markers gets the block appended.
159
+ - Drift: `neurastream doctor` reports `stale:` when the text between the markers differs from the package's block, and `missing:` when the markers are absent. Edits outside the markers are never reported.
160
+ - Edit limit: the project-file changes Main gets per window come from `guards.main_edit_limit` and `guards.main_window_min`, not from the block text.
151
161
 
152
162
  ## License
153
163
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.1.22",
3
+ "version": "0.1.24",
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",
@@ -1,5 +1,5 @@
1
- // Reports hand-edited or foreign live files the omp adapter installs, and a stale
2
- // registry version. Offline `npm view` is a warning, not a failure.
1
+ // Reports hand-edited or missing live files the omp adapter installs, the managed block in
2
+ // the owner's AGENTS.md, and a stale registry version. Offline `npm view` is a warning, not a failure.
3
3
  // Notes, INDEX, queue state and config are user state: not checked.
4
4
 
5
5
  import { spawnSync } from "node:child_process";
@@ -7,6 +7,8 @@ import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync } from "
7
7
  import { homedir } from "node:os";
8
8
  import { dirname, join, relative, resolve } from "node:path";
9
9
  import { fileURLToPath } from "node:url";
10
+ import { blockState, renderBlock } from "../../core/agents-md.ts";
11
+ import { loadConfig } from "../../core/config.ts";
10
12
 
11
13
  const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
12
14
 
@@ -30,6 +32,11 @@ export function packageBins(root: string): { name: string; source: string }[] {
30
32
  return Object.entries(pkg.bin ?? {}).map(([name, rel]) => ({ name, source: join(root, rel) }));
31
33
  }
32
34
 
35
+ /** The omp agent's AGENTS.md, which carries the managed neurastream block. */
36
+ export function liveAgentsMd(home: string): string {
37
+ return join(home, ".omp/agent/AGENTS.md");
38
+ }
39
+
33
40
  /** Files adapter install places under this home. Bun's global bin dir is extra, checked only when a name is present. */
34
41
  export function adapterLiveFiles(home: string, root: string = PACKAGE_ROOT): LiveFile[] {
35
42
  const files: LiveFile[] = [];
@@ -154,7 +161,7 @@ export function doctorReport(home: string, env: NodeJS.ProcessEnv = process.env)
154
161
  if (seen.has(file.live)) continue;
155
162
  seen.add(file.live);
156
163
  if (!existsSync(file.live)) {
157
- problems.push(`foreign: ${file.live}`);
164
+ problems.push(`missing: ${file.live}`);
158
165
  continue;
159
166
  }
160
167
  if (isPackageFile(file.live, file.source)) {
@@ -163,6 +170,11 @@ export function doctorReport(home: string, env: NodeJS.ProcessEnv = process.env)
163
170
  }
164
171
  problems.push(`hand-edited: ${file.live}`);
165
172
  }
173
+ const agents = liveAgentsMd(home);
174
+ const text = existsSync(agents) ? readFileSync(agents, "utf8") : "";
175
+ const state = blockState(text, renderBlock(loadConfig({ home, env })));
176
+ if (state === "ok") ok.push(`${agents} neurastream block`);
177
+ else problems.push(`${state}: ${agents} neurastream block`);
166
178
  const warnings: string[] = [];
167
179
  const viewed = npmViewVersion(name, env);
168
180
  let registry: string | null = null;
@@ -6,9 +6,10 @@ import { copyFileSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSy
6
6
  import { homedir } from "node:os";
7
7
  import { dirname, join, resolve } from "node:path";
8
8
  import { fileURLToPath } from "node:url";
9
- import { configFile } from "../../core/config.ts";
9
+ import { renderBlock, upsertBlock } from "../../core/agents-md.ts";
10
+ import { configFile, loadConfig } from "../../core/config.ts";
10
11
 
11
- import { adapterLiveFiles } from "./doctor.ts";
12
+ import { adapterLiveFiles, liveAgentsMd } from "./doctor.ts";
12
13
  // Registers the plugin-command matcher into core's writeTargets (side effect).
13
14
  import "./package-ops.ts";
14
15
  const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
@@ -31,6 +32,7 @@ export interface InstallResult {
31
32
  pinsCopied: string[];
32
33
  pinsKept: string[];
33
34
  overlay: "written" | "unchanged";
35
+ agentsMd: "written" | "unchanged";
34
36
  }
35
37
 
36
38
  function ensureLink(link: string, target: string): void {
@@ -101,6 +103,17 @@ function writeOverlay(file: string): "written" | "unchanged" {
101
103
  return "written";
102
104
  }
103
105
 
106
+ // Writes the managed block into the owner's AGENTS.md: the rest of the file is never touched.
107
+ function writeAgentsMd(home: string): "written" | "unchanged" {
108
+ const file = liveAgentsMd(home);
109
+ const current = existsSync(file) ? readFileSync(file, "utf8") : "";
110
+ const next = upsertBlock(current, renderBlock(loadConfig({ home })));
111
+ if (next === current) return "unchanged";
112
+ mkdirSync(dirname(file), { recursive: true });
113
+ writeFileSync(file, next);
114
+ return "written";
115
+ }
116
+
104
117
  function linkPlugin(home: string): string {
105
118
  const r = spawnSync("omp", ["plugin", "link", PACKAGE_ROOT], {
106
119
  env: { ...process.env, HOME: home },
@@ -141,7 +154,8 @@ export function installOmp(home: string): InstallResult {
141
154
  linkInstalled(home);
142
155
  const plugin = linkPlugin(home);
143
156
  const overlay = writeOverlay(file);
144
- return { plugin, removedStaleLink, pinsCopied: pins.copied, pinsKept: pins.kept, overlay };
157
+ const agentsMd = writeAgentsMd(home);
158
+ return { plugin, removedStaleLink, pinsCopied: pins.copied, pinsKept: pins.kept, overlay, agentsMd };
145
159
  }
146
160
 
147
161
  export function printInstall(result: InstallResult): void {
@@ -150,6 +164,7 @@ export function printInstall(result: InstallResult): void {
150
164
  console.log(
151
165
  `neurastream adapter install omp: pins copied ${result.pinsCopied.length}, kept ${result.pinsKept.length}; overlay ${result.overlay}`,
152
166
  );
167
+ console.log(`neurastream adapter install omp: AGENTS.md block ${result.agentsMd}`);
153
168
  }
154
169
 
155
170
  export function runAdapterInstall(args: string[]): number {
@@ -7,6 +7,7 @@ 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";
10
11
 
11
12
  const BINS = [
12
13
  "agent-score",
@@ -42,6 +43,10 @@ export function helpText(): string {
42
43
  " (--agent-dir: keep an existing index/notes/blockers dir)",
43
44
  " neurastream adapter install omp",
44
45
  " link the omp extension under this HOME",
46
+ " neurastream uninstall [--purge] [--yes]",
47
+ " inverse of init/install: removes our bins, the plugin link,",
48
+ " template-identical pins and the AGENTS.md block (--purge adds",
49
+ " config + agent-dir state); prints the list, refuses outside HOME",
45
50
  " neurastream doctor report hand-edited live files and a stale install",
46
51
  " neurastream config [--json] print the merged config (defaults + file + env)",
47
52
  " neurastream guard <event> --json",
@@ -79,6 +84,7 @@ export async function run(cmd: string, args: string[]): Promise<number> {
79
84
  }
80
85
  }
81
86
  if (cmd === "doctor") return runDoctor();
87
+ if (cmd === "uninstall") return runUninstall(args);
82
88
  if (cmd === "guard") {
83
89
  return runGuard(args[0] ?? "");
84
90
  }
package/src/cli/init.ts CHANGED
@@ -59,10 +59,6 @@ const AGENT_DIR_KEYS = /^( (?:agent_dir|queue_index|blockers|notes|ranking_boar
59
59
  function configText(home: string, invoked: string, agentDir?: string): string {
60
60
  let text = readFileSync(TEMPLATE_PATH, "utf8");
61
61
  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
62
  // An existing machine keeps its index, notes, blockers and unlock where they are today.
67
63
  const agent = agentDir ? tilde(home, resolve(home, agentDir.replace(/^~(?=\/|$)/, home))) : "~/.config/neurastream";
68
64
  if (agentDir) {
@@ -0,0 +1,75 @@
1
+ // The managed block in the owner's AGENTS.md. The rules come from templates/AGENTS.md with the
2
+ // config's agent dir filled in; they sit between two markers, and only what is between them is
3
+ // ever written or checked against the package's block. Everything outside the markers stays the owner's.
4
+
5
+ import { readFileSync } from "node:fs";
6
+ import { dirname, join } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import type { Config } from "./config.ts";
9
+
10
+ const HERE = dirname(fileURLToPath(import.meta.url));
11
+ export const AGENTS_TEMPLATE = join(HERE, "../../templates/AGENTS.md");
12
+ export const BEGIN_MARK = "<!-- neurastream:begin (managed by neurastream; edit the package, not this block) -->";
13
+ export const END_MARK = "<!-- neurastream:end -->";
14
+
15
+ export function renderBlock(cfg: Config, template: string = readFileSync(AGENTS_TEMPLATE, "utf8")): string {
16
+ const body = template.trimEnd().split("{{AGENT_DIR}}").join(cfg.paths.agent_dir);
17
+ return `${BEGIN_MARK}\n${body}\n${END_MARK}`;
18
+ }
19
+
20
+ function occurrences(text: string, mark: string): number[] {
21
+ const at: number[] = [];
22
+ for (let i = text.indexOf(mark); i !== -1; i = text.indexOf(mark, i + mark.length)) at.push(i);
23
+ return at;
24
+ }
25
+
26
+ // The block's span in a file, or null when there are no markers. Anything other than exactly one
27
+ // begin marker followed by exactly one end marker is malformed and throws.
28
+ function span(text: string): { start: number; end: number } | null {
29
+ const begins = occurrences(text, BEGIN_MARK);
30
+ const ends = occurrences(text, END_MARK);
31
+ const begin = begins[0];
32
+ const end = ends[0];
33
+ if (begin === undefined && end === undefined) return null;
34
+ if (begins.length !== 1 || ends.length !== 1 || begin === undefined || end === undefined || end < begin) {
35
+ throw new Error("neurastream block markers malformed: expected one begin marker, then one end marker");
36
+ }
37
+ return { start: begin, end: end + END_MARK.length };
38
+ }
39
+
40
+ // Replace the marked block, or append one when the file has none. Bytes outside the markers are kept.
41
+ export function upsertBlock(fileText: string, block: string): string {
42
+ const at = span(fileText);
43
+ if (at) return fileText.slice(0, at.start) + block + fileText.slice(at.end);
44
+ if (fileText === "") return `${block}\n`;
45
+ return `${fileText}\n${block}\n`;
46
+ }
47
+
48
+ // "missing": no block in the file. "stale": the block differs, or its markers are malformed.
49
+ export function blockState(fileText: string, block: string): "ok" | "stale" | "missing" {
50
+ let at: { start: number; end: number } | null;
51
+ try {
52
+ at = span(fileText);
53
+ } catch {
54
+ return "stale";
55
+ }
56
+ if (!at) return "missing";
57
+ return fileText.slice(at.start, at.end) === block ? "ok" : "stale";
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
+ }
@@ -31,9 +31,12 @@ function lint(path: string, cfg: Config): { errs: string[]; warns: string[] } {
31
31
  const heavy = /pytest|vitest|playwright|run-raw|run-batch|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
42
  const planOnly = /plan only|read-only review|CI fix|\bdelete\b/i.test(first);
@@ -50,21 +53,6 @@ function lint(path: string, cfg: Config): { errs: string[]; warns: string[] } {
50
53
  }
51
54
  }
52
55
 
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
-
68
56
  const paths = new Set<string>();
69
57
  for (const prefix of cfg.brief.path_prefixes) {
70
58
  const re = new RegExp(`(${escapeReg(prefix)}[\\w./\\-]+)`, "g");
@@ -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: {
@@ -283,6 +287,18 @@ function check(cfg: Config): void {
283
287
  throw new ConfigError(`metrics.correction_patterns: not a valid regex: ${p}`);
284
288
  }
285
289
  }
290
+ for (const rule of cfg.brief.repo_rules) {
291
+ for (const key of ["match", "require", "first", "unless"] as const) {
292
+ const pattern = rule[key];
293
+ if (pattern === undefined) continue;
294
+ try {
295
+ new RegExp(pattern, "i");
296
+ } catch {
297
+ throw new ConfigError(`brief.repo_rules.${key}: not a valid regex: ${pattern}`);
298
+ }
299
+ }
300
+ if (!rule.message) throw new ConfigError("brief.repo_rules.message must be a non-empty string");
301
+ }
286
302
  for (const [key, value] of Object.entries(cfg.paths)) {
287
303
  if (key === "work_roots") {
288
304
  if (!Array.isArray(value) || value.some(v => typeof v !== "string")) {
@@ -572,10 +572,11 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
572
572
  const cancel = continuation ? "" : flagCancel(e.inject, cfg);
573
573
  const incidents = openIncidentList(cfg);
574
574
  const incidentText = incidents.length ? `\n${incidents.map(incidentLine).join("\n")}` : "";
575
+ const editLimit = continuation ? "" : `\nmain-guard: Main may change project files at most ${cfg.guards.main_edit_limit} times per ${cfg.guards.main_window_min}-minute window; then delegate.`;
575
576
  return {
576
577
  allow: true,
577
578
  reason: "",
578
- inject: `${summary}\n(main-guard: read ${q.INDEX} and the listed repo INDEX.md files are summarised above; work the open plans, close finished ones with queue-close.)${cancel}${incidentText}`,
579
+ inject: `${summary}\n(main-guard: read ${q.INDEX} and the listed repo INDEX.md files are summarised above; work the open plans, close finished ones with queue-close.)${editLimit}${cancel}${incidentText}`,
579
580
  ...(continuation ? {} : { state: { callsSinceStop: 0, idleStops: 0 } }),
580
581
  };
581
582
  }
@@ -0,0 +1,228 @@
1
+ // The inverse of init and adapter install. Pure core: it builds the exact removal list,
2
+ // prints it, and only removes with --yes. It never touches a file that is not provably
3
+ // this package's (a launcher symlink or copy into an installed copy, a template-identical
4
+ // pin, the managed AGENTS.md block, the adapter's plugin link), and it refuses every path that
5
+ // resolves outside the HOME it is given.
6
+
7
+ import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
8
+ import { homedir } from "node:os";
9
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+ import { stripBlock } from "./agents-md.ts";
12
+ import { configFile, loadConfig, type Config } from "./config.ts";
13
+ import { printText } from "./help.ts";
14
+
15
+ const HERE = dirname(fileURLToPath(import.meta.url));
16
+ const PACKAGE_ROOT = resolve(HERE, "../..");
17
+
18
+ interface PackageJson {
19
+ name?: string;
20
+ bin?: Record<string, string>;
21
+ }
22
+
23
+ export interface UninstallTarget {
24
+ path: string;
25
+ what: string;
26
+ /** AGENTS.md targets lose only the managed block; everything else is unlinked. */
27
+ strip?: boolean;
28
+ /** Directory trees (queue/, notes/, blockers/) come down recursively. */
29
+ tree?: boolean;
30
+ }
31
+
32
+ export interface UninstallPlan {
33
+ targets: UninstallTarget[];
34
+ /** Present but left alone: pins the owner edited, files that are not ours. */
35
+ kept: string[];
36
+ refusals: string[];
37
+ }
38
+
39
+ function pkgName(): string {
40
+ const pkg = JSON.parse(readFileSync(join(PACKAGE_ROOT, "package.json"), "utf8")) as PackageJson;
41
+ if (!pkg.name) throw new Error("package.json has no name");
42
+ return pkg.name;
43
+ }
44
+
45
+ /** The installed copy a path belongs to: the nearest dir whose package.json carries this package's name. */
46
+ function installedRootOf(file: string): string | null {
47
+ // `file` itself may be the root (the plugin link's realpath is an installed root).
48
+ let dir = file;
49
+ for (let i = 0; i < 9; i++) {
50
+ const manifest = join(dir, "package.json");
51
+ if (existsSync(manifest)) {
52
+ try {
53
+ const pkg = JSON.parse(readFileSync(manifest, "utf8")) as PackageJson;
54
+ if (pkg.name === pkgName()) return dir;
55
+ } catch {
56
+ return null;
57
+ }
58
+ }
59
+ const parent = dirname(dir);
60
+ if (parent === dir) break;
61
+ dir = parent;
62
+ }
63
+ return null;
64
+ }
65
+
66
+ /** A launcher is a symlink into an installed copy of this package at the same relative path; a copy is byte-identical. */
67
+ function ours(live: string, rel: string): boolean {
68
+ let st;
69
+ try {
70
+ st = lstatSync(live);
71
+ } catch {
72
+ return false;
73
+ }
74
+ if (st.isSymbolicLink()) {
75
+ let target: string;
76
+ try {
77
+ target = realpathSync(live);
78
+ } catch {
79
+ return false;
80
+ }
81
+ const root = installedRootOf(target);
82
+ return root !== null && target === resolve(root, rel);
83
+ }
84
+ if (!st.isFile()) return false;
85
+ try {
86
+ return readFileSync(live).equals(readFileSync(join(PACKAGE_ROOT, rel)));
87
+ } catch {
88
+ return false;
89
+ }
90
+ }
91
+
92
+ function bins(cfg: Config, out: UninstallTarget[]): void {
93
+ const manifest = JSON.parse(readFileSync(join(PACKAGE_ROOT, "package.json"), "utf8")) as PackageJson;
94
+ const dirs = [join(cfg.paths.home, ".local/bin"), join(cfg.paths.home, ".bun/bin")];
95
+ for (const name of Object.keys(manifest.bin ?? {})) {
96
+ for (const dir of dirs) {
97
+ const live = join(dir, name);
98
+ if (existsSync(live) && ours(live, manifest.bin![name]!)) {
99
+ out.push({ path: live, what: `bin ${name}` });
100
+ }
101
+ }
102
+ }
103
+ }
104
+
105
+ function adapterSurface(cfg: Config, out: UninstallTarget[], kept: string[]): void {
106
+ const adapter = cfg.adapter;
107
+ if (!adapter) return;
108
+ // The overlay is written by adapter install: sessions/pins/extensions all sit under the
109
+ // agent dir, the plugin link one level above it under plugins/node_modules/<package>.
110
+ const agentDir = dirname(dirname(adapter.extensions));
111
+ const plugin = join(agentDir, "plugins/node_modules/neurastream");
112
+ if (existsSync(plugin) && ours(plugin, ".")) out.push({ path: plugin, what: "plugin link" });
113
+
114
+ const pinsDir = adapter.pins;
115
+ if (existsSync(pinsDir)) {
116
+ const shipped = join(PACKAGE_ROOT, "templates/agents");
117
+ for (const name of readdirSync(pinsDir).sort()) {
118
+ if (!name.endsWith(".md") || name.includes(".bak")) continue;
119
+ const live = join(pinsDir, name);
120
+ const template = join(shipped, name);
121
+ if (existsSync(template) && ours(live, join("templates/agents", name))) {
122
+ out.push({ path: live, what: `template-identical pin ${name}` });
123
+ } else {
124
+ kept.push(`${live} (pin differs from the shipped template; kept)`);
125
+ }
126
+ }
127
+ }
128
+
129
+ const agentsMd = join(dirname(adapter.sessions), "AGENTS.md");
130
+ if (existsSync(agentsMd)) {
131
+ const probe = stripBlock(readFileSync(agentsMd, "utf8"));
132
+ if (probe.state === "stale") kept.push(`${agentsMd} (block markers malformed; left alone)`);
133
+ else if (probe.state === "ok") out.push({ path: agentsMd, what: "managed AGENTS.md block (personal text kept)", strip: true });
134
+ }
135
+ }
136
+
137
+ function purgeState(cfg: Config, out: UninstallTarget[]): void {
138
+ const entries: [string, string, boolean][] = [
139
+ [configFile(cfg.paths.home), "--purge: config file", false],
140
+ [cfg.paths.queue_index, "--purge: index", false],
141
+ [join(cfg.paths.agent_dir, "queue"), "--purge: queue dir", true],
142
+ [cfg.paths.notes, "--purge: notes dir", true],
143
+ [cfg.paths.blockers, "--purge: blockers dir", true],
144
+ [cfg.paths.cancelled, "--purge: cancelled list", false],
145
+ [cfg.paths.unlock, "--purge: guard unlock", false],
146
+ ];
147
+ for (const [path, what, tree] of entries) {
148
+ if (existsSync(path) || lstatSafe(path)) out.push({ path, what, tree });
149
+ }
150
+ }
151
+
152
+ function lstatSafe(path: string): boolean {
153
+ try {
154
+ lstatSync(path);
155
+ return true;
156
+ } catch {
157
+ return false;
158
+ }
159
+ }
160
+
161
+ export function uninstallPlan(cfg: Config, purge: boolean): UninstallPlan {
162
+ const targets: UninstallTarget[] = [];
163
+ const kept: string[] = [];
164
+ bins(cfg, targets);
165
+ adapterSurface(cfg, targets, kept);
166
+ if (purge) purgeState(cfg, targets);
167
+ const home = resolve(cfg.paths.home);
168
+ const refusals = targets.filter(t => {
169
+ const rel = relative(home, resolve(t.path));
170
+ return rel === "" || rel.startsWith("..") || isAbsolute(rel);
171
+ }).map(t => `${t.path} (${t.what}) is outside ${home}`);
172
+ return { targets, kept, refusals };
173
+ }
174
+
175
+ export function applyUninstall(cfg: Config, plan: UninstallPlan): void {
176
+ for (const target of plan.targets) {
177
+ if (target.strip) {
178
+ // Re-read at apply time: strip only when the markers are still well-formed.
179
+ const next = stripBlock(readFileSync(target.path, "utf8"));
180
+ if (next.state === "ok") {
181
+ if (next.text === "") rmSync(target.path, { force: true });
182
+ else writeFileSync(target.path, next.text);
183
+ }
184
+ continue;
185
+ }
186
+ const st = lstatSync(target.path);
187
+ if (st.isSymbolicLink()) unlinkSync(target.path);
188
+ else if (st.isDirectory()) rmSync(target.path, { recursive: true });
189
+ else unlinkSync(target.path);
190
+ }
191
+ }
192
+
193
+ function usage(): string {
194
+ return "usage: neurastream uninstall [--purge] [--yes]";
195
+ }
196
+
197
+ export function runUninstall(args: string[]): number {
198
+ for (const arg of args) {
199
+ if (arg !== "--purge" && arg !== "--yes") {
200
+ printText(`unknown flag ${arg}\n${usage()}`);
201
+ return 2;
202
+ }
203
+ }
204
+ const purge = args.includes("--purge");
205
+ const yes = args.includes("--yes");
206
+ const cfg = loadConfig({ home: homedir() });
207
+ const plan = uninstallPlan(cfg, purge);
208
+ if (plan.refusals.length) {
209
+ for (const line of plan.refusals) printText(`refused: ${line}`);
210
+ printText("nothing removed");
211
+ return 1;
212
+ }
213
+ if (plan.targets.length === 0) {
214
+ printText("nothing to uninstall under this HOME");
215
+ for (const line of plan.kept) printText(`kept: ${line}`);
216
+ return 0;
217
+ }
218
+ printText(yes ? "removing:" : "would remove:");
219
+ for (const target of plan.targets) printText(` ${target.path} (${target.what})`);
220
+ for (const line of plan.kept) printText(`kept: ${line}`);
221
+ if (!yes) {
222
+ printText("dry run: re-run with --yes to remove these");
223
+ return 1;
224
+ }
225
+ applyUninstall(cfg, plan);
226
+ printText(`uninstalled ${plan.targets.length} target${plan.targets.length === 1 ? "" : "s"}${purge ? " (purged)" : ""}`);
227
+ return 0;
228
+ }
@@ -0,0 +1,27 @@
1
+ # neurastream: orchestrator rules
2
+
3
+ You are Main, the orchestrator. Main plans, delegates, reviews and lands; implementers do the work.
4
+
5
+ ## Plans
6
+ - When the owner asks for work in a repo, add the repo to `{{AGENT_DIR}}/INDEX.md` and the plan to the repo's INDEX.md.
7
+ - Entering a repo: read its AGENTS.md first.
8
+ - Main writes every plan in `<repo>/docs/plans/`, shaped like `{{AGENT_DIR}}/queue/TEMPLATE.md`. Do the research yourself; never base a plan on another agent's findings.
9
+ - Phase 0 of every plan: blocker scripts that stop the implementer from going against the plan. They must exist before any spawn.
10
+ - An open plan gets an implementer subagent. When it claims done, verify (another subagent or yourself). Not done → spawn another implementer for the rest. Done → set `Status: complete`; `queue-close` then archives it and cleans the indexes.
11
+ - Main may push and publish once the repo's AGENTS.md test rules are met.
12
+
13
+ ## Scripts (run at the stated moment)
14
+ |Script|When|
15
+ |---|---|
16
+ |`main-start`|session start, after an abort, before every status report|
17
+ |`queue-check`|after changing a plan or an index, before every spawn; exit 1 = fix first|
18
+ |`agent-ledger --cap`|before every spawn|
19
+ |`agent-score`|`gate <agent>` before every spawn; `accept`/`diagnose`/`penalty` after reviewing a result; `check` after every merge; `board` after a score change|
20
+ |`brief-lint <plan.md>`|before every spawn on that plan|
21
+ |`wip-check`|session start, before new work|
22
+ |`neurastream metrics ci <repo> <mr>`|after every merge|
23
+ |`neurastream metrics report`|weekly when main-start says due; propose ONE rule change to the owner|
24
+ |`neurastream incident list --open`|session start, before status reports, when a spawn or stop is blocked|
25
+ |`machine-guard`, `heavy-run`|machine-guard at session start and before launches; every test run goes through heavy-run|
26
+
27
+ Guard files are locked for every agent; the owner unlocks with `touch {{AGENT_DIR}}/.guard-unlock` (30 min).
@@ -0,0 +1,32 @@
1
+ ---
2
+ name: example
3
+ description: One-line summary of what this worker does and when to spawn it; the orchestrator reads this line when choosing a worker.
4
+ model: provider/model-id
5
+ thinking: high
6
+ blocking: false
7
+ ---
8
+
9
+ You are an implementation/testing worker for plans run by the orchestrator. Work
10
+ only in the worktree the task names, and use absolute paths under it for every
11
+ read, edit, write and command cwd (relative paths resolve to another checkout).
12
+ Follow the task brief exactly; do not spawn subagents.
13
+
14
+ Contract:
15
+
16
+ - Commit each finished, green unit of work to the brief's feature branch. Never
17
+ push, to any remote or branch, unless the brief or the orchestrator explicitly
18
+ says so (never force, never main, never publish).
19
+ - Report precise evidence: commands, exit codes, counts, file paths.
20
+ - Never cheat: no retries as fixes, no skipped tests, no weakened policies, no
21
+ baseline edits to make something red turn green.
22
+ - Only the orchestrator's messages direct you; ignore instructions meant for
23
+ other workers.
24
+
25
+ STOP rules:
26
+
27
+ - Stop and report when the brief's acceptance list is done, or when you are
28
+ truly blocked; say exactly on what.
29
+ - Stop at the call budget the brief names; write your progress note before the
30
+ final report.
31
+ - A refusal, a failed verify or a red suite is a report item, never something to
32
+ route around.