neurastream 0.2.6 → 0.2.7

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
@@ -25,7 +25,7 @@ flowchart LR
25
25
  |---|---|
26
26
  | Queue (`queue-check`, `queue-close`, `queue-cancel`) | Every open plan is a file in a main checkout, listed in the one main index (`paths.queue_index`, one absolute path per line — never repo directories) and follows a template; one plan = one worktree. A plan leaves the queue only when its branch is merged into remote main and its done check passes; a failing check reopens it. Closing removes the plan's worktree when it is clean and its branch landed — a plain `git worktree remove`; a dirty, unmerged or unremovable worktree and the repo's main checkout are kept with the reason. Branches leave only via `git branch -d`, so a branch whose merge git cannot see stays. |
27
27
  | Blockers | Each plan's phase 0 lists what helpers may not do: push, touch a path, run a command, or write a text. The guard judges the command that runs and the files it changes, not words inside commit messages, quoted text or heredoc bodies: `git commit -m "... push ..."` is allowed, `git push` is refused. |
28
- | Guards | Helpers may only edit their plan's `## Progress`; every new entry ends with a `Findings:` line (`Findings: none`, or one item per finding with `file:line` evidence) or the edit is refused and the file restored, and each item becomes an incident. Helpers get a warning at call 90 and are stopped at call 100; Main can set a different stop for one run with a `Call budget: <N>` line in the task brief (see "Main reads the code for its plans" below). Protected files need an owner unlock (a file the owner touches, valid 30 minutes). |
28
+ | Guards | Helpers may only edit their plan's `## Progress`; every new entry ends with a `Findings:` line (`Findings: none`, or one item per finding with `file:line` evidence) or the edit is refused and the file restored, and each item becomes an incident. Helpers get a warning at call 90 and are stopped at call 100; Main can set a different stop for one run with a `Call budget: <N>` line in the task brief (see "Main reads the code for its plans" below). Protected files need an owner unlock (a file the owner touches, valid 30 minutes). With `guards.chat_unlock` on (default off), the owner's whole chat message `unlock` / `unlock N` / `lock` — typed in the terminal or through a collab guest prompt from a write peer — moves that file instead; nothing a model, a subagent or a tool produces can. |
29
29
  | Ledger (`agent-ledger`) | Tokens, cost, state and exit reason per agent; `--cap` refuses a spawn when a provider already runs 2. |
30
30
  | Scoring (`agent-score`) | Points only for work Main accepted by commit, times the phase difficulty. Ranked per dollar and per hour. |
31
31
  | Brief lint (`brief-lint`) | Refuses a helper brief that misses a required rule (acceptance, stop condition, no push, call budget). |
@@ -119,6 +119,46 @@ In both modes:
119
119
  - The previous session file stays where it is.
120
120
  - `rollover.enabled: false` turns the feature off.
121
121
 
