gentle-pi 4.6.0 → 4.7.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 (290) hide show
  1. package/README.md +10 -11
  2. package/assets/agents/gentle-ai-explore.md +1 -0
  3. package/assets/agents/gentle-ai-verify.md +5 -2
  4. package/assets/agents/gentle-ai-worker.md +3 -0
  5. package/assets/agents/jd-fix-agent.md +1 -0
  6. package/assets/agents/jd-judge-a.md +1 -0
  7. package/assets/agents/jd-judge-b.md +1 -0
  8. package/assets/design-canvas/canvas.css +13 -1
  9. package/assets/design-canvas/canvas.js +11 -2
  10. package/assets/install-wizard/wizard.js +1 -0
  11. package/assets/migrations/agent-body-history.json +16 -1
  12. package/assets/orchestrator-delegation-reference.md +4 -4
  13. package/assets/orchestrator-delegation.md +1 -1
  14. package/assets/orchestrator-full-delegation-card.md +65 -0
  15. package/assets/orchestrator-full-delegation.md +34 -0
  16. package/assets/orchestrator-memory.md +3 -3
  17. package/assets/orchestrator-prompts.md +1 -1
  18. package/assets/orchestrator-skills.md +1 -1
  19. package/assets/orchestrator-verification.md +7 -5
  20. package/assets/orchestrator.md +3 -3
  21. package/bin/gentle-shell.mjs +164 -56
  22. package/docs/agent-status.md +61 -0
  23. package/docs/bundled-install.md +7 -5
  24. package/docs/delegated-verification.md +29 -7
  25. package/docs/gentle-agents-activity.md +14 -0
  26. package/docs/gentle-shell.md +54 -16
  27. package/docs/install-wizard.md +1 -1
  28. package/docs/permission-modes.md +9 -4
  29. package/docs/readme-reference.md +75 -30
  30. package/docs/render-cache-performance.md +11 -1
  31. package/docs/review-coordinator.md +33 -0
  32. package/docs/review-request-context.md +19 -0
  33. package/docs/review-windows-acl.md +18 -0
  34. package/docs/voice.md +6 -3
  35. package/docs/yolo-mode.md +5 -5
  36. package/extensions/ask-user-choice.ts +1 -0
  37. package/extensions/ask-user-question.ts +1 -0
  38. package/extensions/child-safety.ts +3 -0
  39. package/extensions/gentle-agent-status.ts +99 -0
  40. package/extensions/gentle-agents.ts +326 -34
  41. package/extensions/gentle-ai.ts +1496 -454
  42. package/extensions/gentle-shell.ts +293 -63
  43. package/extensions/gentle-todo.ts +18 -2
  44. package/extensions/gentle-tps.ts +48 -0
  45. package/extensions/quiet-tools.ts +38 -8
  46. package/extensions/skill-registry.ts +175 -18
  47. package/extensions/startup-banner.ts +30 -3
  48. package/lib/agent-profile-pin.ts +3 -3
  49. package/lib/agent-profiles.ts +160 -2
  50. package/lib/agent-status.ts +105 -0
  51. package/lib/agents-config.ts +46 -0
  52. package/lib/agents-history.ts +24 -5
  53. package/lib/agents-messaging.ts +47 -5
  54. package/lib/agents-runner.ts +183 -12
  55. package/lib/auto-permission-runtime.ts +1 -1
  56. package/lib/bounded-writer-admission.ts +13 -1
  57. package/lib/card-content-policy.ts +8 -6
  58. package/lib/command-palette.ts +133 -17
  59. package/lib/context-backstop.ts +14 -5
  60. package/lib/destructive-command-guard.ts +48 -4
  61. package/lib/execution-surface-guard.ts +20 -0
  62. package/lib/exploration-budget.ts +4 -2
  63. package/lib/gentle-ai-binary.ts +1 -1
  64. package/lib/gentle-design.ts +3 -0
  65. package/lib/gentle-shell-bundled.ts +6 -19
  66. package/lib/gentle-shell-launcher.ts +43 -8
  67. package/lib/herdr-activity.ts +14 -2
  68. package/lib/herdr-busy.ts +45 -0
  69. package/lib/image-attachments.ts +33 -0
  70. package/lib/image-disk-cache.ts +137 -0
  71. package/lib/inprocess-reviewer.ts +270 -140
  72. package/lib/jobs-view.ts +198 -11
  73. package/lib/model-routing-authority.ts +22 -4
  74. package/lib/native-choice-list.ts +20 -2
  75. package/lib/native-review-cli.ts +96 -19
  76. package/lib/orchestrator-mode-policy.ts +105 -0
  77. package/lib/questionnaire/questionnaire-view.ts +105 -12
  78. package/lib/rdd-mode-control.ts +32 -0
  79. package/lib/reply-language-anchor.ts +104 -0
  80. package/lib/review-blocker.ts +92 -0
  81. package/lib/review-candidate-symlink-scan.ts +136 -0
  82. package/lib/review-candidate-view-owner.ts +81 -44
  83. package/lib/review-continuation-registry.ts +99 -0
  84. package/lib/review-coordinator.ts +163 -0
  85. package/lib/review-failure-facts.ts +49 -0
  86. package/lib/review-host-relay.ts +46 -10
  87. package/lib/review-integration-v2.ts +7 -1
  88. package/lib/review-relay-phase-timing.ts +45 -0
  89. package/lib/review-start-context.ts +17 -0
  90. package/lib/session-profile-freeze.ts +4 -2
  91. package/lib/shell-bar.ts +140 -58
  92. package/lib/shell-changes.ts +2 -0
  93. package/lib/shell-panel.ts +17 -3
  94. package/lib/shell-sidebar-layout.ts +112 -40
  95. package/lib/shell-sidebar.ts +7 -0
  96. package/lib/shell-todo.ts +10 -3
  97. package/lib/verifier-admission.ts +1 -1
  98. package/lib/visual-customization-policy.ts +36 -16
  99. package/lib/visual-customize-view.ts +216 -21
  100. package/lib/visual-layout-preview.ts +9 -5
  101. package/lib/visual-profiles.ts +2 -2
  102. package/lib/windows-session-transport.ts +53 -2
  103. package/lib/yolo-session-policy.ts +40 -15
  104. package/package.json +2 -1
  105. package/runtime/gentle-ai-binary.mjs +1 -1
  106. package/runtime/gentle-shell-bundled.mjs +6 -19
  107. package/runtime/gentle-shell-launcher.mjs +42 -7
  108. package/runtime/native-review-cli.mjs +93 -16
  109. package/runtime/review-integration-v2.mjs +7 -1
  110. package/scripts/build-full-delegation-card.mjs +175 -0
  111. package/scripts/bundled-install.mjs +38 -8
  112. package/scripts/download-progress.mjs +68 -0
  113. package/scripts/gentle-ai-installer.mjs +41 -18
  114. package/scripts/gentle-ai-proxy.mjs +294 -0
  115. package/scripts/install-gentle-ai.mjs +14 -1
  116. package/scripts/installer-preflight.mjs +5 -5
  117. package/scripts/installer-runner.mjs +27 -12
  118. package/scripts/installer-server.mjs +8 -7
  119. package/scripts/render-cache-host.mjs +72 -0
  120. package/scripts/render-cache-performance-worker.mjs +5 -4
  121. package/scripts/render-cache-performance.mjs +6 -1
  122. package/scripts/run-test-suite.mjs +40 -28
  123. package/scripts/verify-package-files.mjs +12 -2
  124. package/scripts/voice-worker.cjs +32 -6
  125. package/skills/design/SKILL.md +11 -8
  126. package/skills/gentle-ai/SKILL.md +2 -2
  127. package/skills/gentle-ui-design/SKILL.md +46 -0
  128. package/skills/gentle-ui-design/references/adaptive-interfaces.md +46 -0
  129. package/skills/gentle-ui-design/references/browse-and-compare.md +62 -0
  130. package/skills/gentle-ui-design/references/composition-and-feedback.md +56 -0
  131. package/skills/gentle-ui-design/references/task-and-content.md +60 -0
  132. package/skills/skill-registry/SKILL.md +4 -2
  133. package/skills/work-unit-commits/SKILL.md +6 -7
  134. package/tests/agent-home.test.ts +28 -9
  135. package/tests/agent-profiles-workflow.test.ts +163 -0
  136. package/tests/agent-risk-escalation.test.ts +1 -1
  137. package/tests/agent-status.test.ts +143 -0
  138. package/tests/agents-config.test.ts +96 -0
  139. package/tests/agents-history.test.ts +31 -0
  140. package/tests/agents-jobs-frames.test.ts +93 -0
  141. package/tests/agents-prompt-lifecycle-runtime.test.ts +376 -0
  142. package/tests/agents-runner-drain.test.ts +193 -0
  143. package/tests/agents-runner.test.ts +178 -2
  144. package/tests/append-system-prompt-route.test.ts +4 -1
  145. package/tests/ask-user-choice.test.ts +4 -3
  146. package/tests/ask-user-question.test.ts +97 -0
  147. package/tests/auto-permission-runtime.test.ts +1 -1
  148. package/tests/autonomous-guard.test.ts +346 -10
  149. package/tests/bounded-stop-contract.test.ts +43 -3
  150. package/tests/bridge-cost.test.ts +19 -4
  151. package/tests/bundled-install.test.ts +30 -5
  152. package/tests/card-content-policy.test.ts +3 -3
  153. package/tests/chained-pr-skill.test.ts +8 -6
  154. package/tests/child-safety.test.ts +11 -0
  155. package/tests/codegraph-tools.test.ts +11 -5
  156. package/tests/command-palette.test.ts +284 -1
  157. package/tests/delegate-for-reason-contract.test.ts +3 -3
  158. package/tests/design-canvas-assets.test.ts +185 -2
  159. package/tests/destructive-command-guard.test.ts +52 -0
  160. package/tests/download-progress.test.ts +71 -0
  161. package/tests/execution-surface-guard.test.ts +55 -0
  162. package/tests/fixtures/primary-session-prompt/gentleman.golden.md +9 -5
  163. package/tests/fixtures/proxy-tls/proxy.crt +19 -0
  164. package/tests/fixtures/proxy-tls/proxy.key +28 -0
  165. package/tests/fixtures/session-profile-v1/gentle-ai-reviewer.ts +89 -0
  166. package/tests/fixtures/session-profile-v1/replay.ts +53 -6
  167. package/tests/full-delegation-closure.test.ts +131 -0
  168. package/tests/full-delegation-notices.test.ts +76 -0
  169. package/tests/generic-agent-tools.test.ts +3 -3
  170. package/tests/gentle-agent-status.test.ts +74 -0
  171. package/tests/gentle-agents-child-jobs.test.ts +237 -0
  172. package/tests/gentle-agents.test.ts +1070 -12
  173. package/tests/gentle-ai-binary.test.ts +3 -1
  174. package/tests/gentle-ai-elapsed-store.test.ts +19 -0
  175. package/tests/gentle-ai-exploration-budget.test.ts +18 -2
  176. package/tests/gentle-ai-installer.test.ts +134 -51
  177. package/tests/gentle-ai-proxy.test.ts +434 -0
  178. package/tests/gentle-ai.test.ts +113 -38
  179. package/tests/gentle-design.test.ts +21 -0
  180. package/tests/gentle-herdr-activity.test.ts +9 -6
  181. package/tests/gentle-shell-bin.test.ts +123 -0
  182. package/tests/gentle-shell-bundled.test.ts +207 -31
  183. package/tests/gentle-shell-launcher.test.ts +77 -10
  184. package/tests/gentle-shell.test.ts +899 -59
  185. package/tests/gentle-todo.test.ts +19 -2
  186. package/tests/gentle-tps.test.ts +123 -0
  187. package/tests/gentle-ui-design-skill.test.ts +59 -0
  188. package/tests/herdr-busy.test.ts +59 -0
  189. package/tests/herdr-task-summary-policy.test.ts +8 -4
  190. package/tests/image-disk-cache.test.ts +163 -0
  191. package/tests/independent-recovery-delivery.test.ts +83 -0
  192. package/tests/inprocess-reviewer.test.ts +176 -4
  193. package/tests/installer-posix-bootstrap.test.ts +1 -1
  194. package/tests/installer-preflight.test.ts +5 -4
  195. package/tests/installer-runner.test.ts +79 -44
  196. package/tests/installer-server.test.ts +14 -11
  197. package/tests/jobs-view.test.ts +260 -6
  198. package/tests/modal-mouse-boundaries.test.ts +136 -0
  199. package/tests/model-routing-authority.test.ts +178 -2
  200. package/tests/native-choice-list.test.ts +77 -2
  201. package/tests/native-review-capability-contract.test.ts +7 -1
  202. package/tests/native-review-cli.test.ts +269 -1
  203. package/tests/no-self-pause-contract.test.ts +4 -1
  204. package/tests/odd-routing-canonical-ratchet.test.ts +3 -3
  205. package/tests/orchestrator-budget.test.ts +7 -2
  206. package/tests/orchestrator-delegation-mode.test.ts +153 -0
  207. package/tests/orchestrator-mode-policy.test.ts +175 -0
  208. package/tests/orchestrator-prompt-budget.test.ts +3 -1
  209. package/tests/orchestrator-rdd-ownership.test.ts +2 -2
  210. package/tests/package-manifest.test.ts +11 -9
  211. package/tests/permission-allowlist.test.ts +202 -0
  212. package/tests/pi-update-launcher.test.ts +8 -0
  213. package/tests/pnpm-workspace-config.test.ts +58 -0
  214. package/tests/primary-session-prompt.test.ts +13 -0
  215. package/tests/profile-pin.test.ts +29 -2
  216. package/tests/profile-tier-footer.test.ts +5 -0
  217. package/tests/profiles-panel-delegation-mode.test.ts +422 -0
  218. package/tests/questionnaire-view.test.ts +115 -0
  219. package/tests/quiet-bash-runtime.test.ts +1 -1
  220. package/tests/quiet-tool-rendering.test.ts +48 -0
  221. package/tests/rdd-aware-verification-contract.test.ts +16 -11
  222. package/tests/rdd-customize.test.ts +287 -0
  223. package/tests/rdd-mode-cache.test.ts +450 -0
  224. package/tests/rdd-mode-control.test.ts +407 -0
  225. package/tests/rdd-mode-scope-regression.test.ts +137 -0
  226. package/tests/rdd-off-independent-regression.test.ts +69 -0
  227. package/tests/rdd-status-line.test.ts +18 -0
  228. package/tests/render-cache-performance.test.ts +171 -2
  229. package/tests/reply-language-anchor.test.ts +173 -0
  230. package/tests/review-agent-end-preflight.test.ts +1 -1
  231. package/tests/review-blocker.test.ts +193 -0
  232. package/tests/review-candidate-owner-retry.test.ts +1 -1
  233. package/tests/review-candidate-symlink-scan.test.ts +157 -0
  234. package/tests/review-candidate-view.test.ts +1 -1
  235. package/tests/review-candidate-windows-boundary.test.ts +131 -0
  236. package/tests/review-candidate-windows-probe.test.ts +63 -0
  237. package/tests/review-committed-restart-ack.test.ts +129 -0
  238. package/tests/review-continuation-registry.test.ts +76 -0
  239. package/tests/review-controller-native-routing.test.ts +261 -5
  240. package/tests/review-controller-workspace-root.test.ts +230 -3
  241. package/tests/review-controller.test.ts +96 -11
  242. package/tests/review-coordinator-runtime.test.ts +117 -0
  243. package/tests/review-coordinator.test.ts +195 -0
  244. package/tests/review-failure-facts.test.ts +87 -0
  245. package/tests/review-host-relay-routing.test.ts +258 -4
  246. package/tests/review-host-relay.test.ts +39 -0
  247. package/tests/review-integration-v2.test.ts +46 -3
  248. package/tests/review-json-arguments.test.ts +65 -10
  249. package/tests/review-last-event-closure.test.ts +68 -0
  250. package/tests/review-loadout-rdd-off-sdk.test.ts +65 -31
  251. package/tests/review-owner-identity.test.ts +60 -24
  252. package/tests/review-relay-phase-timing.test.ts +128 -0
  253. package/tests/review-relay-transport-agent.test.ts +12 -2
  254. package/tests/review-reviewer-evidence.test.ts +183 -0
  255. package/tests/review-risk-assessment.test.ts +74 -3
  256. package/tests/review-session-standing-permission-controller.test.ts +21 -1
  257. package/tests/review-start-context.test.ts +19 -0
  258. package/tests/review-tool-prose-budget.test.ts +121 -0
  259. package/tests/run-test-suite.test.ts +122 -1
  260. package/tests/runtime-harness.mjs +4 -1
  261. package/tests/sensitive-path-tools.test.ts +181 -5
  262. package/tests/session-profile-append-controller-pi.test.ts +60 -31
  263. package/tests/session-profile-binding.test.ts +19 -1
  264. package/tests/session-profile-disk-reader-pi.test.ts +58 -16
  265. package/tests/session-profile-v1-compat.test.ts +35 -1
  266. package/tests/shell-bar.test.ts +186 -42
  267. package/tests/shell-panel.test.ts +50 -22
  268. package/tests/shell-sidebar-fullscreen.test.ts +5 -5
  269. package/tests/shell-sidebar-layout.test.ts +294 -23
  270. package/tests/shell-sidebar-scroll-benchmark.test.ts +1 -1
  271. package/tests/shell-surface-transparent.test.ts +89 -0
  272. package/tests/shell-todo.test.ts +12 -0
  273. package/tests/skill-registry.test.ts +838 -5
  274. package/tests/startup-banner.test.ts +152 -1
  275. package/tests/startup-home-repo.test.ts +2 -0
  276. package/tests/support/review-coordinator-runtime.ts +69 -0
  277. package/tests/task-size-routing-contract.test.ts +5 -3
  278. package/tests/verifier-admission.test.ts +49 -0
  279. package/tests/verify-first-launch-contract.test.ts +78 -3
  280. package/tests/visual-customization-policy.test.ts +39 -6
  281. package/tests/visual-customize-view.test.ts +573 -9
  282. package/tests/visual-layout-preview.test.ts +15 -1
  283. package/tests/visual-profiles.test.ts +11 -0
  284. package/tests/voice-worker.test.ts +73 -2
  285. package/tests/windows-session-transport.test.ts +126 -0
  286. package/tests/work-continuity-contract.test.ts +28 -0
  287. package/tests/writer-feature-document-admission.test.ts +92 -0
  288. package/tests/yolo-customize.test.ts +27 -4
  289. package/tests/yolo-mode.test.ts +23 -18
  290. package/tests/yolo-session-policy.test.ts +270 -1
