neurastream 0.3.18 → 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 (66) hide show
  1. package/README.md +88 -490
  2. package/package.json +1 -1
  3. package/src/adapters/index.ts +3 -2
  4. package/src/adapters/omp/adapter.ts +2 -1
  5. package/src/adapters/omp/auto-close.ts +64 -0
  6. package/src/adapters/omp/chat-commands.ts +161 -0
  7. package/src/adapters/omp/inbox.ts +221 -0
  8. package/src/adapters/omp/index.ts +138 -1050
  9. package/src/adapters/omp/launch.ts +35 -9
  10. package/src/adapters/omp/rate-limit-controller.ts +196 -0
  11. package/src/adapters/omp/rollover-controller.ts +334 -0
  12. package/src/adapters/omp/types.ts +143 -0
  13. package/src/cli/claim.ts +1 -3
  14. package/src/cli/commands.ts +33 -2
  15. package/src/cli/dispatch.ts +55 -30
  16. package/src/cli/guard.ts +0 -3
  17. package/src/cli/incident.ts +2 -2
  18. package/src/cli/metrics.ts +1 -1
  19. package/src/cli/recall.ts +6 -8
  20. package/src/cli/results-build.ts +2 -4
  21. package/src/cli/workspace.ts +13 -5
  22. package/src/core/adapter.ts +16 -0
  23. package/src/core/autonomy.ts +24 -21
  24. package/src/core/blockers.ts +326 -30
  25. package/src/core/file-lock.ts +71 -12
  26. package/src/core/guards/plan-edit.ts +338 -0
  27. package/src/core/guards/planner.ts +70 -0
  28. package/src/core/guards/review.ts +391 -0
  29. package/src/core/guards/spawn.ts +699 -0
  30. package/src/core/guards/state.ts +581 -0
  31. package/src/core/guards/stop.ts +235 -0
  32. package/src/core/guards/tool.ts +541 -0
  33. package/src/core/guards.ts +12 -2661
  34. package/src/core/incidents.ts +134 -99
  35. package/src/core/machine-guard.ts +23 -5
  36. package/src/core/main-start.ts +11 -9
  37. package/src/core/mr-sweep.ts +4 -2
  38. package/src/core/notify.ts +15 -15
  39. package/src/core/owner-log.ts +19 -17
  40. package/src/core/owner-topics.ts +38 -48
  41. package/src/core/owner-ui/auth.ts +164 -0
  42. package/src/core/owner-ui/data.ts +437 -0
  43. package/src/core/owner-ui/handlers.ts +250 -0
  44. package/src/core/owner-ui/messages.ts +209 -0
  45. package/src/core/owner-ui/render.ts +714 -0
  46. package/src/core/owner-ui/results.ts +266 -0
  47. package/src/core/owner-ui/server.ts +142 -0
  48. package/src/core/owner-ui.ts +11 -2118
  49. package/src/core/page-notes.ts +25 -0
  50. package/src/core/pages.ts +452 -78
  51. package/src/core/plan-approval.ts +24 -26
  52. package/src/core/queue/lib.ts +170 -137
  53. package/src/core/queue-cancel.ts +29 -15
  54. package/src/core/queue-check.ts +5 -7
  55. package/src/core/queue-close.ts +54 -29
  56. package/src/core/queue-finished.ts +9 -10
  57. package/src/core/queue-migrate.ts +1 -3
  58. package/src/core/queue-trim.ts +2 -4
  59. package/src/core/results.ts +0 -2
  60. package/src/core/rollover.ts +2 -3
  61. package/src/core/secret-redact.ts +65 -14
  62. package/src/core/tailscale.ts +79 -3
  63. package/src/core/team-client.ts +18 -6
  64. package/src/core/uninstall.ts +2 -0
  65. package/src/core/watch.ts +3 -2
  66. package/src/core/queue/env.ts +0 -14
@@ -16,48 +16,51 @@
16
16
  // Harness payloads are untyped at the boundary: every field read goes through a runtime check.
17
17
 
18
18
  import { execFileSync, spawn } from "node:child_process";
19
- import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
20
- import { basename, dirname, extname, join, resolve } from "node:path";
21
- import type { Decision, TraceEvent } from "../../core/adapter.ts";
19
+ import { closeSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
20
+ import { basename, extname, join, resolve } from "node:path";
21
+ import type { TraceEvent } from "../../core/adapter.ts";
22
22
  import { AGENTS_TEMPLATE, renderBlock } from "../../core/agents-md.ts";
23
- import { chatGo, chatPlanner, chatTier, currentPlanner, plannerPin, stampPlannerMode, verifyPlannerMode, type Tier } from "../../core/autonomy.ts";
24
- import { chatApprove } from "../../core/plan-approval.ts";
25
- import { burdenRule, repoRules, rulesChanged } from "../../core/repo-rules.ts";
23
+ import { currentPlanner, plannerPin, stampPlannerMode, verifyPlannerMode } from "../../core/autonomy.ts";
24
+ import { briefPaths } from "../../core/brief-lint.ts";
25
+ import { fileClaimStore, type ClaimStore } from "../../core/claims.ts";
26
+ import { nowSec } from "../../core/clock.ts";
26
27
  import { configFile, loadConfig, reloadingConfig, type Config } from "../../core/config.ts";
27
- import { checkWrite, deferSteer, type WriteCheckConfig } from "../../core/write-check.ts";
28
- import { nowSec, strftime } from "../../core/clock.ts";
28
+ import { tryLock, type HeldLock } from "../../core/file-lock.ts";
29
+ import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, mainId, mainStateDir, newProgressEntries, planReadNote, plannerSpawnPlan, recordMainResult, rekeySpawnFile, resetMainCalls, revertMainEdit, reviewSpawnEnd, STOP_PLAN_OFFER_REFUSAL } from "../../core/guards.ts";
29
30
  import { runDetectors, type DetectorInput } from "../../core/incident-detectors.ts";
30
- import { fileClaimStore, type ClaimStore } from "../../core/claims.ts";
31
- import { remoteStoreFor } from "../../core/team-client.ts";
32
- import { appendOwnerAnswer, readOwnerAnswers, readOwnerMessages } from "../../core/incidents.ts";
31
+ import { appendOwnerAnswer } from "../../core/incidents.ts";
32
+ import { mainDetectors } from "../../core/main-start.ts";
33
+ import { notifyProviders, ownerAnswerHandback, ownerAnswerSteer, postReply } from "../../core/notify.ts";
33
34
  import { appendedSinceSpawn, markTopicsSpawned, ownerLogDir, recordOwnerLog } from "../../core/owner-log.ts";
34
35
  import { topicsDue, topicsLogFile } from "../../core/owner-topics.ts";
35
- import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, mainId, mainStateDir, newProgressEntries, planReadNote, plannerSpawnPlan, recordMainResult, resetMainCalls, revertMainEdit, rekeySpawnFile, reviewSpawnEnd, STOP_PLAN_OFFER_REFUSAL } from "../../core/guards.ts";
36
- import { rateLimited } from "../../core/rate-limit.ts";
37
- import { backPost, clearLimitState, limitMetric, limitedPost, onLimited, readLimitState, timingOf, writeLimitState } from "../../core/limit-probe.ts";
38
- import { appendMetric } from "../../core/metrics.ts";
39
- import { notifyProviders, ownerAnswerHandback, ownerAnswerSteer, postReply } from "../../core/notify.ts";
36
+ import { readPressure } from "../../core/pressure.ts";
37
+ import * as q from "../../core/queue/lib.ts";
38
+ import { burdenRule, repoRules, rulesChanged } from "../../core/repo-rules.ts";
39
+ import { notePath, ownerText, spawnRefusal } from "../../core/rollover.ts";
40
40
  import { loadKnownSecrets, redactSecrets, redactSummary } from "../../core/secret-redact.ts";
41
- import { inboxPath } from "../../core/owner-ui.ts";
42
41
  import { realTailscale } from "../../core/tailscale.ts";
43
- import { briefPaths } from "../../core/brief-lint.ts";
42
+ import { remoteStoreFor } from "../../core/team-client.ts";
44
43
  import { actionsRules, ownedRepoOf, suspiciousActions, unreportedFindings } from "../../core/trace-actions.ts";
45
- import { applyQueueEnv } from "../../core/queue/env.ts";
46
- import { mainDetectors, mainStartText } from "../../core/main-start.ts";
47
-
48
- import { buildHandoff, holdsBlock, notePath, noteRequest, OWNER_AWAY, ownerText, relaunchPath, rolloverState, spawnRefusal, unansweredOwnerMessages, type RolloverState } from "../../core/rollover.ts";
49
- import { defaultCompletedResults, defaultRunSource, runIdOf } from "./sessions.ts";
50
- import { ompProviders } from "./providers.ts";
44
+ import { checkWrite, deferSteer, type WriteCheckConfig } from "../../core/write-check.ts";
45
+ import { autoClose } from "./auto-close.ts";
46
+ import { registerChatCommands } from "./chat-commands.ts";
47
+ import { CLAIM_BEAT_MS, deliverOwnerInbox, OWNER_INBOX_POLL_MS, ownerInboxCursorPath, ownerInboxMessage, pendingInboxRecords, pressureTick, seedInboxFloor } from "./inbox.ts";
51
48
  import { adapterLog, MAIN_ENV } from "./launch.ts";
52
- import { parseTraceFile } from "./traces.ts";
53
- import { packageJsonPath, packageVersion } from "./package-root.ts";
54
- import * as q from "../../core/queue/lib.ts";
55
- import { pinModel, providerOfModel, recordOut, resetEpochFromText } from "../../core/provider-state.ts";
56
- import { annotateResetTimes } from "../../core/reset-time.ts";
57
- import { tryLock, type HeldLock } from "../../core/file-lock.ts";
58
- import { currentHolder, pressureLevel, pressureMessage, pressureTransition, readPressure, type PressureSample, type PressureState } from "../../core/pressure.ts";
59
49
  // Registers the plugin-command matcher into core's writeTargets (side effect).
60
50
  import "./package-ops.ts";
51
+ import { createRateLimitController, limitProbeSpawn, recordProviderOutFromRateLimit, recordProviderOutFromTask } from "./rate-limit-controller.ts";
52
+ import { createRolloverController } from "./rollover-controller.ts";
53
+ import { defaultCompletedResults, defaultRunSource, runIdOf } from "./sessions.ts";
54
+ import { parseTraceFile } from "./traces.ts";
55
+ import { asCtx, asRecord, asRolloverCtx, asString, call, isMain, lastAssistantIn, toExtensionResult, type EventReply, type ExtensionHost, type RolloverCtx } from "./types.ts";
56
+
57
+ export { adapterLog, autoClose, CLAIM_BEAT_MS, deliverOwnerInbox, limitProbeSpawn, OWNER_INBOX_POLL_MS, ownerInboxCursorPath, ownerInboxMessage, pendingInboxRecords, pressureTick, recordProviderOutFromRateLimit, toExtensionResult, type ExtensionHost };
58
+
59
+ /** Optional test/caller seams for `createOmpAdapter`. */
60
+ export interface OmpAdapterOptions {
61
+ /** Overrides the `doctor` runner passed into `mainStartText` during in-process rollover fallback. */
62
+ doctor?: () => Promise<string> | string;
63
+ }
61
64
 
