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
@@ -0,0 +1,162 @@
1
+ import assert from 'node:assert/strict';
2
+ import { test } from 'node:test';
3
+ import * as fs from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { updateSelectedPi } from '../scripts/pi-update.mjs';
7
+
8
+ const PI = '@earendil-works/pi-coding-agent';
9
+ const CLI = 'dist/bundle/cli.js';
10
+
11
+ async function fixture(t: any, options: {manager?: string, locks?: string[], workspace?: boolean, range?: string, mismatch?: boolean, managerVersion?: string, fail?: boolean, unreadable?: boolean, unlink?: boolean, installedSource?: boolean, configOnly?: boolean, multipleProjects?: boolean} = {}) {
12
+ const temp = await fs.realpath(await fs.mkdtemp(join(tmpdir(), 'pi-source-')));
13
+ t.after(() => fs.rm(temp, {recursive: true, force: true}));
14
+ const root = join(temp, 'checkout');
15
+ const modules = join(temp, 'global', 'node_modules');
16
+ const link = join(modules, 'gentle-pi');
17
+ const peer = join(root, 'node_modules', PI);
18
+ const manager = options.manager ?? 'pnpm';
19
+ const lock = manager === 'npm' ? 'package-lock.json' : 'pnpm-lock.yaml';
20
+ const manifest = JSON.stringify({name: 'gentle-pi', version: '4.4.0', packageManager: `${manager}@11.1.1`, devDependencies: {[PI]: options.range ?? '^1.0.0'}});
21
+ await fs.mkdir(join(root, '.git'), {recursive: true});
22
+ await fs.mkdir(modules, {recursive: true});
23
+ await fs.mkdir(join(peer, 'dist', 'bundle'), {recursive: true});
24
+ await fs.writeFile(join(root, 'package.json'), manifest);
25
+ for (const name of options.locks ?? [lock]) await fs.writeFile(join(root, name), name === 'package-lock.json' ? '{"lockfileVersion":3}' : "lockfileVersion: '9.0'\nimporters:\n .: {}\n");
26
+ if (options.workspace || options.configOnly) await fs.writeFile(join(root, 'pnpm-workspace.yaml'), options.workspace ? 'packages: [packages/*]\n' : 'minimumReleaseAge: 4320\nblockExoticSubdeps: true\n');
27
+ await fs.writeFile(join(peer, 'package.json'), JSON.stringify({name: PI, version: '1.0.0', bin: {pi: CLI}}));
28
+ await fs.writeFile(join(peer, CLI), 'old Pi');
29
+ if (options.installedSource) {
30
+ const source = join(temp, 'Pi-source-checkout');
31
+ await fs.rename(peer, source);
32
+ await fs.mkdir(join(source, '.git'));
33
+ await fs.symlink(source, peer, 'junction');
34
+ }
35
+ await fs.writeFile(join(root, 'unrelated.txt'), 'preserve me');
36
+ await fs.symlink(root, link, 'junction');
37
+ const calls: {command: string, args: string[], cwd?: string, env?: Record<string,string>}[] = [];
38
+ const updates: typeof calls = [];
39
+ const output: string[] = [];
40
+ const snapshot = async () => ({pnpmConfig:options.workspace || options.configOnly ? await fs.readFile(join(root,'pnpm-workspace.yaml'),'utf8') : null, installedRoot:await fs.realpath(peer), installedLink:(await fs.lstat(peer)).isSymbolicLink() ? await fs.readlink(peer) : null, manifest: await fs.readFile(join(root, 'package.json'), 'utf8'), link: await fs.realpath(link), peer: await fs.readFile(join(peer, 'package.json'), 'utf8'), unrelated: await fs.readFile(join(root, 'unrelated.txt'), 'utf8'), locks: await Promise.all((options.locks ?? [lock]).map(name => fs.readFile(join(root, name), 'utf8')))});
41
+ const before = await snapshot();
42
+ const input = {runtime: {kind: 'bundled', command: process.execPath, args: [join(peer, CLI)]}, packageRoot: link, cwd: temp, home: temp, env: {}, currentVersion: '1.0.0', out: (s: string) => output.push(s), adapters: {
43
+ fs,
44
+ which: async (name: string) => `/fake/${name}`,
45
+ run: async (command: string, args: string[], {cwd,env}: {cwd?: string,env?: Record<string,string>} = {}) => {
46
+ calls.push({command, args, cwd, ...(env ? {env} : {})});
47
+ if (args.includes('list') && args.includes('--recursive')) return {code:0, stdout:JSON.stringify(options.multipleProjects ? [{path:root},{path:join(temp,'other-project')}] : [{path:root}])};
48
+ if (args.includes('list')) return {code: 0, stdout: JSON.stringify([{path: join(temp, 'pnpm'), dependencies: {}}])};
49
+ if (args.includes('ls')) return {code: 0, stdout: JSON.stringify({path: join(temp, 'global'), dependencies: {'gentle-pi': {path: link, resolved: 'file:../../checkout'}}})};
50
+ if (args.includes('--version')) return {code: 0, stdout: `${options.managerVersion ?? '11.1.1'}\n`};
51
+ if (args.includes('config')) return {code:0, stdout:options.workspace ? '["packages/*"]\n' : ''};
52
+ updates.push({command, args, cwd, ...(env ? {env} : {})});
53
+ if (options.fail) return {code: 1, stdout: '', stderrTail: 'npm error fixture install failed'};
54
+ if (options.unreadable) await fs.rm(join(peer, 'package.json'));
55
+ else await fs.writeFile(join(peer, 'package.json'), JSON.stringify({name: PI, version: '1.1.0', bin: {pi: CLI}}));
56
+ if (options.unlink) await fs.unlink(link);
57
+ return {code: 0, stdout: ''};
58
+ },
59
+ }};
60
+ if (options.mismatch) {
61
+ const other = join(temp, 'other', CLI);
62
+ await fs.mkdir(join(temp, 'other', 'dist', 'bundle'), {recursive: true});
63
+ await fs.writeFile(other, 'other Pi');
64
+ input.runtime.args = [other];
65
+ }
66
+ return {input, root, peer, link, manager, manifest, output, updates, calls, snapshot, before};
67
+ }
68
+
69
+ for (const manager of ['pnpm', 'npm']) test(`source-linked Shell updates only its local Pi using ${manager}, not the global link owner`, async t => {
70
+ const f = await fixture(t, {manager});
71
+ assert.equal(await updateSelectedPi(f.input), 0);
72
+ const flags = manager === 'pnpm' ? ['--dir', f.root, '--lockfile-dir', f.root, '--recursive=false', '--ignore-pnpmfile'] : ['--prefix', f.root, '--workspaces=false', '--no-audit', '--no-fund'];
73
+ assert.deepEqual(f.updates, [{command: `/fake/${manager}`, args: ['update', PI, '--no-save', '--ignore-scripts', '--global=false', ...flags, ...(manager === 'pnpm' ? ['--pm-on-fail=ignore'] : [])], cwd: f.root, ...(manager === 'pnpm' ? {env:{COREPACK_ENABLE_PROJECT_SPEC:'0',COREPACK_ENABLE_NETWORK:'0'}} : {})}]);
74
+ assert.deepEqual(f.output, [`${manager} updated ${PI} in ${f.root}; the selected Pi is now 1.1.0 (was 1.0.0).`]);
75
+ assert.equal(await fs.realpath(f.link), f.root);
76
+ assert.equal(await fs.readFile(join(f.root, 'package.json'), 'utf8'), f.manifest);
77
+ assert.equal(await fs.readFile(join(f.root, 'unrelated.txt'), 'utf8'), 'preserve me');
78
+ assert.ok(f.calls.filter(c => c.args.includes('list') || c.args.includes('ls') || c.args.includes('--version')).every(c => c.cwd === f.input.cwd));
79
+ });
80
+
81
+ test('newer pnpm uses its current version without downloading the older project pin', async t => {
82
+ const f = await fixture(t, {managerVersion:'11.5.0', configOnly:true});
83
+ assert.equal(await updateSelectedPi(f.input), 0);
84
+ assert.equal(f.updates.length, 1);
85
+ assert.deepEqual(f.output, [`pnpm updated ${PI} in ${f.root}; the selected Pi is now 1.1.0 (was 1.0.0).`]);
86
+ const projectCalls = f.calls.filter(call => call.args.includes('config') || call.args.includes('--recursive') || call.args[0] === 'update');
87
+ assert.equal(projectCalls.length, 3);
88
+ assert.ok(projectCalls.every(call => call.args.includes('--pm-on-fail=ignore')));
89
+ assert.ok(f.calls.filter(call => call.args.includes('--version') || projectCalls.includes(call)).every(call => call.env?.COREPACK_ENABLE_PROJECT_SPEC === '0' && call.env?.COREPACK_ENABLE_NETWORK === '0'));
90
+ const after = await f.snapshot();
91
+ assert.equal(after.manifest, f.before.manifest);
92
+ assert.equal(after.pnpmConfig, f.before.pnpmConfig);
93
+ assert.equal(after.unrelated, f.before.unrelated);
94
+ assert.equal(after.link, f.before.link);
95
+ });
96
+
97
+ test('older pnpm refuses before mutation or output', async t => {
98
+ const f = await fixture(t, {managerVersion:'11.1.0'});
99
+ await assert.rejects(updateSelectedPi(f.input), /requires pnpm@11\.1\.1 or newer/);
100
+ assert.deepEqual(f.updates, []);
101
+ assert.deepEqual(f.output, []);
102
+ assert.deepEqual(await f.snapshot(), f.before);
103
+ });
104
+
105
+ for (const [name, options] of Object.entries({
106
+ 'conflicting lockfiles': {locks: ['pnpm-lock.yaml', 'package-lock.json']},
107
+ 'missing lockfile': {locks: []},
108
+ 'workspace checkout': {workspace: true},
109
+ 'implicit workspace projects': {configOnly:true, multipleProjects:true},
110
+ 'unknown project manager': {manager: 'yarn', locks: ['yarn.lock']},
111
+ 'a linked Pi dependency': {range: 'file:../pi'},
112
+ 'a different selected Pi': {mismatch: true},
113
+ })) test(`source update refuses ${name} without changing files or counters`, async t => {
114
+ const f = await fixture(t, options);
115
+ await assert.rejects(updateSelectedPi(f.input), /ownership/);
116
+ assert.deepEqual(f.updates, []);
117
+ assert.deepEqual(f.output, []);
118
+ assert.deepEqual(await f.snapshot(), f.before);
119
+ });
120
+
121
+ test('source update preserves root-only pnpm security configuration instead of ignoring it', async t => {
122
+ const f = await fixture(t, {configOnly:true});
123
+ assert.equal(await updateSelectedPi(f.input), 0);
124
+ assert.equal(f.updates.length, 1);
125
+ assert.ok(f.calls.some(call => call.args.includes('config') && call.args.includes('packages')));
126
+ assert.ok(f.updates[0].args.includes('--workspace-root'));
127
+ assert.ok(f.updates[0].args.includes('--recursive=false'));
128
+ assert.ok(!f.updates[0].args.includes('--ignore-workspace'));
129
+ assert.equal((await f.snapshot()).pnpmConfig, f.before.pnpmConfig);
130
+ assert.equal(await fs.readFile(join(f.root,'package.json'),'utf8'), f.manifest);
131
+ assert.equal(await fs.realpath(f.link), f.root);
132
+ });
133
+
134
+ test('source update refuses an installed Pi source override despite a registry range', async t => {
135
+ const f = await fixture(t, {installedSource:true});
136
+ await assert.rejects(updateSelectedPi(f.input), /source Pi is a linked source checkout/);
137
+ assert.deepEqual(f.updates, []);
138
+ assert.deepEqual(f.output, []);
139
+ assert.deepEqual(await f.snapshot(), f.before);
140
+ });
141
+
142
+ test('source update failure reports the real manager error and never retries', async t => {
143
+ const f = await fixture(t, {manager: 'npm', fail: true});
144
+ await assert.rejects(updateSelectedPi(f.input), /npm error fixture install failed/);
145
+ assert.equal(f.updates.length, 1);
146
+ assert.deepEqual(f.output, []);
147
+ assert.deepEqual(await f.snapshot(), f.before);
148
+ });
149
+
150
+ test('source update reports unavailable readback instead of claiming a version', async t => {
151
+ const f = await fixture(t, {unreadable: true});
152
+ assert.equal(await updateSelectedPi(f.input), 0);
153
+ assert.match(f.output.join('\n'), /version.*could not be read back/);
154
+ assert.doesNotMatch(f.output.join('\n'), /is now/);
155
+ });
156
+
157
+ test('source update cannot claim success when its global Shell link disappeared', async t => {
158
+ const f = await fixture(t, {unlink: true});
159
+ await assert.rejects(updateSelectedPi(f.input), /Shell link.*changed/);
160
+ assert.equal(f.updates.length, 1);
161
+ assert.deepEqual(f.output, []);
162
+ });
@@ -0,0 +1,311 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { SessionManager } from "@earendil-works/pi-coding-agent";
4
+ import { createSessionProfileIntegration } from "../lib/session-profile-integration.ts";
5
+ import { normalizeProfilesFile, PROFILES_KIND, PROFILES_VERSION, createProfile, duplicateProfile, emptyProfilesFile, parseProfileExportText, parseProfilesFileText, serializeProfileExport, serializeProfilesFile } from "../lib/agent-profiles.ts";
6
+ import { createSessionProfileBind, readSessionProfileEntry, replaySessionProfileBranch, SESSION_PROFILE_CUSTOM_TYPE } from "../lib/session-profile-persistence.ts";
7
+ import { normalizeRoutingEntry } from "../lib/model-routing-authority.ts";
8
+ import { parseAgentsConfig, resolveAgentProfile, withPinnedModelProfiles } from "../lib/agents-config.ts";
9
+ import { __testing } from "../extensions/gentle-ai.ts";
10
+ import fast from "../extensions/gentle-fast.ts";
11
+ import { CHILD_TIER_ENV, PROFILE_TIER_EVENT } from "../lib/openai-fast-tier.ts";
12
+ import { runInProcessReviewer } from "../lib/inprocess-reviewer.ts";
13
+ import { bindSessionProfile, clearSessionProfileBinding } from "../lib/session-profile-binding.ts";
14
+ import { freezeSessionProfileAtStartup, readFrozenDefaultOrchestrator, readFrozenInheritedProfile, setFrozenDefaultOrchestrator } from "../lib/session-profile-freeze.ts";
15
+
16
+ test("All Fast sets compatible routes without toggling existing Fast or changing other fields", () => {
17
+ const model = "openai/gpt-6.1-sol";
18
+ const codex = "openai-codex/gpt-6.1-terra";
19
+ const draft = { orchestrator: { model, thinking: "high" as const, tier: "standard" as const }, worker: { model: codex, thinking: "medium" as const }, verify: { model, tier: "fast" as const }, other: { model: "other/model", tier: "standard" as const }, inherited: { thinking: "high" as const } };
20
+ const original = structuredClone(draft);
21
+ for (const width of [72, 120]) {
22
+ const results: any[] = [];
23
+ __testing.routingTablePanel(draft, [model, codex], ["worker", "verify", "other", "inherited"], width, undefined, undefined, ["a", "a", "s"], [], results, { fastModels: [model, codex] });
24
+ assert.equal(results.length, 1);
25
+ assert.equal(results[0].type, "save");
26
+ assert.equal(results[0].name, "current");
27
+ assert.deepEqual(results[0].config, { ...original, orchestrator: { ...original.orchestrator, tier: "fast" }, worker: { ...original.worker, tier: "fast" } });
28
+ assert.deepEqual(draft, original, "editing does not mutate the original profile");
29
+ }
30
+ });
31
+
32
+ test("All Fast is clickable at narrow and wide widths and does not save or apply by itself", () => {
33
+ const model = "openai/gpt-6.1-sol";
34
+ const draft = { orchestrator: { model }, worker: { model } };
35
+ for (const width of [72, 120]) {
36
+ const args: [typeof draft, string[], string[], number, undefined, undefined] = [draft, [model], ["worker"], width, undefined, undefined];
37
+ const options = { fastModels: [model] };
38
+ const before = __testing.routingTablePanel(...args, [], [], [], options);
39
+ const y = before.findIndex(line => line.includes("All Fast"));
40
+ assert.notEqual(y, -1, `All Fast is visible at ${width} columns`);
41
+ const results: any[] = [];
42
+ const after = __testing.routingTablePanel(...args, [], [{ type: "click", x: before[y].indexOf("All Fast") + 2, y }], results, options);
43
+ assert.equal(after.filter(line => line.includes("Fast ▾")).length, 2);
44
+ assert.match(after.join("\n"), /2 unsaved/);
45
+ assert.deepEqual(results, [], "bulk edit does not silently save or change session/defaults");
46
+ }
47
+ });
48
+
49
+ test("individual tier selection still overrides All Fast", () => {
50
+ const model = "openai/gpt-6.1-sol";
51
+ const results: any[] = [];
52
+ __testing.routingTablePanel({ orchestrator: { model }, worker: { model } }, [model], ["worker"], 120, undefined, undefined, ["a", "t", "s"], [], results, { fastModels: [model] });
53
+ assert.equal(results[0].config.orchestrator.tier, "standard");
54
+ assert.equal(results[0].config.worker.tier, "fast");
55
+ });
56
+
57
+ test("profile UI saves Fast for both providers and independent roles", () => {
58
+ for (const provider of ["openai", "openai-codex"]) {
59
+ const model = `${provider}/gpt-5.6-luna`;
60
+ const results: any[] = [];
61
+ const lines = __testing.routingTablePanel({ orchestrator: { model }, worker: { model } }, [model], ["worker"], 120, undefined, undefined, ["t", "j", "j", "t", "s"], [], results, { fastModels: [model] });
62
+ assert.match(lines.join("\n"), /Fast/);
63
+ assert.equal(results[0].type, "save");
64
+ assert.equal(results[0].config.orchestrator.tier, "fast");
65
+ assert.equal(results[0].config.worker.tier, "fast");
66
+ }
67
+ });
68
+
69
+ test("tier and fallback controls coexist at narrow and wide widths", () => {
70
+ const model = "openai/gpt-5.6-luna";
71
+ const draft = { orchestrator: { model } };
72
+ const fallbacks = { chain: () => [{ model: "fallback/model" }], save: () => undefined };
73
+ for (const width of [72, 120]) {
74
+ const options = { fastModels: [model], fallbacks };
75
+ const screen = __testing.routingTablePanel(draft, [model], [], width, undefined, undefined, [], [], [], options);
76
+ const row = screen.findIndex((line) => line.includes("Standard ▾"));
77
+ assert.notEqual(row, -1, `tier is fully visible at ${width} columns`);
78
+ const tierX = screen[row].indexOf("Standard") + 1;
79
+ const clicked = __testing.routingTablePanel(draft, [model], [], width, undefined, undefined, [], [{ type: "click", x: tierX, y: row }], [], options);
80
+ assert.match(clicked.join("\n"), /Fast ▾/);
81
+ assert.match(clicked.join("\n"), /↑↓ agent/);
82
+ if (width === 72) assert.doesNotMatch(clicked.join("\n"), /t tier/);
83
+ else assert.match(clicked.join("\n"), /t tier/);
84
+ }
85
+ const wide = __testing.routingTablePanel(draft, [model], [], 120, undefined, undefined, ["t"], [], [], { fastModels: [model], fallbacks });
86
+ assert.match(wide.join("\n"), /Fast ▾\s+↪ fallback\/model/);
87
+ const fallbackCard = __testing.routingTablePanel(draft, [model], [], 120, undefined, undefined, ["f"], [], [], { fastModels: [model], fallbacks });
88
+ assert.match(fallbackCard.join("\n"), /Fallbacks for the orchestrator/);
89
+ });
90
+
91
+ test("profile UI does not offer tier for an unsupported route", () => {
92
+ const results: any[] = [];
93
+ __testing.routingTablePanel({ orchestrator: { model: "openai/other" } }, [], [], 100, undefined, undefined, ["t", "s"], [], results, { fastModels: [] });
94
+ assert.deepEqual(results, []);
95
+ });
96
+
97
+ for (const provider of ["openai", "openai-codex"]) {
98
+ test(`${provider} profile retains Fast through normalization and session replay`, () => {
99
+ const model = `${provider}/gpt-5.6-luna`;
100
+ const result = normalizeProfilesFile({ kind: PROFILES_KIND, version: PROFILES_VERSION, profiles: { work: { orchestrator: { model, thinking: "high", tier: "fast" } } } });
101
+ assert.ok(result);
102
+ assert.deepEqual(result.file.profiles.work.orchestrator, { model, thinking: "high", tier: "fast" });
103
+ const binding = createSessionProfileBind("work", result.file.profiles.work);
104
+ assert.deepEqual(replaySessionProfileBranch([{ type: "custom", customType: SESSION_PROFILE_CUSTOM_TYPE, data: binding }]), { status: "bound", binding, entryIndex: 0 });
105
+ });
106
+ }
107
+
108
+ test("profile clone, file and export roundtrips preserve independent tier routes", () => {
109
+ const route = { orchestrator: { model: "openai/gpt-5.6-luna", thinking: "high" as const, tier: "fast" as const }, worker: { model: "openai-codex/gpt-5.6-sol", tier: "standard" as const } };
110
+ const file = duplicateProfile(createProfile(emptyProfilesFile(), "work", route), "work", "copy");
111
+ route.orchestrator.tier = "standard" as any;
112
+ assert.equal(file.profiles.copy.orchestrator.tier, "fast");
113
+ const parsed = parseProfilesFileText(serializeProfilesFile(file));
114
+ assert.equal(parsed.status, "valid");
115
+ if (parsed.status === "valid") assert.equal(parsed.file.profiles.copy.worker.tier, "standard");
116
+ assert.deepEqual(JSON.parse(JSON.stringify(parseProfileExportText(serializeProfileExport("work", file.profiles.work))?.config)), file.profiles.work);
117
+ });
118
+
119
+ test("child profile resolver carries the tier from the selected route", () => {
120
+ const config = withPinnedModelProfiles(parseAgentsConfig(undefined, undefined), { worker: { model: "openai/gpt-5.6-luna", thinking: "high", tier: "fast" } });
121
+ const agent = { name: "worker", description: "", filePath: "", scope: "global" as const, instructions: "", model: undefined, thinking: undefined, mode: undefined, tools: [] };
122
+ assert.equal(resolveAgentProfile(agent, config).tier, "fast");
123
+ });
124
+
125
+ test("old and invalid-tier routes preserve model and effort normalization", () => {
126
+ assert.deepEqual(normalizeRoutingEntry({ model: "openai/gpt-5.6-luna", effort: "high" }), { model: "openai/gpt-5.6-luna", thinking: "high" });
127
+ assert.deepEqual(normalizeRoutingEntry({ model: "openai/gpt-5.6-luna", thinking: "low", tier: "invalid" }), { model: "openai/gpt-5.6-luna", thinking: "low" });
128
+ });
129
+
130
+ test("profile application switches tiers without affecting unsupported models", async () => {
131
+ const handlers = new Map<string, Function>();
132
+ const bus = new Map<string, Function>();
133
+ const model = { provider: "openai-codex", api: "openai-codex-responses", id: "gpt-5.6-luna" };
134
+ const ctx: any = { model, hasUI: false, sessionManager: { getSessionId: () => "profile-test" }, ui: { notify() {} } };
135
+ fast({ on: (name: string, fn: Function) => handlers.set(name, fn), events: { on: (name: string, fn: Function) => bus.set(name, fn) } } as any);
136
+ handlers.get("session_start")!({}, ctx);
137
+ const request = () => handlers.get("before_provider_request")!({ payload: {} }, ctx);
138
+ bus.get(PROFILE_TIER_EVENT)!({ sessionId: "profile-test", tier: "fast", model: "openai-codex/gpt-5.6-luna" });
139
+ assert.equal(request().service_tier, "priority");
140
+ bus.get(PROFILE_TIER_EVENT)!({ sessionId: "profile-test", tier: "standard", model: "openai-codex/gpt-5.6-luna" });
141
+ assert.equal(request().service_tier, "default");
142
+ bus.get(PROFILE_TIER_EVENT)!({ sessionId: "profile-test", tier: undefined });
143
+ assert.equal(request(), undefined);
144
+ bus.get(PROFILE_TIER_EVENT)!({ sessionId: "other", tier: "fast" });
145
+ assert.equal(request(), undefined);
146
+ bus.get(PROFILE_TIER_EVENT)!({ sessionId: "profile-test", tier: "fast", model: "openai-codex/gpt-5.6-luna" });
147
+ ctx.model = { ...model, id: "gpt-5.6-sol" };
148
+ handlers.get("model_select")!({ model: ctx.model }, ctx);
149
+ assert.equal(request(), undefined);
150
+ ctx.model = { ...model, api: "openai-completions" };
151
+ assert.equal(request(), undefined);
152
+ });
153
+
154
+ test("session tree restores its frozen profile binding", async () => {
155
+ const handlers = new Map<string, Function>();
156
+ const bus = new Map<string, Function>();
157
+ const model = { provider: "openai", api: "openai-responses", id: "gpt-5.6-luna" };
158
+ const ctx: any = { model, hasUI: false, sessionManager: { getSessionId: () => "tier-restore-test" }, ui: { notify() {} } };
159
+ fast({ on: (name: string, fn: Function) => handlers.set(name, fn), events: { on: (name: string, fn: Function) => bus.set(name, fn) } } as any);
160
+ const previousChild = process.env.GENTLE_PI_AGENTS_CHILD;
161
+ process.env.GENTLE_PI_AGENTS_CHILD = "0";
162
+ bindSessionProfile("tier-restore-test", "work", { orchestrator: { model: "openai/gpt-5.6-luna", tier: "fast" } });
163
+ try {
164
+ handlers.get("session_start")!({}, ctx);
165
+ const request = () => handlers.get("before_provider_request")!({ payload: {} }, ctx);
166
+ assert.equal(request().service_tier, "priority");
167
+ bus.get(PROFILE_TIER_EVENT)!({ sessionId: "tier-restore-test", tier: "standard", model: "openai/gpt-5.6-luna" });
168
+ assert.equal(request().service_tier, "default");
169
+ handlers.get("session_tree")!({}, ctx);
170
+ assert.equal(request().service_tier, "priority");
171
+ } finally {
172
+ clearSessionProfileBinding("tier-restore-test");
173
+ if (previousChild === undefined) delete process.env.GENTLE_PI_AGENTS_CHILD;
174
+ else process.env.GENTLE_PI_AGENTS_CHILD = previousChild;
175
+ }
176
+ });
177
+
178
+ test("child runtime uses only its launch route and rejects model mismatches", () => {
179
+ const oldChild = process.env.GENTLE_PI_AGENTS_CHILD;
180
+ const oldTier = process.env[CHILD_TIER_ENV];
181
+ const handlers = new Map<string, Function>();
182
+ const ctx: any = { model: { provider: "openai-codex", api: "openai-codex-responses", id: "gpt-5.6-luna" }, hasUI: false, sessionManager: { getSessionId: () => "child" }, ui: { notify() {} } };
183
+ fast({ on: (name: string, fn: Function) => handlers.set(name, fn) } as any);
184
+ try {
185
+ process.env.GENTLE_PI_AGENTS_CHILD = "1";
186
+ process.env[CHILD_TIER_ENV] = JSON.stringify({ model: "openai-codex/gpt-5.6-luna", tier: "fast" });
187
+ handlers.get("session_start")!({}, ctx);
188
+ assert.equal(handlers.get("before_provider_request")!({ payload: {} }, ctx).service_tier, "priority");
189
+ process.env[CHILD_TIER_ENV] = JSON.stringify({ model: "openai/gpt-5.6-luna", tier: "fast" });
190
+ handlers.get("session_start")!({}, ctx);
191
+ assert.equal(handlers.get("before_provider_request")!({ payload: {} }, ctx), undefined);
192
+ } finally {
193
+ if (oldChild === undefined) delete process.env.GENTLE_PI_AGENTS_CHILD; else process.env.GENTLE_PI_AGENTS_CHILD = oldChild;
194
+ if (oldTier === undefined) delete process.env[CHILD_TIER_ENV]; else process.env[CHILD_TIER_ENV] = oldTier;
195
+ }
196
+ });
197
+
198
+ test("fresh default tier is frozen per session and used only for its model", () => {
199
+ let current: any = { model: "openai/gpt-5.6-luna", tier: "fast" };
200
+ const options: any = { sessionId: "tier-default-test", cwd: "/nonexistent", configHome: "/nonexistent", env: {}, resolveWorktree: () => undefined, readDefaultOrchestrator: () => current };
201
+ freezeSessionProfileAtStartup(options);
202
+ current = { model: "openai/gpt-5.6-luna", tier: "standard" };
203
+ freezeSessionProfileAtStartup(options);
204
+ assert.equal(readFrozenInheritedProfile("tier-default-test")?.defaultOrchestrator?.tier, "fast");
205
+ freezeSessionProfileAtStartup({ ...options, sessionId: "tier-default-new" });
206
+ assert.equal(readFrozenInheritedProfile("tier-default-new")?.defaultOrchestrator?.tier, "standard");
207
+ freezeSessionProfileAtStartup({ ...options, sessionId: "tier-default-follow", env: { GENTLE_PI_PROFILE_FOLLOW: "1" } });
208
+ current = { model: "openai/gpt-5.6-luna", tier: "fast" };
209
+ freezeSessionProfileAtStartup({ ...options, sessionId: "tier-default-follow", env: { GENTLE_PI_PROFILE_FOLLOW: "1" } });
210
+ assert.equal(readFrozenDefaultOrchestrator("tier-default-follow")?.tier, "standard");
211
+ current = { model: "openai/gpt-5.6-luna", tier: "standard" };
212
+ const handlers = new Map<string, Function>();
213
+ const ctx: any = { model: { provider: "openai", api: "openai-responses", id: "gpt-5.6-luna" }, cwd: "/nonexistent", hasUI: false, sessionManager: { getSessionId: () => "tier-default-test" }, ui: { notify() {} } };
214
+ fast({ on: (name: string, fn: Function) => handlers.set(name, fn) } as any);
215
+ const old = process.env.GENTLE_PI_AGENTS_CHILD;
216
+ try {
217
+ process.env.GENTLE_PI_AGENTS_CHILD = "0";
218
+ handlers.get("session_start")!({}, ctx);
219
+ assert.equal(handlers.get("before_provider_request")!({ payload: {} }, ctx)?.service_tier, "priority");
220
+ bindSessionProfile("tier-default-test", "explicit", { orchestrator: { model: "openai/gpt-5.6-luna", tier: "standard" } });
221
+ handlers.get("session_start")!({}, ctx);
222
+ assert.equal(handlers.get("before_provider_request")!({ payload: {} }, ctx)?.service_tier, "default");
223
+ bindSessionProfile("tier-default-test", "old", { worker: { model: "openai/gpt-5.6-luna" } });
224
+ handlers.get("session_start")!({}, ctx);
225
+ assert.equal(handlers.get("before_provider_request")!({ payload: {} }, ctx), undefined);
226
+ clearSessionProfileBinding("tier-default-test");
227
+ setFrozenDefaultOrchestrator("tier-default-test", current);
228
+ handlers.get("session_start")!({}, ctx);
229
+ assert.equal(handlers.get("before_provider_request")!({ payload: {} }, ctx)?.service_tier, "default");
230
+ ctx.model = { ...ctx.model, id: "gpt-5.6-sol" };
231
+ handlers.get("session_start")!({}, ctx);
232
+ assert.equal(handlers.get("before_provider_request")!({ payload: {} }, ctx), undefined);
233
+ } finally { if (old === undefined) delete process.env.GENTLE_PI_AGENTS_CHILD; else process.env.GENTLE_PI_AGENTS_CHILD = old; }
234
+ });
235
+
236
+ for (const provider of ["openai", "openai-codex"]) for (const order of ["fast-first", "profiles-first"]) {
237
+ test(`${provider}/${order} selecting a thinking-only profile clears Fast without switching models`, async () => {
238
+ const model = { provider, api: provider === "openai" ? "openai-responses" : "openai-codex-responses", id: "gpt-5.6-luna" };
239
+ const ref = `${provider}/${model.id}`;
240
+ const manager = SessionManager.inMemory("/nonexistent");
241
+ const integration = createSessionProfileIntegration();
242
+ integration.start(manager, (type, data) => { manager.appendCustomEntry(type, data); }, { reason: "startup" });
243
+ const handlers = new Map<string, Function>();
244
+ const listeners = new Map<string, Function[]>();
245
+ const bus: any = { on: (name: string, fn: Function) => listeners.set(name, [...(listeners.get(name) ?? []), fn]), emit: (name: string, data: unknown) => { for (const fn of listeners.get(name) ?? []) fn(data); } };
246
+ const fastCtx: any = { model, hasUI: false, sessionManager: { getSessionId: () => manager.getSessionId() }, ui: { notify() {} } };
247
+ const ctx: any = { model, sessionManager: manager, modelRegistry: { find: () => model }, hasUI: false, ui: { notify() {} } };
248
+ let switched = 0;
249
+ let succeeds = true;
250
+ const live: any = { events: bus, setModel: async () => { switched++; return succeeds; }, setThinkingLevel() { throw new Error("thinking-only must not change thinking"); }, getThinkingLevel: () => "high" };
251
+ const file = createProfile(createProfile(createProfile(emptyProfilesFile(), "fast", { orchestrator: { model: ref, tier: "fast" } }), "old", { orchestrator: { thinking: "high" } }), "standard", { orchestrator: { model: ref, tier: "standard" } });
252
+ const installFast = () => fast({ on: (name: string, fn: Function) => handlers.set(name, fn), events: bus } as any);
253
+ let select!: (name: string) => Promise<void>;
254
+ const installProfiles = () => { select = async (name) => {
255
+ const result: any[] = [];
256
+ __testing.routingTablePanel(file.profiles[name], [ref], [], 100, undefined, undefined, ["u"], [], result, { file, profileName: name, fastModels: [ref] });
257
+ assert.equal(result[0]?.type, "use-session");
258
+ await __testing.runProfilesPanelAction(ctx, live, "/nonexistent/profiles.json", file, result[0]);
259
+ }; };
260
+ if (order === "fast-first") { installFast(); installProfiles(); } else { installProfiles(); installFast(); }
261
+ handlers.get("session_start")!({}, fastCtx);
262
+ const request = () => handlers.get("before_provider_request")!({ payload: {} }, fastCtx);
263
+ await select("fast");
264
+ assert.equal(request()?.service_tier, "priority", `${provider}/${order}: fast selection`);
265
+ const previousSwitches = switched;
266
+ await select("old");
267
+ assert.equal(request(), undefined, `${provider}/${order}: thinking-only must clear Fast`);
268
+ assert.equal(switched, previousSwitches, `${provider}/${order}: no model switch`);
269
+ await select("fast");
270
+ assert.equal(request()?.service_tier, "priority");
271
+ succeeds = false;
272
+ await select("standard");
273
+ assert.equal(request()?.service_tier, "priority", `${provider}/${order}: failed Standard switch preserves profile Fast`);
274
+ });
275
+ }
276
+
277
+ test("live switching emits tier only for successful and current model switches", async () => {
278
+ const model: any = { provider: "openai", api: "openai-responses", id: "gpt-5.6-luna" };
279
+ const ctx: any = { sessionManager: { getSessionId: () => "test" }, modelRegistry: { find: () => model }, hasUI: false };
280
+ const emitted: any[] = [];
281
+ let success = false;
282
+ let current = true;
283
+ const live: any = { setModel: async () => success, getThinkingLevel: () => "high", setThinkingLevel() {}, events: { emit: (...args: any[]) => emitted.push(args) } };
284
+ const route: any = { model: "openai/gpt-5.6-luna", tier: "fast" };
285
+ await __testing.switchLiveOrchestrator(ctx, live, route, () => current);
286
+ assert.equal(emitted.length, 0);
287
+ success = true;
288
+ current = false;
289
+ await __testing.switchLiveOrchestrator(ctx, live, route, () => current);
290
+ assert.equal(emitted.length, 0);
291
+ current = true;
292
+ await __testing.switchLiveOrchestrator(ctx, live, route, () => current);
293
+ assert.deepEqual(emitted, [[PROFILE_TIER_EVENT, { sessionId: "test", tier: "fast", model: "openai/gpt-5.6-luna" }]]);
294
+ });
295
+
296
+ test("direct provider route applies tier through the provider payload hook", async () => {
297
+ for (const [provider, api] of [["openai", "openai-responses"], ["openai-codex", "openai-codex-responses"]]) {
298
+ const model: any = { provider, api, id: "gpt-5.6-luna", reasoning: false };
299
+ let options: any;
300
+ const registry: any = { find: () => model, getApiKeyAndHeaders: async () => ({ ok: true }) };
301
+ const complete: any = async (_model: any, _context: any, value: any) => { options = value; return { content: [{ type: "text", text: "ok" }], stopReason: "stop" }; };
302
+ const result = await runInProcessReviewer({ selection: `${provider}/${model.id}`, tier: "fast", prompt: Buffer.from("test"), timeoutMs: 1000, routingKey: "review-risk" }, { registry, complete });
303
+ assert.equal(result.kind, "text");
304
+ assert.deepEqual(await options.onPayload({ input: "x" }, model), { input: "x", service_tier: "priority" });
305
+ }
306
+ });
307
+
308
+ test("session snapshots reject invalid tier instead of silently changing binding", () => {
309
+ const entry = { type: "custom", customType: SESSION_PROFILE_CUSTOM_TYPE, data: { kind: "bind", origin: "user", name: "work", modelProfiles: { worker: { model: "openai/gpt-5.6-luna", tier: "invalid" } } } };
310
+ assert.deepEqual(readSessionProfileEntry(entry), { status: "invalid" });
311
+ });
@@ -0,0 +1,79 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { visibleWidth } from "@earendil-works/pi-tui";
7
+ import { buildShellBarModel, createActiveProfileReader } from "../extensions/gentle-shell.ts";
8
+ import { bindSessionProfile, resetSessionProfileBindingsForTesting } from "../lib/session-profile-binding.ts";
9
+ import { renderShellStatusBar, renderShellTitleRow, renderShellBar, type ShellBarModel } from "../lib/shell-bar.ts";
10
+
11
+ const theme = { fg: (_role: string, text: string) => text, bold: (text: string) => text };
12
+ const base: ShellBarModel = {
13
+ cwd: "/fixture", branch: "main", dirty: 0, sessionName: "fixture",
14
+ modelId: "gpt-6.1-sol", effort: "xhigh", contextPercent: 95, contextWindow: 200000,
15
+ costTotal: 13.21, subscription: false, usage: undefined, statuses: [],
16
+ };
17
+
18
+ test("bottom tier reads the named profile configuration, not its older session snapshot", (t) => {
19
+ const home = mkdtempSync(join(tmpdir(), "profile-tier-footer-"));
20
+ t.after(() => { resetSessionProfileBindingsForTesting(); rmSync(home, { recursive: true, force: true }); });
21
+ const profiles = { team: { orchestrator: { model: "openai/gpt-6.1-sol", tier: "fast" } }, other: { orchestrator: { model: "openai/gpt-6.1-sol", tier: "standard" } } };
22
+ const save = (active: string) => writeFileSync(join(home, "profiles.json"), JSON.stringify({ kind: "gentle-pi.agent_model_profiles", version: 1, active, profiles }));
23
+ save("team");
24
+ bindSessionProfile("footer-tier", "team", { orchestrator: { model: "openai/gpt-6.1-sol" } });
25
+ const reader = createActiveProfileReader({ GENTLE_PI_CONFIG_HOME: home });
26
+ reader.bind(home, () => undefined, "footer-tier");
27
+ assert.equal(reader(), "team (session)");
28
+ assert.equal(reader.tier(), "fast", "the configured tier shows even when the binding has no tier");
29
+ save("other"); reader.refresh();
30
+ assert.equal(reader.tier(), "fast", "a different global default does not replace the session's named profile");
31
+ profiles.team.orchestrator.tier = "standard"; save("other");
32
+ assert.equal(reader.refresh(), true, "tier changes invalidate footer presentation");
33
+ assert.equal(reader.tier(), "standard");
34
+ assert.equal(reader(), "team (session)", "existing profile labeling is unchanged");
35
+ });
36
+
37
+ test("bottom bar places configured Fast or Standard beside effort without changing other bars", () => {
38
+ for (const profileTier of ["fast", "standard"] as const) {
39
+ const configured = { ...base, profileTier };
40
+ for (const width of [40, 60, 72, 80, 120, 140, 180]) {
41
+ const row = renderShellStatusBar(configured, theme, width).rows[0]!;
42
+ assert.equal(visibleWidth(row), width);
43
+ if (width >= 72) assert.match(row, new RegExp("gpt-6.1-sol · xhigh · " + (profileTier === "fast" ? "Fast" : "Standard")));
44
+ assert.match(row, /ctx.*95%/);
45
+ assert.match(row, /\$13\.21/);
46
+ }
47
+ const narrow = renderShellStatusBar({ ...configured, permission: { mode: "SUPER YOLO" } }, theme, 72).rows[0]!;
48
+ assert.ok(narrow.includes("gpt-6.1-sol · xhigh"), "the new tier yields before displacing the existing model and effort");
49
+ assert.equal(renderShellTitleRow(configured, theme, 120), renderShellTitleRow(base, theme, 120));
50
+ assert.deepEqual(renderShellBar(configured, theme, 120), renderShellBar(base, theme, 120));
51
+ }
52
+ assert.doesNotMatch(renderShellStatusBar(base, theme, 120).rows[0]!, /No tier|Fast|Standard|server/);
53
+ });
54
+
55
+ test("legacy tier integration is excluded while permission warnings and other statuses survive", () => {
56
+ const pi = { getThinkingLevel: () => "xhigh" } as any;
57
+ const ctx = {
58
+ model: { provider: "openai", api: "openai-responses", id: "gpt-6.1-sol", reasoning: true },
59
+ getContextUsage: () => ({ percent: 95, contextWindow: 200000 }),
60
+ modelRegistry: { isUsingOAuth: () => false },
61
+ sessionManager: { getCwd: () => "/fixture", getSessionName: () => "fixture", getEntries: () => [] },
62
+ } as any;
63
+ const footer = {
64
+ getGitBranch: () => "main",
65
+ getExtensionStatuses: () => new Map([
66
+ ["gentle-fast", "No tier selected; last response from server: Standard (default)"],
67
+ ["gentle:mode", "Permissions: SUPER YOLO"],
68
+ ["gentle:yolo", "SUPER YOLO — no permission prompts; private paths stay blocked"],
69
+ ["other", "ready"],
70
+ ]),
71
+ } as any;
72
+ const model = buildShellBarModel(pi, ctx, footer, { profileTier: "fast" });
73
+ assert.equal(model.profileTier, "fast");
74
+ assert.deepEqual(model.integrations, ["ready"]);
75
+ assert.equal(model.permission?.detail, "no permission prompts; private paths stay blocked");
76
+ assert.ok(model.statuses.includes("ready"));
77
+ assert.ok(model.statuses.some(text => text.includes("private paths stay blocked")));
78
+ assert.ok(!model.statuses.some(text => /No tier|last response/.test(text)));
79
+ });