neurastream 0.3.20 → 0.3.21

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.
Files changed (49) hide show
  1. package/package.json +1 -1
  2. package/src/adapters/index.ts +3 -2
  3. package/src/adapters/omp/adapter.ts +2 -1
  4. package/src/adapters/omp/auto-close.ts +64 -0
  5. package/src/adapters/omp/chat-commands.ts +161 -0
  6. package/src/adapters/omp/inbox.ts +221 -0
  7. package/src/adapters/omp/index.ts +115 -1039
  8. package/src/adapters/omp/launch.ts +31 -3
  9. package/src/adapters/omp/rate-limit-controller.ts +196 -0
  10. package/src/adapters/omp/rollover-controller.ts +334 -0
  11. package/src/adapters/omp/types.ts +143 -0
  12. package/src/cli/commands.ts +33 -2
  13. package/src/cli/dispatch.ts +37 -16
  14. package/src/cli/recall.ts +3 -2
  15. package/src/cli/results-build.ts +1 -1
  16. package/src/cli/workspace.ts +13 -2
  17. package/src/core/adapter.ts +16 -0
  18. package/src/core/blockers.ts +326 -30
  19. package/src/core/file-lock.ts +71 -12
  20. package/src/core/guards/plan-edit.ts +338 -0
  21. package/src/core/guards/planner.ts +70 -0
  22. package/src/core/guards/review.ts +391 -0
  23. package/src/core/guards/spawn.ts +699 -0
  24. package/src/core/guards/state.ts +581 -0
  25. package/src/core/guards/stop.ts +235 -0
  26. package/src/core/guards/tool.ts +541 -0
  27. package/src/core/guards.ts +12 -2658
  28. package/src/core/incidents.ts +125 -91
  29. package/src/core/machine-guard.ts +23 -5
  30. package/src/core/main-start.ts +10 -8
  31. package/src/core/owner-topics.ts +2 -13
  32. package/src/core/owner-ui/auth.ts +164 -0
  33. package/src/core/owner-ui/data.ts +437 -0
  34. package/src/core/owner-ui/handlers.ts +250 -0
  35. package/src/core/owner-ui/messages.ts +209 -0
  36. package/src/core/owner-ui/render.ts +714 -0
  37. package/src/core/owner-ui/results.ts +266 -0
  38. package/src/core/owner-ui/server.ts +142 -0
  39. package/src/core/owner-ui.ts +11 -2121
  40. package/src/core/page-notes.ts +25 -0
  41. package/src/core/pages.ts +452 -77
  42. package/src/core/plan-approval.ts +12 -14
  43. package/src/core/queue/lib.ts +88 -39
  44. package/src/core/queue-cancel.ts +21 -17
  45. package/src/core/queue-close.ts +48 -23
  46. package/src/core/secret-redact.ts +65 -14
  47. package/src/core/tailscale.ts +79 -3
  48. package/src/core/team-client.ts +13 -2
  49. package/src/core/uninstall.ts +2 -0