62
65
  /**
63
66
  * Re-reads the config, then holds the planner mode facts to the owner's baseline (P2 d): a
@@ -88,105 +91,9 @@ function defaultMainEvents(cfg: Config): TraceEvent[] {
88
91
  }
89
92
  }
90
93
 
91
- /** Subset of the harness extension host the adapter needs. */
92
- export interface ExtensionHost {
93
- on(event: string, cb: (...args: unknown[]) => unknown): void;
94
- registerCommand(name: string, opts: { description?: string; handler: (args: unknown, ctx: unknown) => unknown }): void;
95
- sendUserMessage(content: string | ({ type: "text"; text: string } | { type: "image"; data: string; mimeType: string })[]): void;
96
- sendMessage(message: { customType: string; content: string; display: boolean }, options: { triggerTurn: boolean; deliverAs: "nextTurn" }): void;
97
- }
98
-
99
- /** The parts of a harness call context the handlers look at. */
100
- interface HostCtx {
101
- hasAgent: boolean;
102
- kind?: string;
103
- id?: string;
104
- cwd?: string;
105
- setInterval?: (cb: () => void, ms: number) => unknown;
106
- spawnLimitProbe?: () => void;
107
- }
108
-
109
- function asRecord(v: unknown): Record<string, unknown> {
110
- return v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
111
- }
112
-
113
- function asString(v: unknown, fallback = ""): string {
114
- return typeof v === "string" ? v : fallback;
115
- }
116
-
117
- /** The last assistant message of an omp event's `messages` array, as the adapter needs it: its
118
- * joined text-block text and the shape that tells a real hand-back from a mid-run continuation
119
- * (plan 20261025_0130). omp sends the reply in `session_stop.last_assistant_message` (falling
120
- * back to the last assistant entry of `messages`) and in `agent_end.messages`; reading the
121
- * session file instead lags a whole turn because session_stop fires BEFORE agent_end. */
122
- interface EventReply {
123
- text: string;
124
- stopReason: string | null;
125
- toolCalls: number;
126
- /** The provider's error text on a turn that ended on one (`429 … retry-after-ms=…`); null otherwise. */
127
- errorMessage: string | null;
128
- /** The provider and model fields of the assistant message, when the event carries them; the provider-out recording keys on the provider. */
129
- provider: string | null;
130
- model: string | null;
131
- }
132
-
133
- function lastAssistantIn(messages: unknown): EventReply | null {
134
- const arr = Array.isArray(messages) ? messages : [];
135
- for (let i = arr.length - 1; i >= 0; i--) {
136
- const m = asRecord(arr[i]);
137
- if (m.role !== "assistant") continue;
138
- const content = Array.isArray(m.content) ? m.content : [];
139
- const text = content
140
- .filter(c => asRecord(c).type === "text")
141
- .map(c => asString(asRecord(c).text))
142
- .join("\n")
143
- .trim();
144
- return {
145
- text,
146
- stopReason: typeof m.stopReason === "string" ? m.stopReason : null,
147
- toolCalls: content.filter(c => asRecord(c).type === "toolCall").length,
148
- errorMessage: typeof m.errorMessage === "string" ? m.errorMessage : null,
149
- provider: typeof m.provider === "string" ? m.provider : null,
150
- model: typeof m.model === "string" ? m.model : null,
151
- };
152
- }
153
- return null;
154
- }
155
-
156
- function asCtx(v: unknown): HostCtx {
157
- const r = asRecord(v);
158
- // The agent envelope only ever carries kind/id strings (original extensions read just those);
159
- // cast fixes the envelope, every field below is checked before use.
160
- const agent = r.agent as { kind?: unknown; id?: unknown } | null | undefined;
161
- const out: HostCtx = { hasAgent: agent !== null && agent !== undefined };
162
- if (agent) {
163
- if (typeof agent.kind === "string") out.kind = agent.kind;
164
- if (typeof agent.id === "string") out.id = agent.id;
165
- }
166
- if (typeof r.cwd === "string") out.cwd = r.cwd;
167
- // Harness-injected timer with the original main-guard signature (ctx.setInterval).
168
- const interval = r.setInterval as ((cb: () => void, ms: number) => unknown) | undefined;
169
- if (typeof interval === "function") out.setInterval = interval;
170
- // Harness-injected probe spawner (tests); the default starts the niced probe child.
171
- const probe = r.spawnLimitProbe as (() => void) | undefined;
172
- if (typeof probe === "function") out.spawnLimitProbe = probe;
173
- return out;
174
- }
175
-
176
- /** Map a core decision onto the extension return shapes. */
177
- export function toExtensionResult(d: Decision): Record<string, unknown> {
178
- if (!d.allow) return { block: true, reason: d.reason, decision: "block" };
179
- if (d.inject) return { additionalContext: d.inject };
180
- return {};
181
- }
182
-
183
94
  // A push or merge by Main may have landed a completed plan: try closing right away.
184
95
  const PUSH_MERGE = /\bgit\b[^\n;|&]*\bpush\b|\b(glab\s+mr|gh\s+pr)\s+merge\b/;
185
96
 
186
- // The installed package and its version: see ./package-root.ts.
187
-
188
- export { adapterLog };
189
-
190
97
  /**
191
98
  * Paths named inside the one configured method doc (brief.method_read): Main-owned and outside
192
99
  * every run's write scope, so its named paths are trusted one hop past the brief text (P10c).
@@ -240,52 +147,6 @@ function subActionDetectors(cfg: Config, ctx: unknown, planFile: string, before:
240
147
  }
241
148
  }
242
149
 
243
- // Background queue-close for every plan Main marked complete — and (P4, plan 20261031_0911) for
244
- // every OPEN plan whose work has landed. Ported from the original autoClose: same filter, same
245
- // "--- auto-close attempt" log line, detached child with stdio on the per-plan close log.
246
- // QUEUE_CLOSE_BIN overrides the binary (tests); without it the package's own executable
247
- // bin/queue-close runs (its `#!/usr/bin/env bun` shebang picks bun).
248
- // Never process.execPath: inside the harness that is the harness binary itself, so the child was
249
- // a new agent session that loaded this plugin and auto-closed again — a process fork bomb
250
- // (2026-10-21 OOMs, ~175 processes).
251
- function closeChildArgs(plan: string, auto: boolean): [string, string[]] {
252
- const bin = process.env.QUEUE_CLOSE_BIN;
253
- const args = auto ? ["--auto", plan] : [plan];
254
- if (bin) return [bin, args];
255
- return [join(import.meta.dir, "..", "..", "..", "bin", "queue-close"), args];
256
- }
257
-
258
- export function autoClose(cfg: Config): string[] {
259
- const started: string[] = [];
260
- let plans: q.Plan[];
261
- try {
262
- // P4: landed open plans auto-close too (q.autoCloseCandidate) — the child runs queue-close
263
- // --auto and writes "Status: complete" itself when the done check passes.
264
- plans = q.activePlans().filter(p => (p.status === "complete" || p.status === "cancelled" || q.autoCloseCandidate(p)) && !p.errors.length);
265
- } catch {
266
- return started;
267
- }
268
- try {
269
- mkdirSync(q.stateDirPath(), { recursive: true });
270
- } catch {}
271
- for (const p of plans) {
272
- try {
273
- const outFile = q.closeLog(p.file);
274
- appendFileSync(outFile, `--- ${new Date().toISOString()} auto-close attempt\n`);
275
- const out = openSync(outFile, "a");
276
- const [bin, args] = closeChildArgs(p.file, p.status === "open");
277
- const child = spawn(bin, args, { detached: true, stdio: ["ignore", out, out], env: process.env });
278
- child.unref();
279
- closeSync(out);
280
- started.push(p.file);
281
- } catch (err) {
282
- adapterLog(cfg, `auto-close: could not start for ${p.file}: ${err}`);
283
- }
284
- }
285
- if (started.length) adapterLog(cfg, `auto-close started: ${started.join(", ")}`);
286
- return started;
287
- }
288
-
289
150
  // Main's stop gate needs the ledger output (original: `agent-ledger --hours 12` through bash -lc,
290
151
  // errors folded into empty output).
291
152
  function ledgerText(cfg: Config): string {
@@ -299,10 +160,10 @@ function ledgerText(cfg: Config): string {
299
160
 
300
161
  // Write-time checks (plan 20261028_1228): the text of each file a call names that a configured linter
301
162
  // covers, read before the call runs; null when the file does not exist yet.
302
- function writeCheckSnapshot(tool: string, input: Record<string, unknown>, cwd: string, wc: WriteCheckConfig): Map<string, string | null> {
163
+ function writeCheckSnapshot(tool: string, input: Record<string, unknown>, cwd: string, wc: WriteCheckConfig, cfg: Config): Map<string, string | null> {
303
164
  const exts = wc.linters.flatMap((l) => l.ext);
304
165
  const snap = new Map<string, string | null>();
305
- for (const file of q.writeTargets(tool, input, cwd)) {
166
+ for (const file of q.writeTargets(tool, input, cwd, cfg.paths)) {
306
167
  if (!exts.includes(extname(file))) continue;
307
168
  try {
308
169
  snap.set(file, readFileSync(file, "utf8"));
@@ -318,8 +179,8 @@ function writeCheckSnapshot(tool: string, input: Record<string, unknown>, cwd: s
318
179
  function snapshotPlans(tool: string, input: Record<string, unknown>, cwd: string, snap: Map<string, string>, main: boolean, plannerPlan: string | null, cfg: Config): void {
319
180
  if (tool !== "write" && tool !== "edit") return;
320
181
  const delegated = currentPlanner(cfg) === "delegated";
321
- const plans = q.activePlans();
322
- for (const p of q.writeTargets(tool, input, cwd)) {
182
+ const plans = q.activePlans(cfg.paths);
183
+ for (const p of q.writeTargets(tool, input, cwd, cfg.paths)) {
323
184
  if (snap.has(p)) continue;
324
185
  if (main) {
325
186
  // Main's own plan text is checked too; a plan that did not exist yet snapshots as "".
@@ -331,7 +192,7 @@ function snapshotPlans(tool: string, input: Record<string, unknown>, cwd: string
331
192
  }
332
193
  continue;
333
194
  }
334
- if (!q.isOrchestrationPath(p, plans) || !q.planAt(p, plans)) {
195
+ if (!q.isOrchestrationPath(p, plans, cfg.paths.queue_index) || !q.planAt(p, plans)) {
335
196
  // planner mode P2 (b): the brief's named plan snapshots before its create/edit so
336
197
  // checkPlanEdit judges it (Planner header, Main-only lines) — a new plan file is not
337
198
  // an indexed path yet, and every other plan write is refused pre-tool while delegated.
@@ -365,98 +226,6 @@ function redactToolResult(content: unknown[], cfg: Config): { content: unknown[]
365
226
  return { content: out, note: redactSummary([...hits].map(([type, count]) => ({ type, count }))) };
366
227
  }
367
228
 
368
- // Provider out-until from live data (plan 20261025_1700 P1). Two automatic recordings, both
369
- // keyed on the provider half of an agent pin's `model:` frontmatter, both best effort and
370
- // logged once. The reset-time case trusts the provider's own words; the no-time case falls
371
- // back to the armed rate-limit wait, so a provider without a quoted reset time still lands in
372
- // the file the guards and the ledger read.
373
- const resetRule = (cfg: Config): { pattern: string; zone: string } => ({ pattern: cfg.quota.reset_pattern, zone: cfg.quota.reset_tz });
374
-
375
- /** Task result that quotes a reset time: record it for the sub's provider. A batch naming
376
- * several providers cannot attribute the time to one of them, so it records nothing. */
377
- function recordProviderOutFromTask(e: Record<string, unknown>, content: unknown[], cfg: Config): void {
378
- if (asString(e.toolName) !== "task" || e.isError === true) return;
379
- const text = content.map(p => asString(asRecord(p).text)).join("\n");
380
- const epoch = resetEpochFromText(text, resetRule(cfg));
381
- if (epoch === null) return;
382
- const tasks = Array.isArray(asRecord(e.input).tasks) ? (asRecord(e.input).tasks as unknown[]) : [];
383
- const providers = new Set<string>();
384
- for (const t of tasks) {
385
- const provider = providerOfModel(pinModel(cfg, asString(asRecord(t).agent)));
386
- if (provider) providers.add(provider);
387
- }
388
- if (providers.size !== 1) return;
389
- const provider = [...providers][0]!;
390
- recordOut(cfg, provider, epoch, "task-result");
391
- adapterLog(cfg, `PROVIDER-OUT recorded: ${provider} out until ${new Date(epoch * 1000).toISOString()} (task result)`);
392
- }
393
-
394
- /** Rate-limited turn end: record the reset time the error text names, else the armed wait. Returns the
395
- * named reset in epoch ms (null when the text names none): the one parse of that text, which the call
396
- * site passes on to the rate-limit episode (plan 20261027_1500 P2/P3). */
397
- export function recordProviderOutFromRateLimit(reply: EventReply | null, untilMs: number, cfg: Config): number | null {
398
- const named = reply ? resetEpochFromText(reply.errorMessage ?? "", resetRule(cfg)) : null;
399
- const provider = reply?.provider ?? providerOfModel(reply?.model ?? null);
400
- if (provider) {
401
- const epoch = named ?? Math.floor(untilMs / 1000);
402
- recordOut(cfg, provider, epoch, named !== null ? "rate-limit-reset" : "rate-limit");
403
- adapterLog(cfg, `PROVIDER-OUT recorded: ${provider} out until ${new Date(epoch * 1000).toISOString()} (${named !== null ? "reset time in error text" : "rate limit, no reset time"})`);
404
- }
405
- return named === null ? null : named * 1000;
406
- }
407
-
408
- // Session rollover helpers: the harness context read through runtime checks, and the file size and
409
- // mtime reads. The decisions are in src/core/rollover.ts.
410
- const WAIT_NOTICE_MS = 15 * 60_000;
411
-
412
- interface RolloverCtx {
413
- sessionId: string;
414
- sessionFile: string;
415
- runningJobs(): string[];
416
- waitForIdle(): unknown;
417
- newSession(opts: { parentSession: string }): unknown;
418
- notify(message: string): void;
419
- draft(): string;
420
- shutdown(): void;
421
- }
422
-
423
- /** Call a method on a harness object by name; undefined when it is not a function. */
424
- function call(obj: Record<string, unknown>, key: string, args: unknown[] = []): unknown {
425
- const fn = obj[key];
426
- return typeof fn === "function" ? Reflect.apply(fn, obj, args) : undefined;
427
- }
428
-
429
- function asRolloverCtx(v: unknown): RolloverCtx | null {
430
- const r = asRecord(v);
431
- const sm = asRecord(r.sessionManager);
432
- const sessionId = call(sm, "getSessionId");
433
- const sessionFile = call(sm, "getSessionFile");
434
- if (typeof sessionId !== "string" || typeof sessionFile !== "string") return null;
435
- return {
436
- sessionId,
437
- sessionFile,
438
- runningJobs: () => {
439
- const running = asRecord(call(r, "getAsyncJobSnapshot")).running;
440
- return Array.isArray(running) ? running.map(j => asString(asRecord(j).label, "job")) : [];
441
- },
442
- waitForIdle: () => call(r, "waitForIdle"),
443
- newSession: opts => call(r, "newSession", [opts]),
444
- notify: message => call(asRecord(r.ui), "notify", [message]),
445
- draft: () => {
446
- const text = call(asRecord(r.ui), "getEditorText");
447
- return typeof text === "string" ? text : "";
448
- },
449
- shutdown: () => {
450
- call(r, "shutdown");
451
- },
452
- };
453
- }
454
-
455
- function isMain(ctx: unknown): boolean {
456
- const c = asCtx(ctx);
457
- return !c.hasAgent || c.kind === "main";
458
- }
459
-
460
229
  // Owner topics (plan P8): one detached, niced `recall` child, as the limit probe is. The child env drops
