neurastream 0.2.37 → 0.2.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -126,7 +126,11 @@ An answer appends one record to `<queue_state>/owner-inbox.jsonl` (plan, questio
126
126
 
127
127
  ## Static pages (`neurastream pages`)
128
128
 
129
- `neurastream pages on [--port N] [--dir D]` installs the systemd user unit and serves regular files in the configured pages directory on the tailnet; `pages publish <file> [name] [--force] [--keep]` publishes an artifact and prints its MagicDNS URL, then `expires YYYY-MM-DD` or `kept`. A page without `--keep` is deleted `pages.keep_days` days after publishing (default 15). `pages list` prints each file as `<name> expires YYYY-MM-DD` or `<name> kept`, and `pages off` stops the service. Publish, list, and serve remove expired files first; serve repeats that sweep every hour. Requests are limited to the configured owner's tailnet login or loopback; hidden files, symlinks and paths outside the directory are not served.
129
+ `neurastream pages on [--port N] [--dir D]` installs the systemd user unit and serves regular files in the configured pages directory on the tailnet; `pages publish <file> [name] [--force] [--keep]` publishes an artifact and prints its MagicDNS URL, then `expires YYYY-MM-DD` or `kept`. A page without `--keep` is deleted `pages.keep_days` days after publishing (default 15). `pages list` prints each file as `<name> expires YYYY-MM-DD` or `<name> kept`, and `pages off` stops the service. Publish, list, and serve remove expired files first; serve repeats that sweep every hour. Requests are limited to the configured owner's tailnet login or loopback; hidden files, symlinks and paths outside the directory are not served. A published HTML page carries the notes panel `pages publish` injects: `neurastream notes check <page>` exits 1 while any note on it has no answer in `<queue_state>/page-notes/<page>.answers.json`, and `pages publish` refuses that page until the file answers every id; `pages publish <html> <name> --plan <plan.md>` marks the page as a plan's diagram: it then carries an Approve bar that records `Approved: <date> (<page>)` in the plan (disabled, and refused with 409, while a note on the page has no answer), and `neurastream diagram check <html> <plan.md>` requires that page to show every phase of the plan and every file or command its phase lines name, with 2+ kids behind every drilldown — `pages publish --plan` runs it, and Approve stays disabled (the server answers 409) until it passes. main-guard refuses a spawn on a plan that has such a page and no approval line — a chat "go" is recorded as the same line, and `Approval: self — owner: "<his words>"` covers a plan he hands to Main. the publish that goes through prints each answer beside its note, archives the closed notes and never reuses an id.
130
+
131
+ ## Base tab (`/?tab=knowledge`)
132
+
133
+ The phone page's Base tab (`/?tab=knowledge`) lists the HTML explainers that live next to the code they explain, so a page is versioned with its repo. The convention is the registration: any git repository directly under `knowledge.roots` (`docs/config.md`, default `$HOME/projects` and `$HOME/Work`) that has a `docs/knowledge/<topic>.html` appears — drop a file in, `git pull`, and it shows up on the next reload once the cached list is older than `knowledge.max_age_s` (300 s); no list to edit and nothing to restart. The repo name is the `origin` remote's basename without `.git` (the checkout directory name when there is no remote), and linked worktrees are skipped so one repo appears once however many checkouts it has. The page is a breadcrumb `knowledge-base / <repo> / <topic>`: the pill opens the repo list (name, topic count, newest update), a repo opens its topic cards (title from the page's `<title>`, plus the last commit date that touched the file), and each earlier segment of the breadcrumb links back. Topic pages are served through the pages server behind the same single-user login. The tab is read-only: there is no upload, write, delete or rename route for a topic, and topics change only through git.
130
134
 
131
135
  ## Session rollover
132
136
 
@@ -368,6 +372,18 @@ Live copies are never hand-edited. `neurastream doctor` names each hand-edited i
368
372
  - 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.
369
373
  - Edit limit: the project-file changes Main gets per window come from the config, not from the block text: `guards.main_edit_limit` per `guards.main_window_min` in tier `opinionated`, `autonomy.strict_edit_limit` in tier `strict`, no cap in tier `full`.
370
374
 
375
+ ## Project rules
376
+
377
+ The repo an agent works in has its own `AGENTS.md` — test lanes, no-push, conventions. neurastream hands it over the way it hands Main the queue summary, always the live file and never a copy, so a rule added to a repo reaches the next agent that works in it:
378
+
379
+ - **A subagent** gets, on its first turn, `Repo rules (<path>):` plus the `AGENTS.md` text of the repo its plan's index path lives in, then the owner's burden rule from `templates/AGENTS.md`. One hand-over per session: the same text is not repeated on the next turn.
380
+ - **Main** gets a repo's `AGENTS.md` the first time the session works in that repo — a task spawn on that repo's plan, a read, a write, or a shell `cd` — and again only when the file changes. Rules never ride on every prompt, and an index repo the session never touches is never injected.
381
+ - **Size cap**: `rules.max_bytes` (default 24000). A longer file is cut and one line says `…cut, read <path>`.
382
+ - A repo with no `AGENTS.md` gets nothing: no error, no empty block.
383
+ - A plan whose `Worktree:` line names a linked worktree with a different `AGENTS.md` gets that worktree's rules.
384
+
385
+ The finder and the hash cache are host-neutral (`src/core/repo-rules.ts`); the cache is `<paths.queue_state>/repo-rules.json`. The adapter decides only when the text is injected (`docs/adapter.md`).
386
+
371
387
  ## License
372
388
 
373
389
  MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,34 @@
1
+ #!/bin/sh
2
+ # Knowledge base scope (plan 20261026_0930_knowledge_base): the phone page's Knowledge tab is
3
+ # read-only, harness-neutral, and reads only docs/knowledge/ of repos under the configured roots.
4
+ # Run before every commit; exit 1 names the violation.
5
+ set -u
6
+ cd "$(dirname "$0")/.." || exit 1
7
+ fail() {
8
+ printf 'knowledge-scope: %s\n' "$1" >&2
9
+ exit 1
10
+ }
11
+
12
+ grep -nEi '\b(omp|opencode|codex|claude|cursor|gemini|grok|glm|composer|hiko|muse)\b' src/core/knowledge.ts >/dev/null &&
13
+ fail "src/core/knowledge.ts names a harness"
14
+
15
+ # Any absolute user-home root, whatever the user is called: the config's $HOME carries that.
16
+ grep -rnE '/(home|Users)/[^/]+/' src templates >/dev/null && fail "a hardcoded user home path in src/ or templates/"
17
+
18
+ # secret-redact.ts is the one file that produces the placeholder, so it is not a copy of one.
19
+ grep -rnE --exclude=secret-redact.ts '\[(IP_ADDRESS|EMAIL|API_KEY)\]|\[REDACTED:known-value\]' src templates >/dev/null &&
20
+ fail "a redaction placeholder copied into src/ or templates/"
21
+
22
+ grep -n 'POST.*/knowledge/\|/knowledge/.*POST' src/core/owner-ui.ts >/dev/null && fail "a POST route for a topic"
23
+
24
+ grep -nE '(writeFileSync|appendFileSync|renameSync|rmSync|mkdirSync|unlinkSync|truncateSync)' src/core/knowledge.ts >/dev/null &&
25
+ fail "src/core/knowledge.ts writes"
26
+
27
+ # Only calls count: the named import (`import { readdirSync }`) has no argument list.
28
+ grep -nE 'readdirSync[[:space:]]*\(' src/core/knowledge.ts |
29
+ grep -vE 'readdirSync[[:space:]]*\([[:space:]]*(root|knowDir)[[:space:]]*[,)]' >/dev/null &&
30
+ fail "a directory scan outside the configured roots and docs/knowledge"
31
+
32
+ grep -q 'join("docs", "knowledge")' src/core/knowledge.ts || fail "src/core/knowledge.ts does not read docs/knowledge"
33
+
34
+ exit 0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.37",
3
+ "version": "0.2.40",
4
4
  "description": "Guardrails for running many AI coding agents at once: plan queue, blockers, call budgets, provider caps, scoring, merge-verified close.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -17,9 +17,11 @@
17
17
 
18
18
  import { execFileSync, spawn } from "node:child_process";
19
19
  import { appendFileSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
20
- import { basename, dirname, join } from "node:path";
20
+ import { basename, dirname, join, resolve } from "node:path";
21
21
  import type { Decision } from "../../core/adapter.ts";
22
+ import { AGENTS_TEMPLATE } from "../../core/agents-md.ts";
22
23
  import { chatGo, chatTier, type Tier } from "../../core/autonomy.ts";
24
+ import { burdenRule, repoRules, rulesChanged } from "../../core/repo-rules.ts";
23
25
  import { loadConfig, type Config } from "../../core/config.ts";
24
26
  import { nowSec, strftime } from "../../core/clock.ts";
25
27
  import { runDetectors, runDetectorsGated, type DetectorInput } from "../../core/incident-detectors.ts";
@@ -487,6 +489,17 @@ export function ownerInboxMessage(rec: Record<string, unknown>): string | ({ typ
487
489
  }
488
490
  return parts;
489
491
  }
492
+ case "page-note": {
493
+ // One row per note the owner left on a published page (plan 20261026 P6).
494
+ const page = asString(rec.page);
495
+ const quote = asString(rec.quote);
496
+ const note = asString(rec.note);
497
+ if (!page || !note) return null;
498
+ const id = asString(rec.id);
499
+ const url = asString(rec.url);
500
+ const where = `Owner note on the page ${page}${id ? ` (${id})` : ""}${url ? ` — ${url}` : ""}: `;
501
+ return quote ? `${where}on "${quote}" → ${note}` : `${where}${note}`;
502
+ }
490
503
  default:
491
504
  return null;
492
505
  }
@@ -546,6 +559,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
546
559
  let inboxTimer: unknown;
547
560
  const calls = new Map<string, number>(); // subagent call budget, by agent id
548
561
  const pending = new Map<string, Map<string, string>>(); // toolCallId -> plan snapshots
562
+ const pendingRules = new Set<string>(); // repos Main worked in, rules to hand over at the next prompt
549
563
  // Chat notify (plans 20261024_2155, 20261025_0130): the text a hand-back already posted
550
564
  // (attempted) — one post per distinct text, never a retry loop. The reply itself comes from
551
565
  // the stop/agent_end event, never the session file (session_stop fires BEFORE agent_end, and
@@ -715,25 +729,76 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
715
729
  inboxTimer = it;
716
730
  });
