neurastream 0.2.66 → 0.2.68

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.
@@ -0,0 +1,225 @@
1
+ // The probe loop (plan 20261027_1500, P2): when the provider rate-limits the main agent, wait for
2
+ // the named reset if the provider gave one; otherwise probe it every probe_interval_s until it
3
+ // answers, up to max_probes. The state transitions are pure (onLimited, onProbe); runProbe runs the
4
+ // configured probe command under the main-limit lock. The episode file (main-limit.json) and
5
+ // probeStep (one tick of the loop) live here too. Harness-neutral: nothing here names a harness or a provider.
6
+
7
+ import { spawnSync } from "node:child_process";
8
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
9
+ import { dirname, join } from "node:path";
10
+ import type { Config } from "./config.ts";
11
+ import { strftime } from "./clock.ts";
12
+ import { tryLock } from "./file-lock.ts";
13
+ import { appendMetric } from "./metrics.ts";
14
+ import { postReply } from "./notify.ts";
15
+ import { loadKnownSecrets, redactSecrets } from "./secret-redact.ts";
16
+
17
+ /** One rate-limit episode of the main agent. Times are epoch ms. */
18
+ export interface LimitState {
19
+ since: number;
20
+ model: string;
21
+ reset_named: boolean;
22
+ next_probe_at: number;
23
+ probes: number;
24
+ last_error: string;
25
+ back_at: number | null;
26
+ }
27
+
28
+ export interface ProbeTiming {
29
+ probe_interval_s: number;
30
+ max_probes: number;
31
+ slack_s: number;
32
+ }
33
+
34
+ export type ProbeOutcome = { kind: "resume" } | { kind: "again"; at: number } | { kind: "give_up" };
35
+
36
+ export interface ProbeStep {
37
+ state: LimitState;
38
+ outcome: ProbeOutcome;
39
+ }
40
+
41
+ export interface ProbeResult {
42
+ ok: boolean;
43
+ exitCode: number | null;
44
+ stderr: string;
45
+ }
46
+
47
+ export type ProbeRunner = (
48
+ file: string,
49
+ args: string[],
50
+ opts: { timeout: number },
51
+ ) => { status: number | null; stderr: string; error?: Error };
52
+
53
+ const defaultRun: ProbeRunner = (file, args, opts) => spawnSync(file, args, { ...opts, encoding: "utf8" as const });
54
+
55
+ const shellQuote = (value: string): string => `'${value.replaceAll("'", "'\\''")}'`;
56
+
57
+ /**
58
+ * The main agent was rate-limited at `now`. A named reset (epoch ms) is waited for, plus slack;
59
+ * without one the first probe comes after probe_interval_s.
60
+ */
61
+ export function onLimited(
62
+ state: LimitState | null,
63
+ namedResetMs: number | null,
64
+ errorText: string,
65
+ now: number,
66
+ model: string,
67
+ timing: ProbeTiming,
68
+ ): LimitState {
69
+ const named = namedResetMs !== null;
70
+ const next = named ? namedResetMs + timing.slack_s * 1000 : now + timing.probe_interval_s * 1000;
71
+ return {
72
+ since: state?.since ?? now,
73
+ model,
74
+ reset_named: named,
75
+ next_probe_at: next,
76
+ probes: state?.probes ?? 0,
77
+ last_error: errorText,
78
+ back_at: named ? next : null,
79
+ };
80
+ }
81
+
82
+ /**
83
+ * A probe finished at `now`. Every probe counts. A successful probe resumes; a failed one probes
84
+ * again after probe_interval_s until max_probes is reached, then gives up.
85
+ */
86
+ export function onProbe(state: LimitState, ok: boolean, errorText: string, now: number, timing: ProbeTiming): ProbeStep {
87
+ const probes = state.probes + 1;
88
+ if (ok) return { state: { ...state, probes }, outcome: { kind: "resume" } };
89
+ if (probes >= timing.max_probes) {
90
+ return { state: { ...state, probes, last_error: errorText }, outcome: { kind: "give_up" } };
91
+ }
92
+ const at = now + timing.probe_interval_s * 1000;
93
+ return { state: { ...state, probes, last_error: errorText, next_probe_at: at }, outcome: { kind: "again", at } };
94
+ }
95
+
96
+ /**
97
+ * Run guards.rate_limit.probe_cmd once, with {model} replaced by the shell-quoted model, under the
98
+ * main-limit lock. Returns "busy" when another probe holds the lock. The output is never logged in
99
+ * full: stderr is redacted, then cut to 200 characters.
100
+ */
101
+ export function runProbe(cfg: Config, model: string, run: ProbeRunner = defaultRun): ProbeResult | "busy" {
102
+ const lock = tryLock(join(cfg.paths.queue_state, "main-limit.lock"));
103
+ if (!lock) return "busy";
104
+ try {
105
+ const rl = cfg.guards.rate_limit;
106
+ const cmd = rl.probe_cmd.replaceAll("{model}", shellQuote(model));
107
+ const r = run("sh", ["-c", cmd], { timeout: rl.probe_timeout_s * 1000 });
108
+ const stderr = redactSecrets(r.stderr, loadKnownSecrets(cfg), cfg.secrets.extra_patterns).text.slice(0, 200);
109
+ return { ok: r.status === 0 && !r.error, exitCode: r.status, stderr };
110
+ } finally {
111
+ lock.release();
112
+ }
113
+ }
114
+
115
+ /** Where the open episode lives: one JSON file in queue_state, replaced atomically. */
116
+ export function limitStatePath(cfg: Config): string {
117
+ return join(cfg.paths.queue_state, "main-limit.json");
118
+ }
119
+
120
+ /** The open episode, or null when there is none (or the file cannot be parsed). */
121
+ export function readLimitState(cfg: Config): LimitState | null {
122
+ try {
123
+ return JSON.parse(readFileSync(limitStatePath(cfg), "utf8")) as LimitState;
124
+ } catch {
125
+ return null;
126
+ }
127
+ }
128
+
129
+ export function writeLimitState(cfg: Config, state: LimitState): void {
130
+ const path = limitStatePath(cfg);
131
+ mkdirSync(dirname(path), { recursive: true });
132
+ writeFileSync(`${path}.tmp`, `${JSON.stringify(state)}\n`);
133
+ renameSync(`${path}.tmp`, path);
134
+ }
135
+
136
+ export function clearLimitState(cfg: Config): void {
137
+ rmSync(limitStatePath(cfg), { force: true });
138
+ }
139
+
140
+ export function timingOf(cfg: Config): ProbeTiming {
141
+ const rl = cfg.guards.rate_limit;
142
+ return { probe_interval_s: rl.probe_interval_s, max_probes: rl.max_probes, slack_s: rl.slack_s };
143
+ }
144
+
145
+ /**
146
+ * One tick of the probe loop at `now`. Returns "idle" when no episode is open, the episode is
147
+ * already back, or the next probe is not due; "busy" when another probe holds the lock. Otherwise
148
+ * runs one probe and records its outcome. A give-up closes the episode: one ⚠ post to the owner
149
+ * chat (via `notify`, default the redacting postReply) and one `limit` metric. If the episode was
150
+ * closed (turn-end disarm) or replaced while the probe ran, the result is dropped instead of
151
+ * written back. A resume only marks the episode back — the adapter's tick posts the ✅ and the
152
+ * metric when it sends Main's new turn.
153
+ */
154
+ export function probeStep(
155
+ cfg: Config,
156
+ now: number,
157
+ run: ProbeRunner = defaultRun,
158
+ notify: (text: string) => void = (text) => {
159
+ void postReply(text, cfg);
160
+ },
161
+ ): "idle" | "busy" | ProbeOutcome["kind"] {
162
+ const st = readLimitState(cfg);
163
+ if (!st || st.back_at !== null || now < st.next_probe_at) return "idle";
164
+ const r = runProbe(cfg, st.model, run);
165
+ if (r === "busy") return "busy";
166
+ const current = readLimitState(cfg);
167
+ if (!current || current.since !== st.since) return "idle";
168
+ const timing = timingOf(cfg);
169
+ const step = onProbe(current, r.ok, r.stderr, now, timing);
170
+ if (step.outcome.kind === "give_up") {
171
+ clearLimitState(cfg);
172
+ appendMetric(cfg, limitMetric(step.state, now));
173
+ notify(giveUpPost(timing));
174
+ } else if (step.outcome.kind === "resume") writeLimitState(cfg, { ...step.state, back_at: now });
175
+ else writeLimitState(cfg, step.state);
176
+ return step.outcome.kind;
177
+ }
178
+
179
+ // ---- P4 tell + record: the owner-facing texts and the metric record of a finished episode ----
180
+ // Every text here is built from times and counts only; the error text in LimitState.last_error is
181
+ // unredacted, so no builder takes it — a post, the metric and the report line cannot carry it.
182
+
183
+ /** Minutes the main agent has been limited, from `since` to the episode's end. */
184
+ function limitedMinutes(state: LimitState, now: number): number {
185
+ return Math.max(0, Math.round(((state.back_at ?? now) - state.since) / 60000));
186
+ }
187
+
188
+ /** A duration in whole units the owner reads at a glance: "24 h", "15 min", "5 s". */
189
+ function durationText(seconds: number): string {
190
+ if (seconds >= 3600) return `${Math.round(seconds / 360) / 10} h`;
191
+ if (seconds >= 60) return `${Math.round(seconds / 60)} min`;
192
+ return `${seconds} s`;
193
+ }
194
+
195
+ const clockHM = (ms: number): string => strftime(ms / 1000, "%H:%M");
196
+
197
+ /** The post when an episode opens: a named reset announces when it lifts, an unnamed one the probe cadence. */
198
+ export function limitedPost(state: LimitState, interval_s: number): string {
199
+ const at = clockHM(state.since);
200
+ return state.reset_named
201
+ ? `⏳ Main hit its limit at ${at}; resets at ${clockHM(state.next_probe_at)}`
202
+ : `⏳ Main hit its limit at ${at}; checking every ${durationText(interval_s)}`;
203
+ }
204
+
205
+ /** The post when the provider answered or the named reset passed: times and counts only. */
206
+ export function backPost(state: LimitState): string {
207
+ return `✅ Main is back at ${clockHM(state.back_at!)} (limited ${limitedMinutes(state, state.back_at!)} min, ${state.probes} checks)`;
208
+ }
209
+
210
+ /** The post when max_probes is spent without an answer. */
211
+ export function giveUpPost(timing: ProbeTiming): string {
212
+ return `⚠ Main still limited after ${durationText(timing.max_probes * timing.probe_interval_s)}`;
213
+ }
214
+
215
+ /** The metric record of one finished episode: numbers and a boolean, never the error text. */
216
+ export function limitMetric(state: LimitState, now: number): Record<string, unknown> {
217
+ return {
218
+ type: "limit",
219
+ since: state.since,
220
+ back_at: state.back_at,
221
+ minutes: limitedMinutes(state, now),
222
+ probes: state.probes,
223
+ reset_named: state.reset_named,
224
+ };
225
+ }
@@ -209,6 +209,13 @@ const enqueuePost = <T>(operation: () => Promise<T>): Promise<T> => {
209
209
  return result;
210
210
  }