461
230
  // MAIN_ENV so the child is not Main. Its stdout and stderr append to owner-topics.log (stats and `topics: fail`
462
231
  // lines only). A context that injects `spawnTopics` (tests) gets the call instead.
@@ -469,8 +238,8 @@ function spawnTopics(cfg: Config, ctx: unknown, args: string[]): void {
469
238
  }
470
239
  let out: number | undefined;
471
240
  try {
472
- mkdirSync(ownerLogDir(), { recursive: true, mode: 0o700 });
473
- out = openSync(topicsLogFile(), "a", 0o600);
241
+ mkdirSync(ownerLogDir(cfg.paths), { recursive: true, mode: 0o700 });
242
+ out = openSync(topicsLogFile(cfg.paths), "a", 0o600);
474
243
  const child = spawn("nice", ["-n", "19", "bun", join(import.meta.dir, "../../cli/main.ts"), ...args], { detached: true, stdio: ["ignore", out, out], env });
475
244
  child.on("error", err => adapterLog(cfg, `OWNER-TOPICS: could not start: ${err.message}`));
476
245
  child.unref();
@@ -481,206 +250,8 @@ function spawnTopics(cfg: Config, ctx: unknown, args: string[]): void {
481
250
  }
482
251
  }
483
252
 
484
- function mtimeOf(path: string): number | null {
485
- try {
486
- return statSync(path).mtimeMs;
487
- } catch {
488
- return null;
489
- }
490
- }
491
-
492
- function sizeOf(path: string): number {
493
- try {
494
- return statSync(path).size;
495
- } catch {
496
- return 0;
497
- }
498
- }
499
-
500
- // ---- owner inbox delivery (plan 20261024_2230 P3b) ----
501
- // The phone page appends answers to <queue_state>/owner-inbox.jsonl — a protected state file, so
502
- // no agent can forge an owner answer (guards refuse the write). Main's session delivers each
503
- // record once as a user message (pi.sendUserMessage, no options: idle → a new turn, streaming →
504
- // the steer queue), at turn end and on a 15 s timer while idle. The consumed-row count lives in
505
- // <queue_state>/owner-inbox.cursor; subagent sessions never deliver and never move it.
506
-
507
- /** Idle-poll interval for the owner inbox. */
508
- export const OWNER_INBOX_POLL_MS = 15_000;
509
- /** How often the adapter heartbeats every claim this Main holds (plan 20261027_1300 P3). */
510
- export const CLAIM_BEAT_MS = 60_000;
511
-
512
- /** The delivered cursor: how many owner-inbox rows this Main's session has consumed (P5: one file per Main, under its mainStateDir). */
513
- export function ownerInboxCursorPath(cfg?: Config): string {
514
- return `${mainStateDir(cfg)}/inbox-cursor`;
515
- }
516
-
517
- /** Rows this Main starts past when it has never delivered (P5): set at adapter creation so a Main that registers late does not replay old rows. null = adopt the file or 0. */
518
- let inboxFloor: number | null = null;
519
-
520
- function readOwnerInboxCursor(cfg: Config): number {
521
- try {
522
- const n = Number(readFileSync(ownerInboxCursorPath(cfg), "utf8").trim());
523
- return Number.isInteger(n) && n >= 0 ? n : inboxFloor ?? 0;
524
- } catch {
525
- return inboxFloor ?? 0;
526
- }
527
- }
528
-
529
- function writeOwnerInboxCursor(cfg: Config, n: number): void {
530
- try {
531
- mkdirSync(mainStateDir(cfg), { recursive: true });
532
- writeFileSync(ownerInboxCursorPath(cfg), `${n}\n`);
533
- } catch {}
534
- }
535
-
536
- /** The user message one inbox record becomes, or null when the record is not one Main can act on.
537
- * Records without `kind` are page answers (the original shape). */
538
- export function ownerInboxMessage(rec: Record<string, unknown>): string | ({ type: "text"; text: string } | { type: "image"; data: string; mimeType: string })[] | null {
539
- const kind = rec.kind === undefined ? "answer" : asString(rec.kind);
540
- const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null);
541
- switch (kind) {
542
- case "answer": {
543
- const plan = asString(rec.plan);
544
- const question = asString(rec.question);
545
- const answer = asString(rec.answer);
546
- if (!plan || !question || !answer) return null;
547
- return `Owner answered on the phone page — ${basename(plan)}: ${question} → ${answer}`;
548
- }
549
- case "unlock": {
550
- const minutes = num(rec.minutes);
551
- const until = num(rec.until);
552
- if (minutes === null || until === null) return null;
553
- return `Owner unlocked the guards from the phone page for ${minutes} min (until ${strftime(until, "%H:%M")}). Do the step that waited on the unlock now.`;
554
- }
555
- case "lock":
556
- return "Owner locked the guards from the phone page.";
557
- case "approval": {
558
- const page = asString(rec.page);
559
- const plan = asString(rec.plan);
560
- if (page === "" || plan === "") return null;
561
- return `Owner approved ${basename(plan)} on page ${page}.`;
562
- }
563
- case "reorder": {
564
- const plan = asString(rec.plan);
565
- const from = num(rec.from);
566
- const to = num(rec.to);
567
- if (!plan || from === null || to === null) return null;
568
- return `Owner moved ${basename(plan)} from #${from} to #${to} on the phone page; INDEX.md has the new order — work by it.`;
569
- }
570
- case "message": {
571
- const ts = num(rec.ts);
572
- const id = asString(rec.id);
573
- if (ts === null || !/^[0-9]+-[0-9a-f]{6}$/.test(id)) return null;
574
- const at = strftime(ts, "%H:%M");
575
- const dir = join(q.stateDirPath(), "owner-messages", id);
576
- let message: Record<string, unknown>;
577
- try {
578
- message = JSON.parse(readFileSync(join(dir, "message.json"), "utf8")) as Record<string, unknown>;
579
- } catch {
580
- return [{ type: "text", text: `Owner sent a message from the phone page at ${at}; it expired (12 h) before delivery.` }];
581
- }
582
- const text = asString(message.text);
583
- const names = Array.isArray(message.images) ? message.images.filter((name): name is string => typeof name === "string" && /^[1-4]\.(png|jpg|gif|webp)$/.test(name)) : [];
584
- const parts: ({ type: "text"; text: string } | { type: "image"; data: string; mimeType: string })[] = [];
585
- const paths = names.map(name => join(dir, name));
586
- parts.push({
587
- type: "text",
588
- text: `Owner message from the phone page (${at}): ${text}${paths.length ? `\nImages:\n${paths.map(path => `- ${path}`).join("\n")}` : ""}`,
589
- });
590
- for (const name of names) {
591
- const ext = name.slice(name.lastIndexOf(".") + 1);
592
- const mimeType = ext === "jpg" ? "image/jpeg" : `image/${ext}`;
593
- try {
594
- parts.push({ type: "image", data: readFileSync(join(dir, name)).toString("base64"), mimeType });
595
- } catch {
596
- return [{ type: "text", text: `Owner sent a message from the phone page at ${at}; it expired (12 h) before delivery.` }];
597
- }
598
- }
599
- return parts;
600
- }
601
- case "page-note": {
602
- // One row per note the owner left on a published page (plan 20261026 P6).
603
- const page = asString(rec.page);
604
- const quote = asString(rec.quote);
605
- const note = asString(rec.note);
606
- if (!page || !note) return null;
607
- const id = asString(rec.id);
608
- const url = asString(rec.url);
609
- const where = `Owner note on the page ${page}${id ? ` (${id})` : ""}${url ? ` — ${url}` : ""}: `;
610
- return quote ? `${where}on "${quote}" → ${note}` : `${where}${note}`;
611
- }
612
- default:
613
- return null;
614
- }
615
- }
616
-
617
- /** The JSONL rows after `cursor` (a row count), as records, plus the new cursor. A torn last row
618
- * (a page write that has not landed completely) stays unconsumed; a malformed complete row is
619
- * consumed but skipped, so one bad line cannot wedge delivery. */
620
- export function pendingInboxRecords(text: string, cursor: number): { records: Record<string, unknown>[]; next: number } {
621
- const endsClean = text === "" || text.endsWith("\n");
622
- const rows = text.split("\n");
623
- if (rows.length && rows[rows.length - 1] === "") rows.pop();
624
- const records: Record<string, unknown>[] = [];
625
- let next = Math.min(cursor, rows.length);
626
- for (let i = cursor; i < rows.length; i++) {
627
- const torn = i === rows.length - 1 && !endsClean;
628
- try {
629
- const rec: unknown = JSON.parse((rows[i] ?? "").trim());
630
- if (rec !== null && typeof rec === "object" && !Array.isArray(rec)) records.push(rec as Record<string, unknown>);
631
- } catch {}
632
- if (!torn) next = i + 1;
633
- }
634
- return { records, next };
635
- }
636
-
637
- /** Deliver every inbox row past the cursor once, as a user message to Main; then store the cursor.
638
- * Synchronous, so the turn-end path and the idle timer cannot interleave. */
639
- export function deliverOwnerInbox(pi: ExtensionHost, cfg: Config): void {
640
- let text: string;
641
- try {
642
- text = readFileSync(inboxPath(), "utf8");
643
- } catch {
644
- return; // no inbox yet: nothing to deliver
645
- }
646
- const cursor = readOwnerInboxCursor(cfg);
647
- const { records, next } = pendingInboxRecords(text, cursor);
648
- if (next === cursor) return;
649
- let delivered = 0;
650
- for (const rec of records) {
651
- // P5: a row addressed to another Main (`to` set and not this Main's id) is consumed but not delivered here.
652
- if (typeof rec.to === "string" && rec.to !== "" && rec.to !== mainId()) continue;
653
- const msg = ownerInboxMessage(rec);
654
- if (msg === null) continue;
655
- pi.sendUserMessage(msg);
656
- delivered++;
657
- }
658
- writeOwnerInboxCursor(cfg, next);
659
- adapterLog(cfg, `owner inbox: delivered ${delivered} answer(s) (cursor ${cursor} → ${next})`);
660
- }
661
-
662
253
  /** The most recently registered createOmpAdapter cleanup, for the exported reset(). */