@@ -1,8 +1,9 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
- import { visibleWidth } from "@earendil-works/pi-tui";
3
+ import { TuiAltScreen, visibleWidth, type Terminal, type TuiMouseEvent } from "@earendil-works/pi-tui";
4
+ import { loadThemeFromPath } from "../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
4
5
  import type { JobRecord } from "../lib/background-jobs.ts";
5
- import { JobsView } from "../lib/jobs-view.ts";
6
+ import { JobsView, type JobsViewDeps } from "../lib/jobs-view.ts";
6
7
  import { stripAnsi } from "../lib/terminal-theme.ts";
7
8
 
8
9
  const theme = { fg: (_role: string, text: string) => text };
@@ -22,12 +23,12 @@ function job(overrides: Partial<JobRecord> & Pick<JobRecord, "id">): JobRecord {
22
23
  };
23
24
  }
24
25
 
25
- function harness(jobs: JobRecord[], rows = 14) {
26
+ function harness(jobs: JobRecord[], rows = 14, colors: JobsViewDeps["theme"] = theme) {
26
27
  const stopped: string[] = [];
27
28
  let closed = 0;
28
29
  let renders = 0;
29
30
  const view = new JobsView({
30
- theme,
31
+ theme: colors,
31
32
  rows: () => rows,
32
33
  jobs: () => jobs,
33
34
  now: () => 125_000,
@@ -35,10 +36,27 @@ function harness(jobs: JobRecord[], rows = 14) {
35
36
  onClose: () => { closed += 1; },
36
37
  requestRender: () => { renders += 1; },
37
38
  });
38
- const screen = (width = 100) => view.render(width).map(stripAnsi);
39
- return { view, screen, stopped, closed: () => closed, renders: () => renders };
39
+ const interaction = view;
40
+ const frame = (width = 100) => interaction.render(width);
41
+ const screen = (width = 100) => frame(width).map(stripAnsi);
42
+ return { view, interaction, frame, screen, stopped, closed: () => closed, renders: () => renders, setRows: (next: number) => { rows = next; } };
40
43
  }
41
44
 
45
+ function mouse(frame: string[], text: string, type: TuiMouseEvent["type"] = "click", button: TuiMouseEvent["button"] = type === "move" ? "none" : "left"): TuiMouseEvent {
46
+ const lines = frame.map(stripAnsi);
47
+ const y = lines.findIndex((line) => line.includes(text));
48
+ assert.ok(y >= 0, `Missing ${text}:\n${lines.join("\n")}`);
49
+ const x = visibleWidth(lines[y]!.slice(0, lines[y]!.indexOf(text)));
50
+ return { type, button, x, y, screenX: x, screenY: y, width: visibleWidth(lines[0]!), height: lines.length, shift: false, alt: false, ctrl: false };
51
+ }
52
+
53
+ function click(h: ReturnType<typeof harness>, frame: string[], text: string): void {
54
+ h.interaction.handleMouse(mouse(frame, text, "press"));
55
+ h.interaction.handleMouse(mouse(frame, text));
56
+ }
57
+
58
+ const gentleTheme = loadThemeFromPath("themes/Gentle.json", "truecolor");
59
+
42
60
  test("the split view lists this session's jobs beside the selected job's details and output tail", () => {
43
61
  const h = harness([
44
62
  job({ id: "job-1", label: "CI for PR 1834", command: "gh run watch 42 --exit-status", tail: ["check lint: pass", "check test: pending"] }),
@@ -158,3 +176,239 @@ test("a monitor shows its kind and event count in the list and details", () => {
158
176
  assert.match(text, /Status +running · .* · 3 events/);
159
177
  } finally { h.view.dispose(); }
160
178
  });
179
+
180
+ test("pointer hover uses the shared warning role without selecting, stopping or repeatedly redrawing", () => {
181
+ const h = harness([job({ id: "first" }), job({ id: "second" })], 14, gentleTheme);
182
+ try {
183
+ let frame = h.frame();
184
+ const event = mouse(frame, "second", "move");
185
+ const before = h.renders();
186
+ assert.equal(h.interaction.handleMouse(event)?.render, true);
187
+ frame = h.frame();
188
+ const hovered = frame[event.y]!;
189
+ assert.ok(hovered.includes(gentleTheme.getFgAnsi("warning")), "the rendered job row uses the warning token");
190
+ assert.match(frame.map(stripAnsi).join("\n"), /› ◐ first/);
191
+ assert.deepEqual(h.stopped, []);
192
+ assert.equal(h.closed(), 0);
193
+ assert.equal(h.interaction.handleMouse(event)?.render, false, "the same target does not redraw");
194
+ assert.equal(h.renders(), before);
195
+ const blank = { ...event, x: 3, screenX: 3, y: 7, screenY: 7 };
196
+ h.interaction.handleMouse(blank);
197
+ assert.equal(h.renders(), before + 1, "moving to a blank row clears the hover");
198
+ assert.ok(!h.frame()[event.y]!.includes(gentleTheme.getFgAnsi("warning")));
199
+ } finally { h.view.dispose(); }
200
+ });
201
+
202
+ test("clicking a visible row selects its exact job and never implicitly stops it", () => {
203
+ const h = harness([job({ id: "first" }), job({ id: "second", tail: ["second output"] })]);
204
+ try {
205
+ let frame = h.frame();
206
+ h.interaction.handleMouse(mouse(frame, "second", "press"));
207
+ assert.match(h.screen().join("\n"), /› ◐ first/, "press alone does not select");
208
+ frame = h.frame();
209
+ h.interaction.handleMouse(mouse(frame, "second", "click", "right"));
210
+ assert.match(h.screen().join("\n"), /› ◐ first/, "right click does nothing");
211
+ frame = h.frame();
212
+ click(h, frame, "second");
213
+ assert.match(h.screen().join("\n"), /› ◐ second/);
214
+ assert.match(h.screen().join("\n"), /second output/);
215
+ assert.deepEqual(h.stopped, []);
216
+ assert.equal(h.closed(), 0);
217
+ } finally { h.view.dispose(); }
218
+ });
219
+
220
+ test("stale rows, hidden rows and invalid geometry never select or stop a different job", () => {
221
+ const jobs = [job({ id: "first", startedAt: 20 }), job({ id: "second", startedAt: 10 })];
222
+ const h = harness(jobs);
223
+ try {
224
+ const frame = h.frame();
225
+ const stale = mouse(frame, "second");
226
+ jobs.push(job({ id: "newest", startedAt: 30 }));
227
+ h.interaction.handleMouse(stale);
228
+ assert.match(h.screen().join("\n"), /› ◐ first/, "a reordered row is rejected");
229
+ const fresh = h.frame();
230
+ const title = mouse(fresh, "Jobs");
231
+ const blank = { ...title, x: 3, screenX: 3, y: 8, screenY: 8 };
232
+ h.interaction.handleMouse(title);
233
+ h.interaction.handleMouse(blank);
234
+ h.interaction.handleMouse({ ...mouse(fresh, "second"), width: 99 });
235
+ assert.match(h.screen().join("\n"), /› ◐ first/);
236
+ assert.deepEqual(h.stopped, []);
237
+ assert.equal(h.closed(), 0);
238
+ } finally { h.view.dispose(); }
239
+ });
240
+
241
+ test("the explicit stop control rechecks the rendered identity and current running status", () => {
242
+ const first = job({ id: "first" });
243
+ const second = job({ id: "second" });
244
+ const h = harness([first, second], 14, gentleTheme);
245
+ try {
246
+ let frame = h.frame();
247
+ const stop = mouse(frame, "s Stop");
248
+ h.interaction.handleMouse({ ...stop, type: "move", button: "none" });
249
+ assert.ok(h.frame()[stop.y]!.includes(gentleTheme.getFgAnsi("warning")));
250
+ assert.deepEqual(h.stopped, []);
251
+ h.interaction.handleMouse({ ...stop, type: "press" });
252
+ h.view.handleInput("j");
253
+ frame = h.frame();
254
+ h.interaction.handleMouse(mouse(frame, "s Stop"));
255
+ assert.deepEqual(h.stopped, [], "a press on first cannot stop second after selection changes");
256
+ click(h, frame, "s Stop");
257
+ assert.deepEqual(h.stopped, ["second"]);
258
+ frame = h.frame();
259
+ const staleStop = mouse(frame, "s Stop");
260
+ second.status = "exited";
261
+ h.interaction.handleMouse(staleStop);
262
+ assert.deepEqual(h.stopped, ["second"], "a finished job cannot be stopped using an old control");
263
+ assert.doesNotMatch(h.screen().at(-2)!, /s Stop/);
264
+ assert.equal(first.status, "running");
265
+ } finally { h.view.dispose(); }
266
+ });
267
+
268
+ test("narrow details/list and close controls work by click while hidden controls stay inert", () => {
269
+ const h = harness([job({ id: "first" }), job({ id: "second", command: "show second" })], 14, gentleTheme);
270
+ try {
271
+ let frame = h.frame(40);
272
+ click(h, frame, "second");
273
+ frame = h.frame(40);
274
+ assert.match(frame.map(stripAnsi).join("\n"), /show second/);
275
+ assert.doesNotMatch(frame.map(stripAnsi).join("\n"), /› ◐ second/);
276
+ const back = mouse(frame, "tab list", "move");
277
+ h.interaction.handleMouse(back);
278
+ assert.ok(h.frame(40)[back.y]!.includes(gentleTheme.getFgAnsi("warning")));
279
+ frame = h.frame(40);
280
+ click(h, frame, "tab list");
281
+ frame = h.frame(40);
282
+ assert.match(frame.map(stripAnsi).join("\n"), /› ◐ second/);
283
+ click(h, frame, "tab details");
284
+ frame = h.frame(40);
285
+ assert.match(frame.map(stripAnsi).join("\n"), /show second/);
286
+ const close = mouse(frame, "q close", "move");
287
+ h.interaction.handleMouse(close);
288
+ assert.ok(h.frame(40)[close.y]!.includes(gentleTheme.getFgAnsi("warning")));
289
+ assert.equal(h.closed(), 0, "hovering close does not close the overlay");
290
+ click(h, h.frame(40), "q close");
291
+ assert.equal(h.closed(), 1);
292
+ assert.deepEqual(h.stopped, []);
293
+ } finally { h.view.dispose(); }
294
+ });
295
+
296
+ test("very narrow details retain visible mouse back and close controls", () => {
297
+ for (const width of [12, 14, 20, 24, 30, 40]) {
298
+ const h = harness([job({ id: "first" }), job({ id: "second", command: "second detail" })]);
299
+ try {
300
+ h.frame(width);
301
+ h.view.handleInput("\t");
302
+ let frame = h.frame(width);
303
+ const footer = stripAnsi(frame.at(-2)!);
304
+ const back = footer.includes("tab list") ? "tab list" : "←";
305
+ const close = footer.includes("q close") ? "q close" : "×";
306
+ assert.ok(footer.includes(back) && footer.includes(close), `${width} columns: ${footer}`);
307
+ click(h, frame, back);
308
+ frame = h.frame(width);
309
+ const listFooter = stripAnsi(frame.at(-2)!);
310
+ assert.ok(listFooter.includes("tab details") || listFooter.includes("→"), `${width} columns: ${listFooter}`);
311
+ assert.deepEqual(h.stopped, []);
312
+ assert.equal(h.closed(), 0);
313
+ } finally { h.view.dispose(); }
314
+ }
315
+ });
316
+
317
+ test("a changed row under a pending press cannot select the replacement", () => {
318
+ const jobs = [job({ id: "first", startedAt: 20 }), job({ id: "second", startedAt: 10 })];
319
+ const h = harness(jobs);
320
+ try {
321
+ const before = h.frame();
322
+ const row = mouse(before, "second");
323
+ h.interaction.handleMouse({ ...row, type: "press" });
324
+ jobs.push(job({ id: "newest", startedAt: 30 }));
325
+ h.frame();
326
+ h.interaction.handleMouse(row);
327
+ assert.match(h.screen().join("\n"), /› ◐ first/);
328
+ assert.deepEqual(h.stopped, []);
329
+ assert.equal(h.closed(), 0);
330
+ } finally { h.view.dispose(); }
331
+ });
332
+
333
+ test("scrolled lists target only the visible job identities and fallback close remains clickable", () => {
334
+ const h = harness(Array.from({ length: 6 }, (_, index) => job({ id: `job-${index}`, startedAt: 6 - index })), 6);
335
+ try {
336
+ const stale = mouse(h.frame(), "job-1");
337
+ for (let index = 0; index < 4; index += 1) h.view.handleInput("j");
338
+ h.interaction.handleMouse(stale);
339
+ let frame = h.frame();
340
+ assert.match(frame.map(stripAnsi).join("\n"), /› ◐ job-4/);
341
+ assert.ok(!frame.map(stripAnsi).some((line) => line.includes("job-0")));
342
+ click(h, frame, "job-3");
343
+ assert.match(h.screen().join("\n"), /› ◐ job-3/);
344
+ assert.deepEqual(h.stopped, []);
345
+ frame = h.frame(8);
346
+ click(h, frame, "×");
347
+ assert.equal(h.closed(), 1);
348
+ } finally { h.view.dispose(); }
349
+ });
350
+
351
+ test("resize, invalidation and disposal discard pointer geometry and hover", () => {
352
+ const h = harness([job({ id: "first" }), job({ id: "second" })], 14, gentleTheme);
353
+ try {
354
+ let frame = h.frame();
355
+ const row = mouse(frame, "second");
356
+ h.interaction.handleMouse({ ...row, type: "move", button: "none" });
357
+ h.setRows(8);
358
+ h.interaction.handleMouse(row);
359
+ assert.deepEqual(h.stopped, []);
360
+ frame = h.frame(80);
361
+ assert.ok(!frame.join("\n").includes(gentleTheme.getFgAnsi("warning")));
362
+ assert.match(frame.map(stripAnsi).join("\n"), /› ◐ first/);
363
+ const fresh = mouse(frame, "second");
364
+ h.interaction.handleMouse({ ...fresh, type: "move", button: "none" });
365
+ assert.ok(h.frame(80)[fresh.y]!.includes(gentleTheme.getFgAnsi("warning")));
366
+ h.view.invalidate();
367
+ h.interaction.handleMouse(fresh);
368
+ frame = h.frame(80);
369
+ assert.ok(!frame.join("\n").includes(gentleTheme.getFgAnsi("warning")));
370
+ assert.match(frame.map(stripAnsi).join("\n"), /› ◐ first/);
371
+ h.interaction.handleMouse({ ...fresh, type: "move", button: "none" });
372
+ h.view.dispose();
373
+ h.interaction.handleMouse(fresh);
374
+ assert.ok(!h.frame(80).join("\n").includes(gentleTheme.getFgAnsi("warning")));
375
+ assert.deepEqual(h.stopped, []);
376
+ assert.equal(h.closed(), 0);
377
+ } finally { h.view.dispose(); }
378
+ });
379
+
380
+ test("real centered TuiAltScreen SGR events hover, select and stop the visible job", () => {
381
+ let input: ((data: string) => void) | undefined;
382
+ const terminal: Terminal = {
383
+ start(onInput) { input = onInput; }, stop() {}, async drainInput() {}, write() {}, get columns() { return 120; }, get rows() { return 30; }, get kittyProtocolActive() { return false; }, moveBy() {}, hideCursor() {}, showCursor() {}, clearLine() {}, clearFromCursor() {}, clearScreen() {}, setTitle() {}, setProgress() {}, setProgramStatus() {},
384
+ };
385
+ const h = harness([job({ id: "first" }), job({ id: "second" })], 14, gentleTheme);
386
+ const tui = new TuiAltScreen(terminal, false, undefined, { mouse: true });
387
+ const overlay = tui.showOverlay(h.interaction, { anchor: "center", width: 80, maxHeight: 14 });
388
+ tui.start();
389
+ tui.renderNow(true);
390
+ try {
391
+ const bounds = overlay.getBounds();
392
+ assert.ok(bounds && bounds.col > 0 && bounds.row > 0);
393
+ let frame = h.frame(80);
394
+ const row = mouse(frame, "second");
395
+ const x = bounds.col + row.x + 1, y = bounds.row + row.y + 1;
396
+ input?.(`\x1b[<35;${x};${y}M`);
397
+ frame = h.frame(80);
398
+ assert.ok(frame[row.y]!.includes(gentleTheme.getFgAnsi("warning")));
399
+ assert.match(frame.map(stripAnsi).join("\n"), /› ◐ first/);
400
+ input?.("\x1b[<35;1;1M");
401
+ assert.ok(h.frame(80)[row.y]!.includes(gentleTheme.getFgAnsi("warning")), "native overlay dispatch does not deliver outside-card motion");
402
+ input?.(`\x1b[<0;${x};${y}M`);
403
+ input?.(`\x1b[<0;${x};${y}m`);
404
+ tui.renderNow(true);
405
+ frame = h.frame(80);
406
+ assert.match(frame.map(stripAnsi).join("\n"), /› ◐ second/);
407
+ assert.deepEqual(h.stopped, []);
408
+ const stop = mouse(frame, "s Stop");
409
+ const sx = bounds.col + stop.x + 1, sy = bounds.row + stop.y + 1;
410
+ input?.(`\x1b[<0;${sx};${sy}M`);
411
+ input?.(`\x1b[<0;${sx};${sy}m`);
412
+ assert.deepEqual(h.stopped, ["second"]);
413
+ } finally { tui.stop(); h.view.dispose(); }
414
+ });
@@ -0,0 +1,136 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { createHash } from "node:crypto";
4
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { visibleWidth, type TuiMouseEvent } from "@earendil-works/pi-tui";
8
+ import { JobsView } from "../lib/jobs-view.ts";
9
+ import type { JobRecord } from "../lib/background-jobs.ts";
10
+ import { VisualCustomizeView } from "../lib/visual-customize-view.ts";
11
+ import { stripAnsi } from "../lib/terminal-theme.ts";
12
+ const theme = { fg: (role: string, text: string) => role === "warning" ? `\x1b[33m${text}\x1b[39m` : text };
13
+ const tick = () => new Promise<void>(resolve => setImmediate(resolve));
14
+ function at(lines: string[], label: string, type: TuiMouseEvent["type"], delta = 0): TuiMouseEvent {
15
+ const plain = lines.map(stripAnsi);
16
+ const y = plain.findIndex(line => line.includes(label));
17
+ assert.ok(y >= 0, label);
18
+ const x = visibleWidth(plain[y]!.slice(0, plain[y]!.lastIndexOf(label))) + delta;
19
+ return { type, button: type === "move" ? "none" : "left", x, y, screenX: x, screenY: y,
20
+ width: visibleWidth(plain[0]!), height: lines.length, shift: false, alt: false, ctrl: false };
21
+ }
22
+ const record = (id: string, startedAt: number): JobRecord => ({ id, startedAt, kind: "command", label: id, command: `run ${id}`, cwd: "/repo", ownerSessionId: "session", outputPath: `/isolated/${id}.log`, status: "running", tail: [] });
23
+ // S2/S3: adversarial live identity changes, with and without intervening paint.
24
+ test("pending Stop never transfers across removal, reorder, or completion", () => {
25
+ for (const mutation of ["remove", "reorder", "complete", "replace-record"] as const)
26
+ for (const repaint of [false, true]) {
27
+ let jobs = [record("first", 20), record("second", 10)];
28
+ const stopped: JobRecord[] = [];
29
+ const view = new JobsView({ theme, rows: () => 14, jobs: () => jobs, now: () => 100, onStop: j => stopped.push(j), onClose() { }, requestRender() { } });
30
+ try {
31
+ const first = jobs[0]!;
32
+ const frame = view.render(100);
33
+ view.handleMouse(at(frame, "s Stop", "move"));
34
+ assert.deepEqual(stopped, []);
35
+ view.handleMouse(at(frame, "s Stop", "press"));
36
+ if (mutation === "remove")
37
+ jobs.shift();
38
+ if (mutation === "reorder")
39
+ jobs.unshift(record("newest", 30));
40
+ if (mutation === "complete")
41
+ first.status = "stopped";
42
+ if (mutation === "replace-record")
43
+ jobs[0] = { ...first, tail: ["new live output"] };
44
+ if (repaint)
45
+ view.render(100);
46
+ view.handleMouse(at(frame, "s Stop", "click"));
47
+ if (mutation === "replace-record")
48
+ assert.deepEqual(stopped, [jobs[0]], "stop must receive the live record, not rendered snapshot");
49
+ else if (mutation === "reorder" && repaint)
50
+ assert.deepEqual(stopped, [first], "a repaint can preserve the same explicit job identity");
51
+ else
52
+ assert.deepEqual(stopped, [], `${mutation}, repaint=${repaint}`);
53
+ if (mutation === "remove") {
54
+ const fresh = view.render(100);
55
+ view.handleMouse(at(fresh, "s Stop", "press"));
56
+ view.handleMouse(at(fresh, "s Stop", "click"));
57
+ assert.deepEqual(stopped, [jobs[0]], "a new deliberate press can stop the remaining running job");
58
+ }
59
+ }
60
+ finally {
61
+ view.dispose();
62
+ }
63
+ }
64
+ });
65
+ // S1/S2: all consent cells remain explicit after orange paint and rerender.
66
+ test("hovered inline yes/cancel spans preserve exact stored bytes until deliberate consent", async (t) => {
67
+ const dir = mkdtempSync(join(tmpdir(), "hover-consent-"));
68
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
69
+ for (const width of [36, 80, 140])
70
+ for (const label of ["y yes", "cancel"])
71
+ for (let delta = -1; delta <= label.length; delta++) {
72
+ const path = join(dir, `${width}-${label.replaceAll(" ", "_")}-${delta}.json`);
73
+ writeFileSync(path, '{"permission":"NORMAL"}\n');
74
+ const hash = () => createHash("sha256").update(readFileSync(path)).digest("hex");
75
+ const before = hash();
76
+ const answers: boolean[] = [];
77
+ const view = new VisualCustomizeView({ rows: [{ label: "Permission", action: async (inline) => {
78
+ const yes = await inline.confirm("Go?");
79
+ answers.push(yes);
80
+ if (yes)
81
+ writeFileSync(path, '{"permission":"YOLO"}\n');
82
+ } }], theme, rowsAvailable: () => 24, requestRender() { }, onClose() { } });
83
+ try {
84
+ let frame = view.render(width);
85
+ view.handleMouse(at(frame, "Permission", "click"));
86
+ await tick();
87
+ frame = view.render(width);
88
+ view.handleMouse(at(frame, label, "move", delta));
89
+ frame = view.render(width);
90
+ assert.equal(hash(), before, "hover never writes");
91
+ assert.deepEqual(answers, []);
92
+ view.handleMouse(at(frame, label, "press", delta));
93
+ assert.equal(hash(), before, "press never writes");
94
+ frame = view.render(width);
95
+ view.handleMouse(at(frame, label, "click", delta));
96
+ await tick();
97
+ const inside = delta >= 0 && delta < label.length;
98
+ assert.deepEqual(answers, inside ? [label === "y yes"] : []);
99
+ if (!inside || label === "cancel")
100
+ assert.equal(hash(), before, "every rejected/declined action leaves exact stored bytes");
101
+ else
102
+ assert.equal(readFileSync(path, "utf8"), '{"permission":"YOLO"}\n');
103
+ }
104
+ finally {
105
+ view.dispose();
106
+ await tick();
107
+ }
108
+ }
109
+ });
110
+ // S1/S2: same-name content drift must still fail after all confirmation paints.
111
+ test("hover cannot make a changed profile fingerprint apply replace or delete", async () => {
112
+ for (const key of ["a", "r", "d"]) {
113
+ const profile = { name: "Desk y yes", themeName: "dark", animationPolicy: "quality" as const, banner: { showRose: true, showTextLogo: true, color: "pink" as const }, visual: { statusPlacement: "auto" as const, headerPlacement: "top" as const, density: "comfortable" as const, surface: "tinted" as const, visibility: { changes: true, rdd: true, agents: true, todo: true, usageCost: true, modelDetails: true, contextWarning: true, stats: false } } };
114
+ let catalog = [profile];
115
+ const effects: string[] = [];
116
+ const view = new VisualCustomizeView({ rows: [], theme, rowsAvailable: () => 12, requestRender() { }, onClose() { }, profiles: { list: () => catalog, save: () => { effects.push("replace"); }, apply: () => { effects.push("apply"); }, delete: () => { effects.push("delete"); }, reset() { } } });
117
+ try {
118
+ view.handleInput("p");
119
+ view.handleInput(key);
120
+ let frame = view.render(80);
121
+ view.handleMouse(at(frame, "y yes", "move"));
122
+ frame = view.render(80);
123
+ assert.deepEqual(effects, []);
124
+ catalog = [{ ...profile, themeName: "light" }];
125
+ view.handleMouse(at(frame, "y yes", "press"));
126
+ frame = view.render(80);
127
+ view.handleMouse(at(frame, "y yes", "click"));
128
+ await tick();
129
+ assert.deepEqual(effects, []);
130
+ assert.match(view.render(80).map(stripAnsi).join("\n"), /Profile changed; choose again\./);
131
+ }
132
+ finally {
133
+ view.dispose();
134
+ }
135
+ }
136
+ });
@@ -3,7 +3,171 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync }
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import test from "node:test";
6
- import { applySavedModelConfig, readModelConfig, readModelConfigAsync } from "../extensions/gentle-ai.ts";
6
+ import { __testing, applySavedModelConfig, readModelConfig, readModelConfigAsync } from "../extensions/gentle-ai.ts";
7
+ import {
8
+ localProfilePinPath,
9
+ setProfilePinWorktreeResolverForTesting,
10
+ writeProfilePinSync,
11
+ } from "../lib/agent-profile-pin.ts";
12
+
13
+ test("coincident global and legacy paths preserve invalid-global status", async (t) => {
14
+ const cwd = mkdtempSync(join(tmpdir(), "gentle-pi-model-coincidence-"));
15
+ const configHome = join(cwd, ".pi", "gentle-ai");
16
+ mkdirSync(configHome, { recursive: true });
17
+ const previous = process.env.GENTLE_PI_CONFIG_HOME;
18
+ process.env.GENTLE_PI_CONFIG_HOME = configHome;
19
+ t.after(() => {
20
+ if (previous === undefined) delete process.env.GENTLE_PI_CONFIG_HOME;
21
+ else process.env.GENTLE_PI_CONFIG_HOME = previous;
22
+ rmSync(cwd, { recursive: true, force: true });
23
+ });
24
+ const path = join(configHome, "models.json");
25
+ assert.equal(path, join(cwd, ".pi", "gentle-ai", "models.json"));
26
+ writeFileSync(path, "{");
27
+ const results = [__testing.readSavedModelConfig(cwd), await __testing.readSavedModelConfigAsync(cwd)];
28
+ assert.deepEqual(results, [ { status: "invalid", path }, { status: "invalid", path } ]);
29
+ assert.deepEqual(readModelConfig(cwd), {});
30
+ assert.deepEqual(await readModelConfigAsync(cwd), {});
31
+ });
32
+
33
+ test("bootstrapped active profile preserves legacy routing while global models are missing", async (t) => {
34
+ const cwd = mkdtempSync(join(tmpdir(), "gentle-pi-model-bootstrap-"));
35
+ const configHome = join(cwd, "global");
36
+ const projectHome = join(cwd, ".pi", "gentle-ai");
37
+ mkdirSync(configHome, { recursive: true });
38
+ mkdirSync(projectHome, { recursive: true });
39
+ const previous = process.env.GENTLE_PI_CONFIG_HOME;
40
+ process.env.GENTLE_PI_CONFIG_HOME = configHome;
41
+ t.after(() => {
42
+ if (previous === undefined) delete process.env.GENTLE_PI_CONFIG_HOME;
43
+ else process.env.GENTLE_PI_CONFIG_HOME = previous;
44
+ rmSync(cwd, { recursive: true, force: true });
45
+ });
46
+ const config = { "review-risk": { model: "openai/gpt-5" } };
47
+ writeFileSync(join(projectHome, "models.json"), JSON.stringify(config));
48
+ writeFileSync(join(configHome, "profiles.json"), JSON.stringify({
49
+ kind: "gentle-pi.agent_model_profiles", version: 1, active: "current", profiles: { current: config },
50
+ }));
51
+ const expected = { "review-risk": { model: "openai/gpt-5", thinking: undefined } };
52
+ assert.deepEqual({ sync: readModelConfig(cwd), async: await readModelConfigAsync(cwd) }, {
53
+ sync: expected, async: expected,
54
+ });
55
+ assert.throws(() => statSync(join(configHome, "models.json")), { code: "ENOENT" });
56
+ });
57
+
58
+ test("active profile omission is preserved while global models are still missing", async (t) => {
59
+ const cwd = mkdtempSync(join(tmpdir(), "gentle-pi-model-profile-missing-"));
60
+ const configHome = join(cwd, "global");
61
+ const projectHome = join(cwd, ".pi", "gentle-ai");
62
+ mkdirSync(configHome, { recursive: true });
63
+ mkdirSync(projectHome, { recursive: true });
64
+ const previous = process.env.GENTLE_PI_CONFIG_HOME;
65
+ process.env.GENTLE_PI_CONFIG_HOME = configHome;
66
+ t.after(() => {
67
+ if (previous === undefined) delete process.env.GENTLE_PI_CONFIG_HOME;
68
+ else process.env.GENTLE_PI_CONFIG_HOME = previous;
69
+ rmSync(cwd, { recursive: true, force: true });
70
+ });
71
+ writeFileSync(join(configHome, "profiles.json"), JSON.stringify({
72
+ kind: "gentle-pi.agent_model_profiles", version: 1, active: "team", profiles: { team: {} },
73
+ }));
74
+ writeFileSync(join(projectHome, "models.json"), JSON.stringify({ "review-risk": { model: "openai/gpt-5" } }));
75
+ assert.deepEqual({ sync: readModelConfig(cwd), async: await readModelConfigAsync(cwd) }, { sync: {}, async: {} });
76
+ assert.throws(() => statSync(join(configHome, "models.json")), { code: "ENOENT" });
77
+ });
78
+
79
+ test("active profile omission prevents stale legacy materialization while global models are still missing", async (t) => {
80
+ const cwd = mkdtempSync(join(tmpdir(), "gentle-pi-model-profile-missing-apply-"));
81
+ const configHome = join(cwd, "global");
82
+ const projectHome = join(cwd, ".pi", "gentle-ai");
83
+ mkdirSync(configHome, { recursive: true });
84
+ mkdirSync(projectHome, { recursive: true });
85
+ const previous = process.env.GENTLE_PI_CONFIG_HOME;
86
+ process.env.GENTLE_PI_CONFIG_HOME = configHome;
87
+ t.after(() => {
88
+ if (previous === undefined) delete process.env.GENTLE_PI_CONFIG_HOME;
89
+ else process.env.GENTLE_PI_CONFIG_HOME = previous;
90
+ rmSync(cwd, { recursive: true, force: true });
91
+ });
92
+ writeFileSync(join(configHome, "profiles.json"), JSON.stringify({
93
+ kind: "gentle-pi.agent_model_profiles", version: 1, active: "team", profiles: { team: {} },
94
+ }));
95
+ writeFileSync(join(projectHome, "models.json"), JSON.stringify({ "review-risk": { model: "openai/gpt-5" } }));
96
+ const materialized: unknown[] = [];
97
+ const result = await applySavedModelConfig({ cwd } as Parameters<typeof applySavedModelConfig>[0], async (target, config) => {
98
+ assert.equal(target, cwd);
99
+ materialized.push(config);
100
+ return { updated: 0, skipped: 0 };
101
+ });
102
+ assert.deepEqual({ sync: readModelConfig(cwd), async: await readModelConfigAsync(cwd), materialized, result }, {
103
+ sync: {}, async: {}, materialized: [{}], result: { updated: 0, skipped: 0 },
104
+ });
105
+ assert.throws(() => statSync(join(configHome, "models.json")), { code: "ENOENT" });
106
+ });
107
+
108
+ test("active profile omission prevents stale legacy routing reads and materialization", async (t) => {
109
+ const cwd = mkdtempSync(join(tmpdir(), "gentle-pi-model-profile-"));
110
+ const configHome = join(cwd, "global");
111
+ const projectHome = join(cwd, ".pi", "gentle-ai");
112
+ mkdirSync(configHome, { recursive: true });
113
+ mkdirSync(projectHome, { recursive: true });
114
+ const previous = process.env.GENTLE_PI_CONFIG_HOME;
115
+ process.env.GENTLE_PI_CONFIG_HOME = configHome;
116
+ t.after(() => {
117
+ if (previous === undefined) delete process.env.GENTLE_PI_CONFIG_HOME;
118
+ else process.env.GENTLE_PI_CONFIG_HOME = previous;
119
+ rmSync(cwd, { recursive: true, force: true });
120
+ });
121
+ writeFileSync(join(configHome, "profiles.json"), JSON.stringify({
122
+ kind: "gentle-pi.agent_model_profiles", version: 1, active: "team", profiles: { team: {} },
123
+ }));
124
+ writeFileSync(join(configHome, "models.json"), "{}");
125
+ writeFileSync(join(projectHome, "models.json"), JSON.stringify({ "review-risk": { model: "openai/gpt-5" } }));
126
+ const materialized: unknown[] = [];
127
+ const result = await applySavedModelConfig({ cwd } as Parameters<typeof applySavedModelConfig>[0], async (target, config) => {
128
+ assert.equal(target, cwd);
129
+ materialized.push(config);
130
+ return { updated: 0, skipped: 0 };
131
+ });
132
+ assert.deepEqual({ sync: readModelConfig(cwd), async: await readModelConfigAsync(cwd), materialized, result }, {
133
+ sync: {}, async: {}, materialized: [{}], result: { updated: 0, skipped: 0 },
134
+ });
135
+ });
136
+
137
+ // gentle-shell#2477 regression: a pinned or active profile replaced the legacy
138
+ // project source even when no model config existed at all, so a session that
139
+ // had deliberately cleared its profile read the pin back as saved routing. The
140
+ // profile snapshot only stands in for a legacy file that is actually there.
141
+ test("a pin or active profile invents no saved routing while no model config exists", async (t) => {
142
+ const previous = process.env.GENTLE_PI_CONFIG_HOME;
143
+ t.after(() => {
144
+ setProfilePinWorktreeResolverForTesting();
145
+ if (previous === undefined) delete process.env.GENTLE_PI_CONFIG_HOME;
146
+ else process.env.GENTLE_PI_CONFIG_HOME = previous;
147
+ });
148
+ const chosen = { "review-risk": { model: "openai/pinned-risk" } };
149
+ for (const target of ["pinned", "active"] as const) {
150
+ const cwd = mkdtempSync(join(tmpdir(), `gentle-pi-model-${target}-no-config-`));
151
+ const configHome = join(cwd, "global");
152
+ const projectHome = join(cwd, ".pi", "gentle-ai");
153
+ mkdirSync(configHome, { recursive: true });
154
+ mkdirSync(projectHome, { recursive: true });
155
+ process.env.GENTLE_PI_CONFIG_HOME = configHome;
156
+ t.after(() => rmSync(cwd, { recursive: true, force: true }));
157
+ writeFileSync(join(configHome, "profiles.json"), JSON.stringify({
158
+ kind: "gentle-pi.agent_model_profiles", version: 1, ...(target === "active" ? { active: "chosen" } : {}), profiles: { chosen },
159
+ }));
160
+ const identity = { root: join(cwd, "worktree"), commonDir: join(cwd, "git-common") };
161
+ mkdirSync(identity.root, { recursive: true });
162
+ mkdirSync(identity.commonDir, { recursive: true });
163
+ setProfilePinWorktreeResolverForTesting(() => identity);
164
+ if (target === "pinned") writeProfilePinSync(localProfilePinPath(identity.commonDir), "chosen");
165
+ assert.deepEqual({ sync: readModelConfig(cwd), async: await readModelConfigAsync(cwd) }, { sync: {}, async: {} }, `${target} routing stays empty`);
166
+ assert.deepEqual(__testing.readSavedModelConfig(cwd), { status: "missing" }, `${target} saved routing stays missing`);
167
+ assert.deepEqual(await __testing.readSavedModelConfigAsync(cwd), { status: "missing" }, `${target} async saved routing stays missing`);
168
+ assert.throws(() => statSync(join(configHome, "models.json")), { code: "ENOENT" }, `reading never writes the global file`);
169
+ }
170
+ });
7
171
 
8
172
  test("model routing authority normalizes and preserves sync/async source status", async (t) => {
9
173
  const loaded = await import("../lib/model-routing-authority.ts").then(
@@ -110,12 +274,24 @@ test("model routing authority normalizes and preserves sync/async source status"
110
274
  path: invalidGlobalPath,
111
275
  });
112
276
 
277
+ // A present global config must merge with, not fully shadow, the legacy project
278
+ // config (gentle-shell#2163): project-only keys survive, same-name keys prefer global.
279
+ const globalWithProjectKeyOverride = join(globalDir, "global-with-project-key.json");
280
+ writeFileSync(globalWithProjectKeyOverride, JSON.stringify({ project: "openai/gpt-5" }));
281
+ const invalidProjectPath = join(projectConfigDir, "invalid.json");
282
+ writeFileSync(invalidProjectPath, "[]");
283
+
113
284
  const sourceCases = [
114
285
  [missingPath, missingPath, { status: "missing" }],
115
286
  [missingPath, projectPath, { status: "valid", config: { project: { model: "google/gemini" } } }],
116
- [validGlobalPath, projectPath, validSync],
287
+ [
288
+ validGlobalPath, projectPath,
289
+ { status: "valid", config: { ...validSync.status === "valid" ? validSync.config : {}, project: { model: "google/gemini" } } },
290
+ ],
291
+ [globalWithProjectKeyOverride, projectPath, { status: "valid", config: { project: { model: "openai/gpt-5" } } }],
117
292
  [missingPath, invalidGlobalPath, { status: "invalid", path: invalidGlobalPath }],
118
293
  [invalidGlobalPath, projectPath, { status: "invalid", path: invalidGlobalPath }],
294
+ [validGlobalPath, invalidProjectPath, { status: "invalid", path: invalidProjectPath }],
119
295
  ] as const;
120
296
  for (const [globalSource, projectSource, expected] of sourceCases) {
121
297
  assert.deepEqual(authority.readSavedModelConfig(globalSource, projectSource), expected);