neurastream 0.2.36 → 0.2.39

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
 
@@ -246,6 +250,12 @@ omp retries a 429 itself while the provider's wait fits its `retry.maxDelayMs` (
246
250
 
247
251
  Before Main reads a message, reset timestamps matching `quota.reset_pattern` are annotated with their local time, for example `reset at 2026-10-25 18:56:22 (= 2026-10-25 11:56:22 CET local)`. Set `quota.reset_tz` to the provider's time zone; an explicit zone or UTC offset in the message takes precedence.
248
252
 
253
+ ## Provider state and pick order
254
+
255
+ Who is rate-limited comes from recorded live data, not from memory (I-20261025-164). An out-until time is recorded — `quota-reset --provider <name> "<429 text>"` stores the time it parses (zone from `quota.reset_tz`), the adapter records a task result quoting a `reset at …` line for the pinned provider, and a rate limit without a parseable time records now plus its wait — as `{provider, until, at, source}` lines in `<paths.queue_state>/provider-out.jsonl`; the newest record per provider wins. `agent-ledger --cap` and `main-start` print the live line, for example `providers: zai free · openrouter out until 18:40`; never state which providers or agents are limited — read that line.
256
+
257
+ The owner's pick order is enforced, not prose: config `ledger.prefer` names agents in order (first = preferred, empty = off). While a higher pick's provider is free, the spawn gates refuse a lower pick unless the brief carries `Pick note: <why>`, and a brief that claims a provider the recorded state shows free is rate-limited is refused outright. `agent-score gate` ranks inside the order: with an earlier pick free it names that one (`gate: glm is first in prefer and free → use it`) instead of recommending a later paid agent by score; with `ledger.prefer` empty the old score-only verdicts stand.
258
+
249
259
  ## Suspicious actions (`neurastream traces actions`)
250
260
 
251
261
  `neurastream traces actions <runId|--since 24h> [--json]` lists the suspicious tool actions a run's trace shows: reads of secret paths (`traces.actions.secret_globs`), network commands (`net_tools`) to unknown hosts, pipes into a shell (`shell_patterns`), and writes outside `write_roots` (empty = `paths.work_roots`; both empty = off) or on `deny_globs`. The high ones also open realtime suspicious-action incidents.
