neurastream 0.2.62 → 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/README.md CHANGED
@@ -121,6 +121,10 @@ Owner rule: never write a plan when another agent is doing the research or readi
121
121
 
122
122
  A plan parked for the owner has one line: `WAITING on owner: <what to do> — blocked: <what stays stuck until then> — why you: <why Main cannot do it>` (`blocked` and `why you` may be omitted). That line is the only hold, and only Main writes it (plan-guard refuses subagents). The queue summary shows it as a flag on the plan, cut at 80 characters. Compaction and the rollover handoff read the same lines through `ownerHolds`: the compaction context lists each `<plan file>: WAITING on owner: <text>` line (or `none`) and says any other "needs the owner" or "paused" claim is unverified; the handoff's generated state carries the same lines. Main does not keep holds in a handoff note. A plan header may also carry `Summary: <one or two plain sentences>` under Branch (`templates/queue/TEMPLATE.md`); old plans without it still pass `queue-check`, and the phone page uses that line as the queue card's summary.
123
123
 
124
+ ## Live re-check
125
+
126
+ A "waiting on you" card or a "done" claim only counts while its own command still proves it. A plan's `WAITING on owner:` line may end with `— still true if: \`<cmd>\`` (exit 0 = the hold is still real): neurastream runs that command in the plan's worktree before a question card is shown, at main-start and after `neurastream metrics ci` (timeout `queue.waiting_check_timeout_sec`, default 60 s; results cached for `queue.waiting_check_ttl_sec`, default 600 s). When it exits non-zero the card is hidden, the queue summary shows `[STALE?] <ask>` instead of `WAITING on owner:`, `queue-check` prints `STALE HOLD: <plan>: <ask> — check \`<cmd>\` exited <code>`, and one `stale-hold` incident opens per check run — the hold line itself is never edited; only Main removes it. A Progress entry (dated the day the done-claim check shipped or later) that says done/complete/"nothing left"/"finished" about a phase must quote that phase's `verify:` command with its result, or `queue-check` fails with `unbacked done claim: <plan> <entry start>`; hold lines dated that day or later without a `still true if` check are a printed warning. The rollover handoff lists every `(from: \`cmd\`)` of Main's note under `## Numbers to re-run` right after the note — re-run these before repeating any number. Owner messages that sat unanswered survive gaps: the rate-limit resume and the rollover handoff start with `UNANSWERED OWNER MESSAGES — answer these first, then end the turn so the reply reaches Discord:` and quote each message's arrival time and first 300 characters. A real Main turn end records its reply as the answer in the same `<queue_state>/owner-messages.jsonl` store (the page's answer shape); a turn that ends on a provider error answers nothing, so the block is quoted again on the next resume or handoff.
127
+
124
128
  ## Queue priority
125
129
 