211
211
 
212
+ /** Resolves once every post enqueued so far has finished. Posts are fire-and-forget for callers;
213
+ * tests drain the queue before clearing their hit lists, so one test's late post never lands in
214
+ * the next test's window. */
215
+ export function notifyIdle(): Promise<void> {
216
+ return postQueue;
217
+ }
218
+
212
219
  /** Post Main's final reply to every configured provider, serially across calls. 429s retry once
213
220
  * after Discord's requested delay (capped at 10 seconds); other failures return to the caller. */
214
221
  export function postReply(text: string, cfg: Config): Promise<NotifyPostResult[]> {
@@ -797,6 +797,10 @@ function protectedPaths(): string[] {
797
797
  // The user's neurastream config file, even when agent_dir points elsewhere: an agent that
798
798
  // could rewrite it could point notify at its own webhook.
799
799
  `${HOME}/.config/neurastream/config.yml`,
800
+ // The planner mode guard baseline beside that file (plan 20261102_1515 P2 d): the
801
+ // owner-only anchor of the mode facts. A write that could plant or edit it would make the
802
+ // writer's own dirt the truth, so no tool may touch it.
803
+ `${HOME}/.config/neurastream/guard-baseline`,
800
804
  `${agent}/notes/subagents.md`,
801
805
  `${agent}/.guard-unlock`,
802
806
  `${path.dirname(agent)}/git-no-verify-guard.mjs`,
@@ -1,65 +1,37 @@
1
- // Provider rate limits (plan 20261025_0640): a turn that ended on one waits it out instead of
2
- // asking again straight into the limit. Pure decisions only: what counts as a rate limit, and how
3
- // long to wait. The words and the waits come from config (guards.rate_limit); the adapter supplies
4
- // the turn's stop reason and error text and arms the timer.
1
+ // Provider rate limits (plan 20261025_0640, reshaped by 20261027_1500 P2): a turn that ended on a
2
+ // rate limit is recognised here; what happens next (a named wait or probing the provider) is decided
3
+ // by the adapter and src/core/limit-probe.ts. Pure: what counts as a rate limit, and the retry-after
4
+ // the provider names. The words come from config (guards.rate_limit); the adapter supplies the turn's
5
+ // stop reason and error text.
5
6
 
6
7
  export interface RateLimitConfig {
7
8
  /** Case-insensitive substrings in the error text that mark a rate limit. */
8
9
  patterns: string[];
9
- /** Wait when the error text names no retry-after. */
10
- default_wait_s: number;
11
- /** Cap for the parsed (or doubled) wait, before slack. */
12
- max_wait_s: number;
13
- /** Added on top of every wait. */
14
- slack_s: number;
15
10
  }
16
11
 
17
- export interface RateLimitWait {
18
- /** Epoch ms when the next turn should start. */
19
- untilMs: number;
20
- /** Total wait in ms, slack included. */
21
- waitMs: number;
12
+ export interface RateLimited {
13
+ /** The provider's named retry-after in ms, or null when the error text names none. */
14
+ retryAfterMs: number | null;
22
15
  }
23
16
 
24
17
  const RETRY_AFTER_MS = /retry-after-ms[=:]\s*(\d+)/i;
25
18
  const RETRY_AFTER_S = /retry-after[=:]\s*(\d+)/i;
26
19
 
27
- function retryAfterMs(errorText: string, cfg: RateLimitConfig): { ms: number; named: boolean } {
20
+ function namedRetryAfterMs(errorText: string): number | null {
28
21
  const ms = RETRY_AFTER_MS.exec(errorText);
29
- if (ms) return { ms: Number(ms[1]), named: true };
22
+ if (ms) return Number(ms[1]);
30
23
  const s = RETRY_AFTER_S.exec(errorText);
31
- if (s) return { ms: Number(s[1]) * 1000, named: true };
32
- return { ms: cfg.default_wait_s * 1000, named: false };
24
+ if (s) return Number(s[1]) * 1000;
25
+ return null;
33
26
  }
34
27
 
35
28
  /**
36
- * The wait for a turn that ended on a provider rate limit, or null when it did not: the stop
37
- * reason must be "error" and the error text must contain one of the configured patterns
38
- * (case-insensitive). A named retry-after is used as-is; otherwise default_wait_s is doubled
39
- * for each later attempt. The resulting wait is clamped to max_wait_s, then slack_s is added.
29
+ * The rate limit a turn ended on, or null when it did not: the stop reason must be "error" and the
30
+ * error text must contain one of the configured patterns (case-insensitive).
40
31
  */
41
- export function rateLimitWait(
42
- stopReason: string | null,
43
- errorText: string | null,
44
- now: number,
45
- cfg: RateLimitConfig,
46
- attempt: number,
47
- ): RateLimitWait | null {
32
+ export function rateLimited(stopReason: string | null, errorText: string | null, cfg: RateLimitConfig): RateLimited | null {
48
33
  if (stopReason !== "error" || !errorText) return null;
49
34
  const text = errorText.toLowerCase();
50
35
  if (!cfg.patterns.some(p => text.includes(p.toLowerCase()))) return null;
51
- const capMs = cfg.max_wait_s * 1000;
52
- const retryAfter = retryAfterMs(errorText, cfg);
53
- let baseMs = retryAfter.ms;
54
- if (!retryAfter.named) {
55
- for (let i = 1; i < Math.max(1, attempt); i++) {
56
- baseMs *= 2;
57
- if (baseMs >= capMs) {
58
- baseMs = capMs;
59
- break;
60
- }
61
- }
62
- }
63
- const waitMs = Math.min(baseMs, capMs) + cfg.slack_s * 1000;
64
- return { untilMs: now + waitMs, waitMs };
36
+ return { retryAfterMs: namedRetryAfterMs(errorText) };
65
37
  }
@@ -292,10 +292,18 @@ export function buildReport(cfg: Config, source: RunSource, days: number, now: n
292
292
  }),
293
293
  ];
294
294
  const falseAlarms = events.filter((e) => e.type === "false-alarm" && inWindow(Number(e.ts), cur)).length;
295
+ // Plan 20261027_1500 P4: finished main-agent limit episodes, one line over the window. The
296
+ // metric record is numbers + a boolean, but read only the pinned fields here, so a stray
297
+ // last_error can never reach the report.
298
+ const limitEvents = events.filter((e) => e.type === "limit" && inWindow(Number(e.since) / 1000, cur));
299
+ const limitMinutes = limitEvents.reduce((n, e) => n + Number(e.minutes ?? 0), 0);
295
300
  const noisy = noisyDetectors(incidents, cur, cfg.watch);
296
301
  const quality = [
297
302
  `Silent failures: ${silentFailures(incidents, cur)} watch incidents; suspected false blocks: ${m7(incidents, falseAlarms, cur)}`,
298
303
  `Flaky jobs: ${events.filter((e) => e.type === "ci-flaky" && inWindow(Number(e.ts), cur)).length} same-commit red→green re-runs`,
304
+ ...(limitEvents.length > 0
305
+ ? [`Main limited: ${limitMinutes >= 60 ? `${Math.round(limitMinutes / 6) / 10} h` : `${limitMinutes} min`} over ${limitEvents.length} episodes`]
306
+ : []),
299
307
  "Dismiss rate by kind (opened, planned, dismissed):",
300
308
  ...kindStats(incidents, cur).map((k) => `- ${k.kind}: ${k.opened}, ${k.planned}, ${k.dismissed} (${Math.round(k.dismissRate * 100)}% dismissed)`),
301
309
  ];
@@ -9,7 +9,7 @@ You are Main, the orchestrator. Main plans, delegates, reviews and lands; implem
9
9
  - INDEX.md order is priority: free agents go to the top plans first. A lower plan goes first only when the higher one says `Waits on: <plan>`, is WAITING on owner, or the brief quotes the owner: `Priority skip: <plan> — owner: "<his words>"`.
10
10
  - A hold is one line: `WAITING on owner: <what to do> — blocked: <what stays stuck until then> — why you: <why Main cannot do it>`. The phone page shows those three parts; a missing part is left out.
11
11
  - Entering a repo: read its AGENTS.md first.
12
- - Main writes every plan in `<repo>/docs/plans/`, shaped like `{{AGENT_DIR}}/queue/TEMPLATE.md`. Do the research yourself; never base a plan on another agent's findings.
12
+ - Main writes every plan in `<repo>/docs/plans/`, shaped like `{{AGENT_DIR}}/queue/TEMPLATE.md`. Do the research yourself; never base a plan on another agent's findings. In `planner delegated` mode the planner agent writes the plan instead (`Planner: <agent>` header; the research and the `## Code read by Main` list are the planner's): Main routes the owner's asks to it, dispatches implementers, checks the outcomes (verify commands, CI, the reviewer's PASS) and lands, and Main does not read repo code to plan. The owner's whole message `planner main` returns this rule; `autonomy.planner` (default `main`) is the same switch in the config.
13
13
  - Phase 0 of every plan: blocker scripts that stop the implementer from going against the plan. They must exist before any spawn.
14
14
  - Every plan has `## Reuse`; no spawn without a current reviewer PASS (`templates/plan-review-brief.md`, recorded only from the reviewer's own Progress edit); a brief names every open MR of its plan with an `MR !N:` line.
15
15
  - Plan order: plan → page built from the architecture-drilldown template (`neurastream pages publish <page.html> --plan <plan.md>` refuses anything else) → owner approves (Approve on the page, or types `approve <YYYYMMDD_HHMM>`) → reviewer PASS → implementer. Once `approval.since` is set, a plan stamped at or after it gets no spawn without a page and an approval record for its current text; a body edit voids the approval, a Progress-only edit keeps it.
@@ -131,9 +131,11 @@ guards:
131
131
  plan_offer: 'want me to (write|make) a plan|should i plan|shall i plan|if you want, i(''ll)? plan|plan it or|\bi will\b|\bi(''|’)ll\b' # refused: don't promise or offer it — do it now, or write the plan and index it
132
132
  rate_limit:
133
133
  patterns: ["429", "rate_limit", "rate limit", "overloaded", "529"] # error-text substrings (case-insensitive) that mark a provider rate limit
134
- default_wait_s: 300 # wait when the error text names no retry-after
135
- max_wait_s: 3600 # cap for the parsed (or doubled) wait, before slack
136
134
  slack_s: 15 # added on top of every wait
135
+ probe_interval_s: 300 # probe the provider this often (s) while it names no reset
136
+ max_probes: 288 # probes before the episode gives up (288 x 300 s = 24 h)
137
+ probe_timeout_s: 90 # kill a probe that runs longer than this (s)
138
+ probe_cmd: "omp -p --no-extensions --no-session --model {model} 'reply ok'" # {model} is replaced by the shell-quoted model; exit 0 = the provider answered
137
139
  blocker_timeout_ms: 10000 # timeout for blocker checks in milliseconds
138
140
  skip_tools: [todo, wait, ask, web_search, job, cancel_job] # tools the guard never counts
139
141
  read_tools: [read, grep, glob, find] # tools counted as reads
@@ -147,6 +149,7 @@ guards:
147
149
 
148
150
  autonomy:
149
151
  tier: opinionated # strict | opinionated | full: how much Main does without asking; the owner moves it with `tier <name>` in chat or a button on the phone page
152
+ planner: main # main = Main writes the plans; delegated = the planner agent plans and Main routes only (plan 20261102_1515); the owner flips it with `planner <mode>` in chat or here
150
153
  strict_edit_limit: 2 # Main's project-file changes per main_window_min in tier strict
151
154
  go_minutes: 10 # minutes the approve phrase approves exactly one push/merge in tier strict
152
155
  go_phrase: "go push" # the whole chat message that approves one push/merge in tier strict (I-20261025-201); a bare `go` is an ordinary message
@@ -1,5 +1,7 @@
1
1
  # <short title>
2
2
  Worktree: <work root>/<repo>-<topic> (configure paths.work_roots, e.g. {{HOME}}/work)
3
+ <!-- Planner mode: in `planner delegated` the planner agent writes the plan, and the plan carries a
4
+ bare `Planner: <agent>` line above the first `##` (no trailing comment). Omit it while Main plans. -->
3
5
  Branch: <type>/<topic>
4
6
  Summary: <one or two plain sentences: what this plan gives the owner>
5
7
  PRIORITY-ID: <optional, e.g. PR01>