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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.3.18",
3
+ "version": "0.3.21",
4
4
  "description": "Guardrails for running many AI coding agents at once: plan queue, blockers, call budgets, provider caps, scoring, merge-verified close.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -3,14 +3,13 @@
3
3
  // is one folder under src/adapters plus one entry in ADAPTERS below — zero core changes
4
4
  // (docs/adapter.md, "Adding a harness").
5
5
 
6
- import type { DumpRef, LaunchOptions, OwnerTurn, RelatedTrace, RunSource, TaskResult, TraceRun, TraceSource } from "../core/adapter.ts";
6
+ import type { CompleteRequest, CompleteResult, DumpRef, LaunchOptions, OwnerTurn, RelatedTrace, RunSource, TaskResult, TraceRun, TraceSource } from "../core/adapter.ts";
7
7
  import type { Config } from "../core/config.ts";
8
8
  import type { ProviderStatus } from "../core/provider-state.ts";
9
9
  import type { Episode } from "../core/episodes.ts";
10
10
  import type { DumpParts, DumpTokens } from "../core/trace-bloat.ts";
11
11
  import type { SpawnBrief } from "../core/trace-briefs.ts";
12
12
  import { ompAdapter } from "./omp/adapter.ts";
13
- export { ompComplete } from "./omp/launch.ts";
14
13
 