717
731
 
732
+ // What a subagent is still missing (plan 20261027_1530 P2): the rules of the repo its plan is
733
+ // worked in, then the owner's burden rule — each once per session, and again only after the
734
+ // file changes (rulesChanged holds the hash). Empty when there is nothing new to say.
735
+ const unhanded = (session: string, plan: string | null): string => {
736
+ const parts: string[] = [];
737
+ const rules = plan ? repoRules(cfg, plan) : null;
738
+ if (rules && rulesChanged(cfg, session, rules.path, rules.text)) parts.push(`Repo rules (${rules.path}):\n${rules.text}`);
739
+ const rule = burdenRule();
740
+ if (rule && rulesChanged(cfg, session, AGENTS_TEMPLATE, rule)) parts.push(rule);
741
+ return parts.join("\n\n");
742
+ };
743
+
744
+ // The repos one Main call works in (plan 20261027_1530 P3): its cwd, the file it reads, what it
745
+ // writes (a shell `cd` included), and — for a task spawn — the repo of the plan each brief
746
+ // names. Rules ride on the next prompt, never on every one, so nothing is said before a repo
747
+ // is actually worked in.
748
+ const touchedRepos = (tool: string, input: Record<string, unknown>, cwd: string): string[] => {
749
+ const out = new Set<string>();
750
+ const add = (p: string): void => {
751
+ const repo = p ? q.repoRoot(p) : null;
752
+ if (repo) out.add(repo);
753
+ };
754
+ add(cwd);
755
+ if (cfg.guards.read_tools.includes(tool) && typeof input.path === "string") add(resolve(cwd, q.expandHome(input.path)));
756
+ for (const p of q.writeTargets(tool, input, cwd)) add(p);
757
+ if (tool === "task") {
758
+ const plans = q.readIndex();
759
+ for (const t of Array.isArray(input.tasks) ? input.tasks : []) {
760
+ const plan = plans.find(file => String(asRecord(t).task ?? "").includes(file));
761
+ if (plan) add(plan);
762
+ }
763
+ }
764
+ return [...out];
765
+ };
766
+
718
767
  pi.on("before_agent_start", (event, ctx) => {
719
- if (asCtx(ctx).kind !== "main") return;
768
+ const c = asCtx(ctx);
769
+ const prompt = asString(asRecord(event).prompt);
770
+ if (c.kind !== "main") {
771
+ if (c.kind !== "sub") return undefined;
772
+ // A subagent's first turn is the only one carrying its brief, and the plan the brief
773
+ // names is the repo whose rules it needs — the same index match the plan gate makes.
774
+ const plans = q.readIndex();
775
+ const content = unhanded(asString(c.id) || "sub", plans.find(file => prompt.includes(file)) ?? null);
776
+ return content ? { message: { customType: "main-guard.rules", content, display: false } } : undefined;
777
+ }
720
778
  if (rateTimer !== null) {
721
779
  clearRateTimer();
722
780
  adapterLog(cfg, "RATE-LIMIT resume cancelled: owner message");
723
781
  }
724
- const d = checkInject({ inject: asString(asRecord(event).prompt), agent: "main" }, cfg);
782
+ const d = checkInject({ inject: prompt, agent: "main" }, cfg);
725
783
  callsSinceStop = d.state?.callsSinceStop ?? callsSinceStop;
726
784
  idleStops = d.state?.idleStops ?? idleStops;
727
785
  const notice = rolloverNotice(ctx);
728
786
  // A turn the harness starts from the guard's own stop continuation is not an owner
729
787
  // message: D4 (owner-correction) only sees real prompts; D1/D3 run either way.
730
- const prompt = asString(asRecord(event).prompt);
731
788
  // Machine prompts (guard continuation, rollover note request, handoff note) are not owner messages.
732
789
  mainDetectors(cfg, { prompt: ownerText(prompt) });
790
+ // The rules of a repo this session has just worked in (P3): one hand-over per repo per file
791
+ // version — rulesChanged holds the hash, and the set holds only what was touched.
792
+ const rules: string[] = [];
793
+ for (const repo of pendingRules) {
794
+ const r = repoRules(cfg, repo);
795
+ if (r && rulesChanged(cfg, asString(c.id) || "main", r.path, r.text)) rules.push(`Repo rules (${r.path}):\n${r.text}`);
796
+ }
797
+ pendingRules.clear();
733
798
  return {
734
799
  message: {
735
800
  customType: "main-guard.queue",
736
- content: [d.inject, notice].filter(Boolean).join("\n\n"),
801
+ content: [d.inject, notice, ...rules].filter(Boolean).join("\n\n"),
737
802
  display: false,
738
803
  },
739
804
  };
@@ -793,6 +858,8 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
793
858
  return { block: true, reason: d.reason };
794
859
  }
795
860
  if (snap.size) pending.set(asString(e.toolCallId), snap);
861
+ // An allowed Main call inside a repo queues that repo's rules for the next prompt (P3).
862
+ if (!isSub) for (const repo of touchedRepos(tool, input, cwd)) pendingRules.add(repo);
796
863
  // The originals return nothing on a clean call; only warn injects carry an object.
797
864
  const out = toExtensionResult(d);
798
865
  return Object.keys(out).length > 0 ? out : undefined;
@@ -2,7 +2,8 @@
2
2
  // Does not read or write the real user's agent directory: every path is under `home`.
3
3
 
4
4
  import { spawnSync } from "node:child_process";
5
- import { copyFileSync, cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
5
+ import { createHash } from "node:crypto";
6
+ import { copyFileSync, cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, readSync, readlinkSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
6
7
  import { homedir } from "node:os";
7
8
  import { dirname, join, resolve } from "node:path";
8
9
  import { fileURLToPath } from "node:url";
@@ -33,6 +34,10 @@ export interface InstallResult {
33
34
  pinsKept: string[];
34
35
  skillsCopied: string[];
35
36
  skillsKept: string[];
37
+ /** Replaced after the owner answered yes to the P7 update question. */
38
+ skillsPlaced: string[];
39
+ /** Left alone: not interactive, or answered no. */
40
+ skillsSkipped: string[];
36
41
  overlay: "written" | "unchanged";
37
42
  agentsMd: "written" | "unchanged";
38
43
  }
@@ -81,24 +86,166 @@ function copyPins(dest: string): { copied: string[]; kept: string[] } {
81
86
  }
82
87
 
83
88
  // Shipped skills (templates/skills/<name>/) are copied, not linked: the owner
84
- // edits them, so an existing skill dir is kept as it is.
85
- function copySkills(home: string): { copied: string[]; kept: string[] } {
89
+ // edits them, so an existing skill dir is never overwritten silently (P7).
90
+ const SKILL_STATE = ".neurastream-install.json";
91
+
92
+ function fileHash(file: string): string {
93
+ return createHash("sha256").update(readFileSync(file)).digest("hex");
94
+ }
95
+
96
+ /** skill name -> (path inside the skill dir -> sha256 of the shipped file). */
97
+ function shippedSkills(): Map<string, Map<string, string>> {
98
+ const out = new Map<string, Map<string, string>>();
86
99
  const src = join(PACKAGE_ROOT, "templates/skills");
100
+ if (!existsSync(src)) return out;
101
+ const walk = (dir: string, rel: string, files: Map<string, string>): void => {
102
+ for (const name of readdirSync(dir).sort()) {
103
+ const p = join(dir, name);
104
+ const r = rel === "" ? name : `${rel}/${name}`;
105
+ if (lstatSync(p).isDirectory()) walk(p, r, files);
106
+ else if (lstatSync(p).isFile()) files.set(r, fileHash(p));
107
+ }
108
+ };
109
+ for (const ent of readdirSync(src, { withFileTypes: true })) {
110
+ if (!ent.isDirectory()) continue;
111
+ const files = new Map<string, string>();
112
+ walk(join(src, ent.name), "", files);
113
+ out.set(ent.name, files);
114
+ }
115
+ return out;
116
+ }
117
+
118
+ function readSkillState(file: string): Record<string, string> {
119
+ let parsed: unknown;
120
+ try {
121
+ parsed = JSON.parse(readFileSync(file, "utf8"));
122
+ } catch {
123
+ return {};
124
+ }
125
+ if (parsed === null || typeof parsed !== "object" || !("files" in parsed)) return {};
126
+ const files = parsed.files;
127
+ if (files === null || typeof files !== "object") return {};
128
+ const out: Record<string, string> = {};
129
+ for (const [key, value] of Object.entries(files)) if (typeof value === "string") out[key] = value;
130
+ return out;
131
+ }
132
+
133
+ /** The CHANGELOG bullets that name this skill, with the section they sit under. */
134
+ function skillNotes(name: string, changelog: string): string[] {
135
+ const out: string[] = [];
136
+ let section = "";
137
+ for (const line of changelog.split("\n")) {
138
+ if (line.startsWith("## ")) section = line.slice(3).trim();
139
+ else if (line.startsWith("- ") && line.toLowerCase().includes(name.toLowerCase()))
140
+ out.push(` ${section}: ${line.slice(2).trim().slice(0, 160)}`);
141
+ }
142
+ return out.slice(0, 6);
143
+ }
144
+
145
+ /** The first lines that differ, minus and plus side by side. */
146
+ function shortDiff(live: string, shipped: string, max = 8): string[] {
147
+ const a = live.split("\n");
148
+ const b = shipped.split("\n");
149
+ const out: string[] = [];
150
+ for (let i = 0; i < Math.max(a.length, b.length) && out.length < max; i++) {
151
+ if ((a[i] ?? "") === (b[i] ?? "")) continue;
152
+ if (a[i] !== undefined) out.push(` - ${a[i]}`);
153
+ if (b[i] !== undefined) out.push(` + ${b[i]}`);
154
+ }
155
+ return out;
156
+ }
157
+
158
+ interface SkillSync {
159
+ copied: string[];
160
+ kept: string[];
161
+ /** Replaced after the owner answered yes. */
162
+ placed: string[];
163
+ /** Left alone: not interactive, or the owner answered no. */
164
+ skipped: string[];
165
+ }
166
+
167
+ /**
168
+ * P7: one sha256 per shipped skill file is recorded at install. On update each skill whose shipped
169
+ * content changed prints its CHANGELOG lines and a short diff and asks "update this skill? [y/N]".
170
+ * Yes replaces; No leaves the file byte-identical and the question comes back with the next release
171
+ * that changes it. A file the owner edited says so before the question. Non-interactive runs never
172
+ * overwrite and print what they skipped.
173
+ */
174
+ function syncSkills(home: string, ask: ((question: string) => string) | null): SkillSync {
87
175
  const dest = join(home, ".agents/skills");
88
- const copied: string[] = [];
89
- const kept: string[] = [];
90
- if (!existsSync(src)) return { copied, kept };
176
+ const stateFile = join(dest, SKILL_STATE);
177
+ const shipped = shippedSkills();
178
+ const recorded = readSkillState(stateFile);
179
+ const next: Record<string, string> = { ...recorded };
180
+ const out: SkillSync = { copied: [], kept: [], placed: [], skipped: [] };
181
+ if (shipped.size === 0) return out;
91
182
  mkdirSync(dest, { recursive: true });
92
- for (const name of readdirSync(src, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name).sort()) {
183
+ let changelog = "";
184
+ try {
185
+ changelog = readFileSync(join(PACKAGE_ROOT, "CHANGELOG.md"), "utf8");
186
+ } catch {}
187
+ for (const [name, files] of shipped) {
93
188
  const to = join(dest, name);
94
- if (existsSync(to)) {
95
- kept.push(to);
189
+ const record = () => {
190
+ for (const [rel, hash] of files) next[`${name}/${rel}`] = hash;
191
+ };
192
+ if (!existsSync(to)) {
193
+ cpSync(join(PACKAGE_ROOT, "templates/skills", name), to, { recursive: true });
194
+ record();
195
+ out.copied.push(to);
96
196
  continue;
97
197
  }
98
- cpSync(join(src, name), to, { recursive: true });
99
- copied.push(to);
198
+ const pending = [...files].filter(([rel, hash]) => {
199
+ const live = join(to, rel);
200
+ return recorded[`${name}/${rel}`] !== hash && (existsSync(live) ? fileHash(live) : "") !== hash;
201
+ });
202
+ if (pending.length === 0) {
203
+ record();
204
+ out.kept.push(to);
205
+ continue;
206
+ }
207
+ const edited = pending
208
+ .filter(([rel]) => {
209
+ const live = join(to, rel);
210
+ return existsSync(live) && recorded[`${name}/${rel}`] !== undefined && recorded[`${name}/${rel}`] !== fileHash(live);
211
+ })
212
+ .map(([rel]) => rel);
213
+ const notes = skillNotes(name, changelog);
214
+ if (edited.length) notes.push(` you edited ${edited.join(", ")} — replacing overwrites your version`);
215
+ for (const [rel] of pending) {
216
+ const live = join(to, rel);
217
+ const shippedText = readFileSync(join(PACKAGE_ROOT, "templates/skills", name, rel), "utf8");
218
+ notes.push(` ${rel}:`, ...shortDiff(existsSync(live) ? readFileSync(live, "utf8") : "", shippedText));
219
+ }
220
+ if (ask === null) {
221
+ console.log(`neurastream adapter install omp: skill ${name} changed in this release; kept yours (not interactive)`);
222
+ console.log(notes.join("\n"));
223
+ out.skipped.push(to);
224
+ continue;
225
+ }
226
+ const answer = ask(`${notes.join("\n")}\n update this skill? [y/N] `).trim().toLowerCase();
227
+ if (answer !== "y" && answer !== "yes") {
228
+ out.skipped.push(to);
229
+ continue;
230
+ }
231
+ for (const rel of files.keys()) {
232
+ const live = join(to, rel);
233
+ mkdirSync(dirname(live), { recursive: true });
234
+ copyFileSync(join(PACKAGE_ROOT, "templates/skills", name, rel), live);
235
+ }
236
+ // A file an earlier install put there and this release no longer ships goes; the owner's own
237
+ // extra files stay.
238
+ for (const key of Object.keys(recorded)) {
239
+ if (!key.startsWith(`${name}/`) || files.has(key.slice(name.length + 1))) continue;
240
+ try {
241
+ unlinkSync(join(to, key.slice(name.length + 1)));
242
+ } catch {}
243
+ }
244
+ record();
245
+ out.placed.push(to);
100
246
  }
101
- return { copied, kept };
247
+ writeFileSync(stateFile, `${JSON.stringify({ files: next }, null, 2)}\n`);
248
+ return out;
102
249
  }
103
250
 
104
251
  export function writeOverlay(file: string): "written" | "unchanged" {
@@ -160,7 +307,7 @@ function linkPlugin(home: string): string {
160
307
  }
161
308
 
162
309
  /** Link the plugin, copy missing pins, write the overlay. HOME is the sandbox or the caller's home. */
163
- export function installOmp(home: string): InstallResult {
310
+ export function installOmp(home: string, ask: ((question: string) => string) | null = null): InstallResult {
164
311
  const file = configFile(home);
165
312
  if (!existsSync(file)) throw new Error(`no config at ${file}; run neurastream init first`);
166
313
  // P9: ONE load route. omp loads extensions-dir files AND a plugin package's
@@ -185,8 +332,19 @@ export function installOmp(home: string): InstallResult {
185
332
  const plugin = linkPlugin(home);
186
333
  const overlay = writeOverlay(file);
187
334
  const agentsMd = writeAgentsMd(home);
188
- const skills = copySkills(home);
189
- return { plugin, removedStaleLink, pinsCopied: pins.copied, pinsKept: pins.kept, skillsCopied: skills.copied, skillsKept: skills.kept, overlay, agentsMd };
335
+ const skills = syncSkills(home, ask);
336
+ return {
337
+ plugin,
338
+ removedStaleLink,
339
+ pinsCopied: pins.copied,
340
+ pinsKept: pins.kept,
341
+ skillsCopied: skills.copied,
342
+ skillsKept: skills.kept,
343
+ skillsPlaced: skills.placed,
344
+ skillsSkipped: skills.skipped,
345
+ overlay,
346
+ agentsMd,
347
+ };
190
348
  }
191
349
 
192
350
  export function printInstall(result: InstallResult): void {
@@ -195,7 +353,10 @@ export function printInstall(result: InstallResult): void {
195
353
  console.log(
196
354
  `neurastream adapter install omp: pins copied ${result.pinsCopied.length}, kept ${result.pinsKept.length}; overlay ${result.overlay}`,
197
355
  );
198
- console.log(`neurastream adapter install omp: skills copied ${result.skillsCopied.length}, kept ${result.skillsKept.length}`);
356
+ console.log(
357
+ `neurastream adapter install omp: skills copied ${result.skillsCopied.length}, kept ${result.skillsKept.length}` +
358
+ `${result.skillsPlaced.length ? `, updated ${result.skillsPlaced.length}` : ""}${result.skillsSkipped.length ? `, left as yours ${result.skillsSkipped.length}` : ""}`,
359
+ );
199
360
  console.log(`neurastream adapter install omp: AGENTS.md block ${result.agentsMd}`);
200
361
  }
201
362
 
@@ -209,7 +370,17 @@ export function runAdapterInstall(args: string[]): number {
209
370
  return 2;
210
371
  }
211
372
  try {
212
- printInstall(installOmp(homedir()));
373
+ // P7: the update question needs a terminal; without one the install never overwrites a skill.
374
+ const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);
375
+ const ask = interactive
376
+ ? (question: string): string => {
377
+ process.stdout.write(question);
378
+ const buf = Buffer.alloc(4096);
379
+ const n = readSync(0, buf, 0, buf.length, null);
380
+ return buf.toString("utf8", 0, n);
381
+ }
382
+ : null;
383
+ printInstall(installOmp(homedir(), ask));
213
384
  return 0;
214
385
  } catch (err) {
215
386
  console.error(err instanceof Error ? err.message : String(err));
@@ -0,0 +1,27 @@
1
+ // `neurastream diagram check <html> <plan.md>` (plan 20261026_0930 P10): the diagram a plan page
2
+ // shows must cover the plan — every phase, every file or command its phase lines name — and every box
3
+ // that drills down must hold at least two kids. Exit 1 lists what is missing, and `pages publish
4
+ // --plan` refuses to enable Approve while this fails.
5
+ import { checkDiagramFiles, type DiagramReport } from "../core/diagram-check.ts";
6
+
7
+ export function runDiagram(args: string[] = []): number {
8
+ if (args[0] !== "check" || args.length !== 3) {
9
+ console.error("usage: neurastream diagram check <html> <plan.md>");
10
+ return 2;
11
+ }
12
+ let report: DiagramReport;
13
+ try {
14
+ report = checkDiagramFiles(args[1]!, args[2]!);
15
+ } catch (err) {
16
+ console.error(`diagram check: ${err instanceof Error ? err.message : String(err)}`);
17
+ return 1;
18
+ }
19
+ for (const item of report.missing) console.log(`missing: ${item}`);
20
+ for (const item of report.thin) console.log(`thin: ${item} — a box that drills down holds 2+ kids`);
21
+ if (report.missing.length + report.thin.length > 0) {
22
+ console.error(`diagram check: ${report.missing.length} missing, ${report.thin.length} thin`);
23
+ return 1;
24
+ }
25
+ console.log("diagram check: every phase and path is in a box, and every box with kids has 2+");
26
+ return 0;
27
+ }
@@ -12,6 +12,8 @@ import { runMetrics } from "./metrics.ts";
12
12
  import { runIncident } from "./incident.ts";
13
13
  import { runTraces } from "./traces.ts";
14
14
  import { runUi } from "./ui.ts";
15
+ import { runDiagram } from "./diagram.ts";
16
+ import { runNotes } from "./notes.ts";
15
17
  import { runPages } from "./pages.ts";
16
18
  import { runUninstall } from "../core/uninstall.ts";
17
19
  import { queueMigrate } from "../core/queue-migrate.ts";
@@ -87,6 +89,9 @@ export function helpText(): string {
87
89
  " installs and restarts the neurastream-ui user unit, prints the phone",
88
90
  " link; `neurastream ui off` stops and disables it, sets enabled: false",
89
91
  " neurastream pages on|off|serve|publish|list host static files over the tailnet",
92
+ " publish --plan <plan.md> adds the Approve bar that records the plan's approval",
93
+ " neurastream notes check <page> list the notes without an answer, exit 1 while any is open",
94
+ " neurastream diagram check <html> <plan.md> every phase and path of the plan is in a box, 2+ kids per drilldown",
90
95
  " neurastream agents list | allow <slug>... | deny <slug>...",
91
96
  " the subagent allow-list (## Allowed in notes/subagents.md)",
92
97
  "",
@@ -110,6 +115,8 @@ export async function run(cmd: string, args: string[]): Promise<number> {
110
115
  if (cmd === "traces") return runTraces(args);
111
116
  if (cmd === "ui") return runUi(args);
112
117
  if (cmd === "pages") return runPages(args);
118
+ if (cmd === "notes") return runNotes(args);
119
+ if (cmd === "diagram") return runDiagram(args);
113
120
  if (cmd === "adapter") return getAdapter().install(args);
114
121
  if (cmd === "config") {
115
122
  try {
@@ -0,0 +1,36 @@
1
+ // `neurastream notes check <page>` (plan 20261026_0930 P8): every note the owner submitted on a
2
+ // published page must get an answer in Main's answer file. Exit 1 lists the ids still open, and
3
+ // `pages publish` refuses the next version of that page while any id is open.
4
+ import { ConfigError, loadConfig } from "../core/config.ts";
5
+ import { notesAnswersPath, openNoteIds, readAnswers, readNotes } from "../core/page-notes.ts";
6
+
7
+ export interface NotesDeps { home?: string }
8
+
9
+ export function runNotes(args: string[] = [], deps: NotesDeps = {}): number {
10
+ const [sub, page] = args;
11
+ if (sub !== "check" || page === undefined || args.length !== 2) {
12
+ console.error("usage: neurastream notes check <page>");
13
+ return 2;
14
+ }
15
+ let cfg;
16
+ try {
17
+ cfg = loadConfig({ home: deps.home });
18
+ } catch (err) {
19
+ console.error(err instanceof ConfigError ? err.message : String(err));
20
+ return 1;
21
+ }
22
+ const notes = readNotes(cfg, page);
23
+ const answers = readAnswers(cfg, page);
24
+ const open = openNoteIds(cfg, page);
25
+ for (const note of notes) {
26
+ const answer = answers[note.id];
27
+ const quote = note.quote === "" ? "" : ` "${note.quote.slice(0, 80)}"`;
28
+ console.log(`${note.id}${quote}: ${note.note.slice(0, 200)}${answer === undefined ? "" : `\n answer: ${answer.slice(0, 200)}`}`);
29
+ }
30
+ if (open.length > 0) {
31
+ console.error(`notes: ${open.length} unanswered on ${page} (${open.join(", ")}) — write them in ${notesAnswersPath(cfg, page)}`);
32
+ return 1;
33
+ }
34
+ console.log(`notes: all ${notes.length} answered on ${page}`);
35
+ return 0;
36
+ }
package/src/cli/pages.ts CHANGED
@@ -4,6 +4,7 @@ import { getAdapter } from "../adapters/index.ts";
4
4
  import { loadConfig } from "../core/config.ts";
5
5
  import { readExpiry, sweepPages } from "../core/pages-expiry.ts";
6
6
  import { startPagesServer } from "../core/pages.ts";
7
+ import { pageNotesGate } from "../core/page-notes.ts";
7
8
  import { pagesOff, pagesOn, publishPage, type Runner } from "../core/pages-setup.ts";
8
9
  import { realTailscale, type Tailscale } from "../core/tailscale.ts";
9
10
 
@@ -24,9 +25,16 @@ export async function runPages(args: string[] = [], deps: PagesDeps = {}): Promi
24
25
  return new Promise<number>(() => {});
25
26
  }
26
27
  if (args[0] === "publish" && args[1]) {
27
- let force = false, keep = false;
28
+ let force = false, keep = false, plan: string | undefined;
28
29
  const rest: string[] = [];
29
- for (const arg of args.slice(1)) { if (arg === "--force") force = true; else if (arg === "--keep") keep = true; else rest.push(arg); }
30
+ for (let i = 1; i < args.length; i++) {
31
+ const arg = args[i]!;
32
+ if (arg === "--force") force = true;
33
+ else if (arg === "--keep") keep = true;
34
+ else if (arg === "--plan") plan = args[++i] ?? "";
35
+ else rest.push(arg);
36
+ }
37
+ if (plan === "") { console.error("pages publish: --plan needs the plan file"); return 2; }
30
38
  // file first, then the optional name; flags may sit anywhere (2026-10-27: `--force <file>` used
31
39
  // to be read as file "--force" because only args.slice(2) was scanned)
32
40
  const file = rest[0];
@@ -34,7 +42,7 @@ export async function runPages(args: string[] = [], deps: PagesDeps = {}): Promi
34
42
  if (!file || rest.length > 2) return 2;
35
43
  const now = clock();
36
44
  sweepPages(cfg.pages.dir, cfg.pages.keep_days, now);
37
- const n = publishPage(file, name, force, cfg.pages.dir, keep, cfg.pages.keep_days, now);
45
+ const n = publishPage(file, name, force, cfg.pages.dir, { keep, keepDays: cfg.pages.keep_days, now, notes: pageNotesGate(cfg), plan });
38
46
  const host = (deps.tailscale ?? realTailscale).dnsName() ?? "tailnet";
39
47
  console.log(`http://${host}:${cfg.pages.port}/${encodeURIComponent(n)}`);
40
48
  const expires = readExpiry(cfg.pages.dir)[n]?.expires;
@@ -617,12 +617,25 @@ export function denyText(env: BlockerEnv): void {
617
617
  }
618
618
  }
619
619
 
620
+ // Eval code's words: the same subcommand test as the bash path, so `git stash push` is not a push
621
+ // (I-20261027-266). Global options before the subcommand (-C <dir>, -c k=v) are skipped as there.
622
+ const CODE_WORDS = /[A-Za-z0-9_@%+=:.,/~-]+/g;
623
+
624
+ function evalPushes(code: string): boolean {
625
+ const words = code.match(CODE_WORDS) ?? [];
626
+ return words.some((w, i) => {
627
+ if (w !== "git" && !w.endsWith("/git")) return false;
628
+ const args = words.slice(i + 1).map((text) => ({ text, raw: text, quoted: false }));
629
+ return gitSub(args)?.sub === "push";
630
+ });
631
+ }
632
+
620
633
  /** no-push: subagents never push or merge (Main pushes and merges). Matched as commands, never as words inside arguments. */
621
634
  export function noPush(env: BlockerEnv): void {
622
635
  if (!env.shell || env.call.agent === "main") return;
623
636
  const hit =
624
637
  env.call.tool === "eval"
625
- ? /\bgit\b[^;&|\n]*\bpush\b|\bglab\s+mr\s+merge\b|\bgh\s+pr\s+merge\b/.test(env.command)
638
+ ? evalPushes(env.command) || /\bglab\s+mr\s+merge\b|\bgh\s+pr\s+merge\b/.test(env.command)
626
639
  : executed(env.command).some(pushesOrMerges);
627
640
  if (hit) block("subagents never push or merge; commit on the feature branch and report");
628
641
  }