663
254
  let activeAdapterReset: (() => void) | null = null;
664
- /** Pressure alert tick (plan 20261026_0100 P2): classifies one sample, runs the transition, and tells Main on a RED or GREEN fire. The state lives in <queue_state>/pressure.json and is rewritten only when it changes, so a reloaded session does not re-fire. */
665
- export function pressureTick(pi: ExtensionHost, cfg: Config, sample: PressureSample, now: number): void {
666
- const file = join(cfg.paths.queue_state, "pressure.json");
667
- let prev: PressureState | null = null;
668
- try {
669
- prev = JSON.parse(readFileSync(file, "utf8")) as PressureState;
670
- } catch {}
671
- const level = pressureLevel(sample, cfg);
672
- const r = pressureTransition(prev, level, now, cfg);
673
- const next = JSON.stringify(r.state);
674
- if (next !== JSON.stringify(prev)) {
675
- try {
676
- mkdirSync(cfg.paths.queue_state, { recursive: true });
677
- writeFileSync(file, next);
678
- } catch {}
679
- }
680
- if (r.fire === "red") {
681
- pi.sendUserMessage(pressureMessage("red", sample, currentHolder(cfg, now)));
682
- } else if (r.fire === "green") pi.sendUserMessage(pressureMessage("green", sample, null));
683
- }
684
255
 
685
256
  /** This process's held Main session lock (plan 20261103_1146 P2): the first main session_start
686
257
  * locks `<queue_state>/mains/<id>/session.lock` for the process lifetime — the kernel frees it
@@ -688,54 +259,30 @@ export function pressureTick(pi: ExtensionHost, cfg: Config, sample: PressureSam
688
259
  * process take the id, and a new flock of the same file in this process is busy. reset() is the
689
260
  * only release, so tests do not leak the flock into the next file. */
690
261
  let heldSessionLock: HeldLock | null = null;
691
- /** The limit tick: one check of the open episode every 30 s (plan 20261027_1500 P3). */
692
- const LIMIT_TICK_MS = 30_000;
693
- /** The probe's command line and env. Never process.execPath: inside the harness that is the omp
694
- * binary, so the child was a full Main session (2026-11-03: stray Mains). bun comes from PATH, as
695
- * every bin's `#!/usr/bin/env bun` shebang does; the child env drops MAIN_ENV. */
696
- export function limitProbeSpawn(env: NodeJS.ProcessEnv = process.env): { cmd: string; args: string[]; env: NodeJS.ProcessEnv } {
697
- const { [MAIN_ENV]: _main, ...rest } = env;
698
- return { cmd: "nice", args: ["-n", "19", "bun", join(import.meta.dir, "../../cli/limit-probe.ts")], env: rest };
699
- }
700
- /** One limit probe as a niced child (cli/limit-probe.ts). It writes the episode state itself;
701
- * a failed start is logged and the next tick tries again. */
702
- function spawnLimitProbeChild(cfg: Config): void {
703
- const p = limitProbeSpawn();
704
- const child = spawn(p.cmd, p.args, { detached: true, stdio: "ignore", env: p.env });
705
- child.on("error", err => adapterLog(cfg, `RATE-LIMIT probe: could not start: ${err.message}`));
706
- child.unref();
707
- }
262
+
708
263
  /** Register the guard handlers on one extension host. `initial` is injectable for tests; `freshConfig` re-reads the config per guarded call. */
709
- export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig: () => Config = () => initial): void {
264
+ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig: () => Config = () => initial, opts: OmpAdapterOptions = {}): void {
710
265
  // Guarded handlers take `cfg = freshConfig()` first, so an edited config.yml reaches the next call (P4e).
711
266
  let cfg = initial;
712
- // The queue library resolves its paths from env snapshots; point them at this config first.
713
- applyQueueEnv(cfg);
714
267
  // P2 d: the first seam — a mode fact another writer left behind is reverted before any handler runs.
715
268
  cfg = freshPlannerConfig(freshConfig);
716
- // P5: seed the per-Main inbox floor once — a Main that has never delivered starts past rows
717
- // that predate its registration; the pre-multi-main cursor file belongs to the default id's
718
- // first start. Later reads/writes own the file, so the floor is only a creation-time default.
719
- try {
720
- if (!existsSync(ownerInboxCursorPath(cfg))) {
721
- mkdirSync(mainStateDir(cfg), { recursive: true });
722
- if (mainId() === "main") {
723
- try {
724
- renameSync(`${q.stateDirPath()}/owner-inbox.cursor`, ownerInboxCursorPath(cfg));
725
- } catch {}
726
- }
727
- if (!existsSync(ownerInboxCursorPath(cfg))) {
728
- try {
729
- inboxFloor = pendingInboxRecords(readFileSync(inboxPath(), "utf8"), 0).next;
730
- } catch {
731
- inboxFloor = 0;
732
- }
733
- }
734
- }
735
- } catch {}
269
+ const getCfg = (): Config => cfg;
270
+ seedInboxFloor(cfg);
736
271
  // Main's rules ride its system prompt each turn; they are never written into the owner's AGENTS.md.
737
272
  const mainRules = renderBlock(cfg);
738
273
 
274
+ const rateLimit = createRateLimitController(pi, getCfg);
275
+ const rollover = createRolloverController(pi, getCfg, { doctor: opts.doctor });
276
+
277
+ // Clear the previous adapter's armed grace timer before this one overwrites the pointer (P3c).
278
+ // Do not release heldSessionLock: this runs on every factory re-entry, and the lock is
279
+ // process-lifetime (plan 20261103_1146 P4). reset() still releases it.
280
+ activeAdapterReset?.();
281
+ activeAdapterReset = (): void => {
282
+ rollover.clearState();
283
+ rateLimit.stopTick();
284
+ };
285
+
739
286
  let callsSinceStop = 0;
740
287
  let idleStops = 0;
741
288
  let timer: unknown;
@@ -755,26 +302,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
755
302
  // emits (sessionStopWillContinue) consumes it and posts nothing — a blocked stop's reply is a
756
303
  // mid-work report, never a hand-back.
757
304
  let stopBlocked = false;
758
- // Rate-limit probe loop (plan 20261027_1500 P3). A limited turn end opens one episode in
759
- // main-limit.json: a named reset is waited for; otherwise a niced probe child runs every
760
- // probe_interval_s until one gets through or max_probes is spent. ONE tick (LIMIT_TICK_MS)
761
- // reads the episode: it spawns a due probe, or, once the provider is back, sends Main ONE new
762
- // turn. A new Main turn cancels the tick and keeps the episode (probe count kept); a turn that
763
- // ends without a limit clears it.
764
- let limitTickArmed = false;
765
- let limitTick: NodeJS.Timeout | null = null;
766
- const rateClock = (ms: number): string => strftime(ms / 1000, "%H:%M");
767
- const stopLimitTick = (): void => {
768
- limitTickArmed = false;
769
- if (limitTick !== null) {
770
- clearInterval(limitTick);
771
- limitTick = null;
772
- }
773
- };
774
- const disarmRateEpisode = (): void => {
775
- stopLimitTick();
776
- clearLimitState(cfg);
777
- };
305
+
778
306
  // P5b: a real turn end answers every owner message it followed — the answer (the turn's own
779
307
  // reply, the page's lastAnswerFor shape) rides the same owner-message store. Rate-limited,
780
308
  // blocked and mid-run ends are not turn ends: nothing is recorded.
@@ -786,74 +314,12 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
786
314
  adapterLog(cfg, `RECALL-LOG record failed: ${err instanceof Error ? err.message : String(err)}`);
787
315
  }
788
316
  try {
789
- appendOwnerAnswer(reply.text);
317
+ appendOwnerAnswer(reply.text, cfg.paths);
790
318
  } catch (err) {
791
319
  adapterLog(cfg, `OWNER-ANSWER record failed: ${err instanceof Error ? err.message : String(err)}`);
792
320
  }
793
321
  };