15
14
  export interface HarnessAdapter {
16
15
  name: string;
@@ -50,6 +49,8 @@ export interface HarnessAdapter {
50
49
  doctor(): number;
51
50
  /** Providers the harness knows and their state now; null = its store could not be read (doctor names why); [] = the harness has no such data. */
52
51
  providers(cfg: Config): ProviderStatus[] | null;
52
+ /** One stateless text completion through the harness's configured gateway. */
53
+ complete(req: CompleteRequest): Promise<CompleteResult>;
53
54
  }
54
55
 
55
56
  const ADAPTERS: Record<string, HarnessAdapter> = {
@@ -5,7 +5,7 @@ import type { HarnessAdapter } from "../index.ts";
5
5
  import { runDoctor } from "./doctor.ts";
6
6
  import { ompProviders } from "./providers.ts";
7
7
  import { runAdapterInstall } from "./install.ts";
8
- import { runMainLauncher } from "./launch.ts";
8
+ import { ompComplete, runMainLauncher } from "./launch.ts";
9
9
  import { defaultCompletedResults, defaultOwnerTurns, defaultRunSource } from "./sessions.ts";
10
10
  import { dumpModel, dumpParts, dumpPromptTokens, ompDumps, ompEpisodes, ompScoreTraces, ompTraceRuns, ompTraceSource, ompTraceStart, spawnBriefsIn, subagentTraces } from "./traces.ts";
11
11
 
@@ -30,4 +30,5 @@ export const ompAdapter: HarnessAdapter = {
30
30
  install: runAdapterInstall,
31
31
  doctor: runDoctor,
32
32
  providers: ompProviders,
33
+ complete: ompComplete,
33
34
  };
@@ -0,0 +1,64 @@
1
+ // Background queue-close for every plan Main marked complete — and (P4, plan 20261031_0911) for
2
+ // every OPEN plan whose work has landed. Ported from the original autoClose: same filter, same
3
+ // "--- auto-close attempt" log line, detached child with stdio on the per-plan close log.
4
+ // QUEUE_CLOSE_BIN overrides the binary (tests); without it the package's own executable
5
+ // bin/queue-close runs (its `#!/usr/bin/env bun` shebang picks bun).
6
+ // Never process.execPath: inside the harness that is the harness binary itself, so the child was
7
+ // a new agent session that loaded this plugin and auto-closed again — a process fork bomb
8
+ // (2026-10-21 OOMs, ~175 processes).
9
+
10
+ import { spawn } from "node:child_process";
11
+ import { appendFileSync, closeSync, mkdirSync, openSync } from "node:fs";
12
+ import { join } from "node:path";
13
+ import type { Config } from "../../core/config.ts";
14
+ import * as q from "../../core/queue/lib.ts";
15
+ import { adapterLog } from "./launch.ts";
16
+
17
+ export function closeChildArgs(plan: string, auto: boolean): [string, string[]] {
18
+ const bin = process.env.QUEUE_CLOSE_BIN;
19
+ const args = auto ? ["--auto", plan] : [plan];
20
+ if (bin) return [bin, args];
21
+ return [join(import.meta.dir, "..", "..", "..", "bin", "queue-close"), args];
22
+ }
23
+
24
+ export function autoClose(cfg: Config): string[] {
25
+ const started: string[] = [];
26
+ let plans: q.Plan[];
27
+ try {
28
+ // P4: landed open plans auto-close too (q.autoCloseCandidate) — the child runs queue-close
29
+ // --auto and writes "Status: complete" itself when the done check passes.
30
+ plans = q.activePlans(cfg.paths).filter(p => (p.status === "complete" || p.status === "cancelled" || q.autoCloseCandidate(p)) && !p.errors.length);
31
+ } catch {
32
+ return started;
33
+ }
34
+ try {
35
+ mkdirSync(cfg.paths.queue_state, { recursive: true });
36
+ } catch {}
37
+ for (const p of plans) {
38
+ try {
39
+ const outFile = q.closeLog(p.file, cfg.paths);
40
+ appendFileSync(outFile, `--- ${new Date().toISOString()} auto-close attempt\n`);
41
+ const out = openSync(outFile, "a");
42
+ const [bin, args] = closeChildArgs(p.file, p.status === "open");
43
+ const childEnv: NodeJS.ProcessEnv = {
44
+ ...process.env,
45
+ HOME: cfg.paths.home,
46
+ QUEUE_AGENT: cfg.paths.agent_dir,
47
+ QUEUE_INDEX: cfg.paths.queue_index,
48
+ QUEUE_BLOCKERS: cfg.paths.blockers,
49
+ QUEUE_STATE: cfg.paths.queue_state,
50
+ QUEUE_SUBAGENTS: cfg.paths.subagents,
51
+ QUEUE_CANCELLED: cfg.paths.cancelled,
52
+ QUEUE_UNLOCK: cfg.paths.unlock,
53
+ };
54
+ const child = spawn(bin, args, { detached: true, stdio: ["ignore", out, out], env: childEnv });
55
+ child.unref();
56
+ closeSync(out);
57
+ started.push(p.file);
58
+ } catch (err) {
59
+ adapterLog(cfg, `auto-close: could not start for ${p.file}: ${err}`);
60
+ }
61
+ }
62
+ if (started.length) adapterLog(cfg, `auto-close started: ${started.join(", ")}`);
63
+ return started;
64
+ }
@@ -0,0 +1,161 @@
1
+ // Chat unlock, autonomy tiers, planner switch, one-shot `go`, plan approval, and context reset-time annotation.
2
+
3
+ import { basename } from "node:path";
4
+ import { chatGo, chatPlanner, chatTier, type Tier } from "../../core/autonomy.ts";
5
+ import { strftime } from "../../core/clock.ts";
6
+ import type { Config } from "../../core/config.ts";
7
+ import { chatApprove } from "../../core/plan-approval.ts";
8
+ import * as q from "../../core/queue/lib.ts";
9
+ import { annotateResetTimes } from "../../core/reset-time.ts";
10
+ import { asRecord, asRolloverCtx, asString, isMain, type ExtensionHost } from "./types.ts";
11
+
12
+ const CHAT_PROMPT_MAX_AGE_MS = 10 * 60_000;
13
+
14
+ /**
15
+ * Registers the interactive `input` and collab `context` chat-command handlers on the extension host.
16
+ * Must be registered before the rollover `input` handler so unlock/tier/planner/go/approve win
17
+ * while a rollover is ready or in flight.
18
+ *
19
+ * Args:
20
+ * pi (ExtensionHost): Active extension host
21
+ * getCfg (() => Config): Accessor returning the adapter's current config
22
+ */
23
+ export function registerChatCommands(pi: ExtensionHost, getCfg: () => Config): void {
24
+ // Chat unlock + autonomy tiers (guards.chat_unlock): the owner's whole message "unlock"/
25
+ // "unlock N"/"lock" moves the guard unlock file, "tier <name>" sets the autonomy tier and the
26
+ // approve phrase (autonomy.go_phrase, default "go push") approves one strict landing
27
+ // (src/core/queue/lib.ts chatUnlock, src/core/autonomy.ts chatTier/chatGo). Only prompts the
28
+ // owner really typed count: the local terminal (input event, source "interactive") and collab
29
+ // guest prompts from write peers. This handler is registered BEFORE the rollover input handler,
30
+ // so the unlock wins while a rollover is ready or in flight (emitInput short-circuits on
31
+ // { handled: true }). An applied unlock also wakes Main (sendUserMessage: idle → a new turn,
32
+ // mid-turn → the steer queue), the same message the phone-page unlock sends through the owner inbox.
33
+ const notifyUnlock = (ctx: unknown, r: { command?: "unlock" | "lock"; minutes?: number; until?: number }): void => {
34
+ const c = asRolloverCtx(ctx);
35
+ if (r.command === "unlock" && r.minutes !== undefined && r.until !== undefined) {
36
+ const hhmm = strftime(r.until, "%H:%M");
37
+ c?.notify(`guard unlocked for ${r.minutes} min (until ${hhmm})`);
38
+ pi.sendUserMessage(`Owner unlocked the guards in chat for ${r.minutes} min (until ${hhmm}). Do the step that waited on the unlock now.`);
39
+ } else if (r.command === "lock") {
40
+ c?.notify("guard locked again");
41
+ }
42
+ };
43
+ // The tier switch and the one-shot `go` travel the same two owner paths and answer the same way.
44
+ const notifyTier = (ctx: unknown, r: { tier?: Tier }): void => {
45
+ const c = asRolloverCtx(ctx);
46
+ if (!c || r.tier === undefined) return;
47
+ c.notify(`tier now ${r.tier}`);
48
+ };
49
+ const notifyGo = (ctx: unknown, r: { minutes?: number }): void => {
50
+ const cfg = getCfg();
51
+ const c = asRolloverCtx(ctx);
52
+ if (!c || r.minutes === undefined) return;
53
+ c.notify(`${cfg.autonomy.go_phrase}: one push/merge approved for ${r.minutes} min`);
54
+ };
55
+
56
+ pi.on("input", (event, ctx) => {
57
+ const cfg = getCfg();
58
+ if (!cfg.guards.chat_unlock || !isMain(ctx)) return undefined;
59
+ const e = asRecord(event);
60
+ if (asString(e.source) !== "interactive") return undefined;
61
+ const text = asString(e.text);
62
+ const t = chatTier(text, cfg, "interactive");
63
+ if (t.applied) {
64
+ notifyTier(ctx, t);
65
+ return { handled: true };
66
+ }
67
+ const p = chatPlanner(text, cfg, "interactive");
68
+ if (p.applied) {
69
+ asRolloverCtx(ctx)?.notify(`planner now ${p.planner}`);
70
+ return { handled: true };
71
+ }
72
+ const g = chatGo(text, cfg, "interactive");
73
+ if (g.applied) {
74
+ notifyGo(ctx, g);
75
+ return { handled: true };
76
+ }
77
+ const a = chatApprove(text, cfg, "interactive");
78
+ if (a.applied) {
79
+ asRolloverCtx(ctx)?.notify(`approved ${basename(a.plan)}`);
80
+ return { handled: true };
81
+ }
82
+ if (a.problem !== undefined) {
83
+ asRolloverCtx(ctx)?.notify(a.problem);
84
+ return { handled: true };
85
+ }
86
+ const r = q.chatUnlock(asString(e.text), cfg, "interactive");
87
+ if (!r.applied) return undefined;
88
+ notifyUnlock(ctx, r);
89
+ return { handled: true };
90
+ });
91
+
92
+ // A collab guest prompt (collab/host.ts #handlePrompt, write peers only) is NOT an input event:
93
+ // it is session.promptCustomMessage({ customType: "collab-prompt", details: { from },
94
+ // attribution: "user" }), which lands in the agent context — the adapter sees it on the
95
+ // "context" event (types.ts ContextEvent, the messages about to go to the LLM). The message
96
+ // stays in the transcript, so later LLM calls replay it: a seen key (timestamp + text) is acted
97
+ // on once, and a resumed session replaying old prompts is stopped by the age limit.
98
+ const seenChatPrompts = new Set<string>();
99
+ pi.on("context", (event, ctx) => {
100
+ if (!isMain(ctx)) return undefined;
101
+ const cfg = getCfg();
102
+ const messages = asRecord(event).messages;
103
+ if (!Array.isArray(messages)) return undefined;
104
+ if (cfg.guards.chat_unlock) {
105
+ for (const raw of messages) {
106
+ const m = asRecord(raw);
107
+ if (m.role !== "custom" || m.customType !== "collab-prompt" || m.attribution !== "user") continue;
108
+ const from = asString(asRecord(m.details).from);
109
+ if (from === "") continue;
110
+ const text =
111
+ typeof m.content === "string"
112
+ ? m.content
113
+ : Array.isArray(m.content)
114
+ ? m.content.map(c => asString(asRecord(c).text)).join("")
115
+ : "";
116
+ const timestamp = typeof m.timestamp === "number" ? m.timestamp : 0;
117
+ if (Date.now() - timestamp > CHAT_PROMPT_MAX_AGE_MS) continue;
118
+ const key = `${timestamp}:${text}`;
119
+ if (seenChatPrompts.has(key)) continue;
120
+ seenChatPrompts.add(key);
121
+ const r = q.chatUnlock(text, cfg, `collab:${from}`);
122
+ if (r.applied) {
123
+ notifyUnlock(ctx, r);
124
+ continue;
125
+ }
126
+ const t = chatTier(text, cfg, `collab:${from}`);
127
+ if (t.applied) {
128
+ notifyTier(ctx, t);
129
+ continue;
130
+ }
131
+ const g = chatGo(text, cfg, `collab:${from}`);
132
+ if (g.applied) notifyGo(ctx, g);
133
+ }
134
+ }
135
+ const rule = { pattern: cfg.quota.reset_pattern, zone: cfg.quota.reset_tz };
136
+ let changed = false;
137
+ const mapped = messages.map(raw => {
138
+ const message = asRecord(raw);
139
+ if (typeof message.content === "string") {
140
+ const content = annotateResetTimes(message.content, rule);
141
+ if (content === message.content) return raw;
142
+ changed = true;
143
+ return { ...message, content };
144
+ }
145
+ if (!Array.isArray(message.content)) return raw;
146
+ let contentChanged = false;
147
+ const content = message.content.map(part => {
148
+ const block = asRecord(part);
149
+ if (typeof block.text !== "string") return part;
150
+ const text = annotateResetTimes(block.text, rule);
151
+ if (text === block.text) return part;
152
+ contentChanged = true;
153
+ return { ...block, text };
154
+ });
155
+ if (!contentChanged) return raw;
156
+ changed = true;
157
+ return { ...message, content };
158
+ });
159
+ return changed ? { messages: mapped } : undefined;
160
+ });
161
+ }
@@ -0,0 +1,221 @@
1
+ // Owner inbox delivery (plan 20261024_2230 P3b) and machine pressure tick (plan 20261026_0100 P2).
2
+ // The phone page appends answers to <queue_state>/owner-inbox.jsonl — a protected state file, so
3
+ // no agent can forge an owner answer (guards refuse the write). Main's session delivers each
4
+ // record once as a user message (pi.sendUserMessage, no options: idle → a new turn, streaming →
5
+ // the steer queue), at turn end and on a 15 s timer while idle. The consumed-row count lives in
6
+ // <queue_state>/mains/<id>/inbox-cursor; subagent sessions never deliver and never move it.
7
+
8
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
9
+ import { basename, join } from "node:path";
10
+ import { strftime } from "../../core/clock.ts";
11
+ import type { Config } from "../../core/config.ts";
12
+ import { mainId, mainStateDir } from "../../core/guards.ts";
13
+ import { inboxPath } from "../../core/owner-ui.ts";
14
+ import { currentHolder, pressureLevel, pressureMessage, pressureTransition, type PressureSample, type PressureState } from "../../core/pressure.ts";
15
+ import type * as q from "../../core/queue/lib.ts";
16
+ import { adapterLog } from "./launch.ts";
17
+ import { asString, type ExtensionHost } from "./types.ts";
18
+
19
+ /** Idle-poll interval for the owner inbox. */
20
+ export const OWNER_INBOX_POLL_MS = 15_000;
21
+ /** How often the adapter heartbeats every claim this Main holds (plan 20261027_1300 P3). */
22
+ export const CLAIM_BEAT_MS = 60_000;
23
+
24
+ /** The delivered cursor: how many owner-inbox rows this Main's session has consumed (P5: one file per Main, under its mainStateDir). */
25
+ export function ownerInboxCursorPath(cfg: Config | Pick<q.QueuePaths, "queue_state">): string {
26
+ return `${mainStateDir(cfg)}/inbox-cursor`;
27
+ }
28
+
29
+ /** 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. */
30
+ let inboxFloor: number | null = null;
31
+
32
+ /**
33
+ * Seeds the per-Main inbox cursor floor once at adapter creation so a newly registered Main does
34
+ * not replay historical inbox rows; adopts the legacy cursor file for `main` if present.
35
+ *
36
+ * Args:
37
+ * cfg (Config): Loaded neurastream configuration
38
+ */
39
+ export function seedInboxFloor(cfg: Config): void {
40
+ try {
41
+ if (!existsSync(ownerInboxCursorPath(cfg))) {
42
+ mkdirSync(mainStateDir(cfg), { recursive: true });
43
+ if (mainId() === "main") {
44
+ try {
45
+ renameSync(`${cfg.paths.queue_state}/owner-inbox.cursor`, ownerInboxCursorPath(cfg));
46
+ } catch {}
47
+ }
48
+ if (!existsSync(ownerInboxCursorPath(cfg))) {
49
+ try {
50
+ inboxFloor = pendingInboxRecords(readFileSync(inboxPath(cfg.paths), "utf8"), 0).next;
51
+ } catch {
52
+ inboxFloor = 0;
53
+ }
54
+ }
55
+ }
56
+ } catch {}
57
+ }
58
+
59
+ function readOwnerInboxCursor(cfg: Config): number {
60
+ try {
61
+ const n = Number(readFileSync(ownerInboxCursorPath(cfg), "utf8").trim());
62
+ return Number.isInteger(n) && n >= 0 ? n : inboxFloor ?? 0;
63
+ } catch {
64
+ return inboxFloor ?? 0;
65
+ }
66
+ }
67
+
68
+ function writeOwnerInboxCursor(cfg: Config, n: number): void {
69
+ try {
70
+ mkdirSync(mainStateDir(cfg), { recursive: true });
71
+ writeFileSync(ownerInboxCursorPath(cfg), `${n}\n`);
72
+ } catch {}
73
+ }
74
+
75
+ /** The user message one inbox record becomes, or null when the record is not one Main can act on.
76
+ * Records without `kind` are page answers (the original shape). */
77
+ export function ownerInboxMessage(rec: Record<string, unknown>, queuePaths?: Pick<q.QueuePaths, "queue_state">): string | ({ type: "text"; text: string } | { type: "image"; data: string; mimeType: string })[] | null {
78
+ const kind = rec.kind === undefined ? "answer" : asString(rec.kind);
79
+ const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null);
80
+ switch (kind) {
81
+ case "answer": {
82
+ const plan = asString(rec.plan);
83
+ const question = asString(rec.question);
84
+ const answer = asString(rec.answer);
85
+ if (!plan || !question || !answer) return null;
86
+ return `Owner answered on the phone page — ${basename(plan)}: ${question} → ${answer}`;
87
+ }
88
+ case "unlock": {
89
+ const minutes = num(rec.minutes);
90
+ const until = num(rec.until);
91
+ if (minutes === null || until === null) return null;
92
+ 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.`;
93
+ }
94
+ case "lock":
95
+ return "Owner locked the guards from the phone page.";
96
+ case "approval": {
97
+ const page = asString(rec.page);
98
+ const plan = asString(rec.plan);
99
+ if (page === "" || plan === "") return null;
100
+ return `Owner approved ${basename(plan)} on page ${page}.`;
101
+ }
102
+ case "reorder": {
103
+ const plan = asString(rec.plan);
104
+ const from = num(rec.from);
105
+ const to = num(rec.to);
106
+ if (!plan || from === null || to === null) return null;
107
+ return `Owner moved ${basename(plan)} from #${from} to #${to} on the phone page; INDEX.md has the new order — work by it.`;
108
+ }
109
+ case "message": {
110
+ const ts = num(rec.ts);
111
+ const id = asString(rec.id);
112
+ if (ts === null || !/^[0-9]+-[0-9a-f]{6}$/.test(id)) return null;
113
+ const at = strftime(ts, "%H:%M");
114
+ if (!queuePaths) return null;
115
+ const dir = join(queuePaths.queue_state, "owner-messages", id);
116
+ let message: Record<string, unknown>;
117
+ try {
118
+ message = JSON.parse(readFileSync(join(dir, "message.json"), "utf8")) as Record<string, unknown>;
119
+ } catch {
120
+ return [{ type: "text", text: `Owner sent a message from the phone page at ${at}; it expired (12 h) before delivery.` }];
121
+ }
122
+ const text = asString(message.text);
123
+ const names = Array.isArray(message.images) ? message.images.filter((name): name is string => typeof name === "string" && /^[1-4]\.(png|jpg|gif|webp)$/.test(name)) : [];
124
+ const parts: ({ type: "text"; text: string } | { type: "image"; data: string; mimeType: string })[] = [];
125
+ const paths = names.map(name => join(dir, name));
126
+ parts.push({
127
+ type: "text",
128
+ text: `Owner message from the phone page (${at}): ${text}${paths.length ? `\nImages:\n${paths.map(path => `- ${path}`).join("\n")}` : ""}`,
129
+ });
130
+ for (const name of names) {
131
+ const ext = name.slice(name.lastIndexOf(".") + 1);
132
+ const mimeType = ext === "jpg" ? "image/jpeg" : `image/${ext}`;
133
+ try {
134
+ parts.push({ type: "image", data: readFileSync(join(dir, name)).toString("base64"), mimeType });
135
+ } catch {
136
+ return [{ type: "text", text: `Owner sent a message from the phone page at ${at}; it expired (12 h) before delivery.` }];
137
+ }
138
+ }
139
+ return parts;
140
+ }
141
+ case "page-note": {
142
+ // One row per note the owner left on a published page (plan 20261026 P6).
143
+ const page = asString(rec.page);
144
+ const quote = asString(rec.quote);
145
+ const note = asString(rec.note);
146
+ if (!page || !note) return null;
147
+ const id = asString(rec.id);
148
+ const url = asString(rec.url);
149
+ const where = `Owner note on the page ${page}${id ? ` (${id})` : ""}${url ? ` — ${url}` : ""}: `;
150
+ return quote ? `${where}on "${quote}" → ${note}` : `${where}${note}`;
151
+ }
152
+ default:
153
+ return null;
154
+ }
155
+ }
156
+
157
+ /** The JSONL rows after `cursor` (a row count), as records, plus the new cursor. A torn last row
158
+ * (a page write that has not landed completely) stays unconsumed; a malformed complete row is
159
+ * consumed but skipped, so one bad line cannot wedge delivery. */
160
+ export function pendingInboxRecords(text: string, cursor: number): { records: Record<string, unknown>[]; next: number } {
161
+ const endsClean = text === "" || text.endsWith("\n");
162
+ const rows = text.split("\n");
163
+ if (rows.length && rows[rows.length - 1] === "") rows.pop();
164
+ const records: Record<string, unknown>[] = [];
165
+ let next = Math.min(cursor, rows.length);
166
+ for (let i = cursor; i < rows.length; i++) {
167
+ const torn = i === rows.length - 1 && !endsClean;
168
+ try {
169
+ const rec: unknown = JSON.parse((rows[i] ?? "").trim());
170
+ if (rec !== null && typeof rec === "object" && !Array.isArray(rec)) records.push(rec as Record<string, unknown>);
171
+ } catch {}
172
+ if (!torn) next = i + 1;
173
+ }
174
+ return { records, next };
175
+ }
176
+
177
+ /** Deliver every inbox row past the cursor once, as a user message to Main; then store the cursor.
178
+ * Synchronous, so the turn-end path and the idle timer cannot interleave. */
179
+ export function deliverOwnerInbox(pi: ExtensionHost, cfg: Config): void {
180
+ let text: string;
181
+ try {
182
+ text = readFileSync(inboxPath(cfg.paths), "utf8");
183
+ } catch {
184
+ return; // no inbox yet: nothing to deliver
185
+ }
186
+ const cursor = readOwnerInboxCursor(cfg);
187
+ const { records, next } = pendingInboxRecords(text, cursor);
188
+ if (next === cursor) return;
189
+ let delivered = 0;
190
+ for (const rec of records) {
191
+ // P5: a row addressed to another Main (`to` set and not this Main's id) is consumed but not delivered here.
192
+ if (typeof rec.to === "string" && rec.to !== "" && rec.to !== mainId()) continue;
193
+ const msg = ownerInboxMessage(rec, cfg.paths);
194
+ if (msg === null) continue;
195
+ pi.sendUserMessage(msg);
196
+ delivered++;
197
+ }
198
+ writeOwnerInboxCursor(cfg, next);
199
+ adapterLog(cfg, `owner inbox: delivered ${delivered} answer(s) (cursor ${cursor} → ${next})`);
200
+ }
201
+
202
+ /** 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. */
203
+ export function pressureTick(pi: ExtensionHost, cfg: Config, sample: PressureSample, now: number): void {
204
+ const file = join(cfg.paths.queue_state, "pressure.json");
205
+ let prev: PressureState | null = null;
206
+ try {
207
+ prev = JSON.parse(readFileSync(file, "utf8")) as PressureState;
208
+ } catch {}
209
+ const level = pressureLevel(sample, cfg);
210
+ const r = pressureTransition(prev, level, now, cfg);
211
+ const next = JSON.stringify(r.state);
212
+ if (next !== JSON.stringify(prev)) {
213
+ try {
214
+ mkdirSync(cfg.paths.queue_state, { recursive: true });
215
+ writeFileSync(file, next);
216
+ } catch {}
217
+ }
218
+ if (r.fire === "red") {
219
+ pi.sendUserMessage(pressureMessage("red", sample, currentHolder(cfg, now)));
220
+ } else if (r.fire === "green") pi.sendUserMessage(pressureMessage("green", sample, null));
221
+ }