gentle-pi 4.5.0 → 4.6.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 (243) hide show
  1. package/README.md +9 -6
  2. package/assets/agents/gentle-ai-verify.md +4 -0
  3. package/assets/agents/gentle-ai-worker.md +1 -0
  4. package/assets/migrations/agent-body-history.json +147 -0
  5. package/assets/orchestrator-delegation-reference.md +3 -3
  6. package/assets/orchestrator-delegation.md +2 -2
  7. package/assets/orchestrator-verification.md +10 -6
  8. package/assets/orchestrator.md +8 -8
  9. package/bin/gentle-shell.mjs +61 -26
  10. package/docs/ci-performance.md +11 -0
  11. package/docs/delegated-verification.md +6 -0
  12. package/docs/fast-mode.md +15 -0
  13. package/docs/gentle-agents-activity.md +8 -0
  14. package/docs/gentle-music.md +6 -3
  15. package/docs/gentle-shell.md +70 -20
  16. package/docs/install-wizard.md +1 -1
  17. package/docs/mcp-status.md +52 -0
  18. package/docs/prompt-budget.md +28 -0
  19. package/docs/readme-reference.md +82 -21
  20. package/docs/session-profile-format.md +20 -5
  21. package/docs/sound-notifications.md +1 -1
  22. package/docs/star-prompt.md +32 -0
  23. package/docs/work-continuity.md +46 -0
  24. package/extensions/ask-user-question.ts +1 -0
  25. package/extensions/codegraph-tools.ts +38 -4
  26. package/extensions/gentle-agents.ts +477 -50
  27. package/extensions/gentle-ai.ts +1046 -191
  28. package/extensions/gentle-fast.ts +61 -0
  29. package/extensions/gentle-guide.ts +174 -0
  30. package/extensions/gentle-herdr-activity.ts +21 -1
  31. package/extensions/gentle-herdr-agent.ts +144 -0
  32. package/extensions/gentle-music.ts +10 -0
  33. package/extensions/gentle-program-identity.ts +61 -0
  34. package/extensions/gentle-shell.ts +642 -97
  35. package/extensions/gentle-star-prompt.ts +334 -0
  36. package/extensions/gentle-stats.ts +5 -5
  37. package/extensions/gentle-todo.ts +42 -22
  38. package/extensions/history/store.ts +18 -12
  39. package/extensions/skill-registry.ts +35 -3
  40. package/extensions/startup-banner.ts +39 -7
  41. package/lib/agent-assets.ts +74 -17
  42. package/lib/agent-profiles.ts +1 -1
  43. package/lib/agents-config.ts +12 -3
  44. package/lib/agents-keys.ts +8 -16
  45. package/lib/agents-protocol.ts +80 -4
  46. package/lib/agents-runner.ts +105 -4
  47. package/lib/agents-view.ts +6 -1
  48. package/lib/agents-widget.ts +132 -9
  49. package/lib/bridge-cost.ts +28 -0
  50. package/lib/codemode-renderer.ts +16 -0
  51. package/lib/command-palette-catalog.ts +1 -0
  52. package/lib/command-palette.ts +21 -8
  53. package/lib/exploration-budget.ts +62 -0
  54. package/lib/gentle-guide.ts +201 -0
  55. package/lib/gentle-shell-launcher.ts +4 -0
  56. package/lib/herdr-activity.ts +9 -3
  57. package/lib/herdr-task-summary-policy.ts +85 -0
  58. package/lib/inprocess-reviewer.ts +33 -13
  59. package/lib/jobs-sidebar-state.ts +5 -6
  60. package/lib/jobs-widget.ts +16 -52
  61. package/lib/keymaps-customize.ts +81 -0
  62. package/lib/keymaps.ts +291 -0
  63. package/lib/model-fallback-notice.ts +61 -0
  64. package/lib/model-fallback-policy.ts +141 -0
  65. package/lib/model-fallback-store.ts +143 -0
  66. package/lib/model-routing-authority.ts +10 -2
  67. package/lib/nan-provider.ts +3 -2
  68. package/lib/native-review-cli.ts +7 -2
  69. package/lib/notification-customize.ts +48 -51
  70. package/lib/openai-fast-tier.ts +22 -0
  71. package/lib/orchestrator-discovery.ts +5 -1
  72. package/lib/orchestrator-fallback.ts +75 -0
  73. package/lib/pasted-image-paths.ts +113 -0
  74. package/lib/questionnaire/questionnaire-view.ts +121 -7
  75. package/lib/review-candidate-view-owner.ts +4 -0
  76. package/lib/review-candidate-view.ts +10 -7
  77. package/lib/review-host-relay.ts +5 -1
  78. package/lib/review-integration-v2.ts +22 -7
  79. package/lib/review-repository.ts +5 -0
  80. package/lib/session-profile-append-controller.ts +21 -6
  81. package/lib/session-profile-authority.ts +119 -0
  82. package/lib/session-profile-binding.ts +54 -5
  83. package/lib/session-profile-freeze.ts +105 -9
  84. package/lib/session-profile-integration.ts +313 -0
  85. package/lib/session-profile-persistence.ts +63 -9
  86. package/lib/shell-bar.ts +171 -56
  87. package/lib/shell-card.ts +26 -6
  88. package/lib/shell-page.ts +120 -0
  89. package/lib/shell-panel.ts +149 -0
  90. package/lib/shell-prompt.ts +53 -1
  91. package/lib/shell-sidebar-layout.ts +98 -25
  92. package/lib/shell-sidebar.ts +54 -1
  93. package/lib/shell-stats.ts +123 -0
  94. package/lib/shell-todo.ts +71 -0
  95. package/lib/shell-usage.ts +12 -2
  96. package/lib/star-prompt.ts +197 -0
  97. package/lib/verifier-admission.ts +18 -8
  98. package/lib/verifier-settle-reminder.ts +64 -0
  99. package/lib/vim-editor-adapter.ts +6 -1
  100. package/lib/visual-customization-policy.ts +41 -6
  101. package/lib/visual-customize-view.ts +164 -26
  102. package/lib/visual-layout-preview.ts +43 -0
  103. package/lib/yolo-session-policy.ts +28 -1
  104. package/package.json +1 -1
  105. package/runtime/gentle-shell-launcher.mjs +4 -0
  106. package/runtime/native-review-cli.mjs +7 -2
  107. package/runtime/review-integration-v2.mjs +22 -7
  108. package/runtime/windows-session-transport.ps1 +60 -3
  109. package/scripts/bootstrap.sh +4 -1
  110. package/scripts/installer-preflight.mjs +1 -1
  111. package/scripts/pi-update.mjs +113 -3
  112. package/scripts/run-test-suite.mjs +17 -1
  113. package/scripts/shell-snapshot.mjs +340 -0
  114. package/scripts/test-packed-runner.mjs +1 -1
  115. package/scripts/update-agent-body-history.mjs +41 -0
  116. package/scripts/verify-installer-tap.mjs +45 -0
  117. package/scripts/verify-package-files.mjs +2 -0
  118. package/skills/gentle-ai/SKILL.md +2 -2
  119. package/skills/tui-design/NOTICE.md +5 -0
  120. package/skills/tui-design/SKILL.md +56 -0
  121. package/skills/tui-design/references/commands.md +75 -0
  122. package/skills/tui-design/references/critique.md +48 -0
  123. package/skills/tui-design/references/design-doc.md +44 -0
  124. package/skills/tui-design/references/terminal-craft.md +64 -0
  125. package/skills/tui-design/references/visual-loop.md +32 -0
  126. package/tests/agents-protocol.test.ts +53 -1
  127. package/tests/agents-runner.test.ts +168 -3
  128. package/tests/agents-view.test.ts +27 -0
  129. package/tests/agents-widget.test.ts +312 -10
  130. package/tests/bounded-scan-contract.test.ts +39 -0
  131. package/tests/bridge-cost.test.ts +32 -0
  132. package/tests/bundled-install.test.ts +6 -4
  133. package/tests/ci-concurrency.test.ts +11 -0
  134. package/tests/ci-merge-base-identity.test.ts +114 -0
  135. package/tests/codegraph-tools.test.ts +69 -0
  136. package/tests/codemode-rendering.test.ts +22 -2
  137. package/tests/command-palette.test.ts +16 -2
  138. package/tests/commit-slice-signal.test.ts +11 -9
  139. package/tests/delegate-for-reason-contract.test.ts +5 -4
  140. package/tests/design-canvas-server.test.ts +6 -2
  141. package/tests/exploration-budget.test.ts +128 -0
  142. package/tests/fixtures/agent-assets/gentle-ai-worker.strict-tdd-era.md +122 -0
  143. package/tests/fixtures/measure-orchestrator-prompt.mjs +2 -1
  144. package/tests/fixtures/primary-session-prompt/gentleman.golden.md +18 -10
  145. package/tests/fixtures/session-profile-v1/replay.ts +125 -0
  146. package/tests/fixtures/session-profile-v1/session-profile-authority.ts +113 -0
  147. package/tests/fixtures/session-profile-v1/session-profile-binding.ts +83 -0
  148. package/tests/fixtures/session-profile-v1/session-profile-disk-reader.ts +182 -0
  149. package/tests/fixtures/session-profile-v1/session-profile-freeze.ts +290 -0
  150. package/tests/fixtures/session-profile-v1/session-profile-persistence.ts +195 -0
  151. package/tests/fixtures/session-profile-v1/v1-inputs.ts +16 -0
  152. package/tests/fixtures/windows-pipe-availability.ps1 +26 -0
  153. package/tests/fixtures/windows-session-bootstrap.ps1 +6 -2
  154. package/tests/gentle-agents.test.ts +416 -21
  155. package/tests/gentle-ai-exploration-budget.test.ts +135 -0
  156. package/tests/gentle-ai.test.ts +1011 -37
  157. package/tests/gentle-fast.test.ts +73 -0
  158. package/tests/gentle-guide.test.ts +208 -0
  159. package/tests/gentle-herdr-activity.test.ts +76 -2
  160. package/tests/gentle-herdr-agent.test.ts +111 -0
  161. package/tests/gentle-music.test.ts +36 -1
  162. package/tests/gentle-program-identity.test.ts +197 -0
  163. package/tests/gentle-shell-bin.test.ts +49 -26
  164. package/tests/gentle-shell-launcher.test.ts +18 -2
  165. package/tests/gentle-shell.test.ts +1068 -37
  166. package/tests/gentle-stats.test.ts +15 -2
  167. package/tests/gentle-todo.test.ts +50 -4
  168. package/tests/herdr-task-summary-policy.test.ts +128 -0
  169. package/tests/history-store-private-mode.test.ts +40 -0
  170. package/tests/image-paste-chips.test.ts +42 -0
  171. package/tests/inprocess-reviewer.test.ts +122 -0
  172. package/tests/installer-posix-bootstrap.test.ts +67 -5
  173. package/tests/installer-server.test.ts +2 -2
  174. package/tests/installer-windows-diagnostics.test.ts +4 -5
  175. package/tests/isolated-config-home.ts +28 -0
  176. package/tests/jobs-widget.test.ts +25 -37
  177. package/tests/keymaps-customize.test.ts +114 -0
  178. package/tests/keymaps.test.ts +103 -0
  179. package/tests/maintainer/mcp-status.maintest.ts +88 -0
  180. package/tests/maintainer/pi-update-source.maintest.ts +116 -0
  181. package/tests/model-fallback-notice.test.ts +45 -0
  182. package/tests/model-fallback-policy.test.ts +83 -0
  183. package/tests/model-fallback-store.test.ts +111 -0
  184. package/tests/nan-provider.test.ts +4 -4
  185. package/tests/no-self-pause-contract.test.ts +19 -0
  186. package/tests/notification-customize.test.ts +58 -34
  187. package/tests/odd-routing-canonical-ratchet.test.ts +3 -3
  188. package/tests/odd-routing-contract.test.ts +1 -1
  189. package/tests/orchestrator-fallback.test.ts +82 -0
  190. package/tests/orchestrator-prompt-budget.test.ts +131 -0
  191. package/tests/package-manifest.test.ts +160 -7
  192. package/tests/pasted-image-paths.test.ts +118 -0
  193. package/tests/persona-reply-language.test.ts +61 -0
  194. package/tests/pi-update-launcher.test.ts +32 -8
  195. package/tests/pi-update-source.test.ts +162 -0
  196. package/tests/profile-fast-tier.test.ts +311 -0
  197. package/tests/profile-tier-footer.test.ts +79 -0
  198. package/tests/questionnaire-view.test.ts +150 -0
  199. package/tests/review-candidate-owner-sweep.test.ts +93 -0
  200. package/tests/review-candidate-view.test.ts +51 -0
  201. package/tests/review-controller-native-routing.test.ts +120 -6
  202. package/tests/review-gate.test.ts +24 -0
  203. package/tests/review-inspect-preflight.test.ts +197 -0
  204. package/tests/review-integration-v2-forward.test.ts +59 -0
  205. package/tests/review-repository.test.ts +52 -1
  206. package/tests/review-sidebar-state.test.ts +5 -5
  207. package/tests/run-test-suite.test.ts +61 -5
  208. package/tests/sensitive-path-tools.test.ts +74 -0
  209. package/tests/session-profile-append-controller.test.ts +63 -0
  210. package/tests/session-profile-authority.test.ts +259 -0
  211. package/tests/session-profile-binding.test.ts +15 -0
  212. package/tests/session-profile-extension.test.ts +615 -0
  213. package/tests/session-profile-freeze.test.ts +110 -2
  214. package/tests/session-profile-integration.test.ts +857 -0
  215. package/tests/session-profile-persistence.test.ts +57 -0
  216. package/tests/session-profile-v1-compat.test.ts +221 -0
  217. package/tests/shell-bar.test.ts +113 -55
  218. package/tests/shell-card.test.ts +13 -1
  219. package/tests/shell-page.test.ts +108 -0
  220. package/tests/shell-panel.test.ts +332 -0
  221. package/tests/shell-prompt.test.ts +54 -0
  222. package/tests/shell-render-cache.test.ts +5 -0
  223. package/tests/shell-sidebar-fullscreen.test.ts +12 -0
  224. package/tests/shell-sidebar-layout.test.ts +159 -27
  225. package/tests/shell-stats.test.ts +90 -0
  226. package/tests/shell-usage.test.ts +14 -0
  227. package/tests/skill-registry.test.ts +68 -1
  228. package/tests/star-prompt.test.ts +470 -0
  229. package/tests/startup-banner.test.ts +57 -1
  230. package/tests/task-size-routing-contract.test.ts +45 -1
  231. package/tests/verifier-settle-reminder.test.ts +281 -0
  232. package/tests/verify-first-launch-contract.test.ts +56 -5
  233. package/tests/verify-installer-tap.test.ts +57 -0
  234. package/tests/vim-editor-adapter.test.ts +2 -2
  235. package/tests/visual-customization-policy.test.ts +61 -7
  236. package/tests/visual-customize-view.test.ts +253 -8
  237. package/tests/visual-layout-preview.test.ts +28 -0
  238. package/tests/windows-session-bootstrap.test.ts +105 -2
  239. package/tests/work-continuity-contract.test.ts +86 -0
  240. package/tests/writer-surfaces.test.ts +12 -10
  241. package/tests/yolo-customize.test.ts +30 -11
  242. package/tests/yolo-mode-runtime.test.ts +4 -2
  243. package/tests/yolo-mode.test.ts +16 -2