794
- const limitTickFire = (c: HostCtx): void => {
795
- if (!limitTickArmed) return;
796
- const state = readLimitState(cfg);
797
- if (state === null) {
798
- stopLimitTick();
799
- adapterLog(cfg, "RATE-LIMIT give up: episode state gone (max_probes spent or unreadable)");
800
- return;
801
- }
802
- const now = Date.now();
803
- if (state.back_at !== null) {
804
- if (now < state.back_at) return;
805
- stopLimitTick();
806
- clearLimitState(cfg);
807
- // P4: the finished episode is recorded once and the owner hears one back post; both are
808
- // times and counts only — the episode's last_error never reaches chat or ledger.
809
- appendMetric(cfg, limitMetric(state, now));
810
- adapterLog(cfg, `RATE-LIMIT back: provider limit over (back at ${rateClock(state.back_at)}); new turn sent`);
811
- void postReply(backPost(state), cfg).then(results => {
812
- for (const r of results) if (!r.posted) adapterLog(cfg, `notify: ${r.provider}: ${r.error}`);
813
- });
814
- pi.sendUserMessage(`main-guard: the provider limit is over (back at ${rateClock(state.back_at)}). Continue the queue where you stopped.`);
815
- return;
816
- }
817
- if (now < state.next_probe_at) return;
818
- (c.spawnLimitProbe ?? (() => spawnLimitProbeChild(cfg)))();
819
- };
820
- const armLimitTick = (c: HostCtx): void => {
821
- stopLimitTick();
822
- limitTickArmed = true;
823
- const t: unknown = c.setInterval ? c.setInterval(() => limitTickFire(c), LIMIT_TICK_MS) : setInterval(() => limitTickFire(c), LIMIT_TICK_MS);
824
- if (t && typeof t === "object" && "unref" in t && typeof t.unref === "function") t.unref();
825
- limitTick = t as NodeJS.Timeout;
826
- };
827
- // A turn that ended on a provider rate limit: the episode opens (or continues with its probe
828
- // count), the owner chat hears once per episode, and the tick takes over.
829
- const onRateLimitedStop = (c: HostCtx, namedResetMs: number | null, errorText: string, model: string): void => {
830
- const prev = readLimitState(cfg);
831
- const timing = timingOf(cfg);
832
- const state = onLimited(prev, namedResetMs, errorText, Date.now(), model, timing);
833
- try {
834
- writeLimitState(cfg, state);
835
- } catch (err) {
836
- adapterLog(cfg, `RATE-LIMIT state write failed: ${err instanceof Error ? err.message : String(err)}`);
837
- return;
838
- }
839
- adapterLog(cfg, `RATE-LIMIT stop: ${state.reset_named ? "named reset" : "probe"} at ${rateClock(state.next_probe_at)} (probes ${state.probes} of ${timing.max_probes})`);
840
- if (prev === null) {
841
- adapterLog(cfg, "notify: posted (rate-limit)");
842
- void postReply(limitedPost(state, timing.probe_interval_s), cfg).then(results => {
843
- for (const r of results) if (!r.posted) adapterLog(cfg, `notify: ${r.provider}: ${r.error}`);
844
- });
845
- }
846
- armLimitTick(c);
847
- };
848
- // The rate-limit decision for one turn end, from the event's own last assistant message. The
849
- // untilMs is the fallback wait recorded with PROVIDER-OUT when the error text names no reset.
850
- const rateLimitOf = (reply: EventReply | null): { untilMs: number } | null => {
851
- const rl = cfg.guards.rate_limit;
852
- const hit = rateLimited(reply?.stopReason ?? null, reply?.errorMessage ?? null, rl);
853
- if (!hit) return null;
854
- const waitMs = (hit.retryAfterMs ?? rl.probe_interval_s * 1000) + rl.slack_s * 1000;
855
- return { untilMs: Date.now() + waitMs };
856
- };
322
+
857
323
  // One guard-log line per notify decision: `notify: posted|skipped (<why>)`. Fire-and-forget:
858
324
  // the decision never awaits the post; a failed or slow post logs one line and never blocks
859
325
  // or retries.
@@ -901,9 +367,9 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
901
367
  // source the owner page lists). Keys are `plan file|waiting line`, remembered in
902
368
  // <queue_state>/notify-waiting.json; a key whose line is gone is dropped, so the same question
903
369
  // asked again later posts again. No waiting plans: no decision, no log line.
