neurastream 0.2.63 → 0.2.64

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.63",
3
+ "version": "0.2.64",
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",
@@ -25,12 +25,12 @@ import { chatApprove } from "../../core/plan-approval.ts";
25
25
  import { burdenRule, repoRules, rulesChanged } from "../../core/repo-rules.ts";
26
26
  import { configFile, loadConfig, reloadingConfig, type Config } from "../../core/config.ts";
27
27
  import { checkWrite, deferSteer, type WriteCheckConfig } from "../../core/write-check.ts";
28
- import { strftime } from "../../core/clock.ts";
28
+ import { nowSec, strftime } from "../../core/clock.ts";
29
29
  import { runDetectors, type DetectorInput } from "../../core/incident-detectors.ts";
30
30
  import { appendOwnerAnswer, readOwnerAnswers, readOwnerMessages } from "../../core/incidents.ts";
31
31
  import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, newProgressEntries, planReadNote, recordMainResult, resetMainCalls, revertMainEdit, rekeySpawnFile, reviewSpawnEnd, STOP_PLAN_OFFER_REFUSAL } from "../../core/guards.ts";
32
32
  import { rateLimitWait } from "../../core/rate-limit.ts";
33
- import { notifyProviders, postReply } from "../../core/notify.ts";
33
+ import { notifyProviders, ownerAnswerHandback, ownerAnswerSteer, postReply } from "../../core/notify.ts";
34
34
  import { loadKnownSecrets, redactSecrets, redactSummary } from "../../core/secret-redact.ts";
35
35
  import { inboxPath } from "../../core/owner-ui.ts";
36
36
  import { realTailscale } from "../../core/tailscale.ts";
@@ -926,6 +926,12 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
926
926
 
927
927
  pi.on("tool_result", (event, ctx) => {
928
928
  cfg = freshConfig();
929
+ // P9: an owner message past notify.answer_within_min with no hand-back steers once per
930
+ // message; sendUserMessage reaches Main mid-turn through the steer queue.
931
+ if (isMain(ctx)) {
932
+ const steer = ownerAnswerSteer(cfg, nowSec());
933
+ if (steer) pi.sendUserMessage(steer);
934
+ }
929
935
  onSizeCheck("tool_result", event, ctx);
930
936
  const e = asRecord(event);
931
937
  const c = asCtx(ctx);
@@ -1350,9 +1356,11 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1350
1356
  // A real hand-back: the turn ended without a rate limit — the episode is over.
1351
1357
  disarmRateEpisode();
1352
1358
  recordTurnAnswer(reply);
1353
- // A deferred hand-back fires no session_stop: reset the per-turn cap here (I-20261030-24)
1354
- // and steer a promise like checkStop refuses it (I-20261030-32).
1359
+ // A deferred hand-back fires no session_stop: reset the per-turn cap here (I-20261030-24),
1360
+ // record the hand-back for the owner-answer wait (P9), and steer a promise like checkStop
1361
+ // refuses it (I-20261030-32).
1355
1362
  resetMainCalls();
1363
+ ownerAnswerHandback(nowSec());
1356
1364
  if (new RegExp(cfg.guards.plan_offer, "i").test(reply.text)) {
1357
1365
  pi.sendUserMessage(STOP_PLAN_OFFER_REFUSAL);
1358
1366
  }
@@ -1396,6 +1404,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1396
1404
  if (!isMain(ctx)) return;
1397
1405
  if (asRecord(e).willContinue === true) return;
1398
1406
  resetMainCalls();
1407
+ ownerAnswerHandback(nowSec());
1399
1408
  });
1400
1409
  // P4k backstop (plan 20261028_1600): a named review spawn that ends with no verdict recorded at its edit is judged here, from its own plan file; the note tells Main at its next prompt.
