@zhuxixi/pi-agent-board 0.13.0 → 0.14.0

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 (91) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +37 -12
  3. package/docs/SECTION_FOLDING.md +53 -0
  4. package/docs/superpowers/plans/2026-10-23-issue-222-attach-ready.md +290 -0
  5. package/docs/superpowers/plans/2026-10-26-issue-245-key-hints-doc-sync.md +244 -0
  6. package/docs/superpowers/plans/2026-10-27-issue-172-fullscreen-selection-clear.md +344 -0
  7. package/docs/superpowers/plans/2026-10-27-issue-252-select-key-hints.md +209 -0
  8. package/docs/superpowers/plans/2026-10-28-issue-255-coordinator-endpoint-zombie.md +442 -0
  9. package/docs/superpowers/plans/2026-10-28-issue-257-legacy-pty-runner-endpoint-cleanup.md +256 -0
  10. package/docs/superpowers/plans/2026-11-03-cwd-favorites-full-pool.md +266 -0
  11. package/docs/superpowers/plans/2026-11-03-issue-266-alt-h-detach.md +467 -0
  12. package/docs/superpowers/plans/2026-11-04-issue-270-scenario-stdout-flush.md +584 -0
  13. package/docs/superpowers/plans/2026-11-05-issue-278-ctrl-g-external-editor.md +381 -0
  14. package/docs/superpowers/plans/2026-11-06-issue-280-frame-witness-delivery.md +430 -0
  15. package/docs/superpowers/plans/2026-11-07-issue-284-attach-recovery.md +115 -0
  16. package/docs/superpowers/plans/2026-11-07-issue-284-u1-u2-trial-guide.md +39 -0
  17. package/docs/superpowers/plans/2026-11-08-host-restart-model-override.md +894 -0
  18. package/docs/superpowers/plans/2026-11-08-issue-288-cap-floor.md +51 -0
  19. package/docs/superpowers/plans/2026-11-09-dashboard-fold-flake.md +166 -0
  20. package/docs/superpowers/plans/2026-11-09-issue-273-harness-console-log-exit.md +369 -0
  21. package/docs/superpowers/plans/2026-11-10-issue-258-board-selection-settle.md +760 -0
  22. package/docs/superpowers/plans/2026-11-13-issue-294-snapshot-resize-intent.md +590 -0
  23. package/docs/superpowers/plans/2026-11-16-greeting-title-poll.md +838 -0
  24. package/docs/superpowers/plans/2026-11-22-issue-297-compaction-mirror.md +797 -0
  25. package/docs/superpowers/plans/2026-11-23-issue-254-cursor-keep-position.md +663 -0
  26. package/docs/superpowers/plans/2026-11-23-issue-95-legacy-quarantine.md +320 -0
  27. package/docs/superpowers/specs/2026-10-23-issue-222-attach-ready-design.md +204 -0
  28. package/docs/superpowers/specs/2026-10-26-issue-245-key-hints-doc-sync-design.md +72 -0
  29. package/docs/superpowers/specs/2026-10-27-issue-172-fullscreen-selection-clear-design.md +248 -0
  30. package/docs/superpowers/specs/2026-10-27-issue-252-select-key-hints-design.md +95 -0
  31. package/docs/superpowers/specs/2026-10-28-issue-255-coordinator-endpoint-zombie-design.md +380 -0
  32. package/docs/superpowers/specs/2026-10-28-issue-257-legacy-pty-runner-endpoint-cleanup-design.md +197 -0
  33. package/docs/superpowers/specs/2026-11-03-cwd-favorites-full-pool-design.md +106 -0
  34. package/docs/superpowers/specs/2026-11-03-issue-266-alt-h-detach-design.md +185 -0
  35. package/docs/superpowers/specs/2026-11-04-issue-270-scenario-stdout-flush-design.md +176 -0
  36. package/docs/superpowers/specs/2026-11-05-issue-278-ctrl-g-external-editor-design.md +185 -0
  37. package/docs/superpowers/specs/2026-11-07-issue-284-attach-recovery-design.md +166 -0
  38. package/docs/superpowers/specs/2026-11-08-host-restart-model-override-design.md +115 -0
  39. package/docs/superpowers/specs/2026-11-08-issue-288-cap-floor-design.md +86 -0
  40. package/docs/superpowers/specs/2026-11-09-dashboard-fold-flake-design.md +109 -0
  41. package/docs/superpowers/specs/2026-11-09-issue-273-harness-console-log-exit-design.md +182 -0
  42. package/docs/superpowers/specs/2026-11-10-issue-258-board-selection-settle-design.md +109 -0
  43. package/docs/superpowers/specs/2026-11-13-issue-294-snapshot-resize-intent-design.md +141 -0
  44. package/docs/superpowers/specs/2026-11-16-greeting-title-poll-design.md +174 -0
  45. package/docs/superpowers/specs/2026-11-22-issue-297-compaction-mirror-design.md +158 -0
  46. package/docs/superpowers/specs/2026-11-22-issue-95-legacy-quarantine-design.md +209 -0
  47. package/docs/superpowers/specs/2026-11-23-issue-254-cursor-keep-position-design.md +201 -0
  48. package/package.json +1 -1
  49. package/runner/pty-runner.mjs +526 -63
  50. package/runner/state-coordinator.mjs +62 -5
  51. package/runner/title-runner.mjs +33 -24
  52. package/src/commands/agent-board.ts +5 -1
  53. package/src/core/attach-detach.mjs +27 -0
  54. package/src/core/attach-frame-proof.mjs +897 -0
  55. package/src/core/attach-frame-reporter.mjs +738 -0
  56. package/src/core/attach-frame-stream.mjs +266 -0
  57. package/src/core/attach-pr-label.mjs +12 -0
  58. package/src/core/attach-recovery.mjs +239 -0
  59. package/src/core/attach-screen-owner.mjs +55 -0
  60. package/src/core/attach-view-proof.mjs +709 -0
  61. package/src/core/auto-state.mjs +6 -1
  62. package/src/core/cwd-stats.mjs +3 -1
  63. package/src/core/dashboard-prefs.mjs +31 -0
  64. package/src/core/derive.mjs +8 -1
  65. package/src/core/events.mjs +127 -1
  66. package/src/core/foreground-projection-cache.mjs +1 -0
  67. package/src/core/frame-witness-update.mjs +35 -0
  68. package/src/core/fullscreen-selection.mjs +60 -0
  69. package/src/core/host-coordination.mjs +48 -0
  70. package/src/core/host-protocol.mjs +13 -2
  71. package/src/core/hosted-frame-witness.mjs +60 -0
  72. package/src/core/paths.mjs +10 -3
  73. package/src/core/pty-attach-render.mjs +239 -0
  74. package/src/core/pty-kitty-images.mjs +237 -0
  75. package/src/core/pty-scroll.mjs +8 -8
  76. package/src/core/rows.mjs +43 -7
  77. package/src/core/session-entries.mjs +82 -0
  78. package/src/core/session-launch-prefs.mjs +45 -0
  79. package/src/core/session-view.mjs +3 -63
  80. package/src/core/store.mjs +1 -0
  81. package/src/core/terminal-attach-client.mjs +199 -20
  82. package/src/core/terminal-attach-protocol.mjs +221 -7
  83. package/src/core/terminal-model.mjs +24 -3
  84. package/src/core/terminal-snapshot.mjs +10 -0
  85. package/src/core/title-flow.mjs +66 -0
  86. package/src/core/title.mjs +101 -0
  87. package/src/core/types.mjs +17 -0
  88. package/src/index.ts +85 -0
  89. package/src/runtime/service.mjs +87 -18
  90. package/src/ui/dashboard.ts +206 -49
  91. package/src/ui/pty-attach.ts +1472 -99