122
+ ## Notify the owner
123
+
124
+ When Main's turn ends and the session stop hands back to the owner, neurastream posts Main's final reply to the configured chat channels — deterministic code in the adapter, no model call, no tokens, never forgotten. Discord, Slack, both, or neither: notify is off until a webhook file exists.
125
+
126
+ The webhook URL is a secret (anyone holding it can post as the bot), so it never goes into `config.yml`. The config holds the file's path only (`docs/config.md`):
127
+
128
+ ```yaml
129
+ notify:
130
+ discord_webhook_file: "~/.config/neurastream/secrets/discord-webhook" # "" = off
131
+ slack_webhook_file: "~/.config/neurastream/secrets/slack-webhook" # "" = off
132
+ prefix: "" # optional label prepended to each post, e.g. "Main:"
133
+ ```
134
+
135
+ Set a channel up:
136
+
137
+ - Discord: Server Settings → Integrations → Webhooks → New Webhook → copy the URL.
138
+ - Slack: add the "Incoming Webhooks" app to your workspace → copy the webhook URL for your channel.
139
+
140
+ Then write the URL into its secret file — as the owner, in a terminal (the guard refuses agents; the examples show the path, never a URL):
141
+
142
+ ```sh
143
+ umask 077
144
+ mkdir -p ~/.config/neurastream/secrets
145
+ printf '%s' '<url>' > ~/.config/neurastream/secrets/discord-webhook
146
+ chmod 600 ~/.config/neurastream/secrets/discord-webhook
147
+ ```
148
+
149
+ Repeat for `slack-webhook`, then check:
150
+
151
+ ```sh
152
+ neurastream doctor # problems: a loose file mode, a raw URL in config.yml, a secret next to config.yml; warning: a missing file
153
+ neurastream notify test # posts one line to every configured channel; exit 1 when one fails
154
+ ```
155
+
156
+ Guard rules around it:
157
+
158
+ - No agent (Main included) can read a configured secret file, list its directory, or glob over it — unlock or not. Writes to the secret files and to `~/.config/neurastream/config.yml` need the owner's unlock like any guard file.
159
+ - A stop the guard blocks posts nothing; when Main continues and really hands back later, that later stop posts the final text. A subagent session never posts, and a relaunch (the launcher's rollover) posts nothing.
160
+ - The post never delays the stop decision: it times out at 5 seconds per chunk, makes one attempt, and writes one guard-log line when a channel fails. Long replies are split per channel (Discord 2000, Slack 3000 characters) on line boundaries where possible.
161
+
122
162
  ## Self-metrics
123
163
 
124
164
  `neurastream metrics report [--days N]` compares this window (the last `metrics.report_days`, default 7) with the one before it, writes `<paths.notes>/metrics.md`, and prints the same report. Worst change is marked `◀ worst`. The five numbers:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.6",
3
+ "version": "0.2.7",
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",
@@ -11,6 +11,7 @@ import { dirname, join, relative, resolve } from "node:path";
11
11
  import { fileURLToPath } from "node:url";
12
12
  import { blockState, renderBlock } from "../../core/agents-md.ts";
13
13
  import { loadConfig } from "../../core/config.ts";
14
+ import { notifyFindings } from "../../core/notify.ts";
14
15
  import { readIndex } from "../../core/queue/lib.ts";
15
16
 
16
17
  const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
@@ -196,6 +197,9 @@ export function doctorReport(home: string, env: NodeJS.ProcessEnv = process.env)
196
197
  if (state === "ok") ok.push(`${agents} neurastream block`);
197
198
  else problems.push(`${state}: ${agents} neurastream block`);
198
199
  const warnings: string[] = [];
200
+ const notify = notifyFindings(cfg);
201
+ problems.push(...notify.problems);
202
+ warnings.push(...notify.warnings);
199
203
  const viewed = npmViewVersion(name, env);
200
204
  let registry: string | null = null;
201
205
  if ("warning" in viewed) warnings.push(viewed.warning);
@@ -23,11 +23,12 @@ import { loadConfig, type Config } from "../../core/config.ts";
23
23
  import { nowSec } from "../../core/clock.ts";
24
24
  import { runDetectorsGated } from "../../core/incident-detectors.ts";
25
25
  import { checkInject, checkPlanEdit, checkStop, checkTool, MAIN_PLAN_FILE, recordMainResult, rekeySpawnFile } from "../../core/guards.ts";
26
+ import { postReply } from "../../core/notify.ts";
26
27
  import { applyQueueEnv } from "../../core/queue/env.ts";
27
28
  import { mainStartText, runDailyCheck } from "../../core/main-start.ts";
28
29
  import { readBlocks } from "../../core/metrics.ts";
29
30
  import { buildHandoff, holdsBlock, notePath, noteRequest, OWNER_AWAY, ownerText, relaunchPath, rolloverState, spawnRefusal, type RolloverState } from "../../core/rollover.ts";
30
- import { defaultCompletedResults, defaultRunSource } from "./sessions.ts";
31
+ import { defaultCompletedResults, defaultRunSource, lastAssistantText } from "./sessions.ts";
31
32
  import { packageJsonPath, packageVersion } from "./package-root.ts";
32
33
  import * as q from "../../core/queue/lib.ts";
33
34
  // Registers the plugin-command matcher into core's writeTargets (side effect).
@@ -268,6 +269,10 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
268
269
  let timer: unknown;
269
270
  const calls = new Map<string, number>(); // subagent call budget, by agent id
270
271
  const pending = new Map<string, Map<string, string>>(); // toolCallId -> plan snapshots
272
+ // Chat notify (plan 20261024_2155): the last assistant text of the main session, and the text
273
+ // a stop already posted (attempted) — one post per distinct text, never a retry loop.
274
+ let lastReply: string | null = null;
275
+ let postedReply: string | null = null;
271
276
 
272
277
  pi.on("session_start", (_e, ctx) => {
273
278
  const c = asCtx(ctx);
@@ -415,6 +420,17 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
415
420
  if (c.hasAgent && c.kind !== "main") return;
416
421
  // A relaunch is requested: omp shuts down at the next idle, so the stop must not be continued.
417
422
  if (relaunched) return undefined;
423
+ // The stop hands the turn back to the owner: post Main's final reply, once per distinct
424
+ // text. Fire-and-forget: the decision never awaits the post; a failed or slow post logs
425
+ // one line and never blocks or retries.
426
+ const notifyOwner = (): void => {
427
+ const text = lastReply;
428
+ if (!text || text === postedReply) return;
429
+ postedReply = text;
430
+ void postReply(text, cfg).then(results => {
431
+ for (const r of results) if (!r.posted) adapterLog(cfg, `notify: ${r.provider}: ${r.error}`);
432
+ });
433
+ };
418
434
  // A pending rollover decides the stop and checkStop is not consulted: its queue, incident and cancel
419
435
  // blocks would hold Main at a wait the new session raises again through main-start, and its "spawn an
420
436
  // agent" text is refused while the rollover is pending.
@@ -427,15 +443,21 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
427
443
  }
428
444
  if (snap.state === "ready" || snap.state === "wait-jobs") {
429
445
  adapterLog(cfg, `ALLOW stop: rollover ${snap.state}`);
430
- // Under the launcher a ready rollover starts now; plain omp waits for the owner's next message.
431
- if (snap.state === "ready" && process.env.NEURASTREAM_MAIN_LAUNCHER === "1") requestRelaunch(rc, notePath(rc.sessionId));
446
+ // Under the launcher a ready rollover starts now (not a hand-back to the owner);
447
+ // plain omp waits for the owner's next message.
448
+ const handsToOwner = !(snap.state === "ready" && process.env.NEURASTREAM_MAIN_LAUNCHER === "1" && requestRelaunch(rc, notePath(rc.sessionId)));
449
+ if (handsToOwner) notifyOwner();
432
450
  return undefined;
433
451
  }
434
452
  }
435
453
  const d = checkStop({ agent: "main", callsSinceStop, idleStops, ledgerText: ledgerText(cfg) }, cfg);
436
454
  callsSinceStop = d.state?.callsSinceStop ?? 0;
437
455
  idleStops = d.state?.idleStops ?? idleStops;
438
- return d.allow ? undefined : { decision: "block", reason: d.reason };
456
+ if (d.allow) {
457
+ notifyOwner();
458
+ return undefined;
459
+ }
460
+ return { decision: "block", reason: d.reason };
439
461
  });