@@ -362,6 +372,18 @@ Live copies are never hand-edited. `neurastream doctor` names each hand-edited i
362
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.
363
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`.
364
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
+
365
387
  ## License
366
388
 
367
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.36",
3
+ "version": "0.2.39",
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";
@@ -39,6 +41,7 @@ import { adapterLog } from "./launch.ts";
39
41
  import { parseTraceFile } from "./traces.ts";
40
42
  import { packageJsonPath, packageVersion } from "./package-root.ts";
41
43
  import * as q from "../../core/queue/lib.ts";
44
+ import { pinModel, providerOfModel, recordOut, resetEpochFromText } from "../../core/provider-state.ts";
42
45
  import { annotateResetTimes } from "../../core/reset-time.ts";
43
46
  // Registers the plugin-command matcher into core's writeTargets (side effect).
44
47
  import "./package-ops.ts";
@@ -79,6 +82,9 @@ interface EventReply {
79
82
  toolCalls: number;
80
83
  /** The provider's error text on a turn that ended on one (`429 … retry-after-ms=…`); null otherwise. */
81
84
  errorMessage: string | null;
85
+ /** The provider and model fields of the assistant message, when the event carries them; the provider-out recording keys on the provider. */
86
+ provider: string | null;
87
+ model: string | null;
82
88
  }
83
89
 
84
90
  function lastAssistantIn(messages: unknown): EventReply | null {
@@ -97,6 +103,8 @@ function lastAssistantIn(messages: unknown): EventReply | null {
97
103
  stopReason: typeof m.stopReason === "string" ? m.stopReason : null,
98
104
  toolCalls: content.filter(c => asRecord(c).type === "toolCall").length,
99
105
  errorMessage: typeof m.errorMessage === "string" ? m.errorMessage : null,
106
+ provider: typeof m.provider === "string" ? m.provider : null,
107
+ model: typeof m.model === "string" ? m.model : null,
100
108
  };
101
109
  }
102
110
  return null;
@@ -287,6 +295,42 @@ function redactToolResult(content: unknown[], cfg: Config): { content: unknown[]
287
295
  return { content: out, note: redactSummary([...hits].map(([type, count]) => ({ type, count }))) };
288
296
  }
289
297
 
298
+ // Provider out-until from live data (plan 20261025_1700 P1). Two automatic recordings, both
299
+ // keyed on the provider half of an agent pin's `model:` frontmatter, both best effort and
300
+ // logged once. The reset-time case trusts the provider's own words; the no-time case falls
301
+ // back to the armed rate-limit wait, so a provider without a quoted reset time still lands in
302
+ // the file the guards and the ledger read.
303
+ const resetRule = (cfg: Config): { pattern: string; zone: string } => ({ pattern: cfg.quota.reset_pattern, zone: cfg.quota.reset_tz });
304
+
305
+ /** Task result that quotes a reset time: record it for the sub's provider. A batch naming
306
+ * several providers cannot attribute the time to one of them, so it records nothing. */
307
+ function recordProviderOutFromTask(e: Record<string, unknown>, content: unknown[], cfg: Config): void {
308
+ if (asString(e.toolName) !== "task" || e.isError === true) return;
309
+ const text = content.map(p => asString(asRecord(p).text)).join("\n");
310
+ const epoch = resetEpochFromText(text, resetRule(cfg));
311
+ if (epoch === null) return;
312
+ const tasks = Array.isArray(asRecord(e.input).tasks) ? (asRecord(e.input).tasks as unknown[]) : [];
313
+ const providers = new Set<string>();
314
+ for (const t of tasks) {
315
+ const provider = providerOfModel(pinModel(cfg, asString(asRecord(t).agent)));
316
+ if (provider) providers.add(provider);
317
+ }
318
+ if (providers.size !== 1) return;
319
+ const provider = [...providers][0]!;
320
+ recordOut(cfg, provider, epoch, "task-result");
321
+ adapterLog(cfg, `PROVIDER-OUT recorded: ${provider} out until ${new Date(epoch * 1000).toISOString()} (task result)`);
322
+ }
323
+
324
+ /** Rate-limited turn end: record the reset time the error text names, else the armed wait. */
325
+ function recordProviderOutFromRateLimit(reply: EventReply | null, untilMs: number, cfg: Config): void {
326
+ const provider = reply?.provider ?? providerOfModel(reply?.model ?? null);
327
+ if (!provider) return;
328
+ const named = reply ? resetEpochFromText(reply.errorMessage ?? "", resetRule(cfg)) : null;
329
+ const epoch = named ?? Math.floor(untilMs / 1000);
330
+ recordOut(cfg, provider, epoch, named !== null ? "rate-limit-reset" : "rate-limit");
331
+ adapterLog(cfg, `PROVIDER-OUT recorded: ${provider} out until ${new Date(epoch * 1000).toISOString()} (${named !== null ? "reset time in error text" : "rate limit, no reset time"})`);
332
+ }
333
+
290
334
  // Session rollover helpers: the harness context read through runtime checks, and the file size and
291
335
  // mtime reads. The decisions are in src/core/rollover.ts.
292
336
  const WAIT_NOTICE_MS = 15 * 60_000;
@@ -445,6 +489,17 @@ export function ownerInboxMessage(rec: Record<string, unknown>): string | ({ typ
445
489
  }
446
490
  return parts;
447
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
+ }
448
503
  default:
449
504
  return null;
450
505
  }
@@ -504,6 +559,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
504
559
  let inboxTimer: unknown;
505
560
  const calls = new Map<string, number>(); // subagent call budget, by agent id
506
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
507
563
  // Chat notify (plans 20261024_2155, 20261025_0130): the text a hand-back already posted
508
564
  // (attempted) — one post per distinct text, never a retry loop. The reply itself comes from
509
565
  // the stop/agent_end event, never the session file (session_stop fires BEFORE agent_end, and
@@ -673,25 +729,76 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
673
729
  inboxTimer = it;
674
730
  });
675
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
+
676
767
  pi.on("before_agent_start", (event, ctx) => {
677
- 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
+ }
678
778
  if (rateTimer !== null) {
679
779
  clearRateTimer();
680
780
  adapterLog(cfg, "RATE-LIMIT resume cancelled: owner message");
681
781
  }
682
- const d = checkInject({ inject: asString(asRecord(event).prompt), agent: "main" }, cfg);
782
+ const d = checkInject({ inject: prompt, agent: "main" }, cfg);
683
783
  callsSinceStop = d.state?.callsSinceStop ?? callsSinceStop;
684
784
  idleStops = d.state?.idleStops ?? idleStops;
685
785
  const notice = rolloverNotice(ctx);
686
786
  // A turn the harness starts from the guard's own stop continuation is not an owner
687
787
  // message: D4 (owner-correction) only sees real prompts; D1/D3 run either way.
688
- const prompt = asString(asRecord(event).prompt);
689
788
  // Machine prompts (guard continuation, rollover note request, handoff note) are not owner messages.
690
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();
691
798
  return {
692
799
  message: {
693
800
  customType: "main-guard.queue",
694
- content: [d.inject, notice].filter(Boolean).join("\n\n"),
801
+ content: [d.inject, notice, ...rules].filter(Boolean).join("\n\n"),
695
802
  display: false,
696
803
  },
697
804
  };
@@ -751,6 +858,8 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
751
858
  return { block: true, reason: d.reason };
752
859
  }
753
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);
754
863
  // The originals return nothing on a clean call; only warn injects carry an object.
755
864
  const out = toExtensionResult(d);
756
865
  return Object.keys(out).length > 0 ? out : undefined;
@@ -775,6 +884,13 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
775
884
  const redacted = redactToolResult(Array.isArray(e.content) ? e.content : [], cfg);
776
885
  const content = redacted.content;
777
886
  const notes: string[] = redacted.note ? [redacted.note] : [];
887
+ // Provider out-until from a task result that quotes a reset time (plan 20261025_1700 P1):
888
+ // recorded from the redacted text before anything else, never thrown.
889
+ try {
890
+ recordProviderOutFromTask(e, content, cfg);
891
+ } catch (err) {
892
+ adapterLog(cfg, `PROVIDER-OUT record failed: ${err instanceof Error ? err.message : String(err)}`);
893
+ }
778
894
  if (snap) {
779
895
  pending.delete(id);
780
896
  for (const [file, before] of snap) {
@@ -850,6 +966,13 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
850
966
  // and without touching the idle-stop counters: checkStop is not consulted.
851
967
  const rl = rateLimitOf(reply);
852
968
  if (rl) {
969
+ // Who is rate-limited is live data (plan 20261025_1700 P1): the error text's own reset
970
+ // time, else the armed wait. Best effort — a failed write never changes the stop.
971
+ try {
972
+ recordProviderOutFromRateLimit(reply, rl.untilMs, cfg);
973
+ } catch (err) {
974
+ adapterLog(cfg, `PROVIDER-OUT record failed: ${err instanceof Error ? err.message : String(err)}`);
975
+ }
853
976
  onRateLimitedStop(rl.untilMs, rl.waitMs);
854
977
  return undefined;
855
978
  }
@@ -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));
@@ -12,6 +12,7 @@ import { queueCancel } from "../core/queue-cancel.ts";
12
12
  import { queueCheck } from "../core/queue-check.ts";
13
13
  import { queueTrim } from "../core/queue-trim.ts";
14
14
  import { queueClose } from "../core/queue-close.ts";
15
+ import { queueFinished } from "../core/queue-finished.ts";
15
16
  import { resourceAlerts } from "../core/resource-alerts.ts";
16
17
  import { tmpSnapshot } from "../core/tmp-snapshot.ts";
17
18
  import { wipBackup } from "../core/wip-backup.ts";
@@ -32,6 +33,7 @@ export const PORTED = [
32
33
  "queue-check",
33
34
  "queue-trim",
34
35
  "queue-close",
36
+ "queue-finished",
35
37
  "queue-cancel",
36
38
  "main-start",
37
39
  "machine-guard",
@@ -72,6 +74,8 @@ export async function runPorted(cmd: string, args: string[]): Promise<number> {
72
74
  return queueTrim(args, rt.cfg);
73
75
  case "queue-close":
74
76
  return queueClose(args, rt.cfg);
77
+ case "queue-finished":
78
+ return queueFinished(args, rt.cfg);
75
79
  case "queue-cancel":
76
80
  return queueCancel(args, rt.cfg);
77
81
  case "main-start": {
@@ -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
+ }