@@ -0,0 +1,894 @@
1
+ # Host Restart Model Override Fix — Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
+
5
+ **Goal:** Stop passing `--model`/`--thinking` to child pi when the session can restore them itself, so host restarts no longer reset in-session `/model` and `/thinking` choices (issue #286).
6
+
7
+ **Architecture:** Two new pure core modules — `session-entries.mjs` (JSONL parse + active-branch walk, extracted from `session-view.mjs` as the single branch-semantics source) and `session-launch-prefs.mjs` (restore-ability policy). `service.mjs` gains one thin I/O helper that reads the session file and applies the policy; the three spawn paths (`launchForView`, `startHostUnderLease`, `adoptClaimedHost`) and the issue-#90 guard switch from `meta.defaultModel` to the resolved effective values. Runners are untouched (their `if (config.model)` argv assembly already skips null).
8
+
9
+ **Tech Stack:** Node ESM (`.mjs`), `node:test` + `assert/strict`, no new dependencies.
10
+
11
+ **Spec:** `docs/superpowers/specs/2026-11-08-host-restart-model-override-design.md` (v2). The decision table (§1.1), guard semantics (§1.2), and acceptance IDs live there; every task below cites its acceptance IDs.
12
+
13
+ ## Global Constraints
14
+
15
+ - Tabs for indentation; English comments and commit messages (repo AGENTS.md).
16
+ - `session-launch-prefs.mjs` stays pure: no `node:fs`, no clock, no process env. File reading lives only in the `service.mjs` closure helper. Policy must NOT be inlined into the three spawn sites (spec §4).
17
+ - Runners (`runner/pty-runner.mjs`, `runner/job-runner.mjs`) get zero code changes.
18
+ - All test fixtures under temp dirs (`mkdtempSync`), never the host repository.
19
+ - `validateViewModelMeta`'s error string keeps its exact wording (tests regex `/no longer available/`).
20
+ - Conventional commit subjects (`feat`/`fix`/`refactor`/`test`/`docs`).
21
+ - Session fixture entries: every entry on the branch needs `id` + `parentId` chain; the `type: "session"` header line is NOT a tree entry.
22
+
23
+ ## Review Focus
24
+
25
+ Five input classes the spec implies but per-task tests could miss — each pinned to its owning task:
26
+
27
+ 1. **Torn last line** (concurrent append leaves half-written JSON): bad line is skipped, judgment uses complete lines only → Task 1 test `activeBranchEntries skips a torn trailing line`.
28
+ 2. **Header-only session file** (only `type: "session"`, no entries): not restorable, pass defaults → Task 3 test case `header-only text`.
29
+ 3. **`defaultModel: null` view** (launched without a model choice): `droppedModel` must stay false and `model` stays null → Task 3 case `defaults null + restorable session`; Task 4 empty-session reply variant asserts null passthrough without a diagnostic.
30
+ 4. **Dashboard preheat cold start** (cursor-row preheat must not bypass the resolution): preheat reaches the same `ensureHost` → `launchHost` → `startHostUnderLease` entry → Task 4 Step 2 includes a static check that `src/ui/dashboard.ts` preheat calls `ensureHost` (no separate spawn path); the dynamic behavior is pinned by the `ensureHost` integration test.
31
+ 5. **Dispatch of a brand-new view** (session file absent): effective model = `defaultModel` (today's behavior) → Task 4 reply-variant with empty session file asserts passthrough; existing dispatch tests in `test/service.test.mjs` must stay green (full suite in Task 6).
32
+
33
+ ---
34
+
35
+ ### Task 1: `session-entries.mjs` — shared JSONL parse + branch walk (A0)
36
+
37
+ **Files:**
38
+ - Create: `src/core/session-entries.mjs`
39
+ - Test: `test/session-entries.test.mjs` (new)
40
+
41
+ **Interfaces:**
42
+ - Consumes: nothing (leaf module).
43
+ - Produces:
44
+ - `parseSessionEntries(text: string): { header: {id,cwd}|null, entries: any[], byId: Map<string, any> }`
45
+ - `activeBranchEntries(entries: any[], byId: Map<string, any>): any[]` (root→leaf order; leaf = last entry; cycle-safe; stops at broken `parentId`)
46
+
47
+ - [ ] **Step 1: Write the failing tests**
48
+
49
+ Create `test/session-entries.test.mjs`:
50
+
51
+ ```js
52
+ import assert from "node:assert/strict";
53
+ import { test } from "node:test";
54
+ import { activeBranchEntries, parseSessionEntries } from "../src/core/session-entries.mjs";
55
+
56
+ const line = (obj) => JSON.stringify(obj);
57
+
58
+ test("parseSessionEntries extracts header, keeps entries and index, skips bad lines", () => {
59
+ const text = [
60
+ line({ type: "session", id: "s1", cwd: "/r" }),
61
+ "{ not json",
62
+ line({ type: "model_change", id: "e1", parentId: null, provider: "p", modelId: "m" }),
63
+ line({ no: "id-field" }),
64
+ line({ type: "message", id: "e2", parentId: "e1", message: { role: "user", content: "hi" } }),
65
+ "",
66
+ ].join("\n");
67
+ const { header, entries, byId } = parseSessionEntries(text);
68
+ assert.deepEqual(header, { id: "s1", cwd: "/r" });
69
+ assert.equal(entries.length, 2, "bad JSON and id-less lines are skipped");
70
+ assert.equal(byId.size, 2);
71
+ assert.equal(entries[0].id, "e1");
72
+ });
73
+
74
+ test("parseSessionEntries tolerates null/empty text", () => {
75
+ assert.deepEqual(parseSessionEntries(null), { header: null, entries: [], byId: new Map() });
76
+ assert.deepEqual(parseSessionEntries(""), { header: null, entries: [], byId: new Map() });
77
+ });
78
+
79
+ test("activeBranchEntries walks root→leaf from the last entry", () => {
80
+ const text = [
81
+ line({ type: "session", id: "s1", cwd: "/r" }),
82
+ line({ type: "thinking_level_change", id: "e1", parentId: null, thinkingLevel: "high" }),
83
+ line({ type: "message", id: "e2", parentId: "e1", message: { role: "user", content: "hi" } }),
84
+ line({ type: "message", id: "e3", parentId: "e2", message: { role: "assistant", content: "yo" } }),
85
+ ].join("\n");
86
+ const { entries, byId } = parseSessionEntries(text);
87
+ const branch = activeBranchEntries(entries, byId);
88
+ assert.deepEqual(branch.map((e) => e.id), ["e1", "e2", "e3"]);
89
+ });
90
+
91
+ test("activeBranchEntries excludes an abandoned sibling branch", () => {
92
+ // e2 forks: abandoned child e2b, active chain continues through e3 (last entry).
93
+ const text = [
94
+ line({ type: "message", id: "e1", parentId: null, message: { role: "user", content: "hi" } }),
95
+ line({ type: "model_change", id: "e2b", parentId: "e1", provider: "p", modelId: "abandoned" }),
96
+ line({ type: "message", id: "e2", parentId: "e1", message: { role: "user", content: "again" } }),
97
+ line({ type: "message", id: "e3", parentId: "e2", message: { role: "assistant", content: "yo" } }),
98
+ ].join("\n");
99
+ const { entries, byId } = parseSessionEntries(text);
100
+ const branch = activeBranchEntries(entries, byId);
101
+ assert.deepEqual(branch.map((e) => e.id), ["e1", "e2", "e3"], "the abandoned model_change e2b must not be on the branch");
102
+ });
103
+
104
+ test("activeBranchEntries stops at a broken parentId and survives a cycle", () => {
105
+ const orphan = [{ id: "e9", parentId: "missing", type: "message" }];
106
+ assert.deepEqual(activeBranchEntries(orphan, new Map([["e9", orphan[0]]])).map((e) => e.id), ["e9"], "broken parentId ends the walk, reachable entry still returned");
107
+ const a = { id: "a", parentId: "b", type: "message" };
108
+ const b = { id: "b", parentId: "a", type: "message" };
109
+ const branch = activeBranchEntries([a, b], new Map([["a", a], ["b", b]]));
110
+ assert.ok(branch.length <= 2, "cycle guard terminates the walk");
111
+ });
112
+
113
+ test("activeBranchEntries skips a torn trailing line (concurrent append)", () => {
114
+ const text = [
115
+ line({ type: "message", id: "e1", parentId: null, message: { role: "user", content: "hi" } }),
116
+ '{"type":"message","id":"e2","par', // torn last line
117
+ ].join("\n");
118
+ const { entries, byId } = parseSessionEntries(text);
119
+ assert.equal(entries.length, 1, "torn line is dropped by the parser");
120
+ assert.deepEqual(activeBranchEntries(entries, byId).map((e) => e.id), ["e1"]);
121
+ });
122
+ ```
123
+
124
+ - [ ] **Step 2: Run tests to verify they fail**
125
+
126
+ Run: `node --test test/session-entries.test.mjs`
127
+ Expected: FAIL — `Cannot find module '../src/core/session-entries.mjs'`.
128
+
129
+ - [ ] **Step 3: Write `src/core/session-entries.mjs`**
130
+
131
+ Create `src/core/session-entries.mjs`:
132
+
133
+ ```js
134
+ /**
135
+ * Shared session-JSONL structure primitives — the single source of branch
136
+ * semantics for everything agent-board reads out of a pi session file.
137
+ * Extracted verbatim from session-view.mjs (issue #286); display code and
138
+ * launch-prefs policy both consume these so they can never drift apart.
139
+ *
140
+ * The file is a tree: every entry has `id` + `parentId`; the active branch is
141
+ * the root→leaf path ending at the last entry (pi's SessionManager.getBranch
142
+ * picks the same leaf when no explicit leaf is recorded).
143
+ */
144
+
145
+ /**
146
+ * Parse raw JSONL text into a header plus a tree index.
147
+ * Malformed lines, non-objects, and id-less entries are skipped.
148
+ * @param {string} text
149
+ * @returns {{ header: { id: string, cwd: string } | null, entries: any[], byId: Map<string, any> }}
150
+ */
151
+ export function parseSessionEntries(text) {
152
+ /** @type {{ id: string, cwd: string } | null} */
153
+ let header = null;
154
+ /** @type {any[]} */
155
+ const entries = [];
156
+ /** @type {Map<string, any>} */
157
+ const byId = new Map();
158
+
159
+ for (const rawLine of String(text || "").split(/\r?\n/)) {
160
+ const line = rawLine.trim();
161
+ if (!line) continue;
162
+ let entry;
163
+ try {
164
+ entry = JSON.parse(line);
165
+ } catch {
166
+ continue;
167
+ }
168
+ if (entry?.type === "session") {
169
+ header = { id: String(entry.id || ""), cwd: String(entry.cwd || "") };
170
+ continue;
171
+ }
172
+ if (!entry || typeof entry !== "object" || typeof entry.id !== "string") continue;
173
+ entries.push(entry);
174
+ byId.set(entry.id, entry);
175
+ }
176
+
177
+ return { header, entries, byId };
178
+ }
179
+
180
+ /**
181
+ * Walk from the last entry to the root following parentId pointers.
182
+ * Root→leaf order. A broken parentId ends the walk; a seen-set guards cycles.
183
+ * @param {any[]} entries
184
+ * @param {Map<string, any>} byId
185
+ * @returns {any[]}
186
+ */
187
+ export function activeBranchEntries(entries, byId) {
188
+ if (!entries.length) return [];
189
+ /** @type {any[]} */
190
+ const out = [];
191
+ const seen = new Set();
192
+ let cur = entries[entries.length - 1];
193
+ while (cur && typeof cur.id === "string" && !seen.has(cur.id)) {
194
+ out.push(cur);
195
+ seen.add(cur.id);
196
+ cur = cur.parentId ? byId.get(cur.parentId) ?? null : null;
197
+ }
198
+ out.reverse();
199
+ return out;
200
+ }
201
+ ```
202
+
203
+ - [ ] **Step 4: Run tests to verify they pass**
204
+
205
+ Run: `node --test test/session-entries.test.mjs`
206
+ Expected: PASS (6 tests).
207
+
208
+ - [ ] **Step 5: Commit**
209
+
210
+ ```bash
211
+ git add src/core/session-entries.mjs test/session-entries.test.mjs
212
+ git commit -m "feat: extract session-entries primitives shared by view and launch prefs"
213
+ ```
214
+
215
+ ---
216
+
217
+ ### Task 2: Refactor `session-view.mjs` onto the shared primitives (A2)
218
+
219
+ **Files:**
220
+ - Modify: `src/core/session-view.mjs` (parse loop + local `activeBranch`)
221
+ - Test: `test/session-view.test.mjs` (extend; 2 new cases)
222
+
223
+ **Interfaces:**
224
+ - Consumes: `parseSessionEntries`, `activeBranchEntries` from `./session-entries.mjs` (Task 1).
225
+ - Produces: unchanged `parseSessionText(text)` / `loadSessionView(sessionFile)` signatures and `SessionViewData` shape.
226
+
227
+ - [ ] **Step 1: Add the two regression cases to `test/session-view.test.mjs`**
228
+
229
+ Append (keep existing imports; the file already imports `parseSessionText`):
230
+
231
+ ```js
232
+ test("parseSessionText keeps the session header extraction (refactor guard, issue #286)", () => {
233
+ const text = [
234
+ JSON.stringify({ type: "session", id: "s42", cwd: "/work" }),
235
+ JSON.stringify({ type: "message", id: "e1", parentId: null, message: { role: "user", content: "hi" } }),
236
+ ].join("\n");
237
+ const view = parseSessionText(text);
238
+ assert.equal(view.header?.id, "s42");
239
+ assert.equal(view.header?.cwd, "/work");
240
+ });
241
+
242
+ test("parseSessionText skips id-less entries when building the branch (refactor guard, issue #286)", () => {
243
+ const text = [
244
+ JSON.stringify({ type: "message", id: "e1", parentId: null, message: { role: "user", content: "hi" } }),
245
+ JSON.stringify({ type: "message", parentId: "e1", message: { role: "assistant", content: "ghost" } }), // no id
246
+ ].join("\n");
247
+ const view = parseSessionText(text);
248
+ assert.equal(view.items.length, 1, "id-less entry does not reach display items");
249
+ });
250
+ ```
251
+
252
+ - [ ] **Step 2: Run tests (new ones must pass on current code — they pin pre-refactor behavior)**
253
+
254
+ Run: `node --test test/session-view.test.mjs`
255
+ Expected: PASS (4 tests). If a new case fails BEFORE the refactor, the assumption about current behavior is wrong — stop and reconcile with the current parse loop before refactoring.
256
+
257
+ - [ ] **Step 3: Refactor `parseSessionText` to use the shared module**
258
+
259
+ In `src/core/session-view.mjs`:
260
+ 1. Add import at top: `import { activeBranchEntries, parseSessionEntries } from "./session-entries.mjs";`
261
+ 2. Replace the body of `parseSessionText`'s parsing/branch section so it reads:
262
+
263
+ ```js
264
+ export function parseSessionText(text) {
265
+ const { header, entries, byId } = parseSessionEntries(text);
266
+ if (entries.length === 0) return { header, items: [], error: null };
267
+ const branch = activeBranchEntries(entries, byId);
268
+ const items = branch.flatMap(displayItemsForEntry);
269
+ return { header, items, error: null };
270
+ }
271
+ ```
272
+
273
+ 3. Delete the now-unused local `activeBranch` function and the old inline parse loop (header/entries/byId accumulation). Keep `loadSessionView`, `displayItemsForEntry`, `contentText` untouched.
274
+
275
+ - [ ] **Step 4: Run tests to verify refactor is behavior-identical**
276
+
277
+ Run: `node --test test/session-view.test.mjs test/session-entries.test.mjs`
278
+ Expected: PASS (4 + 6 tests).
279
+
280
+ - [ ] **Step 5: Commit**
281
+
282
+ ```bash
283
+ git add src/core/session-view.mjs test/session-view.test.mjs
284
+ git commit -m "refactor: session-view consumes shared session-entries primitives"
285
+ ```
286
+
287
+ ---
288
+
289
+ ### Task 3: `session-launch-prefs.mjs` — restore-ability policy (A1)
290
+
291
+ **Files:**
292
+ - Create: `src/core/session-launch-prefs.mjs`
293
+ - Test: `test/session-launch-prefs.test.mjs` (new)
294
+
295
+ **Interfaces:**
296
+ - Consumes: `parseSessionEntries`, `activeBranchEntries` (Task 1).
297
+ - Produces: `resolveLaunchModelPrefs(defaults: { model: string|null, thinkingLevel: string|null }, text: string|null): { model: string|null, thinkingLevel: string|null, droppedModel: boolean, droppedThinking: boolean }` — Task 4 consumes exactly this.
298
+
299
+ - [ ] **Step 1: Write the failing tests**
300
+
301
+ Create `test/session-launch-prefs.test.mjs`:
302
+
303
+ ```js
304
+ import assert from "node:assert/strict";
305
+ import { test } from "node:test";
306
+ import { resolveLaunchModelPrefs } from "../src/core/session-launch-prefs.mjs";
307
+
308
+ const line = (obj) => JSON.stringify(obj);
309
+ const D = { model: "prov/default-a", thinkingLevel: "high" };
310
+ const prefs = (text, defaults = D) => resolveLaunchModelPrefs(defaults, text);
311
+
312
+ // Decision-table row 1: no message entries at all → pass defaults.
313
+ test("missing/empty/garbage/header-only text passes defaults through", () => {
314
+ for (const text of [null, "", "{ broken", line({ type: "session", id: "s", cwd: "/r" })]) {
315
+ const r = prefs(text);
316
+ assert.deepEqual(r, { model: "prov/default-a", thinkingLevel: "high", droppedModel: false, droppedThinking: false }, `text=${String(text)}`);
317
+ }
318
+ });
319
+
320
+ // Row 3: messages exist but nothing restorable for model.
321
+ test("user-only session passes model and thinking defaults", () => {
322
+ const text = [
323
+ line({ type: "message", id: "e1", parentId: null, message: { role: "user", content: "hi" } }),
324
+ ].join("\n");
325
+ const r = prefs(text);
326
+ assert.equal(r.model, "prov/default-a");
327
+ assert.equal(r.thinkingLevel, "high");
328
+ assert.equal(r.droppedModel, false);
329
+ });
330
+
331
+ // Row 2: assistant message restores the model.
332
+ test("assistant message without model_change drops model but keeps thinking default", () => {
333
+ const text = [
334
+ line({ type: "message", id: "e1", parentId: null, message: { role: "user", content: "hi" } }),
335
+ line({ type: "message", id: "e2", parentId: "e1", message: { role: "assistant", content: "yo" } }),
336
+ ].join("\n");
337
+ const r = prefs(text);
338
+ assert.deepEqual(r, { model: null, thinkingLevel: "high", droppedModel: true, droppedThinking: false });
339
+ });
340
+
341
+ // Row 2: model_change restores the model (pi writes both at session creation).
342
+ test("model_change + message drops model", () => {
343
+ const text = [
344
+ line({ type: "model_change", id: "e1", parentId: null, provider: "prov", modelId: "picked-b" }),
345
+ line({ type: "message", id: "e2", parentId: "e1", message: { role: "user", content: "hi" } }),
346
+ ].join("\n");
347
+ const r = prefs(text);
348
+ assert.equal(r.model, null);
349
+ assert.equal(r.droppedModel, true);
350
+ });
351
+
352
+ // Row 3: model_change with zero messages is NOT restorable (pi gate: hasExistingSession).
353
+ test("model_change without any message entry passes model through", () => {
354
+ const text = [line({ type: "model_change", id: "e1", parentId: null, provider: "prov", modelId: "picked-b" })].join("\n");
355
+ const r = prefs(text);
356
+ assert.equal(r.model, "prov/default-a");
357
+ assert.equal(r.droppedModel, false);
358
+ });
359
+
360
+ // Thinking dimension is independent.
361
+ test("thinking_level_change + message drops thinking only", () => {
362
+ const text = [
363
+ line({ type: "thinking_level_change", id: "e1", parentId: null, thinkingLevel: "medium" }),
364
+ line({ type: "message", id: "e2", parentId: "e1", message: { role: "user", content: "hi" } }),
365
+ ].join("\n");
366
+ const r = prefs(text);
367
+ assert.deepEqual(r, { model: "prov/default-a", thinkingLevel: null, droppedModel: false, droppedThinking: true });
368
+ });
369
+
370
+ test("thinking_level_change without messages passes thinking through", () => {
371
+ const text = [line({ type: "thinking_level_change", id: "e1", parentId: null, thinkingLevel: "medium" })].join("\n");
372
+ const r = prefs(text);
373
+ assert.equal(r.thinkingLevel, "high");
374
+ assert.equal(r.droppedThinking, false);
375
+ });
376
+
377
+ // Row 2+4 mixed: both dropped.
378
+ test("model_change + thinking entry + messages drops both", () => {
379
+ const text = [
380
+ line({ type: "thinking_level_change", id: "e1", parentId: null, thinkingLevel: "medium" }),
381
+ line({ type: "model_change", id: "e2", parentId: "e1", provider: "prov", modelId: "picked-b" }),
382
+ line({ type: "message", id: "e3", parentId: "e2", message: { role: "user", content: "hi" } }),
383
+ ].join("\n");
384
+ const r = prefs(text);
385
+ assert.deepEqual(r, { model: null, thinkingLevel: null, droppedModel: true, droppedThinking: true });
386
+ });
387
+
388
+ // Defaults already null stay null with honest dropped flags.
389
+ test("null defaults + restorable session returns nulls without dropped flags", () => {
390
+ const text = [
391
+ line({ type: "model_change", id: "e1", parentId: null, provider: "prov", modelId: "picked-b" }),
392
+ line({ type: "message", id: "e2", parentId: "e1", message: { role: "assistant", content: "yo" } }),
393
+ ].join("\n");
394
+ const r = prefs(text, { model: null, thinkingLevel: null });
395
+ assert.deepEqual(r, { model: null, thinkingLevel: null, droppedModel: false, droppedThinking: false });
396
+ });
397
+
398
+ // Branch semantics: an abandoned sibling's model_change must not trigger a drop.
399
+ test("forked tree: abandoned branch model_change does not drop; active chain does", () => {
400
+ const abandoned = [
401
+ line({ type: "message", id: "e1", parentId: null, message: { role: "user", content: "hi" } }),
402
+ line({ type: "model_change", id: "e2b", parentId: "e1", provider: "prov", modelId: "abandoned" }),
403
+ line({ type: "message", id: "e2", parentId: "e1", message: { role: "user", content: "again" } }),
404
+ line({ type: "message", id: "e3", parentId: "e2", message: { role: "user", content: "more" } }),
405
+ ].join("\n");
406
+ assert.equal(prefs(abandoned).model, "prov/default-a", "user-only active chain: nothing restorable");
407
+ const active = [
408
+ line({ type: "message", id: "e1", parentId: null, message: { role: "user", content: "hi" } }),
409
+ line({ type: "message", id: "e2", parentId: "e1", message: { role: "user", content: "again" } }),
410
+ line({ type: "model_change", id: "e2b", parentId: "e1", provider: "prov", modelId: "abandoned" }),
411
+ line({ type: "message", id: "e3", parentId: "e2", message: { role: "assistant", content: "yo" } }),
412
+ ].join("\n");
413
+ assert.equal(prefs(active).model, null, "active chain reaches an assistant message → restorable");
414
+ });
415
+ ```
416
+
417
+ - [ ] **Step 2: Run tests to verify they fail**
418
+
419
+ Run: `node --test test/session-launch-prefs.test.mjs`
420
+ Expected: FAIL — module not found.
421
+
422
+ - [ ] **Step 3: Write `src/core/session-launch-prefs.mjs`**
423
+
424
+ ```js
425
+ import { activeBranchEntries, parseSessionEntries } from "./session-entries.mjs";
426
+
427
+ /**
428
+ * Pure launch-prefs policy (issue #286): decide per dimension whether an
429
+ * explicit --model / --thinking flag must be passed when spawning a child pi,
430
+ * or whether the flag must be omitted so pi restores the session's own last
431
+ * selection (pi only restores a dimension when no explicit flag is given).
432
+ *
433
+ * Mirrors pi 1.5.0 createAgentSession's restore gates on the normal path:
434
+ * - model restores when the branch has >=1 message entry AND (a model_change
435
+ * entry OR an assistant message entry);
436
+ * - thinking restores (to the session's own value) only when the branch has a
437
+ * thinking_level_change entry (otherwise pi would restore the SETTINGS
438
+ * default, not the view's defaultThinking — keep passing the explicit flag).
439
+ * Pure policy: no fs, no clock. The caller owns reading the session file.
440
+ * @param {{ model: string|null, thinkingLevel: string|null }} defaults view launch defaults (meta.defaultModel/defaultThinking)
441
+ * @param {string|null} text raw session JSONL, or null when unreadable/missing
442
+ */
443
+ export function resolveLaunchModelPrefs(defaults, text) {
444
+ const model = defaults?.model ?? null;
445
+ const thinkingLevel = defaults?.thinkingLevel ?? null;
446
+ let droppedModel = false;
447
+ let droppedThinking = false;
448
+
449
+ if (text) {
450
+ const { entries, byId } = parseSessionEntries(text);
451
+ const branch = activeBranchEntries(entries, byId);
452
+ const hasMessage = branch.some((e) => e.type === "message");
453
+ if (hasMessage) {
454
+ const modelRestorable = branch.some(
455
+ (e) => e.type === "model_change" || (e.type === "message" && e.message?.role === "assistant"),
456
+ );
457
+ const thinkingRestorable = branch.some((e) => e.type === "thinking_level_change");
458
+ droppedModel = modelRestorable && model !== null;
459
+ droppedThinking = thinkingRestorable && thinkingLevel !== null;
460
+ }
461
+ }
462
+
463
+ return {
464
+ model: droppedModel ? null : model,
465
+ thinkingLevel: droppedThinking ? null : thinkingLevel,
466
+ droppedModel,
467
+ droppedThinking,
468
+ };
469
+ }
470
+ ```
471
+
472
+ Note: `droppedModel` is only true when a real default was actually withheld — a null default staying null is not a "drop" (Task 4's diagnostic fires only on real drops; Task 3's null-defaults case asserts this).
473
+
474
+ - [ ] **Step 4: Run tests to verify they pass**
475
+
476
+ Run: `node --test test/session-launch-prefs.test.mjs`
477
+ Expected: PASS (11 tests).
478
+
479
+ - [ ] **Step 5: Commit**
480
+
481
+ ```bash
482
+ git add src/core/session-launch-prefs.mjs test/session-launch-prefs.test.mjs
483
+ git commit -m "feat: session launch-prefs policy for issue #286 restore-vs-flag decision"
484
+ ```
485
+
486
+ ---
487
+
488
+ ### Task 4: `service.mjs` integration — three spawn paths + #90 guard (A3, A4)
489
+
490
+ **Files:**
491
+ - Modify: `src/runtime/service.mjs` (`:7` import, new closure helper near `validateViewModelMeta`, `launchForView` :240-265, `startHostUnderLease` :337-380, `adoptClaimedHost` :1413-1460)
492
+ - Test: `test/host-resolver.test.mjs` (extend guard section + adopt), `test/service.test.mjs` (extend reply/json-runner section)
493
+
494
+ **Interfaces:**
495
+ - Consumes: `resolveLaunchModelPrefs` (Task 3), existing `appendDiagnostic`, `existsSync`, `readFileSync` (add to the `node:fs` import).
496
+ - Produces: closure helper `resolveViewLaunchPrefs(meta) -> { model, thinkingLevel, droppedModel, droppedThinking }`; `validateViewModelMeta(effectiveModel)` (signature change, private to service.mjs); diagnostic code `launch_prefs_from_session`.
497
+
498
+ - [ ] **Step 1: Write the failing tests — host-resolver (A4 + ensureHost A3)**
499
+
500
+ In `test/host-resolver.test.mjs`, inside the `---- stale defaultModel launch guard (issue #90) ----` section, add (helpers `freshRoot`, `resolverService`, `hostRecord`, and imports `readDiagnostics`, `writeFileSync` already exist in the file):
501
+
502
+ ```js
503
+ test("ensureHost leaves model/thinking to session restore when the session can provide them (issue #286)", () => {
504
+ const root = freshRoot();
505
+ try {
506
+ const meta = createView(root, { id: "v1", name: "restorable", cwd: "/r", defaultModel: "prov/default-a", defaultThinking: "high" });
507
+ writeFileSync(meta.sessionFile, [
508
+ JSON.stringify({ type: "session", id: "s1", cwd: "/r" }),
509
+ JSON.stringify({ type: "thinking_level_change", id: "e1", parentId: null, thinkingLevel: "medium" }),
510
+ JSON.stringify({ type: "model_change", id: "e2", parentId: "e1", provider: "prov", modelId: "picked-b" }),
511
+ JSON.stringify({ type: "message", id: "e3", parentId: "e2", message: { role: "user", content: "hi" } }),
512
+ JSON.stringify({ type: "message", id: "e4", parentId: "e3", message: { role: "assistant", content: "yo" } }),
513
+ ].join("\n") + "\n");
514
+ const spawns = [];
515
+ const svc = resolverService(root, {
516
+ launchHost: (_root, config) => {
517
+ spawns.push({ config });
518
+ return { pid: process.pid, configPath: config.configPath };
519
+ },
520
+ });
521
+ const res = svc.ensureHost("v1");
522
+ assert.equal(res.ok, true);
523
+ assert.equal(spawns.length, 1);
524
+ assert.equal(spawns[0].config.model, null, "model flag must be omitted so pi restores it");
525
+ assert.equal(spawns[0].config.thinkingLevel, null, "thinking flag must be omitted so pi restores it");
526
+ const diags = readDiagnostics(root, "v1");
527
+ assert.ok(diags.some((d) => d.code === "launch_prefs_from_session"), "drop is recorded in diagnostics");
528
+ } finally {
529
+ rmSync(root, { recursive: true, force: true });
530
+ }
531
+ });
532
+
533
+ test("ensureHost launches a restorable session even when defaultModel is provably unavailable (issue #286 + #90)", () => {
534
+ const root = freshRoot();
535
+ try {
536
+ const meta = createView(root, { id: "v1", name: "stale-but-restorable", cwd: "/r", defaultModel: "glm/glm-5.3", defaultThinking: "high" });
537
+ writeFileSync(meta.sessionFile, [
538
+ JSON.stringify({ type: "session", id: "s1", cwd: "/r" }),
539
+ JSON.stringify({ type: "model_change", id: "e1", parentId: null, provider: "zai-coding-cn", modelId: "glm-5.3" }),
540
+ JSON.stringify({ type: "message", id: "e2", parentId: "e1", message: { role: "user", content: "hi" } }),
541
+ JSON.stringify({ type: "message", id: "e3", parentId: "e2", message: { role: "assistant", content: "yo" } }),
542
+ ].join("\n") + "\n");
543
+ const spawns = [];
544
+ const svc = resolverService(root, {
545
+ availableModels: () => [{ provider: "zai-coding-cn", id: "glm-5.3" }],
546
+ launchHost: (_root, config) => {
547
+ spawns.push({ config });
548
+ return { pid: process.pid, configPath: config.configPath };
549
+ },
550
+ });
551
+ const res = svc.ensureHost("v1");
552
+ assert.equal(res.ok, true, "a dead defaultModel must not block a session that restores its own model");
553
+ assert.equal(spawns.length, 1);
554
+ assert.equal(spawns[0].config.model, null);
555
+ } finally {
556
+ rmSync(root, { recursive: true, force: true });
557
+ }
558
+ });
559
+
560
+ test("guard still blocks a dead defaultModel on an unrestorable session (issue #90 unchanged, issue #286)", () => {
561
+ const root = freshRoot();
562
+ try {
563
+ const meta = createView(root, { id: "v1", name: "stale-empty", cwd: "/r", defaultModel: "glm/glm-5.3" });
564
+ writeFileSync(meta.sessionFile, [
565
+ JSON.stringify({ type: "session", id: "s1", cwd: "/r" }),
566
+ JSON.stringify({ type: "message", id: "e1", parentId: null, message: { role: "user", content: "hi" } }),
567
+ ].join("\n") + "\n");
568
+ const spawns = [];
569
+ const svc = resolverService(root, {
570
+ availableModels: () => [{ provider: "zai-coding-cn", id: "glm-5.3" }],
571
+ launchHost: (_root, config) => {
572
+ spawns.push({ config });
573
+ return { pid: process.pid, configPath: config.configPath };
574
+ },
575
+ });
576
+ const res = svc.ensureHost("v1");
577
+ assert.equal(res.ok, false);
578
+ assert.match(res.error, /no longer available/);
579
+ assert.equal(spawns.length, 0, "user-only session cannot restore a model — the explicit dead one must not spawn");
580
+ } finally {
581
+ rmSync(root, { recursive: true, force: true });
582
+ }
583
+ });
584
+
585
+ test("adoption of a stale claim also resolves launch prefs from the session (issue #286)", () => {
586
+ const root = freshRoot();
587
+ try {
588
+ const meta = createView(root, { id: "v1", name: "adopt", cwd: "/r", defaultModel: "prov/default-a", defaultThinking: "high" });
589
+ writeFileSync(meta.sessionFile, [
590
+ JSON.stringify({ type: "session", id: "s1", cwd: "/r" }),
591
+ JSON.stringify({ type: "model_change", id: "e1", parentId: null, provider: "prov", modelId: "picked-b" }),
592
+ JSON.stringify({ type: "message", id: "e2", parentId: "e1", message: { role: "user", content: "hi" } }),
593
+ ].join("\n") + "\n");
594
+ hostRecord(root, "v1", {
595
+ instanceId: "i1",
596
+ state: "starting",
597
+ claimAt: Date.now() - HOST_START_GRACE_MS - 5_000,
598
+ claimPid: process.pid,
599
+ runnerSpawnedAt: null,
600
+ });
601
+ const probe = scriptProbe(["missing", "missing", "ready"]);
602
+ const spawns = [];
603
+ const svc = resolverService(root, {
604
+ probeHostFn: probe.fn,
605
+ sleepFn: instantSleep,
606
+ launchHost: (_root, config) => {
607
+ spawns.push({ config });
608
+ return { pid: process.pid, configPath: config.configPath };
609
+ },
610
+ });
611
+ const result = await svc.resolveAttachTarget("v1", { timeoutMs: 2_000 });
612
+ assert.equal(result.kind, "pty");
613
+ assert.equal(spawns.length, 1, "the stale claim is adopted and spawned");
614
+ assert.equal(spawns[0].config.model, null, "adopted spawn omits the model flag");
615
+ assert.equal(spawns[0].config.thinkingLevel, "high", "no thinking entry in session → keep view default");
616
+ } finally {
617
+ rmSync(root, { recursive: true, force: true });
618
+ }
619
+ });
620
+ ```
621
+
622
+ Mark the adoption test `async` in its declaration: `test("adoption of a stale claim ...", async () => {`.
623
+
624
+ - [ ] **Step 2: Write the failing tests — service reply/json-runner path (A3, launchForView)**
625
+
626
+ In `test/service.test.mjs`, next to the existing `drainNextFollowUp` test (~:1636), add two variants (reuse the file's existing helpers `freshRoot`, `service`, `createView`, `readState`, `writeState`, `readDiagnostics` — import `readDiagnostics` from `../src/core/diagnostics.mjs` and `writeFileSync` from `node:fs` if not already imported):
627
+
628
+ ```js
629
+ async function replyDrainCapture(root, sessionText) {
630
+ const meta = createView(root, { id: "v1", name: "r", cwd: "/r", defaultModel: "prov/default-a", defaultThinking: "high" });
631
+ if (sessionText !== null) writeFileSync(meta.sessionFile, sessionText);
632
+ const st = readState(root, "v1");
633
+ st.semanticState = "working";
634
+ st.processState = "alive";
635
+ writeState(root, st);
636
+ const launched = [];
637
+ const svc = service(root, {
638
+ ptySupport: () => ({ ok: false, reason: "test" }),
639
+ launch: (_root, config) => {
640
+ launched.push(config);
641
+ return { pid: null, configPath: "/no/config.json" };
642
+ },
643
+ });
644
+ const queued = await svc.reply("v1", "next step");
645
+ assert.equal(queued.ok, true);
646
+ const idle = readState(root, "v1");
647
+ idle.semanticState = "idle";
648
+ idle.processState = "exited";
649
+ writeState(root, idle);
650
+ const drained = await svc.drainNextFollowUp("v1");
651
+ assert.equal(drained.ok, true);
652
+ assert.equal(launched.length, 1);
653
+ return { launched: launched[0], svc };
654
+ }
655
+
656
+ test("json-runner follow-up on a restorable session omits model/thinking flags (issue #286)", async () => {
657
+ const root = freshRoot();
658
+ try {
659
+ const sessionText = [
660
+ JSON.stringify({ type: "session", id: "s1", cwd: "/r" }),
661
+ JSON.stringify({ type: "thinking_level_change", id: "e1", parentId: null, thinkingLevel: "medium" }),
662
+ JSON.stringify({ type: "model_change", id: "e2", parentId: "e1", provider: "prov", modelId: "picked-b" }),
663
+ JSON.stringify({ type: "message", id: "e3", parentId: "e2", message: { role: "user", content: "hi" } }),
664
+ JSON.stringify({ type: "message", id: "e4", parentId: "e3", message: { role: "assistant", content: "yo" } }),
665
+ ].join("\n") + "\n";
666
+ const { launched } = await replyDrainCapture(root, sessionText);
667
+ assert.equal(launched.model, null);
668
+ assert.equal(launched.thinkingLevel, null);
669
+ assert.ok(readDiagnostics(root, "v1").some((d) => d.code === "launch_prefs_from_session"));
670
+ } finally {
671
+ rmSync(root, { recursive: true, force: true });
672
+ }
673
+ });
674
+
675
+ test("json-runner follow-up on an empty session keeps launch defaults (issue #286)", async () => {
676
+ const root = freshRoot();
677
+ try {
678
+ const { launched } = await replyDrainCapture(root, "");
679
+ assert.equal(launched.model, "prov/default-a");
680
+ assert.equal(launched.thinkingLevel, "high");
681
+ assert.ok(!readDiagnostics(root, "v1").some((d) => d.code === "launch_prefs_from_session"), "no drop → no diagnostic");
682
+ } finally {
683
+ rmSync(root, { recursive: true, force: true });
684
+ }
685
+ });
686
+ ```
687
+
688
+ (If `freshRoot` does not exist under that name in `service.test.mjs`, use the file's own temp-root helper — do not invent a second one; the existing tests around :1636 show the canonical setup to copy.)
689
+
690
+ - [ ] **Step 3: Static preheat check (Review Focus #4)**
691
+
692
+ Run: `rg -n "ensureHost|launchHost" src/ui/dashboard.ts | head -20`
693
+ Expected: preheat path funnels into the service `ensureHost`/`launchHost` API (no direct runner spawn, no separate config build). If a preheat path builds a config another way, STOP — the spec's three-spawn-path inventory is incomplete and must be revisited before implementation.
694
+
695
+ - [ ] **Step 4: Run the new tests to verify they fail**
696
+
697
+ Run: `node --test test/host-resolver.test.mjs test/service.test.mjs`
698
+ Expected: the four new host-resolver tests and two new service tests FAIL (config carries `defaultModel` verbatim / guard blocks the restorable+dead case); all pre-existing tests still PASS.
699
+
700
+ - [ ] **Step 5: Implement the service integration**
701
+
702
+ In `src/runtime/service.mjs`:
703
+
704
+ 1. Line ~7: `import { existsSync } from "node:fs";` → `import { existsSync, readFileSync } from "node:fs";`
705
+ 2. Add import near the other core imports: `import { resolveLaunchModelPrefs } from "../core/session-launch-prefs.mjs";`
706
+ 3. Above `validateViewModelMeta` (~:309), add the closure helper:
707
+
708
+ ```js
709
+ /**
710
+ * Effective launch prefs for a view (issue #286): read the session file and
711
+ * let the pure policy decide, per dimension, whether the explicit
712
+ * --model/--thinking flag must be withheld so pi restores the session's own
713
+ * last selection. Missing/unreadable session → both flags pass through
714
+ * (today's behavior). Real drops are recorded in diagnostics.
715
+ * @param {import("../core/types.mjs").ViewMeta} meta
716
+ * @returns {{ model: string|null, thinkingLevel: string|null, droppedModel: boolean, droppedThinking: boolean }}
717
+ */
718
+ function resolveViewLaunchPrefs(meta) {
719
+ let text = null;
720
+ try {
721
+ text = existsSync(meta.sessionFile) ? readFileSync(meta.sessionFile, "utf8") : null;
722
+ } catch {
723
+ text = null;
724
+ }
725
+ const prefs = resolveLaunchModelPrefs(
726
+ { model: meta.defaultModel ?? null, thinkingLevel: meta.defaultThinking ?? null },
727
+ text,
728
+ );
729
+ if (prefs.droppedModel || prefs.droppedThinking) {
730
+ appendDiagnostic(root, meta.id, {
731
+ source: "service",
732
+ code: "launch_prefs_from_session",
733
+ message: "Launch model/thinking left to session restore",
734
+ details: { droppedModel: prefs.droppedModel, droppedThinking: prefs.droppedThinking },
735
+ });
736
+ }
737
+ return prefs;
738
+ }
739
+ ```
740
+
741
+ 4. Change `validateViewModelMeta(meta)` to take the effective model (update its JSDoc; keep the error string byte-identical):
742
+
743
+ ```js
744
+ /**
745
+ * Actionable error when the model we are about to spawn with is provably
746
+ * unavailable (issue #90): launching a child with a dead model id makes it
747
+ * exit 1 on every start, so attach would loop cold starts forever. With
748
+ * issue #286 the input is the EFFECTIVE model — null when the session
749
+ * restores its own selection, in which case there is nothing to validate.
750
+ * Only fires when a model is configured AND a live model list is injectable.
751
+ * @param {string|null} effectiveModel
752
+ * @returns {string|null}
753
+ */
754
+ function validateViewModelMeta(effectiveModel) {
755
+ const model = effectiveModel ?? null;
756
+ if (!model || !availableModelsImpl) return null;
757
+ let available;
758
+ try {
759
+ available = availableModelsImpl();
760
+ } catch {
761
+ return null;
762
+ }
763
+ if (modelRefAvailable(model, available)) return null;
764
+ return `Model "${model}" configured for this session is no longer available — update the view's model (or clear defaultModel) and retry attach.`;
765
+ }
766
+ ```
767
+
768
+ 5. `launchForView` (~:240): resolve before building the config, then use it:
769
+
770
+ ```js
771
+ async function launchForView(meta, prompt, kind) {
772
+ const runId = newRunId();
773
+ const launchPrefs = resolveViewLaunchPrefs(meta);
774
+ /** @type {import("../core/types.mjs").RunConfig} */
775
+ const config = {
776
+ /* …unchanged fields… */
777
+ model: launchPrefs.model,
778
+ thinkingLevel: launchPrefs.thinkingLevel,
779
+ tools: null,
780
+ };
781
+ ```
782
+
783
+ (Only the two lines `model:` / `thinkingLevel:` change plus the two added lines.)
784
+
785
+ 6. `startHostUnderLease` (~:337): resolve before the guard, pass effective model to the guard, use prefs in the config:
786
+
787
+ ```js
788
+ // Fail fast BEFORE claiming (issue #90) — on the EFFECTIVE model (issue #286):
789
+ // a session that restores its own model must not be blocked by a dead
790
+ // defaultModel we are not going to pass anyway.
791
+ const launchPrefs = resolveViewLaunchPrefs(meta);
792
+ const modelError = validateViewModelMeta(launchPrefs.model);
793
+ if (modelError) return { ok: false, error: modelError };
794
+ ```
795
+
796
+ and in the config literal (~:368):
797
+
798
+ ```js
799
+ model: launchPrefs.model,
800
+ thinkingLevel: launchPrefs.thinkingLevel,
801
+ ```
802
+
803
+ 7. `adoptClaimedHost` (~:1413): same pattern — resolve before the guard (~:1429), pass `launchPrefs.model` to `validateViewModelMeta`, and set `model: launchPrefs.model, thinkingLevel: launchPrefs.thinkingLevel` in the config literal (~:1445).
804
+
805
+ - [ ] **Step 6: Run the new tests to verify they pass**
806
+
807
+ Run: `node --test test/host-resolver.test.mjs test/service.test.mjs`
808
+ Expected: PASS — new tests green, all pre-existing tests green (the two issue-#90 tests at :717/:744 use empty session files, so their guard behavior is unchanged).
809
+
810
+ - [ ] **Step 7: Commit**
811
+
812
+ ```bash
813
+ git add src/runtime/service.mjs test/host-resolver.test.mjs test/service.test.mjs
814
+ git commit -m "fix: leave model/thinking to session restore on host restart (issue #286)"
815
+ ```
816
+
817
+ ---
818
+
819
+ ### Task 5: Runner argv mapping assertions (A5)
820
+
821
+ **Files:**
822
+ - Test: `test/runner.integration.test.mjs` (extend; no runner code changes)
823
+
824
+ **Interfaces:**
825
+ - Consumes: existing `makeConfig`/`FAKE_PI` harness; `launchRun` from `../src/core/launch.mjs`; the `worker_spawn` diagnostic (already carries `redactWorkerArgs(args)` — `--model` is not redacted).
826
+ - Produces: nothing (pure test coverage).
827
+
828
+ - [ ] **Step 1: Add the argv-mapping test**
829
+
830
+ In `test/runner.integration.test.mjs` (after the existing `makeConfig` helper; imports `readDiagnostics` from `../src/core/diagnostics.mjs` — add if missing):
831
+
832
+ ```js
833
+ test("worker argv carries --model/--thinking only when configured (issue #286)", { timeout: 20000 }, async () => {
834
+ const root = mkdtempSync(join(tmpdir(), "agentview-argv-"));
835
+ try {
836
+ await startCoordinator(root);
837
+ const meta = createView(root, { id: "v1", name: "argv", cwd: root });
838
+ const base = { root, viewId: "v1", runId: "run-argv", kind: "reply", sessionFile: meta.sessionFile, cwd: root, prompt: "do it", piCommand: process.execPath, piArgsPrefix: [FAKE_PI] };
839
+
840
+ // Null prefs (restorable session) → no flags in argv.
841
+ const nullCfg = { ...base, runId: "run-argv-null", model: null, thinkingLevel: null };
842
+ launchRun(root, nullCfg, { runnerScript: RUNNER });
843
+ await waitFor(() => readStatus(root, "v1")?.runId === "run-argv-null" && readStatus(root, "v1")?.processState !== "alive");
844
+ const nullSpawn = readDiagnostics(root, "v1").find((d) => d.code === "worker_spawn" && d.runId === "run-argv-null");
845
+ assert.ok(nullSpawn, "worker_spawn diagnostic recorded");
846
+ assert.ok(!nullSpawn.details.args.includes("--model"), "null model → no --model flag");
847
+ assert.ok(!nullSpawn.details.args.includes("--thinking"), "null thinking → no --thinking flag");
848
+
849
+ // Configured values → flags present (proves the mapping direction).
850
+ const setCfg = { ...base, runId: "run-argv-set", model: "prov/picked-b", thinkingLevel: "high" };
851
+ launchRun(root, setCfg, { runnerScript: RUNNER });
852
+ await waitFor(() => readStatus(root, "v1")?.runId === "run-argv-set" && readStatus(root, "v1")?.processState !== "alive");
853
+ const setSpawn = readDiagnostics(root, "v1").find((d) => d.code === "worker_spawn" && d.runId === "run-argv-set");
854
+ assert.ok(setSpawn, "worker_spawn diagnostic recorded");
855
+ const args = setSpawn.details.args;
856
+ assert.ok(args.includes("--model") && args[args.indexOf("--model") + 1] === "prov/picked-b", "model flag passed through");
857
+ assert.ok(args.includes("--thinking") && args[args.indexOf("--thinking") + 1] === "high", "thinking flag passed through");
858
+ } finally {
859
+ await killDetached(readPid(root, "v1")?.pid ?? null);
860
+ rmSync(root, { recursive: true, force: true });
861
+ }
862
+ });
863
+ ```
864
+
865
+ (Adapt helper names to what the file already exports/uses — `readStatus`, `readPid`, `startCoordinator`, `waitFor`, `killDetached`, `RUNNER`, `FAKE_PI` all exist in this file; if `readPid` returns a different shape, follow the file's own kill pattern from other tests.)
866
+
867
+ - [ ] **Step 2: Run to verify it passes (code already correct — this pins it)**
868
+
869
+ Run: `node --test test/runner.integration.test.mjs`
870
+ Expected: PASS — the new test and all existing runner tests.
871
+
872
+ - [ ] **Step 3: Commit**
873
+
874
+ ```bash
875
+ git add test/runner.integration.test.mjs
876
+ git commit -m "test: pin worker argv model/thinking flag mapping (issue #286)"
877
+ ```
878
+
879
+ ---
880
+
881
+ ### Task 6: Full verification gate (A0–A5 总闸)
882
+
883
+ **Files:** none (verification only)
884
+
885
+ - [ ] **Step 1: Full suite + typecheck + coverage + pack**
886
+
887
+ Run: `npm run verify`
888
+ Expected: typecheck clean; all tests pass (including perf gate and coverage thresholds lines 85 / funcs 80 / branches 70); `pack:dry` clean. New test files count toward coverage of the new modules — if the branches threshold drops because `session-entries`/`session-launch-prefs` have uncovered error paths, add the missing case to the owning task's test file rather than loosening thresholds.
889
+
890
+ - [ ] **Step 2: Cross-check acceptance matrix against evidence**
891
+
892
+ For each of A0–A5, confirm the specific command above ran green in Step 1's output (A0/A1/A2/A5 via their `node --test` files inside the suite; A3/A4 via `test/service.test.mjs` + `test/host-resolver.test.mjs`). Record U1/U2 as `pending` (user verification, post-merge).
893
+
894
+ - [ ] **Step 3: No commit needed** — Task 6 produces evidence only.