904
- const waitingKeysFile = join(cfg.paths.queue_state, "notify-waiting.json");
905
370
  const notifyWaitingPlans = (): void => {
906
- const waiting = q.activePlans(cfg.paths.queue_index).filter(p => p.waiting && p.status === "open" && p.waitingLine);
371
+ const waitingKeysFile = join(cfg.paths.queue_state, "notify-waiting.json");
372
+ const waiting = q.activePlans(cfg.paths).filter(p => p.waiting && p.status === "open" && p.waitingLine);
907
373
  let stored: string[] = [];
908
374
  try {
909
375
  const parsed: unknown = JSON.parse(readFileSync(waitingKeysFile, "utf8"));
@@ -1038,9 +504,9 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1038
504
  };
1039
505
  add(cwd);
1040
506
  if (cfg.guards.read_tools.includes(tool) && typeof input.path === "string") add(resolve(cwd, q.expandHome(input.path)));
1041
- for (const p of q.writeTargets(tool, input, cwd)) add(p);
507
+ for (const p of q.writeTargets(tool, input, cwd, cfg.paths)) add(p);
1042
508
  if (tool === "task") {
1043
- const plans = q.readIndex();
509
+ const plans = q.readIndex(cfg.paths.queue_index);
1044
510
  for (const t of Array.isArray(input.tasks) ? input.tasks : []) {
1045
511
  const plan = plans.find(file => String(asRecord(t).task ?? "").includes(file));
1046
512
  if (plan) add(plan);
@@ -1057,18 +523,15 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1057
523
  if (c.kind !== "sub") return undefined;
1058
524
  // A subagent's first turn is the only one carrying its brief, and the plan the brief
1059
525
  // names is the repo whose rules it needs — the same index match the plan gate makes.
1060
- const plans = q.readIndex();
526
+ const plans = q.readIndex(cfg.paths.queue_index);
1061
527
  const content = unhanded(asString(c.id) || "sub", plans.find(file => prompt.includes(file)) ?? null);
1062
528
  return content ? { message: { customType: "main-guard.rules", content, display: false } } : undefined;
1063
529
  }
1064
- if (limitTickArmed) {
1065
- stopLimitTick();
1066
- adapterLog(cfg, "RATE-LIMIT tick cancelled: owner message (probe count kept)");
1067
- }
530
+ rateLimit.onOwnerPrompt();
1068
531
  const d = checkInject({ inject: prompt, agent: "main" }, cfg);
1069
532
  callsSinceStop = d.state?.callsSinceStop ?? callsSinceStop;
1070
533
  idleStops = d.state?.idleStops ?? idleStops;
1071
- const notice = rolloverNotice(ctx);
534
+ const notice = rollover.notice(ctx);
1072
535
  // A turn the harness starts from the guard's own stop continuation is not an owner
1073
536
  // message: D4 (owner-correction) only sees real prompts; D1/D3 run either way.
1074
537
  // Machine prompts (guard continuation, rollover note request, handoff note) are not owner messages.
@@ -1099,8 +562,8 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1099
562
  cfg = freshPlannerConfig(freshConfig);
1100
563
  const agent = asString(asRecord(event).agent);
1101
564
  const kind = asString(asRecord(event).invocationKind);
1102
- if (!q.allowedAgents().has(agent))
1103
- return { block: true, reason: `main-guard: agent "${agent}" is not in "## Allowed" of ${q.SUBAGENTS_MD}.` };
565
+ if (!q.allowedAgents(cfg.paths.subagents).has(agent))
566
+ return { block: true, reason: `main-guard: agent "${agent}" is not in "## Allowed" of ${cfg.paths.subagents}.` };
1104
567
  if (kind !== "task")
1105
568
  return { block: true, reason: "main-guard: spawn implementers with the task tool (the plan gate checks its brief)." };
1106
569
  return undefined;
@@ -1124,7 +587,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1124
587
  const cwd = c.cwd ?? process.cwd();
1125
588
  // planner mode P2 (plan 20261102_1515): the plan a sub's approved spawn bound to it (the
1126
589
  // brief's `Planner role for <plan path>` line) — the gates check it against plan-path writes.
1127
- const plannerPlan = isSub ? plannerSpawnPlan(id) : null;
590
+ const plannerPlan = isSub ? plannerSpawnPlan(id, cfg.paths) : null;
1128
591
  const snap = new Map<string, string>();
1129
592
  snapshotPlans(tool, input, cwd, snap, !isSub, plannerPlan, cfg);
1130
593
  // Drain (src/core/rollover.ts): while a rollover is pending no new subagent starts; the
@@ -1137,7 +600,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1137
600
  const rc = lastMainRc;
1138
601
  runningJobs = rc?.runningJobs();
1139
602
  if (cfg.rollover.enabled && rc) {
1140
- const why = spawnRefusal(rolloverSnapshot(rc).state, runningJobs ?? []);
603
+ const why = spawnRefusal(rollover.snapshot(rc).state, runningJobs ?? []);
1141
604
  if (why) {
1142
605
  const tasks = Array.isArray(input.tasks) ? input.tasks : [];
1143
606
  adapterLog(cfg, `BLOCK spawn ${String(asRecord(tasks[0]).agent ?? "task")}: rollover pending`);
@@ -1168,7 +631,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1168
631
  if (snap.size) pending.set(asString(e.toolCallId), snap);
1169
632
  const wc = cfg.write_check;
1170
633
  if (wc.enabled && (wc.applies_to === "all" || isSub)) {
1171
- const ws = writeCheckSnapshot(tool, input, cwd, wc);
634
+ const ws = writeCheckSnapshot(tool, input, cwd, wc, cfg);
1172
635
  if (ws.size) pendingWrite.set(asString(e.toolCallId), ws);
1173
636
  }
1174
637
  // An allowed Main call inside a repo queues that repo's rules for the next prompt (P3).
@@ -1182,7 +645,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1182
645
  const trimProgress = (file: string): string | undefined => {
1183
646
  const t = q.trimPlanProgress(file, cfg.queue.progress_keep);
1184
647
  if (!t) return undefined;
1185
- rekeySpawnFile(file, t.before, t.after);
648
+ rekeySpawnFile(file, t.before, t.after, cfg.paths);
1186
649
  return `plan-guard: moved ${t.count} older Progress entries to ${t.archive}; re-read the plan before editing it again.`;
1187
650
  };
1188
651
 
@@ -1194,7 +657,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1194
657
  const steer = ownerAnswerSteer(cfg, nowSec());
1195
658
  if (steer) pi.sendUserMessage(steer);
1196
659
  }
1197
- onSizeCheck("tool_result", event, ctx);
660
+ rollover.onSizeCheck("tool_result", event, ctx);
1198
661
  const e = asRecord(event);
1199
662
  const c = asCtx(ctx);
1200
663
  const id = asString(e.toolCallId);
@@ -1240,7 +703,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1240
703
  } catch {}
1241
704
  if (d.note) notes.push(d.note);
1242
705
  }
1243
- if (d.allow && (!c.hasAgent || c.kind === "main") && q.doneCount(after) > q.doneCount(before) && q.planAt(file, q.activePlans())) {
706
+ if (d.allow && (!c.hasAgent || c.kind === "main") && q.doneCount(after) > q.doneCount(before) && q.planAt(file, q.activePlans(cfg.paths))) {
1244
707
  const note = trimProgress(file);
1245
708
  if (note) notes.push(note);
1246
709
  }
@@ -1287,7 +750,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1287
750
  }
1288
751
  if ((!c.hasAgent || c.kind === "main") && !e.isError) {
1289
752
  const text = content.map(p => asString(asRecord(p).text)).join("\n");
1290
- recordMainResult(asString(e.toolName), asRecord(e.input), c.cwd ?? process.cwd(), text);
753
+ recordMainResult(asString(e.toolName), asRecord(e.input), c.cwd ?? process.cwd(), text, cfg.paths);
1291
754
  // After the reads are recorded: a fresh hit clears its own warning, a stale list warns
1292
755
  // before Main drafts an edit the plan-read guard would refuse (I-20261025-208 P3).
1293
756
  const readNote = planReadNote(asString(e.toolName), asRecord(e.input), c.cwd ?? process.cwd(), text, cfg);
@@ -1311,7 +774,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1311
774
  const c = asCtx(ctx);
1312
775
  if (c.hasAgent && c.kind !== "main") return;
1313
776
  // A relaunch is requested: omp shuts down at the next idle, so the stop must not be continued.
1314
- if (relaunched) {
777
+ if (rollover.isRelaunched()) {
1315
778
  adapterLog(cfg, "notify: skipped (relaunch requested)");
1316
779
  return undefined;
1317
780
  }
@@ -1324,7 +787,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1324
787
  // A turn that ended on a provider rate limit waits it out (plan 20261025_0640): ALLOW before
1325
788
  // the rollover and queue decisions — any block here would re-ask straight into the limit —
1326
789
  // and without touching the idle-stop counters: checkStop is not consulted.
1327
- const rl = rateLimitOf(reply);
790
+ const rl = rateLimit.rateLimitOf(reply);
1328
791
  if (rl) {
1329
792
  // Who is rate-limited is live data (plan 20261025_1700 P1): the error text's own reset
1330
793
  // time, else the fallback wait. Best effort — a failed write never changes the stop.
@@ -1334,28 +797,28 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1334
797
  } catch (err) {
1335
798
  adapterLog(cfg, `PROVIDER-OUT record failed: ${err instanceof Error ? err.message : String(err)}`);
1336
799
  }
1337
- onRateLimitedStop(c, named, reply?.errorMessage ?? "", reply?.model ?? "");
800
+ rateLimit.onRateLimitedStop(c, named, reply?.errorMessage ?? "", reply?.model ?? "");
1338
801
  return undefined;
1339
802
  }
1340
803
  // Any turn that ends without a rate limit ends the episode and disarms its resume timer.
1341
- disarmRateEpisode();
804
+ rateLimit.disarmEpisode();
1342
805
  // A pending rollover decides the stop and checkStop is not consulted: its queue, incident and cancel
1343
806
  // blocks would hold Main at a wait the new session raises again through main-start, and its "spawn an
1344
807
  // agent" text is refused while the rollover is pending.
1345
808
  const rc = cfg.rollover.enabled ? asRolloverCtx(ctx) : null;
1346
809
  if (rc) {
1347
- const snap = rolloverSnapshot(rc);
810
+ const snap = rollover.snapshot(rc);
1348
811
  if (snap.state === "need-note") {
1349
812
  adapterLog(cfg, "BLOCK stop: rollover need-note");
1350
813
  notifyHandback(reply, "blocked session_stop");
1351
814
  stopBlocked = true;
1352
- return { decision: "block", reason: noteRequestFor(rc, snap) };
815
+ return { decision: "block", reason: rollover.noteRequestFor(rc, snap) };
1353
816
  }
1354
817
  if (snap.state === "ready" || snap.state === "wait-jobs") {
1355
818
  adapterLog(cfg, `ALLOW stop: rollover ${snap.state}`);
1356
819
  recordTurnAnswer(reply);
1357
820
  // Under the launcher a ready rollover starts now (not a hand-back to the owner).
1358
- const handsToOwner = !(snap.state === "ready" && requestRelaunch(rc, notePath(rc.sessionId)));
821
+ const handsToOwner = !(snap.state === "ready" && rollover.requestRelaunch(rc, notePath(rc.sessionId, mainStateDir(cfg))));
1359
822
  if (handsToOwner) notifyHandback(reply, "allowed session_stop");
1360
823
  else adapterLog(cfg, "notify: skipped (relaunch requested)");
1361
824
  return undefined;
@@ -1374,218 +837,17 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1374
837
  return { decision: "block", reason: d.reason };
1375
838
  });
1376
839
 
1377
- // Session rollover (src/core/rollover.ts). Main's session size decides when a handoff note is
1378
- // asked for at turn end (a sendMessage that triggers Main's next turn). The owner's next message
1379
- // then starts a fresh session from that note; under `neurastream main` the launcher starts it at
1380
- // once. The size and the installed version are re-read at every turn end and tool result; the
1381
- // note request goes out once per session file and note state.
1382
- // The version this process loaded at start: the plugin code that is actually running.
1383
- const loadedVersion = packageVersion(packageJsonPath());
1384
- let crossed: { file: string; atMs: number } | null = null;
1385
- // The note request already sent, keyed by session file + note mtime at send time ("none" when
1386
- // no note exists): a note that expires while jobs run falls back to need-note with a key no
1387
- // request was sent for, so it gets exactly one new request and never a loop.
1388
- let asked: string | null = null;
1389
- let waitNoticeMs = 0;
1390
-
1391
- const rolloverSnapshot = (c: RolloverCtx): { state: RolloverState; noteMtimeMs: number | null; stale: boolean; liveVersion: string | null } => {
1392
- const nowMs = Date.now();
1393
- const bytes = sizeOf(c.sessionFile);
1394
- const maxMb = cfg.rollover.max_session_mb;
1395
- const noteMtimeMs = mtimeOf(notePath(c.sessionId));
1396
- const liveVersion = packageVersion(packageJsonPath());
1397
- const stale = liveVersion === null || loadedVersion === null || liveVersion !== loadedVersion;
1398
- if (stale) {
1399
- // Note freshness is measured against the crossing: a stale session counts as crossed
1400
- // from the first check that saw it, whatever its size.
1401
- if (crossed?.file !== c.sessionFile) crossed = { file: c.sessionFile, atMs: nowMs };
1402
- } else if (bytes < maxMb * 1024 * 1024) crossed = null;
1403
- else if (crossed?.file !== c.sessionFile) crossed = { file: c.sessionFile, atMs: nowMs };
1404
- return {
1405
- state: rolloverState({
1406
- sessionBytes: bytes,
1407
- maxMb,
1408
- runningJobs: c.runningJobs(),
1409
- crossedAtMs: crossed?.atMs ?? null,
1410
- noteMtimeMs,
1411
- nowMs,
1412
- stale,
1413
- }),
1414
- noteMtimeMs,
1415
- stale,
1416
- liveVersion,
1417
- };
1418
- };
1419
-
1420
- // The note request for a state. A stale install names both versions in place of the size line.
1421
- const noteRequestFor = (c: RolloverCtx, snap: { stale: boolean; liveVersion: string | null }): string => {
1422
- const reason = snap.stale ? `neurastream on disk is ${snap.liveVersion ?? "unknown"}, this session runs ${loadedVersion ?? "unknown"}` : undefined;
1423
- return noteRequest(notePath(c.sessionId), reason);
1424
- };
1425
-
1426
- let relaunched = false;
1427
- // omp 18.11.1 defers an extension shutdown: it re-checks only when shutdown() is called again or
1428
- // an owner submission finishes, so a refused exit once left a dead UI that swallowed every owner
1429
- // message (I-20261024-4). One unref'd timer per request: if omp still has not exited
1430
- // rollover.exit_grace_s after the request, the adapter rolls over in-process. The timer keeps its
1431
- // own clearer: session_shutdown cancels the fallback when omp really exits.
1432
- let clearGrace: (() => void) | null = null;
1433
- const armGraceTimer = (c: RolloverCtx): void => {
1434
- clearGrace?.();
1435
- const t = setTimeout(() => {
1436
- clearGrace = null;
1437
- exitGraceElapsed(c);
1438
- }, cfg.rollover.exit_grace_s * 1000);
1439
- if (t && typeof t === "object" && "unref" in t && typeof t.unref === "function") t.unref();
1440
- clearGrace = () => {
1441
- clearTimeout(t);
1442
- clearGrace = null;
1443
- };
1444
- };
1445
-
1446
- // One in-process rollover at a time: while it waits for idle, the size check must not start
1447
- // a relaunch over it.
1448
- let flight: string[] | null = null;
1449
-
1450
- // The one in-process rollover, the exit-grace fallback: gather the generated state, wait for
1451
- // idle, then start a fresh session whose first message is the handoff. A state change during
1452
- // the wait sends the owner's text to this session as an ordinary message.
1453
- const rolloverInProcess = async (c: RolloverCtx, owner: string[], notice: string): Promise<void> => {
1454
- const previous = c.sessionFile;
1455
- const path = notePath(c.sessionId);
1456
- flight = owner;
1457
- try {
1458
- c.notify(notice);
1459
- const generated = [
1460
- await mainStartText([], cfg, { inheritStdin: false }, { source: defaultRunSource(cfg), results: defaultCompletedResults(cfg), providers: ompProviders(cfg) }),
1461
- holdsBlock(q.ownerHolds()),
1462
- ].join("\n");
1463
- const note = readFileSync(path, "utf8");
1464
- adapterLog(cfg, `rollover: new session from ${previous}; note ${path}`);
1465
- await c.waitForIdle();
1466
- const again = rolloverSnapshot(c).state;
1467
- if (relaunched || again !== "ready") {
1468
- c.notify(`main-rollover: the state changed while waiting for idle (${relaunched ? "relaunch requested" : again}); no new session.`);
1469
- // The owner's text is not lost: it goes to this session as an ordinary message.
1470
- const pending = owner.filter(s => s !== "").join("\n");
1471
- if (pending !== "") pi.sendUserMessage(pending);
1472
- return;
1473
- }
1474
- const r = asRecord(await c.newSession({ parentSession: previous }));
1475
- if (r.cancelled === true) return;
1476
- // Read after the await: owner messages that arrived during newSession are part of the handoff.
1477
- const handoff = buildHandoff({
1478
- generated,
1479
- note,
1480
- previousSessionFile: previous,
1481
- ownerMessage: owner.filter(s => s !== "").join("\n"),
1482
- unanswered: unansweredOwnerMessages(readOwnerMessages(), readOwnerAnswers()),
1483
- });
1484
- pi.sendUserMessage(handoff);
1485
- } finally {
1486
- flight = null;
1487
- }
1488
- };
1489
-
1490
- // Clear the rollover episode state so a later createOmpAdapter setup in the same
1491
- // process starts clean: a stale armGraceTimer would otherwise fire with this
1492
- // closure's cfg and recreate torn-down dirs (P3c).
1493
- const clearRolloverState = (): void => {
1494
- clearGrace?.();
1495
- relaunched = false;
1496
- flight = null;
1497
- };
1498
- // Clear the previous adapter's armed grace timer before this one overwrites the pointer (P3c).
1499
- // Do not release heldSessionLock: this runs on every factory re-entry, and the lock is
1500
- // process-lifetime (plan 20261103_1146 P4). reset() still releases it.
1501
- activeAdapterReset?.();
1502
- activeAdapterReset = (): void => {
1503
- clearRolloverState();
1504
- stopLimitTick();
1505
- };
1506
- // The launcher restarts omp: the request file carries the note and the editor draft, and omp
1507
- // shuts down only after the file is written. A failed write keeps the session running.
1508
- // Returns whether the request was written.
1509
- const requestRelaunch = (c: RolloverCtx, note: string, draft = c.draft()): boolean => {
1510
- try {
1511
- mkdirSync(dirname(relaunchPath()), { recursive: true });
1512
- writeFileSync(relaunchPath(), `${JSON.stringify({ previousSessionFile: c.sessionFile, notePath: note, draft })}\n`);
1513
- } catch (err) {
1514
- adapterLog(cfg, `rollover: relaunch request not written: ${String(err)}`);
1515
- return false;
1516
- }
1517
- relaunched = true;
1518
- adapterLog(cfg, `rollover: relaunch requested from ${c.sessionFile}`);
1519
- c.shutdown();
1520
- armGraceTimer(c);
1521
- return true;
1522
- };
1523
-
1524
- // An owner message typed while the relaunch is pending joins the request's draft, in order; the
1525
- // launcher's handoff carries it. The rewrite is atomic, so the launcher never reads a partial file.
1526
- const appendToRelaunch = (text: string): boolean => {
1527
- try {
1528
- const req = asRecord(JSON.parse(readFileSync(relaunchPath(), "utf8")));
1529
- const draft = [asString(req.draft), text].filter(s => s !== "").join("\n");
1530
- const tmp = `${relaunchPath()}.tmp`;
1531
- writeFileSync(tmp, `${JSON.stringify({ ...req, draft })}\n`);
1532
- renameSync(tmp, relaunchPath());
1533
- return true;
1534
- } catch (err) {
1535
- adapterLog(cfg, `rollover: owner message not added to the relaunch request: ${String(err)}`);
1536
- return false;
1537
- }
1538
- };
840
+ // ---- ordered agent_end pipeline (consolidates all 7 turn-end stages in exact sequence) ----
1539
841
 
1540
- // The grace elapsed without a session_shutdown: omp refused the exit. Read the request's draft,
1541
- // drop the request and roll over here, so the owner's messages reach a live session instead of a
1542
- // dead UI. The owner-away text stands in when nothing was typed.
1543
- const exitGraceElapsed = (c: RolloverCtx): void => {
1544
- adapterLog(cfg, `rollover: omp did not exit within ${cfg.rollover.exit_grace_s}s; rolling over in-process`);
1545
- let draft = "";
1546
- try {
1547
- draft = asString(asRecord(JSON.parse(readFileSync(relaunchPath(), "utf8"))).draft);
1548
- } catch {}
1549
- rmSync(relaunchPath(), { force: true });
1550
- relaunched = false;
1551
- rolloverInProcess(c, [draft.trim() === "" ? OWNER_AWAY : draft], "rollover: omp did not restart; continuing in a new session here").catch((err: unknown) => {
1552
- adapterLog(cfg, `rollover: in-process rollover failed: ${err instanceof Error ? err.message : String(err)}`);
1553
- });
1554
- };
1555
-
1556
- const onSizeCheck = (kind: "tool_result" | "agent_end", e: unknown, ctx: unknown): void => {
1557
- const c = asRolloverCtx(ctx);
1558
- if (!cfg.rollover.enabled || !c || !isMain(ctx)) return;
1559
- const snap = rolloverSnapshot(c);
1560
- const key = `${c.sessionFile}:${snap.noteMtimeMs ?? "none"}`;
1561
- // A terminal run end: omp 18.11.1 sets willContinue on a non-terminal agent_end.
1562
- const terminal = kind === "agent_end" && asRecord(e).willContinue !== true;
1563
- if (snap.state === "need-note" && asked !== key) {
1564
- asked = key;
1565
- pi.sendMessage(
1566
- { customType: "main-guard.rollover", content: noteRequestFor(c, snap), display: false },
1567
- { triggerTurn: true, deliverAs: "nextTurn" },
1568
- );
1569
- } else if (terminal && snap.state === "ready" && !relaunched && flight === null) {
1570
- // flight !== null: an in-process rollover (the fallback) owns this session's end.
1571
- requestRelaunch(c, notePath(c.sessionId));
1572
- } else if (terminal && relaunched) {
1573
- // A tool result mid-run never restarts the session (I-20261024-4), and omp's interactive
1574
- // mode re-runs its deferred exit check only when shutdown() is called again: re-arm at
1575
- // every later terminal run end instead of waiting for an owner message.
1576
- c.shutdown();
1577
- }
1578
- };
1579
- pi.on("agent_end", (e, ctx) => onSizeCheck("agent_end", e, ctx));
1580
- // Hand-back without a session_stop (plan 20261025_0130): while an async job is pending omp
1581
- // fires agent_end with willContinue:true and SKIPS session_stop — this deferred hand-back
842
+ // Stage 2: Hand-back without a session_stop (plan 20261025_0130): while an async job is pending
843
+ // omp fires agent_end with willContinue:true and SKIPS session_stop — this deferred hand-back
1582
844
  // posts from the event's own messages. omp also sets willContinue after a BLOCKED stop
1583
845
  // (sessionStopWillContinue) and for todo/plan-mode/rewind continuations, so a post here needs
1584
846
  // both: no blocked stop just decided (the flag), and an async job really pending. A terminal
1585
847
  // end (willContinue unset) is not a hand-back: the session_stop that follows it decides. A
1586
848
  // mid-run continuation — tool calls, or a non-"stop" reason such as an auto-retry — posts
1587
849
  // nothing.
1588
- pi.on("agent_end", (e, ctx) => {
850
+ const onDeferredHandback = (e: unknown, ctx: unknown): void => {
1589
851
  if (!isMain(ctx)) return;
1590
852
  if (asRecord(e).willContinue !== true) return;
1591
853
  if (stopBlocked) {
@@ -1598,7 +860,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1598
860
  // hand-back opens the episode instead of logging "no reply text" — its reply carries an
1599
861
  // error, no text. A mid-run continuation (tool calls, auto-retry) is not a turn end: the
1600
862
  // episode state stays as it is.
1601
- const rl = rateLimitOf(reply);
863
+ const rl = rateLimit.rateLimitOf(reply);
1602
864
  if (rl) {
1603
865
  // The same one parse as session_stop (plan 20261027_1500 P1/P3): the error text's own
1604
866
  // reset time, else the fallback wait. Best effort — a failed write never changes the stop.
@@ -1608,7 +870,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1608
870
  } catch (err) {
1609
871
  adapterLog(cfg, `PROVIDER-OUT record failed: ${err instanceof Error ? err.message : String(err)}`);
1610
872
  }
1611
- onRateLimitedStop(asCtx(ctx), named, reply?.errorMessage ?? "", reply?.model ?? "");
873
+ rateLimit.onRateLimitedStop(asCtx(ctx), named, reply?.errorMessage ?? "", reply?.model ?? "");
1612
874
  return;
1613
875
  }
1614
876
  const jobCount = asRolloverCtx(ctx)?.runningJobs().length ?? 0;
@@ -1618,7 +880,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1618
880
  }
1619
881
  if (!reply || !reply.text) {
1620
882
  // A turn that ended on some other no-text outcome is a turn end without a rate limit.
1621
- disarmRateEpisode();
883
+ rateLimit.disarmEpisode();
1622
884
  adapterLog(cfg, "notify: skipped (no reply text, agent_end hand-back)");
1623
885
  return;
1624
886
  }
@@ -1630,29 +892,23 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1630
892
  return;
1631
893
  }
1632
894
  // A real hand-back: the turn ended without a rate limit — the episode is over.
1633
- disarmRateEpisode();
895
+ rateLimit.disarmEpisode();
1634
896
  recordTurnAnswer(reply);
1635
897
  // A deferred hand-back fires no session_stop: reset the per-turn cap here (I-20261030-24),
1636
898
  // record the hand-back for the owner-answer wait (P9), and steer a promise like checkStop
1637
899
  // refuses it (I-20261030-32).
1638
- resetMainCalls();
1639
- ownerAnswerHandback(nowSec());
900
+ resetMainCalls(cfg.paths);
901
+ ownerAnswerHandback(nowSec(), cfg.paths);
1640
902
  if (new RegExp(cfg.guards.plan_offer, "i").test(reply.text)) {
1641
903
  pi.sendUserMessage(STOP_PLAN_OFFER_REFUSAL);
1642
904
  }
1643
905
  notifyHandback(reply, "agent_end hand-back");
1644
- });
1645
- // Turn end: page answers that arrived during the turn go out (P3b), then open plans that now
1646
- // WAIT on the owner ping Discord (P3b). Main only.
1647
- pi.on("agent_end", (_e, ctx) => {
1648
- if (!isMain(ctx)) return;
1649
- deliverOwnerInbox(pi, cfg);
1650
- notifyWaitingPlans();
1651
- });
1652
- // Write-check deferral (I-20261028-166): at a session's own turn end its still-present deferred
1653
- // findings go out — Main by steer (the only session sendUserMessage is proven to reach), a
1654
- // subagent through the adapter log; cleared per session, so it is never repeated.
1655
- pi.on("agent_end", (_e, ctx) => {
906
+ };
907
+
908
+ // Stage 4: Write-check deferral (I-20261028-166): at a session's own turn end its still-present
909
+ // deferred findings go out — Main by steer (the only session sendUserMessage is proven to
910
+ // reach), a subagent through the adapter log; cleared per session, so it is never repeated.
911
+ const onDeferredWriteCheck = (ctx: unknown): void => {
1656
912
  const c = asCtx(ctx);
1657
913
  const wc = cfg.write_check;
1658
914
  const key = c.id ?? "main";
@@ -1671,47 +927,52 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1671
927
  if (steers.length === 0) return;
1672
928
  if (!c.hasAgent || c.kind === "main") pi.sendUserMessage(steers.join("\n"));
1673
929
  else adapterLog(cfg, `WRITE-CHECK deferred still present: ${steers.join(" | ")}`);
1674
- });
930
+ };
1675
931
 