126
130
  `INDEX.md` order is priority: the top line is rank 1. The queue summary lists plans in that order (`N. <file> [flags] <goal>`). Before a spawn, the guard checks every plan above each plan the brief names. A higher plan that is idle — open, no `WAITING on owner:`, not awaiting merge, still has an unticked phase, and not itself waiting on another open indexed plan via a `Waits on: <plan>` line — and not staffed by a running job blocks the spawn unless the brief quotes the owner: `Priority skip: <plan> — owner: "<his words>"`, at least four words that appear in an owner message of the last 24 h (`<queue_state>/owner-messages.jsonl`, recorded from Main's prompts); any other skip line is refused. `Waits on:` lines are Main-only, like `WAITING on owner:`. Staffing is `<queue_state>/staffing.json` (each plan's newest spawn's task names) matched against omp's running job labels. The owner reorders the queue by dragging cards on the phone page — a drag held near the screen edge autoscrolls the page, so the end of a queue taller than the screen is reachable. The order must respect the dependencies: an open plan may not sit above the open plan its `Waits on:` line names — `queue-check` lists one problem per misranked plan and exits 1, the summary shows the target as a `waits on #N` flag on the plan, and a drag that would create such an order is refused with that reason (`blocked: #N <plan> waits on #M …`) before the index or the reorder inbox change. A `Waits on:` target that is complete or gone from the index imposes no order.
@@ -214,6 +218,38 @@ Guard rules around it:
214
218
 
215
219
  "Needs you" pings use the same channels so the owner learns on the phone that a decision is his: when a Main turn ends with an open plan whose `WAITING on owner:` line was not pinged before, neurastream posts `🔔 Needs you — <plan>: <question>` (with the `neurastream ui` phone-page link when `ui.enabled: true`), and when the guard refuses a Main tool call because it touches a protected guard file, it posts `🔓 Main needs an unlock to continue (<file>)` — the unlock ping at most once per 30 minutes, each waiting question once until its line changes or disappears, remembered in `<queue_state>/notify-waiting.json`. Every decision logs one `notify: needs-you posted|skipped (<why>)` guard-log line.
216
220
 
221
+ ## Continuous feedback (watch)
222
+
223
+ Every scheduled job reports in, and a small timer checks the reports every few minutes — even when no Main session is open. This is the loop that catches a backup failing silently for six days.
224
+
225
+ Every job beats: wip-snapshot, wip-backup, `metrics report`, the pages server and the owner page server write `<queue_state>/heartbeats/<name>.json` — `{name, at, ok, detail}` — after every run; a crash beats `ok: false` with the first error line, then exits with its usual code. Your own cron jobs join the same loop with the hidden command:
226
+
227
+ ```sh
228
+ neurastream heartbeat <name> # the run was fine
229
+ neurastream heartbeat <name> --fail "why" # report a failure
230
+ ```
231
+
232
+ One watcher pass (`neurastream watch`) checks, in order: heartbeats with `ok: false` and heartbeats older than `watch.expect[name]` hours (only jobs listed there must beat at all); failed user units matching the `watch.units` globs, with the unit's last error line; CI per active-plan repo — a red default branch (`ci-red-main`), an open MR red for more than `watch.ci_red_hours` (`ci-red-mr`, held back while an agent runs on its plan), an M3 record for every MR merged since the last pass (the ledger is the cursor, so `metrics ci` can no longer be forgotten), and a commit that went red then green as a `ci-flaky` metric; then the gated incident detectors; and last, one release verdict per closed tag (better or worse over the before window — a verdict stays open for Main to plan or dismiss, it is never auto-closed as recovered). Each new problem opens one incident; when the problem recovers, the incident closes again.
233
+
234
+ Notify: every NEW incident posts one `⚠ <job>: <state> at <time> — <first error line> (incident <id>)` through the configured channels — at most `watch.max_posts_per_run` (default 3) per run, then one "+N more, see `neurastream incident list --open`" line. Without a provider the incident still opens and nothing posts; already-open problems post nothing; every post is scrubbed by the secret redactor, so the text carries a job name, a time and a first error line — never file contents or env values.
235
+
236
+ `neurastream watch on|off` installs/removes the timer: a systemd user timer `neurastream-watch.{service,timer}` or a macOS LaunchAgent (`neurastream-watch.plist`), running one pass every `watch.interval_min` (default 15). The service manager is probed first; a failed probe writes nothing. `neurastream doctor` prints `watch: on|off, last run N min ago`, and main-start raises a `watch:not-running` incident once the last pass is older than 3 intervals — the watcher watches itself.
237
+
238
+ The noisy-detector rule: in the weekly report, a detector kind with at least `watch.noisy_min` (default 5) incidents in the window and a dismiss rate of at least `watch.noisy_ratio` (default 0.5) opens one `noisy detector: <kind> (<d>/<n> dismissed)` incident with the three latest dismiss reasons — an alarm that says its own alarm is crying wolf.
239
+
240
+ Config (`docs/config.md`, `templates/config.yml`):
241
+
242
+ ```yaml
243
+ watch:
244
+ expect: # hours after which a job's last heartbeat is stale; only listed jobs must beat at all
245
+ wip-snapshot: 2 # hourly snapshot
246
+ wip-backup: 26 # nightly backup; one missed day is not yet stale
247
+ metrics-report: 192 # 8 days; the weekly report job
248
+ units: ["neurastream-*", "wip-*"] # failed user units the watcher reports
249
+ max_posts_per_run: 3 # new-incident posts per run, then one "+N more" line
250
+ interval_min: 15 # minutes between watcher runs
251
+ ```
252
+
217
253
  ## Secrets never reach the chat
218
254
 
219
255
  A value the machine holds is hidden before the model, the chat and the session log see it (`src/core/secret-redact.ts`, plan 20261025_2204, incident I-20261025-197). Detection is by **content**, not by file name — the old name list never knew about `~/.npmrc`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.62",
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",
@@ -18,7 +18,7 @@
18
18
  import { execFileSync, spawn } from "node:child_process";
19
19
  import { appendFileSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
20
20
  import { basename, dirname, extname, join, resolve } from "node:path";
21
- import type { Decision } from "../../core/adapter.ts";
21
+ import type { Decision, TraceEvent } from "../../core/adapter.ts";
22
22
  import { AGENTS_TEMPLATE, renderBlock } from "../../core/agents-md.ts";
23
23
  import { chatGo, chatTier, type Tier } from "../../core/autonomy.ts";
24
24
  import { chatApprove } from "../../core/plan-approval.ts";
@@ -26,18 +26,19 @@ 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
28
  import { nowSec, strftime } from "../../core/clock.ts";
29
- import { runDetectors, runDetectorsGated, type DetectorInput } from "../../core/incident-detectors.ts";
29
+ import { runDetectors, type DetectorInput } from "../../core/incident-detectors.ts";
30
+ import { appendOwnerAnswer, readOwnerAnswers, readOwnerMessages } from "../../core/incidents.ts";
30
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";
31
32
  import { rateLimitWait } from "../../core/rate-limit.ts";
32
- import { notifyProviders, postReply } from "../../core/notify.ts";
33
+ import { notifyProviders, ownerAnswerHandback, ownerAnswerSteer, postReply } from "../../core/notify.ts";
33
34
  import { loadKnownSecrets, redactSecrets, redactSummary } from "../../core/secret-redact.ts";
34
35
  import { inboxPath } from "../../core/owner-ui.ts";
35
36
  import { realTailscale } from "../../core/tailscale.ts";
36
37
  import { actionsRules, ownedRepoOf, suspiciousActions, unreportedFindings } from "../../core/trace-actions.ts";
37
38
  import { applyQueueEnv } from "../../core/queue/env.ts";
38
- import { mainStartText, runDailyCheck } from "../../core/main-start.ts";
39
- import { readBlocks } from "../../core/metrics.ts";
40
- import { buildHandoff, holdsBlock, notePath, noteRequest, OWNER_AWAY, ownerText, relaunchPath, rolloverState, spawnRefusal, type RolloverState } from "../../core/rollover.ts";
39
+ import { mainDetectors, mainStartText } from "../../core/main-start.ts";
40
+
41
+ import { buildHandoff, holdsBlock, notePath, noteRequest, OWNER_AWAY, ownerText, relaunchPath, rolloverState, spawnRefusal, unansweredOwnerMessages, withUnanswered, type RolloverState } from "../../core/rollover.ts";
41
42
  import { defaultCompletedResults, defaultRunSource, runIdOf } from "./sessions.ts";
42
43
  import { adapterLog, MAIN_ENV } from "./launch.ts";
43
44
  import { parseTraceFile } from "./traces.ts";
@@ -48,6 +49,16 @@ import { annotateResetTimes } from "../../core/reset-time.ts";
48
49
  // Registers the plugin-command matcher into core's writeTargets (side effect).
49
50
  import "./package-ops.ts";
50
51
 
52
+ /** TraceEvents of the newest Main session file (D8's input); [] when there is none or it cannot be read. */
53
+ function defaultMainEvents(cfg: Config): TraceEvent[] {
54
+ try {
55
+ const s = defaultRunSource(cfg).mainSession();
56
+ return s ? parseTraceFile(s.file, runIdOf(s.file)) : [];
57
+ } catch {
58
+ return [];
59
+ }
60
+ }
61
+
51
62
  /** Subset of the harness extension host the adapter needs. */
52
63
  export interface ExtensionHost {
53
64
  on(event: string, cb: (...args: unknown[]) => unknown): void;
@@ -143,27 +154,6 @@ const PUSH_MERGE = /\bgit\b[^\n;|&]*\bpush\b|\b(glab\s+mr|gh\s+pr)\s+merge\b/;
143
154
 
144
155
  export { adapterLog };
145
156
 
146
- /**
147
- * Real-time incident detectors (plan 20261022_2330 P3) at Main's prompt and after each Main bash
148
- * result, plus the once-per-day metrics check (P4, retried until it marks the day). The cheap
149
- * detectors (D2 bash, D4 prompt) run on every call; D1/D3 and their inputs — Main's session
150
- * file, the ledger runs, both guard logs — are gathered behind the scan interval
151
- * (incidents.scan_interval_sec, see runDetectorsGated). Best effort: a failed check is logged,
152
- * never thrown.
153
- */
154
- function mainDetectors(cfg: Config, extra: { prompt?: string; bash?: { command: string; output: string } }): void {
155
- try {
156
- runDetectorsGated(cfg, extra, () => ({
157
- results: defaultCompletedResults(cfg),
158
- runs: defaultRunSource(cfg).listRuns(nowSec() - 2 * 86400),
159
- blocks: readBlocks(cfg),
160
- }));
161
- runDailyCheck(cfg, defaultRunSource(cfg), nowSec());
162
- } catch (err) {
163
- adapterLog(cfg, `incident detectors failed: ${err instanceof Error ? err.message : String(err)}`);
164
- }
165
- }
166
-
167
157
  /**
168
158
  * D6 + D7 over a subagent's own trace, right after an allowed Progress edit (plan
169
159
  * 20261024_0301 P6): the sub's session file (its harness session manager hands it out) is
@@ -624,12 +614,24 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
624
614
  clearRateTimer();
625
615
  rateAttempt = 0;
626
616
  };
617
+ // P5b: a real turn end answers every owner message it followed — the answer (the turn's own
618
+ // reply, the page's lastAnswerFor shape) rides the same owner-message store. Rate-limited,
619
+ // blocked and mid-run ends are not turn ends: nothing is recorded.
620
+ const recordTurnAnswer = (reply: EventReply | null): void => {
621
+ if (!reply?.text) return;
622
+ try {
623
+ appendOwnerAnswer(reply.text);
624
+ } catch (err) {
625
+ adapterLog(cfg, `OWNER-ANSWER record failed: ${err instanceof Error ? err.message : String(err)}`);
626
+ }
627
+ };
627
628
  // The one resume: replacing any armed timer, exactly one new user message when the wait is over.
628
629
  const armRateResume = (untilMs: number): void => {
629
630
  clearRateTimer();
630
631
  rateTimer = setTimeout(() => {
631
632
  rateTimer = null;
632
- pi.sendUserMessage(`main-guard: the provider rate limit is over (waited until ${rateClock(untilMs)}). Continue the queue where you stopped.`);
633
+ // P5b: whichever resume text exists, it quotes owner messages no turn has answered.
634
+ pi.sendUserMessage(withUnanswered(`main-guard: the provider rate limit is over (waited until ${rateClock(untilMs)}). Continue the queue where you stopped.`, readOwnerMessages(), readOwnerAnswers()));
633
635
  adapterLog(cfg, `RATE-LIMIT resume: new turn sent (waited until ${rateClock(untilMs)})`);
634
636
  }, untilMs - Date.now());
635
637
  };
@@ -822,7 +824,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
822
824
  // A turn the harness starts from the guard's own stop continuation is not an owner
823
825
  // message: D4 (owner-correction) only sees real prompts; D1/D3 run either way.
824
826
  // Machine prompts (guard continuation, rollover note request, handoff note) are not owner messages.
825
- mainDetectors(cfg, { prompt: ownerText(prompt) });
827
+ mainDetectors(cfg, { runSource: defaultRunSource, completedResults: defaultCompletedResults, mainEvents: defaultMainEvents }, { prompt: ownerText(prompt) });
826
828
  // The rules of a repo this session has just worked in (P3): one hand-over per repo per file
827
829
  // version — rulesChanged holds the hash, and the set holds only what was touched.
828
830
  const rules: string[] = [];
@@ -924,6 +926,12 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
924
926
 
925
927
  pi.on("tool_result", (event, ctx) => {
926
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
+ }
927
935
  onSizeCheck("tool_result", event, ctx);
928
936
  const e = asRecord(event);
929
937
  const c = asCtx(ctx);
@@ -1028,7 +1036,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1028
1036
  }
1029
1037
  // Real-time detectors after each Main bash result, crashes included (D2 wants the stack).
1030
1038
  if ((!c.hasAgent || c.kind === "main") && asString(e.toolName) === "bash") {
1031
- mainDetectors(cfg, {
1039
+ mainDetectors(cfg, { runSource: defaultRunSource, completedResults: defaultCompletedResults, mainEvents: defaultMainEvents }, {
1032
1040
  bash: { command: asString(asRecord(e.input).command), output: content.map(p => asString(asRecord(p).text)).join("\n") },
1033
1041
  });
1034
1042
  }
@@ -1082,6 +1090,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1082
1090
  }
1083
1091
  if (snap.state === "ready" || snap.state === "wait-jobs") {
1084
1092
  adapterLog(cfg, `ALLOW stop: rollover ${snap.state}`);
1093
+ recordTurnAnswer(reply);
1085
1094
  // Under the launcher a ready rollover starts now (not a hand-back to the owner).
1086
1095
  const handsToOwner = !(snap.state === "ready" && requestRelaunch(rc, notePath(rc.sessionId)));
1087
1096
  if (handsToOwner) notifyHandback(reply, "allowed session_stop");
@@ -1093,6 +1102,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1093
1102
  callsSinceStop = d.state?.callsSinceStop ?? 0;
1094
1103
  idleStops = d.state?.idleStops ?? idleStops;
1095
1104
  if (d.allow) {
1105
+ recordTurnAnswer(reply);
1096
1106
  notifyHandback(reply, "allowed session_stop");
1097
1107
  return undefined;
1098
1108
  }
@@ -1206,6 +1216,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1206
1216
  note,
1207
1217
  previousSessionFile: previous,
1208
1218
  ownerMessage: owner.filter(s => s !== "").join("\n"),
1219
+ unanswered: unansweredOwnerMessages(readOwnerMessages(), readOwnerAnswers()),
1209
1220
  });
1210
1221
  pi.sendUserMessage(handoff);
1211
1222
  } finally {
@@ -1344,9 +1355,12 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1344
1355
  }
1345
1356
  // A real hand-back: the turn ended without a rate limit — the episode is over.
1346
1357
  disarmRateEpisode();
1347
- // A deferred hand-back fires no session_stop: reset the per-turn cap here (I-20261030-24)
1348
- // and steer a promise like checkStop refuses it (I-20261030-32).
1358
+ recordTurnAnswer(reply);
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).
1349
1362
  resetMainCalls();
1363
+ ownerAnswerHandback(nowSec());
1350
1364
  if (new RegExp(cfg.guards.plan_offer, "i").test(reply.text)) {
1351
1365
  pi.sendUserMessage(STOP_PLAN_OFFER_REFUSAL);
1352
1366
  }
@@ -1390,6 +1404,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1390
1404
  if (!isMain(ctx)) return;
1391
1405
  if (asRecord(e).willContinue === true) return;
1392
1406
  resetMainCalls();
1407
+ ownerAnswerHandback(nowSec());
1393
1408
  });
1394
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.
1395
1410
  pi.on("agent_end", (_e, ctx) => {
@@ -8,10 +8,12 @@ import { appendFileSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSyn
8
8
  import { basename, dirname, join } from "node:path";
9
9
  import type { LaunchOptions } from "../../core/adapter.ts";
10
10
  import type { Config } from "../../core/config.ts";
11
+ import { readOwnerAnswers, readOwnerMessages } from "../../core/incidents.ts";
11
12
  import { mainStartText } from "../../core/main-start.ts";
13
+ import { appendMetric } from "../../core/metrics.ts";
12
14
  import { applyQueueEnv } from "../../core/queue/env.ts";
13
15
  import * as q from "../../core/queue/lib.ts";
14
- import { buildHandoff, holdsBlock, MAX_NOTE_AGE_MS, OWNER_AWAY, relaunchPath } from "../../core/rollover.ts";
16
+ import { buildHandoff, holdsBlock, MAX_NOTE_AGE_MS, OWNER_AWAY, relaunchPath, unansweredOwnerMessages } from "../../core/rollover.ts";
15
17
  import { PROXY_BIN, proxyOnPath } from "../../core/secret-redact.ts";
16
18
  import { PACKAGE_ROOT, packageJsonPath, packageVersion } from "./package-root.ts";
17
19
  import { defaultCompletedResults, defaultRunSource } from "./sessions.ts";
@@ -186,6 +188,8 @@ export async function runMainLauncher(args: string[], cfg: Config, opts: LaunchO
186
188
  const changed = loaded === null || installed === null || loaded !== installed;
187
189
  if (changed && noteReadable(req.notePath)) {
188
190
  adapterLog(cfg, `rollover: relaunch handed to a fresh launcher (${loaded ?? "unknown"} → ${installed ?? "unknown"})`);
191
+ // P11: one version-change ledger event per relaunch on a version change; the release verdict reads a to < from event as a downgrade.
192
+ appendMetric(cfg, { type: "version-change", from: loaded ?? "unknown", to: installed ?? "unknown", ts: Math.floor(Date.now() / 1000) });
189
193
  return runChild(process.execPath, [join(PACKAGE_ROOT, "src", "cli", "main.ts"), "main", ...carried], {
190
194
  ...process.env,
191
195
  NEURASTREAM_RELAUNCH_SINCE: String(started),
@@ -277,6 +281,7 @@ async function nextMessage(req: RelaunchRequest, cfg: Config, mainStart: typeof
277
281
  note,
278
282
  previousSessionFile: req.previousSessionFile,
279
283
  ownerMessage: `${OWNER_AWAY}${draft}`,
284
+ unanswered: unansweredOwnerMessages(readOwnerMessages(), readOwnerAnswers()),
280
285
  });
281
286
  const bytes = Buffer.byteLength(handoff);
282
287
  if (bytes <= MAX_INLINE_HANDOFF) {
@@ -18,6 +18,7 @@ import { tmpSnapshot } from "../core/tmp-snapshot.ts";
18
18
  import { wipBackup } from "../core/wip-backup.ts";
19
19
  import { wipCheck } from "../core/wip-check.ts";
20
20
  import { wipSnapshot } from "../core/wip-snapshot.ts";
21
+ import { withHeartbeat } from "../core/heartbeat.ts";
21
22
  import { runtime } from "./runtime.ts";
22
23
  import { getAdapter } from "../adapters/index.ts";
23
24
 
@@ -63,9 +64,9 @@ export async function runPorted(cmd: string, args: string[]): Promise<number> {
63
64
  case "wip-check":
64
65
  return wipCheck(args, rt.cfg);
65
66
  case "wip-backup":
66
- return wipBackup(args, rt.cfg);
67
+ return withHeartbeat(rt.cfg, "wip-backup", () => wipBackup(args, rt.cfg));
67
68
  case "wip-snapshot":
68
- return wipSnapshot(args, rt.cfg);
69
+ return withHeartbeat(rt.cfg, "wip-snapshot", () => wipSnapshot(args, rt.cfg));
69
70
  case "main-health":
70
71
  return mainHealth(args, rt.cfg, rt.source);
71
72
  case "queue-check":
@@ -2,7 +2,14 @@ import { existsSync, readFileSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { pagesDoctor } from "../core/pages-doctor.ts";
4
4
  import { ConfigError, configFile, loadConfig, type Config } from "../core/config.ts";
5
+ import { beat, withHeartbeat } from "../core/heartbeat.ts";
6
+ import { helpDoc } from "../core/help.ts";
7
+ import { watchOnce, systemUnitLister, watchDoctorLine, watchHealth, timerStaffedPlans } from "../core/watch.ts";
8
+ import { defaultGather } from "../core/main-start.ts";
9
+ import { gatherTags } from "../core/results.ts";
10
+ import { nowSec } from "../core/clock.ts";
5
11
  import { postReply } from "../core/notify.ts";
12
+ import { log } from "../core/guards.ts";
6
13
  import { loadKnownSecrets, redactSecrets, redactSummary } from "../core/secret-redact.ts";
7
14
  import { applyQueueEnv } from "../core/queue/env.ts";
8
15
  import { getAdapter } from "../adapters/index.ts";
@@ -16,9 +23,11 @@ import { runUi } from "./ui.ts";
16
23
  import { runDiagram } from "./diagram.ts";
17
24
  import { runNotes } from "./notes.ts";
18
25
  import { runPages } from "./pages.ts";
26
+ import { watchOn, watchOff } from "./watch-setup.ts";
19
27
  import { runUninstall } from "../core/uninstall.ts";
20
28
  import { queueMigrate } from "../core/queue-migrate.ts";
21
- import { allowedAgents, enforceReadOnlyIndex, indexPath, readIndex, subagentsPath, writeIndex } from "../core/queue/lib.ts";
29
+ import { activePlans, allowedAgents, enforceReadOnlyIndex, gitTop, indexPath, readIndex, subagentsPath, writeIndex } from "../core/queue/lib.ts";
30
+ import { defaultRunner } from "../core/mr-sweep.ts";
22
31
  import { allowAgents, denyAgents, invalidSlugs } from "../core/subagents.ts";
23
32
 
24
33
  const BINS = [
@@ -139,11 +148,77 @@ export async function run(cmd: string, args: string[]): Promise<number> {
139
148
  try {
140
149
  const was = enforceReadOnlyIndex(loadConfig().paths.queue_index);
141
150
  if (was) console.warn(`warning: ${indexPath()} — was ${was}, set 0444 (the plan index is read-only on disk)`);
151
+ console.log(watchDoctorLine(watchHealth(loadConfig(), Date.now())));
142
152
  } catch {} // a broken config is doctor's own report; the adapter doctor names it
143
153
  return getAdapter().doctor();
144
154
  }
145
155
  if (cmd === "notify") return runNotify(args);
146
156
  if (cmd === "redact") return runRedact(args);
157
+ // Hidden: not in helpText. Beats once — the live check (plan P8) and the owner's own cron jobs.
158
+ if (cmd === "heartbeat") {
159
+ const failIdx = args.indexOf("--fail");
160
+ const fail = failIdx >= 0 ? args[failIdx + 1] : undefined;
161
+ const name = args.find((a, i) => a !== "--fail" && i !== failIdx + 1 && !a.startsWith("--"));
162
+ if (!name || (failIdx >= 0 && fail === undefined)) {
163
+ console.error('usage: neurastream heartbeat <name> [--fail "<text>"]');
164
+ return 2;
165
+ }
166
+ try {
167
+ beat(loadConfig(), name, { ok: fail === undefined, detail: fail ?? "" });
168
+ } catch (err) {
169
+ console.error(err instanceof ConfigError ? err.message : String(err));
170
+ return 1;
171
+ }
172
+ return 0;
173
+ }
174
+ // One watcher pass (plan 20261027_1430 P2); the P4 timer calls this every watch interval.
175
+ // Beats its own "watch" heartbeat AFTER the pass: ok only when the watcher itself ran.
176
+ if (cmd === "watch") {
177
+ if (args.length === 1 && (args[0] === "--help" || args[0] === "-h")) {
178
+ console.log(helpDoc("watch"));
179
+ return 0;
180
+ }
181
+ if (args.length === 1 && args[0] === "on") return watchOn();
182
+ if (args.length === 1 && args[0] === "off") return watchOff();
183
+ if (args.length) {
184
+ console.error("usage: neurastream watch [on|off]");
185
+ return 2;
186
+ }
187
+ try {
188
+ const cfg = loadConfig();
189
+ // main.ts calls process.exit right after run() returns, so every post is awaited
190
+ // before the exit; a failed provider lands in guard.log, never crashes the watcher.
191
+ const sends: Promise<void>[] = [];
192
+ const code = withHeartbeat(cfg, "watch", () => {
193
+ const report = watchOnce(cfg, {
194
+ now: nowSec,
195
+ listUnits: systemUnitLister,
196
+ gather: defaultGather(cfg, getAdapter(cfg)),
197
+ // P11: the self repo's tags and the session source feed the release verdict; no tags — no verdicts.
198
+ source: getAdapter(cfg).runSource(cfg),
199
+ tags: gatherTags(gitTop(import.meta.dir)?.repo ?? null),
200
+ notify: text => {
201
+ sends.push(
202
+ postReply(text, cfg).then(rs => {
203
+ for (const r of rs) if (!r.posted) log(cfg.paths.guard_log, `watch notify failed [${r.provider}]: ${r.error}`);
204
+ }),
205
+ );
206
+ },
207
+ runner: defaultRunner,
208
+ plans: () => activePlans(),
209
+ // Plans whose newest spawn (staffing.json) is inside the watch.ci_red_hours window: a timer run has no live job list to ask.
210
+ staffed: now => timerStaffedPlans(now, cfg.watch.ci_red_hours),
211
+ });
212
+ console.log(`watch: ${report.opened.length} opened, ${report.deduped.length} deduped, ${report.closed.length} recovered, ${report.detectors.length} detector findings`);
213
+ return 0;
214
+ });
215
+ await Promise.allSettled(sends);
216
+ return code;
217
+ } catch (err) {
218
+ console.error(err instanceof ConfigError ? err.message : String(err));
219
+ return 1;
220
+ }
221
+ }
147
222
  if (cmd === "uninstall") return runUninstall(args);
148
223
  if (cmd === "queue" && args[0] === "migrate") {
149
224
  try {
package/src/cli/init.ts CHANGED
@@ -9,6 +9,7 @@ import { fileURLToPath } from "node:url";
9
9
  import { configFile, loadConfig, TEMPLATE_PATH, type Config } from "../core/config.ts";
10
10
  import { allowedAgents } from "../core/queue/lib.ts";
11
11
  import { allowAgents, invalidSlugs, InvalidSlugError } from "../core/subagents.ts";
12
+ import { watchOn } from "./watch-setup.ts";
12
13
 
13
14
  const HERE = dirname(fileURLToPath(import.meta.url));
14
15
  export const PACKAGE_ROOT = resolve(HERE, "../..");
@@ -181,6 +182,13 @@ export function runInit(args: string[] = []): number {
181
182
  const interactive = allow === undefined && Boolean(process.stdin.isTTY && process.stdout.isTTY);
182
183
  const ask = interactive ? () => askLine("Subagents allowed to spawn (comma-separated names, empty = none): ") : undefined;
183
184
  printInit(initHome(homedir(), { invoked: process.argv[1] ?? "", env: process.env, agentDir, allow, ask }));
185
+ // Interactive only (plan 20261027_1430 P4): empty, y or yes installs the watcher timer.
186
+ if (interactive) {
187
+ const answer = askLine("Watch neurastream jobs and alert me? [Y/n] ").trim().toLowerCase();
188
+ if ((answer === "" || answer === "y" || answer === "yes") && watchOn() !== 0) {
189
+ console.log("watch not set up; fix the error above, then run `neurastream watch on`");
190
+ }
191
+ }
184
192
  return 0;
185
193
  } catch (err) {
186
194
  console.error(err instanceof Error ? err.message : String(err));
@@ -6,6 +6,7 @@ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
6
6
  import { join } from "node:path";
7
7
  import { ConfigError, loadConfig, type Config } from "../core/config.ts";
8
8
  import { appendMetric, readMetricEvents } from "../core/metrics.ts";
9
+ import { recordCiMr } from "../core/ci.ts";
9
10
  import { nowSec } from "../core/clock.ts";
10
11
  import type { RunSource } from "../core/adapter.ts";
11
12
  import { buildReport, type BloatSummary, type ProviderSummary } from "../core/report.ts";
@@ -13,8 +14,10 @@ import { providerFindings } from "../core/trace-provider.ts";
13
14
  import { bloatRules } from "../core/trace-bloat.ts";
14
15
  import { getAdapter } from "../adapters/index.ts";
15
16
  import { featuresReport, gatherTags, loadPlans, releasesReport, type FeaturesReport, type ReleasesReport } from "../core/results.ts";
16
- import { gitTop } from "../core/queue/lib.ts";
17
+ import { activePlans, gitTop } from "../core/queue/lib.ts";
18
+ import { recheckHolds, spawnHoldRunner, staleHoldLines, type HoldRunner } from "../core/waiting-check.ts";
17
19
  import { assignDumps, bloatReport } from "./traces.ts";
20
+ import { withHeartbeat } from "../core/heartbeat.ts";
18
21
 
19
22
  export const METRICS_USAGE = [
20
23
  "usage: neurastream metrics ci <repo-dir> <mr-id>",
@@ -30,72 +33,29 @@ function flagValue(args: string[], name: string): string | undefined {
30
33
  return i >= 0 ? args[i + 1] : undefined;
31
34
  }
32
35
 
33
- /** Single-quotes a value for `sh -c`, so an MR id cannot inject shell syntax. */
34
- function shellQuote(v: string): string {
35
- return `'${v.replaceAll("'", "'\\''")}'`;
36
- }
37
-
38
36
  /** Runs the configured CI command in the repo and records how many pipelines the MR needed. */
39
- export function recordCi(cfg: Config, repoDir: string, mr: string, now: number): number {
37
+ export function recordCi(cfg: Config, repoDir: string, mr: string, now: number, run: HoldRunner = spawnHoldRunner(cfg.queue.waiting_check_timeout_sec)): number {
40
38
  if (!repoDir || !mr) {
41
39
  console.error(METRICS_USAGE);
42
40
  return 2;
43
41
  }
44
- const template = cfg.metrics.ci_pipelines_cmd;
45
- if (!template) {
46
- console.error("metrics.ci_pipelines_cmd not set");
47
- return 2;
48
- }
49
42
  if (!existsSync(repoDir)) {
50
43
  console.error(`repo-dir not found: ${repoDir}`);
51
44
  return 2;
52
45
  }
53
- const proc = Bun.spawnSync(["sh", "-c", template.replaceAll("{mr}", shellQuote(mr))], {
54
- cwd: repoDir,
55
- stdout: "pipe",
56
- stderr: "pipe",
57
- });
58
- if (proc.exitCode !== 0) {
59
- console.error(`ci command exited ${proc.exitCode}: ${proc.stderr.toString().trim()}`);
60
- return 1;
61
- }
62
- let pipelines: unknown;
63
- try {
64
- pipelines = JSON.parse(proc.stdout.toString());
65
- } catch {
66
- pipelines = undefined;
67
- }
68
- if (!Array.isArray(pipelines)) {
69
- console.error("ci command must print a JSON array on stdout");
70
- return 1;
46
+ const r = recordCiMr(cfg, repoDir, mr, now);
47
+ if (!r.ok) {
48
+ console.error(r.error);
49
+ return r.code;
71
50
  }
72
- appendMetric(cfg, { type: "ci", mr, repo: repoDir, tries: pipelines.length, ts: now });
73
- console.log(`ci: ${mr} needed ${pipelines.length} pipeline(s)`);
74
- recordProducts(cfg, repoDir, now);
51
+ console.log(`ci: ${mr} needed ${r.tries} pipeline(s)`);
52
+ for (const s of r.skipped) console.error(s);
53
+ // A new CI record can change what a hold check sees, so every hold is re-checked now, not on its TTL.
54
+ const plans = activePlans(cfg.paths.queue_index);
55
+ for (const line of staleHoldLines(recheckHolds(cfg, plans, run, now, true), plans)) console.log(line);
75
56
  return 0;
76
57
  }
77
58
 
78
- const PRODUCT_TIMEOUT_MS = 10_000;
79
-
80
- /**
81
- * Runs the repo's configured product numbers once each (metrics.product_cmds) and appends one
82
- * product record per number. A command that fails, times out or prints anything but one finite
83
- * number is skipped with a stderr line; the ci record itself never fails on a product number.
84
- */
85
- function recordProducts(cfg: Config, repoDir: string, now: number): void {
86
- for (const [name, cmd] of Object.entries(cfg.metrics.product_cmds[repoDir] ?? {})) {
87
- const proc = Bun.spawnSync(["sh", "-c", cmd], { cwd: repoDir, stdout: "pipe", stderr: "pipe", timeout: PRODUCT_TIMEOUT_MS });
88
- const out = proc.stdout.toString().trim();
89
- const value = Number(out);
90
- if (proc.exitCode !== 0 || out === "" || !Number.isFinite(value)) {
91
- const why = proc.exitCode !== 0 ? `exit ${proc.exitCode ?? "signal"}` : `not one number: "${out.slice(0, 40)}"`;
92
- console.error(`product_cmds.${name}: skipped (${why})`);
93
- continue;
94
- }
95
- appendMetric(cfg, { type: "product", repo: repoDir, name, value, ts: now });
96
- }
97
- }
98
-
99
59
  /** Marks one guard BLOCK line (by its ISO timestamp) as a false alarm. */
100
60
  export function recordFalseAlarm(cfg: Config, logTs: string, why: string, now: number): number {
101
61
  if (!logTs || !why) {
@@ -286,7 +246,7 @@ export async function runMetrics(args: string[]): Promise<number> {
286
246
  const [sub = "", ...rest] = args;
287
247
  const now = nowSec();
288
248
  if (sub === "ci") return recordCi(cfg, rest[0] ?? "", rest[1] ?? "", now);
289
- if (sub === "report") return reportCmd(cfg, getAdapter(cfg).runSource(cfg), rest, now);
249
+ if (sub === "report") return withHeartbeat(cfg, "metrics-report", () => reportCmd(cfg, getAdapter(cfg).runSource(cfg), rest, now));
290
250
  if (sub === "features") return featuresCmd(cfg, getAdapter(cfg).runSource(cfg), rest, now);
291
251
  if (sub === "releases") return releasesCmd(cfg, getAdapter(cfg).runSource(cfg), rest, now);
292
252
  if (sub === "false-alarm") return recordFalseAlarm(cfg, rest[0] ?? "", flagValue(rest, "--why") ?? "", now);
package/src/cli/pages.ts CHANGED
@@ -2,6 +2,7 @@ import { readdirSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { getAdapter } from "../adapters/index.ts";
4
4
  import { loadConfig } from "../core/config.ts";
5
+ import { beat, errorLine } from "../core/heartbeat.ts";
5
6
  import { readExpiry, sweepPages } from "../core/pages-expiry.ts";
6
7
  import { startPagesServer } from "../core/pages.ts";
7
8
  import { pageNotesGate } from "../core/page-notes.ts";
@@ -18,9 +19,15 @@ export async function runPages(args: string[] = [], deps: PagesDeps = {}): Promi
18
19
  if (args[0] === "off" && args.length === 1) return pagesOff({ home, runner: deps.runner });
19
20
  const cfg = loadConfig({ home });
20
21
  if (args[0] === "serve" && args.length === 1) {
21
- if (!cfg.pages.enabled) throw new Error("pages.enabled is false");
22
- sweepPages(cfg.pages.dir, cfg.pages.keep_days, clock());
23
- startPagesServer({ cfg, tailscale: deps.tailscale ?? realTailscale, source: getAdapter(cfg).runSource(cfg) });
22
+ try {
23
+ if (!cfg.pages.enabled) throw new Error("pages.enabled is false");
24
+ sweepPages(cfg.pages.dir, cfg.pages.keep_days, clock());
25
+ startPagesServer({ cfg, tailscale: deps.tailscale ?? realTailscale, source: getAdapter(cfg).runSource(cfg) });
26
+ } catch (e) {
27
+ beat(cfg, "pages-serve", { ok: false, detail: errorLine(e) });
28
+ throw e;
29
+ }
30
+ beat(cfg, "pages-serve", { ok: true });
24
31
  setInterval(() => { try { sweepPages(cfg.pages.dir, cfg.pages.keep_days, clock()); } catch (e) { console.error(e instanceof Error ? e.message : String(e)); } }, HOUR_MS);
25
32
  return new Promise<number>(() => {});
26
33
  }
package/src/cli/ui.ts CHANGED
@@ -6,6 +6,7 @@
6
6
 
7
7
  import { getAdapter } from "../adapters/index.ts";
8
8
  import { ConfigError, loadConfig, type Config } from "../core/config.ts";
9
+ import { beat, errorLine } from "../core/heartbeat.ts";
9
10
  import { startOwnerUi, type OwnerUiOptions, type OwnerUiServer } from "../core/owner-ui.ts";
10
11
  import { applyQueueEnv } from "../core/queue/env.ts";
11
12
  import { realTailscale, type Tailscale } from "../core/tailscale.ts";
@@ -84,7 +85,13 @@ export async function runUi(args: string[] = [], deps: UiDeps = {}): Promise<num
84
85
  console.error("neurastream ui: ui.owner_login is empty — set the tailscale login that may open the page");
85
86
  return 1;
86
87
  }
87
- (deps.start ?? startOwnerUi)({ cfg, tailscale: realTailscale, source: getAdapter(cfg).runSource(cfg) });
88
+ try {
89
+ (deps.start ?? startOwnerUi)({ cfg, tailscale: realTailscale, source: getAdapter(cfg).runSource(cfg) });
90
+ } catch (e) {
91
+ beat(cfg, "ui", { ok: false, detail: errorLine(e) });
92
+ throw e;
93
+ }
94
+ beat(cfg, "ui", { ok: true });
88
95
  // src/cli/main.ts exits with the code this returns, which would kill the server: serving
89
96
  // never resolves, and the process runs until systemd or a signal stops it.
90
97
  return new Promise<number>(() => {});