@@ -1,16 +1,18 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { execFileSync } from "node:child_process";
3
3
  import { createHash } from "node:crypto";
4
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
4
+ import fs, { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
5
+ import { syncBuiltinESMExports } from "node:module";
5
6
  import { tmpdir } from "node:os";
6
7
  import { dirname, join } from "node:path";
7
8
  import test from "node:test";
8
9
  import { gzipSync } from "node:zlib";
9
- import { initTheme } from "@earendil-works/pi-coding-agent";
10
+ import { createAgentSession, DefaultResourceLoader, initTheme, ModelRuntime, SessionManager, SettingsManager } from "@earendil-works/pi-coding-agent";
10
11
  import { visibleWidth } from "@earendil-works/pi-tui";
11
12
  import { validateToolArguments } from "@earendil-works/pi-ai";
12
13
  import type {
13
14
  ExtensionAPI,
15
+ ExtensionCommandContext,
14
16
  ExtensionContext,
15
17
  Theme,
16
18
  ToolCallEventResult,
@@ -18,6 +20,10 @@ import type {
18
20
  import { __testing, applyModelConfig, applyModelConfigAsync, createGentleAiExtension } from "../extensions/gentle-ai.ts";
19
21
  import { PROFILES_KIND, PROFILES_VERSION, bootstrapProfilesFile, readProfilesFileResult, type AgentProfilesFile } from "../lib/agent-profiles.ts";
20
22
  import { bindSessionProfile, readSessionProfileBinding, resetSessionProfileBindingsForTesting } from "../lib/session-profile-binding.ts";
23
+ import { freezeSessionProfileAtStartup, resetFrozenInheritedProfilesForTesting } from "../lib/session-profile-freeze.ts";
24
+ import { createSessionProfileBind, createSessionProfileClear, createSessionProfileStartupBind, SESSION_PROFILE_CUSTOM_TYPE } from "../lib/session-profile-persistence.ts";
25
+ import { createSessionProfileIntegration, runCurrentSessionProfileSelection } from "../lib/session-profile-integration.ts";
26
+ import { readSessionProfileAuthority } from "../lib/session-profile-authority.ts";
21
27
  import type { AgentModelConfig, AgentRoutingEntry, ThinkingLevel } from "../lib/model-routing-authority.ts";
22
28
  type LiveSession = Pick<ExtensionAPI, "setModel" | "setThinkingLevel" | "getThinkingLevel">;
23
29
  import { PROFILE_PIN_KIND, PROFILE_PIN_VERSION, setProfilePinWorktreeResolverForTesting, writeProfilePinSync } from "../lib/agent-profile-pin.ts";
@@ -406,7 +412,11 @@ function routingConsumerFixture(t: test.TestContext, agents = ["worker"]) {
406
412
  process.env.USERPROFILE = isolatedHome;
407
413
  process.env.GENTLE_PI_CONFIG_HOME = configHome;
408
414
  process.env.GENTLE_PI_AGENT_HOME = agentHome;
415
+ // Every fixture models the same session id, so a profile frozen by one test
416
+ // must not become the next test's session profile.
417
+ resetFrozenInheritedProfilesForTesting();
409
418
  t.after(() => {
419
+ resetFrozenInheritedProfilesForTesting();
410
420
  if (previousConfigHome === undefined) delete process.env.GENTLE_PI_CONFIG_HOME;
411
421
  else process.env.GENTLE_PI_CONFIG_HOME = previousConfigHome;
412
422
  if (previousAgentHome === undefined) delete process.env.GENTLE_PI_AGENT_HOME;
@@ -504,6 +514,9 @@ function routingConsumerFixture(t: test.TestContext, agents = ["worker"]) {
504
514
  liveThinking = thinking;
505
515
  },
506
516
  refuseSetModel() { setModelResult = false; },
517
+ // Enter persists the session profile record, so a test that presses it
518
+ // swaps in a real session manager it can append to and corroborate.
519
+ useSessionManager(manager: unknown) { (ctx as { sessionManager: unknown }).sessionManager = manager; },
507
520
  rejectThinkingLevel() { thinkingRejects = true; },
508
521
  confirmCalls,
509
522
  onConfirm(handler: (title: string, message: string) => Promise<boolean>) { onConfirm = handler; },
@@ -969,6 +982,7 @@ test("ordinary native capture exposes a registered schema and STATUS binding cop
969
982
 
970
983
  assert.ok(tools.has("gentle_review_capture"));
971
984
  assert.deepEqual(tools.get("gentle_review_capture")?.parameters.required, ["lineageId", "collectBinding"]);
985
+ assert.deepEqual(tools.get("gentle_review")?.parameters.required, ["operation"]);
972
986
 
973
987
  const sha = `sha256:${"a".repeat(64)}`;
974
988
  const lineageId = "ordinary-capture";
@@ -1119,7 +1133,7 @@ test("ordinary START reports candidate-owner preparation failure as pre-native n
1119
1133
  start: async () => { nativeStarts += 1; throw new Error("native START must not run"); },
1120
1134
  } as unknown as NativeReviewCli;
1121
1135
  const candidateViews = {
1122
- createOrReuse: () => { throw new CandidateViewError("candidate view owner preparation failed", "candidate-owner-preparation-failed"); },
1136
+ createOrReuse: () => { throw new CandidateViewError("candidate view owner preparation failed (EACCES)", "candidate-owner-preparation-failed"); },
1123
1137
  } as unknown as CandidateViewRegistry;
1124
1138
  const result = await __testing.executeReviewControllerOperation(
1125
1139
  { operation: "start", input: JSON.stringify({ mode: "ordinary" }) },
@@ -1133,7 +1147,7 @@ test("ordinary START reports candidate-owner preparation failure as pre-native n
1133
1147
  assert.equal(result.mutation_outcome, "none");
1134
1148
  assert.deepEqual(result.diagnostics, {
1135
1149
  code: "candidate-owner-preparation-failed",
1136
- message: "candidate view rejected before native START",
1150
+ message: "candidate view owner preparation failed (EACCES)",
1137
1151
  });
1138
1152
 
1139
1153
  let materializationStatusCalls = 0;
@@ -1372,8 +1386,9 @@ test("models screen shows profiles as tabs with their scope, the orchestrator fi
1372
1386
  assert.match(plain[3] ?? "", /current\s+Used in this session\. Default for new sessions\./);
1373
1387
  assert.match(plain[5] ?? "", /▸ Orchestrator\s+openai-codex\/gpt-6\.1-sol\s+max/);
1374
1388
  assert.match(plain.join("\n"), /Agent\s+Model ▾\s+Effort ▾\s+set every agent/);
1375
- assert.match(plain.join("\n"), /\[ Use in this session \] \[ Make default \] \[ Save \]\s+Saved/);
1376
- assert.match(plain.join("\n"), /←→ profile {2}↑↓ agent {2}enter model {2}e effort {2}s save {2}u use {2}d default {2}n new {2}m menu {2}esc close/);
1389
+ assert.match(plain.join("\n"), /\[ u · Use in this session \] \[ d · Make default \] \[ s · Save \]\s+Saved/);
1390
+ // The profile tabs and buttons remain available when lower-priority hints yield.
1391
+ assert.match(plain.join("\n"), /←→ profile {2}↑↓ agent {2}enter model {2}e effort {2}f fallbacks {2}t tier {2}s save {2}u use(?: {2}d default)? {2}esc close/);
1377
1392
  assert.doesNotMatch(plain.join("\n"), /⋯/, "no ellipsis-like glyph: it reads as cut text");
1378
1393
  });
1379
1394
 
@@ -1430,8 +1445,8 @@ test("models screen pointer: hover uses selectedBg, and one click runs exactly o
1430
1445
  assert.ok(!outside.some((line) => line.includes("Model for")), "a click outside a card closes it");
1431
1446
 
1432
1447
  const results: Array<{ type: string; name?: string; saveFirst?: AgentModelConfig }> = [];
1433
- renderScreen([], [{ type: "click", ...screenAt(base, "[ Use in this session ]") }], results);
1434
- renderScreen([], [{ type: "click", ...screenAt(base, "[ Make default ]") }], results);
1448
+ renderScreen([], [{ type: "click", ...screenAt(base, "[ u · Use in this session ]") }], results);
1449
+ renderScreen([], [{ type: "click", ...screenAt(base, "[ d · Make default ]") }], results);
1435
1450
  renderScreen([], [{ type: "click", ...screenAt(base, " nan ") }], results);
1436
1451
  assert.deepEqual(results.map((result) => result.type), ["use-session", "apply-global", "load"]);
1437
1452
 
@@ -1507,7 +1522,7 @@ test("models screen fits narrow terminals without cutting text", () => {
1507
1522
  }
1508
1523
  }
1509
1524
  const narrow = renderScreen([], [], [], { width: 60 }).map(stripAnsi).join("\n");
1510
- assert.match(narrow, /\[ Use here \] \[ Default \] \[ Save \]/, "short labels when the full ones do not fit");
1525
+ assert.match(narrow, /\[ u · Use here \] \[ d · Default \] \[ s · Save \]/, "short labels when the full ones do not fit");
1511
1526
  });
1512
1527
 
1513
1528
  test("models screen offers only the effort levels each model supports and shows where Pi lands the rest", async () => {
@@ -1539,10 +1554,10 @@ test("models screen offers only the effort levels each model supports and shows
1539
1554
  test("models screen lists configuration problems under the profile name without cutting them", () => {
1540
1555
  const notices = [
1541
1556
  "The local pin file /home/user/project/.git/gentle-ai/profile-pin.json is not a valid pin and is ignored. Fix or remove it.",
1542
- 'No agent matches "sdd-design" in this profile, so it is ignored at launch.',
1557
+ 'Profile key "sdd-design" matches no agent configured in gentle-shell, so it is ignored at launch.',
1543
1558
  ];
1544
1559
  const plain = renderScreen([], [], [], { width: 80, notices }).map(stripAnsi);
1545
- assert.ok(plain.some((line) => line.includes('⚠ No agent matches "sdd-design"')));
1560
+ assert.ok(plain.some((line) => line.includes('⚠ Profile key "sdd-design"')));
1546
1561
  assert.ok(!plain.some((line) => line.includes("…")));
1547
1562
  });
1548
1563
 
@@ -3132,7 +3147,8 @@ test("From what's running now creates a profile from the routing in effect witho
3132
3147
  worker: readFileSync(workerPath, "utf8"),
3133
3148
  settings: readFileSync(settingsPath, "utf8"),
3134
3149
  };
3135
- writeStore({ "a-target": {}, "z-active": { worker: { model: "openai/beta" } } }, "z-active");
3150
+ // No default profile: the session resolves none, so launches use the global routing.
3151
+ writeStore({ "a-target": {}, "z-active": { worker: { model: "openai/beta" } } }, undefined);
3136
3152
  const reopened = await runProfilesNameAction(fixture, SCREEN_KEYS.newFromLive, "captured");
3137
3153
 
3138
3154
  const store = JSON.parse(readFileSync(join(fixture.configHome, "profiles.json"), "utf8"));
@@ -3142,7 +3158,7 @@ test("From what's running now creates a profile from the routing in effect witho
3142
3158
  });
3143
3159
  assert.deepEqual(store.profiles["a-target"], {}, "no existing profile is overwritten");
3144
3160
  assert.deepEqual(store.profiles["z-active"], { worker: { model: "openai/beta" } });
3145
- assert.equal(store.active, "z-active");
3161
+ assert.equal(store.active, undefined);
3146
3162
  assert.equal(readFileSync(fixture.globalPath, "utf8"), before.models);
3147
3163
  assert.equal(readFileSync(subagentsPath, "utf8"), before.subagents);
3148
3164
  assert.equal(readFileSync(workerPath, "utf8"), before.worker);
@@ -3230,6 +3246,7 @@ test("models screen saves the explicit orchestrator choice into the profile", as
3230
3246
  assert.equal(fixture.notifications.some((entry) => entry.severity === "warning"), false);
3231
3247
 
3232
3248
  // Use in this session still drives the live session.
3249
+ fixture.useSessionManager(profileActionManager(fixture.root));
3233
3250
  actOnProfile(fixture, "u");
3234
3251
  await fixture.run("gentle:profiles");
3235
3252
  assert.deepEqual(fixture.liveSwitches, [
@@ -3531,7 +3548,7 @@ test("the models screen flags profile keys no agent matches and never flags prov
3531
3548
  await fixture.run("gentle:profiles");
3532
3549
  const flat = (rendered: string) => rendered.replace(/\s*│\s*/g, " ").replace(/\s+/g, " ");
3533
3550
  assert.equal(rendered.split("\n").length, 24, "the frame spans the terminal height");
3534
- assert.match(flat(rendered), /⚠ No agent matches "sdd-design" in this profile, so it is ignored at launch\./);
3551
+ assert.match(flat(rendered), /⚠ Profile key "sdd-design" matches no agent configured in gentle-shell, so it is ignored at launch\./);
3535
3552
  assert.doesNotMatch(flat(rendered), /review-refuter"/, "provider review roles are never flagged");
3536
3553
  assert.match(rendered, /Orchestrator\s+nan\/glm5\.3\s+high/);
3537
3554
  assert.match(rendered, /worker\s+openai\/alpha\s+high/);
@@ -3555,7 +3572,7 @@ test("at 60 columns the unmatched-key notice wraps instead of being cut", async
3555
3572
  assert.ok(panel);
3556
3573
  const narrow = stripAnsi(panel.render(60).join("\n"));
3557
3574
  const flat = (rendered: string) => rendered.replace(/\s*│\s*/g, " ").replace(/\s+/g, " ");
3558
- assert.match(flat(narrow), /⚠ No agent matches "sdd-design" in this profile, so it is ignored at launch\./);
3575
+ assert.match(flat(narrow), /⚠ Profile key "sdd-design" matches no agent configured in gentle-shell, so it is ignored at launch\./);
3559
3576
  assert.ok(!narrow.split("\n").some((line) => line.includes("…")), "nothing is cut");
3560
3577
  });
3561
3578
 
@@ -3564,7 +3581,8 @@ test("at 60 columns the unmatched-key notice wraps instead of being cut", async
3564
3581
  // a suggestion is left to the launch warning.
3565
3582
  test("the models screen names subagents.json keys that match no agent and suggest none", async (t) => {
3566
3583
  const { fixture, writeStore } = profilesStoreFixture(t);
3567
- writeStore({ team: { worker: { model: "openai/alpha", thinking: "high" } } }, "team");
3584
+ // No default profile, so the session resolves none and subagents.json routes its launches.
3585
+ writeStore({ team: { worker: { model: "openai/alpha", thinking: "high" } } }, undefined);
3568
3586
  writeFileSync(join(fixture.root, ".pi", "subagents.json"), `${JSON.stringify({
3569
3587
  model_profiles: {
3570
3588
  worker: { model: "openai/alpha" },
@@ -3777,9 +3795,10 @@ test("Use in this repo pins the shown profile for the clone without touching the
3777
3795
  assert.equal(readFileSync(storePath, "utf8"), storeBefore, "a pin stores a name, never routing");
3778
3796
  assert.match(fixture.notifications.at(-1)?.message ?? "", /pinned profile "team" for this clone in /);
3779
3797
  assert.ok(firstPanel);
3780
- // The reopened screen marks the profile used in this repo (⌂) and says so.
3798
+ // The reopened screen marks the profile used in this repo (⌂) and says so;
3799
+ // ◉ stays on it because the session froze it as the default at startup.
3781
3800
  assert.ok(reopenedPanel);
3782
- assert.match(stripAnsi(renderComponent(reopenedPanel)), /team ★⌂/);
3801
+ assert.match(stripAnsi(renderComponent(reopenedPanel)), /team ◉★⌂/);
3783
3802
  assert.match(stripAnsi(renderComponent(reopenedPanel)), /Used in this repo\./);
3784
3803
  // Rendering an existing screen must not resolve Git or read the pin again.
3785
3804
  setProfilePinWorktreeResolverForTesting(() => { throw new Error("unexpected pin read during render"); });
@@ -3788,18 +3807,54 @@ test("Use in this repo pins the shown profile for the clone without touching the
3788
3807
  });
3789
3808
 
3790
3809
  test("the profile pin scope note sanitizes its worktree-derived path", (t) => {
3791
- const { fixture, writeStore } = profilesStoreFixture(t);
3810
+ const { fixture, localPinPath: safeLocalPath, writeStore } = profilesStoreFixture(t);
3792
3811
  writeStore({ team: { worker: { model: "openai/alpha" } } }, "team");
3793
3812
  const commonDir = join(fixture.root, "git-\x1b]52;c;payload\x07-common");
3794
3813
  const localPath = join(commonDir, "gentle-ai", "profile-pin.json");
3795
- writeProfilePinSync(localPath, "team");
3814
+ writeProfilePinSync(safeLocalPath, "team");
3796
3815
  setProfilePinWorktreeResolverForTesting(() => ({ root: fixture.root, commonDir }));
3797
3816
 
3798
- const note = __testing.profilePinScopeNote(fixture.root);
3799
- assert.ok(note);
3800
- assert.doesNotMatch(note, /[\x00-\x1f\x7f-\x9f]/);
3801
- assert.doesNotMatch(note, /payload/);
3802
- assert.match(note, /profile-pin\.json/);
3817
+ // Windows cannot create this hostile filename. Redirect only its disk reads;
3818
+ // the real resolver still passes the unsanitized path to production rendering.
3819
+ const originalExistsSync = fs.existsSync;
3820
+ const originalReadFileSync = fs.readFileSync;
3821
+ let hostileExistsCalls = 0;
3822
+ let hostileReadCalls = 0;
3823
+ try {
3824
+ t.mock.method(fs, "existsSync", (path: Parameters<typeof existsSync>[0]) => {
3825
+ if (path === localPath) {
3826
+ hostileExistsCalls++;
3827
+ return originalExistsSync(safeLocalPath);
3828
+ }
3829
+ return originalExistsSync(path);
3830
+ });
3831
+ t.mock.method(fs, "readFileSync", (...args: Parameters<typeof readFileSync>) => {
3832
+ if (args[0] === localPath) {
3833
+ hostileReadCalls++;
3834
+ args[0] = safeLocalPath;
3835
+ }
3836
+ return originalReadFileSync(...args);
3837
+ });
3838
+ syncBuiltinESMExports();
3839
+
3840
+ const note = __testing.profilePinScopeNote(fixture.root);
3841
+ assert.ok(note);
3842
+ assert.doesNotMatch(note, /[\x00-\x1f\x7f-\x9f]/);
3843
+ assert.doesNotMatch(note, /payload/);
3844
+ assert.match(note, /profile-pin\.json/);
3845
+ assert.equal(hostileExistsCalls, 1);
3846
+ assert.equal(hostileReadCalls, 1);
3847
+ } finally {
3848
+ try {
3849
+ t.mock.restoreAll();
3850
+ } finally {
3851
+ syncBuiltinESMExports();
3852
+ }
3853
+ }
3854
+ assert.equal(fs.existsSync, originalExistsSync);
3855
+ assert.equal(fs.readFileSync, originalReadFileSync);
3856
+ assert.equal(existsSync, originalExistsSync);
3857
+ assert.equal(readFileSync, originalReadFileSync);
3803
3858
  });
3804
3859
 
3805
3860
  test("publish declares the profile in the worktree so the routing can be committed", async (t) => {
@@ -3882,7 +3937,7 @@ test("the tab of the pinned profile carries ⌂ and the screen opens on it", asy
3882
3937
  });
3883
3938
  await fixture.run("gentle:profiles");
3884
3939
  const tabLine = (rendered ?? "").split("\n")[1] ?? "";
3885
- assert.match(tabLine, /other ⌂/);
3940
+ assert.match(tabLine, /other ◉⌂/, "the pin present at startup is also the session's profile");
3886
3941
  assert.doesNotMatch(tabLine, /team ★⌂/);
3887
3942
  assert.equal(selectedProfileTitle(rendered ?? ""), "other", "a winning pin is the profile the screen opens on");
3888
3943
  });
@@ -4126,6 +4181,14 @@ function readValidProfilesStore(path: string) {
4126
4181
  return result.file;
4127
4182
  }
4128
4183
 
4184
+ /** A real persisted session started under the profile integration, so Enter can bind and persist. */
4185
+ function profileActionManager(root: string): SessionManager {
4186
+ const manager = SessionManager.create(root, join(root, "session-fixture"));
4187
+ manager.appendMessage({ role: "user", content: "isolated profile action", timestamp: 1 });
4188
+ createSessionProfileIntegration().start(manager, (type, data) => { manager.appendCustomEntry(type, data); }, { reason: "startup" });
4189
+ return manager;
4190
+ }
4191
+
4129
4192
  test("Enter switches the live orchestrator, binds the profile, and writes nothing", async (t) => {
4130
4193
  const { fixture, storePath, settingsPath, writeStore, writeSettings } = profilesStoreFixture(t);
4131
4194
  writeSettings();
@@ -4136,11 +4199,12 @@ test("Enter switches the live orchestrator, binds the profile, and writes nothin
4136
4199
  };
4137
4200
  resetSessionProfileBindingsForTesting();
4138
4201
  const notifications: Array<{ message: string; severity: string }> = [];
4202
+ const manager = profileActionManager(fixture.root);
4139
4203
  const ctx = {
4140
4204
  cwd: fixture.root,
4141
4205
  hasUI: true,
4142
4206
  ui: { notify(message: string, severity: string) { notifications.push({ message, severity }); } },
4143
- sessionManager: { getSessionId: () => "session-panel" },
4207
+ sessionManager: manager,
4144
4208
  modelRegistry: { find: () => ({ provider: "openai", id: "beta" }) },
4145
4209
  } as unknown as ExtensionContext;
4146
4210
  const models: unknown[] = [];
@@ -4154,16 +4218,18 @@ test("Enter switches the live orchestrator, binds the profile, and writes nothin
4154
4218
  await __testing.runProfilesPanelAction(ctx, live, storePath, file, { type: "use-session", name: "team" }, {});
4155
4219
  assert.deepEqual(models, [{ provider: "openai", id: "beta" }]);
4156
4220
  assert.deepEqual(thinking, ["high"]);
4157
- const binding = readSessionProfileBinding("session-panel");
4221
+ const binding = readSessionProfileBinding(manager.getSessionId());
4158
4222
  assert.equal(binding?.name, "team");
4159
4223
  assert.equal(binding?.modelProfiles.worker?.model, "openai/alpha");
4160
4224
  assert.equal(readFileSync(storePath, "utf8"), before.store, "the profiles store is untouched");
4161
4225
  assert.equal(readFileSync(settingsPath, "utf8"), before.settings, "Pi settings are untouched");
4162
4226
  assert.equal(existsSync(fixture.globalPath), false, "no global models.json is written");
4163
4227
  assert.equal(existsSync(join(fixture.root, ".pi", "subagents.json")), false, "no materialized store is written");
4228
+ assert.equal(manager.getBranch().filter((entry) => entry.type === "custom" && entry.customType === "gentle-pi.session-profile/v1").length, 1, "only the session profile record is written");
4164
4229
  const applied = notifications.at(-1)?.message ?? "";
4165
4230
  assert.match(applied, /bound profile "team" to this session/);
4166
4231
  assert.match(applied, /its tab shows ◉/);
4232
+ assert.match(applied, /persisted in this session/);
4167
4233
  assert.match(applied, /This session now runs on openai\/beta · high/);
4168
4234
  assert.match(applied, /Subagents and reviewers use this session's routing snapshot/);
4169
4235
  assert.match(applied, /global routing, pins, and materialized stores are untouched/);
@@ -4182,10 +4248,11 @@ test("Enter switches only the selecting session's orchestrator and leaves shared
4182
4248
  bindSessionProfile("other-session", "old", { worker: { model: "openai/old" } });
4183
4249
  const switches: string[] = [];
4184
4250
  const thinking: ThinkingLevel[] = [];
4251
+ const manager = profileActionManager(fixture.root);
4185
4252
  const ctx = {
4186
4253
  cwd: fixture.root, hasUI: true,
4187
4254
  ui: { notify() {} },
4188
- sessionManager: { getSessionId: () => "selecting-session" },
4255
+ sessionManager: manager,
4189
4256
  modelRegistry: { find: (provider: string, id: string) => ({ provider, id }) },
4190
4257
  } as unknown as ExtensionContext;
4191
4258
  const live = {
@@ -4196,7 +4263,7 @@ test("Enter switches only the selecting session's orchestrator and leaves shared
4196
4263
  await __testing.runProfilesPanelAction(ctx, live, storePath, readValidProfilesStore(storePath), { type: "use-session", name: "team" });
4197
4264
  assert.deepEqual(switches, ["openai/alpha"]);
4198
4265
  assert.deepEqual(thinking, ["high"]);
4199
- assert.equal(readSessionProfileBinding("selecting-session")?.name, "team");
4266
+ assert.equal(readSessionProfileBinding(manager.getSessionId())?.name, "team");
4200
4267
  assert.equal(readSessionProfileBinding("other-session")?.modelProfiles.worker?.model, "openai/old");
4201
4268
  assert.equal(readSessionProfileBinding("unbound-session"), undefined);
4202
4269
  assert.equal(readFileSync(storePath, "utf8"), beforeStore);
@@ -4207,11 +4274,13 @@ test("Enter switches only the selecting session's orchestrator and leaves shared
4207
4274
 
4208
4275
  test("reviewer routing uses the selecting session snapshot without leaking to other sessions", (t) => {
4209
4276
  const { fixture, writeStore } = profilesStoreFixture(t);
4210
- writeStore({ team: {} }, "team");
4277
+ // No active profile: an unbound session inherits none, so it reads the global routing.
4278
+ writeStore({ team: {} });
4211
4279
  mkdirSync(fixture.configHome, { recursive: true });
4212
4280
  writeFileSync(fixture.globalPath, JSON.stringify({ "review-risk": { model: "openai/global" }, "review-reliability": { model: "openai/global" } }));
4213
4281
  resetSessionProfileBindingsForTesting();
4214
- t.after(() => resetSessionProfileBindingsForTesting());
4282
+ resetFrozenInheritedProfilesForTesting();
4283
+ t.after(() => { resetSessionProfileBindingsForTesting(); resetFrozenInheritedProfilesForTesting(); });
4215
4284
  bindSessionProfile("selecting-session", "team", { "review-risk": { model: "openai/session", thinking: "high" } });
4216
4285
  const selected = __testing.readReviewerModelConfig(fixture.root, "selecting-session");
4217
4286
  assert.equal(selected["review-risk"]?.model, "openai/session");
@@ -4220,6 +4289,165 @@ test("reviewer routing uses the selecting session snapshot without leaking to ot
4220
4289
  assert.equal(__testing.readReviewerModelConfig(fixture.root, undefined)["review-risk"]?.model, "openai/global");
4221
4290
  });
4222
4291
 
4292
+ test("reviewer routing follows the profile the session froze at startup, not later global routing", (t) => {
4293
+ const { fixture, writeStore } = profilesStoreFixture(t);
4294
+ resetSessionProfileBindingsForTesting();
4295
+ resetFrozenInheritedProfilesForTesting();
4296
+ t.after(() => resetFrozenInheritedProfilesForTesting());
4297
+ writeStore({ sol: { "review-risk": { model: "openai/sol" } } }, "sol");
4298
+ writeFileSync(fixture.globalPath, JSON.stringify({ "review-risk": { model: "nan/flash" } }));
4299
+ freezeSessionProfileAtStartup({ sessionId: "frozen-session", cwd: fixture.root, configHome: fixture.configHome });
4300
+ assert.equal(__testing.reviewHostRelaySelection("risk", __testing.readReviewerModelConfig(fixture.root, "frozen-session")).selection, "openai/sol");
4301
+ assert.equal(__testing.reviewHostRelaySelection("risk", __testing.readReviewerModelConfig(fixture.root, undefined)).selection, "nan/flash");
4302
+ });
4303
+
4304
+ test("provider review roles fall back to the session profile orchestrator before the persisted default", (t) => {
4305
+ const { writeStore, writeSettings } = profilesStoreFixture(t);
4306
+ writeStore({ sol: {} }, "sol");
4307
+ writeSettings({ defaultProvider: "nan", defaultModel: "flash" });
4308
+ resetSessionProfileBindingsForTesting();
4309
+ t.after(() => resetSessionProfileBindingsForTesting());
4310
+ bindSessionProfile("bound-session", "sol", { orchestrator: { model: "openai/sol", thinking: "high" }, "review-validator": { model: "openai/validator" } });
4311
+ const routing = __testing.readReviewerModelConfig(process.cwd(), "bound-session");
4312
+ assert.deepEqual(__testing.reviewHostRelaySelection("review-refuter", routing), { selection: "openai/sol", thinking: "high", routingKey: "review-refuter" });
4313
+ assert.equal(__testing.reviewHostRelaySelection("review-validator", routing).selection, "openai/validator");
4314
+ assert.deepEqual(__testing.reviewHostRelaySelection("risk", routing), { routingKey: "review-risk" }, "lens roles stay fail-closed");
4315
+ assert.equal(__testing.reviewHostRelaySelection("review-refuter", {}).selection, "nan/flash", "without a session orchestrator the persisted default still applies");
4316
+ });
4317
+
4318
+ test("provider review roles skip the orchestrator fallback for an inherited profile", (t) => {
4319
+ const { fixture, writeStore, writeSettings } = profilesStoreFixture(t);
4320
+ resetSessionProfileBindingsForTesting();
4321
+ resetFrozenInheritedProfilesForTesting();
4322
+ t.after(() => resetFrozenInheritedProfilesForTesting());
4323
+ // Inherited routing drops the orchestrator key, so only Use in this session feeds the fallback.
4324
+ writeStore({ sol: { orchestrator: { model: "openai/sol" }, "review-risk": { model: "openai/sol-risk" } } }, "sol");
4325
+ writeSettings({ defaultProvider: "nan", defaultModel: "flash" });
4326
+ freezeSessionProfileAtStartup({ sessionId: "inherited-session", cwd: fixture.root, configHome: fixture.configHome });
4327
+ const routing = __testing.readReviewerModelConfig(fixture.root, "inherited-session");
4328
+ assert.equal(__testing.reviewHostRelaySelection("risk", routing).selection, "openai/sol-risk");
4329
+ assert.equal(__testing.reviewHostRelaySelection("review-refuter", routing).selection, "nan/flash");
4330
+ });
4331
+
4332
+ test("provider review roles skip the orchestrator fallback for a repository pin", (t) => {
4333
+ const { fixture, writeStore, writeSettings, localPinPath, writePin } = profilesStoreFixture(t);
4334
+ resetSessionProfileBindingsForTesting();
4335
+ resetFrozenInheritedProfilesForTesting();
4336
+ t.after(() => resetFrozenInheritedProfilesForTesting());
4337
+ // Pinned routing drops the orchestrator key, so the pin's own orchestrator never feeds the fallback.
4338
+ writeStore({ pinned: { orchestrator: { model: "openai/pinned" }, "review-risk": { model: "openai/pinned-risk" } } });
4339
+ writePin(localPinPath, "pinned");
4340
+ writeSettings({ defaultProvider: "nan", defaultModel: "flash" });
4341
+ const routing = __testing.readReviewerModelConfig(fixture.root, undefined);
4342
+ assert.equal(__testing.reviewHostRelaySelection("risk", routing).selection, "openai/pinned-risk");
4343
+ assert.equal(__testing.reviewHostRelaySelection("review-refuter", routing).selection, "nan/flash");
4344
+ assert.equal(__testing.reviewHostRelaySelection("review-validator", routing).selection, "nan/flash");
4345
+ });
4346
+
4347
+ test("reviewer routing keeps a frozen pin snapshot after the pin changes", (t) => {
4348
+ const { fixture, writeStore, writeSettings, localPinPath, writePin } = profilesStoreFixture(t);
4349
+ resetSessionProfileBindingsForTesting();
4350
+ resetFrozenInheritedProfilesForTesting();
4351
+ t.after(() => resetFrozenInheritedProfilesForTesting());
4352
+ writeStore({
4353
+ pinned: { orchestrator: { model: "openai/pinned" }, "review-risk": { model: "openai/pinned-risk" } },
4354
+ later: { "review-risk": { model: "openai/later-risk" }, "review-refuter": { model: "openai/later-refuter" } },
4355
+ });
4356
+ writePin(localPinPath, "pinned");
4357
+ writeSettings({ defaultProvider: "nan", defaultModel: "flash" });
4358
+ freezeSessionProfileAtStartup({ sessionId: "pinned-session", cwd: fixture.root, configHome: fixture.configHome });
4359
+ writePin(localPinPath, "later");
4360
+ const routing = __testing.readReviewerModelConfig(fixture.root, "pinned-session");
4361
+ assert.equal(__testing.reviewHostRelaySelection("risk", routing).selection, "openai/pinned-risk");
4362
+ assert.equal(__testing.reviewHostRelaySelection("review-refuter", routing).selection, "nan/flash");
4363
+ assert.equal(__testing.reviewHostRelaySelection("review-validator", routing).selection, "nan/flash");
4364
+ });
4365
+
4366
+ test("reviewer routing of a session frozen without a profile ignores a pin added later", (t) => {
4367
+ const { fixture, writeStore, localPinPath, writePin } = profilesStoreFixture(t);
4368
+ resetSessionProfileBindingsForTesting();
4369
+ resetFrozenInheritedProfilesForTesting();
4370
+ t.after(() => resetFrozenInheritedProfilesForTesting());
4371
+ writeStore({ later: { "review-risk": { model: "openai/later-risk" } } });
4372
+ mkdirSync(fixture.configHome, { recursive: true });
4373
+ writeFileSync(fixture.globalPath, JSON.stringify({ "review-risk": { model: "openai/global" } }));
4374
+ freezeSessionProfileAtStartup({ sessionId: "unpinned-session", cwd: fixture.root, configHome: fixture.configHome });
4375
+ writePin(localPinPath, "later");
4376
+ assert.equal(__testing.reviewHostRelaySelection("risk", __testing.readReviewerModelConfig(fixture.root, "unpinned-session")).selection, "openai/global");
4377
+ });
4378
+
4379
+ test("reviewer routing in follow mode reads the profile the target resolves now", (t) => {
4380
+ const { fixture, writeStore, localPinPath, writePin } = profilesStoreFixture(t);
4381
+ resetSessionProfileBindingsForTesting();
4382
+ resetFrozenInheritedProfilesForTesting();
4383
+ const previous = process.env.GENTLE_PI_PROFILE_FOLLOW;
4384
+ process.env.GENTLE_PI_PROFILE_FOLLOW = "1";
4385
+ t.after(() => {
4386
+ if (previous === undefined) delete process.env.GENTLE_PI_PROFILE_FOLLOW;
4387
+ else process.env.GENTLE_PI_PROFILE_FOLLOW = previous;
4388
+ resetFrozenInheritedProfilesForTesting();
4389
+ });
4390
+ writeStore({ sol: { "review-risk": { model: "openai/sol" } } }, "sol");
4391
+ mkdirSync(fixture.configHome, { recursive: true });
4392
+ writeFileSync(fixture.globalPath, JSON.stringify({ "review-risk": { model: "openai/global" } }));
4393
+ assert.equal(__testing.reviewHostRelaySelection("risk", __testing.readReviewerModelConfig(fixture.root, "follow-session")).selection, "openai/sol");
4394
+ writeStore({ sol: { "review-risk": { model: "openai/sol" } }, moon: { "review-risk": { model: "openai/moon" } } }, "moon");
4395
+ assert.equal(__testing.reviewHostRelaySelection("risk", __testing.readReviewerModelConfig(fixture.root, "follow-session")).selection, "openai/moon");
4396
+ });
4397
+
4398
+ test("provider review roles ignore an orchestrator saved in global routing", (t) => {
4399
+ const { fixture, writeStore, writeSettings } = profilesStoreFixture(t);
4400
+ resetSessionProfileBindingsForTesting();
4401
+ resetFrozenInheritedProfilesForTesting();
4402
+ writeStore({ team: {} });
4403
+ writeSettings({ defaultProvider: "nan", defaultModel: "flash" });
4404
+ mkdirSync(fixture.configHome, { recursive: true });
4405
+ writeFileSync(fixture.globalPath, JSON.stringify({ orchestrator: { model: "openai/stale" } }));
4406
+ const routing = __testing.readReviewerModelConfig(fixture.root, undefined);
4407
+ assert.equal(__testing.reviewHostRelaySelection("review-refuter", routing).selection, "nan/flash");
4408
+ assert.equal(__testing.reviewHostRelaySelection("review-validator", routing).selection, "nan/flash");
4409
+ });
4410
+
4411
+ test("reviewer routing of a session frozen without a profile uses a foreign repository's own pin", (t) => {
4412
+ const { fixture, writeStore } = profilesStoreFixture(t);
4413
+ resetSessionProfileBindingsForTesting();
4414
+ resetFrozenInheritedProfilesForTesting();
4415
+ t.after(() => resetFrozenInheritedProfilesForTesting());
4416
+ const foreignRoot = join(fixture.root, "foreign");
4417
+ const identity = (path: string) => path.startsWith(foreignRoot)
4418
+ ? { root: foreignRoot, commonDir: join(foreignRoot, ".git") }
4419
+ : { root: join(fixture.root, "worktree"), commonDir: join(fixture.root, "git-common") };
4420
+ setProfilePinWorktreeResolverForTesting(identity);
4421
+ writeStore({ theirs: { "review-risk": { model: "openai/theirs" } } });
4422
+ mkdirSync(fixture.configHome, { recursive: true });
4423
+ writeFileSync(fixture.globalPath, JSON.stringify({ "review-risk": { model: "openai/global" } }));
4424
+ freezeSessionProfileAtStartup({ sessionId: "home-session", cwd: fixture.root, configHome: fixture.configHome });
4425
+ const foreignPin = join(foreignRoot, ".git", "gentle-ai", "profile-pin.json");
4426
+ mkdirSync(dirname(foreignPin), { recursive: true });
4427
+ writeFileSync(foreignPin, `${JSON.stringify({ kind: PROFILE_PIN_KIND, version: PROFILE_PIN_VERSION, profile: "theirs" }, null, 2)}\n`);
4428
+ assert.equal(__testing.reviewHostRelaySelection("risk", __testing.readReviewerModelConfig(foreignRoot, "home-session", fixture.root)).selection, "openai/theirs");
4429
+ assert.equal(__testing.reviewHostRelaySelection("risk", __testing.readReviewerModelConfig(fixture.root, "home-session", fixture.root)).selection, "openai/global", "the session's own repository still ignores pins");
4430
+ });
4431
+
4432
+ test("reviewer routing of a session started outside Git uses the target repository's pin", (t) => {
4433
+ const { fixture, writeStore } = profilesStoreFixture(t);
4434
+ resetSessionProfileBindingsForTesting();
4435
+ resetFrozenInheritedProfilesForTesting();
4436
+ t.after(() => resetFrozenInheritedProfilesForTesting());
4437
+ const repoRoot = join(fixture.root, "repo");
4438
+ const outside = join(fixture.root, "outside");
4439
+ mkdirSync(outside, { recursive: true });
4440
+ setProfilePinWorktreeResolverForTesting((path: string) => path.startsWith(repoRoot) ? { root: repoRoot, commonDir: join(repoRoot, ".git") } : undefined);
4441
+ writeStore({ theirs: { "review-risk": { model: "openai/theirs" } } });
4442
+ mkdirSync(fixture.configHome, { recursive: true });
4443
+ writeFileSync(fixture.globalPath, JSON.stringify({ "review-risk": { model: "openai/global" } }));
4444
+ freezeSessionProfileAtStartup({ sessionId: "outside-session", cwd: outside, configHome: fixture.configHome });
4445
+ const pin = join(repoRoot, ".git", "gentle-ai", "profile-pin.json");
4446
+ mkdirSync(dirname(pin), { recursive: true });
4447
+ writeFileSync(pin, `${JSON.stringify({ kind: PROFILE_PIN_KIND, version: PROFILE_PIN_VERSION, profile: "theirs" }, null, 2)}\n`);
4448
+ assert.equal(__testing.reviewHostRelaySelection("risk", __testing.readReviewerModelConfig(repoRoot, "outside-session", outside)).selection, "openai/theirs");
4449
+ });
4450
+
4223
4451
  test("Enter preserves session-only routing when the orchestrator is absent or cannot switch", async (t) => {
4224
4452
  for (const rejected of [false, true]) {
4225
4453
  const { fixture, storePath, settingsPath, writeStore, writeSettings } = profilesStoreFixture(t);
@@ -4235,11 +4463,12 @@ test("Enter preserves session-only routing when the orchestrator is absent or ca
4235
4463
  const notifications: string[] = [];
4236
4464
  let modelCalls = 0;
4237
4465
  let thinkingCalls = 0;
4466
+ const manager = profileActionManager(fixture.root);
4238
4467
  const ctx = {
4239
4468
  cwd: fixture.root,
4240
4469
  hasUI: true,
4241
4470
  ui: { notify(message: string) { notifications.push(message); } },
4242
- sessionManager: { getSessionId: () => "session-panel" },
4471
+ sessionManager: manager,
4243
4472
  modelRegistry: { find: () => ({ provider: "openai", id: "beta" }) },
4244
4473
  } as unknown as ExtensionContext;
4245
4474
  const live = {
@@ -4250,7 +4479,7 @@ test("Enter preserves session-only routing when the orchestrator is absent or ca
4250
4479
  await __testing.runProfilesPanelAction(ctx, live, storePath, readValidProfilesStore(storePath), { type: "use-session", name: "team" }, {});
4251
4480
  assert.equal(modelCalls, rejected ? 1 : 0);
4252
4481
  assert.equal(thinkingCalls, 0);
4253
- assert.equal(readSessionProfileBinding("session-panel")?.modelProfiles.worker?.model, "openai/alpha");
4482
+ assert.equal(readSessionProfileBinding(manager.getSessionId())?.modelProfiles.worker?.model, "openai/alpha");
4254
4483
  assert.equal(readFileSync(storePath, "utf8"), storeBefore);
4255
4484
  assert.equal(readFileSync(settingsPath, "utf8"), settingsBefore);
4256
4485
  assert.equal(existsSync(fixture.globalPath), false);
@@ -4260,6 +4489,507 @@ test("Enter preserves session-only routing when the orchestrator is absent or ca
4260
4489
  }
4261
4490
  });
4262
4491
 
4492
+ test("u keeps the session binding when a subagent launch requires session profile authority (#2623)", async (t) => {
4493
+ const { fixture, storePath, writeStore, writeSettings } = profilesStoreFixture(t);
4494
+ writeSettings();
4495
+ writeStore({ team: { worker: { model: "openai/alpha" } } }, "team");
4496
+ resetSessionProfileBindingsForTesting();
4497
+ const manager = profileActionManager(fixture.root);
4498
+ const notifications: Array<{ message: string; severity: string }> = [];
4499
+ const ctx = {
4500
+ cwd: fixture.root,
4501
+ hasUI: true,
4502
+ ui: { notify(message: string, severity: string) { notifications.push({ message, severity }); } },
4503
+ sessionManager: manager,
4504
+ } as unknown as ExtensionContext;
4505
+ const live = {
4506
+ setModel: async () => true,
4507
+ setThinkingLevel() {},
4508
+ getThinkingLevel(): ThinkingLevel { return "medium"; },
4509
+ };
4510
+ await __testing.runProfilesPanelAction(ctx, live, storePath, readValidProfilesStore(storePath), { type: "use-session", name: "team" }, {});
4511
+ assert.equal(readSessionProfileBinding(manager.getSessionId())?.name, "team", "u binds the profile to the session");
4512
+ // Every subagent launch asks for session profile authority first; the u
4513
+ // binding must survive that check, not be dropped for missing disk state.
4514
+ const { requireSessionProfileAuthority } = await import("../lib/session-profile-authority.ts");
4515
+ const authority = requireSessionProfileAuthority(manager);
4516
+ assert.equal(authority.available, true);
4517
+ assert.equal(
4518
+ readSessionProfileBinding(manager.getSessionId())?.name,
4519
+ "team",
4520
+ "the session binding was dropped by the first subagent launch",
4521
+ );
4522
+ assert.equal(authority.binding?.name, "team", "authority does not publish the bound profile");
4523
+ resetSessionProfileBindingsForTesting();
4524
+ });
4525
+
4526
+ test("a reload landing while a models screen step is in flight closes the loop without touching the stale ctx", async (t) => {
4527
+ const { fixture, storePath, writeStore } = profilesStoreFixture(t);
4528
+ writeStore({ team: { worker: { model: "openai/alpha" } } }, undefined);
4529
+ const storeBefore = readFileSync(storePath, "utf8");
4530
+ let stale = false;
4531
+ let staleReads = 0;
4532
+ let screens = 0;
4533
+ const notifications: string[] = [];
4534
+ const ui = {
4535
+ notify(message: string) { notifications.push(message); },
4536
+ // The runner invalidates the ctx while this step is still pending.
4537
+ custom: async () => {
4538
+ screens += 1;
4539
+ await Promise.resolve();
4540
+ stale = true;
4541
+ return { type: "create-live" };
4542
+ },
4543
+ input: async () => "snapshot",
4544
+ };
4545
+ const guard = <T>(value: T): T => {
4546
+ if (stale) {
4547
+ staleReads += 1;
4548
+ throw new Error("stale ctx");
4549
+ }
4550
+ return value;
4551
+ };
4552
+ const ctx = {
4553
+ get cwd() { return guard(fixture.root); },
4554
+ hasUI: true,
4555
+ get ui() { return guard(ui); },
4556
+ get sessionManager() { return guard(profileActionManager(fixture.root)); },
4557
+ } as unknown as ExtensionContext;
4558
+ const live = { setModel: async () => true, setThinkingLevel() {}, getThinkingLevel: (): ThinkingLevel => "medium" };
4559
+ await __testing.openProfilesPanelLoop(ctx, live, "team");
4560
+ assert.equal(screens, 1, "the screen is not reopened on a stale ctx");
4561
+ assert.equal(staleReads, 1, "only the liveness probe touches the stale ctx");
4562
+ assert.deepEqual(notifications, []);
4563
+ assert.equal(readFileSync(storePath, "utf8"), storeBefore, "no profile is created from a stale ctx");
4564
+ });
4565
+
4566
+ test("Enter skipped by a session replacement while queued never touches the stale ctx", async (t) => {
4567
+ const { fixture, storePath, writeStore } = profilesStoreFixture(t);
4568
+ writeStore({ team: { worker: { model: "openai/alpha" } } }, undefined);
4569
+ resetSessionProfileBindingsForTesting();
4570
+ t.after(() => resetSessionProfileBindingsForTesting());
4571
+ const manager = profileActionManager(fixture.root);
4572
+ let stale = false;
4573
+ const notifications: string[] = [];
4574
+ const ui = { notify(message: string) { notifications.push(message); } };
4575
+ const ctx = {
4576
+ cwd: fixture.root,
4577
+ hasUI: true,
4578
+ get ui() { if (stale) throw new Error("stale ctx"); return ui; },
4579
+ get sessionManager() { if (stale) throw new Error("stale ctx"); return manager; },
4580
+ } as unknown as ExtensionContext;
4581
+ let release!: () => void;
4582
+ const holder = runCurrentSessionProfileSelection(manager, () => new Promise<void>((resolve) => { release = resolve; }));
4583
+ const live = { setModel: async () => true, setThinkingLevel() {}, getThinkingLevel: (): ThinkingLevel => "medium" };
4584
+ const enter = __testing.runProfilesPanelAction(ctx, live, storePath, readValidProfilesStore(storePath), { type: "use-session", name: "team" }, {});
4585
+ await new Promise((resolve) => setImmediate(resolve));
4586
+ const file = manager.getSessionFile();
4587
+ manager.getSessionFile = () => `${file}.replaced`;
4588
+ stale = true;
4589
+ release();
4590
+ await holder;
4591
+ await enter;
4592
+ assert.deepEqual(notifications, [], "no notice is sent through the stale ctx");
4593
+ assert.equal(readSessionProfileBinding(manager.getSessionId()), undefined);
4594
+ });
4595
+
4596
+ /** Runs `/gentle:profiles <args>` through the registered command on a real persisted session. */
4597
+ function profilesCommandHarness(t: test.TestContext, profiles: Record<string, unknown> = { team: { orchestrator: { model: "openai/beta", thinking: "high" }, worker: { model: "openai/alpha" } } }) {
4598
+ const { fixture, storePath, settingsPath, writeStore, writeSettings } = profilesStoreFixture(t);
4599
+ writeSettings();
4600
+ writeStore(profiles, undefined);
4601
+ resetSessionProfileBindingsForTesting();
4602
+ t.after(() => resetSessionProfileBindingsForTesting());
4603
+ const commands = new Map<string, Parameters<ExtensionAPI["registerCommand"]>[1]>();
4604
+ const handlers = new Map<string, (event: unknown, ctx: ExtensionContext) => Promise<void>>();
4605
+ const liveCalls: string[] = [];
4606
+ // Like Pi, `appendEntry` writes to the session the last start ran on.
4607
+ let started: SessionManager | undefined;
4608
+ createGentleAiExtension({ nativeReviewCli: null })({
4609
+ on(name: string, handler: (event: unknown, ctx: ExtensionContext) => Promise<void>) { handlers.set(name, handler); },
4610
+ appendEntry(type: string, data: unknown) { started!.appendCustomEntry(type, data); },
4611
+ registerTool() {},
4612
+ registerCommand(name, command) { commands.set(name, command); },
4613
+ setModel: async () => { liveCalls.push("model"); return true; },
4614
+ setThinkingLevel: () => { liveCalls.push("thinking"); },
4615
+ getThinkingLevel: () => "medium",
4616
+ } as unknown as ExtensionAPI);
4617
+ const notifications: Array<{ message: string; severity: string }> = [];
4618
+ const manager = profileActionManager(fixture.root);
4619
+ const ctx = {
4620
+ cwd: fixture.root,
4621
+ hasUI: true,
4622
+ ui: { notify(message: string, severity: string) { notifications.push({ message, severity }); } },
4623
+ sessionManager: manager,
4624
+ modelRegistry: { find: (provider: string, id: string) => ({ provider, id }) },
4625
+ } as unknown as ExtensionCommandContext;
4626
+ const family = () => manager.getBranch().filter((entry) => entry.type === "custom" && typeof entry.customType === "string" && entry.customType.startsWith("gentle-pi.session-profile/"));
4627
+ const before = { store: readFileSync(storePath, "utf8"), settings: readFileSync(settingsPath, "utf8") };
4628
+ const assertSharedUntouched = () => {
4629
+ assert.equal(readFileSync(storePath, "utf8"), before.store, "the profiles store is untouched");
4630
+ assert.equal(readFileSync(settingsPath, "utf8"), before.settings, "Pi settings are untouched");
4631
+ assert.equal(existsSync(fixture.globalPath), false, "no global models.json is written");
4632
+ assert.equal(existsSync(join(fixture.root, ".pi", "subagents.json")), false, "no materialized store is written");
4633
+ };
4634
+ return {
4635
+ manager, ctx, notifications, liveCalls, family, assertSharedUntouched, storePath,
4636
+ run: (args: string, runCtx: ExtensionCommandContext = ctx) => commands.get("gentle:profiles")!.handler(args, runCtx),
4637
+ start: (event: unknown, startCtx: ExtensionContext = ctx) => {
4638
+ started = startCtx.sessionManager as SessionManager;
4639
+ return handlers.get("session_start")!(event, startCtx);
4640
+ },
4641
+ last: () => notifications.at(-1) ?? { message: "", severity: "" },
4642
+ };
4643
+ }
4644
+
4645
+ test("/gentle:profiles clear removes the session binding and records an explicit clear", async (t) => {
4646
+ const h = profilesCommandHarness(t);
4647
+ const live = { setModel: async () => true, setThinkingLevel() {}, getThinkingLevel: (): ThinkingLevel => "medium" };
4648
+ await __testing.runProfilesPanelAction(h.ctx, live, h.storePath, readValidProfilesStore(h.storePath), { type: "use-session", name: "team" }, {});
4649
+ assert.equal(readSessionProfileBinding(h.manager.getSessionId())?.name, "team");
4650
+ h.liveCalls.length = 0;
4651
+ await h.run("clear");
4652
+ assert.equal(readSessionProfileBinding(h.manager.getSessionId()), undefined);
4653
+ assert.equal(h.family().length, 2, "one clear record follows the bind record");
4654
+ assert.deepEqual((h.family().at(-1) as { data?: unknown }).data, { kind: "clear" });
4655
+ assert.equal(h.last().severity, "info");
4656
+ assert.match(h.last().message, /cleared session profile "team"/);
4657
+ assert.match(h.last().message, /persisted in this session/);
4658
+ assert.match(h.last().message, /New launches use the routing without a session profile/);
4659
+ assert.match(h.last().message, /live orchestrator is unchanged/);
4660
+ assert.deepEqual(h.liveCalls, [], "clear never touches the live model or thinking");
4661
+ h.assertSharedUntouched();
4662
+ });
4663
+
4664
+ test("/gentle:profiles clear skipped by a session replacement while queued never touches the stale ctx", async (t) => {
4665
+ const h = profilesCommandHarness(t);
4666
+ let stale = false;
4667
+ const staleNotifications: string[] = [];
4668
+ const staleCtx = {
4669
+ cwd: h.ctx.cwd,
4670
+ hasUI: true,
4671
+ get ui() { if (stale) throw new Error("stale ctx"); return { notify(message: string) { staleNotifications.push(message); } }; },
4672
+ get sessionManager() { if (stale) throw new Error("stale ctx"); return h.manager; },
4673
+ } as unknown as ExtensionCommandContext;
4674
+ let release!: () => void;
4675
+ const holder = runCurrentSessionProfileSelection(h.manager, () => new Promise<void>((resolve) => { release = resolve; }));
4676
+ const clear = h.run("clear", staleCtx);
4677
+ await new Promise((resolve) => setImmediate(resolve));
4678
+ const file = h.manager.getSessionFile();
4679
+ h.manager.getSessionFile = () => `${file}.replaced`;
4680
+ stale = true;
4681
+ release();
4682
+ await holder;
4683
+ await clear;
4684
+ assert.deepEqual(staleNotifications, [], "no notice is sent through the stale ctx");
4685
+ assert.equal(h.family().length, 0, "nothing is written");
4686
+ });
4687
+
4688
+ test("/gentle:profiles clear with extra arguments shows the usage warning and writes nothing", async (t) => {
4689
+ const h = profilesCommandHarness(t);
4690
+ const live = { setModel: async () => true, setThinkingLevel() {}, getThinkingLevel: (): ThinkingLevel => "medium" };
4691
+ await __testing.runProfilesPanelAction(h.ctx, live, h.storePath, readValidProfilesStore(h.storePath), { type: "use-session", name: "team" }, {});
4692
+ const recordsBefore = h.family().length;
4693
+ await h.run("clear extra");
4694
+ assert.equal(h.last().severity, "warning");
4695
+ assert.match(h.last().message, /^Usage: \/gentle:profiles \[.*clear\]/);
4696
+ assert.equal(h.family().length, recordsBefore, "no clear record is appended");
4697
+ assert.equal(readSessionProfileBinding(h.manager.getSessionId())?.name, "team");
4698
+ await h.run(" clear ");
4699
+ assert.equal(readSessionProfileBinding(h.manager.getSessionId()), undefined, "surrounding whitespace still clears");
4700
+ });
4701
+
4702
+ test("/gentle:profiles clear on a never-bound session writes nothing and says so", async (t) => {
4703
+ const h = profilesCommandHarness(t);
4704
+ await h.run("clear");
4705
+ assert.equal(h.family().length, 0);
4706
+ assert.equal(readSessionProfileBinding(h.manager.getSessionId()), undefined);
4707
+ assert.equal(h.last().severity, "info");
4708
+ assert.match(h.last().message, /no session profile was ever selected in this session; nothing to clear/);
4709
+ h.assertSharedUntouched();
4710
+ });
4711
+
4712
+ for (const kind of ["in-memory", "unsaved"] as const)
4713
+ test(`/gentle:profiles clear on a never-bound ${kind} session writes nothing and keeps launches available`, async (t) => {
4714
+ const h = profilesCommandHarness(t);
4715
+ const manager = kind === "in-memory" ? SessionManager.inMemory(h.ctx.cwd) : SessionManager.create(h.ctx.cwd, join(h.ctx.cwd, "unsaved-sessions"));
4716
+ if (kind === "in-memory") manager.appendMessage({ role: "user", content: "unsaved conversation", timestamp: 1 });
4717
+ createSessionProfileIntegration().start(manager, (type, data) => { manager.appendCustomEntry(type, data); }, { reason: "startup" });
4718
+ (h.ctx as unknown as { sessionManager: unknown }).sessionManager = manager;
4719
+ await h.run("clear");
4720
+ assert.equal(manager.getBranch().filter((entry) => entry.type === "custom").length, 0, "no clear record is written");
4721
+ assert.equal(h.last().severity, "info");
4722
+ assert.match(h.last().message, /no session profile was ever selected in this session; nothing to clear/);
4723
+ const authority = readSessionProfileAuthority(manager);
4724
+ assert.equal(authority.available, true, "subagent launches stay available");
4725
+ assert.equal(authority.available && authority.binding, undefined);
4726
+ });
4727
+
4728
+ test("/gentle:profiles clear on an already-cleared session writes nothing and says so", async (t) => {
4729
+ const h = profilesCommandHarness(t);
4730
+ const live = { setModel: async () => true, setThinkingLevel() {}, getThinkingLevel: (): ThinkingLevel => "medium" };
4731
+ await __testing.runProfilesPanelAction(h.ctx, live, h.storePath, readValidProfilesStore(h.storePath), { type: "use-session", name: "team" }, {});
4732
+ await h.run("clear");
4733
+ await h.run("clear");
4734
+ assert.equal(h.family().length, 2, "the second clear appends nothing");
4735
+ assert.equal(h.last().severity, "info");
4736
+ assert.match(h.last().message, /session profile is already cleared; nothing to clear/);
4737
+ });
4738
+
4739
+ // gentle-shell#2742, section 3: the newest record carries the startup state.
4740
+ const TEAM_DEFINITION = { orchestrator: { model: "openai/beta", thinking: "high" as const }, worker: { model: "openai/alpha" } };
4741
+ const withFast = { team: TEAM_DEFINITION, fast: { worker: { model: "openai/gamma" } } };
4742
+ const useInSession = (h: ReturnType<typeof profilesCommandHarness>, name: string) =>
4743
+ __testing.runProfilesPanelAction(h.ctx, { setModel: async () => true, setThinkingLevel() {}, getThinkingLevel: (): ThinkingLevel => "medium" }, h.storePath, readValidProfilesStore(h.storePath), { type: "use-session", name }, {});
4744
+ const newest = (h: ReturnType<typeof profilesCommandHarness>) => (h.family().at(-1) as { data?: unknown }).data;
4745
+
4746
+ test("Use in this session carries a recorded startup profile and clear goes back to it", async (t) => {
4747
+ const h = profilesCommandHarness(t, withFast);
4748
+ const startup = createSessionProfileStartupBind("local", "team", TEAM_DEFINITION);
4749
+ h.manager.appendCustomEntry(SESSION_PROFILE_CUSTOM_TYPE, startup);
4750
+ await useInSession(h, "fast");
4751
+ assert.deepEqual(newest(h), createSessionProfileBind("fast", withFast.fast, { origin: "local", name: "team", modelProfiles: TEAM_DEFINITION }));
4752
+ await h.run("clear");
4753
+ assert.equal(h.family().length, 3);
4754
+ assert.deepEqual(newest(h), startup, "the startup bind is written again, orchestrator included");
4755
+ assert.equal(readSessionProfileBinding(h.manager.getSessionId())?.origin, "local");
4756
+ assert.equal(h.last().severity, "info");
4757
+ assert.equal(h.last().message, 'el Gentleman cleared session profile "fast" (persisted in this session). New launches go back to the profile this session started with, "team (local)", and use it. The live orchestrator is unchanged.');
4758
+ await h.run("clear");
4759
+ assert.equal(h.family().length, 3, "a startup record is already there: nothing is written");
4760
+ assert.equal(h.last().message, 'el Gentleman: this session is already on the profile it started with, "team (local)"; nothing to clear.');
4761
+ h.assertSharedUntouched();
4762
+ });
4763
+
4764
+ test("clear goes back to no profile when the newest record says the session started without one", async (t) => {
4765
+ const h = profilesCommandHarness(t, withFast);
4766
+ h.manager.appendCustomEntry(SESSION_PROFILE_CUSTOM_TYPE, createSessionProfileClear("none"));
4767
+ await h.run("clear");
4768
+ assert.equal(h.family().length, 1, "a startup-none record is already there: nothing is written");
4769
+ assert.equal(h.last().message, "el Gentleman: this session is already on no profile, as it started; nothing to clear.");
4770
+ await useInSession(h, "fast");
4771
+ assert.deepEqual(newest(h), createSessionProfileBind("fast", withFast.fast, "none"));
4772
+ await h.run("clear");
4773
+ assert.deepEqual(newest(h), { kind: "clear", startup: "none" });
4774
+ assert.equal(readSessionProfileBinding(h.manager.getSessionId()), undefined);
4775
+ assert.equal(h.last().message, 'el Gentleman cleared session profile "fast" (persisted in this session). New launches go back to no profile, as this session started. The live orchestrator is unchanged.');
4776
+ });
4777
+
4778
+ test("clear in follow mode writes a legacy clear even when the newest record carries the startup state", async (t) => {
4779
+ const h = profilesCommandHarness(t, withFast);
4780
+ h.manager.appendCustomEntry(SESSION_PROFILE_CUSTOM_TYPE, createSessionProfileBind("fast", withFast.fast, "none"));
4781
+ process.env.GENTLE_PI_PROFILE_FOLLOW = "1";
4782
+ t.after(() => { delete process.env.GENTLE_PI_PROFILE_FOLLOW; });
4783
+ await h.run("clear");
4784
+ assert.deepEqual(newest(h), { kind: "clear" });
4785
+ assert.match(h.last().message, /New launches use the routing without a session profile/);
4786
+ });
4787
+
4788
+ // gentle-shell#2742, section 6: follow mode has no startup state, so a startup
4789
+ // record on the newest entry is cleared like any bind, back to the current defaults.
4790
+ // The separator after the cleared subject is matched with `.`.
4791
+ for (const [record, subject] of [
4792
+ ["startup bind", 'session profile "team"'],
4793
+ ["clear with startup none", "the recorded startup state"],
4794
+ ] as const)
4795
+ test(`clear in follow mode appends a legacy clear when the newest record is a ${record}`, async (t) => {
4796
+ const h = profilesCommandHarness(t, withFast);
4797
+ h.manager.appendCustomEntry(SESSION_PROFILE_CUSTOM_TYPE, record === "startup bind" ? createSessionProfileStartupBind("local", "team", TEAM_DEFINITION) : createSessionProfileClear("none"));
4798
+ process.env.GENTLE_PI_PROFILE_FOLLOW = "1";
4799
+ t.after(() => { delete process.env.GENTLE_PI_PROFILE_FOLLOW; });
4800
+ await h.run("clear");
4801
+ assert.equal(h.family().length, 2, "one legacy clear follows the startup record");
4802
+ assert.deepEqual(newest(h), { kind: "clear" });
4803
+ assert.equal(h.last().severity, "info");
4804
+ assert.match(h.last().message, new RegExp(`^el Gentleman cleared ${subject} . persisted in this session\\. New launches use the routing without a session profile \\(pins, repository declaration, global\\)\\. The live orchestrator is unchanged\\.$`));
4805
+ h.assertSharedUntouched();
4806
+ });
4807
+
4808
+ // gentle-shell#2742, section 3: a resume is not the session's own start, even
4809
+ // with no conversation on its branch, so the defaults current at resume time are
4810
+ // not its startup state and a legacy user bind still clears to a legacy clear.
4811
+ test("clear after a resume with no conversation writes a legacy clear, not the resume-time defaults", async (t) => {
4812
+ const h = profilesCommandHarness(t, withFast);
4813
+ resetFrozenInheritedProfilesForTesting();
4814
+ t.after(() => resetFrozenInheritedProfilesForTesting());
4815
+ writeFileSync(h.storePath, `${JSON.stringify({ kind: PROFILES_KIND, version: PROFILES_VERSION, profiles: withFast, active: "team" }, null, 2)}\n`);
4816
+ const sessions = join(h.ctx.cwd, "resumed-sessions");
4817
+ const source = SessionManager.create(h.ctx.cwd, sessions);
4818
+ source.appendCustomEntry(SESSION_PROFILE_CUSTOM_TYPE, createSessionProfileBind("fast", withFast.fast));
4819
+ source.appendMessage({ role: "user", content: "flush the resumed fixture", timestamp: 1 });
4820
+ const file = source.getSessionFile()!;
4821
+ writeFileSync(file, `${readFileSync(file, "utf8").trim().split("\n").filter((line) => JSON.parse(line).type !== "message").join("\n")}\n`);
4822
+ const manager = SessionManager.open(file, sessions);
4823
+ assert.equal(manager.getBranch().some((entry) => entry.type === "message"), false, "the resumed branch has no conversation");
4824
+ const ctx = { ...h.ctx, sessionManager: manager } as unknown as ExtensionCommandContext;
4825
+ await h.start({ type: "session_start", reason: "resume" }, ctx);
4826
+ const family = () => manager.getBranch().filter((entry) => entry.type === "custom" && entry.customType === SESSION_PROFILE_CUSTOM_TYPE);
4827
+ assert.equal(family().length, 1, "the resume writes no record");
4828
+ await h.run("clear", ctx);
4829
+ assert.equal(family().length, 2, "one record follows the legacy bind");
4830
+ assert.deepEqual((family().at(-1) as { data?: unknown }).data, { kind: "clear" }, "an unknown startup state writes a legacy clear");
4831
+ assert.equal(readSessionProfileBinding(manager.getSessionId()), undefined);
4832
+ assert.equal(h.last().severity, "info");
4833
+ assert.match(h.last().message, /^el Gentleman cleared session profile "fast" . persisted in this session\. New launches use the routing without a session profile \(pins, repository declaration, global\)\. The live orchestrator is unchanged\.$/);
4834
+ });
4835
+
4836
+ test("clear after a session's own start goes back to the defaults it started with", async (t) => {
4837
+ const h = profilesCommandHarness(t, withFast);
4838
+ resetFrozenInheritedProfilesForTesting();
4839
+ t.after(() => resetFrozenInheritedProfilesForTesting());
4840
+ writeFileSync(h.storePath, `${JSON.stringify({ kind: PROFILES_KIND, version: PROFILES_VERSION, profiles: withFast, active: "team" }, null, 2)}\n`);
4841
+ const manager = SessionManager.create(h.ctx.cwd, join(h.ctx.cwd, "own-start-sessions"));
4842
+ const ctx = { ...h.ctx, sessionManager: manager } as unknown as ExtensionCommandContext;
4843
+ await h.start({ type: "session_start", reason: "startup" }, ctx);
4844
+ manager.appendMessage({ role: "user", content: "flush the own-start fixture", timestamp: 1 });
4845
+ await __testing.runProfilesPanelAction(ctx, { setModel: async () => true, setThinkingLevel() {}, getThinkingLevel: (): ThinkingLevel => "medium" }, h.storePath, readValidProfilesStore(h.storePath), { type: "use-session", name: "fast" }, {});
4846
+ await h.run("clear", ctx);
4847
+ const family = manager.getBranch().filter((entry) => entry.type === "custom" && entry.customType === SESSION_PROFILE_CUSTOM_TYPE);
4848
+ assert.equal(family.length, 2, "the clear follows the Use in this session bind");
4849
+ assert.deepEqual((family.at(-1) as { data?: unknown }).data, createSessionProfileStartupBind("global", "team", TEAM_DEFINITION));
4850
+ assert.match(h.last().message, /New launches go back to the profile this session started with, "team/);
4851
+ });
4852
+
4853
+ // Pi records a new session's model and thinking level before any extension sees
4854
+ // session_start, and records them again when it opens an existing session with no
4855
+ // conversation, so an own start is a session holding at most that one pair.
4856
+ test("Pi records the model and thinking level of a new session before session_start", async (t) => {
4857
+ const root = mkdtempSync(join(tmpdir(), "own-start-sdk-"));
4858
+ t.after(() => rmSync(root, { recursive: true, force: true }));
4859
+ const agentDir = join(root, "agent");
4860
+ mkdirSync(agentDir);
4861
+ const settingsManager = SettingsManager.inMemory({ compaction: { enabled: false }, retry: { enabled: false } });
4862
+ const modelRuntime = await ModelRuntime.create({ authPath: join(agentDir, "offline-auth.json"), modelsPath: null, refreshOnCreate: false });
4863
+ modelRuntime.registerProvider("offline-own-start", {
4864
+ api: "offline-own-start-test", apiKey: "offline-dummy", baseUrl: "http://offline.invalid",
4865
+ models: [{ id: "fixture", name: "Own start fixture", reasoning: false, input: ["text"], cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: 100000, maxTokens: 1000 }],
4866
+ streamSimple() { throw new Error("no request is expected"); },
4867
+ });
4868
+ const seen: { reason: string; types: string[] }[] = [];
4869
+ const loader = new DefaultResourceLoader({
4870
+ cwd: root, agentDir, settingsManager,
4871
+ noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true,
4872
+ extensionFactories: [(pi) => { pi.on("session_start", (event, ctx) => { seen.push({ reason: event.reason, types: ctx.sessionManager.getEntries().map((entry) => entry.type) }); }); }],
4873
+ });
4874
+ await loader.reload();
4875
+ const { session } = await createAgentSession({ cwd: root, agentDir, modelRuntime, model: modelRuntime.getModel("offline-own-start", "fixture")!, resourceLoader: loader, settingsManager, sessionManager: SessionManager.inMemory(root), tools: [] });
4876
+ try {
4877
+ await session.bindExtensions({});
4878
+ } finally {
4879
+ session.dispose();
4880
+ }
4881
+ assert.deepEqual(seen, [{ reason: "startup", types: ["model_change", "thinking_level_change"] }]);
4882
+ });
4883
+
4884
+ /** Use in this session, then clear; returns the record the clear appended. */
4885
+ async function useInSessionThenClear(h: ReturnType<typeof profilesCommandHarness>, ctx: ExtensionCommandContext, manager: SessionManager): Promise<unknown> {
4886
+ await __testing.runProfilesPanelAction(ctx, { setModel: async () => true, setThinkingLevel() {}, getThinkingLevel: (): ThinkingLevel => "medium" }, h.storePath, readValidProfilesStore(h.storePath), { type: "use-session", name: "fast" }, {});
4887
+ await h.run("clear", ctx);
4888
+ const family = manager.getBranch().filter((entry) => entry.type === "custom" && entry.customType === SESSION_PROFILE_CUSTOM_TYPE);
4889
+ return (family.at(-1) as { data?: unknown }).data;
4890
+ }
4891
+
4892
+ /** A saved session holding a legacy explicit bind and no conversation, reopened. */
4893
+ function reopenedLegacyBindSession(h: ReturnType<typeof profilesCommandHarness>, dir: string): SessionManager {
4894
+ const sessions = join(h.ctx.cwd, dir);
4895
+ const source = SessionManager.create(h.ctx.cwd, sessions);
4896
+ source.appendCustomEntry(SESSION_PROFILE_CUSTOM_TYPE, createSessionProfileBind("fast", withFast.fast));
4897
+ source.appendMessage({ role: "user", content: "flush the reopened fixture", timestamp: 1 });
4898
+ const file = source.getSessionFile()!;
4899
+ writeFileSync(file, `${readFileSync(file, "utf8").trim().split("\n").filter((line) => JSON.parse(line).type !== "message").join("\n")}\n`);
4900
+ const manager = SessionManager.open(file, sessions);
4901
+ assert.equal(manager.getEntries().some((entry) => entry.type === "message"), false, "the reopened session has no conversation");
4902
+ return manager;
4903
+ }
4904
+
4905
+ // gentle-shell#2742, section 3: a reload restarts this process's extensions, not
4906
+ // the session, so it never makes the defaults current at resume its startup state.
4907
+ test("clear after a resume and a reload writes a legacy clear, not the resume-time defaults", async (t) => {
4908
+ const h = profilesCommandHarness(t, withFast);
4909
+ resetFrozenInheritedProfilesForTesting();
4910
+ t.after(() => resetFrozenInheritedProfilesForTesting());
4911
+ writeFileSync(h.storePath, `${JSON.stringify({ kind: PROFILES_KIND, version: PROFILES_VERSION, profiles: withFast, active: "team" }, null, 2)}\n`);
4912
+ const manager = reopenedLegacyBindSession(h, "reload-sessions");
4913
+ const ctx = { ...h.ctx, sessionManager: manager } as unknown as ExtensionCommandContext;
4914
+ await h.start({ type: "session_start", reason: "resume" }, ctx);
4915
+ await h.start({ type: "session_start", reason: "reload" }, ctx);
4916
+ assert.deepEqual(await useInSessionThenClear(h, ctx, manager), { kind: "clear" }, "an unknown startup state writes a legacy clear");
4917
+ });
4918
+
4919
+ // The CLI reports "startup" when it opens an existing session file, and Pi then
4920
+ // records the model and thinking level again, so a profile record or an earlier
4921
+ // such pair means the session started before this process.
4922
+ for (const [subject, prepare] of [
4923
+ ["a legacy explicit bind", (manager: SessionManager) => { manager.appendModelChange("openai", "alpha"); manager.appendThinkingLevelChange("medium"); }],
4924
+ ["an earlier start", (manager: SessionManager) => { for (const _ of [1, 2]) { manager.appendModelChange("openai", "alpha"); manager.appendThinkingLevelChange("medium"); } }],
4925
+ ] as const) {
4926
+ test(`clear after a startup on a saved session with ${subject} and no conversation writes a legacy clear`, async (t) => {
4927
+ const h = profilesCommandHarness(t, withFast);
4928
+ resetFrozenInheritedProfilesForTesting();
4929
+ t.after(() => resetFrozenInheritedProfilesForTesting());
4930
+ writeFileSync(h.storePath, `${JSON.stringify({ kind: PROFILES_KIND, version: PROFILES_VERSION, profiles: withFast, active: "team" }, null, 2)}\n`);
4931
+ const manager = subject === "a legacy explicit bind" ? reopenedLegacyBindSession(h, "reopened-sessions") : SessionManager.create(h.ctx.cwd, join(h.ctx.cwd, "reopened-sessions"));
4932
+ prepare(manager);
4933
+ const ctx = { ...h.ctx, sessionManager: manager } as unknown as ExtensionCommandContext;
4934
+ await h.start({ type: "session_start", reason: "startup" }, ctx);
4935
+ assert.deepEqual(await useInSessionThenClear(h, ctx, manager), { kind: "clear" }, "an unknown startup state writes a legacy clear");
4936
+ });
4937
+ }
4938
+
4939
+ for (const reason of ["startup", "new"] as const) {
4940
+ test(`clear after a new session's ${reason} start, as Pi records it, goes back to the defaults it started with`, async (t) => {
4941
+ const h = profilesCommandHarness(t, withFast);
4942
+ resetFrozenInheritedProfilesForTesting();
4943
+ t.after(() => resetFrozenInheritedProfilesForTesting());
4944
+ writeFileSync(h.storePath, `${JSON.stringify({ kind: PROFILES_KIND, version: PROFILES_VERSION, profiles: withFast, active: "team" }, null, 2)}\n`);
4945
+ const manager = SessionManager.create(h.ctx.cwd, join(h.ctx.cwd, "new-sessions"));
4946
+ manager.appendModelChange("openai", "alpha");
4947
+ manager.appendThinkingLevelChange("medium");
4948
+ const ctx = { ...h.ctx, sessionManager: manager } as unknown as ExtensionCommandContext;
4949
+ await h.start(reason === "new" ? { type: "session_start", reason, previousSessionFile: join(h.ctx.cwd, "previous.jsonl") } : { type: "session_start", reason }, ctx);
4950
+ manager.appendMessage({ role: "user", content: "flush the new-session fixture", timestamp: 1 });
4951
+ assert.deepEqual(await useInSessionThenClear(h, ctx, manager), createSessionProfileStartupBind("global", "team", TEAM_DEFINITION));
4952
+ assert.match(h.last().message, /New launches go back to the profile this session started with, "team/);
4953
+ });
4954
+ }
4955
+
4956
+ test("/gentle:profiles clear without a parent session id fails loud and writes nothing", async (t) => {
4957
+ const h = profilesCommandHarness(t);
4958
+ (h.ctx as unknown as { sessionManager: unknown }).sessionManager = { getSessionId: () => "" };
4959
+ await h.run("clear");
4960
+ assert.equal(h.family().length, 0);
4961
+ assert.equal(h.last().severity, "warning");
4962
+ assert.match(h.last().message, /cannot clear the session profile: no parent session id is available here/);
4963
+ h.assertSharedUntouched();
4964
+ });
4965
+
4966
+ for (const [customType, kind] of [["gentle-pi.session-profile/v1", "invalid"], ["gentle-pi.session-profile/v99", "from a newer version"]] as const)
4967
+ test(`an unreadable session profile record (${customType}) warns with its location and clear recovers`, async (t) => {
4968
+ const h = profilesCommandHarness(t);
4969
+ h.manager.appendCustomEntry(customType, { invalid: true });
4970
+ const entryIndex = h.manager.getBranch().length - 1;
4971
+ __testing.notifySessionProfileProblem(h.ctx);
4972
+ assert.equal(h.last().severity, "warning");
4973
+ assert.ok(h.last().message.includes(h.manager.getSessionFile()!), "names the session file");
4974
+ assert.match(h.last().message, new RegExp(`entry ${entryIndex}\\b`));
4975
+ assert.match(h.last().message, new RegExp(`is ${kind}`));
4976
+ assert.match(h.last().message, /Subagent launches are blocked/);
4977
+ assert.match(h.last().message, /Select a profile with Enter or run \/gentle:profiles clear/);
4978
+ await h.run("clear");
4979
+ assert.equal(h.last().severity, "info");
4980
+ assert.match(h.last().message, /cleared the unreadable session profile record/);
4981
+ assert.deepEqual((h.family().at(-1) as { data?: unknown }).data, { kind: "clear" }, "an unknown startup state writes a legacy clear");
4982
+ const count = h.notifications.length;
4983
+ __testing.notifySessionProfileProblem(h.ctx);
4984
+ assert.equal(h.notifications.length, count, "a recovered session raises no warning");
4985
+ });
4986
+
4987
+ test("a readable or absent session profile raises no warning", async (t) => {
4988
+ const h = profilesCommandHarness(t);
4989
+ __testing.notifySessionProfileProblem(h.ctx);
4990
+ assert.equal(h.notifications.length, 0);
4991
+ });
4992
+
4263
4993
  test("a keeps the legacy global apply semantics", async (t) => {
4264
4994
  const { fixture, storePath, writeStore } = profilesStoreFixture(t);
4265
4995
  writeStore({ team: { worker: { model: "openai/alpha" } }, old: {} }, "old");
@@ -4284,16 +5014,17 @@ test("Enter with a winning pin binds the session and never touches the pin layer
4284
5014
  const pinBefore = readFileSync(localPinPath, "utf8");
4285
5015
  const storeBefore = readFileSync(storePath, "utf8");
4286
5016
  resetSessionProfileBindingsForTesting();
5017
+ const manager = profileActionManager(fixture.root);
4287
5018
  const ctx = {
4288
5019
  cwd: fixture.root,
4289
5020
  hasUI: true,
4290
5021
  ui: { notify() {} },
4291
- sessionManager: { getSessionId: () => "session-panel" },
5022
+ sessionManager: manager,
4292
5023
  } as unknown as ExtensionContext;
4293
5024
  const live = { setModel: async () => true, setThinkingLevel() {}, getThinkingLevel(): ThinkingLevel { return "medium"; } };
4294
5025
  const file = readValidProfilesStore(storePath);
4295
5026
  await __testing.runProfilesPanelAction(ctx, live, storePath, file, { type: "use-session", name: "team" }, {});
4296
- assert.equal(readSessionProfileBinding("session-panel")?.name, "team");
5027
+ assert.equal(readSessionProfileBinding(manager.getSessionId())?.name, "team");
4297
5028
  assert.equal(readFileSync(localPinPath, "utf8"), pinBefore, "the clone pin is untouched");
4298
5029
  assert.equal(readFileSync(storePath, "utf8"), storeBefore, "the store is untouched");
4299
5030
  assert.equal(existsSync(fixture.globalPath), false);
@@ -4338,6 +5069,188 @@ test("Enter without a parent session id fails loud and writes nothing", async (t
4338
5069
  resetSessionProfileBindingsForTesting();
4339
5070
  });
4340
5071
 
5072
+ // gentle-shell#1064 slice 3c: the routing screen shows the profile this session launches with.
5073
+ function freezeScreenSession(fixture: ReturnType<typeof routingConsumerFixture>): void {
5074
+ freezeSessionProfileAtStartup({ sessionId: "session-panel", cwd: fixture.root, configHome: fixture.configHome });
5075
+ }
5076
+
5077
+ /** The first screen bare `/gentle:profiles` opens, as text, closed right after. */
5078
+ async function openedScreen(fixture: ReturnType<typeof routingConsumerFixture>, width = 120): Promise<string> {
5079
+ let rendered: string | undefined;
5080
+ fixture.onInput((panel) => {
5081
+ rendered ??= stripAnsi(panel.render(width).join("\n"));
5082
+ panel.handleInput("\x1b");
5083
+ });
5084
+ await fixture.run("gentle:profiles");
5085
+ return rendered ?? "";
5086
+ }
5087
+
5088
+ const screenTabLine = (rendered: string) => rendered.split("\n")[1] ?? "";
5089
+ const screenWorkerRow = (rendered: string) => rendered.split("\n").find((line) => /│\s*worker\s/.test(line)) ?? "";
5090
+ const flatScreen = (rendered: string) => rendered.replace(/\s*│\s*/g, " ").replace(/\s+/g, " ");
5091
+ const savedRoutingNotice = (rendered: string, name: string) =>
5092
+ flatScreen(rendered).includes(`Saved "${name}" differs from this session's launches; Use in this session adopts it.`);
5093
+ const authorityNotice = "Session profile authority is unavailable; affected launches are blocked. Use in this session selects one.";
5094
+
5095
+ /** A real session frozen on "team"; `unreadable` appends a session profile record it cannot read. */
5096
+ function frozenRealSession(fixture: ReturnType<typeof routingConsumerFixture>, unreadable: boolean): void {
5097
+ const manager = profileActionManager(fixture.root);
5098
+ freezeSessionProfileAtStartup({ sessionId: manager.getSessionId(), cwd: fixture.root, configHome: fixture.configHome });
5099
+ if (unreadable) manager.appendCustomEntry("gentle-pi.session-profile/v99", { invalid: true });
5100
+ fixture.useSessionManager(manager);
5101
+ }
5102
+
5103
+ test("a frozen profile is not marked as used while session profile authority is unavailable", async (t) => {
5104
+ const { fixture, writeStore } = profilesStoreFixture(t);
5105
+ writeStore({ team: { worker: { model: "openai/alpha" } }, other: {} }, "team");
5106
+ frozenRealSession(fixture, false);
5107
+ const available = await openedScreen(fixture);
5108
+ assert.match(screenTabLine(available), /team ◉/);
5109
+ assert.doesNotMatch(flatScreen(available), /authority is unavailable/);
5110
+
5111
+ frozenRealSession(fixture, true);
5112
+ const rendered = await openedScreen(fixture, 40);
5113
+ assert.doesNotMatch(rendered, /◉|Used in this session\./);
5114
+ assert.ok(flatScreen(rendered).includes(authorityNotice), "the whole notice fits at 40 columns");
5115
+
5116
+ t.after(() => resetSessionProfileBindingsForTesting());
5117
+ actOnProfile(fixture, "u", "team");
5118
+ await fixture.run("gentle:profiles");
5119
+ const recovered = fixture.panels.at(-1) ?? "";
5120
+ assert.match(screenTabLine(recovered), /team ◉/, "Use in this session recovers");
5121
+ assert.doesNotMatch(flatScreen(recovered), /authority is unavailable/);
5122
+ });
5123
+
5124
+ test("From what's running now refuses while session profile authority is unavailable", async (t) => {
5125
+ const { fixture, storePath, writeStore } = profilesStoreFixture(t);
5126
+ writeStore({ team: { worker: { model: "openai/alpha" } } }, "team");
5127
+ frozenRealSession(fixture, true);
5128
+ const before = readFileSync(storePath, "utf8");
5129
+ const reopened = await runProfilesNameAction(fixture, SCREEN_KEYS.newFromLive);
5130
+ assert.equal(fixture.inputPrompts.length, 0, "no name is asked for");
5131
+ assert.match(profilesPanelFooter(reopened), /Session profile authority is unavailable; affected launches are blocked\. No profile created\./);
5132
+ assert.equal(readFileSync(storePath, "utf8"), before);
5133
+ });
5134
+
5135
+ test("a profile frozen at startup carries ◉ and opens first after the default changes", async (t) => {
5136
+ const { fixture, storePath, writeStore } = profilesStoreFixture(t);
5137
+ const profiles = { team: { worker: { model: "openai/alpha" } }, other: { worker: { model: "openai/beta" } } };
5138
+ writeStore(profiles, "team");
5139
+ freezeScreenSession(fixture);
5140
+ writeStore(profiles, "other");
5141
+ const before = readFileSync(storePath, "utf8");
5142
+ const rendered = await openedScreen(fixture);
5143
+ assert.match(screenTabLine(rendered), /team ◉(\s|$)/);
5144
+ assert.match(screenTabLine(rendered), /other ★(\s|$)/);
5145
+ assert.equal(selectedProfileTitle(rendered), "team");
5146
+ assert.match(screenWorkerRow(rendered), /openai\/alpha/);
5147
+ assert.match(rendered, /Used in this session\./);
5148
+ assert.equal(savedRoutingNotice(rendered, "team"), false, "the saved routing matches the launch routing");
5149
+ assert.doesNotMatch(flatScreen(rendered), /authority is unavailable/);
5150
+ assert.equal(readFileSync(storePath, "utf8"), before);
5151
+ });
5152
+
5153
+ test("a session profile edited in profiles.json after the freeze or the binding says its launches keep the older routing", async (t) => {
5154
+ const { fixture, writeStore } = profilesStoreFixture(t);
5155
+ writeStore({ team: { worker: { model: "openai/alpha" } } }, "team");
5156
+ freezeScreenSession(fixture);
5157
+ writeStore({ team: { worker: { model: "openai/beta" } } }, "team");
5158
+ const frozen = await openedScreen(fixture);
5159
+ assert.match(screenWorkerRow(frozen), /openai\/beta/);
5160
+ assert.equal(savedRoutingNotice(frozen, "team"), true);
5161
+ assert.equal(savedRoutingNotice(await openedScreen(fixture, 40), "team"), true, "the whole notice fits at 40 columns");
5162
+
5163
+ resetFrozenInheritedProfilesForTesting();
5164
+ t.after(() => resetSessionProfileBindingsForTesting());
5165
+ bindSessionProfile("session-panel", "team", { worker: { model: "openai/alpha" } });
5166
+ assert.equal(savedRoutingNotice(await openedScreen(fixture), "team"), true);
5167
+ });
5168
+
5169
+ test("an Enter binding opens on its profile while another is the default (#2451)", async (t) => {
5170
+ const { fixture, writeStore } = profilesStoreFixture(t);
5171
+ writeStore({ team: { worker: { model: "openai/alpha" } }, other: { worker: { model: "openai/beta" } } }, "other");
5172
+ t.after(() => resetSessionProfileBindingsForTesting());
5173
+ bindSessionProfile("session-panel", "team", { worker: { model: "openai/alpha" } });
5174
+ const rendered = await openedScreen(fixture);
5175
+ assert.match(screenTabLine(rendered), /team ◉(\s|$)/);
5176
+ assert.match(screenTabLine(rendered), /other ★(\s|$)/);
5177
+ assert.equal(selectedProfileTitle(rendered), "team");
5178
+ assert.match(screenWorkerRow(rendered), /openai\/alpha/);
5179
+ assert.doesNotMatch(screenWorkerRow(rendered), /openai\/beta/);
5180
+ });
5181
+
5182
+ test("a pin present at startup is the session profile: ◉ and ⌂ on it, rows show its models (#2276)", async (t) => {
5183
+ const { fixture, writeStore, writePin, localPinPath } = profilesStoreFixture(t);
5184
+ writeStore({ team: { worker: { model: "openai/alpha" } }, other: { worker: { model: "openai/beta" } } }, "team");
5185
+ writePin(localPinPath, "other");
5186
+ freezeScreenSession(fixture);
5187
+ const rendered = await openedScreen(fixture);
5188
+ assert.match(screenTabLine(rendered), /other ◉⌂/);
5189
+ assert.match(screenTabLine(rendered), /team ★(\s|$)/);
5190
+ assert.equal(selectedProfileTitle(rendered), "other");
5191
+ assert.match(screenWorkerRow(rendered), /openai\/beta/);
5192
+ });
5193
+
5194
+ test("a session without a profile marks no tab with ◉", async (t) => {
5195
+ const { fixture, writeStore } = profilesStoreFixture(t);
5196
+ writeStore({ team: { worker: { model: "openai/alpha" } }, other: {} }, undefined);
5197
+ freezeScreenSession(fixture);
5198
+ const rendered = await openedScreen(fixture);
5199
+ assert.doesNotMatch(rendered, /◉|Used in this session/);
5200
+ assert.equal(selectedProfileTitle(rendered), "team");
5201
+ });
5202
+
5203
+ test("a frozen profile deleted from profiles.json is named, and no tab carries ◉", async (t) => {
5204
+ const { fixture, writeStore } = profilesStoreFixture(t);
5205
+ writeStore({ team: { worker: { model: "openai/alpha" } }, other: {} }, "team");
5206
+ freezeScreenSession(fixture);
5207
+ writeStore({ other: {} }, undefined);
5208
+ const rendered = await openedScreen(fixture);
5209
+ assert.doesNotMatch(rendered, /◉/);
5210
+ assert.match(
5211
+ rendered.replace(/\s*│\s*/g, " ").replace(/\s+/g, " "),
5212
+ /This session launches with "team", which is no longer in profiles\.json; its launches keep that routing\./,
5213
+ );
5214
+ });
5215
+
5216
+ test("From what's running now in a frozen session saves the frozen routing, not the global one or a later pin", async (t) => {
5217
+ const { fixture, storePath, settingsPath, writeStore, writeSettings, writePin, localPinPath } = profilesStoreFixture(t);
5218
+ writeSettings();
5219
+ mkdirSync(fixture.configHome, { recursive: true });
5220
+ writeFileSync(fixture.globalPath, `${JSON.stringify({ worker: { model: "openai/gamma" } }, null, 2)}\n`);
5221
+ writeStore({ team: { worker: { model: "openai/alpha", thinking: "high" } }, other: { worker: { model: "openai/beta" } } }, "team");
5222
+ freezeScreenSession(fixture);
5223
+ writePin(localPinPath, "other");
5224
+ const before = { models: readFileSync(fixture.globalPath, "utf8"), pin: readFileSync(localPinPath, "utf8"), settings: readFileSync(settingsPath, "utf8") };
5225
+ await runProfilesNameAction(fixture, SCREEN_KEYS.newFromLive, "captured");
5226
+ const store = JSON.parse(readFileSync(storePath, "utf8"));
5227
+ assert.deepEqual(store.profiles, {
5228
+ team: { worker: { model: "openai/alpha", thinking: "high" } },
5229
+ other: { worker: { model: "openai/beta" } },
5230
+ captured: { worker: { model: "openai/alpha", thinking: "high" }, orchestrator: { model: "nan/deepseek-v4-flash", thinking: "high" } },
5231
+ });
5232
+ assert.equal(store.active, "team");
5233
+ assert.deepEqual({ models: readFileSync(fixture.globalPath, "utf8"), pin: readFileSync(localPinPath, "utf8"), settings: readFileSync(settingsPath, "utf8") }, before);
5234
+ });
5235
+
5236
+ test("the subagents.json notice follows whether the session resolves a profile, not the pin", async (t) => {
5237
+ const { fixture, writeStore, writePin, localPinPath } = profilesStoreFixture(t);
5238
+ writeFileSync(join(fixture.root, ".pi", "subagents.json"), `${JSON.stringify({ model_profiles: { explor: { model: "openai/beta" } } }, null, 2)}\n`);
5239
+ writeStore({ team: { worker: { model: "openai/alpha" } } }, "team");
5240
+ freezeScreenSession(fixture);
5241
+ const frozen = await openedScreen(fixture);
5242
+ assert.match(frozen, /Used in this session\./);
5243
+ assert.doesNotMatch(frozen, /subagents\.json routes/, "the frozen profile replaces those keys");
5244
+
5245
+ resetFrozenInheritedProfilesForTesting();
5246
+ writeStore({ team: { worker: { model: "openai/alpha" } } }, undefined);
5247
+ freezeScreenSession(fixture);
5248
+ writePin(localPinPath, "team");
5249
+ const unfrozen = await openedScreen(fixture);
5250
+ assert.match(unfrozen, /Used in this repo\./);
5251
+ assert.match(unfrozen, /subagents\.json routes "explor", which no agent matches, so it is ignored\./, "a pin written after the freeze does not replace them");
5252
+ });
5253
+
4341
5254
  test("file operations are subcommands: profiles restore-routing, export and import, and usage for anything else", async (t) => {
4342
5255
  const { fixture, storePath, writeStore } = profilesStoreFixture(t);
4343
5256
  writeStore({ team: { worker: { model: "openai/alpha", thinking: "high" } } }, "team");
@@ -4369,7 +5282,7 @@ test("file operations are subcommands: profiles restore-routing, export and impo
4369
5282
 
4370
5283
  for (const args of ["export", "export ghost", "publish", "frobnicate", "restore", "export-routing extra"]) {
4371
5284
  await fixture.run("gentle:profiles", args);
4372
- assert.match(fixture.notifications.at(-1)?.message ?? "", /Usage: \/gentle:profiles \[export <name> \| import \| publish <name> \| export-routing \| restore-routing\]/, args);
5285
+ assert.match(fixture.notifications.at(-1)?.message ?? "", /Usage: \/gentle:profiles \[export <name> \| import \| publish <name> \| export-routing \| restore-routing \| clear\]/, args);
4373
5286
  }
4374
5287
  assert.equal(fixture.panelVisits(), 0, "no subcommand opens the screen");
4375
5288
  });
@@ -4443,3 +5356,64 @@ test("switching profile tabs redraws in place: the overlay never closes and reop
4443
5356
  assert.match(profilesPanelFooter(saved ?? ""), /Saved "other"\. Showing "team"\./);
4444
5357
  assert.deepEqual(JSON.parse(readFileSync(storePath, "utf8")).profiles.other, { worker: { model: "openai/alpha", thinking: "high" } });
4445
5358
  });
5359
+
5360
+ test("models screen edits each agent's fallback chain: f opens it, f adds, e sets effort, shift+↑ moves, x removes", () => {
5361
+ const saved = new Map<string, Array<{ model: string; thinking?: string }>>();
5362
+ const writes: string[] = [];
5363
+ const fallbacks = {
5364
+ chain: (profile: string, key: string) => saved.get(`${profile}:${key}`) ?? [],
5365
+ save: (profile: string, key: string, chain: ReadonlyArray<{ model: string; thinking?: string }>) => {
5366
+ saved.set(`${profile}:${key}`, chain.map((step) => ({ ...step })));
5367
+ writes.push(`${key}=${chain.map((step) => step.model + (step.thinking ? `:${step.thinking}` : "")).join(",")}`);
5368
+ return undefined;
5369
+ },
5370
+ };
5371
+ const down = "\x1b[B";
5372
+ const right = "\x1b[C";
5373
+ const shiftUp = "\x1b[1;2A";
5374
+ const lines = __testing.routingTablePanel(screenConfig(), SCREEN_MODELS, SCREEN_AGENTS, 100, undefined, 30,
5375
+ [down, down, "f", "f", "\r", "f", "\r", "e", right, right, right, "\r", shiftUp, "x", "\x1b"], [], [],
5376
+ { file: screenFile(), sessionBoundName: "current", fallbacks } as never);
5377
+ assert.deepEqual(writes, [
5378
+ "gentle-ai-explore=nan/glm5.3",
5379
+ "gentle-ai-explore=nan/glm5.3,openai/gpt-5.5",
5380
+ "gentle-ai-explore=nan/glm5.3,openai/gpt-5.5:low",
5381
+ "gentle-ai-explore=openai/gpt-5.5:low,nan/glm5.3",
5382
+ "gentle-ai-explore=nan/glm5.3",
5383
+ ], "the agent's own model and models already in the chain are not offered");
5384
+ const plain = lines.map(stripAnsi).join("\n");
5385
+ assert.match(plain, /gentle-ai-explore\s+nan\/deepseek-v4-flash\s+high\s+↪ nan\/glm5\.3/, "the row shows its chain");
5386
+ assert.match(plain, /f fallbacks/, "the key is advertised");
5387
+ });
5388
+
5389
+ test("models screen fallback card explains itself and the * chain belongs to the every-agent row", () => {
5390
+ const saved = new Map<string, Array<{ model: string }>>([["current:*", [{ model: "openai/gpt-5.5" }]]]);
5391
+ const fallbacks = { chain: (profile: string, key: string) => saved.get(`${profile}:${key}`) ?? [], save: () => undefined };
5392
+ const card = __testing.routingTablePanel(screenConfig(), SCREEN_MODELS, SCREEN_AGENTS, 100, undefined, 30, ["\x1b[B", "f"], [], [], { file: screenFile(), sessionBoundName: "current", fallbacks } as never).map(stripAnsi).join("\n");
5393
+ assert.match(card, /Fallbacks for every agent/);
5394
+ assert.match(card, /1\. openai\/gpt-5\.5/);
5395
+ assert.match(card, /used in order when the model runs out or keeps failing/i);
5396
+ assert.match(card, /f add · e effort · shift\+↑↓ move · x remove · esc back/);
5397
+ const failing = { chain: () => [], save: () => "profile-fallbacks.json is malformed; fix or remove it first." };
5398
+ const refused = __testing.routingTablePanel(screenConfig(), SCREEN_MODELS, SCREEN_AGENTS, 100, undefined, 30, ["\x1b[B", "\x1b[B", "f", "f", "\r"], [], [], { file: screenFile(), sessionBoundName: "current", fallbacks: failing } as never).map(stripAnsi).join("\n");
5399
+ assert.match(refused, /malformed; fix or remove it first/, "a refused write is reported, not hidden");
5400
+ });
5401
+
5402
+ test("models screen keeps ↑↓ agent at 72 columns; the fallbacks key yields first", () => {
5403
+ const plain = renderScreen([], [], [], { width: 72 }).map(stripAnsi).join("\n");
5404
+ assert.match(plain, /↑↓ agent/);
5405
+ });
5406
+
5407
+ test("fallback chains are saved only for profiles that exist on disk", () => {
5408
+ const home = mkdtempSync(join(tmpdir(), "fallbacks-saved-only-"));
5409
+ try {
5410
+ writeFileSync(join(home, "profiles.json"), JSON.stringify({ kind: "gentle-pi.agent_model_profiles", version: 1, active: "home", profiles: { home: {} } }));
5411
+ const fallbacks = __testing.fileRoutingFallbacks(home);
5412
+ assert.match(fallbacks.save("draft", "*", [{ model: "openai/gpt-5.5" }]) ?? "", /Save the profile first/);
5413
+ assert.equal(existsSync(join(home, "profile-fallbacks.json")), false, "nothing is written for an unsaved profile");
5414
+ assert.equal(fallbacks.save("home", "*", [{ model: "openai/gpt-5.5" }]), undefined);
5415
+ assert.deepEqual(fallbacks.chain("home", "*"), [{ model: "openai/gpt-5.5" }]);
5416
+ } finally {
5417
+ rmSync(home, { recursive: true, force: true });
5418
+ }
5419
+ });