1676
- // Terminal hand-back (plan 20261028_1545 P2): a willContinue agent_end keeps the turn going
1677
- // (blocked stop, todo/plan-mode continuation, deferred hand-back); only its absence ends the
1678
- // turn — the budget resets here and on the deferred hand-back above (I-20261030-24).
1679
932
  pi.on("agent_end", (e, ctx) => {
1680
- if (!isMain(ctx)) return;
1681
- if (asRecord(e).willContinue === true) return;
1682
- resetMainCalls();
1683
- ownerAnswerHandback(nowSec());
1684
- });
1685
- // 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.
1686
- pi.on("agent_end", (_e, ctx) => {
933
+ // 1. Session rollover size/version check & relaunch re-arm
934
+ rollover.onSizeCheck("agent_end", e, ctx);
935
+ // 2. Deferred hand-back notify / rate-limit handling (when willContinue === true)
936
+ onDeferredHandback(e, ctx);
937
+ // 3. Deliver owner inbox & ping Discord on newly waiting plans (Main only)
938
+ if (isMain(ctx)) {
939
+ deliverOwnerInbox(pi, cfg);
940
+ notifyWaitingPlans();
941
+ }
942
+ // 4. Report still-present deferred write-check findings for this session
943
+ onDeferredWriteCheck(ctx);
944
+ // 5. Terminal hand-back: reset Main's per-turn call budget & record answer hand-back
945
+ if (isMain(ctx) && asRecord(e).willContinue !== true) {
946
+ resetMainCalls(cfg.paths);
947
+ ownerAnswerHandback(nowSec(), cfg.paths);
948
+ }
949
+ // 6. P4k backstop: check if a named review subagent ended without recording a verdict
1687
950
  const c = asCtx(ctx);
1688
- if (c.kind !== "sub" || !c.id) return;
1689
- const note = reviewSpawnEnd(c.id, cfg);
1690
- if (note) pendingReviewNotes.push(note);
951
+ if (c.kind === "sub" && c.id) {
952
+ const note = reviewSpawnEnd(c.id, cfg);
953
+ if (note) pendingReviewNotes.push(note);
954
+ }
955
+ // 7. Recall topics: spawn background segmentation when due (Main only)
956
+ if (isMain(ctx) && cfg.recall.topics_model !== "" && topicsDue(appendedSinceSpawn(), cfg.recall.topics_every)) {
957
+ markTopicsSpawned();
958
+ spawnTopics(cfg, ctx, ["recall", "topics"]);
959
+ }
1691
960
  });
1692
961
 
