gentle-pi 4.5.1 → 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 (239) 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-shell.md +69 -19
  15. package/docs/install-wizard.md +1 -1
  16. package/docs/mcp-status.md +52 -0
  17. package/docs/prompt-budget.md +28 -0
  18. package/docs/readme-reference.md +79 -20
  19. package/docs/session-profile-format.md +20 -5
  20. package/docs/sound-notifications.md +1 -1
  21. package/docs/star-prompt.md +32 -0
  22. package/docs/work-continuity.md +46 -0
  23. package/extensions/ask-user-question.ts +1 -0
  24. package/extensions/codegraph-tools.ts +38 -4
  25. package/extensions/gentle-agents.ts +477 -50
  26. package/extensions/gentle-ai.ts +1041 -188
  27. package/extensions/gentle-fast.ts +61 -0
  28. package/extensions/gentle-guide.ts +174 -0
  29. package/extensions/gentle-herdr-activity.ts +21 -1
  30. package/extensions/gentle-herdr-agent.ts +144 -0
  31. package/extensions/gentle-program-identity.ts +61 -0
  32. package/extensions/gentle-shell.ts +642 -97
  33. package/extensions/gentle-star-prompt.ts +334 -0
  34. package/extensions/gentle-stats.ts +5 -5
  35. package/extensions/gentle-todo.ts +42 -22
  36. package/extensions/history/store.ts +18 -12
  37. package/extensions/skill-registry.ts +35 -3
  38. package/extensions/startup-banner.ts +39 -7
  39. package/lib/agent-assets.ts +74 -17
  40. package/lib/agent-profiles.ts +1 -1
  41. package/lib/agents-config.ts +12 -3
  42. package/lib/agents-keys.ts +8 -16
  43. package/lib/agents-protocol.ts +80 -4
  44. package/lib/agents-runner.ts +105 -4
  45. package/lib/agents-view.ts +6 -1
  46. package/lib/agents-widget.ts +132 -9
  47. package/lib/bridge-cost.ts +28 -0
  48. package/lib/codemode-renderer.ts +16 -0
  49. package/lib/command-palette-catalog.ts +1 -0
  50. package/lib/command-palette.ts +21 -8
  51. package/lib/exploration-budget.ts +62 -0
  52. package/lib/gentle-guide.ts +201 -0
  53. package/lib/gentle-shell-launcher.ts +4 -0
  54. package/lib/herdr-activity.ts +9 -3
  55. package/lib/herdr-task-summary-policy.ts +85 -0
  56. package/lib/inprocess-reviewer.ts +33 -13
  57. package/lib/jobs-sidebar-state.ts +5 -6
  58. package/lib/jobs-widget.ts +16 -52
  59. package/lib/keymaps-customize.ts +81 -0
  60. package/lib/keymaps.ts +291 -0
  61. package/lib/model-fallback-notice.ts +61 -0
  62. package/lib/model-fallback-policy.ts +141 -0
  63. package/lib/model-fallback-store.ts +143 -0
  64. package/lib/model-routing-authority.ts +10 -2
  65. package/lib/nan-provider.ts +3 -2
  66. package/lib/native-review-cli.ts +7 -2
  67. package/lib/notification-customize.ts +48 -51
  68. package/lib/openai-fast-tier.ts +22 -0
  69. package/lib/orchestrator-discovery.ts +5 -1
  70. package/lib/orchestrator-fallback.ts +75 -0
  71. package/lib/pasted-image-paths.ts +113 -0
  72. package/lib/questionnaire/questionnaire-view.ts +121 -7
  73. package/lib/review-candidate-view-owner.ts +4 -0
  74. package/lib/review-candidate-view.ts +10 -7
  75. package/lib/review-host-relay.ts +5 -1
  76. package/lib/review-integration-v2.ts +22 -7
  77. package/lib/review-repository.ts +5 -0
  78. package/lib/session-profile-append-controller.ts +21 -6
  79. package/lib/session-profile-authority.ts +119 -0
  80. package/lib/session-profile-binding.ts +54 -5
  81. package/lib/session-profile-freeze.ts +105 -9
  82. package/lib/session-profile-integration.ts +313 -0
  83. package/lib/session-profile-persistence.ts +63 -9
  84. package/lib/shell-bar.ts +171 -56
  85. package/lib/shell-card.ts +26 -6
  86. package/lib/shell-page.ts +120 -0
  87. package/lib/shell-panel.ts +149 -0
  88. package/lib/shell-prompt.ts +53 -1
  89. package/lib/shell-sidebar-layout.ts +98 -25
  90. package/lib/shell-sidebar.ts +54 -1
  91. package/lib/shell-stats.ts +123 -0
  92. package/lib/shell-todo.ts +71 -0
  93. package/lib/shell-usage.ts +12 -2
  94. package/lib/star-prompt.ts +197 -0
  95. package/lib/verifier-admission.ts +18 -8
  96. package/lib/verifier-settle-reminder.ts +64 -0
  97. package/lib/vim-editor-adapter.ts +6 -1
  98. package/lib/visual-customization-policy.ts +41 -6
  99. package/lib/visual-customize-view.ts +164 -26
  100. package/lib/visual-layout-preview.ts +43 -0
  101. package/lib/yolo-session-policy.ts +28 -1
  102. package/package.json +1 -1
  103. package/runtime/gentle-shell-launcher.mjs +4 -0
  104. package/runtime/native-review-cli.mjs +7 -2
  105. package/runtime/review-integration-v2.mjs +22 -7
  106. package/runtime/windows-session-transport.ps1 +60 -3
  107. package/scripts/bootstrap.sh +4 -1
  108. package/scripts/installer-preflight.mjs +1 -1
  109. package/scripts/pi-update.mjs +113 -3
  110. package/scripts/run-test-suite.mjs +17 -1
  111. package/scripts/shell-snapshot.mjs +340 -0
  112. package/scripts/test-packed-runner.mjs +1 -1
  113. package/scripts/update-agent-body-history.mjs +41 -0
  114. package/scripts/verify-installer-tap.mjs +45 -0
  115. package/scripts/verify-package-files.mjs +2 -0
  116. package/skills/gentle-ai/SKILL.md +2 -2
  117. package/skills/tui-design/NOTICE.md +5 -0
  118. package/skills/tui-design/SKILL.md +56 -0
  119. package/skills/tui-design/references/commands.md +75 -0
  120. package/skills/tui-design/references/critique.md +48 -0
  121. package/skills/tui-design/references/design-doc.md +44 -0
  122. package/skills/tui-design/references/terminal-craft.md +64 -0
  123. package/skills/tui-design/references/visual-loop.md +32 -0
  124. package/tests/agents-protocol.test.ts +53 -1
  125. package/tests/agents-runner.test.ts +168 -3
  126. package/tests/agents-view.test.ts +27 -0
  127. package/tests/agents-widget.test.ts +312 -10
  128. package/tests/bounded-scan-contract.test.ts +39 -0
  129. package/tests/bridge-cost.test.ts +32 -0
  130. package/tests/bundled-install.test.ts +6 -4
  131. package/tests/ci-concurrency.test.ts +11 -0
  132. package/tests/ci-merge-base-identity.test.ts +114 -0
  133. package/tests/codegraph-tools.test.ts +69 -0
  134. package/tests/codemode-rendering.test.ts +22 -2
  135. package/tests/command-palette.test.ts +16 -2
  136. package/tests/commit-slice-signal.test.ts +11 -9
  137. package/tests/delegate-for-reason-contract.test.ts +5 -4
  138. package/tests/exploration-budget.test.ts +128 -0
  139. package/tests/fixtures/agent-assets/gentle-ai-worker.strict-tdd-era.md +122 -0
  140. package/tests/fixtures/measure-orchestrator-prompt.mjs +2 -1
  141. package/tests/fixtures/primary-session-prompt/gentleman.golden.md +18 -10
  142. package/tests/fixtures/session-profile-v1/replay.ts +125 -0
  143. package/tests/fixtures/session-profile-v1/session-profile-authority.ts +113 -0
  144. package/tests/fixtures/session-profile-v1/session-profile-binding.ts +83 -0
  145. package/tests/fixtures/session-profile-v1/session-profile-disk-reader.ts +182 -0
  146. package/tests/fixtures/session-profile-v1/session-profile-freeze.ts +290 -0
  147. package/tests/fixtures/session-profile-v1/session-profile-persistence.ts +195 -0
  148. package/tests/fixtures/session-profile-v1/v1-inputs.ts +16 -0
  149. package/tests/fixtures/windows-pipe-availability.ps1 +26 -0
  150. package/tests/fixtures/windows-session-bootstrap.ps1 +6 -2
  151. package/tests/gentle-agents.test.ts +416 -21
  152. package/tests/gentle-ai-exploration-budget.test.ts +135 -0
  153. package/tests/gentle-ai.test.ts +1007 -33
  154. package/tests/gentle-fast.test.ts +73 -0
  155. package/tests/gentle-guide.test.ts +208 -0
  156. package/tests/gentle-herdr-activity.test.ts +76 -2
  157. package/tests/gentle-herdr-agent.test.ts +111 -0
  158. package/tests/gentle-program-identity.test.ts +197 -0
  159. package/tests/gentle-shell-bin.test.ts +49 -26
  160. package/tests/gentle-shell-launcher.test.ts +18 -2
  161. package/tests/gentle-shell.test.ts +1068 -37
  162. package/tests/gentle-stats.test.ts +15 -2
  163. package/tests/gentle-todo.test.ts +50 -4
  164. package/tests/herdr-task-summary-policy.test.ts +128 -0
  165. package/tests/history-store-private-mode.test.ts +40 -0
  166. package/tests/image-paste-chips.test.ts +42 -0
  167. package/tests/inprocess-reviewer.test.ts +122 -0
  168. package/tests/installer-posix-bootstrap.test.ts +67 -5
  169. package/tests/installer-server.test.ts +2 -2
  170. package/tests/installer-windows-diagnostics.test.ts +4 -5
  171. package/tests/isolated-config-home.ts +28 -0
  172. package/tests/jobs-widget.test.ts +25 -37
  173. package/tests/keymaps-customize.test.ts +114 -0
  174. package/tests/keymaps.test.ts +103 -0
  175. package/tests/maintainer/mcp-status.maintest.ts +88 -0
  176. package/tests/maintainer/pi-update-source.maintest.ts +116 -0
  177. package/tests/model-fallback-notice.test.ts +45 -0
  178. package/tests/model-fallback-policy.test.ts +83 -0
  179. package/tests/model-fallback-store.test.ts +111 -0
  180. package/tests/nan-provider.test.ts +4 -4
  181. package/tests/no-self-pause-contract.test.ts +19 -0
  182. package/tests/notification-customize.test.ts +58 -34
  183. package/tests/odd-routing-canonical-ratchet.test.ts +3 -3
  184. package/tests/odd-routing-contract.test.ts +1 -1
  185. package/tests/orchestrator-fallback.test.ts +82 -0
  186. package/tests/orchestrator-prompt-budget.test.ts +131 -0
  187. package/tests/package-manifest.test.ts +160 -7
  188. package/tests/pasted-image-paths.test.ts +118 -0
  189. package/tests/persona-reply-language.test.ts +20 -1
  190. package/tests/pi-update-launcher.test.ts +32 -8
  191. package/tests/pi-update-source.test.ts +162 -0
  192. package/tests/profile-fast-tier.test.ts +311 -0
  193. package/tests/profile-tier-footer.test.ts +79 -0
  194. package/tests/questionnaire-view.test.ts +150 -0
  195. package/tests/review-candidate-owner-sweep.test.ts +93 -0
  196. package/tests/review-candidate-view.test.ts +51 -0
  197. package/tests/review-controller-native-routing.test.ts +120 -6
  198. package/tests/review-gate.test.ts +24 -0
  199. package/tests/review-inspect-preflight.test.ts +197 -0
  200. package/tests/review-integration-v2-forward.test.ts +59 -0
  201. package/tests/review-repository.test.ts +52 -1
  202. package/tests/review-sidebar-state.test.ts +5 -5
  203. package/tests/run-test-suite.test.ts +61 -5
  204. package/tests/sensitive-path-tools.test.ts +74 -0
  205. package/tests/session-profile-append-controller.test.ts +63 -0
  206. package/tests/session-profile-authority.test.ts +259 -0
  207. package/tests/session-profile-binding.test.ts +15 -0
  208. package/tests/session-profile-extension.test.ts +615 -0
  209. package/tests/session-profile-freeze.test.ts +110 -2
  210. package/tests/session-profile-integration.test.ts +857 -0
  211. package/tests/session-profile-persistence.test.ts +57 -0
  212. package/tests/session-profile-v1-compat.test.ts +221 -0
  213. package/tests/shell-bar.test.ts +113 -55
  214. package/tests/shell-card.test.ts +13 -1
  215. package/tests/shell-page.test.ts +108 -0
  216. package/tests/shell-panel.test.ts +332 -0
  217. package/tests/shell-prompt.test.ts +54 -0
  218. package/tests/shell-render-cache.test.ts +5 -0
  219. package/tests/shell-sidebar-fullscreen.test.ts +12 -0
  220. package/tests/shell-sidebar-layout.test.ts +159 -27
  221. package/tests/shell-stats.test.ts +90 -0
  222. package/tests/shell-usage.test.ts +14 -0
  223. package/tests/skill-registry.test.ts +68 -1
  224. package/tests/star-prompt.test.ts +470 -0
  225. package/tests/startup-banner.test.ts +57 -1
  226. package/tests/task-size-routing-contract.test.ts +45 -1
  227. package/tests/verifier-settle-reminder.test.ts +281 -0
  228. package/tests/verify-first-launch-contract.test.ts +56 -5
  229. package/tests/verify-installer-tap.test.ts +57 -0
  230. package/tests/vim-editor-adapter.test.ts +2 -2
  231. package/tests/visual-customization-policy.test.ts +61 -7
  232. package/tests/visual-customize-view.test.ts +253 -8
  233. package/tests/visual-layout-preview.test.ts +28 -0
  234. package/tests/windows-session-bootstrap.test.ts +105 -2
  235. package/tests/work-continuity-contract.test.ts +86 -0
  236. package/tests/writer-surfaces.test.ts +12 -10
  237. package/tests/yolo-customize.test.ts +30 -11
  238. package/tests/yolo-mode-runtime.test.ts +4 -2
  239. package/tests/yolo-mode.test.ts +16 -2
@@ -1,4 +1,7 @@
1
+ import { emptyFallbacksFile, fallbacksFilePath, followProfileRename, readFallbacksFile, setChain, writeFallbacksFile, type FallbackStep } from "../lib/model-fallback-store.ts";
1
2
  import { getSupportedThinkingLevels } from "@earendil-works/pi-ai";
3
+ import { PROFILE_TIER_EVENT, supportsOpenAIFast } from "../lib/openai-fast-tier.ts";
4
+ import { isDeepStrictEqual } from "node:util";
2
5
  import { appendSystemPromptOnce } from "../lib/append-system-prompt.ts";
3
6
  import { dataArgumentRanges, recognizeDestructiveCommands } from "../lib/destructive-command-guard.ts";
4
7
  import { defaultTempScratchFs, isTempScratchRemoval, type TempScratchFs } from "../lib/yolo-temp-scratch.ts";
@@ -6,9 +9,11 @@ import { SHELL_COMMAND_TOOLS } from "../lib/background-jobs.ts";
6
9
  import { evaluateDeliveredTestTool } from "../lib/delivered-test-lint.ts";
7
10
  import { commitSliceToolResult } from "../lib/commit-slice-signal.ts";
8
11
  import { appendContextBackstopNotice, createContextBackstopSignal, createThrottledContextMeasure } from "../lib/context-backstop.ts";
12
+ import { createExplorationBudget } from "../lib/exploration-budget.ts";
9
13
  import { blockChildDestructiveCommand } from "./child-safety.ts";
10
14
  import { allowedEditSurfaces as hasTaskScopedAllowedEditSurfaces, bindSessionRepositoryPreparation, captureBoundSessionRepositoryAuthority, isHomeOrBroadUserDirectory, prepareBoundSessionRepository, rejectUndocumentedWriterLaunch, rejectUnscopedBoundedWriterDispatch, safeBootstrapDirectory, sourcePathWithinProject } from "../lib/bounded-writer-admission.ts";
11
15
  import { rejectUnriskedVerifierLaunch } from "../lib/verifier-admission.ts";
16
+ import { VERIFIER_SETTLE_REMINDER_TYPE, createVerifierSettleReminders, finalAssistantText } from "../lib/verifier-settle-reminder.ts";
12
17
  import { consumeReviewMutation, pendingReviewMutation, pendingReviewMutationProfiles, recordReviewMutation, type ReceiptSession } from "../lib/review-reminder-receipt.ts";
13
18
  import { createReviewSidebarPublisher } from "../lib/review-sidebar-state.ts";
14
19
  import { StatusTimingDiagnostics } from "../lib/status-timing-diagnostics.ts";
@@ -20,13 +25,18 @@ import { execFileSync } from "node:child_process";
20
25
  import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
21
26
  import { isProxy } from "node:util/types";
22
27
  import {
28
+ accessSync,
29
+ constants as fsConstants,
23
30
  existsSync,
24
31
  lstatSync,
25
32
  mkdirSync,
33
+ mkdtempSync,
26
34
  readdirSync,
27
35
  readFileSync,
28
36
  realpathSync,
37
+ rmSync,
29
38
  statSync,
39
+ symlinkSync,
30
40
  writeFileSync,
31
41
  } from "node:fs";