440
462
 
441
463
  // Session rollover (src/core/rollover.ts). Main's session size decides when a handoff note is
@@ -623,6 +645,17 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
623
645
  }
624
646
  };
625
647
  pi.on("agent_end", (e, ctx) => onSizeCheck("agent_end", e, ctx));
648
+ // The text a later allowed stop posts: the last assistant message of each terminal run end in
649
+ // the main session (omp 18.11.1 sets willContinue on a non-terminal end). A blocked stop keeps
650
+ // Main talking, so the final run end overwrites this before the stop that really hands back.
651
+ pi.on("agent_end", (e, ctx) => {
652
+ if (!isMain(ctx)) return;
653
+ if (asRecord(e).willContinue === true) return;
654
+ const rc = asRolloverCtx(ctx);
655
+ if (!rc) return;
656
+ const text = lastAssistantText(rc.sessionFile);
657
+ lastReply = text.trim() ? text : null;
658
+ });
626
659
 
627
660
  // omp is really shutting down: the exit-grace fallback must not fire.
628
661
  pi.on("session_shutdown", () => clearGrace?.());
@@ -653,6 +686,64 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
653
686
  return null;
654
687
  };
655
688
 
689
+ // Chat unlock (guards.chat_unlock): the owner's whole message "unlock"/"unlock N"/"lock" moves
690
+ // the guard unlock file (src/core/queue/lib.ts chatUnlock). Only prompts the owner really typed
691
+ // count: the local terminal (input event, source "interactive") and collab guest prompts from
692
+ // write peers. This handler is registered BEFORE the rollover input handler below, so the unlock
693
+ // wins while a rollover is ready or in flight (emitInput short-circuits on { handled: true }).
694
+ const notifyUnlock = (ctx: unknown, r: { command?: "unlock" | "lock"; minutes?: number }): void => {
695
+ const c = asRolloverCtx(ctx);
696
+ if (!c) return;
697
+ if (r.command === "unlock" && r.minutes !== undefined) {
698
+ const until = new Date(Date.now() + r.minutes * 60_000).toLocaleTimeString();
699
+ c.notify(`guard unlocked for ${r.minutes} min (until ${until})`);
700
+ } else if (r.command === "lock") {
701
+ c.notify("guard locked again");
702
+ }
703
+ };
704
+ pi.on("input", (event, ctx) => {
705
+ if (!cfg.guards.chat_unlock || !isMain(ctx)) return undefined;
706
+ const e = asRecord(event);
707
+ if (asString(e.source) !== "interactive") return undefined;
708
+ const r = q.chatUnlock(asString(e.text), cfg, "interactive");
709
+ if (!r.applied) return undefined;
710
+ notifyUnlock(ctx, r);
711
+ return { handled: true };
712
+ });
713
+ // A collab guest prompt (collab/host.ts #handlePrompt, write peers only) is NOT an input event:
714
+ // it is session.promptCustomMessage({ customType: "collab-prompt", details: { from },
715
+ // attribution: "user" }), which lands in the agent context — the adapter sees it on the
716
+ // "context" event (types.ts ContextEvent, the messages about to go to the LLM). The message
717
+ // stays in the transcript, so later LLM calls replay it: a seen key (timestamp + text) is acted
718
+ // on once, and a resumed session replaying old prompts is stopped by the age limit.
719
+ const seenChatPrompts = new Set<string>();
720
+ const CHAT_PROMPT_MAX_AGE_MS = 10 * 60_000;
721
+ pi.on("context", (event, ctx) => {
722
+ if (!cfg.guards.chat_unlock || !isMain(ctx)) return undefined;
723
+ const messages = asRecord(event).messages;
724
+ if (!Array.isArray(messages)) return undefined;
725
+ for (const raw of messages) {
726
+ const m = asRecord(raw);
727
+ if (m.role !== "custom" || m.customType !== "collab-prompt" || m.attribution !== "user") continue;
728
+ const from = asString(asRecord(m.details).from);
729
+ if (from === "") continue;
730
+ const text =
731
+ typeof m.content === "string"
732
+ ? m.content
733
+ : Array.isArray(m.content)
734
+ ? m.content.map(c => asString(asRecord(c).text)).join("")
735
+ : "";
736
+ const timestamp = typeof m.timestamp === "number" ? m.timestamp : 0;
737
+ if (Date.now() - timestamp > CHAT_PROMPT_MAX_AGE_MS) continue;
738
+ const key = `${timestamp}:${text}`;
739
+ if (seenChatPrompts.has(key)) continue;
740
+ seenChatPrompts.add(key);
741
+ const r = q.chatUnlock(text, cfg, `collab:${from}`);
742
+ if (r.applied) notifyUnlock(ctx, r);
743
+ }
744
+ return undefined;
745
+ });
746
+
656
747
  // Under the launcher the relaunch is the only rollover path: a plain interactive message in the ready