1401
1410
  pi.on("agent_end", (_e, ctx) => {
@@ -243,7 +243,7 @@ export interface Config {
243
243
  quota: { reset_tz: string; reset_pattern: string; label: string };
244
244
  /** Chat notify (src/core/notify.ts): Main's final reply goes to these webhooks at session_stop.
245
245
  * The values are paths to secret files holding the webhook URLs — never the URLs themselves. */
246
- notify: { discord_webhook_file: string; slack_webhook_file: string; prefix: string };
246
+ notify: { discord_webhook_file: string; slack_webhook_file: string; prefix: string; /** Minutes a phone-page owner message may wait before the answer steer (P9; 0 = off). */ answer_within_min: number };
247
247
  /** Content redaction (src/core/secret-redact.ts, plan 20261025_2204): every tool result, every
248
248
  * notify post and `neurastream redact` go through it. Detection is by content, not file name. */
249
249
  secrets: {
@@ -525,6 +525,8 @@ function check(cfg: Config): void {
525
525
  }
526
526
  const wc = cfg.write_check;
527
527
  if (wc.applies_to !== "sub" && wc.applies_to !== "all") throw new ConfigError('write_check.applies_to must be "sub" or "all"');
528
+ if (!(Number.isFinite(cfg.notify.answer_within_min) && cfg.notify.answer_within_min >= 0))
529
+ throw new ConfigError("notify.answer_within_min must be a number >= 0 (minutes an owner message may wait; 0 = off)");
528
530
  if (!(wc.timeout_ms > 0)) throw new ConfigError("write_check.timeout_ms must be > 0");
529
531
  if (!Array.isArray(wc.linters)) throw new ConfigError("write_check.linters must be a list");
530
532
  if (!Array.isArray(wc.defer_rules) || wc.defer_rules.some((r) => typeof r !== "string" || r === ""))
@@ -1075,12 +1075,33 @@ function runsCloser(input: Record<string, unknown>): boolean {
1075
1075
 
1076
1076
  const bin = (w: string | undefined) => (w ?? "").replace(/^["']+|["']+$/g, "").split("/").pop() ?? "";
1077
1077
 
1078
+ // P5g (plan 20261027_0915): the shell text a call would really run — bash's command line, eval's
1079
+ // !cmd shell-escape lines and the Bun.$/spawn arguments inside its code. Everything else in an
1080
+ // input is prose or string data (a task brief, plan text, an eval cell that only names the page's
1081
+ // words), and prose runs nothing.
1082
+ function shellText(input: Record<string, unknown>): string {
1083
+ if (typeof input.command === "string") return input.command;
1084
+ const code = input.code;
1085
+ if (typeof code !== "string") return "";
1086
+ const out: string[] = [];
1087
+ for (const m of code.matchAll(/^[ \t]*!(.+)$/gm)) out.push(m[1] ?? "");
1088
+ for (const m of code.matchAll(/(?<!\w)(?:Bun\.)?\$[ \t]*`((?:[^`\\]|\\.)*)`/g)) out.push(m[1] ?? "");
1089
+ for (const m of code.matchAll(/\b(?:Bun\.)?spawn(?:Sync)?[ \t]*\(([^)]*)/g))
1090
+ out.push(
1091
+ [...(m[1] ?? "").matchAll(/[`"']([^`"']*)[`"']/g)]
1092
+ .map(s => s[1] ?? "")
1093
+ .join(" "),
1094
+ );
1095
+ return out.join("\n");
1096
+ }
1097
+
1078
1098
  // True when a command segment starts the owner page (plan 20261024_2230 P3c): `neurastream ui`
1079
1099
  // serves it and `systemctl --user start/restart/enable` of neurastream-ui relaunches it — the
1080
- // owner's systemd moves, never an agent's, unlocked or not. Segment splitting and launcher
1081
- // skipping match runsCloser, so `sh -c "neurastream ui"` and `sudo systemctl --user ...` are seen.
1100
+ // owner's systemd moves, never an agent's, unlocked or not. P5g: the text is shellText's — only
1101
+ // real shell commands, never prose. Segment splitting and launcher skipping match runsCloser, so
1102
+ // `sh -c "neurastream ui"` and `sudo systemctl --user ...` are seen.
1082
1103
  function startsOwnerUi(input: Record<string, unknown>): boolean {
1083
- const text = Object.values(input).filter((v): v is string => typeof v === "string").join("\n");
1104
+ const text = shellText(input);
1084
1105
  return text.split(/&&|\|\||;|\||\n|\$\(|`/).some(seg => {
1085
1106
  const words = seg.trim().split(/\s+/).filter(Boolean).map(w => w.replace(/^["'(]+|["')]+$/g, ""));
1086
1107
  let i = 0;
@@ -1139,6 +1160,17 @@ function addedText(input: Record<string, unknown>): string {
1139
1160
  .join("\n");
1140
1161
  }
1141
1162
 
1163
+ // P5g: tools whose string fields are content — a task brief, the text a write or edit adds — are
1164
+ // prose, never reads; the notify-secret check scans only their path argument.
1165
+ const PROSE_TOOLS: Record<string, true> = { task: true, write: true, edit: true, ast_edit: true };
1166
+
1167
+ // Only a tool call's path arguments — the paths it names as targets, not its prose fields.
1168
+ function pathArgs(input: Record<string, unknown>): Record<string, unknown> {
1169
+ const out: Record<string, unknown> = {};
1170
+ for (const key of ["path", "file"]) if (typeof input[key] === "string") out[key] = input[key];
1171
+ return out;
1172
+ }
1173
+
1142
1174
  // Subagent half of a tool call (the original plan-guard checkCall without the main return).
1143
1175
  // `cap` is the sub's hard call cap: its recorded per-spawn budget, else the global sub_max_calls.
1144
1176
  function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[], writes: string[], cfg: Config, cap: number): string | null {
@@ -1438,8 +1470,14 @@ export function checkTool(e: ToolEvent, cfg: Config): Decision {
1438
1470
  }
1439
1471
  // Notify secrets: no agent, main or sub, reads a webhook URL — with or without the unlock.
1440
1472
  // A call that changes a secret is not a read: its target goes through the protected-write
1441
- // rule above, so the owner's unlock covers it like any guard file.
1442
- const secretHit = notifySecretReadHit(paths.filter(p => !writes.includes(p)), cfg);
1473
+ // rule above, so the owner's unlock covers it like any guard file. P5g: the scan reads real
1474
+ // read targets only — naming a secret-shaped glob in a task brief or in plan text is prose,
1475
+ // not a read — so prose tools (task, write/edit) scan just their path argument, while every
1476
+ // other tool keeps the whole-input scan (glob/grep patterns arrive through it).
1477
+ const secretPaths: string[] = [];
1478
+ for (const p of [...(e.paths ?? []), ...q.touchedPaths(e.tool, PROSE_TOOLS[e.tool] === true ? pathArgs(input) : input, e.cwd)])
1479
+ if (!secretPaths.includes(p)) secretPaths.push(p);
1480
+ const secretHit = notifySecretReadHit(secretPaths.filter(p => !writes.includes(p)), cfg);
1443
1481
  if (secretHit) {
1444
1482
  log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} notify secret: ${secretHit}`);
1445
1483
  return deny(`plan-guard: ${secretHit} is a notify secret path. Only the owner touches the webhook files, in a terminal.`);
@@ -4,8 +4,11 @@
4
4
  // from them (guard rules in guards.ts), and does the posting. Plain TypeScript, no harness here.
5
5
 
6
6
  import { dirname } from "node:path";
7
- import { readFileSync, statSync } from "node:fs";
7
+ import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
8
8
  import { configFile, type Config } from "./config.ts";
9
+ import { strftime } from "./clock.ts";
10
+ import { recentOwnerMessages, type MessageRow } from "./owner-ui.ts";
11
+ import { stateDirPath } from "./queue/lib.ts";
9
12
  import { loadKnownSecrets, redactSecrets } from "./secret-redact.ts";
10
13
 
11
14
  export type NotifyProviderName = "discord" | "slack";
@@ -42,10 +45,14 @@ function hitsSecret(p: string, file: string): boolean {
42
45
  const m = GLOB_META.exec(p);
43
46
  if (!m) return false;
44
47
  const base = p.slice(0, m.index).replace(/\/+$/, "");
45
- if (!base) return false;
46
- // The glob's literal prefix is the secrets dir, sits inside it, or is an ancestor of it:
47
- // every match it can name is a secret (or reveals the directory listing).
48
- return base === dir || base.startsWith(`${dir}/`) || dir.startsWith(`${base}/`);
48
+ // The glob's literal prefix is the secrets dir or sits inside it: every match it can name is a
49
+ // secret (or reveals the directory listing).
50
+ if (base && (base === dir || base.startsWith(`${dir}/`))) return true;
51
+ // P5g: a wider glob refuses only when it actually matches a secret file or the secrets dir
52
+ // (Bun.Glob, filesystem-free, asked once per secret file and once per its directory), never
53
+ // by its prefix alone — a home-wide glob hunting an unrelated folder passes, and the cost
54
+ // stays bounded by the number of secret files, not by what the glob would expand to.
55
+ return new Bun.Glob(p).match(file) || new Bun.Glob(p).match(dir);
49
56
  }
50
57
 
51
58
  /** The first touched read path that hits a configured secret file, its directory, or a glob over
@@ -225,3 +232,65 @@ export function postReply(text: string, cfg: Config): Promise<NotifyPostResult[]
225
232
  return out;
226
233
  });
227
234
  }
235
+
236
+ // ---- Owner answer steer (plan 20261027_1430 P9): a phone-page owner message must be answered
237
+ // by the next hand-back within notify.answer_within_min. The rule is host-neutral: core decides
238
+ // who is waiting and keeps the once-per-message markers; the harness adapter injects the steer
239
+ // at its tool_result hook and records the hand-back at its turn end. The markers live in a file
240
+ // under the queue state, not in session memory: one-shot CLI calls and a reloaded plugin must
241
+ // agree, like the guard window file.
242
+
243
+ function ownerAnswerStatePath(): string {
244
+ return `${stateDirPath()}/owner-answer.json`;
245
+ }
246
+
247
+ interface OwnerAnswerState {
248
+ /** Unix seconds of the last hand-back; a message older than this was answered by it. */
249
+ lastHandBack: number;
250
+ /** Message ids this turn already steered, so a message steers once per turn. */
251
+ steered: string[];
252
+ }
253
+
254
+ function readOwnerAnswerState(): OwnerAnswerState {
255
+ try {
256
+ const s = JSON.parse(readFileSync(ownerAnswerStatePath(), "utf8")) as Partial<OwnerAnswerState>;
257
+ return {
258
+ lastHandBack: Number(s.lastHandBack) || 0,
259
+ steered: Array.isArray(s.steered) ? s.steered.filter((x): x is string => typeof x === "string") : [],
260
+ };
261
+ } catch {
262
+ return { lastHandBack: 0, steered: [] };
263
+ }
264
+ }
265
+
266
+ function writeOwnerAnswerState(state: OwnerAnswerState): void {
267
+ mkdirSync(stateDirPath(), { recursive: true });
268
+ writeFileSync(ownerAnswerStatePath(), `${JSON.stringify(state)}\n`);
269
+ }
270
+
271
+ /** Phone-page owner messages waiting past notify.answer_within_min with no hand-back after them; none when the limit is 0. */
272
+ export function waitingOwnerMessages(cfg: Config, now: number): MessageRow[] {
273
+ const limit = cfg.notify.answer_within_min * 60;
274
+ if (!(limit > 0)) return [];
275
+ const { lastHandBack } = readOwnerAnswerState();
276
+ return recentOwnerMessages(now).filter((m) => now - m.ts > limit && m.ts > lastHandBack);
277
+ }
278
+
279
+ /** The steer for every waiting message this turn has not steered yet — one line per message, so
280
+ * each owner ask lands once — or null when nobody is waiting. Marks the messages steered. */
281
+ export function ownerAnswerSteer(cfg: Config, now: number): string | null {
282
+ const limit = cfg.notify.answer_within_min * 60;
283
+ if (!(limit > 0)) return null;
284
+ const state = readOwnerAnswerState();
285
+ const due = recentOwnerMessages(now).filter((m) => now - m.ts > limit && m.ts > state.lastHandBack && !state.steered.includes(m.id));
286
+ if (due.length === 0) return null;
287
+ state.steered.push(...due.map((m) => m.id));
288
+ writeOwnerAnswerState(state);
289
+ return due.map((m) => `Owner asked at ${strftime(m.ts, "%H:%M")}; end your turn with the answer now`).join("\n");
290
+ }
291
+
292
+ /** A hand-back ends the wait: the reply just posted answers whatever waited, so the wait clears
293
+ * and the next owner message starts fresh. */
294
+ export function ownerAnswerHandback(now: number): void {
295
+ writeOwnerAnswerState({ lastHandBack: now, steered: [] });
296
+ }
package/src/core/watch.ts CHANGED
@@ -23,7 +23,7 @@ import { readBeats, type Heartbeat } from "./heartbeat.ts";
23
23
  import { runDetectorsGated, type GatedInputs } from "./incident-detectors.ts";
24
24
  import { log, readStaffingEntries } from "./guards.ts";
25
25
  import { appendMetric, inWindow, readBlocks, readMetricEvents, reasonKey, type Window } from "./metrics.ts";
26
- import { notifyProviders } from "./notify.ts";
26
+ import { notifyProviders, waitingOwnerMessages } from "./notify.ts";
27
27
  import { addIncident, dismissIncident, openIncidents, readIncidents, type IncidentView } from "./incidents.ts";
28
28
  import { m7, rowsOf, silentFailures, snap } from "./report.ts";
29
29
  import { loadKnownSecrets, redactSecrets } from "./secret-redact.ts";
@@ -105,6 +105,8 @@ export interface WatchReport {
105
105
  closed: IncidentView[];
106
106
  /** Incidents the gated detectors folded themselves (their own sources and kinds). */
107
107
  detectors: IncidentView[];
108
+ /** Owner messages that first crossed notify.answer_within_min this pass (M8, P9). */
109
+ ownerWaits: number;
108
110
  }
109
111
 
110
112
  /** One problem the watcher found: exactly one addIncident input plus the fields its ⚠ post
@@ -269,7 +271,17 @@ export function watchOnce(cfg: Config, deps: WatchDeps): WatchReport {
269
271
  notify: text => deps.notify(cfg.secrets.redact ? redactSecrets(text, loadKnownSecrets(cfg), cfg.secrets.extra_patterns).text : text),
270
272
  });
271
273
  }
272
- return { opened, deduped, closed, detectors };
274
+ // (f) P9: an owner message that crossed notify.answer_within_min with no hand-back counts M8,
275
+ // one metric per message — the ledger is the once-only marker, not per-pass state.
276
+ let ownerWaits = 0;
277
+ const m8Done = new Set(readMetricEvents(cfg).filter(e => e.type === "m8").map(e => String(e.id)));
278
+ for (const m of waitingOwnerMessages(cfg, now)) {
279
+ if (m8Done.has(m.id)) continue;
280
+ appendMetric(cfg, { type: "m8", id: m.id, waited_sec: now - m.ts, ts: now });
281
+ ownerWaits++;
282
+ }
283
+ if (ownerWaits > 0) log(cfg.paths.guard_log, `watch: M8 ${ownerWaits} owner wait(s) past notify.answer_within_min`);
284
+ return { opened, deduped, closed, detectors, ownerWaits };
273
285
  }
274
286
 
275
287
  // ---- P11: the release verdict — is the new version better or worse? ----
@@ -240,6 +240,7 @@ notify:
240
240
  discord_webhook_file: "" # file holding the Discord webhook URL; "" = off (README: Notify the owner)
241
241
  slack_webhook_file: "" # file holding the Slack webhook URL; "" = off
242
242
  prefix: "" # optional label prepended to each posted reply, e.g. "Main:"
243
+ answer_within_min: 3 # minutes an owner message may wait before the tool-result steer steers Main to answer it now (0 = off)
243
244
 
244
245
  secrets: # content redaction (src/core/secret-redact.ts); a hit prints as [REDACTED:<type>]
245
246
  redact: true # every tool result, every notify post and `neurastream redact` go through the redactor