32
42
  import {
@@ -37,12 +47,13 @@ import {
37
47
  writeFile,
38
48
  } from "node:fs/promises";
39
49
  import { homedir } from "node:os";
40
- import { discoverAgents, loadAgentsConfig, unmatchedProfileKeys } from "../lib/agents-config.ts";
50
+ import { PROVIDER_REVIEW_ROLES, discoverAgents, loadAgentsConfig, unmatchedProfileKeys } from "../lib/agents-config.ts";
41
51
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
42
52
  import { fileURLToPath } from "node:url";
43
53
  import type {
44
54
  ExtensionAPI,
45
55
  ExtensionContext,
56
+ SessionShutdownEvent,
46
57
  Theme,
47
58
  ThemeColor,
48
59
  ToolCallEventResult,
@@ -114,7 +125,12 @@ import {
114
125
  type ProfilePinSource,
115
126
  type ProfilePinStatus,
116
127
  } from "../lib/agent-profile-pin.ts";
117
- import { bindSessionProfile, readSessionProfileBinding } from "../lib/session-profile-binding.ts";
128
+ import { clearSessionProfileBinding, readSessionProfileBinding } from "../lib/session-profile-binding.ts";
129
+ import { createSessionProfileIntegration, hasPendingSessionProfileSelection, readCurrentSessionProfileOutcome, runCurrentSessionProfileSelection, waitCurrentSessionProfileSelection } from "../lib/session-profile-integration.ts";
130
+ import { publishSessionProfileOutcome, readSessionProfileAuthority } from "../lib/session-profile-authority.ts";
131
+ import { isSessionProfileFamilyEntry, type SessionProfileStartupState } from "../lib/session-profile-persistence.ts";
132
+ import type { SessionProfileAppendOutcome } from "../lib/session-profile-append-controller.ts";
133
+ import { freezeSessionProfileAtOwnStart, profileFollowEnabled, readSessionProfileOwnStartup, resolveSessionProfile, sessionProfileLabel, sessionProfileModelProfiles, sessionProfileRoutingAt, setFrozenDefaultOrchestrator } from "../lib/session-profile-freeze.ts";
118
134
  import {
119
135
  applyOrchestratorSettings,
120
136
  readOrchestratorSettings,
@@ -168,7 +184,8 @@ import {
168
184
  import { GentleAiElapsedTimingLedger } from "../lib/gentle-ai-elapsed-store.ts";
169
185
  import { renderGentleAiLifecycleCall, renderGentleAiResult, type GentleAiRenderContext } from "../lib/gentle-ai-renderer.ts";
170
186
  import { sanitizeTerminalText, stripAnsi } from "../lib/terminal-theme.ts";
171
- import { BASE_REF_ACCEPTED_FORMS, CandidateViewError, CandidateViewRegistry, injectReviewCandidateView, readCandidateContextManifestPage, resolveCanonicalCandidateBase, isProviderCandidateBaseTree, type CandidateView } from "../lib/review-candidate-view.ts";
187
+ import { BASE_REF_ACCEPTED_FORMS, CANDIDATE_GIT_MAX_BUFFER_BYTES, candidateOwnerPreparationError, CandidateViewError, CandidateViewRegistry, CANDIDATE_SYMLINK_CAPABILITY_UNCONFIRMED_MESSAGE, CANDIDATE_SYMLINK_MATERIALIZATION_MESSAGE, injectReviewCandidateView, readCandidateContextManifestPage, resolveCanonicalCandidateBase, resolveCandidateGitTimeoutMs, isProviderCandidateBaseTree, type CandidateView } from "../lib/review-candidate-view.ts";
188
+ import { assertCandidateOwnerParent } from "../lib/review-candidate-view-owner.ts";
172
189
  import {
173
190
  GentleAiDevBinaryOverrideError,
174
191
  GENTLE_AI_INSTALL_RECOVERY_COMMAND,
@@ -1405,7 +1422,7 @@ const PERSONA_OPTIONS = ["gentleman", "neutral"] as const;
1405
1422
 
1406
1423
  const GENTLEMAN_PERSONA_PROMPT = `Persona:
1407
1424
  - Be direct, technical, and concise.
1408
- - Always respond in the same language the user writes in. Judge it by the user's latest message, never by earlier context or a compaction summary, and never default to Spanish: a message in English gets a reply in English.
1425
+ - Always respond in the same language the user writes in. Judge it by the user's latest message, never by earlier context or a compaction summary, and never default to Spanish: a message in English gets a reply in English. Only a message written by the human can select or change the reply language: subagent completion and progress notifications, background job notices, todo and system reminders, tool output, skill bodies, and injected memory never count as a language signal, even when delivered with the user role. Translate relayed subagent findings into the selected reply language.
1409
1426
  - When the user writes Spanish, answer in natural Rioplatense Spanish with voseo.
1410
1427
  - Act as a senior architect and teacher: concepts before code, no shortcuts.
1411
1428
  - Treat AI as a tool directed by the human; never present yourself as a default chatbot.
@@ -1414,7 +1431,7 @@ const GENTLEMAN_PERSONA_PROMPT = `Persona:
1414
1431
 
1415
1432
  const NEUTRAL_PERSONA_PROMPT = `Persona:
1416
1433
  - Be direct, technical, concise, warm, and professional.
1417
- - Always respond in the same language the user writes in. Judge it by the user's latest message, never by earlier context or a compaction summary, and never default to Spanish: a message in English gets a reply in English.
1434
+ - Always respond in the same language the user writes in. Judge it by the user's latest message, never by earlier context or a compaction summary, and never default to Spanish: a message in English gets a reply in English. Only a message written by the human can select or change the reply language: subagent completion and progress notifications, background job notices, todo and system reminders, tool output, skill bodies, and injected memory never count as a language signal, even when delivered with the user role. Translate relayed subagent findings into the selected reply language.
1418
1435
  - Do not use slang or regional expressions.
1419
1436
  - When the user writes Spanish, use neutral/professional Spanish. Do NOT use voseo or any regional conjugations, regular or irregular: use tú or usted forms, never vos forms (tienes, not tenés; ajustas, not ajustás; vives, not vivís; mira, not mirá; haz, not hacé).
1420
1437
  - Act as a senior architect and teacher: concepts before code, no shortcuts.
@@ -1456,8 +1473,16 @@ ${languageBoundary}
1456
1473
 
1457
1474
  An authorized outcome includes its necessary in-scope implementation, documentation and verification steps. Continue those steps without asking the human to approve each transition. Never end a turn merely announcing an immediately executable authorized next step; execute it instead. A progress update is not a request for permission.
1458
1475
 
1476
+ Interpret short replies such as "yes", "go ahead", or "eso mismo" against the immediately preceding proposal. When the human unambiguously accepts a concrete implementation action they already understand, execute that action within its agreed scope without asking again. Confirming a preference alone does not authorize implementation; genuinely unclear change intent still requires one focused question. Contextual approval never substitutes for provider-owned consent, exact-token authorization, or separate publishing and destructive-action permission.
1477
+
1478
+ Resolving an incident or subdecision does not complete or cancel the original authorized objective; resume safe, necessary in-scope steps automatically, using judgment for proportionate recovery and respecting explicit user dispositions. Investigate pending technical uncertainty rather than treating it alone as a new human decision.
1479
+
1459
1480
  Stop only for an unresolved consequential scope/product decision, required explicit consent, a denied action, unavailable required proof, or the human's explicit stop. Do not infer permission for publishing, destructive actions, unrelated scope or native consent from this continuity rule. Report a concrete blocker and the exact decision needed rather than requesting a generic "continue".
1460
1481
 
1482
+ Before a terminal bounded-stop outcome, distinguish a recoverable technical or harness failure from genuinely inaccessible required proof. A failed test or harness check may be corrected and rerun without another authorization only within the authorized scope and existing correction budget, subject to every applicable limit. Honor explicit one run, no retries, or diagnostic-only limits; stop for permission denial, required new consent, or exhausted budget. Do not propose diagnostic-only or single-attempt authorization unless the human requested it. Respect terminal review and verification outcomes and existing bounded-stop rules: never reset budgets, add retry allowances, weaken checks, or override final outcomes. An unavailable verifier remains unavailable; do not retry or escalate it.
1483
+
1484
+ For worker-prohibited maintenance or rollback, worker prohibitions remain unchanged. The parent only may perform the operation when the human explicitly authorized the operation itself, exact scope, ownership, and preservation are established, and available permitted tools can perform it; fresh runtime/native consent and guards remain binding. A broad feature authorization is not destructive authority; never substitute another worker or tool to bypass a denial. For an upgrade require a validated backup, artifact and migration validation where applicable, and a recovery path. For rollback preserve unrelated edits even in the same file, remove only proven task-created helpers, and never blanket restore, reset, or clean. Stop when ambiguous ownership or denial stops the operation, or any prerequisite is missing. This route is guidance, not authorization.
1485
+
1461
1486
  For background work, launch the bounded action and end the turn when no independent in-scope work remains. Retain its identity and resume the already-authorized continuation automatically on its completion event; do not ask the human to say "continue", poll, or claim completion while checks remain pending.
1462
1487
 
1463
1488
  Default workflow: Organic Driven Development (MANDATORY)
@@ -1466,7 +1491,7 @@ ${oddProtocolSteps()}
1466
1491
 
1467
1492
  Harness principles:
1468
1493
  - el Gentleman is not prompt engineering. It is runtime discipline around powerful agents.
1469
- - Clarify scope, constraints, acceptance criteria, and non-goals before implementation.
1494
+ - Clarify scope, constraints, acceptance criteria, and non-goals when needed for the human to understand the action or to resolve consequential uncertainty. Reuse what is already established; after informed approval, proceed without repeating the clarification unless new consequential uncertainty appears.
1470
1495
  - Use subagents when available for exploration, planning, implementation, and review, while keeping one parent session responsible for orchestration.
1471
1496
  - For behavior changes with applicable runnable deterministic tests and a clear expected outcome, use test-first by default: observe RED, GREEN, then refactor with focused checks. Write one RED test per requested rule. For every existing command or option the change touches, add one test proving its previous behavior still holds; add no other cases. An existing behavior counts as touched when it shares the code you changed (options, parsers, helpers, validation). Only when your diff changes shared code (options, parsers, helpers) that an existing command the request did not name also uses, run one differential check before finishing, as a single script: for each such command, run it with the new or changed input (for example a new option passed to a sibling subcommand) against the previous code (a copy of the base commit in a \`mktemp -d\` scratch directory, never committed as a test; committed tests never read git history or a fixed commit) and against your change, and compare stdout, stderr, and exit code; any difference nobody asked for is a regression to fix and pin with a test. Test presence alone does not establish applicability; no chat or TUI toggle activates it. For passive documentation, non-testable changes, an unavailable runner, or no meaningful RED, explain why and run proportionate ordinary functional or structural verification. Never invent lifecycle evidence or skip checks. Follow orchestrator-delegation.md for ODD forwarding and evidence.
1472
1497
  - Protect the human reviewer: avoid oversized changes, surface review workload risk, and ask before turning one task into a large multi-area change.
@@ -1774,7 +1799,12 @@ function loadRuntimeGuardrailsConfig(
1774
1799
  }
1775
1800
  }
1776
1801
 
1777
- const PATH_GUARDED_TOOL_NAMES = new Set(["read", "write", "edit"]);
1802
+ // Tools whose `path` input names the file or directory they reach. The guard
1803
+ // sees only that input: a search scoped to a directory (grep over ".", with or
1804
+ // without a glob) still reads whatever the directory contains, and bash is not
1805
+ // covered here. Keeping secret bytes out of those results is a separate design
1806
+ // (gentle-shell#2349).
1807
+ const PATH_GUARDED_TOOL_NAMES = new Set(["read", "write", "edit", "grep", "find", "ls"]);
1778
1808
  const PATH_INPUT_KEYS = new Set([
1779
1809
  "path",
1780
1810
  "paths",
@@ -2480,9 +2510,33 @@ function readEffectiveModelConfig(cwd: string): AgentModelConfig {
2480
2510
  return pinnedEffectiveModelConfig(cwd) ?? readGlobalEffectiveModelConfig(cwd);
2481
2511
  }
2482
2512
 
2483
- /** Resolve one complete reviewer routing snapshot without per-role fallback. */
2484
- function readReviewerModelConfig(cwd: string, sessionId: string | undefined): AgentModelConfig {
2485
- return readSessionProfileBinding(sessionId)?.modelProfiles ?? pinnedEffectiveModelConfig(cwd) ?? readModelConfig(cwd);
2513
+ /**
2514
+ * Resolve one complete reviewer routing snapshot without per-role fallback,
2515
+ * through the same rule launches read (gentle-shell#1064): the Enter binding,
2516
+ * else the profile the session froze at startup (a session frozen without one
2517
+ * never adopts a later pin), else in follow mode the profile the target
2518
+ * resolves now. A reviewer never runs on routing the session no longer uses.
2519
+ */
2520
+ function readReviewerModelConfig(cwd: string, sessionId: string | undefined, sessionCwd: string = cwd): AgentModelConfig {
2521
+ const resolution = resolveSessionProfile({ sessionId, cwd: sessionCwd, configHome: gentleAiConfigHome() });
2522
+ // A target in another Git repository keeps its own pin layers, as launches do.
2523
+ const target = readProfilePinStatus(cwd)?.commonDir;
2524
+ const home = readProfilePinStatus(sessionCwd)?.commonDir;
2525
+ // A session outside Git has no repository of its own, so any Git target is foreign.
2526
+ const foreignRepository = target !== undefined && target !== home;
2527
+ // A caller without a session keeps the routing it read before session profiles.
2528
+ // An explicit binding carries its full modelProfiles (orchestrator included) to
2529
+ // the fallback below; sessionProfileRoutingAt role-routes it, and launches must
2530
+ // never see the orchestrator key (gentle-shell#2742, section 8).
2531
+ const routed = resolution.kind === "live" ? pinnedEffectiveModelConfig(cwd)
2532
+ : resolution.kind === "explicit" ? resolution.modelProfiles
2533
+ : sessionProfileRoutingAt(resolution, { cwd, configHome: gentleAiConfigHome(), foreignRepository });
2534
+ const config = routed === undefined ? readModelConfig(cwd) : cloneModelConfig(routed);
2535
+ // Only a profile chosen with Use in this session carries its orchestrator to
2536
+ // the provider review roles; inherited, pinned and global routing leave them on
2537
+ // Pi's persisted default (gentle-shell#2716 A1).
2538
+ if (resolution.kind !== "explicit") delete config.orchestrator;
2539
+ return config;
2486
2540
  }
2487
2541
 
2488
2542
  /** The routing in effect once the pin is set aside: what a global save materializes. */
@@ -2497,6 +2551,44 @@ function readGlobalEffectiveModelConfig(cwd: string): AgentModelConfig {
2497
2551
  return effective;
2498
2552
  }
2499
2553
 
2554
+ /**
2555
+ * The profile this session's launches resolve (gentle-shell#1064 slice 3c): the
2556
+ * Enter binding, then the profile frozen at startup, through the same rule the
2557
+ * launcher reads. It resolves from the session's directory, as the freeze and
2558
+ * the launcher do. `undefined` means the session resolves no profile, so
2559
+ * launches keep the global routing; a pin the session did not freeze never
2560
+ * reaches them and is not read here. Without session profile authority the
2561
+ * launches are blocked, so no profile is theirs.
2562
+ */
2563
+ function sessionLaunchProfile(ctx: ExtensionContext, authorityAvailable: boolean): { name: string; modelProfiles: AgentModelConfig } | undefined {
2564
+ if (!authorityAvailable) return undefined;
2565
+ const resolution = resolveSessionProfile({
2566
+ sessionId: ctx.sessionManager?.getSessionId?.(),
2567
+ cwd: ctx.sessionManager?.getCwd?.() ?? ctx.cwd,
2568
+ configHome: gentleAiConfigHome(),
2569
+ });
2570
+ const name = resolution.kind === "explicit" ? resolution.name : resolution.profile?.name;
2571
+ const routing = sessionProfileModelProfiles(resolution);
2572
+ return name === undefined || routing === undefined ? undefined : { name, modelProfiles: cloneModelConfig(routing) };
2573
+ }
2574
+
2575
+ /**
2576
+ * Whether this session's launches may run, read as the launcher reads it (and,
2577
+ * like it, clearing a binding it cannot corroborate). A manager without a
2578
+ * branch has no session profile record to distrust.
2579
+ */
2580
+ function sessionProfileAuthorityAvailable(ctx: ExtensionContext): boolean {
2581
+ const manager = ctx.sessionManager;
2582
+ if (typeof manager?.getSessionId !== "function" || typeof manager.getBranch !== "function") return true;
2583
+ return readSessionProfileAuthority(manager).available;
2584
+ }
2585
+
2586
+ /** The routing this session's launches use: its profile, or the global effective routing. */
2587
+ async function readSessionLaunchModelConfigAsync(ctx: ExtensionContext, authorityAvailable: boolean): Promise<AgentModelConfig> {
2588
+ return sessionLaunchProfile(ctx, authorityAvailable)?.modelProfiles
2589
+ ?? await readGlobalEffectiveModelConfigFromAsync(ctx.cwd, await readModelConfigAsync(ctx.cwd));
2590
+ }
2591
+
2500
2592
  async function readEffectiveModelConfigAsync(cwd: string): Promise<AgentModelConfig> {
2501
2593
  const pinned = pinnedEffectiveModelConfig(cwd);
2502
2594
  if (pinned) return pinned;
@@ -2869,8 +2961,6 @@ function isValidJsonObjectFileOrMissing(path: string): boolean {
2869
2961
  }
2870
2962
  }
2871
2963
 
2872
- const PROVIDER_REVIEW_ROLES = ["review-refuter", "review-validator"] as const;
2873
-
2874
2964
  function isProviderReviewRole(name: string): boolean {
2875
2965
  return PROVIDER_REVIEW_ROLES.some((role) => role === name);
2876
2966
  }
@@ -3211,12 +3301,15 @@ const ROUTING_TABLE_HINTS: Array<{ text: string; keep: number }> = [
3211
3301
  { text: "↑↓ agent", keep: 6 },
3212
3302
  { text: "enter model", keep: 1 },
3213
3303
  { text: "e effort", keep: 2 },
3304
+ { text: "f fallbacks", keep: 6.5 },
3305
+ { text: "t tier", keep: 6.25 },
3214
3306
  { text: "s save", keep: 3 },
3215
3307
  { text: "u use", keep: 7 },
3216
3308
  { text: "d default", keep: 8 },
3217
3309
  { text: "n new", keep: 10 },
3218
3310
  { text: "m menu", keep: 9 },
3219
3311
  { text: "esc close", keep: 4 },
3312
+ { text: "a all fast", keep: 11 },
3220
3313
  ];
3221
3314
  /** Model card chrome (title, search, rule, blank, hint), its borders, and a margin so the card never touches the frame. */
3222
3315
  const ROUTING_MODEL_CARD_CHROME_ROWS = 11;
@@ -3269,6 +3362,8 @@ type RoutingTableMouseAction =
3269
3362
  | { kind: "new" }
3270
3363
  | { kind: "row"; row: string }
3271
3364
  | { kind: "effort"; row: string }
3365
+ | { kind: "tier"; row: string }
3366
+ | { kind: "all-fast" }
3272
3367
  | { kind: "model-option"; index: number }
3273
3368
  | { kind: "effort-option"; index: number }
3274
3369
  | { kind: "menu-item"; id: string }
@@ -3297,8 +3392,47 @@ const ROUTING_TABLE_BUTTONS: Record<RoutingTableButton, string> = {
3297
3392
  * Model and effort changes happen in small cards over the still-visible table.
3298
3393
  * Keyboard and pointer reach the same actions, and each key means one thing.
3299
3394
  */
3395
+ /** Reads and writes the profile's fallback chains; `save` returns an error message when it refuses. */
3396
+ interface RoutingFallbacks {
3397
+ chain(profile: string, key: string): readonly FallbackStep[];
3398
+ save(profile: string, key: string, chain: readonly FallbackStep[]): string | undefined;
3399
+ }
3400
+
3401
+ /** The panel's view of profile-fallbacks.json: read once, re-read after each save; a broken file is never overwritten. */
3402
+ function fileRoutingFallbacks(configHome: string): RoutingFallbacks {
3403
+ const path = fallbacksFilePath(configHome);
3404
+ let read = readFallbacksFile(path);
3405
+ return {
3406
+ chain: (profile, key) => (read.status === "valid" ? read.file.profiles[profile]?.[key] ?? [] : []),
3407
+ save: (profile, key, chain) => {
3408
+ // Chains belong to saved profiles; a draft would leave them orphaned.
3409
+ const profiles = readProfilesFileResult(profilesFilePath(configHome));
3410
+ if (profiles.status !== "valid" || !hasOwnProfile(profiles.file.profiles, profile)) return `Save the profile first (s), then add its fallbacks.`;
3411
+ read = readFallbacksFile(path);
3412
+ if (read.status === "invalid") return `${path} is malformed; fix or remove it first.`;
3413
+ try {
3414
+ writeFallbacksFile(path, setChain(read.status === "valid" ? read.file : emptyFallbacksFile(), profile, key, chain));
3415
+ } catch (error) {
3416
+ return `Fallbacks not saved: ${error instanceof Error ? error.message : String(error)}`;
3417
+ } finally {
3418
+ read = readFallbacksFile(path);
3419
+ }
3420
+ return undefined;
3421
+ },
3422
+ };
3423
+ }
3424
+
3425
+ /** A renamed or deleted profile takes its fallback chains along; a failure leaves the chains where they were. */
3426
+ function followProfileFallbacks(profilesPath: string, from: string, to: string | undefined): void {
3427
+ try { followProfileRename(dirname(profilesPath), from, to); } catch { /* The profile change already succeeded. */ }
3428
+ }
3429
+
3300
3430
  class RoutingTablePanel implements OverlayComponent {
3301
- private overlay: "model" | "effort" | "menu" | "new" | "switch" | undefined;
3431
+ private overlay: "model" | "effort" | "menu" | "new" | "switch" | "fallbacks" | undefined;
3432
+ /** The model and effort cards are picking a fallback step, not the row's own model. */
3433
+ private pickingFallback = false;
3434
+ private fallbackCursor = 0;
3435
+ private readonly fallbacks: RoutingFallbacks | undefined;
3302
3436
  private target: string = PROFILE_ORCHESTRATOR_KEY;
3303
3437
  private pending: RoutingTableResult | undefined;
3304
3438
  private cursor = 0;
@@ -3326,6 +3460,7 @@ class RoutingTablePanel implements OverlayComponent {
3326
3460
  private sessionBoundName: string | undefined;
3327
3461
  private pinWinner: string | undefined;
3328
3462
  private readonly thinkingSupport: Record<string, readonly ThinkingLevel[]>;
3463
+ private readonly fastModels: ReadonlySet<string>;
3329
3464
  /** Configuration problems the screen must not hide: pins that do not resolve, keys no agent matches. */
3330
3465
  private notices: string[];
3331
3466
  private readonly switchProfile: RoutingProfileSwitcher | undefined;
@@ -3344,12 +3479,16 @@ class RoutingTablePanel implements OverlayComponent {
3344
3479
  pinWinner?: string;
3345
3480
  feedback?: string;
3346
3481
  thinkingSupport?: Record<string, readonly ThinkingLevel[]>;
3482
+ fastModels?: string[];
3347
3483
  notices?: string[];
3348
3484
  switchProfile?: RoutingProfileSwitcher;
3485
+ fallbacks?: RoutingFallbacks;
3349
3486
  } = {},
3350
3487
  ) {
3351
3488
  this.switchProfile = options.switchProfile;
3489
+ this.fallbacks = options.fallbacks;
3352
3490
  this.thinkingSupport = options.thinkingSupport ?? {};
3491
+ this.fastModels = new Set(options.fastModels ?? []);
3353
3492
  this.notices = options.notices ?? [];
3354
3493
  this.file = options.file ?? bootstrapProfilesFile(cloneModelConfig(draft));
3355
3494
  const names = Object.keys(this.file.profiles);
@@ -3384,11 +3523,12 @@ class RoutingTablePanel implements OverlayComponent {
3384
3523
  for (const key of [PROFILE_ORCHESTRATOR_KEY, ...this.agents]) {
3385
3524
  if (this.isEdited(key, "model")) count += 1;
3386
3525
  if (this.isEdited(key, "thinking")) count += 1;
3526
+ if (this.isEdited(key, "tier")) count += 1;
3387
3527
  }
3388
3528
  return count;
3389
3529
  }
3390
3530
 
3391
- private isEdited(key: string, field: "model" | "thinking"): boolean {
3531
+ private isEdited(key: string, field: "model" | "thinking" | "tier"): boolean {
3392
3532
  return (this.draft[key]?.[field] ?? undefined) !== (this.stored[key]?.[field] ?? undefined);
3393
3533
  }
3394
3534
 
@@ -3451,7 +3591,8 @@ class RoutingTablePanel implements OverlayComponent {
3451
3591
 
3452
3592
  /** The effort card's choices: inherit, then the supported levels, or every level when unknown. */
3453
3593
  private effortOptions(): Array<ThinkingLevel | typeof INHERIT_THINKING> {
3454
- const supported = this.supportedLevels(this.target);
3594
+ const step = this.pickingFallback ? this.chain()[this.fallbackCursor] : undefined;
3595
+ const supported = step ? this.thinkingSupport[step.model] : this.supportedLevels(this.target);
3455
3596
  return [INHERIT_THINKING, ...THINKING_LEVELS.filter((level) => !supported || supported.includes(level))];
3456
3597
  }
3457
3598
 
@@ -3472,6 +3613,12 @@ class RoutingTablePanel implements OverlayComponent {
3472
3613
 
3473
3614
  private modelOptions(): string[] {
3474
3615
  const query = this.query.trim().toLowerCase();
3616
+ if (this.pickingFallback) {
3617
+ // Only real models, never the row's own one or one already in the chain.
3618
+ const taken = new Set([...this.chain().map((step) => step.model), ...this.targetKeys().map((key) => this.draft[key]?.model)]);
3619
+ const offered = this.catalog.filter((option) => !taken.has(option));
3620
+ return query ? offered.filter((option) => option.toLowerCase().includes(query)) : offered;
3621
+ }
3475
3622
  const all = [this.inheritLabel(this.target), ...this.catalog];
3476
3623
  const matches = query ? all.filter((option) => option.toLowerCase().includes(query)) : all;
3477
3624
  return [...matches, ROUTING_CUSTOM_MODEL];
@@ -3533,11 +3680,106 @@ class RoutingTablePanel implements OverlayComponent {
3533
3680
  }
3534
3681
 
3535
3682
  private closeOverlay(): void {
3536
- this.overlay = undefined;
3683
+ this.overlay = this.pickingFallback ? "fallbacks" : undefined;
3684
+ this.pickingFallback = false;
3537
3685
  this.pending = undefined;
3538
3686
  this.query = "";
3539
3687
  }
3540
3688
 
3689
+ // -- fallback chains --------------------------------------------------------
3690
+
3691
+ /** The chain key of a row: the every-agent row edits the profile's `*` chain. */
3692
+ private chainKey(row: string): string {
3693
+ return row === ROUTING_ALL_ROW ? "*" : row;
3694
+ }
3695
+
3696
+ private chain(row = this.target): FallbackStep[] {
3697
+ return [...(this.fallbacks?.chain(this.profileName, this.chainKey(row)) ?? [])].map((step) => ({ ...step }));
3698
+ }
3699
+
3700
+ private saveChain(chain: FallbackStep[], message: string): boolean {
3701
+ const error = this.fallbacks?.save(this.profileName, this.chainKey(this.target), chain);
3702
+ if (error) {
3703
+ this.say(error);
3704
+ return false;
3705
+ }
3706
+ this.say(message);
3707
+ return true;
3708
+ }
3709
+
3710
+ private openFallbacks(row: string): void {
3711
+ if (!this.fallbacks) return this.say("Fallback chains are unavailable here.");
3712
+ this.target = row;
3713
+ this.overlay = "fallbacks";
3714
+ this.fallbackCursor = 0;
3715
+ }
3716
+
3717
+ private handleFallbacksKey(data: string): void {
3718
+ const chain = this.chain();
3719
+ const label = this.rowLabel(this.target);
3720
+ if (matchesKey(data, "escape")) {
3721
+ this.overlay = undefined;
3722
+ return;
3723
+ }
3724
+ if (matchesKey(data, "shift+up") || matchesKey(data, "shift+down")) {
3725
+ const to = this.fallbackCursor + (matchesKey(data, "shift+up") ? -1 : 1);
3726
+ if (to < 0 || to >= chain.length) return;
3727
+ const [step] = chain.splice(this.fallbackCursor, 1);
3728
+ chain.splice(to, 0, step!);
3729
+ if (this.saveChain(chain, `${label}: ${step!.model} is fallback ${to + 1}.`)) this.fallbackCursor = to;
3730
+ return;
3731
+ }
3732
+ if (matchesKey(data, "up") || matchesKey(data, "k")) {
3733
+ this.fallbackCursor = Math.max(0, this.fallbackCursor - 1);
3734
+ return;
3735
+ }
3736
+ if (matchesKey(data, "down") || matchesKey(data, "j")) {
3737
+ this.fallbackCursor = Math.min(Math.max(0, chain.length - 1), this.fallbackCursor + 1);
3738
+ return;
3739
+ }
3740
+ if (matchesKey(data, "f") || matchesKey(data, "a") || matchesKey(data, "return")) {
3741
+ this.pickingFallback = true;
3742
+ this.overlay = "model";
3743
+ this.query = "";
3744
+ this.modelCursor = 0;
3745
+ if (this.modelOptions().length === 0) {
3746
+ this.closeOverlay();
3747
+ this.say(`${label}: every model is already in its chain.`);
3748
+ }
3749
+ return;
3750
+ }
3751
+ if (matchesKey(data, "e") && chain[this.fallbackCursor]) {
3752
+ this.pickingFallback = true;
3753
+ this.overlay = "effort";
3754
+ const current = chain[this.fallbackCursor]!.thinking;
3755
+ this.effortCursor = Math.max(0, current === undefined ? 0 : this.effortOptions().indexOf(current));
3756
+ return;
3757
+ }
3758
+ if ((matchesKey(data, "x") || matchesKey(data, "delete")) && chain[this.fallbackCursor]) {
3759
+ const [removed] = chain.splice(this.fallbackCursor, 1);
3760
+ if (this.saveChain(chain, `${label}: removed fallback ${removed!.model}.`)) this.fallbackCursor = Math.max(0, Math.min(this.fallbackCursor, chain.length - 1));
3761
+ }
3762
+ }
3763
+
3764
+ private fallbacksCard(inner: number): { lines: string[]; width: number; top: number; left: number } {
3765
+ const width = Math.min(60, inner - 4);
3766
+ const content = width - 4;
3767
+ const chain = this.chain();
3768
+ const lines: string[] = [];
3769
+ lines.push(this.renderText("Fallbacks for ", "muted") + this.renderText(this.target === ROUTING_ALL_ROW ? "every agent" : this.rowLabel(this.target), "title"));
3770
+ lines.push(this.renderText(truncateToWidth("Used in order when the model runs out or keeps failing.", content, "…"), "dim"));
3771
+ lines.push(this.renderText("─".repeat(content), "border"));
3772
+ if (chain.length === 0) lines.push(this.renderText(this.target === ROUTING_ALL_ROW ? "No fallbacks. f adds one for every agent without its own." : "No fallbacks. f adds one.", "dim"));
3773
+ chain.forEach((step, index) => {
3774
+ const focused = index === this.fallbackCursor;
3775
+ const text = truncateToWidth(`${index + 1}. ${sanitizeTerminalText(step.model)}${step.thinking ? ` · ${step.thinking}` : ""}`, content - 2, "…");
3776
+ lines.push(this.renderText(focused ? "▸ " : " ", "accent") + this.renderText(text, focused ? "title" : "text"));
3777
+ });
3778
+ lines.push("");
3779
+ lines.push(this.renderText(truncateToWidth("f add · e effort · shift+↑↓ move · x remove · esc back", content, "…"), "dim"));
3780
+ return { lines, width, top: 4, left: Math.max(0, Math.floor((inner - width) / 2)) };
3781
+ }
3782
+
3541
3783
  /** Leaving this profile with unsaved edits asks first; nothing is lost in silence. */
3542
3784
  private leave(result: RoutingTableResult): void {
3543
3785
  if (this.changeCount() === 0) {
@@ -3582,6 +3824,29 @@ class RoutingTablePanel implements OverlayComponent {
3582
3824
  this.effortCursor = Math.max(0, landed === undefined ? 0 : this.effortOptions().indexOf(landed));
3583
3825
  }
3584
3826
 
3827
+ private toggleTier(key: string): void {
3828
+ const entry = this.draft[key];
3829
+ if (!entry?.model || !this.fastModels.has(entry.model)) {
3830
+ this.say("Standard/Fast is available only for compatible OpenAI models.");
3831
+ return;
3832
+ }
3833
+ entry.tier = entry.tier === "fast" ? "standard" : "fast";
3834
+ this.say(`${this.rowLabel(key)}: ${entry.tier === "fast" ? "Fast" : "Standard"}. Save keeps it in ${this.profileName}.${entry.tier === "fast" ? " Fast depends on plan/model; subscription usage 2.5x or purchased credits 2x. API pricing differs." : ""}`);
3835
+ }
3836
+
3837
+ private setAllFast(): void {
3838
+ let count = 0;
3839
+ for (const key of [PROFILE_ORCHESTRATOR_KEY, ...this.agents]) {
3840
+ const entry = this.draft[key];
3841
+ if (!entry?.model || !this.fastModels.has(entry.model)) continue;
3842
+ if (entry.tier !== "fast") this.toggleTier(key);
3843
+ count += 1;
3844
+ }
3845
+ this.say(count
3846
+ ? `All Fast: ${count} compatible route${count === 1 ? "" : "s"}. Save to keep. Subscription 2.5x; purchased credits 2x. API pricing differs.`
3847
+ : "No compatible OpenAI routes in this profile.");
3848
+ }
3849
+
3585
3850
  private openMenu(kind: "menu" | "new"): void {
3586
3851
  this.overlay = kind;
3587
3852
  this.menuCursor = 0;
@@ -3589,6 +3854,12 @@ class RoutingTablePanel implements OverlayComponent {
3589
3854
 
3590
3855
  private pickModel(option: string | undefined): void {
3591
3856
  if (option === undefined) return;
3857
+ if (this.pickingFallback) {
3858
+ const chain = [...this.chain(), { model: option }];
3859
+ if (this.saveChain(chain, `${this.rowLabel(this.target)}: fallback ${chain.length} is ${option}.`)) this.fallbackCursor = chain.length - 1;
3860
+ this.closeOverlay();
3861
+ return;
3862
+ }
3592
3863
  if (option === ROUTING_CUSTOM_MODEL) {
3593
3864
  this.finish({ type: "custom", target: this.target, config: cloneModelConfig(this.draft) });
3594
3865
  return;
@@ -3603,6 +3874,16 @@ class RoutingTablePanel implements OverlayComponent {
3603
3874
  const option = this.effortOptions()[index];
3604
3875
  if (option === undefined) return;
3605
3876
  const thinking = option === INHERIT_THINKING ? undefined : (option as ThinkingLevel);
3877
+ if (this.pickingFallback) {
3878
+ const chain = this.chain();
3879
+ const step = chain[this.fallbackCursor];
3880
+ if (step) {
3881
+ chain[this.fallbackCursor] = thinking ? { model: step.model, thinking } : { model: step.model };
3882
+ this.saveChain(chain, `${this.rowLabel(this.target)}: ${step.model} effort ${thinking ?? "inherit"}.`);
3883
+ }
3884
+ this.closeOverlay();
3885
+ return;
3886
+ }
3606
3887
  for (const key of this.targetKeys()) this.setThinking(key, thinking);
3607
3888
  this.say(`${this.rowLabel(this.target)}: effort ${thinking ?? "inherit"}. Save keeps it in ${this.profileName}.`);
3608
3889
  this.closeOverlay();
@@ -3618,6 +3899,7 @@ class RoutingTablePanel implements OverlayComponent {
3618
3899
  return;
3619
3900
  }
3620
3901
  const entry = { ...(this.draft[key] ?? {}) };
3902
+ if (model !== entry.model) delete entry.tier;
3621
3903
  if (model === undefined) delete entry.model;
3622
3904
  else entry.model = model;
3623
3905
  this.draft[key] = entry.model || entry.thinking ? entry : {};
@@ -3710,6 +3992,9 @@ class RoutingTablePanel implements OverlayComponent {
3710
3992
  case "switch":
3711
3993
  this.handleSwitchKey(data);
3712
3994
  return;
3995
+ case "fallbacks":
3996
+ this.handleFallbacksKey(data);
3997
+ return;
3713
3998
  default:
3714
3999
  this.handleTableKey(data);
3715
4000
  }
@@ -3738,6 +4023,9 @@ class RoutingTablePanel implements OverlayComponent {
3738
4023
  }
3739
4024
  if (matchesKey(data, "return")) return this.openModel(this.rows[this.cursor] ?? PROFILE_ORCHESTRATOR_KEY);
3740
4025
  if (matchesKey(data, "e")) return this.openEffort(this.rows[this.cursor] ?? PROFILE_ORCHESTRATOR_KEY);
4026
+ if (matchesKey(data, "f")) return this.openFallbacks(this.rows[this.cursor] ?? PROFILE_ORCHESTRATOR_KEY);
4027
+ if (matchesKey(data, "t")) return this.toggleTier(this.rows[this.cursor] ?? PROFILE_ORCHESTRATOR_KEY);
4028
+ if (matchesKey(data, "a")) return this.setAllFast();
3741
4029
  if (matchesKey(data, "s") || matchesKey(data, "ctrl+s")) return this.pressButton("save");
3742
4030
  if (matchesKey(data, "u")) return this.pressButton("use");
3743
4031
  if (matchesKey(data, "d")) return this.pressButton("default");
@@ -3856,6 +4144,7 @@ class RoutingTablePanel implements OverlayComponent {
3856
4144
  switch (action.kind) {
3857
4145
  case "row":
3858
4146
  case "effort":
4147
+ case "tier":
3859
4148
  return `row:${action.row}`;
3860
4149
  case "tab":
3861
4150
  return `tab:${action.name}`;
@@ -3890,6 +4179,13 @@ class RoutingTablePanel implements OverlayComponent {
3890
4179
  this.cursor = Math.max(0, this.rows.indexOf(action.row));
3891
4180
  this.openEffort(action.row);
3892
4181
  return;
4182
+ case "tier":
4183
+ this.cursor = Math.max(0, this.rows.indexOf(action.row));
4184
+ this.toggleTier(action.row);
4185
+ return;
4186
+ case "all-fast":
4187
+ this.setAllFast();
4188
+ return;
3893
4189
  case "model-option":
3894
4190
  this.pickModel(this.modelOptions()[action.index]);
3895
4191
  return;
@@ -3990,22 +4286,30 @@ class RoutingTablePanel implements OverlayComponent {
3990
4286
  const safe = truncateToWidth(sanitizeTerminalText(text), agentCol - 1, "…");
3991
4287
  return safe + " ".repeat(Math.max(0, agentCol - visibleWidth(safe)));
3992
4288
  };
3993
- const modelCol = Math.max(20, Math.min(40, inner - agentCol - 12));
4289
+ const tierRoom = Object.values(this.draft).some((entry) => entry.model && this.fastModels.has(entry.model)) ? 12 : 0;
4290
+ const modelCol = Math.max(20, Math.min(40, inner - agentCol - 12 - tierRoom));
3994
4291
  const effortStart = 2 + agentCol + modelCol;
3995
4292
  const row = (key: string, label: string, labelTone: PanelTone) => {
3996
4293
  const focused = this.rows[this.cursor] === key;
3997
4294
  const model = this.modelValue(key);
3998
4295
  const effort = this.effortValue(key);
4296
+ const tier = this.draft[key]?.model && this.fastModels.has(this.draft[key]!.model!) ? ` ${this.draft[key]?.tier === "fast" ? "Fast" : "Standard"} ▾` : "";
3999
4297
  const modelTone: PanelTone = this.isEdited(key, "model")
4000
4298
  ? "edited"
4001
4299
  : model === LEAVE_ORCHESTRATOR_UNTOUCHED || model === "inherit" || model === ROUTING_PI_DEFAULT ? "dim" : "text";
4002
4300
  const effortTone: PanelTone = this.isEdited(key, "thinking") ? "edited" : effort === "inherit" || effort === ROUTING_PI_DEFAULT ? "dim" : "status";
4003
- const plain = `${focused ? "▸ " : " "}${padLabel(label)}${truncateToWidth(model, modelCol - 1, "…").padEnd(modelCol)}${effort}`;
4301
+ const chain = this.fallbacks ? this.chain(key) : [];
4302
+ const room = inner - effortStart - visibleWidth(effort + tier) - 3;
4303
+ const fallback = chain.length && room > 4 ? truncateToWidth(`↪ ${sanitizeTerminalText(chain[0]!.model)}${chain.length > 1 ? ` +${chain.length - 1}` : ""}`, room, "…") : "";
4304
+ const plain = `${focused ? "▸ " : " "}${padLabel(label)}${truncateToWidth(model, modelCol - 1, "…").padEnd(modelCol)}${effort}${tier}${fallback ? ` ${fallback}` : ""}`;
4004
4305
  const styled =
4005
4306
  this.renderText(focused ? "▸ " : " ", "accent")
4006
4307
  + this.renderText(padLabel(label), labelTone)
4007
4308
  + this.renderText(truncateToWidth(model, modelCol - 1, "…").padEnd(modelCol), modelTone)
4008
- + this.renderText(effort, effortTone);
4309
+ + this.renderText(effort, effortTone)
4310
+ + this.renderText(tier, this.isEdited(key, "tier") ? "edited" : "status")
4311
+ + (fallback ? ` ${this.renderText(fallback, "dim")}` : "");
4312
+ if (tier) region({ kind: "tier", row: key }, effortStart + visibleWidth(effort), Math.min(inner, effortStart + visibleWidth(effort + tier)));
4009
4313
  if (effort) region({ kind: "effort", row: key }, effortStart, inner);
4010
4314
  region({ kind: "row", row: key }, 0, inner);
4011
4315
  lines.push(this.hoverWrap(`row:${key}`, styled, plain, inner));
@@ -4017,9 +4321,11 @@ class RoutingTablePanel implements OverlayComponent {
4017
4321
  // The header doubles as the "every agent" row: Model ▾ and Effort ▾.
4018
4322
  const headerFocused = this.rows[this.cursor] === ROUTING_ALL_ROW;
4019
4323
  const headerBase = `${headerFocused ? "▸ " : " "}${"Agent".padEnd(agentCol)}${"Model ▾".padEnd(modelCol)}Effort ▾`;
4020
- const headerNote = visibleWidth(`${headerBase} set every agent`) <= inner ? " set every agent" : "";
4021
- const headerPlain = `${headerBase}${headerNote}`;
4324
+ const allFast = tierRoom && visibleWidth(`${headerBase} All Fast`) <= inner ? " All Fast" : "";
4325
+ const headerNote = visibleWidth(`${headerBase}${allFast} set every agent`) <= inner ? " set every agent" : "";
4326
+ const headerPlain = `${headerBase}${allFast}${headerNote}`;
4022
4327
  region({ kind: "effort", row: ROUTING_ALL_ROW }, effortStart, effortStart + "Effort ▾".length);
4328
+ if (allFast) region({ kind: "all-fast" }, visibleWidth(headerBase), visibleWidth(headerBase + allFast));
4023
4329
  region({ kind: "row", row: ROUTING_ALL_ROW }, 0, inner);
4024
4330
  lines.push(
4025
4331
  this.hoverWrap(
@@ -4028,6 +4334,7 @@ class RoutingTablePanel implements OverlayComponent {
4028
4334
  + this.renderText("Agent".padEnd(agentCol), "muted")
4029
4335
  + this.renderText("Model ▾".padEnd(modelCol), "muted")
4030
4336
  + this.renderText("Effort ▾", "muted")
4337
+ + (allFast ? this.hoverWrap("all-fast", this.renderText(allFast, "accent"), allFast) : "")
4031
4338
  + this.renderText(headerNote, "dim"),
4032
4339
  headerPlain,
4033
4340
  inner,
@@ -4045,8 +4352,9 @@ class RoutingTablePanel implements OverlayComponent {
4045
4352
  const status = changes > 0 ? `● ${changes} unsaved` : "Saved";
4046
4353
  const buttonsWidth = (labels: (id: RoutingTableButton) => string) =>
4047
4354
  1 + (["use", "default", "save"] as const).reduce((sum, id) => sum + labels(id).length + 6, 0);
4048
- const fullLabel = (id: RoutingTableButton) => ROUTING_TABLE_BUTTONS[id];
4049
- const shortLabel = (id: RoutingTableButton) => ROUTING_TABLE_SHORT_BUTTONS[id] ?? ROUTING_TABLE_BUTTONS[id];
4355
+ const keyed = (id: RoutingTableButton, text: string) => `${id === "use" ? "u" : id === "default" ? "d" : "s"} · ${text}`;
4356
+ const fullLabel = (id: RoutingTableButton) => keyed(id, ROUTING_TABLE_BUTTONS[id]);
4357
+ const shortLabel = (id: RoutingTableButton) => keyed(id, ROUTING_TABLE_SHORT_BUTTONS[id] ?? ROUTING_TABLE_BUTTONS[id]);
4050
4358
  const label = buttonsWidth(fullLabel) + status.length + 1 <= inner ? fullLabel : shortLabel;
4051
4359
  let footer = "";
4052
4360
  let footerColumn = 0;
@@ -4197,6 +4505,8 @@ class RoutingTablePanel implements OverlayComponent {
4197
4505
  return this.menuCard(inner, this.activeTabColumn);
4198
4506
  case "new":
4199
4507
  return this.menuCard(inner, this.newColumn);
4508
+ case "fallbacks":
4509
+ return this.fallbacksCard(inner);
4200
4510
  default:
4201
4511
  return this.switchCard(inner);
4202
4512
  }
@@ -4430,7 +4740,9 @@ function renderRoutingTableForTesting(
4430
4740
  profileName?: string;
4431
4741
  feedback?: string;
4432
4742
  thinkingSupport?: Record<string, readonly ThinkingLevel[]>;
4743
+ fastModels?: string[];
4433
4744
  notices?: string[];
4745
+ fallbacks?: RoutingFallbacks;
4434
4746
  } = {},
4435
4747
  ): string[] {
4436
4748
  const panel = new RoutingTablePanel(
@@ -4492,8 +4804,11 @@ function routingScreenNotices(
4492
4804
  file: AgentProfilesFile,
4493
4805
  shownName: string,
4494
4806
  sessionBoundName: string | undefined,
4807
+ launchRouting?: AgentModelConfig,
4808
+ authorityAvailable = true,
4495
4809
  ): string[] {
4496
4810
  const notices: string[] = [];
4811
+ if (!authorityAvailable) notices.push("Session profile authority is unavailable; affected launches are blocked. Use in this session selects one.");
4497
4812
  const pins = evaluateProfilePin(readProfilePinStatus(ctx.cwd), file.profiles);
4498
4813
  for (const issue of pins.invalid) {
4499
4814
  notices.push(`The ${issue.source} pin file ${issue.path} is not a valid pin and is ignored. Fix or remove it.`);
@@ -4501,6 +4816,17 @@ function routingScreenNotices(
4501
4816
  for (const issue of pins.stale) {
4502
4817
  notices.push(`The ${issue.source} pin names "${issue.profile}", which no profile defines, so it is ignored (${issue.path}).`);
4503
4818
  }
4819
+ if (sessionBoundName !== undefined && !hasOwnProfile(file.profiles, sessionBoundName)) {
4820
+ notices.push(`This session launches with "${sessionBoundName}", which is no longer in profiles.json; its launches keep that routing.`);
4821
+ }
4822
+ // The table shows the saved profile; the session's launches keep the routing
4823
+ // they took at the freeze or the binding. Both sides compare role routes only.
4824
+ const roleRoutes = (config: unknown) => JSON.stringify(Object.entries(normalizeModelConfig(config) ?? {})
4825
+ .filter(([key]) => !isProfileOrchestratorKey(key)).sort(([a], [b]) => a.localeCompare(b)));
4826
+ if (shownName === sessionBoundName && launchRouting !== undefined && hasOwnProfile(file.profiles, shownName)
4827
+ && roleRoutes(file.profiles[shownName]) !== roleRoutes(launchRouting)) {
4828
+ notices.push(`Saved "${shownName}" differs from this session's launches; Use in this session adopts it.`);
4829
+ }
4504
4830
  const roots = {
4505
4831
  cwd: ctx.sessionManager?.getCwd?.() ?? ctx.cwd,
4506
4832
  home: homedir(),
@@ -4527,9 +4853,10 @@ function routingScreenNotices(
4527
4853
  if (entry.suggestion !== undefined) notices.push(`Profile key "${entry.key}" matches no agent configured in gentle-shell; did you mean ${entry.suggestion}?`);
4528
4854
  }
4529
4855
  // Issue #2400: model_profiles keys in subagents.json that match nothing and
4530
- // suggest nothing. A session binding or a winning pin replaces those launches'
4531
- // routing, so the file's keys do not apply there.
4532
- if (sessionBoundName === undefined && pinnedEffectiveModelConfig(ctx.cwd) === undefined) {
4856
+ // suggest nothing. When the session resolves a profile (its binding or the one
4857
+ // frozen at startup), that profile replaces those launches' routing, so the
4858
+ // file's keys do not apply there; a pin the session did not freeze does not.
4859
+ if (sessionBoundName === undefined) {
4533
4860
  const stray = unmatchedProfileKeys(loadAgentsConfig(roots).modelProfiles, discovered)
4534
4861
  .filter((entry) => entry.suggestion === undefined && !isProviderReviewRole(entry.key) && !profileKeys.includes(entry.key))
4535
4862
  .map((entry) => entry.key);
@@ -4546,6 +4873,10 @@ async function showRoutingTablePanel(
4546
4873
  ): Promise<RoutingTableResult> {
4547
4874
  const modelOptions = await getPiModelOptions(ctx);
4548
4875
  const thinkingSupport = await getPiThinkingSupport(ctx);
4876
+ let fastModels: string[] = [];
4877
+ try {
4878
+ fastModels = (await ctx.modelRegistry.getAvailable()).filter(supportsOpenAIFast).map((model) => `${model.provider}/${model.id}`);
4879
+ } catch { /* Unknown catalog entries do not claim Fast compatibility. */ }
4549
4880
  const agents = modelAssignmentNames(ctx.cwd);
4550
4881
  return ctx.ui.custom<RoutingTableResult>(
4551
4882
  (tui, theme, _keybindings, done) => {
@@ -4563,8 +4894,10 @@ async function showRoutingTablePanel(
4563
4894
  pinWinner: request.pinWinner,
4564
4895
  feedback: request.feedback,
4565
4896
  thinkingSupport,
4897
+ fastModels,
4566
4898
  notices: request.notices,
4567
4899
  switchProfile: request.switchProfile,
4900
+ fallbacks: fileRoutingFallbacks(gentleAiConfigHome()),
4568
4901
  },
4569
4902
  );
4570
4903
  const container = createNativeFullscreenInteraction({
@@ -4605,7 +4938,12 @@ async function openModelsScreen(ctx: ExtensionContext, live: LiveSession): Promi
4605
4938
  : read.status === "missing"
4606
4939
  ? ({ name: "current", source: "active" } as CurrentProfileTarget)
4607
4940
  : undefined;
4608
- await openProfilesPanelLoop(ctx, live, target?.name);
4941
+ // The screen opens on the profile this session launches with while the store
4942
+ // still has it (gentle-shell#1064 slice 3c).
4943
+ const authorityAvailable = sessionProfileAuthorityAvailable(ctx);
4944
+ const launchName = sessionLaunchProfile(ctx, authorityAvailable)?.name;
4945
+ const opensOnLaunch = read.status === "valid" && launchName !== undefined && hasOwnProfile(read.file.profiles, launchName);
4946
+ await openProfilesPanelLoop(ctx, live, opensOnLaunch ? launchName : target?.name, authorityAvailable);
4609
4947
  }
4610
4948
 
4611
4949
  /** `/gentle:profiles export-routing`: write the saved global routing to models.export.json. */
@@ -4844,7 +5182,7 @@ function reportProfilesDrops(ctx: ExtensionContext, path: string, drops: Profile
4844
5182
  }
4845
5183
 
4846
5184
  /** Pi's own live-session controls: the ExtensionAPI's setModel/setThinkingLevel. */
4847
- type LiveSession = Pick<ExtensionAPI, "setModel" | "setThinkingLevel" | "getThinkingLevel">;
5185
+ type LiveSession = Pick<ExtensionAPI, "setModel" | "setThinkingLevel" | "getThinkingLevel"> & Partial<Pick<ExtensionAPI, "events">>;
4848
5186
 
4849
5187
  /**
4850
5188
  * Switch the running session to the profile's orchestrator. `settings.json`
@@ -4854,7 +5192,7 @@ type LiveSession = Pick<ExtensionAPI, "setModel" | "setThinkingLevel" | "getThin
4854
5192
  * keep the current live model and report what happened; callers retain their
4855
5193
  * routing snapshot or persisted default independently.
4856
5194
  */
4857
- async function switchLiveOrchestrator(ctx: ExtensionContext, live: LiveSession, entry: AgentRoutingEntry): Promise<string> {
5195
+ async function switchLiveOrchestrator(ctx: ExtensionContext, live: LiveSession, entry: AgentRoutingEntry, current: () => boolean = () => true, onSuccess?: () => void): Promise<string> {
4858
5196
  const reference = parseOrchestratorModelRef(entry.model);
4859
5197
  if (reference === undefined) return "";
4860
5198
  const label = `${reference.provider}/${reference.model}`;
@@ -4874,6 +5212,9 @@ async function switchLiveOrchestrator(ctx: ExtensionContext, live: LiveSession,
4874
5212
  return `\nThis session could not switch to ${label}: ${sanitizeTerminalText(error instanceof Error ? error.message : String(error))}.`;
4875
5213
  }
4876
5214
  if (!switched) return `\nno authentication is configured for ${reference.provider}; this session keeps its current model.`;
5215
+ if (!current()) return "";
5216
+ onSuccess?.();
5217
+ live.events?.emit(PROFILE_TIER_EVENT, { sessionId: ctx.sessionManager?.getSessionId?.(), tier: supportsOpenAIFast(model) ? entry.tier : undefined, model: `${model.provider}/${model.id}` });
4877
5218
  if (entry.thinking === undefined) return `\nThis session now runs on ${label}.`;
4878
5219
  try {
4879
5220
  live.setThinkingLevel(entry.thinking);
@@ -4931,9 +5272,10 @@ async function runProfilesPanelAction(
4931
5272
  switch (result.type) {
4932
5273
  case "use-session": {
4933
5274
  if (!hasOwnProfile(file.profiles, result.name)) return file;
4934
- // Use in this session binds a complete routing snapshot to this parent
4935
- // session and switches only its live orchestrator. No shared defaults,
4936
- // materialized stores, agent frontmatter, pins, or declarations are written.
5275
+ // Enter persists a complete routing snapshot for this parent session,
5276
+ // publishes only the returned state, then switches its live orchestrator.
5277
+ // No shared defaults, materialized stores, agent frontmatter, pins, or
5278
+ // declarations are written.
4937
5279
  const sessionId = ctx.sessionManager?.getSessionId?.();
4938
5280
  if (typeof sessionId !== "string" || sessionId.length === 0) {
4939
5281
  report.status = `This Pi session has no id to bind "${result.name}" to. Use Make default instead.`;
@@ -4943,19 +5285,61 @@ async function runProfilesPanelAction(
4943
5285
  );
4944
5286
  return file;
4945
5287
  }
4946
- const snapshot = normalizeModelConfig(result.config ?? file.profiles[result.name]) ?? {};
4947
- bindSessionProfile(sessionId, result.name, snapshot);
4948
- const orchestrator = readProfileOrchestrator(snapshot);
4949
- const liveNote = orchestrator === undefined ? "" : await switchLiveOrchestrator(ctx, live, orchestrator);
4950
- report.status = `This session now uses "${result.name}". Nothing shared was written.${liveNote.replace(/\n/g, " ")}`;
4951
- ctx.ui.notify(
4952
- `el Gentleman bound profile "${result.name}" to this session — its tab shows ◉. Subagents and reviewers use this session's routing snapshot. Shared defaults were not written: the global routing, pins, and materialized stores are untouched. Make default writes them.${liveNote}`,
4953
- "info",
4954
- );
5288
+ const selected = await runCurrentSessionProfileSelection(ctx.sessionManager, async (attachment, owned) => {
5289
+ const startup = knownSessionProfileStartup(attachment.refresh().state, sessionId);
5290
+ const outcome = attachment.bind(result.name, normalizeModelConfig(result.config ?? file.profiles[result.name]) ?? {}, startup);
5291
+ if (!owned()) return false;
5292
+ const authority = publishSessionProfileOutcome(ctx.sessionManager, outcome);
5293
+ if ((outcome.status !== "persisted" && outcome.status !== "not-persisted") || outcome.state.status !== "bound" || !authority.available) {
5294
+ const kept = authority.available ? "The last disk-corroborated state was preserved." : "Session profile authority is unavailable; affected launches are blocked.";
5295
+ report.status = `"${result.name}" was not bound to this session. ${kept}`;
5296
+ ctx.ui.notify(
5297
+ `el Gentleman could not bind profile "${result.name}". ${kept} No live model or thinking change was applied.`,
5298
+ "warning",
5299
+ );
5300
+ return false;
5301
+ }
5302
+ const snapshot = outcome.state.binding;
5303
+ // The live switch applies only while this exact snapshot is still current.
5304
+ const current = () => {
5305
+ if (!owned()) return false;
5306
+ const state = readCurrentSessionProfileOutcome(ctx.sessionManager)?.state;
5307
+ return state?.status === "bound" && isDeepStrictEqual(state.binding, snapshot);
5308
+ };
5309
+ const orchestrator = readProfileOrchestrator(snapshot.modelProfiles);
5310
+ const liveNote = orchestrator === undefined ? "" : await switchLiveOrchestrator(ctx, {
5311
+ setModel: (model) => current() ? live.setModel(model) : Promise.resolve(false),
5312
+ setThinkingLevel: (level) => { if (current()) live.setThinkingLevel(level); },
5313
+ getThinkingLevel: () => live.getThinkingLevel(),
5314
+ events: live.events,
5315
+ }, orchestrator, current);
5316
+ if (orchestrator?.model === undefined && current()) live.events?.emit(PROFILE_TIER_EVENT, { sessionId, tier: undefined });
5317
+ if (current()) {
5318
+ const persistence = outcome.status === "persisted" ? "persisted in this session" : "not yet persisted; active only until detach or disk corroboration";
5319
+ report.status = `This session now uses "${snapshot.name}" (${persistence}). Nothing shared was written.${liveNote.replace(/\n/g, " ")}`;
5320
+ ctx.ui.notify(
5321
+ `el Gentleman bound profile "${snapshot.name}" to this session — its tab shows ◉; ${persistence}. Subagents and reviewers use this session's routing snapshot. Shared defaults were not written: the global routing, pins, and materialized stores are untouched. Make default writes them.${liveNote}`,
5322
+ "info",
5323
+ );
5324
+ }
5325
+ return true;
5326
+ });
5327
+ // A selection skipped by a reload or session replacement leaves a stale
5328
+ // ctx; only a still-active command reports the missing attachment.
5329
+ if (selected === undefined && isCommandContextActive(ctx)) {
5330
+ report.status = `"${result.name}" was not bound: this session's attachment is unavailable.`;
5331
+ ctx.ui.notify(
5332
+ `el Gentleman cannot bind profile "${result.name}": the current session attachment is unavailable. No profile or live model change was applied.`,
5333
+ "warning",
5334
+ );
5335
+ }
4955
5336
  return file;
4956
5337
  }
4957
5338
  case "apply-global": {
4958
5339
  if (!hasOwnProfile(file.profiles, result.name)) return file;
5340
+ const manager = ctx.sessionManager;
5341
+ const sessionId = manager?.getSessionId?.();
5342
+ const current = () => isCommandContextActive(ctx) && ctx.sessionManager === manager && manager?.getSessionId?.() === sessionId;
4959
5343
  // A pinned repository resolves its subagent routing from the profile at launch,
4960
5344
  // so a global apply would move global state this repository never reads. When a
4961
5345
  // pin wins, applying is repo-scoped: re-pin this clone and write no global
@@ -5017,7 +5401,7 @@ async function runProfilesPanelAction(
5017
5401
  clearedRoutes.push(`${name}: ${formatOrchestratorSelection(from)} → inherit (cleared)`);
5018
5402
  } else if (from === undefined) {
5019
5403
  addedRoutes.push(`${name}: ${formatOrchestratorSelection(to)} (added)`);
5020
- } else if (from.model !== to.model || from.thinking !== to.thinking) {
5404
+ } else if (from.model !== to.model || from.thinking !== to.thinking || from.tier !== to.tier) {
5021
5405
  replacedRoutes.push(`${name}: ${formatOrchestratorSelection(from)} → ${formatOrchestratorSelection(to)}`);
5022
5406
  }
5023
5407
  }
@@ -5080,6 +5464,7 @@ async function runProfilesPanelAction(
5080
5464
  return current.status === "valid" && current.entry !== undefined
5081
5465
  && current.entry.model === orchestratorEntry.model
5082
5466
  && current.entry.thinking === orchestratorEntry.thinking
5467
+ && (savedRouting.status === "valid" ? savedRouting.config[PROFILE_ORCHESTRATOR_KEY]?.tier : undefined) === orchestratorEntry.tier
5083
5468
  && liveOrchestrator !== undefined
5084
5469
  && liveOrchestrator.model === orchestratorEntry.model
5085
5470
  && liveOrchestrator.thinking === orchestratorEntry.thinking;
@@ -5215,7 +5600,16 @@ async function runProfilesPanelAction(
5215
5600
  // settings.json only governs future sessions. The session the user is
5216
5601
  // sitting in keeps its model until told otherwise, which made a profile
5217
5602
  // look applied while the orchestrator kept answering with the old one.
5218
- orchestratorNote += await switchLiveOrchestrator(ctx, live, orchestratorEntry);
5603
+ if (current()) {
5604
+ if (orchestratorEntry.model) orchestratorNote += await switchLiveOrchestrator(ctx, live, orchestratorEntry, current, () => setFrozenDefaultOrchestrator(sessionId, orchestratorEntry));
5605
+ else {
5606
+ setFrozenDefaultOrchestrator(sessionId, undefined);
5607
+ live.events?.emit(PROFILE_TIER_EVENT, { sessionId, tier: undefined });
5608
+ }
5609
+ }
5610
+ } else if (current()) {
5611
+ setFrozenDefaultOrchestrator(sessionId, undefined);
5612
+ live.events?.emit(PROFILE_TIER_EVENT, { sessionId, tier: undefined });
5219
5613
  }
5220
5614
  // A pin that does not resolve changes nothing at launch, so the global apply
5221
5615
  // above is what governs this repository. Saying so keeps a broken pin from
@@ -5293,6 +5687,7 @@ async function runProfilesPanelAction(
5293
5687
  try {
5294
5688
  const next = renameProfile(file, result.name, name);
5295
5689
  writeProfilesFileSync(path, next);
5690
+ followProfileFallbacks(path, result.name, name);
5296
5691
  // A pin stores a name, so a rename that did not follow it would leave every
5297
5692
  // pinned repository with a name the store no longer defines, which silently
5298
5693
  // returns those repositories to the global routing.
@@ -5345,6 +5740,7 @@ async function runProfilesPanelAction(
5345
5740
  try {
5346
5741
  const next = deleteProfile(file, result.name);
5347
5742
  writeProfilesFileSync(path, next);
5743
+ followProfileFallbacks(path, result.name, undefined);
5348
5744
  return next;
5349
5745
  } catch (error) {
5350
5746
  ctx.ui.notify(`Profile not deleted: ${profilesErrorMessage(error)}`, "warning");
@@ -5475,11 +5871,12 @@ async function runProfilesPanelAction(
5475
5871
  }
5476
5872
 
5477
5873
  /** `/gentle:profiles`: seed or open the store, then loop the panel over one action at a time until it closes. */
5478
- const PROFILES_COMMAND_USAGE = "Usage: /gentle:profiles [export <name> | import | publish <name> | export-routing | restore-routing]";
5874
+ const PROFILES_COMMAND_USAGE = "Usage: /gentle:profiles [export <name> | import | publish <name> | export-routing | restore-routing | clear]";
5479
5875
 
5480
5876
  /**
5481
5877
  * `/gentle:profiles` opens the models screen. File operations live in
5482
- * subcommands rather than on the screen: `export <name>` and `import` move a
5878
+ * subcommands rather than on the screen: `clear` ends this session's profile
5879
+ * selection, `export <name>` and `import` move a
5483
5880
  * profile through `profiles.export.json`, `publish <name>` toggles the
5484
5881
  * committed repository declaration, and `export-routing` / `restore-routing`
5485
5882
  * move the saved global routing (models.json, not a profile) through
@@ -5492,13 +5889,14 @@ async function handleProfilesCommand(ctx: ExtensionContext, live: LiveSession, a
5492
5889
  await openModelsScreen(ctx, live);
5493
5890
  return;
5494
5891
  }
5495
- if (verb === "export-routing" || verb === "restore-routing") {
5892
+ if (verb === "export-routing" || verb === "restore-routing" || verb === "clear") {
5496
5893
  if (rest.length > 0) {
5497
5894
  ctx.ui.notify(PROFILES_COMMAND_USAGE, "warning");
5498
5895
  return;
5499
5896
  }
5500
5897
  if (verb === "export-routing") await exportRoutingCommand(ctx);
5501
- else await restoreModelExport(ctx);
5898
+ else if (verb === "restore-routing") await restoreModelExport(ctx);
5899
+ else await handleProfilesClear(ctx);
5502
5900
  return;
5503
5901
  }
5504
5902
  const store = await loadProfilesStore(ctx);
@@ -5569,18 +5967,20 @@ async function openProfilesPanelLoop(
5569
5967
  ctx: ExtensionContext,
5570
5968
  live: LiveSession,
5571
5969
  initialSelectedName?: string,
5970
+ openingAuthority?: boolean,
5572
5971
  ): Promise<void> {
5573
5972
  const store = await loadProfilesStore(ctx);
5574
5973
  if (!store) return;
5575
5974
  const { path } = store;
5576
5975
  let file = store.file;
5577
- const sessionBoundName = () => readSessionProfileBinding(ctx.sessionManager?.getSessionId?.())?.name;
5578
5976
  const pinWinner = () => evaluateProfilePin(readProfilePinStatus(ctx.cwd), file.profiles).winner?.profile;
5579
5977
  let selectedName = initialSelectedName
5580
5978
  ?? resolveCurrentProfileTarget(ctx.cwd, { status: "valid", file, drops: { droppedProfiles: [], droppedAgents: [], droppedActive: undefined } })?.name
5581
5979
  ?? Object.keys(file.profiles)[0];
5582
5980
  let feedback: string | undefined;
5583
5981
  let draftOverride: AgentModelConfig | undefined;
5982
+ // Read once per visit: the opening read serves the first one.
5983
+ let authorityAvailable = true;
5584
5984
  const writeDraft = (name: string, config: AgentModelConfig): boolean => {
5585
5985
  try {
5586
5986
  const next = hasOwnProfile(file.profiles, name)
@@ -5602,156 +6002,314 @@ async function openProfilesPanelLoop(
5602
6002
  return { error };
5603
6003
  }
5604
6004
  selectedName = name;
5605
- const boundName = sessionBoundName();
6005
+ // The profile this session launches with, bound or frozen: the tab marked ◉.
6006
+ const launch = sessionLaunchProfile(ctx, authorityAvailable);
5606
6007
  return {
5607
6008
  file,
5608
- sessionBoundName: boundName,
6009
+ sessionBoundName: launch?.name,
5609
6010
  pinWinner: pinWinner(),
5610
- notices: routingScreenNotices(ctx, file, name, boundName),
6011
+ notices: routingScreenNotices(ctx, file, name, launch?.name, launch?.modelProfiles, authorityAvailable),
5611
6012
  feedback: `${saveFirst ? `Saved "${previous}". ` : ""}Showing "${name}".`,
5612
6013
  };
5613
6014
  };
5614
6015
  const differsFromStore = (name: string, config: AgentModelConfig) =>
5615
6016
  JSON.stringify(normalizeModelConfig(config) ?? {}) !== JSON.stringify(normalizeModelConfig(file.profiles[name]) ?? {});
5616
- while (true) {
5617
- if (selectedName === undefined || !hasOwnProfile(file.profiles, selectedName)) {
5618
- selectedName = Object.keys(file.profiles)[0];
5619
- draftOverride = undefined;
5620
- }
5621
- if (selectedName === undefined) {
5622
- ctx.ui.notify("el Gentleman has no profiles left. Run /gentle:profiles again to seed one from the routing in effect.", "info");
5623
- return;
5624
- }
5625
- const stored = cloneModelConfig(normalizeModelConfig(file.profiles[selectedName]) ?? {});
5626
- const boundName = sessionBoundName();
5627
- const result = await showRoutingTablePanel(ctx, {
5628
- name: selectedName,
5629
- config: draftOverride ?? stored,
5630
- file,
5631
- sessionBoundName: boundName,
5632
- pinWinner: pinWinner(),
5633
- feedback,
5634
- notices: routingScreenNotices(ctx, file, selectedName, boundName),
5635
- switchProfile,
5636
- });
5637
- draftOverride = undefined;
5638
- feedback = undefined;
5639
- const previous = selectedName;
5640
- if (result.saveFirst && !writeDraft(previous, result.saveFirst)) {
5641
- draftOverride = result.saveFirst;
5642
- continue;
6017
+ // Pi's runner invalidates this command ctx in a microtask when a reload or
6018
+ // session replacement lands, possibly while a panel or input step is still in
6019
+ // flight. Every step therefore re-checks the ctx when it settles (or throws),
6020
+ // and a stale ctx closes the loop quietly instead of touching ctx.cwd again.
6021
+ const stale = Symbol("stale-profiles-ctx");
6022
+ const step = async <T>(run: () => Promise<T>): Promise<T> => {
6023
+ let value: T;
6024
+ try {
6025
+ value = await run();
6026
+ } catch (error) {
6027
+ if (!isCommandContextActive(ctx)) throw stale;
6028
+ throw error;
5643
6029
  }
5644
- const savedNote = result.saveFirst ? `Saved "${previous}". ` : "";
5645
- switch (result.type) {
5646
- case "close":
6030
+ if (!isCommandContextActive(ctx)) throw stale;
6031
+ return value;
6032
+ };
6033
+ try {
6034
+ await runProfilesPanelSteps();
6035
+ } catch (error) {
6036
+ if (error !== stale) throw error;
6037
+ }
6038
+ async function runProfilesPanelSteps(): Promise<void> {
6039
+ while (true) {
6040
+ if (!isCommandContextActive(ctx)) return;
6041
+ if (selectedName === undefined || !hasOwnProfile(file.profiles, selectedName)) {
6042
+ selectedName = Object.keys(file.profiles)[0];
6043
+ draftOverride = undefined;
6044
+ }
6045
+ if (selectedName === undefined) {
6046
+ ctx.ui.notify("el Gentleman has no profiles left. Run /gentle:profiles again to seed one from the routing in effect.", "info");
5647
6047
  return;
5648
- case "load":
5649
- selectedName = result.name;
5650
- feedback = `${savedNote}Showing "${result.name}".`;
6048
+ }
6049
+ const shown = selectedName;
6050
+ const stored = cloneModelConfig(normalizeModelConfig(file.profiles[shown]) ?? {});
6051
+ authorityAvailable = openingAuthority ?? sessionProfileAuthorityAvailable(ctx);
6052
+ openingAuthority = undefined;
6053
+ const launch = sessionLaunchProfile(ctx, authorityAvailable);
6054
+ const result = await step(() => showRoutingTablePanel(ctx, {
6055
+ name: shown,
6056
+ config: draftOverride ?? stored,
6057
+ file,
6058
+ sessionBoundName: launch?.name,
6059
+ pinWinner: pinWinner(),
6060
+ feedback,
6061
+ notices: routingScreenNotices(ctx, file, shown, launch?.name, launch?.modelProfiles, authorityAvailable),
6062
+ switchProfile,
6063
+ }));
6064
+ draftOverride = undefined;
6065
+ feedback = undefined;
6066
+ const previous = selectedName;
6067
+ if (result.saveFirst && !writeDraft(previous, result.saveFirst)) {
6068
+ draftOverride = result.saveFirst;
5651
6069
  continue;
5652
- case "custom": {
5653
- const label = result.target === PROFILE_ORCHESTRATOR_KEY
5654
- ? "the orchestrator"
5655
- : result.target === ROUTING_ALL_ROW ? "every agent" : sanitizeTerminalText(result.target);
5656
- const answer = await ctx.ui.input(`Custom model id for ${label}`, "provider/model");
5657
- draftOverride = cloneModelConfig(result.config);
5658
- if (answer === undefined || answer.trim() === "") {
5659
- feedback = "No custom model set.";
6070
+ }
6071
+ const savedNote = result.saveFirst ? `Saved "${previous}". ` : "";
6072
+ switch (result.type) {
6073
+ case "close":
6074
+ return;
6075
+ case "load":
6076
+ selectedName = result.name;
6077
+ feedback = `${savedNote}Showing "${result.name}".`;
5660
6078
  continue;
5661
- }
5662
- const model = normalizeModelId(answer.trim());
5663
- if (!model) {
5664
- feedback = "Custom model id must be one provider/model line using letters, numbers, '.', '-', '_', '~', ':', '@', '/', '+', '%' only.";
6079
+ case "custom": {
6080
+ const label = result.target === PROFILE_ORCHESTRATOR_KEY
6081
+ ? "the orchestrator"
6082
+ : result.target === ROUTING_ALL_ROW ? "every agent" : sanitizeTerminalText(result.target);
6083
+ const answer = await step(() => ctx.ui.input(`Custom model id for ${label}`, "provider/model"));
6084
+ draftOverride = cloneModelConfig(result.config);
6085
+ if (answer === undefined || answer.trim() === "") {
6086
+ feedback = "No custom model set.";
6087
+ continue;
6088
+ }
6089
+ const model = normalizeModelId(answer.trim());
6090
+ if (!model) {
6091
+ feedback = "Custom model id must be one provider/model line using letters, numbers, '.', '-', '_', '~', ':', '@', '/', '+', '%' only.";
6092
+ continue;
6093
+ }
6094
+ const keys = result.target === ROUTING_ALL_ROW ? modelAssignmentNames(ctx.cwd) : [result.target];
6095
+ for (const key of keys) draftOverride[key] = { ...(draftOverride[key] ?? {}), model };
6096
+ feedback = `${label}: model ${model}. Save keeps it in "${previous}".`;
5665
6097
  continue;
5666
6098
  }
5667
- const keys = result.target === ROUTING_ALL_ROW ? modelAssignmentNames(ctx.cwd) : [result.target];
5668
- for (const key of keys) draftOverride[key] = { ...(draftOverride[key] ?? {}), model };
5669
- feedback = `${label}: model ${model}. Save keeps it in "${previous}".`;
5670
- continue;
5671
- }
5672
- case "save":
5673
- if (writeDraft(previous, result.config)) feedback = `Saved "${previous}".`;
5674
- else draftOverride = result.config;
5675
- continue;
5676
- case "use-session": {
5677
- // What you see is what the session uses: edits are saved first.
5678
- // A tab switch may have changed the shown profile since this visit opened.
5679
- const config = result.config ?? cloneModelConfig(normalizeModelConfig(file.profiles[previous]) ?? {});
5680
- const saved = differsFromStore(previous, config);
5681
- if (saved && !writeDraft(previous, config)) {
5682
- draftOverride = config;
6099
+ case "save":
6100
+ if (writeDraft(previous, result.config)) feedback = `Saved "${previous}".`;
6101
+ else draftOverride = result.config;
5683
6102
  continue;
5684
- }
5685
- const report: ProfilesPanelReport = {};
5686
- file = await runProfilesPanelAction(ctx, live, path, file, { type: "use-session", name: previous, config }, report);
5687
- feedback = `${saved ? `Saved "${previous}". ` : ""}${report.status ?? ""}`.trim() || undefined;
5688
- continue;
5689
- }
5690
- case "apply-global": {
5691
- // Make default saves what you see, then runs the guarded global
5692
- // apply with its diff confirmation, pin honesty, and rollback.
5693
- const saved = differsFromStore(previous, result.config);
5694
- if (saved && !writeDraft(previous, result.config)) {
5695
- draftOverride = result.config;
6103
+ case "use-session": {
6104
+ // What you see is what the session uses: edits are saved first.
6105
+ // A tab switch may have changed the shown profile since this visit opened.
6106
+ const config = result.config ?? cloneModelConfig(normalizeModelConfig(file.profiles[previous]) ?? {});
6107
+ const saved = differsFromStore(previous, config);
6108
+ if (saved && !writeDraft(previous, config)) {
6109
+ draftOverride = config;
6110
+ continue;
6111
+ }
6112
+ const report: ProfilesPanelReport = {};
6113
+ file = await step(() => runProfilesPanelAction(ctx, live, path, file, { type: "use-session", name: previous, config }, report));
6114
+ feedback = `${saved ? `Saved "${previous}". ` : ""}${report.status ?? ""}`.trim() || undefined;
5696
6115
  continue;
5697
6116
  }
5698
- file = await runProfilesPanelAction(ctx, live, path, file, { type: "apply-global", name: previous, config: cloneModelConfig(result.config) });
5699
- const prefix = saved ? `Saved "${previous}". ` : "";
5700
- feedback = file.active === previous
5701
- ? `${prefix}"${previous}" is the default for new sessions.`
5702
- : pinWinner() === previous
5703
- ? `${prefix}This repo pins its profile, so "${previous}" now applies to this repo only.`
5704
- : `${prefix}"${previous}" was not made the default.`;
5705
- continue;
5706
- }
5707
- case "create-live": {
5708
- const answer = await ctx.ui.input("Name for a profile of what's running now", "e.g. snapshot");
5709
- const name = answer?.trim() ?? "";
5710
- if (name === "") {
5711
- feedback = `${savedNote}No profile created.`;
6117
+ case "apply-global": {
6118
+ // Make default saves what you see, then runs the guarded global
6119
+ // apply with its diff confirmation, pin honesty, and rollback.
6120
+ const saved = differsFromStore(previous, result.config);
6121
+ if (saved && !writeDraft(previous, result.config)) {
6122
+ draftOverride = result.config;
6123
+ continue;
6124
+ }
6125
+ file = await step(() => runProfilesPanelAction(ctx, live, path, file, { type: "apply-global", name: previous, config: cloneModelConfig(result.config) }));
6126
+ const prefix = saved ? `Saved "${previous}". ` : "";
6127
+ feedback = file.active === previous
6128
+ ? `${prefix}"${previous}" is the default for new sessions.`
6129
+ : pinWinner() === previous
6130
+ ? `${prefix}This repo pins its profile, so "${previous}" now applies to this repo only.`
6131
+ : `${prefix}"${previous}" was not made the default.`;
5712
6132
  continue;
5713
6133
  }
5714
- // Captures the routing this session's launches resolve and the
5715
- // orchestrator it actually runs, the way the old snapshot did.
5716
- const snapshot = profileSnapshotFrom(
5717
- readSessionProfileBinding(ctx.sessionManager?.getSessionId?.())?.modelProfiles
5718
- ?? await readEffectiveModelConfigAsync(ctx.cwd),
5719
- liveOrchestratorSnapshot(ctx, live) ?? readOrchestratorSettings(orchestratorSettingsPath()),
5720
- );
5721
- try {
5722
- const next = createProfile(file, name, snapshot);
5723
- writeProfilesFileSync(path, next);
5724
- file = next;
5725
- selectedName = name;
5726
- feedback = `${savedNote}Created "${name}" from what's running now.`;
5727
- } catch (error) {
5728
- feedback = `${savedNote}Profile not created: ${profilesErrorMessage(error)}`;
5729
- }
5730
- continue;
5731
- }
5732
- default: {
5733
- const report: ProfilesPanelReport = {};
5734
- file = await runProfilesPanelAction(ctx, live, path, file, result, report);
5735
- selectedName = report.selectedName ?? selectedName;
5736
- if (result.type === "delete" && !hasOwnProfile(file.profiles, previous)) {
5737
- feedback = `Deleted "${previous}".`;
5738
- } else if (result.type === "pin") {
5739
- feedback = report.status ?? (pinWinner() === previous
5740
- ? `"${previous}" is used in this repo.`
5741
- : `"${previous}" is no longer pinned to this repo.`);
5742
- } else {
5743
- feedback = report.status ? `${savedNote}${report.status}` : savedNote || undefined;
6134
+ case "create-live": {
6135
+ if (!authorityAvailable) {
6136
+ feedback = `${savedNote}Session profile authority is unavailable; affected launches are blocked. No profile created.`;
6137
+ continue;
6138
+ }
6139
+ const answer = await step(() => ctx.ui.input("Name for a profile of what's running now", "e.g. snapshot"));
6140
+ const name = answer?.trim() ?? "";
6141
+ if (name === "") {
6142
+ feedback = `${savedNote}No profile created.`;
6143
+ continue;
6144
+ }
6145
+ // Captures the routing this session's launches resolve and the
6146
+ // orchestrator it actually runs, the way the old snapshot did.
6147
+ const snapshot = profileSnapshotFrom(
6148
+ await step(() => readSessionLaunchModelConfigAsync(ctx, authorityAvailable)),
6149
+ liveOrchestratorSnapshot(ctx, live) ?? readOrchestratorSettings(orchestratorSettingsPath()),
6150
+ );
6151
+ try {
6152
+ const next = createProfile(file, name, snapshot);
6153
+ writeProfilesFileSync(path, next);
6154
+ file = next;
6155
+ selectedName = name;
6156
+ feedback = `${savedNote}Created "${name}" from what's running now.`;
6157
+ } catch (error) {
6158
+ feedback = `${savedNote}Profile not created: ${profilesErrorMessage(error)}`;
6159
+ }
6160
+ continue;
5744
6161
  }
5745
- // Rename, pin, and a declined delete keep the profile on screen; carry
5746
- // unsaved edits across them instead of reloading from the store.
5747
- if (result.draft && hasOwnProfile(file.profiles, selectedName) && (selectedName === previous || result.type === "rename")) {
5748
- draftOverride = result.draft;
6162
+ default: {
6163
+ const report: ProfilesPanelReport = {};
6164
+ file = await step(() => runProfilesPanelAction(ctx, live, path, file, result, report));
6165
+ selectedName = report.selectedName ?? selectedName;
6166
+ if (result.type === "delete" && !hasOwnProfile(file.profiles, previous)) {
6167
+ feedback = `Deleted "${previous}".`;
6168
+ } else if (result.type === "pin") {
6169
+ feedback = report.status ?? (pinWinner() === previous
6170
+ ? `"${previous}" is used in this repo.`
6171
+ : `"${previous}" is no longer pinned to this repo.`);
6172
+ } else {
6173
+ feedback = report.status ? `${savedNote}${report.status}` : savedNote || undefined;
6174
+ }
6175
+ // Rename, pin, and a declined delete keep the profile on screen; carry
6176
+ // unsaved edits across them instead of reloading from the store.
6177
+ if (result.draft && hasOwnProfile(file.profiles, selectedName) && (selectedName === previous || result.type === "rename")) {
6178
+ draftOverride = result.draft;
6179
+ }
5749
6180
  }
5750
6181
  }
5751
6182
  }
5752
6183
  }
5753
6184
  }
5754
6185
 
6186
+ /**
6187
+ * The startup state this session knows (gentle-shell#2742, section 3): the one
6188
+ * the newest corroborated record carries, else the profile this process froze
6189
+ * at the session's own start. Follow mode has none.
6190
+ */
6191
+ function knownSessionProfileStartup(state: SessionProfileAppendOutcome["state"], sessionId: string): SessionProfileStartupState | undefined {
6192
+ if (profileFollowEnabled()) return undefined;
6193
+ if (state.status === "bound") {
6194
+ const { origin, name, modelProfiles, startup } = state.binding;
6195
+ if (origin !== "user") return { origin, name, modelProfiles };
6196
+ if (startup !== undefined) return startup;
6197
+ } else if (state.status === "cleared" && state.startup === "none") return "none";
6198
+ return readSessionProfileOwnStartup(sessionId);
6199
+ }
6200
+
6201
+ /** Where a clear goes back to, named with the status label convention. */
6202
+ function startupStateText(startup: SessionProfileStartupState): string {
6203
+ return startup === "none" ? "no profile, as this session started" : `the profile this session started with, "${sessionProfileLabel({ kind: "inherited", profile: startup })}", and use it`;
6204
+ }
6205
+
6206
+ /**
6207
+ * `/gentle:profiles clear`: go back to the startup state when it is known
6208
+ * (gentle-shell#2742, section 3), else append a legacy clear record, and publish
6209
+ * only the returned state. Never-bound, already-cleared and startup sessions
6210
+ * write nothing; an unreadable record is the recovery case and is replaced.
6211
+ * Follow mode has no startup state, so a startup record gets a legacy clear
6212
+ * (section 6). The live orchestrator and every shared default stay untouched.
6213
+ */
6214
+ async function handleProfilesClear(ctx: ExtensionContext): Promise<void> {
6215
+ const sessionId = ctx.sessionManager?.getSessionId?.();
6216
+ if (typeof sessionId !== "string" || sessionId.length === 0) {
6217
+ ctx.ui.notify("el Gentleman cannot clear the session profile: no parent session id is available here.", "warning");
6218
+ return;
6219
+ }
6220
+ const selected = await runCurrentSessionProfileSelection(ctx.sessionManager, async (attachment, owned) => {
6221
+ const prior = attachment.refresh().state;
6222
+ // An unsaved or in-memory branch reads as indeterminate; without any profile
6223
+ // record on the branch it was never selected, so nothing is written.
6224
+ const selectedBefore = ctx.sessionManager.getBranch().some((entry) => isSessionProfileFamilyEntry(entry));
6225
+ if (prior.status === "absent" || (prior.status === "indeterminate" && !selectedBefore)) {
6226
+ ctx.ui.notify("el Gentleman: no session profile was ever selected in this session; nothing to clear.", "info");
6227
+ return true;
6228
+ }
6229
+ const startupOrigin = prior.status === "bound" && prior.binding.origin !== "user" ? prior.binding.origin : undefined;
6230
+ if (!profileFollowEnabled() && (startupOrigin !== undefined || (prior.status === "cleared" && prior.startup === "none"))) {
6231
+ const label = prior.status === "bound" && startupOrigin ? sessionProfileLabel({ kind: "inherited", profile: { ...prior.binding, origin: startupOrigin } }) : undefined;
6232
+ ctx.ui.notify(label === undefined ? "el Gentleman: this session is already on no profile, as it started; nothing to clear." : `el Gentleman: this session is already on the profile it started with, "${label}"; nothing to clear.`, "info");
6233
+ return true;
6234
+ }
6235
+ if (prior.status === "cleared" && prior.startup !== "none") {
6236
+ ctx.ui.notify("el Gentleman: this session profile is already cleared; nothing to clear.", "info");
6237
+ return true;
6238
+ }
6239
+ const startup = knownSessionProfileStartup(prior, sessionId);
6240
+ const outcome = typeof startup === "object" ? attachment.bindStartup(startup.origin, startup.name, startup.modelProfiles) : attachment.clear(startup);
6241
+ if (!owned()) return false;
6242
+ const authority = publishSessionProfileOutcome(ctx.sessionManager, outcome);
6243
+ if ((outcome.status !== "persisted" && outcome.status !== "not-persisted") || outcome.state.status !== (typeof startup === "object" ? "bound" : "cleared") || !authority.available) {
6244
+ ctx.ui.notify(
6245
+ `el Gentleman could not clear the session profile. ${authority.available ? "The last disk-corroborated state was preserved." : "Session profile authority is unavailable; affected launches are blocked."}`,
6246
+ "warning",
6247
+ );
6248
+ return false;
6249
+ }
6250
+ const what = prior.status === "bound" ? `session profile "${prior.binding.name}"` : prior.status === "cleared" ? "the recorded startup state" : "the unreadable session profile record";
6251
+ const persistence = outcome.status === "persisted" ? "persisted in this session" : "not yet persisted; active only until detach or disk corroboration";
6252
+ if (startup !== undefined) {
6253
+ ctx.ui.notify(`el Gentleman cleared ${what} (${persistence}). New launches go back to ${startupStateText(startup)}. The live orchestrator is unchanged.`, "info");
6254
+ return true;
6255
+ }
6256
+ ctx.ui.notify(
6257
+ `el Gentleman cleared ${what} — ${outcome.status === "persisted" ? "persisted in this session" : "not yet persisted; active only until detach or disk corroboration"}. New launches use the routing without a session profile (pins, repository declaration, global). The live orchestrator is unchanged.`,
6258
+ "info",
6259
+ );
6260
+ return true;
6261
+ });
6262
+ // A selection skipped by a reload or session replacement leaves a stale ctx;
6263
+ // only a still-active command reports the missing attachment.
6264
+ if (selected === undefined && isCommandContextActive(ctx))
6265
+ ctx.ui.notify("el Gentleman cannot clear the session profile: the current session attachment is unavailable. Nothing was changed.", "warning");
6266
+ }
6267
+
6268
+ /**
6269
+ * Whether this `session_start` is the session's own start (gentle-shell#2742,
6270
+ * section 3). Pi has no new-session flag: "startup" also opens an existing
6271
+ * session file, and a reload or resume restarts a session that already began.
6272
+ * Before `session_start`, Pi records the model and thinking level of a session
6273
+ * without a conversation, a new one included, so an own start holds at most
6274
+ * that one pair. A profile record, any other entry, or an earlier pair means
6275
+ * the session started before, and its startup state stays unknown.
6276
+ */
6277
+ function isSessionOwnStart(event: { reason: string }, manager: ExtensionContext["sessionManager"]): boolean {
6278
+ if (event.reason !== "startup" && event.reason !== "new") return false;
6279
+ const seen = new Set<string>();
6280
+ for (const entry of manager.getEntries()) {
6281
+ if ((entry.type !== "model_change" && entry.type !== "thinking_level_change") || seen.has(entry.type)) return false;
6282
+ seen.add(entry.type);
6283
+ }
6284
+ return true;
6285
+ }
6286
+
6287
+ /**
6288
+ * Warn when the current session profile record cannot be read: an invalid record
6289
+ * or one from a newer version blocks affected launches instead of falling back.
6290
+ */
6291
+ function notifySessionProfileProblem(ctx: ExtensionContext): void {
6292
+ const state = readCurrentSessionProfileOutcome(ctx.sessionManager)?.state;
6293
+ if (state?.status !== "invalid" && state?.status !== "unsupported") return;
6294
+ const file = ctx.sessionManager.getSessionFile?.() ?? "this in-memory session";
6295
+ const where = `${sanitizeTerminalText(file)} entry ${state.entryIndex ?? "?"}${state.lineNumber === undefined ? "" : ` (line ${state.lineNumber})`}`;
6296
+ const kind = state.status === "invalid" ? "invalid" : "from a newer version";
6297
+ ctx.ui.notify(
6298
+ `el Gentleman: the session profile record at ${where} is ${kind}. Subagent launches are blocked until it is replaced. Select a profile with Enter or run /gentle:profiles clear.`,
6299
+ "warning",
6300
+ );
6301
+ }
6302
+
6303
+ /** Pi's runner throws on any access to a ctx made stale by reload or session replacement. */
6304
+ function isCommandContextActive(ctx: ExtensionContext): boolean {
6305
+ try {
6306
+ void ctx.sessionManager;
6307
+ return true;
6308
+ } catch {
6309
+ return false;
6310
+ }
6311
+ }
6312
+
5755
6313
  async function handlePersonaCommand(ctx: ExtensionContext): Promise<void> {
5756
6314
  const current = readPersonaMode(ctx.cwd);
5757
6315
  const selected = await ctx.ui.select(
@@ -5850,7 +6408,7 @@ const REVIEW_CONTROLLER_PARAMETER_FIELDS = {
5850
6408
  },
5851
6409
  input: {
5852
6410
  type: "string",
5853
- description: "A JSON object or serialized object string for START/ASSESS/answer-consent; every other operation requires a serialized object string. New native ordinary START uses {\"mode\":\"ordinary\"}, plus the agent lens selection {\"lenses\":[\"risk\",...],\"lensesReason\":\"<what you touched and how>\"} (both or neither, 1-4 of risk, resilience, readability, reliability; never with focus; providers that predate it keep the tier default); answer-consent uses exactly {\"consentBinding\":\"<opaque id>\",\"answer\":\"granted|declined\"}. Ordinary provider capture belongs only to gentle_review_capture. An explicit baseRef requires committedOnly: true and requests a committed range, while repository-local policyPath remains optional. baseRef must be HEAD, a full 40- or 64-character commit id, or a ref name; abbreviated commit ids are rejected as base-ref-unresolvable. ASSESS accepts an optional object with baseRef, committedOnly, writerModelId, writerEffort, and nativeReviewOutcome (gentle-pi#662/#668/#1175). The writer profile comes from the runtime-recorded model and effort of the pending mutations for this root (writerProfileSource runtime); writerModelId and writerEffort are only a fallback when no runtime evidence exists (caller), and with neither the profile fails closed to small (fallback). The writer profile is reported but never adds a verifier: the plan adds the independent verifier only when escalate names a Task Size high-risk item. ASSESS derives `closed` only from the native candidate.consumed fact for this exact candidate, which native records only when the approved review for that candidate is acknowledged; a caller-supplied closed is not authority and, without that fact, resolves to unknown. Every outcome yields the exact risk-gated plan ASSESS returns when RDD is off: a closed review never removes the separate verifier the tier requires (verify-always-rdd-high S1), unknown is never treated as closed, and a decline is candidate-scoped and never lowers the bar below the RDD-off path. A declined or unavailable outcome, stated explicitly or recorded by this process for this exact candidate (never a different one, and never from repository state alone), wins over closure. The returned outcome_source (explicit|derived|unknown) says which of these produced the value. Legacy controller input remains separate.",
6411
+ description: "A JSON object or serialized object string for START/ASSESS/answer-consent; every other operation requires a serialized object string. New native ordinary START uses {\"mode\":\"ordinary\"}, plus the agent lens selection {\"lenses\":[\"risk\",...],\"lensesReason\":\"<what you touched and how>\"} (both or neither, 1-4 of risk, resilience, readability, reliability; never with focus; providers that predate it keep the tier default); answer-consent uses exactly {\"consentBinding\":\"<opaque id>\",\"answer\":\"granted|declined\"}. Ordinary provider capture belongs only to gentle_review_capture. An explicit baseRef requires committedOnly: true and requests a committed range, while repository-local policyPath remains optional. baseRef must be HEAD, a full 40- or 64-character commit id, or a ref name; abbreviated commit ids are rejected as base-ref-unresolvable. ASSESS accepts an optional object with baseRef, committedOnly, writerModelId, writerEffort, nativeReviewOutcome, and escalate (gentle-pi#662/#668/#1175/#2647); escalate is {\"item\":N,\"reason\":\"...\"} with item an integer from 1 to 6 and a non-empty reason of at most 500 characters; any other shape is rejected, and omitting it means no escalation. The writer profile comes from the runtime-recorded model and effort of the pending mutations for this root (writerProfileSource runtime); writerModelId and writerEffort are only a fallback when no runtime evidence exists (caller), and with neither the profile fails closed to small (fallback). The writer profile is reported but never adds a verifier: the plan adds the independent verifier only when escalate names a Task Size high-risk item. ASSESS derives `closed` only from the native candidate.consumed fact for this exact candidate, which native records only when the approved review for that candidate is acknowledged; a caller-supplied closed is not authority and, without that fact, resolves to unknown. Every outcome yields the exact risk-gated plan ASSESS returns when RDD is off: a closed review never removes the separate verifier the tier requires (verify-always-rdd-high S1), unknown is never treated as closed, and a decline is candidate-scoped and never lowers the bar below the RDD-off path. A declined or unavailable outcome, stated explicitly or recorded by this process for this exact candidate (never a different one, and never from repository state alone), wins over closure. The returned outcome_source (explicit|derived|unknown) says which of these produced the value. Legacy controller input remains separate.",
5854
6412
  },
5855
6413
  outputPath: { type: "string", description: "Retired with legacy bundle export; ignored. Export returns legacy-operation-retired." },
5856
6414
  inputPath: { type: "string", description: "Repository-local JSON input file for the separate legacy controller flow (alternative to input). Legacy bundle import is retired." },
@@ -7649,7 +8207,7 @@ function nativeOperationFailure(operation: ReviewControllerOperation | "gentle_r
7649
8207
  const preservesNativeTargetStatusDiagnostic = nativeDiagnostics?.operation === NATIVE_REVIEW_OPERATION.STATUS;
7650
8208
  const preservesAnswerConsentStartDiagnostic = operation === REVIEW_CONTROLLER_OPERATION.ANSWER_CONSENT && nativeDiagnostics?.operation === NATIVE_REVIEW_OPERATION.START;
7651
8209
  const diagnostics = operation === REVIEW_CONTROLLER_OPERATION.START && error instanceof CandidateViewError && value.candidateViewPreNative === true
7652
- ? error.diagnostics ?? { code: error.reason, message: "candidate view rejected before native START" }
8210
+ ? error.diagnostics ?? { code: error.reason, message: error.message }
7653
8211
  : error instanceof CandidateViewError
7654
8212
  ? { code: error.reason, message: error.message }
7655
8213
  : nativeDiagnostics?.operation === `review/${operation}` || preservesNativeTargetStatusDiagnostic || preservesAnswerConsentStartDiagnostic
@@ -7867,6 +8425,167 @@ function nativePreLineageCandidateIdentity(
7867
8425
  : undefined;
7868
8426
  }
7869
8427
 
8428
+ // gentle-ai#2196: inspect must not advertise a START whose candidate-view
8429
+ // materialization is already known to fail. START materializes the frozen
8430
+ // view and then verifies cheap non-mutating invariants; when one is
8431
+ // deterministically false (the POSIX candidate owner parent is not private,
8432
+ // or the frozen tree tracks symlinks this process cannot create natively),
8433
+ // inspect runs the same non-persistent checks first and withholds the ready
8434
+ // advertisement with the exact typed diagnostics the START refusal would
8435
+ // carry, so STATUS and START stop disagreeing about operations that cannot
8436
+ // begin. The Windows owner boundary keeps its START-time DACL validation for
8437
+ // now; this preflight only answers questions a non-persistent check settles
8438
+ // (the capability probe creates and removes a temporary directory). The
8439
+ // symlink scan never claims a confirmed symlink-free tree from an incomplete
8440
+ // listing (timeout, output limit, unreadable tree), and the capability probe
8441
+ // samples the filesystem that will hold the candidate view — when that
8442
+ // filesystem cannot be probed, the capability stays unconfirmed and the
8443
+ // advertisement is withheld instead of guessing from another filesystem.
8444
+ let candidateViewSymlinkProbe: ((probeRoot: string) => void) | undefined;
8445
+
8446
+ function setCandidateViewSymlinkProbeForTesting(probe: ((probeRoot: string) => void) | undefined): void {
8447
+ candidateViewSymlinkProbe = probe;
8448
+ }
8449
+
8450
+ // Thrown when no existing directory of the candidate-view filesystem can host
8451
+ // the probe: the capability stays unconfirmed instead of being reported as
8452
+ // incapable, so an unverifiable filesystem never masquerades as a pass.
8453
+ class CandidateViewSymlinkProbeUnavailableError extends Error {}
8454
+
8455
+ function defaultCandidateViewSymlinkProbe(probeRoot: string): void {
8456
+ let directory: string;
8457
+ try {
8458
+ directory = mkdtempSync(join(probeRoot, "gentle-symlink-probe-"));
8459
+ } catch (error) {
8460
+ throw new CandidateViewSymlinkProbeUnavailableError("cannot create a probe directory on the candidate-view filesystem", { cause: error });
8461
+ }
8462
+ try {
8463
+ symlinkSync("probe-target", join(directory, "probe"), process.platform === "win32" ? "file" : undefined);
8464
+ } finally {
8465
+ rmSync(directory, { recursive: true, force: true });
8466
+ }
8467
+ }
8468
+
8469
+ // The deepest existing ancestor of the candidate-view parent: probing there
8470
+ // samples the filesystem that will actually hold the candidate view. Before
8471
+ // the first START only the Git common directory exists; after one, the probe
8472
+ // lands inside the real candidate-views parent.
8473
+ function nearestExistingAncestorDirectory(path: string): string | undefined {
8474
+ let current = path;
8475
+ for (;;) {
8476
+ try {
8477
+ if (statSync(current).isDirectory()) return current;
8478
+ } catch {
8479
+ // Missing or unreadable: keep walking up.
8480
+ }
8481
+ const parent = dirname(current);
8482
+ if (parent === current) return undefined;
8483
+ current = parent;
8484
+ }
8485
+ }
8486
+
8487
+ type CandidateTreeSymlinkScan = "tracks-symlinks" | "no-symlinks" | "unconfirmed";
8488
+
8489
+ function scanCandidateTreeForSymlinks(cwd: string, candidateTree: string): CandidateTreeSymlinkScan {
8490
+ // Discovery must describe the selected directory, never an ambient Git
8491
+ // override pointing at a different repository or worktree.
8492
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_")));
8493
+ try {
8494
+ const listing = execFileSync("git", ["ls-tree", "-r", "--full-tree", candidateTree], {
8495
+ cwd,
8496
+ env,
8497
+ encoding: "utf8",
8498
+ windowsHide: true,
8499
+ stdio: ["ignore", "pipe", "pipe"],
8500
+ // Same bounds the candidate-view materialization uses: a bounded
8501
+ // child that cannot hang the event loop, and a listing past the
8502
+ // output limit is an incomplete scan, never a symlink-free verdict.
8503
+ timeout: resolveCandidateGitTimeoutMs(),
8504
+ maxBuffer: CANDIDATE_GIT_MAX_BUFFER_BYTES,
8505
+ });
8506
+ return listing.split("\n").some((line) => line.startsWith("120000 ")) ? "tracks-symlinks" : "no-symlinks";
8507
+ } catch {
8508
+ // A timed-out, over-limit, or otherwise unreadable tree is an
8509
+ // incomplete scan, not a deterministic materialization failure;
8510
+ // START owns reporting unreadable trees.
8511
+ return "unconfirmed";
8512
+ }
8513
+ }
8514
+
8515
+ type CandidateViewSymlinkCapability = "capable" | "incapable" | "unconfirmed";
8516
+
8517
+ function candidateViewSymlinkCapability(commonDir: string | undefined): CandidateViewSymlinkCapability {
8518
+ if (commonDir === undefined) return "unconfirmed";
8519
+ const probeRoot = nearestExistingAncestorDirectory(join(commonDir, "gentle-ai", "candidate-views"));
8520
+ if (probeRoot === undefined) return "unconfirmed";
8521
+ try {
8522
+ (candidateViewSymlinkProbe ?? defaultCandidateViewSymlinkProbe)(probeRoot);
8523
+ } catch (error) {
8524
+ return error instanceof CandidateViewSymlinkProbeUnavailableError ? "unconfirmed" : "incapable";
8525
+ }
8526
+ return "capable";
8527
+ }
8528
+
8529
+ function candidateViewPreflightRejection(status: ReviewStatusV3, diagnostics: Record<string, string>): Record<string, unknown> {
8530
+ // The native body carries the executable START transition; consumers read the
8531
+ // nested result.next_transition, so a blocked inspect must not forward it.
8532
+ const { next_transition: _withheldTransition, ...blockedResult } = status.raw;
8533
+ return {
8534
+ operation: REVIEW_CONTROLLER_OPERATION.INSPECT,
8535
+ status: "blocked",
8536
+ outcome: "candidate-view-preflight-blocked",
8537
+ result: blockedResult,
8538
+ diagnostics,
8539
+ mutation_performed: false,
8540
+ mutation_outcome: "none",
8541
+ lineage_created: false,
8542
+ next_action: "resolve-native-operation-failure",
8543
+ };
8544
+ }
8545
+
8546
+ function inspectCandidateViewPreflightBlocked(status: ReviewStatusV3, cwd: string, commonDir: string | undefined, platform: NodeJS.Platform = process.platform): Record<string, unknown> | undefined {
8547
+ if (status.action !== "start") return undefined;
8548
+ if (platform !== "win32" && commonDir !== undefined) {
8549
+ try {
8550
+ assertCandidateOwnerParent(commonDir, platform);
8551
+ } catch (error) {
8552
+ // A missing parent is not a deterministic failure while START's prepare
8553
+ // can still create it private under the nearest existing ancestor. Every
8554
+ // other owner failure makes START refuse too, so withhold the
8555
+ // advertisement with the owner-preparation classification.
8556
+ let failureCause: unknown = error;
8557
+ if ((error as NodeJS.ErrnoException | undefined)?.code === "ENOENT") {
8558
+ failureCause = undefined;
8559
+ const ancestor = nearestExistingAncestorDirectory(join(commonDir, "gentle-ai", "candidate-views"));
8560
+ try {
8561
+ if (ancestor !== undefined) accessSync(ancestor, fsConstants.W_OK | fsConstants.X_OK);
8562
+ } catch (accessError) {
8563
+ failureCause = accessError;
8564
+ }
8565
+ }
8566
+ if (failureCause !== undefined) {
8567
+ const failure = candidateOwnerPreparationError(failureCause);
8568
+ const typed = failure.diagnostics !== undefined && "code" in failure.diagnostics ? failure.diagnostics : undefined;
8569
+ return candidateViewPreflightRejection(status, typed ?? { code: failure.reason, message: failure.message });
8570
+ }
8571
+ }
8572
+ }
8573
+ const candidateTree = status.projection.currentCandidateTree;
8574
+ if (isCanonicalProcessString(candidateTree) && scanCandidateTreeForSymlinks(cwd, candidateTree) === "tracks-symlinks") {
8575
+ const capability = candidateViewSymlinkCapability(commonDir);
8576
+ if (capability === "unconfirmed") {
8577
+ // The tree needs native symlinks and the target filesystem could not
8578
+ // be probed: advertising START would only move the same uncertainty
8579
+ // into a materialization refusal (gentle-ai#2196).
8580
+ return candidateViewPreflightRejection(status, { code: "symlink-capability-unconfirmed" as const, message: CANDIDATE_SYMLINK_CAPABILITY_UNCONFIRMED_MESSAGE });
8581
+ }
8582
+ if (capability === "incapable") {
8583
+ return candidateViewPreflightRejection(status, { code: "symlink-materialization-failed" as const, message: CANDIDATE_SYMLINK_MATERIALIZATION_MESSAGE });
8584
+ }
8585
+ }
8586
+ return undefined;
8587
+ }
8588
+
7870
8589
  function readRetainedPreLineageNativeUntrackedSelection(
7871
8590
  selections: Map<string, RetainedNativeStatusSelection>,
7872
8591
  workspaceRoot: string,
@@ -8019,11 +8738,21 @@ function reviewHostRelayFailureReport(error: ReviewHostRelayError): Record<strin
8019
8738
  // never carry them. For those two keys only, a snapshot with no model falls
8020
8739
  // back to Pi's persisted default model and effort, the default the routing
8021
8740
  // panel already labels them with. Lens keys keep the fail-closed rule.
8022
- function reviewHostRelaySelection(lens: string | undefined, config: AgentModelConfig): { selection?: string; thinking?: string; routingKey: string } {
8741
+ function reviewHostRelaySelection(lens: string | undefined, config: AgentModelConfig): { selection?: string; thinking?: string; tier?: AgentRoutingEntry["tier"]; routingKey: string } {
8023
8742
  const routingKey = lens === undefined || lens.length === 0 ? "review capture" : lens.startsWith("review-") ? lens : `review-${lens}`;
8024
8743
  const entry = config[routingKey];
8025
8744
  let model = typeof entry === "object" && entry !== null && typeof (entry as AgentRoutingEntry).model === "string" && (entry as AgentRoutingEntry).model!.length > 0 ? (entry as AgentRoutingEntry).model : undefined;
8026
8745
  let thinking = typeof entry === "object" && entry !== null && typeof (entry as AgentRoutingEntry).thinking === "string" ? (entry as AgentRoutingEntry).thinking : undefined;
8746
+ if (model === undefined && isProviderReviewRole(routingKey)) {
8747
+ // These roles default to the orchestrator: the session profile's own one
8748
+ // first, so a session that switched profile never reviews on the model it
8749
+ // started with (gentle-shell#1064).
8750
+ const orchestrator = readProfileOrchestrator(config);
8751
+ if (orchestrator?.model !== undefined) {
8752
+ model = orchestrator.model;
8753
+ thinking ??= orchestrator.thinking;
8754
+ }
8755
+ }
8027
8756
  if (model === undefined && isProviderReviewRole(routingKey)) {
8028
8757
  const persisted = readOrchestratorSettings(orchestratorSettingsPath());
8029
8758
  if (persisted.status === "valid" && persisted.entry?.model !== undefined) {
@@ -8034,6 +8763,7 @@ function reviewHostRelaySelection(lens: string | undefined, config: AgentModelCo
8034
8763
  return {
8035
8764
  ...(model === undefined ? {} : { selection: model }),
8036
8765
  ...(thinking === undefined ? {} : { thinking }),
8766
+ ...(entry?.tier === undefined ? {} : { tier: entry.tier }),
8037
8767
  routingKey,
8038
8768
  };
8039
8769
  }
@@ -8159,6 +8889,8 @@ async function executeReviewHostRelayCapture(
8159
8889
  reviewerSessionId?: string,
8160
8890
  implicitWorkspaceRoot?: string,
8161
8891
  getReviewerTransport?: () => ReviewHostRelayRequest["reviewerTransport"],
8892
+ // The session's own directory, so a review of another repository routes like a launch there.
8893
+ sessionCwd: string = cwd,
8162
8894
  ): Promise<Record<string, unknown>> {
8163
8895
  try {
8164
8896
  if (slot.submission === undefined) {
@@ -8181,7 +8913,7 @@ async function executeReviewHostRelayCapture(
8181
8913
  // global routing. A pin that omits a required role stays omitted: the
8182
8914
  // typed reviewer-config-invalid refusal below is fail-closed, never a
8183
8915
  // silent per-role fallback to another account's routing.
8184
- const launch = reviewHostRelaySelection(slot.routingKey ?? slot.lens, readReviewerModelConfig(cwd, reviewerSessionId));
8916
+ const launch = reviewHostRelaySelection(slot.routingKey ?? slot.lens, readReviewerModelConfig(cwd, reviewerSessionId, sessionCwd));
8185
8917
  return {
8186
8918
  captureArgumentTokens: slot.captureArgumentTokens,
8187
8919
  targetCwd: cwd,
@@ -8690,13 +9422,21 @@ function selectExactReviewCapture(
8690
9422
  const inputTargetIdentity = exactCollectArgument(input, "target");
8691
9423
  // Go's targeted-validator vector binds its capture target to the correction
8692
9424
  // target from the provider-owned validation request, rather than STATUS's
8693
- // current candidate identity. All other captures remain bound to STATUS.
8694
- const expectedInputTargetIdentity = input.validationRequest?.correctionTargetIdentity ?? statusTargetIdentity;
9425
+ // current candidate identity. All other captures are bound to STATUS's live
9426
+ // target, except correction plans: gentle-ai's reviewAuthorityTargetIdentity
9427
+ // binds them to the frozen authority target (authority_target_identity)
9428
+ // once the candidate drifts.
9429
+ const validationTarget = input.validationRequest?.correctionTargetIdentity;
9430
+ const expectedInputTargetIdentities = validationTarget !== undefined
9431
+ ? [validationTarget]
9432
+ : input.captureOperation === "review.capture-correction-plan"
9433
+ ? [statusTargetIdentity, status.authorityTargetIdentity]
9434
+ : [statusTargetIdentity];
8695
9435
  if (
8696
9436
  !isCanonicalProcessString(inputLineageId) ||
8697
9437
  !isCanonicalProcessString(inputTargetIdentity) ||
8698
9438
  inputLineageId !== lineageId ||
8699
- inputTargetIdentity !== expectedInputTargetIdentity
9439
+ !expectedInputTargetIdentities.includes(inputTargetIdentity)
8700
9440
  ) {
8701
9441
  return captureBindingRejected("collectBinding does not carry one non-empty matching provider lineage and target token");
8702
9442
  }
@@ -8896,7 +9636,7 @@ async function executeReviewCaptureOperation(
8896
9636
  mutation_outcome: "none",
8897
9637
  };
8898
9638
  }
8899
- return withCorrectionTarget(await executeReviewHostRelayCapture(hostRelaySlots[0]!, nativeReviewCli, cwd, selected.binding, retainedUntrackedSelections, route, signal, modelRegistry, reviewerSessionId, implicitWorkspaceRoot, getReviewerTransport));
9639
+ return withCorrectionTarget(await executeReviewHostRelayCapture(hostRelaySlots[0]!, nativeReviewCli, cwd, selected.binding, retainedUntrackedSelections, route, signal, modelRegistry, reviewerSessionId, implicitWorkspaceRoot, getReviewerTransport, sessionCwd));
8900
9640
  }
8901
9641
 
8902
9642
  // gentle-pi#311 P3: gentle-ai's v9 contract renders the refuter and
@@ -8922,7 +9662,7 @@ async function executeReviewCaptureOperation(
8922
9662
  mutation_outcome: "none",
8923
9663
  };
8924
9664
  }
8925
- return withCorrectionTarget(await executeReviewHostRelayCapture(hostMediatedRoleSlots[0]!, nativeReviewCli, cwd, selected.binding, retainedUntrackedSelections, route, signal, modelRegistry, reviewerSessionId, implicitWorkspaceRoot, getReviewerTransport));
9665
+ return withCorrectionTarget(await executeReviewHostRelayCapture(hostMediatedRoleSlots[0]!, nativeReviewCli, cwd, selected.binding, retainedUntrackedSelections, route, signal, modelRegistry, reviewerSessionId, implicitWorkspaceRoot, getReviewerTransport, sessionCwd));
8926
9666
  }
8927
9667
 
8928
9668
  if (selected.input.captureOperation === "review.capture-correction-plan") {
@@ -8952,7 +9692,10 @@ async function executeReviewCaptureOperation(
8952
9692
  cwd,
8953
9693
  ...(signal === undefined ? {} : { signal }),
8954
9694
  });
8955
- return withCorrectionTarget(mapAndClearLastEventClosure(closure, selected.binding, retainedUntrackedSelections, cwd, implicitWorkspaceRoot));
9695
+ // The provider echoes the target the plan was captured for (the frozen
9696
+ // authority target after drift); reconciliation stays on STATUS's target.
9697
+ const capturedTarget = exactCollectArgument(selected.input, "target") ?? selected.binding.targetIdentity;
9698
+ return withCorrectionTarget(mapAndClearLastEventClosure(closure, { ...selected.binding, targetIdentity: capturedTarget }, retainedUntrackedSelections, cwd, implicitWorkspaceRoot));
8956
9699
  } catch (error) {
8957
9700
  return await reconcileUnknownReviewCaptureFailure(error, nativeReviewCli, cwd, selected.binding, retainedUntrackedSelections, route);
8958
9701
  }
@@ -9049,7 +9792,7 @@ async function executeReviewCaptureGroupOperation(
9049
9792
  }
9050
9793
  // Resolve session-over-pin-over-global once for the entire reviewer group,
9051
9794
  // so every slot uses the same complete routing snapshot.
9052
- const reviewerRouting = readReviewerModelConfig(cwd, reviewerSessionId);
9795
+ const reviewerRouting = readReviewerModelConfig(cwd, reviewerSessionId, sessionCwd);
9053
9796
  const reviewerTransport = getReviewerTransport?.();
9054
9797
  const requests: readonly ReviewHostRelayRequest[] = group.slots.map((slot) => ({
9055
9798
  captureArgumentTokens: slot.captureArgumentTokens,
@@ -9200,7 +9943,7 @@ async function executeReviewControllerOperation(
9200
9943
  parameters.operation === REVIEW_CONTROLLER_OPERATION.INSPECT &&
9201
9944
  nativeReviewCli !== null
9202
9945
  ) {
9203
- const rawInspect = parameters.input === undefined
9946
+ const rawInspect = parameters.input === undefined || parameters.input.trim() === ""
9204
9947
  ? undefined
9205
9948
  : parseControllerJson(parameters.input, REVIEW_CONTROLLER_OPERATION.INSPECT);
9206
9949
  const unknownField = rawInspect === undefined
@@ -9210,7 +9953,7 @@ async function executeReviewControllerOperation(
9210
9953
  const baseRef = rawInspect?.baseRef;
9211
9954
  if (baseRef !== undefined && !isCanonicalProcessString(baseRef)) return nativeInspectInputRejection("base-ref-invalid");
9212
9955
  if (baseRef !== undefined && rawInspect?.committedOnly !== true) return nativeInspectInputRejection("committed-only-required");
9213
- if (rawInspect !== undefined && baseRef === undefined) return nativeInspectInputRejection("committed-only-invalid");
9956
+ if (rawInspect?.committedOnly !== undefined && baseRef === undefined) return nativeInspectInputRejection("committed-only-invalid");
9214
9957
  let canonicalBaseRef: string | undefined;
9215
9958
  if (typeof baseRef === "string") {
9216
9959
  try {
@@ -9270,6 +10013,12 @@ async function executeReviewControllerOperation(
9270
10013
  retainNativeStatusSelection(retainedUntrackedSelections, reviewLifecycleStorageKey(defaultCwd, ""), Object.freeze({ ...readyCandidateIdentity, baseRef: canonicalBaseRef, committedOnly: true as const }));
9271
10014
  }
9272
10015
  }
10016
+ // gentle-ai#2196: a ready advertisement must survive the same cheap
10017
+ // candidate-view invariants START verifies, or be withheld.
10018
+ if (plainMapped.status === "ready") {
10019
+ const preflightBlocked = inspectCandidateViewPreflightBlocked(status, defaultCwd, workspaceResolution.identity?.commonDir);
10020
+ if (preflightBlocked !== undefined) return { ...preflightBlocked, ...(includeWorkspaceRoot ? { workspace_root: defaultCwd } : {}) };
10021
+ }
9273
10022
  // gentle-pi#706: the stop alone never tells the caller what to do next.
9274
10023
  return {
9275
10024
  ...plainMapped,
@@ -9280,12 +10029,18 @@ async function executeReviewControllerOperation(
9280
10029
  };
9281
10030
  }
9282
10031
  const input = reviewIntendedUntrackedInput(status);
9283
- if (input === undefined)
10032
+ if (input === undefined) {
10033
+ // gentle-ai#2196: same ready-advertisement preflight as the plain path.
10034
+ if (plainMapped.status === "ready") {
10035
+ const preflightBlocked = inspectCandidateViewPreflightBlocked(status, defaultCwd, workspaceResolution.identity?.commonDir);
10036
+ if (preflightBlocked !== undefined) return { ...preflightBlocked, ...(includeWorkspaceRoot ? { workspace_root: defaultCwd } : {}) };
10037
+ }
9284
10038
  return {
9285
10039
  ...plainMapped,
9286
10040
  untracked_selection: "not-required",
9287
10041
  ...(includeWorkspaceRoot ? { workspace_root: defaultCwd } : {}),
9288
10042
  };
10043
+ }
9289
10044
  const eligibleJson = exactCollectArgument(input, "eligible_paths_json"),
9290
10045
  inventory = exactCollectArgument(input, "expected_untracked_inventory");
9291
10046
  let eligible: unknown;
@@ -9369,6 +10124,12 @@ async function executeReviewControllerOperation(
9369
10124
  undefined,
9370
10125
  includeWorkspaceRoot ? defaultCwd : undefined,
9371
10126
  );
10127
+ // gentle-ai#2196: the resolved selection path advertises START under the
10128
+ // same cheap candidate-view invariants as the plain path.
10129
+ if (resolvedMapped.status === "ready") {
10130
+ const preflightBlocked = inspectCandidateViewPreflightBlocked(resolvedStatus, defaultCwd, workspaceResolution.identity?.commonDir);
10131
+ if (preflightBlocked !== undefined) return { ...preflightBlocked, ...(includeWorkspaceRoot ? { workspace_root: defaultCwd } : {}) };
10132
+ }
9372
10133
  return {
9373
10134
  ...resolvedMapped,
9374
10135
  ...("selectionBinding" in resolvedMapped
@@ -10177,13 +10938,19 @@ async function executeReviewControllerOperation(
10177
10938
 
10178
10939
  /** @internal */
10179
10940
  export const __testing = {
10941
+ setCandidateViewSymlinkProbeForTesting,
10942
+ CandidateViewSymlinkProbeUnavailableError,
10943
+ scanCandidateTreeForSymlinks,
10180
10944
  parseReviewControllerParameters,
10181
10945
  parseReviewCaptureParameters,
10182
10946
  parseReviewCaptureGroupParameters,
10183
10947
  runProfilesPanelAction,
10948
+ openProfilesPanelLoop,
10949
+ notifySessionProfileProblem,
10184
10950
  resolveReviewModeGate,
10185
10951
  readEffectiveModelConfig,
10186
10952
  readReviewerModelConfig,
10953
+ reviewHostRelaySelection,
10187
10954
  readEffectiveModelConfigAsync,
10188
10955
  followRenamedPin,
10189
10956
  profilePinScopeNote,
@@ -10210,6 +10977,7 @@ export const __testing = {
10210
10977
  setReviewHostRelayGroupRunnersForTesting,
10211
10978
  clearReviewTransportProbeForTesting,
10212
10979
  routingTablePanel: renderRoutingTableForTesting,
10980
+ fileRoutingFallbacks,
10213
10981
  piThinkingSupport: getPiThinkingSupport,
10214
10982
  getOrchestratorPrompt,
10215
10983
  renderOrchestratorPrompt,
@@ -10306,11 +11074,22 @@ function createGentleAiExtensionForTesting(
10306
11074
  cancel: () => classifier?.cancel(),
10307
11075
  }, { configHome: gentlePiConfigHome(permissionEnvironment) });
10308
11076
  const auto = autoPermissions;
11077
+ const verifierSettleReminders = createVerifierSettleReminders<PendingReviewConsentSessionKey>();
11078
+ const explorationBudget = createExplorationBudget();
11079
+ // Named-agent or child runs started and not yet settled, per session. Such a run never records verifier attempts (its
11080
+ // tool calls are not primary), so its settle checks must not remind. Each one pairs off at its own `agent_settled`,
11081
+ // nested runs included: Pi may check settlement again after a continuation without a new `before_agent_start`, and
11082
+ // `agent_end` may or may not have paired off the subagent depth by then.
11083
+ const verifierSettleNamedRuns = new Map<PendingReviewConsentSessionKey, number>();
10309
11084
  pi.on("tool_result", (event, ctx) => {
10310
11085
  if (permissionEnvironment.GENTLE_PI_AGENTS_CHILD !== "1") auto.toolResult(event, ctx);
10311
11086
  });
10312
11087
  pi.on("input", (event, ctx) => {
10313
11088
  if (permissionEnvironment.GENTLE_PI_AGENTS_CHILD !== "1") auto.input(event, ctx);
11089
+ // #2652: a new user prompt resets the settle reminder; a steer joins the running prompt.
11090
+ if (permissionEnvironment.GENTLE_PI_AGENTS_CHILD !== "1" && event.streamingBehavior !== "steer") {
11091
+ verifierSettleReminders.userPrompt(pendingReviewConsentSessionKey(ctx, pendingReviewConsentFallbackKey));
11092
+ }
10314
11093
  return { action: "continue" };
10315
11094
  });
10316
11095
 
@@ -10344,11 +11123,21 @@ function createGentleAiExtensionForTesting(
10344
11123
 
10345
11124
  const statusTiming = new StatusTimingDiagnostics();
10346
11125
  const reviewSidebar = createReviewSidebarPublisher(pi);
11126
+ const sessionProfiles = createSessionProfileIntegration();
11127
+ pi.on("session_before_fork", async (event, ctx) => {
11128
+ await waitCurrentSessionProfileSelection(ctx.sessionManager);
11129
+ sessionProfiles.beforeFork(ctx.sessionManager, { entryId: event.entryId, position: event.position });
11130
+ });
11131
+ pi.on("session_before_tree", async (_event, ctx) => {
11132
+ await waitCurrentSessionProfileSelection(ctx.sessionManager);
11133
+ });
10347
11134
  const observedReviewTool: typeof reviewSidebar.tool = (definition) => statusTiming.tool(reviewSidebar.tool(definition));
10348
11135
  pi.on("session_tree", (_event, ctx) => {
10349
11136
  auto.reset();
10350
11137
  reviewSidebar.reset(ctx);
10351
11138
  statusTiming.reset(ctx);
11139
+ readSessionProfileAuthority(ctx.sessionManager);
11140
+ if (ctx.hasUI) notifySessionProfileProblem(ctx);
10352
11141
  });
10353
11142
  // Lean RDD-off review loadout (applyRddOffReviewPrompt): every
10354
11143
  // before_agent_start sets it from the pinned line before Pi prepares that
@@ -10359,6 +11148,19 @@ function createGentleAiExtensionForTesting(
10359
11148
  let reminderManager: ExtensionContext["sessionManager"] | undefined;
10360
11149
  let unbindPreparation: (() => void) | undefined;
10361
11150
  pi.on("session_shutdown", (event, context) => {
11151
+ // A pending Enter selection settles before the profile owner shuts down;
11152
+ // without one the whole shutdown stays synchronous, so terminal cleanup
11153
+ // (child permission transport, sidebars) is never deferred a turn.
11154
+ if (hasPendingSessionProfileSelection(context.sessionManager)) {
11155
+ return waitCurrentSessionProfileSelection(context.sessionManager).then(() => shutdownSession(event, context));
11156
+ }
11157
+ shutdownSession(event, context);
11158
+ });
11159
+ function shutdownSession(event: SessionShutdownEvent, context: ExtensionContext): void {
11160
+ if (sessionProfiles.isCurrent(context.sessionManager)) {
11161
+ clearSessionProfileBinding(context.sessionManager.getSessionId());
11162
+ sessionProfiles.shutdown(context.sessionManager, event);
11163
+ }
10362
11164
  pinnedRddStatusLines.delete(pendingReviewConsentSessionKey(context, pendingReviewConsentFallbackKey));
10363
11165
  rddOffReviewLoadout = false;
10364
11166
  auto.reset();
@@ -10382,7 +11184,8 @@ function createGentleAiExtensionForTesting(
10382
11184
  cleanupAllPendingReviewConsents(pendingReviewConsentRegistry, sessionKey);
10383
11185
  processRetainedNativeStatusSelections.delete(sessionKey);
10384
11186
  processAgentEndSubagentDepth.delete(sessionKey);
10385
- });
11187
+ verifierSettleNamedRuns.delete(sessionKey);
11188
+ }
10386
11189
 
10387
11190
  // gentle-pi ODD input phase labels: the explicit half of the bounded ODD
10388
11191
  // phase signal for the Gentle prompt's working label. Gentle Shell infers
@@ -10747,6 +11550,17 @@ function createGentleAiExtensionForTesting(
10747
11550
  }));
10748
11551
 
10749
11552
  pi.on("session_start", async (event, ctx) => {
11553
+ const profileSessionId = ctx.sessionManager?.getSessionId?.();
11554
+ if (profileSessionId) clearSessionProfileBinding(profileSessionId);
11555
+ sessionProfiles.start(ctx.sessionManager, (type, data) => pi.appendEntry(type, data), event);
11556
+ // gentle-shell#2742: only a session's own start tells this process its
11557
+ // startup state; anything else leaves it unknown.
11558
+ try {
11559
+ if (profileSessionId && isSessionOwnStart(event, ctx.sessionManager))
11560
+ freezeSessionProfileAtOwnStart({ sessionId: profileSessionId, cwd: ctx.sessionManager.getCwd(), configHome: gentleAiConfigHome() });
11561
+ } catch { /* The startup state stays unknown. */ }
11562
+ readSessionProfileAuthority(ctx.sessionManager);
11563
+ if (ctx.hasUI) notifySessionProfileProblem(ctx);
10750
11564
  auto.reset();
10751
11565
  yolo.reset(ctx);
10752
11566
  // Package-owned children reset local state but never initialize primary defaults.
@@ -10858,11 +11672,13 @@ function createGentleAiExtensionForTesting(
10858
11672
  const isChildSession = permissionEnvironment.GENTLE_PI_AGENTS_CHILD === "1";
10859
11673
  const isPrimarySession = !isNamedAgent && !isChildSession;
10860
11674
  const subagentDepthKey = pendingReviewConsentSessionKey(ctx, pendingReviewConsentFallbackKey);
11675
+ if (isPrimarySession && !ctx.signal?.aborted) explorationBudget.start(subagentDepthKey);
10861
11676
  if (isNamedAgent || isChildSession) {
10862
11677
  processAgentEndSubagentDepth.set(subagentDepthKey, (processAgentEndSubagentDepth.get(subagentDepthKey) ?? 0) + 1);
10863
11678
  } else {
10864
11679
  processAgentEndSubagentDepth.set(subagentDepthKey, 0);
10865
11680
  }
11681
+ verifierSettleNamedRuns.set(subagentDepthKey, isPrimarySession ? 0 : (verifierSettleNamedRuns.get(subagentDepthKey) ?? 0) + 1);
10866
11682
  // gentle-pi#677: nudge gentle-ai's own telemetry trigger for a primary
10867
11683
  // session only, reusing the exact isNamedAgent predicate that
10868
11684
  // decides the orchestrator prompt below. At most one attempt per
@@ -10987,6 +11803,34 @@ function createGentleAiExtensionForTesting(
10987
11803
  consumeReviewMutation(pi, ctx.sessionManager, root, mutation, "nudged", targetIdentity);
10988
11804
  });
10989
11805
 
11806
+ // #2652: a primary run that declares `Risk: item N` in its final message and never attempted a verifier launch
11807
+ // gets one visible reminder and one continuation per user prompt. Earlier proposed entries are kept. The incoming
11808
+ // `canContinue` is false for a completed run (its last message is the assistant's); Pi re-validates the continuation
11809
+ // after the appended reminder, so it is not a precondition here.
11810
+ pi.on("agent_before_settle", (event, ctx) => {
11811
+ if (permissionEnvironment.GENTLE_PI_AGENTS_CHILD === "1") return undefined;
11812
+ const sessionKey = pendingReviewConsentSessionKey(ctx, pendingReviewConsentFallbackKey);
11813
+ if ((verifierSettleNamedRuns.get(sessionKey) ?? 0) > 0) return undefined;
11814
+ if (event.outcome !== "completed") return undefined;
11815
+ const reminder = verifierSettleReminders.beforeSettle(
11816
+ sessionKey,
11817
+ finalAssistantText(event.context.contextMessages),
11818
+ );
11819
+ if (reminder === undefined) return undefined;
11820
+ return {
11821
+ entries: [...event.entries, { type: "custom_message", customType: VERIFIER_SETTLE_REMINDER_TYPE, content: reminder, display: true }],
11822
+ continue: true,
11823
+ };
11824
+ });
11825
+
11826
+ pi.on("agent_settled", (_event, ctx) => {
11827
+ if (permissionEnvironment.GENTLE_PI_AGENTS_CHILD === "1") return;
11828
+ const sessionKey = pendingReviewConsentSessionKey(ctx, pendingReviewConsentFallbackKey);
11829
+ const namedRuns = verifierSettleNamedRuns.get(sessionKey) ?? 0;
11830
+ if (namedRuns > 0) verifierSettleNamedRuns.set(sessionKey, namedRuns - 1);
11831
+ else explorationBudget.settle(sessionKey);
11832
+ });
11833
+
10990
11834
  const recordWriteResult = async (event: ToolResultEvent, ctx: ExtensionContext): Promise<void> => {
10991
11835
  if (!reminderSessionActive || (reminderManager && reminderManager !== ctx.sessionManager) || event.isError !== false || (event.toolName !== "write" && event.toolName !== "edit")) return;
10992
11836
  if (!isRecord(event.input) || typeof event.input.path !== "string" || !event.input.path.trim()) return;
@@ -11016,6 +11860,12 @@ function createGentleAiExtensionForTesting(
11016
11860
  // so a crossing is announced on the next sampled result — never later than one window past it.
11017
11861
  const sessionKey = pendingReviewConsentSessionKey(ctx, pendingReviewConsentFallbackKey);
11018
11862
  const primary = permissionEnvironment.GENTLE_PI_AGENTS_CHILD !== "1" && (processAgentEndSubagentDepth.get(sessionKey) ?? 0) === 0;
11863
+ const explorationNotice = explorationBudget.result(sessionKey, event, primary, ctx.signal?.aborted === true);
11864
+ // Keep discovery payloads intact. Steer only an already-active run so the
11865
+ // next model step sees the notice without starting a new run while idle.
11866
+ if (explorationNotice && typeof ctx.isIdle === "function" && !ctx.isIdle()) {
11867
+ try { pi.sendMessage({ customType: "gentle-pi.exploration-budget", content: explorationNotice, details: explorationBudget.facts(sessionKey), display: true }, { deliverAs: "steer", triggerTurn: true }); } catch { /* Advisory only. */ }
11868
+ }
11019
11869
  let notice: string | undefined;
11020
11870
  try { notice = primary ? contextBackstopSignal(sessionKey, contextBackstopMeasure(sessionKey, () => ctx.getContextUsage?.())) : undefined; } catch { notice = undefined; }
11021
11871
  const withNotice = (patch: ToolResultEventResult | undefined) => notice ? appendContextBackstopNotice(event, patch, notice) : patch;
@@ -11036,6 +11886,9 @@ function createGentleAiExtensionForTesting(
11036
11886
  return { block: true, reason: `${event.toolName} runs only as a direct tool call: call it directly, never from codemode or another tool.` };
11037
11887
  }
11038
11888
  const primaryToolCall = permissionEnvironment.GENTLE_PI_AGENTS_CHILD !== "1" && (processAgentEndSubagentDepth.get(pendingReviewConsentSessionKey(ctx, pendingReviewConsentFallbackKey)) ?? 0) === 0;
11889
+ if (primaryToolCall && !ctx.signal?.aborted) explorationBudget.call(pendingReviewConsentSessionKey(ctx, pendingReviewConsentFallbackKey), event.toolCallId, event.toolName, event.parentToolCallId);
11890
+ // #2652: count a verifier launch attempt before any admission check can reject it.
11891
+ if (primaryToolCall) verifierSettleReminders.toolCall(pendingReviewConsentSessionKey(ctx, pendingReviewConsentFallbackKey), event.toolName, event.input);
11039
11892
  // One early mode read settles the session binding (and its one-time epoch
11040
11893
  // bump) before the guarded region below captures its own epoch.
11041
11894
  const settledMode = primaryToolCall ? await yolo.mode(ctx, { toolCallId: event.toolCallId }) : "normal";
@@ -11115,7 +11968,7 @@ function createGentleAiExtensionForTesting(
11115
11968
  }
11116
11969
 
11117
11970
  pi.registerCommand("gentle:profiles", {
11118
- description: "Open the models screen (profiles as tabs). Subcommands: export <name>, import, publish <name>, export-routing, restore-routing.",
11971
+ description: "Open the models screen (profiles as tabs). Subcommands: export <name>, import, publish <name>, export-routing, restore-routing, clear.",
11119
11972
  handler: async (args, ctx) => {
11120
11973
  await handleProfilesCommand(ctx, pi, typeof args === "string" ? args : "");
11121
11974
  },