657
748
  // state requests it, and every such message joins the pending request's draft, in order. Plain omp keeps
658
749
  // `/main-rollover <text>`: the message becomes the owner's first message of the new session.
@@ -49,6 +49,37 @@ function asObj(v: unknown): Record<string, unknown> | null {
49
49
  return typeof v === "object" && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : null;
50
50
  }
51
51
 
52
+ /** The joined text of the session file's last assistant message, trimmed; "" when there is none
53
+ * (unreadable file, no assistant message, or a tool-use-only ending). */
54
+ export function lastAssistantText(file: string): string {
55
+ let text: string;
56
+ try {
57
+ text = readFileSync(file, "utf8");
58
+ } catch {
59
+ return "";
60
+ }
61
+ let out = "";
62
+ for (const line of text.split("\n")) {
63
+ if (!line.trim()) continue;
64
+ let parsed: unknown;
65
+ try {
66
+ parsed = JSON.parse(line);
67
+ } catch {
68
+ continue;
69
+ }
70
+ const d = asObj(parsed);
71
+ if (!d) continue;
72
+ const m = asObj(d.message) ?? d;
73
+ if (m.role !== "assistant") continue;
74
+ const content = Array.isArray(m.content) ? m.content : [];
75
+ const texts = content
76
+ .filter((c): c is Record<string, unknown> => asObj(c) !== null && asObj(c)?.type === "text")
77
+ .map(c => String(c.text ?? ""));
78
+ out = texts.join("\n").trim();
79
+ }
80
+ return out;
81
+ }
82
+
52
83
  function costOf(m: Record<string, unknown>): number {
53
84
  const u = asObj(m.usage);
54
85
  const c = u ? asObj(u.cost) : null;
@@ -1,4 +1,5 @@
1
- import { ConfigError, configFile, loadConfig } from "../core/config.ts";
1
+ import { ConfigError, configFile, loadConfig, type Config } from "../core/config.ts";
2
+ import { postReply } from "../core/notify.ts";
2
3
  import { applyQueueEnv } from "../core/queue/env.ts";
3
4
  import { runAdapterInstall } from "../adapters/omp/install.ts";
4
5
  import { runDoctor } from "../adapters/omp/doctor.ts";
@@ -51,6 +52,7 @@ export function helpText(): string {
51
52
  " template-identical pins and the AGENTS.md block (--purge adds",
52
53
  " config + agent-dir state); prints the list, refuses outside HOME",
53
54
  " neurastream doctor report hand-edited live files and a stale install",
55
+ " neurastream notify test post a test message to the configured Discord/Slack webhooks",
54
56
  " neurastream queue migrate fold the old repo INDEX.md files into the one main index",
55
57
  " neurastream config [--json] print the merged config (defaults + file + env)",
56
58
  " neurastream guard <event> --json",
@@ -90,6 +92,7 @@ export async function run(cmd: string, args: string[]): Promise<number> {
90
92
  }
91
93
  }
92
94
  if (cmd === "doctor") return runDoctor();
95
+ if (cmd === "notify") return runNotify(args);
93
96
  if (cmd === "uninstall") return runUninstall(args);
94
97
  if (cmd === "queue" && args[0] === "migrate") {
95
98
  try {
@@ -116,6 +119,35 @@ export async function run(cmd: string, args: string[]): Promise<number> {
116
119
  return 2;
117
120
  }
118
121
 
122
+ const NOTIFY_USAGE = "usage: neurastream notify test";
123
+
124
+ /** `neurastream notify test`: post one line to every configured provider; exit 1 when any fails. */
125
+ function runNotify(args: string[]): number | Promise<number> {
126
+ if (args[0] !== "test" || args.length !== 1) {
127
+ console.error(NOTIFY_USAGE);
128
+ return 2;
129
+ }
130
+ let cfg: Config;
131
+ try {
132
+ cfg = loadConfig();
133
+ } catch (err) {
134
+ console.error(err instanceof ConfigError ? err.message : String(err));
135
+ return 1;
136
+ }
137
+ return postReply("neurastream notify test", cfg).then(results => {
138
+ let failed = 0;
139
+ for (const r of results) {
140
+ if (r.posted) console.log(`notify ${r.provider}: posted (${r.chunks} chunk${r.chunks === 1 ? "" : "s"})`);
141
+ else {
142
+ failed++;
143
+ console.error(`notify ${r.provider}: ${r.error}`);
144
+ }
145
+ }
146
+ if (results.length === 0) console.log("notify: no provider configured (notify.discord_webhook_file / notify.slack_webhook_file)");
147
+ return failed > 0 ? 1 : 0;
148
+ });
149
+ }
150
+
119
151
  const AGENTS_USAGE = "usage: neurastream agents list | allow <slug>... | deny <slug>...";
120
152
 
121
153
  function runAgents(args: string[]): number {
@@ -105,6 +105,8 @@ export interface Config {
105
105
  main_edit_limit: number;
106
106
  main_window_min: number;
107
107
  unlock_minutes: number;
108
+ /** The owner's whole chat message ("unlock", "unlock N", "lock") moves the guard unlock file. */
109
+ chat_unlock: boolean;
108
110
  plan_read_max_hours: number;
109
111
  idle_stops: number;
110
112
  blocker_timeout_ms: number;
@@ -146,6 +148,9 @@ export interface Config {
146
148
  watch_streak: number;
147
149
  };
148
150
  quota: { reset_tz: string; label: string };
151
+ /** Chat notify (src/core/notify.ts): Main's final reply goes to these webhooks at session_stop.
152
+ * The values are paths to secret files holding the webhook URLs — never the URLs themselves. */
153
+ notify: { discord_webhook_file: string; slack_webhook_file: string; prefix: string };
149
154
  priority: { sleep_sec: number };
150
155
  alerts: { temp_c: number; mem_psi: number; io_psi: number; cooldown_sec: number };
151
156
  snapshot: { tmp_dest: string; git_repo: string; git_backup: string; excludes: string[] };
@@ -23,6 +23,7 @@ import path from "node:path";
23
23
  import type { Decision, InjectEvent, PlanEditEvent, SpawnEvent, StopEvent, ToolEvent } from "./adapter.ts";
24
24
  import type { Config } from "./config.ts";
25
25
  import { addIncident, openIncidents, type IncidentView } from "./incidents.ts";
26
+ import { notifyProtectedPaths, notifySecretReadHit } from "./notify.ts";
26
27
  import * as q from "./queue/lib.ts";
27
28
  import type { Plan } from "./queue/lib.ts";
28
29
 
@@ -193,6 +194,9 @@ function protectedHit(paths: string[], cfg: Config): string | null {
193
194
  const g = q.expandHome(raw);
194
195
  if (g.endsWith("/") ? p.startsWith(g) || `${p}/` === g : p === g) return p;
195
196
  }
197
+ // The user's config file and the configured notify secret files are guard surface too:
198
+ // an agent that could rewrite them could point notify at its own webhook.
199
+ if (notifyProtectedPaths(cfg).includes(p)) return p;
196
200
  }
197
201
  return null;
198
202
  }
@@ -510,6 +514,14 @@ export function checkTool(e: ToolEvent, cfg: Config): Decision {
510
514
  for (const p of [...(e.paths ?? []), ...q.touchedPaths(e.tool, input, e.cwd)]) if (!paths.includes(p)) paths.push(p);
511
515
  const writes: string[] = [];
512
516
  for (const p of [...(e.writes ?? []), ...q.writeTargets(e.tool, input, e.cwd)]) if (!writes.includes(p)) writes.push(p);
517
+ // Notify secrets: no agent, main or sub, reads a webhook URL — with or without the unlock.
518
+ // A call that changes a secret is not a read: its target goes through the protected-write
519
+ // rule above, so the owner's unlock covers it like any guard file.
520
+ const secretHit = notifySecretReadHit(paths.filter(p => !writes.includes(p)), cfg);
521
+ if (secretHit) {
522
+ log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} notify secret: ${secretHit}`);
523
+ return deny(`plan-guard: ${secretHit} is a notify secret path. Only the owner touches the webhook files, in a terminal.`);
524
+ }
513
525
  // Main writes its own rollover note unattended (the note turn has nobody to ask). Only a Write
514
526
  // of a .md directly in <state>/rollover/ is exempt; shell writes, subagents and relaunch.json stay refused.
515
527
  const rolloverDir = path.join(q.stateDirPath(), "rollover");
@@ -521,7 +533,9 @@ export function checkTool(e: ToolEvent, cfg: Config): Decision {
521
533
  if (hit && !unlocked(cfg)) {
522
534
  log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} protected: ${hit}`);
523
535
  return deny(
524
- `plan-guard: ${hit} is a protected guard file. Only the owner changes it (unlock: \`touch ${q.UNLOCK}\` in a terminal, valid ${cfg.guards.unlock_minutes} min).`,
536
+ `plan-guard: ${hit} is a protected guard file. Only the owner changes it (unlock: \`touch ${q.UNLOCK}\` in a terminal${
537
+ cfg.guards.chat_unlock ? `, or type \`unlock ${cfg.guards.unlock_minutes}\` in chat` : ""
538
+ }, valid ${cfg.guards.unlock_minutes} min).`,
525
539
  );
526
540
  }
527
541
  if (e.agent === "main") {
@@ -0,0 +1,197 @@
1
+ // Chat notify (plan 20261024_2155): Main's final reply is posted to Discord and/or Slack when a
2
+ // session stop hands the turn back to the owner. The webhook URLs live in secret files — the
3
+ // config holds only their paths. This module knows the configured paths, keeps every agent away
4
+ // from them (guard rules in guards.ts), and does the posting. Plain TypeScript, no harness here.
5
+
6
+ import { dirname } from "node:path";
7
+ import { readFileSync, statSync } from "node:fs";
8
+ import { configFile, type Config } from "./config.ts";
9
+
10
+ export type NotifyProviderName = "discord" | "slack";
11
+
12
+ export interface NotifyProvider {
13
+ name: NotifyProviderName;
14
+ /** Path of the secret file holding this provider's webhook URL. */
15
+ file: string;
16
+ }
17
+
18
+ /** The configured providers in posting order; a provider is on when its file path is non-empty. */
19
+ export function notifyProviders(cfg: Config): NotifyProvider[] {
20
+ const out: NotifyProvider[] = [];
21
+ if (cfg.notify.discord_webhook_file) out.push({ name: "discord", file: cfg.notify.discord_webhook_file });
22
+ if (cfg.notify.slack_webhook_file) out.push({ name: "slack", file: cfg.notify.slack_webhook_file });
23
+ return out;
24
+ }
25
+
26
+ /** The configured secret files (paths only; contents are read at post time, never cached). */
27
+ export function notifySecretFiles(cfg: Config): string[] {
28
+ return notifyProviders(cfg).map(p => p.file);
29
+ }
30
+
31
+ /** Writes that change a notify secret or the config file itself need the owner's unlock. */
32
+ export function notifyProtectedPaths(cfg: Config): string[] {
33
+ return [configFile(cfg.paths.home), ...notifySecretFiles(cfg)];
34
+ }
35
+
36
+ const GLOB_META = /[*?[]/;
37
+
38
+ function hitsSecret(p: string, file: string): boolean {
39
+ const dir = dirname(file);
40
+ if (p === file || p === dir || p.startsWith(`${dir}/`)) return true;
41
+ const m = GLOB_META.exec(p);
42
+ if (!m) return false;
43
+ const base = p.slice(0, m.index).replace(/\/+$/, "");
44
+ if (!base) return false;
45
+ // The glob's literal prefix is the secrets dir, sits inside it, or is an ancestor of it:
46
+ // every match it can name is a secret (or reveals the directory listing).
47
+ return base === dir || base.startsWith(`${dir}/`) || dir.startsWith(`${base}/`);
48
+ }
49
+
50
+ /** The first touched read path that hits a configured secret file, its directory, or a glob over
51
+ * them; null otherwise. Refused with or without the guard unlock: no agent ever needs a webhook
52
+ * URL. Reading the config file itself and other files beside the secrets stays allowed. */
53
+ export function notifySecretReadHit(paths: string[], cfg: Config): string | null {
54
+ for (const p of paths) {
55
+ for (const file of notifySecretFiles(cfg)) {
56
+ if (hitsSecret(p, file)) return p;
57
+ }
58
+ }
59
+ return null;
60
+ }
61
+
62
+ export interface NotifyFindings {
63
+ problems: string[];
64
+ warnings: string[];
65
+ }
66
+
67
+ /** Host fragments that mark a webhook URL pasted straight into the config file, by provider. */
68
+ const RAW_URL_LABELS: Record<string, string> = {
69
+ "discord.com/api/webhooks": "discord",
70
+ "discordapp.com/api/webhooks": "discord",
71
+ "hooks.slack.com": "slack",
72
+ };
73
+
74
+ /** Doctor findings for the notify setup: a problem when a secret file is readable by group or
75
+ * others, when the config file holds a raw webhook URL, or when a secret file sits next to
76
+ * config.yml; a warning only when a configured secret file is missing (notify is simply off). */
77
+ export function notifyFindings(cfg: Config): NotifyFindings {
78
+ const problems: string[] = [];
79
+ const warnings: string[] = [];
80
+ const configPath = configFile(cfg.paths.home);
81
+ const configDir = dirname(configPath);
82
+ let raw = "";
83
+ try {
84
+ raw = readFileSync(configPath, "utf8");
85
+ } catch {}
86
+ const rawLabels = new Set<string>();
87
+ for (const [host, label] of Object.entries(RAW_URL_LABELS)) if (raw.includes(host)) rawLabels.add(label);
88
+ for (const label of rawLabels) {
89
+ problems.push(`notify: ${configPath} holds a raw ${label} webhook URL; anyone holding it can post as the bot — keep it in a secret file`);
90
+ }
91
+ for (const p of notifyProviders(cfg)) {
92
+ const key = `notify.${p.name}_webhook_file`;
93
+ let st;
94
+ try {
95
+ st = statSync(p.file);
96
+ } catch {
97
+ warnings.push(`notify: ${key} points at ${p.file}, which does not exist; notify stays off until the owner writes it`);
98
+ continue;
99
+ }
100
+ if ((st.mode & 0o77) !== 0) {
101
+ problems.push(`notify: ${p.file} is readable by group/others (mode ${(st.mode & 0o777).toString(8)}); chmod 600 it`);
102
+ }
103
+ if (dirname(p.file) === configDir) {
104
+ problems.push(`notify: ${p.file} sits next to ${configPath}; keep the webhook files in their own directory`);
105
+ }
106
+ }
107
+ return { problems, warnings };
108
+ }
109
+
110
+ // --- posting ---
111
+
112
+ const DISCORD_LIMIT = 2000;
113
+ const SLACK_LIMIT = 3000;
114
+ const POST_TIMEOUT_MS = 5000;
115
+
116
+ export interface NotifyPostResult {
117
+ provider: NotifyProviderName;
118
+ /** True when every chunk of the reply got a 2xx answer. */
119
+ posted: boolean;
120
+ chunks: number;
121
+ /** Why nothing (or not everything) was posted; empty on success. */
122
+ error: string;
123
+ }
124
+
125
+ /** https, or a loopback http URL (local fakes and self-tests): a real webhook URL is always https. */
126
+ function postableUrl(url: string): boolean {
127
+ if (url.startsWith("https://")) return true;
128
+ return /^http:\/\/(127\.0\.0\.1|localhost|\[::1\])([:/?]|$)/.test(url);
129
+ }
130
+
131
+ /** Split within the provider's limit on line boundaries where possible; a run of text longer than
132
+ * the limit is hard-split, so nothing is ever lost. */
133
+ export function notifyChunks(text: string, limit: number): string[] {
134
+ if (text.length <= limit) return [text];
135
+ const out: string[] = [];
136
+ let rest = text;
137
+ while (rest.length > limit) {
138
+ const nl = rest.lastIndexOf("\n", limit - 1);
139
+ const cut = nl > 0 ? nl + 1 : limit;
140
+ out.push(rest.slice(0, cut));
141
+ rest = rest.slice(cut);
142
+ }
143
+ if (rest.length > 0) out.push(rest);
144
+ return out;
145
+ }
146
+
147
+ function webhookUrl(p: NotifyProvider): { url: string; why: string } {
148
+ let raw = "";
149
+ try {
150
+ raw = readFileSync(p.file, "utf8").trim();
151
+ } catch (err) {
152
+ return { url: "", why: `cannot read ${p.file}: ${err instanceof Error ? err.message : String(err)}` };
153
+ }
154
+ if (raw === "") return { url: "", why: `${p.file} is empty` };
155
+ if (!postableUrl(raw)) return { url: "", why: `${p.file} does not hold an https webhook URL` };
156
+ return { url: raw, why: "" };
157
+ }
158
+
159
+ async function postChunks(provider: NotifyProvider, url: string, chunks: string[]): Promise<NotifyPostResult> {
160
+ const key = provider.name === "discord" ? "content" : "text";
161
+ for (const [i, chunk] of chunks.entries()) {
162
+ try {
163
+ const r = await fetch(url, {
164
+ method: "POST",
165
+ headers: { "content-type": "application/json" },
166
+ body: JSON.stringify({ [key]: chunk }),
167
+ signal: AbortSignal.timeout(POST_TIMEOUT_MS),
168
+ });
169
+ if (!r.ok) {
170
+ return { provider: provider.name, posted: false, chunks: i + 1, error: `${provider.name} answered ${r.status} on chunk ${i + 1}/${chunks.length}` };
171
+ }
172
+ } catch (err) {
173
+ return { provider: provider.name, posted: false, chunks: i + 1, error: `${provider.name} chunk ${i + 1}/${chunks.length} failed: ${err instanceof Error ? err.message : String(err)}` };
174
+ }
175
+ }
176
+ return { provider: provider.name, posted: true, chunks: chunks.length, error: "" };
177
+ }
178
+
179
+ /** Post Main's final reply to every configured provider, chunks in order, one attempt per chunk
180
+ * (5 s timeout). Never throws and never retries: a failed or slow post comes back as a failed
181
+ * result for the caller to log. */
182
+ export async function postReply(text: string, cfg: Config): Promise<NotifyPostResult[]> {
183
+ const providers = notifyProviders(cfg);
184
+ const body = cfg.notify.prefix ? `${cfg.notify.prefix} ${text}` : text;
185
+ if (body.trim() === "") return providers.map(p => ({ provider: p.name, posted: false, chunks: 0, error: "empty reply; nothing posted" }));
186
+ const out: NotifyPostResult[] = [];
187
+ for (const p of providers) {
188
+ const { url, why } = webhookUrl(p);
189
+ if (url === "") {
190
+ out.push({ provider: p.name, posted: false, chunks: 0, error: why });
191
+ continue;
192
+ }
193
+ const limit = p.name === "discord" ? DISCORD_LIMIT : SLACK_LIMIT;
194
+ out.push(await postChunks(p, url, notifyChunks(body, limit)));
195
+ }
196
+ return out;
197
+ }
@@ -1,9 +1,10 @@
1
1
  // Queue model: ONE index — the main index lists plan files, one absolute path per line (templates/queue/TEMPLATE.md).
2
2
 
3
3
  import { createHash } from "node:crypto";
4
- import { accessSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
4
+ import { accessSync, appendFileSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
5
5
  import os from "node:os";
6
6
  import path from "node:path";
7
+ import type { Config } from "../config.ts";
7
8
 
8
9
  const HOME = os.homedir();
9
10
  // Base set by applyQueueEnv from paths.agent_dir. Specific QUEUE_* vars still win.
@@ -568,6 +569,9 @@ function protectedPaths(): string[] {
568
569
  `${agent}/CANCELLED.md`,
569
570
  `${stateDirPath()}/`,
570
571
  `${agent}/config.yml`,
572
+ // The user's neurastream config file, even when agent_dir points elsewhere: an agent that
573
+ // could rewrite it could point notify at its own webhook.
574
+ `${HOME}/.config/neurastream/config.yml`,
571
575
  `${agent}/notes/subagents.md`,
572
576
  `${agent}/.guard-unlock`,
573
577
  `${path.dirname(agent)}/git-no-verify-guard.mjs`,
@@ -603,6 +607,50 @@ export function unlocked(): boolean {
603
607
  }
604
608
  }
605
609
 
610
+ export interface ChatUnlockResult {
611
+ /** True when the text was a whole-message unlock/lock command that took effect. */
612
+ applied: boolean;
613
+ command?: "unlock" | "lock";
614
+ /** For an unlock: the minutes the existing mtime window stays open (for the owner notice). */
615
+ minutes?: number;
616
+ }
617
+
618
+ const CHAT_CMD = /^(unlock|lock)(?:\s+(\d+))?$/i;
619
+
620
+ /**
621
+ * Owner unlock by chat (guards.chat_unlock): the whole trimmed message, case-insensitive —
622
+ * "unlock" (open for guards.unlock_minutes), "unlock N" (open for exactly N minutes, N clamped
623
+ * to 1..unlock_minutes) or "lock" (close again). Only the adapter calls this, with text the
624
+ * owner really typed; a model, a tool result or a machine prompt must never reach it. The file
625
+ * is written or removed from the extension process, not through a tool call, so plan-guard does
626
+ * not see the write. Every applied unlock/lock is logged to the plan-guard log.
627
+ */
628
+ export function chatUnlock(text: string, cfg: Config, source: string): ChatUnlockResult {
629
+ if (!cfg.guards.chat_unlock) return { applied: false };
630
+ const m = CHAT_CMD.exec(text.trim());
631
+ if (!m) return { applied: false };
632
+ const minutes = cfg.guards.unlock_minutes;
633
+ if ((m[1] ?? "").toLowerCase() === "lock") {
634
+ rmSync(unlockPath(), { force: true });
635
+ try {
636
+ appendFileSync(cfg.paths.plan_guard_log, `${new Date().toISOString()} LOCK chat source=${source}\n`);
637
+ } catch {}
638
+ return { applied: true, command: "lock" };
639
+ }
640
+ const want = m[2] === undefined ? minutes : Number(m[2]);
641
+ if (want < 1) return { applied: false }; // "unlock 0" is no unlock
642
+ const n = Math.min(want, minutes);
643
+ const file = unlockPath();
644
+ writeFileSync(file, "");
645
+ // Backdate the mtime so the existing window (mtime + unlock_minutes) closes after exactly n minutes.
646
+ const past = (Date.now() - (minutes - n) * 60_000) / 1000; // utimesSync takes seconds
647
+ utimesSync(file, past, past);
648
+ try {
649
+ appendFileSync(cfg.paths.plan_guard_log, `${new Date().toISOString()} UNLOCK chat source=${source} minutes=${n}\n`);
650
+ } catch {}
651
+ return { applied: true, command: "unlock", minutes: n };
652
+ }
653
+
606
654
  export function protectedHit(paths: string[]): string | null {
607
655
  for (const p of paths) for (const g of PROTECTED) if (g.endsWith("/") ? p.startsWith(g) || `${p}/` === g : p === g) return p;
608
656
  return null;
@@ -25,4 +25,4 @@ You are Main, the orchestrator. Main plans, delegates, reviews and lands; implem
25
25
  |`neurastream incident list --open`|session start, before status reports, when a spawn or stop is blocked|
26
26
  |`machine-guard`, `heavy-run`|machine-guard at session start and before launches; every test run goes through heavy-run|
27
27
 
28
- Guard files are locked for every agent; the owner unlocks with `touch {{AGENT_DIR}}/.guard-unlock` (30 min).
28
+ Guard files are locked for every agent; the owner unlocks with `touch {{AGENT_DIR}}/.guard-unlock` (30 min), or — when `guards.chat_unlock` is on in the config — by typing `unlock 30` in chat (`lock` closes it again).
@@ -104,6 +104,7 @@ guards:
104
104
  main_edit_limit: 5
105
105
  main_window_min: 15
106
106
  unlock_minutes: 30
107
+ chat_unlock: false # the owner's whole chat message "unlock"/"unlock N"/"lock" moves the guard unlock file
107
108
  plan_read_max_hours: 24
108
109
  idle_stops: 3
109
110
  blocker_timeout_ms: 10000
@@ -156,6 +157,11 @@ quota:
156
157
  reset_tz: "Asia/Shanghai"
157
158
  label: "quota"
158
159
 
160
+ notify:
161
+ discord_webhook_file: "" # file holding the Discord webhook URL; "" = off (README: Notify the owner)
162
+ slack_webhook_file: "" # file holding the Slack webhook URL; "" = off
163
+ prefix: "" # optional label prepended to each posted reply, e.g. "Main:"
164
+
159
165
  priority:
160
166
  sleep_sec: 120
161
167