@@ -0,0 +1,235 @@
1
+ // Prompt injection, cancel-word flagging, and keep-working stop rules.
2
+
3
+ import type { Decision, InjectEvent, StopEvent } from "../adapter.ts";
4
+ import { currentTier } from "../autonomy.ts";
5
+ import type { Config } from "../config.ts";
6
+ import { withFileLock, writeAtomicSync } from "../file-lock.ts";
7
+ import * as q from "../queue/lib.ts";
8
+ import { summaryHolder, teamSummaryLines, teamViews } from "../team-client.ts";
9
+ import {
10
+ ALLOW,
11
+ CANCEL_TODO,
12
+ incidentLine,
13
+ isOwnerProse,
14
+ log,
15
+ mainCallsExpired,
16
+ openIncidentList,
17
+ readStaffing,
18
+ readWindow,
19
+ recordOwnerMessage,
20
+ staffedPlans,
21
+ unlockLine,
22
+ writeWindow,
23
+ } from "./state.ts";
24
+
25
+ // Owner message that may call work off: flag it; until Main records it with queue-cancel, no
26
+ // spawn and no stop. Returns the text appended to the injected summary.
27
+ export function flagCancel(text: string, cfg: Config): string {
28
+ const m = text.match(q.CANCEL_WORDS);
29
+ if (!m) return "";
30
+ const at = m.index ?? 0;
31
+ const words = text.slice(Math.max(0, at - 60), at + 80).replace(/\s+/g, " ").trim();
32
+ const pendingFile = q.cancelPendingPath(cfg.paths);
33
+ try {
34
+ withFileLock(`${pendingFile}.lock`, () => {
35
+ const prev = q.cancelPending(cfg.paths);
36
+ writeAtomicSync(pendingFile, JSON.stringify({ at: new Date().toISOString(), words: prev ? `${prev.words} … ${words}` : words }));
37
+ });
38
+ } catch (err) {
39
+ log(cfg.paths.guard_log, `cannot write ${pendingFile}: ${err}`);
40
+ }
41
+ log(cfg.paths.guard_log, `cancel flagged: ${words}`);
42
+ return `\nmain-guard: ${CANCEL_TODO} Flagged: "${words}"`;
43
+ }
44
+
45
+ /**
46
+ * prompt/owner message: inject the queue summary, flag cancel wording, list open incidents, reset
47
+ * Main's edit window and the stop counters (the original resets them at every user message). A
48
+ * turn the harness
49
+ * starts from this guard's own stop continuation ("main-guard: …") is not an owner message: it
50
+ * keeps the counters and the edit window, else every continuation reset the idle streak and a
51
+ * model that only answers text was nudged again forever (2026-10-21 OOM: ~205 agent starts in one
52
+ * non-interactive session).
53
+ */
54
+ export function checkInject(e: InjectEvent, cfg: Config): Decision {
55
+ if (e.agent !== "main") return ALLOW;
56
+ const continuation = e.inject.trimStart().startsWith("main-guard:");
57
+ if (!continuation) writeWindow({ used: [], windowStart: 0, mainCalls: 0 }, cfg.paths);
58
+ recordOwnerMessage(e.inject, cfg);
59
+ let summary: string;
60
+ try {
61
+ // P4 (20261027_1305): one GET /view per team, read once and handed to the holder and the
62
+ // team lines, so the summary costs one request per team and never a second GET /claims.
63
+ const views = teamViews(cfg);
64
+ summary = q.queueSummary(cfg.paths, cfg.review.agents, summaryHolder(cfg, {}, views));
65
+ const teamLines = teamSummaryLines(cfg, views, q.SUMMARY_CAP);
66
+ if (teamLines.length) summary += `\n${teamLines.join("\n")}`;
67
+ } catch (err) {
68
+ summary = `Queue unreadable (${cfg.paths.queue_index}): ${err}`;
69
+ }
70
+ // P3 (plan 20261031_1207): only owner prose flags cancel, and incident lines pasted into a
71
+ // prompt (guard output quoting "stop …") never do — their words are not the owner's.
72
+ const cancel = continuation || !isOwnerProse(e.inject)
73
+ ? ""
74
+ : flagCancel(e.inject.split("\n").filter(l => !l.startsWith("INCIDENT I-")).join("\n"), cfg);
75
+ const incidents = openIncidentList(cfg);
76
+ const incidentText = incidents.length ? `\n${incidents.map(incidentLine).join("\n")}` : "";
77
+ // 20261025_1940 P2: the injected line names the autonomy tier and what Main does without asking in it.
78
+ const tier = currentTier(cfg);
79
+ const tierNote =
80
+ tier === "strict"
81
+ ? `Main changes at most ${cfg.autonomy.strict_edit_limit} project files per ${cfg.guards.main_window_min} min, and every git push / glab mr merge / gh pr merge waits for your "${cfg.autonomy.go_phrase}" (one landing, valid ${cfg.autonomy.go_minutes} min).`
82
+ : tier === "full"
83
+ ? `Main works unattended: no edit cap, its own "Priority skip: <plan> — Main: \\"<reason>\\"" skips pass, pushes and merges go through. Owner-only moves (guard files, the phone page, notify secrets, the unlock) stay locked.`
84
+ : `Main changes at most ${cfg.guards.main_edit_limit} project files per ${cfg.guards.main_window_min} min; pushes and merges go through.`;
85
+ const unlockNote = continuation ? "" : unlockLine(cfg);
86
+ const mayNote = ` Main may edit Status/WAITING/Waits on/False positive lines. Test before saying "cannot".`;
87
+ const editLimit = continuation ? "" : `\nautonomy: ${tier} — ${tierNote}${mayNote}${unlockNote}`;
88
+ return {
89
+ allow: true,
90
+ reason: "",
91
+ inject: `${summary}\n(main-guard: read ${cfg.paths.queue_index}; the listed plans are summarised above; work the open plans, close finished ones with queue-close.)${editLimit}${cancel}${incidentText}`,
92
+ ...(continuation ? {} : { state: { callsSinceStop: 0, idleStops: 0 } }),
93
+ };
94
+ }
95
+
96
+ // Plans still responsible for: open plans (parked "WAITING on owner" excluded) plus queue problems.
97
+ export function openQueue(paths: q.QueuePaths, reviewAgents: string[] = []): string[] {
98
+ const open = q
99
+ .activePlans(paths)
100
+ .filter(p => !p.waiting && !q.awaitingMerge(p, paths))
101
+ .map(p => p.file);
102
+ for (const prob of q.queueProblems(paths, reviewAgents)) open.push(`${prob.where}: ${prob.problem}`);
103
+ const unique: string[] = [];
104
+ for (const item of open) if (!unique.includes(item)) unique.push(item);
105
+ return unique;
106
+ }
107
+
108
+ // Agent names from a ledger line that are alive (RUNNING or WAITING, idle under an hour).
109
+ export function liveSubagents(ledgerOut: string): string[] {
110
+ return ledgerOut
111
+ .split("\n")
112
+ .filter(l => !l.startsWith("MAIN ") && /\s(RUNNING|WAITING)\b/.test(l))
113
+ .filter(l => {
114
+ const m = l.match(/idle (\d+)m/);
115
+ return !m || Number(m[1]) < 60;
116
+ })
117
+ .map(l => l.split(/\s+/)[0] ?? "");
118
+ }
119
+
120
+ export const STOP_PLAN_OFFER_REFUSAL = "main-guard: don't promise it — do it now, or write the plan and index it";
121
+
122
+ /**
123
+ * stop: Main may not stop while an open plan is not parked "WAITING on owner" (or the queue has a
124
+ * problem) and no subagent is alive to wake it; an open owner-correction incident (source
125
+ * "realtime", no plan, no dismissal) blocks the stop regardless of live subagents. Three stop
126
+ * attempts in a row with zero tool calls
127
+ * in between are let through. Returns the next counters in `state`.
128
+ */
129
+ export function checkStop(e: StopEvent, cfg: Config): Decision {
130
+ if (e.agent !== "main") return ALLOW;
131
+ const state = { callsSinceStop: e.callsSinceStop, idleStops: e.idleStops };
132
+ // 20261028_0900 P2: a reply that offers to plan instead of planning is refused for the offer
133
+ // itself; the two-empty-stops valves below never release this block.
134
+ if (e.reply && new RegExp(cfg.guards.plan_offer, "i").test(e.reply)) {
135
+ log(cfg.paths.guard_log, "BLOCK stop: reply offers or promises instead of doing it");
136
+ return { allow: false, reason: STOP_PLAN_OFFER_REFUSAL, state };
137
+ }
138
+ // P5 (plan 20261031_1207): once the turn spent its call budget, the stop is the release —
139
+ // refusing it would order a capped Main to keep making calls the cap itself refuses. The
140
+ // 15-min window expiry restarts the count, and the keep-working rule with it.
141
+ if (cfg.guards.main_max_calls > 0) {
142
+ const w = readWindow(cfg.paths);
143
+ if (w.mainCalls >= cfg.guards.main_max_calls && !mainCallsExpired(w)) {
144
+ log(cfg.paths.guard_log, `ALLOW stop: turn spent ${w.mainCalls}/${cfg.guards.main_max_calls} calls`);
145
+ return { ...ALLOW, state };
146
+ }
147
+ }
148
+ let open: string[];
149
+ try {
150
+ open = openQueue(cfg.paths, cfg.review.agents);
151
+ } catch (err) {
152
+ log(cfg.paths.guard_log, `BLOCK stop: cannot read queue: ${err}`);
153
+ open = [`queue unreadable (${cfg.paths.queue_index}): ${err}`];
154
+ }
155
+ const pending = q.cancelPending(cfg.paths);
156
+ if (pending && state.idleStops < 2) {
157
+ if (state.callsSinceStop === 0) state.idleStops++;
158
+ state.callsSinceStop = 0;
159
+ log(cfg.paths.guard_log, `BLOCK stop: cancel pending (${pending.words})`);
160
+ return { allow: false, reason: `main-guard: ${CANCEL_TODO} Flagged: "${pending.words}"`, state };
161
+ }
162
+ // Same release valve as cancel-pending: an idle Main that cannot act is let out after two
163
+ // empty stop attempts instead of looping forever. Live subagents do not clear this block.
164
+ // Findings/traces stay notes: only owner corrections (source "realtime") block the stop.
165
+ const incidents = openIncidentList(cfg).filter(i => i.source === "realtime");
166
+ if (incidents.length && state.idleStops < 2) {
167
+ if (state.callsSinceStop === 0) state.idleStops++;
168
+ state.callsSinceStop = 0;
169
+ const ids = incidents.map(i => i.id).join(", ");
170
+ log(cfg.paths.guard_log, `BLOCK stop: open incidents: ${ids}`);
171
+ return {
172
+ allow: false,
173
+ reason:
174
+ `main-guard: ${incidents.length} open incident(s) with no plan and no dismissal: ${ids}. Plan the fix: ` +
175
+ "`neurastream incident plan <id> <plan.md>` (the plan must contain \"INCIDENT <id>\"), or dismiss it: " +
176
+ '`neurastream incident dismiss <id> --why "<text>"`. The stop stays refused while an incident is open.',
177
+ state,
178
+ };
179
+ }
180
+ // P5 (plan 20261031_0911): a landed open plan whose auto-close failed holds the stop until a
181
+ // running subagent's brief names it (staffing ∩ live ledger); unrelated live subagents release
182
+ // nothing. Valve (20261031_2320): like the incident block above, empty stops count toward
183
+ // cfg.guards.idle_stops; a stop with calls in between resets the count and re-locks.
184
+ const locked = q.activePlans(cfg.paths).filter(p => p.status === "open" && q.autoCloseCandidate(p) && q.lastCloseFailed(p.file, cfg.paths));
185
+ if (locked.length) {
186
+ const staffed = staffedPlans(readStaffing(cfg.paths), liveSubagents(e.ledgerText));
187
+ const unworked = locked.filter(s => !staffed.includes(s.file));
188
+ if (unworked.length) {
189
+ if (state.callsSinceStop === 0) state.idleStops++;
190
+ else state.idleStops = 0;
191
+ state.callsSinceStop = 0;
192
+ if (state.idleStops >= cfg.guards.idle_stops) {
193
+ log(cfg.paths.guard_log, `ALLOW stop after ${state.idleStops} idle stop attempts; locked: ${unworked.map(s => s.file).join(", ")}`);
194
+ return { allow: true, reason: "", state: { callsSinceStop: 0, idleStops: 0 } };
195
+ }
196
+ const left = cfg.guards.idle_stops - state.idleStops;
197
+ log(cfg.paths.guard_log, `BLOCK stop: landed but not closed: ${unworked.map(s => s.file).join(", ")}`);
198
+ return {
199
+ allow: false,
200
+ reason:
201
+ `main-guard: ${unworked.map(s => `${s.file} landed but its auto-close failed (${(q.lastCloseResult(s.file, cfg.paths) ?? "").replace(/^queue-close: /, "")})`).join("; ")}. ` +
202
+ "The stop stays locked: spawn an agent whose brief names the plan, or fix the close. " +
203
+ `${left} idle stop ${left === 1 ? "attempt" : "attempts"} left before the stop is allowed.`,
204
+ state,
205
+ };
206
+ }
207
+ }
208
+ if (open.length === 0) return { ...ALLOW, state };
209
+ const live = liveSubagents(e.ledgerText);
210
+ if (live.length > 0) {
211
+ log(cfg.paths.guard_log, `ALLOW stop: live subagents: ${live.join(", ")}`);
212
+ return { ...ALLOW, state };
213
+ }
214
+ if (state.callsSinceStop === 0) state.idleStops++;
215
+ else state.idleStops = 0;
216
+ state.callsSinceStop = 0;
217
+ if (state.idleStops >= cfg.guards.idle_stops) {
218
+ log(cfg.paths.guard_log, `ALLOW stop after ${state.idleStops} idle stop attempts; open: ${open.join(" | ")}`);
219
+ return { allow: true, reason: "", state: { callsSinceStop: 0, idleStops: 0 } };
220
+ }
221
+ // P5b (plan 20261031_1207): the refusal repeats on every blocked stop; name the first 10 only.
222
+ const listed = open.slice(0, q.SUMMARY_CAP);
223
+ const moreOpen = open.length - listed.length;
224
+ log(cfg.paths.guard_log, `BLOCK stop; open: ${open.join(" | ")}`);
225
+ return {
226
+ allow: false,
227
+ reason:
228
+ `main-guard: the queue has ${open.length} open item${open.length === 1 ? "" : "s"} and no subagent is ` +
229
+ `running to wake you. Owner rule: keep working while the queue has items. Start the next step (spawn an ` +
230
+ `agent), close a finished plan with queue-close, or, if a plan truly waits on the owner, add a line ` +
231
+ `"WAITING on owner: <what>" to that plan. Open: ${listed.join(" | ")}` +
232
+ (moreOpen > 0 ? ` … ${moreOpen} more (queue-check lists all)` : ""),
233
+ state,
234
+ };
235
+ }