1693
- pi.on("agent_end", (_e, ctx) => {
1694
- if (!isMain(ctx) || cfg.recall.topics_model === "") return;
1695
- if (!topicsDue(appendedSinceSpawn(), cfg.recall.topics_every)) return;
1696
- markTopicsSpawned();
1697
- spawnTopics(cfg, ctx, ["recall", "topics"]);
1698
- });
1699
962
  pi.on("session_shutdown", (_e, ctx) => {
1700
- if (!isMain(ctx) || cfg.recall.topics_model === "") return;
1701
- spawnTopics(cfg, ctx, ["recall", "topics", "--close"]);
1702
- });
1703
-
1704
- // omp is really shutting down: the exit-grace fallback must not fire. A clean shutdown is also
1705
- // the owner's last stamp (P2 d): verify first, then record the state that pass confirmed.
1706
- pi.on("session_shutdown", () => {
1707
- clearGrace?.();
963
+ if (isMain(ctx) && cfg.recall.topics_model !== "") {
964
+ spawnTopics(cfg, ctx, ["recall", "topics", "--close"]);
965
+ }
966
+ // omp is really shutting down: the exit-grace fallback must not fire. A clean shutdown is also
967
+ // the owner's last stamp (P2 d): verify first, then record the state that pass confirmed.
968
+ rollover.clearGrace();
1708
969
  stampPlannerState(freshConfig);
1709
970
  });
1710
971
 
1711
972
  // Compaction keeps the owner's holds true: a summary may state a hold only as a plans' WAITING on owner line says it.
1712
973
  pi.on("session.compacting", (_e, ctx) => {
1713
974
  if (!isMain(ctx)) return undefined;
1714
- const holds = q.ownerHolds();
975
+ const holds = q.ownerHolds(cfg.paths);
1715
976
  return {
1716
977
  context: [
1717
978
  "Owner holds/blockers: only plans' WAITING on owner lines are real:",
@@ -1721,184 +982,11 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1721
982
  };
1722
983
  });
1723
984
 
1724
- /** Wait-jobs notice for Main's next turn, throttled; null otherwise. The note request goes out at turn end. */
1725
- const rolloverNotice = (ctx: unknown): string | null => {
1726
- const c = asRolloverCtx(ctx);
1727
- if (!cfg.rollover.enabled || !c) return null;
1728
- const state = rolloverSnapshot(c).state;
1729
- if (state === "wait-jobs" && Date.now() - waitNoticeMs >= WAIT_NOTICE_MS) {
1730
- waitNoticeMs = Date.now();
1731
- const jobs = c.runningJobs().join(", ");
1732
- return `Session rollover: the handoff note is ready, but own jobs are still running (${jobs}). A rollover would cancel them, so the owner's messages stay in this session until they finish.`;
1733
- }
1734
- return null;
1735
- };
1736
-
1737
- // Chat unlock + autonomy tiers (guards.chat_unlock): the owner's whole message "unlock"/
1738
- // "unlock N"/"lock" moves the guard unlock file, "tier <name>" sets the autonomy tier and the
1739
- // approve phrase (autonomy.go_phrase, default "go push") approves one strict landing
1740
- // (src/core/queue/lib.ts chatUnlock, src/core/autonomy.ts
1741
- // chatTier/chatGo). Only prompts the owner really typed
1742
- // count: the local terminal (input event, source "interactive") and collab guest prompts from
1743
- // write peers. This handler is registered BEFORE the rollover input handler below, so the unlock
1744
- // wins while a rollover is ready or in flight (emitInput short-circuits on { handled: true }).
1745
- // An applied unlock also wakes Main (sendUserMessage: idle → a new turn, mid-turn → the steer
1746
- // queue), the same message the phone-page unlock sends through the owner inbox.
1747
- const notifyUnlock = (ctx: unknown, r: { command?: "unlock" | "lock"; minutes?: number; until?: number }): void => {
1748
- const c = asRolloverCtx(ctx);
1749
- if (r.command === "unlock" && r.minutes !== undefined && r.until !== undefined) {
1750
- const hhmm = strftime(r.until, "%H:%M");
1751
- c?.notify(`guard unlocked for ${r.minutes} min (until ${hhmm})`);
1752
- pi.sendUserMessage(`Owner unlocked the guards in chat for ${r.minutes} min (until ${hhmm}). Do the step that waited on the unlock now.`);
1753
- } else if (r.command === "lock") {
1754
- c?.notify("guard locked again");
1755
- }
1756
- };
1757
- // The tier switch and the one-shot `go` travel the same two owner paths and answer the same way.
1758
- const notifyTier = (ctx: unknown, r: { tier?: Tier }): void => {
1759
- const c = asRolloverCtx(ctx);
1760
- if (!c || r.tier === undefined) return;
1761
- c.notify(`tier now ${r.tier}`);
1762
- };
1763
- const notifyGo = (ctx: unknown, r: { minutes?: number }): void => {
1764
- const c = asRolloverCtx(ctx);
1765
- if (!c || r.minutes === undefined) return;
1766
- c.notify(`${cfg.autonomy.go_phrase}: one push/merge approved for ${r.minutes} min`);
1767
- };
1768
- pi.on("input", (event, ctx) => {
1769
- if (!cfg.guards.chat_unlock || !isMain(ctx)) return undefined;
1770
- const e = asRecord(event);
1771
- if (asString(e.source) !== "interactive") return undefined;
1772
- const text = asString(e.text);
1773
- const t = chatTier(text, cfg, "interactive");
1774
- if (t.applied) {
1775
- notifyTier(ctx, t);
1776
- return { handled: true };
1777
- }
1778
- const p = chatPlanner(text, cfg, "interactive");
1779
- if (p.applied) {
1780
- asRolloverCtx(ctx)?.notify(`planner now ${p.planner}`);
1781
- return { handled: true };
1782
- }
1783
- const g = chatGo(text, cfg, "interactive");
1784
- if (g.applied) {
1785
- notifyGo(ctx, g);
1786
- return { handled: true };
1787
- }
1788
- const a = chatApprove(text, cfg, "interactive");
1789
- if (a.applied) {
1790
- asRolloverCtx(ctx)?.notify(`approved ${basename(a.plan)}`);
1791
- return { handled: true };
1792
- }
1793
- if (a.problem !== undefined) {
1794
- asRolloverCtx(ctx)?.notify(a.problem);
1795
- return { handled: true };
1796
- }
1797
- const r = q.chatUnlock(asString(e.text), cfg, "interactive");
1798
- if (!r.applied) return undefined;
1799
- notifyUnlock(ctx, r);
1800
- return { handled: true };
1801
- });
1802
- // A collab guest prompt (collab/host.ts #handlePrompt, write peers only) is NOT an input event:
1803
- // it is session.promptCustomMessage({ customType: "collab-prompt", details: { from },
1804
- // attribution: "user" }), which lands in the agent context — the adapter sees it on the
1805
- // "context" event (types.ts ContextEvent, the messages about to go to the LLM). The message
1806
- // stays in the transcript, so later LLM calls replay it: a seen key (timestamp + text) is acted
1807
- // on once, and a resumed session replaying old prompts is stopped by the age limit.
1808
- const seenChatPrompts = new Set<string>();
1809
- const CHAT_PROMPT_MAX_AGE_MS = 10 * 60_000;
1810
- pi.on("context", (event, ctx) => {
1811
- if (!isMain(ctx)) return undefined;
1812
- const messages = asRecord(event).messages;
1813
- if (!Array.isArray(messages)) return undefined;
1814
- if (cfg.guards.chat_unlock) {
1815
- for (const raw of messages) {
1816
- const m = asRecord(raw);
1817
- if (m.role !== "custom" || m.customType !== "collab-prompt" || m.attribution !== "user") continue;
1818
- const from = asString(asRecord(m.details).from);
1819
- if (from === "") continue;
1820
- const text =
1821
- typeof m.content === "string"
1822
- ? m.content
1823
- : Array.isArray(m.content)
1824
- ? m.content.map(c => asString(asRecord(c).text)).join("")
1825
- : "";
1826
- const timestamp = typeof m.timestamp === "number" ? m.timestamp : 0;
1827
- if (Date.now() - timestamp > CHAT_PROMPT_MAX_AGE_MS) continue;
1828
- const key = `${timestamp}:${text}`;
1829
- if (seenChatPrompts.has(key)) continue;
1830
- seenChatPrompts.add(key);
1831
- const r = q.chatUnlock(text, cfg, `collab:${from}`);
1832
- if (r.applied) {
1833
- notifyUnlock(ctx, r);
1834
- continue;
1835
- }
1836
- const t = chatTier(text, cfg, `collab:${from}`);
1837
- if (t.applied) {
1838
- notifyTier(ctx, t);
1839
- continue;
1840
- }
1841
- const g = chatGo(text, cfg, `collab:${from}`);
1842
- if (g.applied) notifyGo(ctx, g);
1843
- }
1844
- }
1845
- const rule = { pattern: cfg.quota.reset_pattern, zone: cfg.quota.reset_tz };
1846
- let changed = false;
1847
- const mapped = messages.map(raw => {
1848
- const message = asRecord(raw);
1849
- if (typeof message.content === "string") {
1850
- const content = annotateResetTimes(message.content, rule);
1851
- if (content === message.content) return raw;
1852
- changed = true;
1853
- return { ...message, content };
1854
- }
1855
- if (!Array.isArray(message.content)) return raw;
1856
- let contentChanged = false;
1857
- const content = message.content.map(part => {
1858
- const block = asRecord(part);
1859
- if (typeof block.text !== "string") return part;
1860
- const text = annotateResetTimes(block.text, rule);
1861
- if (text === block.text) return part;
1862
- contentChanged = true;
1863
- return { ...block, text };
1864
- });
1865
- if (!contentChanged) return raw;
1866
- changed = true;
1867
- return { ...message, content };
1868
- });
1869
- return changed ? { messages: mapped } : undefined;
1870
- });
1871
-
1872
- // The relaunch is the only rollover path: a plain interactive message in the ready state
1873
- // requests it, and every such message joins the pending request's draft, in order.
1874
- pi.on("input", (event, ctx) => {
1875
- const e = asRecord(event);
1876
- const c = asRolloverCtx(ctx);
1877
- const text = asString(e.text);
1878
- if (!cfg.rollover.enabled || !c || !isMain(ctx)) return undefined;
1879
- if (asString(e.source) !== "interactive" || text === "" || text.startsWith("/")) return undefined;
1880
- if (!relaunched) {
1881
- if (rolloverSnapshot(c).state !== "ready") return undefined;
1882
- // The message is the request's first owner text, so the editor draft is not carried.
1883
- if (!requestRelaunch(c, notePath(c.sessionId), "")) return undefined;
1884
- }
1885
- if (appendToRelaunch(text)) c.notify("rollover in progress: your message goes to the new session");
1886
- else c.notify("rollover in progress: your message could not be saved and was not sent; send it again after the rollover");
1887
- // omp re-checks its deferred exit only when shutdown() is called again: re-arm per message.
1888
- c.shutdown();
1889
- return { handled: true };
1890
- });
1891
-
1892
- // The rollover starts on its own (size + idle), and the owner's next message joins the
1893
- // pending relaunch; the command only says so.
1894
- pi.registerCommand("main-rollover", {
1895
- description: "Start a fresh session from Main's handoff note; the rest of the message is the owner's first message",
1896
- handler: async (_args: unknown, ctx: unknown) => {
1897
- const c = asRolloverCtx(ctx);
1898
- if (!c) return;
1899
- c.notify("main-rollover: under neurastream main the rollover starts from your next message, not from this command.");
1900
- },
1901
- });
985
+ // Register chat commands (unlock/tier/planner/go/approve + context) BEFORE rollover input
986
+ // so unlock wins while a rollover is ready or in flight.
987
+ registerChatCommands(pi, getCfg);
988
+ pi.on("input", (event, ctx) => rollover.handleInput(event, ctx));
989
+ rollover.registerCommand();
1902
990
  }
1903
991
 
1904
992
  /** Clear the active adapter's rollover state and release the session lock. Tests call this in