gentle-pi 4.6.0 → 4.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (290) hide show
  1. package/README.md +10 -11
  2. package/assets/agents/gentle-ai-explore.md +1 -0
  3. package/assets/agents/gentle-ai-verify.md +5 -2
  4. package/assets/agents/gentle-ai-worker.md +3 -0
  5. package/assets/agents/jd-fix-agent.md +1 -0
  6. package/assets/agents/jd-judge-a.md +1 -0
  7. package/assets/agents/jd-judge-b.md +1 -0
  8. package/assets/design-canvas/canvas.css +13 -1
  9. package/assets/design-canvas/canvas.js +11 -2
  10. package/assets/install-wizard/wizard.js +1 -0
  11. package/assets/migrations/agent-body-history.json +16 -1
  12. package/assets/orchestrator-delegation-reference.md +4 -4
  13. package/assets/orchestrator-delegation.md +1 -1
  14. package/assets/orchestrator-full-delegation-card.md +65 -0
  15. package/assets/orchestrator-full-delegation.md +34 -0
  16. package/assets/orchestrator-memory.md +3 -3
  17. package/assets/orchestrator-prompts.md +1 -1
  18. package/assets/orchestrator-skills.md +1 -1
  19. package/assets/orchestrator-verification.md +7 -5
  20. package/assets/orchestrator.md +3 -3
  21. package/bin/gentle-shell.mjs +164 -56
  22. package/docs/agent-status.md +61 -0
  23. package/docs/bundled-install.md +7 -5
  24. package/docs/delegated-verification.md +29 -7
  25. package/docs/gentle-agents-activity.md +14 -0
  26. package/docs/gentle-shell.md +54 -16
  27. package/docs/install-wizard.md +1 -1
  28. package/docs/permission-modes.md +9 -4
  29. package/docs/readme-reference.md +75 -30
  30. package/docs/render-cache-performance.md +11 -1
  31. package/docs/review-coordinator.md +33 -0
  32. package/docs/review-request-context.md +19 -0
  33. package/docs/review-windows-acl.md +18 -0
  34. package/docs/voice.md +6 -3
  35. package/docs/yolo-mode.md +5 -5
  36. package/extensions/ask-user-choice.ts +1 -0
  37. package/extensions/ask-user-question.ts +1 -0
  38. package/extensions/child-safety.ts +3 -0
  39. package/extensions/gentle-agent-status.ts +99 -0
  40. package/extensions/gentle-agents.ts +326 -34
  41. package/extensions/gentle-ai.ts +1496 -454
  42. package/extensions/gentle-shell.ts +293 -63
  43. package/extensions/gentle-todo.ts +18 -2
  44. package/extensions/gentle-tps.ts +48 -0
  45. package/extensions/quiet-tools.ts +38 -8
  46. package/extensions/skill-registry.ts +175 -18
  47. package/extensions/startup-banner.ts +30 -3
  48. package/lib/agent-profile-pin.ts +3 -3
  49. package/lib/agent-profiles.ts +160 -2
  50. package/lib/agent-status.ts +105 -0
  51. package/lib/agents-config.ts +46 -0
  52. package/lib/agents-history.ts +24 -5
  53. package/lib/agents-messaging.ts +47 -5
  54. package/lib/agents-runner.ts +183 -12
  55. package/lib/auto-permission-runtime.ts +1 -1
  56. package/lib/bounded-writer-admission.ts +13 -1
  57. package/lib/card-content-policy.ts +8 -6
  58. package/lib/command-palette.ts +133 -17
  59. package/lib/context-backstop.ts +14 -5
  60. package/lib/destructive-command-guard.ts +48 -4
  61. package/lib/execution-surface-guard.ts +20 -0
  62. package/lib/exploration-budget.ts +4 -2
  63. package/lib/gentle-ai-binary.ts +1 -1
  64. package/lib/gentle-design.ts +3 -0
  65. package/lib/gentle-shell-bundled.ts +6 -19
  66. package/lib/gentle-shell-launcher.ts +43 -8
  67. package/lib/herdr-activity.ts +14 -2
  68. package/lib/herdr-busy.ts +45 -0
  69. package/lib/image-attachments.ts +33 -0
  70. package/lib/image-disk-cache.ts +137 -0
  71. package/lib/inprocess-reviewer.ts +270 -140
  72. package/lib/jobs-view.ts +198 -11
  73. package/lib/model-routing-authority.ts +22 -4
  74. package/lib/native-choice-list.ts +20 -2
  75. package/lib/native-review-cli.ts +96 -19
  76. package/lib/orchestrator-mode-policy.ts +105 -0
  77. package/lib/questionnaire/questionnaire-view.ts +105 -12
  78. package/lib/rdd-mode-control.ts +32 -0
  79. package/lib/reply-language-anchor.ts +104 -0
  80. package/lib/review-blocker.ts +92 -0
  81. package/lib/review-candidate-symlink-scan.ts +136 -0
  82. package/lib/review-candidate-view-owner.ts +81 -44
  83. package/lib/review-continuation-registry.ts +99 -0
  84. package/lib/review-coordinator.ts +163 -0
  85. package/lib/review-failure-facts.ts +49 -0
  86. package/lib/review-host-relay.ts +46 -10
  87. package/lib/review-integration-v2.ts +7 -1
  88. package/lib/review-relay-phase-timing.ts +45 -0
  89. package/lib/review-start-context.ts +17 -0
  90. package/lib/session-profile-freeze.ts +4 -2
  91. package/lib/shell-bar.ts +140 -58
  92. package/lib/shell-changes.ts +2 -0
  93. package/lib/shell-panel.ts +17 -3
  94. package/lib/shell-sidebar-layout.ts +112 -40
  95. package/lib/shell-sidebar.ts +7 -0
  96. package/lib/shell-todo.ts +10 -3
  97. package/lib/verifier-admission.ts +1 -1
  98. package/lib/visual-customization-policy.ts +36 -16
  99. package/lib/visual-customize-view.ts +216 -21
  100. package/lib/visual-layout-preview.ts +9 -5
  101. package/lib/visual-profiles.ts +2 -2
  102. package/lib/windows-session-transport.ts +53 -2
  103. package/lib/yolo-session-policy.ts +40 -15
  104. package/package.json +2 -1
  105. package/runtime/gentle-ai-binary.mjs +1 -1
  106. package/runtime/gentle-shell-bundled.mjs +6 -19
  107. package/runtime/gentle-shell-launcher.mjs +42 -7
  108. package/runtime/native-review-cli.mjs +93 -16
  109. package/runtime/review-integration-v2.mjs +7 -1
  110. package/scripts/build-full-delegation-card.mjs +175 -0
  111. package/scripts/bundled-install.mjs +38 -8
  112. package/scripts/download-progress.mjs +68 -0
  113. package/scripts/gentle-ai-installer.mjs +41 -18
  114. package/scripts/gentle-ai-proxy.mjs +294 -0
  115. package/scripts/install-gentle-ai.mjs +14 -1
  116. package/scripts/installer-preflight.mjs +5 -5
  117. package/scripts/installer-runner.mjs +27 -12
  118. package/scripts/installer-server.mjs +8 -7
  119. package/scripts/render-cache-host.mjs +72 -0
  120. package/scripts/render-cache-performance-worker.mjs +5 -4
  121. package/scripts/render-cache-performance.mjs +6 -1
  122. package/scripts/run-test-suite.mjs +40 -28
  123. package/scripts/verify-package-files.mjs +12 -2
  124. package/scripts/voice-worker.cjs +32 -6
  125. package/skills/design/SKILL.md +11 -8
  126. package/skills/gentle-ai/SKILL.md +2 -2
  127. package/skills/gentle-ui-design/SKILL.md +46 -0
  128. package/skills/gentle-ui-design/references/adaptive-interfaces.md +46 -0
  129. package/skills/gentle-ui-design/references/browse-and-compare.md +62 -0
  130. package/skills/gentle-ui-design/references/composition-and-feedback.md +56 -0
  131. package/skills/gentle-ui-design/references/task-and-content.md +60 -0
  132. package/skills/skill-registry/SKILL.md +4 -2
  133. package/skills/work-unit-commits/SKILL.md +6 -7
  134. package/tests/agent-home.test.ts +28 -9
  135. package/tests/agent-profiles-workflow.test.ts +163 -0
  136. package/tests/agent-risk-escalation.test.ts +1 -1
  137. package/tests/agent-status.test.ts +143 -0
  138. package/tests/agents-config.test.ts +96 -0
  139. package/tests/agents-history.test.ts +31 -0
  140. package/tests/agents-jobs-frames.test.ts +93 -0
  141. package/tests/agents-prompt-lifecycle-runtime.test.ts +376 -0
  142. package/tests/agents-runner-drain.test.ts +193 -0
  143. package/tests/agents-runner.test.ts +178 -2
  144. package/tests/append-system-prompt-route.test.ts +4 -1
  145. package/tests/ask-user-choice.test.ts +4 -3
  146. package/tests/ask-user-question.test.ts +97 -0
  147. package/tests/auto-permission-runtime.test.ts +1 -1
  148. package/tests/autonomous-guard.test.ts +346 -10
  149. package/tests/bounded-stop-contract.test.ts +43 -3
  150. package/tests/bridge-cost.test.ts +19 -4
  151. package/tests/bundled-install.test.ts +30 -5
  152. package/tests/card-content-policy.test.ts +3 -3
  153. package/tests/chained-pr-skill.test.ts +8 -6
  154. package/tests/child-safety.test.ts +11 -0
  155. package/tests/codegraph-tools.test.ts +11 -5
  156. package/tests/command-palette.test.ts +284 -1
  157. package/tests/delegate-for-reason-contract.test.ts +3 -3
  158. package/tests/design-canvas-assets.test.ts +185 -2
  159. package/tests/destructive-command-guard.test.ts +52 -0
  160. package/tests/download-progress.test.ts +71 -0
  161. package/tests/execution-surface-guard.test.ts +55 -0
  162. package/tests/fixtures/primary-session-prompt/gentleman.golden.md +9 -5
  163. package/tests/fixtures/proxy-tls/proxy.crt +19 -0
  164. package/tests/fixtures/proxy-tls/proxy.key +28 -0
  165. package/tests/fixtures/session-profile-v1/gentle-ai-reviewer.ts +89 -0
  166. package/tests/fixtures/session-profile-v1/replay.ts +53 -6
  167. package/tests/full-delegation-closure.test.ts +131 -0
  168. package/tests/full-delegation-notices.test.ts +76 -0
  169. package/tests/generic-agent-tools.test.ts +3 -3
  170. package/tests/gentle-agent-status.test.ts +74 -0
  171. package/tests/gentle-agents-child-jobs.test.ts +237 -0
  172. package/tests/gentle-agents.test.ts +1070 -12
  173. package/tests/gentle-ai-binary.test.ts +3 -1
  174. package/tests/gentle-ai-elapsed-store.test.ts +19 -0
  175. package/tests/gentle-ai-exploration-budget.test.ts +18 -2
  176. package/tests/gentle-ai-installer.test.ts +134 -51
  177. package/tests/gentle-ai-proxy.test.ts +434 -0
  178. package/tests/gentle-ai.test.ts +113 -38
  179. package/tests/gentle-design.test.ts +21 -0
  180. package/tests/gentle-herdr-activity.test.ts +9 -6
  181. package/tests/gentle-shell-bin.test.ts +123 -0
  182. package/tests/gentle-shell-bundled.test.ts +207 -31
  183. package/tests/gentle-shell-launcher.test.ts +77 -10
  184. package/tests/gentle-shell.test.ts +899 -59
  185. package/tests/gentle-todo.test.ts +19 -2
  186. package/tests/gentle-tps.test.ts +123 -0
  187. package/tests/gentle-ui-design-skill.test.ts +59 -0
  188. package/tests/herdr-busy.test.ts +59 -0
  189. package/tests/herdr-task-summary-policy.test.ts +8 -4
  190. package/tests/image-disk-cache.test.ts +163 -0
  191. package/tests/independent-recovery-delivery.test.ts +83 -0
  192. package/tests/inprocess-reviewer.test.ts +176 -4
  193. package/tests/installer-posix-bootstrap.test.ts +1 -1
  194. package/tests/installer-preflight.test.ts +5 -4
  195. package/tests/installer-runner.test.ts +79 -44
  196. package/tests/installer-server.test.ts +14 -11
  197. package/tests/jobs-view.test.ts +260 -6
  198. package/tests/modal-mouse-boundaries.test.ts +136 -0
  199. package/tests/model-routing-authority.test.ts +178 -2
  200. package/tests/native-choice-list.test.ts +77 -2
  201. package/tests/native-review-capability-contract.test.ts +7 -1
  202. package/tests/native-review-cli.test.ts +269 -1
  203. package/tests/no-self-pause-contract.test.ts +4 -1
  204. package/tests/odd-routing-canonical-ratchet.test.ts +3 -3
  205. package/tests/orchestrator-budget.test.ts +7 -2
  206. package/tests/orchestrator-delegation-mode.test.ts +153 -0
  207. package/tests/orchestrator-mode-policy.test.ts +175 -0
  208. package/tests/orchestrator-prompt-budget.test.ts +3 -1
  209. package/tests/orchestrator-rdd-ownership.test.ts +2 -2
  210. package/tests/package-manifest.test.ts +11 -9
  211. package/tests/permission-allowlist.test.ts +202 -0
  212. package/tests/pi-update-launcher.test.ts +8 -0
  213. package/tests/pnpm-workspace-config.test.ts +58 -0
  214. package/tests/primary-session-prompt.test.ts +13 -0
  215. package/tests/profile-pin.test.ts +29 -2
  216. package/tests/profile-tier-footer.test.ts +5 -0
  217. package/tests/profiles-panel-delegation-mode.test.ts +422 -0
  218. package/tests/questionnaire-view.test.ts +115 -0
  219. package/tests/quiet-bash-runtime.test.ts +1 -1
  220. package/tests/quiet-tool-rendering.test.ts +48 -0
  221. package/tests/rdd-aware-verification-contract.test.ts +16 -11
  222. package/tests/rdd-customize.test.ts +287 -0
  223. package/tests/rdd-mode-cache.test.ts +450 -0
  224. package/tests/rdd-mode-control.test.ts +407 -0
  225. package/tests/rdd-mode-scope-regression.test.ts +137 -0
  226. package/tests/rdd-off-independent-regression.test.ts +69 -0
  227. package/tests/rdd-status-line.test.ts +18 -0
  228. package/tests/render-cache-performance.test.ts +171 -2
  229. package/tests/reply-language-anchor.test.ts +173 -0
  230. package/tests/review-agent-end-preflight.test.ts +1 -1
  231. package/tests/review-blocker.test.ts +193 -0
  232. package/tests/review-candidate-owner-retry.test.ts +1 -1
  233. package/tests/review-candidate-symlink-scan.test.ts +157 -0
  234. package/tests/review-candidate-view.test.ts +1 -1
  235. package/tests/review-candidate-windows-boundary.test.ts +131 -0
  236. package/tests/review-candidate-windows-probe.test.ts +63 -0
  237. package/tests/review-committed-restart-ack.test.ts +129 -0
  238. package/tests/review-continuation-registry.test.ts +76 -0
  239. package/tests/review-controller-native-routing.test.ts +261 -5
  240. package/tests/review-controller-workspace-root.test.ts +230 -3
  241. package/tests/review-controller.test.ts +96 -11
  242. package/tests/review-coordinator-runtime.test.ts +117 -0
  243. package/tests/review-coordinator.test.ts +195 -0
  244. package/tests/review-failure-facts.test.ts +87 -0
  245. package/tests/review-host-relay-routing.test.ts +258 -4
  246. package/tests/review-host-relay.test.ts +39 -0
  247. package/tests/review-integration-v2.test.ts +46 -3
  248. package/tests/review-json-arguments.test.ts +65 -10
  249. package/tests/review-last-event-closure.test.ts +68 -0
  250. package/tests/review-loadout-rdd-off-sdk.test.ts +65 -31
  251. package/tests/review-owner-identity.test.ts +60 -24
  252. package/tests/review-relay-phase-timing.test.ts +128 -0
  253. package/tests/review-relay-transport-agent.test.ts +12 -2
  254. package/tests/review-reviewer-evidence.test.ts +183 -0
  255. package/tests/review-risk-assessment.test.ts +74 -3
  256. package/tests/review-session-standing-permission-controller.test.ts +21 -1
  257. package/tests/review-start-context.test.ts +19 -0
  258. package/tests/review-tool-prose-budget.test.ts +121 -0
  259. package/tests/run-test-suite.test.ts +122 -1
  260. package/tests/runtime-harness.mjs +4 -1
  261. package/tests/sensitive-path-tools.test.ts +181 -5
  262. package/tests/session-profile-append-controller-pi.test.ts +60 -31
  263. package/tests/session-profile-binding.test.ts +19 -1
  264. package/tests/session-profile-disk-reader-pi.test.ts +58 -16
  265. package/tests/session-profile-v1-compat.test.ts +35 -1
  266. package/tests/shell-bar.test.ts +186 -42
  267. package/tests/shell-panel.test.ts +50 -22
  268. package/tests/shell-sidebar-fullscreen.test.ts +5 -5
  269. package/tests/shell-sidebar-layout.test.ts +294 -23
  270. package/tests/shell-sidebar-scroll-benchmark.test.ts +1 -1
  271. package/tests/shell-surface-transparent.test.ts +89 -0
  272. package/tests/shell-todo.test.ts +12 -0
  273. package/tests/skill-registry.test.ts +838 -5
  274. package/tests/startup-banner.test.ts +152 -1
  275. package/tests/startup-home-repo.test.ts +2 -0
  276. package/tests/support/review-coordinator-runtime.ts +69 -0
  277. package/tests/task-size-routing-contract.test.ts +5 -3
  278. package/tests/verifier-admission.test.ts +49 -0
  279. package/tests/verify-first-launch-contract.test.ts +78 -3
  280. package/tests/visual-customization-policy.test.ts +39 -6
  281. package/tests/visual-customize-view.test.ts +573 -9
  282. package/tests/visual-layout-preview.test.ts +15 -1
  283. package/tests/visual-profiles.test.ts +11 -0
  284. package/tests/voice-worker.test.ts +73 -2
  285. package/tests/windows-session-transport.test.ts +126 -0
  286. package/tests/work-continuity-contract.test.ts +28 -0
  287. package/tests/writer-feature-document-admission.test.ts +92 -0
  288. package/tests/yolo-customize.test.ts +27 -4
  289. package/tests/yolo-mode.test.ts +23 -18
  290. package/tests/yolo-session-policy.test.ts +270 -1
@@ -17,7 +17,6 @@ Use it for:
17
17
  - Preparing commits before opening a PR.
18
18
  - Turning a large change into chained or stacked PRs.
19
19
  - Keeping reviewer cognitive load healthy.
20
- - Applying SDD tasks without accidentally producing a PR above 400 changed lines.
21
20
  - Committing ODD work in reviewable slices of about 400 authored changed lines.
22
21
 
23
22
  ## Critical Rules
@@ -30,7 +29,7 @@ Use it for:
30
29
  | Keep docs with the user-visible change | Docs belong with the feature or workflow they explain. |
31
30
  | Tell a story | A reviewer should understand why each commit exists from its diff and message. |
32
31
  | Future PR-ready | Each commit should be a candidate chained PR when the change grows. |
33
- | SDD workload guard | If SDD tasks forecast a >400-line change, honor the selected `delivery_strategy`. On chaining paths only, group commits into chained PR slices before implementation. For explicit `single-pr` or `exception-ok`, keep one PR, report the review load, and follow the destination repository's documented contribution/size policy; selection alone does not accept an exception. |
32
+ | Delivery workload guard | If the task forecast produces a >400-line change, honor the selected `delivery_strategy`. On chaining paths only, group commits into chained PR slices before implementation. For explicit `single-pr` or `exception-ok`, keep one PR, report the review load, and follow the destination repository's documented contribution/size policy; selection alone does not accept an exception. |
34
33
  | Budget is not code-golf | Never shrink a diff by deleting comments, blank lines, docs, or tests, or by compressing code, to fit the review budget (400 by default, or the session `review_budget_lines`). Slice by work unit or report the overage. |
35
34
 
36
35
  ## Work Unit Checklist
@@ -61,17 +60,17 @@ Use work-unit commits as the foundation for chained PRs:
61
60
  3. Commit it with a Conventional Commit message.
62
61
  4. If the PR approaches 400 changed lines, promote commits or groups of commits into chained PRs.
63
62
 
64
- ## SDD Relationship
63
+ ## Delivery And Budget
65
64
 
66
- When `sdd-tasks` produces a Review Workload Forecast:
65
+ The chosen `delivery_strategy` governs how commits group into PRs, and the budget constrains how work is sliced, never the code itself.
67
66
 
68
67
  - Low risk: keep work-unit commits inside one PR.
69
68
  - Medium risk: commit by work unit and monitor changed lines before PR creation.
70
- - High risk: follow SDD `delivery_strategy` — ask on `ask-on-risk`, auto-slice with the cached chain choice on `auto-chain`, follow the destination repository's documented contribution/size policy on over-budget `single-pr`, or record an explicitly accepted policy exception on `exception-ok`. A single-PR selection does not itself accept an exception.
69
+ - High risk: follow the selected `delivery_strategy` — ask on `ask-on-risk`, auto-slice with the cached chain choice on `auto-chain`, follow the destination repository's documented contribution/size policy on over-budget `single-pr`, or record an explicitly accepted policy exception on `exception-ok`. A single-PR selection does not itself accept an exception.
71
70
  - `size:exception` is a Gentle-owned repository policy, not a universal label requirement. Never request, create, or add the label for generic users unless the destination policy uses it; preserve its maintainer acceptance and protected-label authorization gates.
72
71
  - Splitting is bounded: after one honest slicing pass, if no cohesive work-unit split fits the budget, stop and report the smallest honest count and rationale. Recommend an exception only where destination policy provides it. Do not iterate shrinking the code to reach the number.
73
72
 
74
- Each SDD work unit should map cleanly to a commit or PR with:
73
+ Each work unit should map cleanly to a commit or PR with:
75
74
 
76
75
  - clear start state,
77
76
  - clear finished state,
@@ -85,7 +84,7 @@ ODD commits work units in reviewable slices of about 400 authored changed lines,
85
84
  - A slice holds one or more whole tasks with their tests and docs; the last slice closes the feature.
86
85
  - A unit whose Risk line names a high-risk item gets its own commit, so native review takes it alone.
87
86
  - The native review candidate is that commit, or the PR slice it belongs to when review is deferred, evaluated against the previous reviewed boundary.
88
- - The running authored line count from work-unit commits feeds the same delivery-strategy vocabulary as SDD.
87
+ - The running authored line count from work-unit commits feeds the delivery-strategy vocabulary.
89
88
  - The feature document records the commit that holds each task and, once a delivery strategy applies, the slice boundaries.
90
89
 
91
90
  ## Commands
@@ -17,8 +17,10 @@ function isolatedHome(t: test.TestContext): string {
17
17
  const previousHome = process.env.HOME;
18
18
  const previousUserProfile = process.env.USERPROFILE;
19
19
  const previousConfigHome = process.env.GENTLE_PI_CONFIG_HOME;
20
- // Clear the higher-priority config override as well as isolating both OS homes.
20
+ const previousShellConfigHome = process.env.GENTLE_SHELL_CONFIG_HOME;
21
+ // Clear both config overrides as well as isolating both OS homes.
21
22
  delete process.env.GENTLE_PI_CONFIG_HOME;
23
+ delete process.env.GENTLE_SHELL_CONFIG_HOME;
22
24
  process.env.HOME = home;
23
25
  process.env.USERPROFILE = home;
24
26
  t.after(() => {
@@ -28,6 +30,8 @@ function isolatedHome(t: test.TestContext): string {
28
30
  else process.env.USERPROFILE = previousUserProfile;
29
31
  if (previousConfigHome === undefined) delete process.env.GENTLE_PI_CONFIG_HOME;
30
32
  else process.env.GENTLE_PI_CONFIG_HOME = previousConfigHome;
33
+ if (previousShellConfigHome === undefined) delete process.env.GENTLE_SHELL_CONFIG_HOME;
34
+ else process.env.GENTLE_SHELL_CONFIG_HOME = previousShellConfigHome;
31
35
  rmSync(home, { recursive: true, force: true });
32
36
  });
33
37
  return home;
@@ -47,21 +51,36 @@ test("gentlePiConfigHome honours GENTLE_PI_CONFIG_HOME and otherwise falls back
47
51
  });
48
52
 
49
53
  test("the isolated home restores defined and undefined config overrides", async (t) => {
50
- const previousConfigHome = process.env.GENTLE_PI_CONFIG_HOME;
54
+ const previous = {
55
+ HOME: process.env.HOME,
56
+ USERPROFILE: process.env.USERPROFILE,
57
+ GENTLE_PI_CONFIG_HOME: process.env.GENTLE_PI_CONFIG_HOME,
58
+ GENTLE_SHELL_CONFIG_HOME: process.env.GENTLE_SHELL_CONFIG_HOME,
59
+ };
60
+ const config = join(tmpdir(), "synthetic-inherited-config");
61
+ const marker = join(tmpdir(), "synthetic-inherited-marker");
51
62
  try {
52
- for (const inherited of [undefined, "/synthetic-inherited-config"]) {
53
- if (inherited === undefined) delete process.env.GENTLE_PI_CONFIG_HOME;
54
- else process.env.GENTLE_PI_CONFIG_HOME = inherited;
55
- await t.test(`inherited override: ${inherited === undefined ? "unset" : "set"}`, (child) => {
63
+ for (const [pi, shell] of [[undefined, undefined], [config, marker], [undefined, marker], [config, undefined]]) {
64
+ if (pi === undefined) delete process.env.GENTLE_PI_CONFIG_HOME;
65
+ else process.env.GENTLE_PI_CONFIG_HOME = pi;
66
+ if (shell === undefined) delete process.env.GENTLE_SHELL_CONFIG_HOME;
67
+ else process.env.GENTLE_SHELL_CONFIG_HOME = shell;
68
+ await t.test(`inherited pi ${pi === undefined ? "unset" : "set"}, shell ${shell === undefined ? "unset" : "set"}`, (child) => {
56
69
  const home = isolatedHome(child);
57
70
  assert.equal(process.env.GENTLE_PI_CONFIG_HOME, undefined);
71
+ assert.equal(process.env.GENTLE_SHELL_CONFIG_HOME, undefined);
58
72
  assert.equal(gentlePiConfigHome(), join(home, ".pi", "gentle-ai"));
59
73
  });
60
- assert.equal(process.env.GENTLE_PI_CONFIG_HOME, inherited);
74
+ assert.equal(process.env.GENTLE_PI_CONFIG_HOME, pi);
75
+ assert.equal(process.env.GENTLE_SHELL_CONFIG_HOME, shell);
76
+ assert.equal(process.env.HOME, previous.HOME);
77
+ assert.equal(process.env.USERPROFILE, previous.USERPROFILE);
61
78
  }
62
79
  } finally {
63
- if (previousConfigHome === undefined) delete process.env.GENTLE_PI_CONFIG_HOME;
64
- else process.env.GENTLE_PI_CONFIG_HOME = previousConfigHome;
80
+ for (const [key, value] of Object.entries(previous)) {
81
+ if (value === undefined) delete process.env[key];
82
+ else process.env[key] = value;
83
+ }
65
84
  }
66
85
  });
67
86
 
@@ -0,0 +1,163 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+
4
+ import {
5
+ DEFAULT_ORCHESTRATOR_MODE,
6
+ ORCHESTRATOR_MODES,
7
+ readProfileWorkflow,
8
+ normalizeProfilesFile,
9
+ serializeProfilesFile,
10
+ parseProfilesFileText,
11
+ emptyProfilesFile,
12
+ createProfile,
13
+ duplicateProfile,
14
+ renameProfile,
15
+ deleteProfile,
16
+ setProfileOrchestratorMode,
17
+ type AgentProfilesFile,
18
+ } from "../lib/agent-profiles.ts";
19
+
20
+ // ---------------------------------------------------------------------------
21
+ // full-delegation-mode S1/S2/S6: the per-profile orchestrator workflow flag.
22
+ //
23
+ // The flag cannot live inside a profile's routing entries: normalizeProfilesFile
24
+ // runs every profile through normalizeModelConfig, whose contract is
25
+ // Record<string, AgentRoutingEntry>, so a nested non-routing key is dropped on
26
+ // read and reported as a broken role. It therefore travels in a sibling
27
+ // `workflow` map keyed by profile name, and these tests lock that contract.
28
+ // ---------------------------------------------------------------------------
29
+
30
+ function fileWith(workflow?: AgentProfilesFile["workflow"]): AgentProfilesFile {
31
+ const base = createProfile(emptyProfilesFile(), "frontier-local", {
32
+ orchestrator: { model: "claude-opus-4-6", thinking: "high" },
33
+ worker: { model: "local/qwen3-coder" },
34
+ });
35
+ const withSecond = createProfile(base, "normal", { orchestrator: { model: "gpt-5.4" } });
36
+ return workflow === undefined ? withSecond : { ...withSecond, workflow };
37
+ }
38
+
39
+ test("a profile with no workflow entry resolves to the organic default", () => {
40
+ assert.equal(DEFAULT_ORCHESTRATOR_MODE, "organic");
41
+ const file = fileWith();
42
+ assert.equal(readProfileWorkflow(file, "normal").orchestratorMode, "organic");
43
+ assert.equal(file.workflow, undefined, "an opted-out file must not gain a workflow map");
44
+ });
45
+
46
+ test("the store round-trips a full-delegation profile without touching its routing", () => {
47
+ const file = setProfileOrchestratorMode(fileWith(), "frontier-local", "full-delegation");
48
+ const text = serializeProfilesFile(file);
49
+ const parsed = parseProfilesFileText(text);
50
+ assert.equal(parsed.status, "valid");
51
+ if (parsed.status !== "valid") return;
52
+ assert.equal(readProfileWorkflow(parsed.file, "frontier-local").orchestratorMode, "full-delegation");
53
+ assert.equal(readProfileWorkflow(parsed.file, "normal").orchestratorMode, "organic");
54
+ // The routing contract is unchanged: the profile still holds only role entries.
55
+ assert.deepEqual(Object.keys(parsed.file.profiles["frontier-local"]).sort(), ["orchestrator", "worker"]);
56
+ assert.equal(parsed.file.profiles["frontier-local"].worker.model, "local/qwen3-coder");
57
+ assert.deepEqual(normalizeProfilesFile(JSON.parse(text))?.drops, { droppedProfiles: [], droppedAgents: [] });
58
+ });
59
+
60
+ test("every declared mode round-trips and nothing else is accepted", () => {
61
+ assert.deepEqual([...ORCHESTRATOR_MODES], ["organic", "full-delegation"]);
62
+ for (const mode of ORCHESTRATOR_MODES) {
63
+ const file = setProfileOrchestratorMode(fileWith(), "normal", mode);
64
+ const parsed = parseProfilesFileText(serializeProfilesFile(file));
65
+ assert.equal(parsed.status, "valid");
66
+ if (parsed.status !== "valid") continue;
67
+ assert.equal(readProfileWorkflow(parsed.file, "normal").orchestratorMode, mode);
68
+ }
69
+ });
70
+
71
+ test("an unknown mode is dropped and reported, never silently honoured", () => {
72
+ const normalized = normalizeProfilesFile({
73
+ kind: "gentle-pi.agent_model_profiles",
74
+ version: 1,
75
+ profiles: { normal: { orchestrator: { model: "gpt-5.4" } } },
76
+ workflow: { normal: { orchestratorMode: "super-delegation" } },
77
+ });
78
+ assert.ok(normalized);
79
+ assert.equal(readProfileWorkflow(normalized.file, "normal").orchestratorMode, "organic");
80
+ assert.deepEqual(normalized.drops.droppedWorkflow, [
81
+ { profile: "normal", mode: "super-delegation" },
82
+ ]);
83
+ });
84
+
85
+ test("a workflow entry naming a profile that does not exist is dropped and reported", () => {
86
+ const normalized = normalizeProfilesFile({
87
+ kind: "gentle-pi.agent_model_profiles",
88
+ version: 1,
89
+ profiles: { normal: { orchestrator: { model: "gpt-5.4" } } },
90
+ workflow: { ghost: { orchestratorMode: "full-delegation" } },
91
+ });
92
+ assert.ok(normalized);
93
+ assert.equal(normalized.file.workflow, undefined);
94
+ assert.deepEqual(normalized.drops.droppedWorkflow, [
95
+ { profile: "ghost", mode: "full-delegation" },
96
+ ]);
97
+ });
98
+
99
+ test("a malformed workflow map is dropped as a whole and never breaks the routing read", () => {
100
+ for (const workflow of [null, 42, "full-delegation", [] as unknown]) {
101
+ const normalized = normalizeProfilesFile({
102
+ kind: "gentle-pi.agent_model_profiles",
103
+ version: 1,
104
+ profiles: { normal: { orchestrator: { model: "gpt-5.4" } } },
105
+ workflow,
106
+ });
107
+ assert.ok(normalized, `workflow=${JSON.stringify(workflow)} must not invalidate the file`);
108
+ assert.equal(normalized.file.workflow, undefined);
109
+ assert.deepEqual(Object.keys(normalized.file.profiles), ["normal"]);
110
+ }
111
+ });
112
+
113
+ test("duplicate carries the mode, rename moves it, delete removes it", () => {
114
+ const withMode = setProfileOrchestratorMode(fileWith(), "frontier-local", "full-delegation");
115
+
116
+ const duplicated = duplicateProfile(withMode, "frontier-local", "frontier-local-copy");
117
+ assert.equal(readProfileWorkflow(duplicated, "frontier-local-copy").orchestratorMode, "full-delegation");
118
+ assert.equal(readProfileWorkflow(duplicated, "frontier-local").orchestratorMode, "full-delegation");
119
+
120
+ const renamed = renameProfile(duplicated, "frontier-local", "frontier-renamed");
121
+ assert.equal(readProfileWorkflow(renamed, "frontier-renamed").orchestratorMode, "full-delegation");
122
+ assert.equal(
123
+ renamed.workflow === undefined ? undefined : Object.hasOwn(renamed.workflow, "frontier-local"),
124
+ false,
125
+ "the old profile name must not keep a workflow entry",
126
+ );
127
+
128
+ const deleted = deleteProfile(renamed, "frontier-renamed");
129
+ assert.equal(
130
+ deleted.workflow === undefined ? undefined : Object.hasOwn(deleted.workflow, "frontier-renamed"),
131
+ false,
132
+ "a deleted profile must not leave a workflow entry behind",
133
+ );
134
+ // Everything else keeps its own mode across those rewrites.
135
+ assert.equal(readProfileWorkflow(deleted, "frontier-local-copy").orchestratorMode, "full-delegation");
136
+ });
137
+
138
+ test("serialization omits an empty workflow map and keeps the file head-stable", () => {
139
+ const file = setProfileOrchestratorMode(fileWith(), "normal", "organic");
140
+ const text = serializeProfilesFile(file);
141
+ assert.equal(text.includes("\"workflow\""), false, "an all-organic file must serialize exactly as before");
142
+ const parsed = parseProfilesFileText(text);
143
+ assert.equal(parsed.status, "valid");
144
+ });
145
+
146
+ test("dropping an unknown mode does not disturb an existing valid entry", () => {
147
+ const normalized = normalizeProfilesFile({
148
+ kind: "gentle-pi.agent_model_profiles",
149
+ version: 1,
150
+ profiles: {
151
+ normal: { orchestrator: { model: "gpt-5.4" } },
152
+ "frontier-local": { orchestrator: { model: "claude-opus-4-6" } },
153
+ },
154
+ workflow: {
155
+ normal: { orchestratorMode: "nope" },
156
+ "frontier-local": { orchestratorMode: "full-delegation" },
157
+ },
158
+ });
159
+ assert.ok(normalized);
160
+ assert.equal(readProfileWorkflow(normalized.file, "frontier-local").orchestratorMode, "full-delegation");
161
+ assert.equal(readProfileWorkflow(normalized.file, "normal").orchestratorMode, "organic");
162
+ assert.deepEqual(normalized.drops.droppedWorkflow, [{ profile: "normal", mode: "nope" }]);
163
+ });
@@ -62,7 +62,7 @@ function assessTool(nativeRisk: "passive" | "medium" | "high" = "medium"): { exe
62
62
  const tools = new Map<string, any>();
63
63
  const pi = { on() {}, registerCommand() {}, registerTool(tool: { name: string }) { tools.set(tool.name, tool); } } as unknown as ExtensionAPI;
64
64
  const nativeReviewCli: Partial<NativeReviewCli> = {
65
- reviewMode: async () => ({ operation: "status", scope: "clone", status: { global: "off", cloneLocal: "off", effective: "off", source: NATIVE_REVIEW_MODE_SOURCE.GLOBAL } }),
65
+ reviewMode: async () => ({ operation: "status", scope: "clone", status: { global: "on", cloneLocal: "", effective: "on", source: NATIVE_REVIEW_MODE_SOURCE.GLOBAL } }),
66
66
  assess: async () => ({
67
67
  schema: REVIEW_ASSESSMENT_SCHEMA,
68
68
  risk: nativeRisk,
@@ -0,0 +1,143 @@
1
+ import assert from "node:assert/strict";
2
+ import test, { after } from "node:test";
3
+ import { spawnSync } from "node:child_process";
4
+ import { createHash } from "node:crypto";
5
+ import { chmodSync, mkdirSync, mkdtempSync, lstatSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
7
+ import { join } from "node:path";
8
+ import { activitySummary } from "../lib/herdr-activity.ts";
9
+
10
+ const temporaryRoots: string[] = [];
11
+ const temporaryDirectory = (prefix: string) => {
12
+ const root = mkdtempSync(join(tmpdir(), prefix));
13
+ temporaryRoots.push(root);
14
+ return root;
15
+ };
16
+ after(() => { for (const root of temporaryRoots) rmSync(root, { recursive: true, force: true }); });
17
+
18
+ const input = { agent: "pi" as const, session: "../session", pid: 42, cwd: "/workspace", state: "working" as const, task: null };
19
+ test("S2: exact schema and UTC timestamp", async () => {
20
+ const { agentStatus } = await import("../lib/agent-status.ts");
21
+ assert.deepEqual(agentStatus(input, 0), { schema: "gentle-shell.agent-status/v1", ...input, updatedAt: "1970-01-01T00:00:00.000Z" });
22
+ });
23
+ test("S2/S4: shared title selection, sanitizing, bounds and null cases; Herdr bytes unchanged", async () => {
24
+ const { activeTodoTitle } = await import("../lib/herdr-activity.ts");
25
+ const tasks = [{ status: "pending", title: "ignored" }, { status: "in_progress", title: "\u001b[31mFix\u001b[0m\n\u202etests" }];
26
+ assert.equal(activeTodoTitle(tasks), "Fix tests");
27
+ assert.equal(activitySummary(tasks), "◐ Fix tests");
28
+ assert.equal(activitySummary([{ status: "in_progress", title: "one two three four" }], 12), "◐ one two\n three four");
29
+ for (const value of [null, [], [{ status: "done", title: "done" }], [{ status: "in_progress", title: 3 }], [{ status: "in_progress", title: "\n\u202e" }]]) assert.equal(activeTodoTitle(value), null);
30
+ assert.equal(activeTodoTitle([{ status: "in_progress", title: 3 }, { status: "in_progress", title: "later" }]), null);
31
+ assert.ok(activeTodoTitle([{ status: "in_progress", title: "x".repeat(5000) }])!.length <= 4096);
32
+ });
33
+ test("S5: private modes, safe stable filename and atomic replacement", async () => {
34
+ const { createAgentStatusStore, agentStatus } = await import("../lib/agent-status.ts");
35
+ const home = temporaryDirectory("agent-status-");
36
+ const store = createAgentStatusStore(home, input.session);
37
+ assert.equal(store.write(agentStatus(input, 0)), true);
38
+ const before = lstatSync(store.path);
39
+ assert.equal(store.write(agentStatus({ ...input, state: "idle" }, 1)), true);
40
+ assert.notEqual(lstatSync(store.path).ino, before.ino);
41
+ assert.equal(JSON.parse(readFileSync(store.path, "utf8")).state, "idle");
42
+ assert.deepEqual(readdirSync(join(home, "agent-status")), [store.path.split(/[\\/]/).at(-1)]);
43
+ if (process.platform !== "win32") {
44
+ assert.equal(lstatSync(join(home, "agent-status")).mode & 0o777, 0o700);
45
+ assert.equal(lstatSync(store.path).mode & 0o777, 0o600);
46
+ }
47
+ store.remove(); assert.deepEqual(readdirSync(join(home, "agent-status")), []);
48
+ });
49
+ test("S5/S6: symlink directories/files refused and failures contained", async (t) => {
50
+ const { createAgentStatusStore, agentStatus } = await import("../lib/agent-status.ts");
51
+ const home = temporaryDirectory("agent-status-");
52
+ const target = temporaryDirectory("agent-status-target-");
53
+ await t.test("symlinked status directory", (t) => {
54
+ try { symlinkSync(target, join(home, "agent-status"), "dir"); }
55
+ catch (error) { if (["EPERM", "EACCES"].includes((error as NodeJS.ErrnoException).code ?? "")) { t.skip("symlink privileges unavailable"); return; } throw error; }
56
+ const linked = createAgentStatusStore(home, "linked");
57
+ assert.equal(linked.write(agentStatus(input, 0)), false); assert.doesNotThrow(() => linked.remove());
58
+ assert.deepEqual(readdirSync(target), []);
59
+ });
60
+ const store = createAgentStatusStore(target, "file"); store.write(agentStatus(input, 0)); store.remove();
61
+ const victim = join(target, "victim"); writeFileSync(victim, "untouched");
62
+ await t.test("symlinked status file", (t) => {
63
+ try { symlinkSync(victim, store.path); }
64
+ catch (error) { if (["EPERM", "EACCES"].includes((error as NodeJS.ErrnoException).code ?? "")) { t.skip("symlink privileges unavailable"); return; } throw error; }
65
+ assert.equal(store.write(agentStatus(input, 0)), false); store.remove();
66
+ assert.ok(lstatSync(store.path).isSymbolicLink()); assert.equal(readFileSync(victim, "utf8"), "untouched");
67
+ });
68
+ const bad = createAgentStatusStore(victim, "bad");
69
+ assert.equal(bad.write(agentStatus(input, 0)), false); assert.doesNotThrow(() => bad.remove());
70
+ });
71
+ test("S5: group/world-writable config home and loose status directory refused", { skip: process.platform === "win32" }, async () => {
72
+ const { createAgentStatusStore, agentStatus } = await import("../lib/agent-status.ts");
73
+ for (const mode of [0o777, 0o775]) {
74
+ const open = temporaryDirectory("agent-status-open-");
75
+ chmodSync(open, mode);
76
+ assert.equal(createAgentStatusStore(open, "s").write(agentStatus(input, 0)), false, `config home mode ${mode.toString(8)}`);
77
+ assert.deepEqual(readdirSync(open), []);
78
+ }
79
+ const loose = temporaryDirectory("agent-status-loose-");
80
+ mkdirSync(join(loose, "agent-status"), { mode: 0o755 }); chmodSync(join(loose, "agent-status"), 0o755);
81
+ assert.equal(createAgentStatusStore(loose, "s").write(agentStatus(input, 0)), false);
82
+ assert.deepEqual(readdirSync(join(loose, "agent-status")), []);
83
+ assert.equal(lstatSync(join(loose, "agent-status")).mode & 0o777, 0o755);
84
+ });
85
+ test("S5: config home under a symlinked ancestor writes and removes", async (t) => {
86
+ const { createAgentStatusStore, agentStatus } = await import("../lib/agent-status.ts");
87
+ const parent = temporaryDirectory("agent-status-ancestor-");
88
+ const target = join(parent, "target"); mkdirSync(target);
89
+ const link = join(parent, "link");
90
+ try { symlinkSync(target, link, "dir"); }
91
+ catch (error) { if (["EPERM", "EACCES"].includes((error as NodeJS.ErrnoException).code ?? "")) { t.skip("symlink privileges unavailable"); return; } throw error; }
92
+ const home = join(link, "config");
93
+ const store = createAgentStatusStore(home, "s");
94
+ assert.equal(store.write(agentStatus(input, 0)), true);
95
+ assert.equal(JSON.parse(readFileSync(store.path, "utf8")).session, input.session);
96
+ if (process.platform !== "win32") {
97
+ assert.equal(lstatSync(home).mode & 0o777, 0o700);
98
+ assert.equal(lstatSync(join(home, "agent-status")).mode & 0o777, 0o700);
99
+ }
100
+ store.remove(); assert.deepEqual(readdirSync(join(home, "agent-status")), []);
101
+ });
102
+ test("S5: symlinked config home is refused", async (t) => {
103
+ const { createAgentStatusStore, agentStatus } = await import("../lib/agent-status.ts");
104
+ const parent = temporaryDirectory("agent-status-home-link-");
105
+ const target = join(parent, "target"); mkdirSync(target);
106
+ const home = join(parent, "config");
107
+ try { symlinkSync(target, home, "dir"); }
108
+ catch (error) { if (["EPERM", "EACCES"].includes((error as NodeJS.ErrnoException).code ?? "")) { t.skip("symlink privileges unavailable"); return; } throw error; }
109
+ const store = createAgentStatusStore(home, "s");
110
+ assert.equal(store.write(agentStatus(input, 0)), false);
111
+ assert.doesNotThrow(() => store.remove());
112
+ assert.deepEqual(readdirSync(target), []);
113
+ });
114
+ test("S6: startup sweep unlinks time- or pid-stale orphans only", async () => {
115
+ const { createAgentStatusStore, agentStatus } = await import("../lib/agent-status.ts");
116
+ const home = temporaryDirectory("agent-status-sweep-");
117
+ const root = join(home, "agent-status");
118
+ mkdirSync(root, { mode: 0o700 }); chmodSync(root, 0o700);
119
+ const statusPath = (session: string) => join(root, `${createHash("sha256").update(session).digest("hex")}.json`);
120
+ const record = (session: string, pid: number, updatedAt: string) => JSON.stringify({ ...agentStatus({ ...input, session, pid }, 0), updatedAt });
121
+ const dead = spawnSync(process.execPath, ["-e", ""]);
122
+ assert.throws(() => process.kill(dead.pid!, 0), { code: "ESRCH" }, "the probe pid must be reaped before the sweep");
123
+ const staleAt = new Date(Date.now() - 25 * 60 * 60 * 1000).toISOString();
124
+ const freshAt = new Date().toISOString();
125
+ writeFileSync(statusPath("own"), record("own", dead.pid!, staleAt));
126
+ writeFileSync(statusPath("stale-time"), record("stale-time", process.pid, staleAt));
127
+ writeFileSync(statusPath("dead-pid"), record("dead-pid", dead.pid!, freshAt));
128
+ writeFileSync(statusPath("live"), record("live", process.pid, freshAt));
129
+ writeFileSync(statusPath("malformed"), "{not json");
130
+ const store = createAgentStatusStore(home, "own");
131
+ assert.equal(JSON.parse(readFileSync(statusPath("own"), "utf8")).updatedAt, staleAt, "the sweep never removes its own session file");
132
+ assert.equal(store.write(agentStatus(input, 1)), true);
133
+ assert.deepEqual(readdirSync(root).sort(), ["live", "malformed", "own"].map((session) => statusPath(session).split(/[\\/]/).at(-1)!).sort());
134
+ assert.equal(JSON.parse(readFileSync(statusPath("live"), "utf8")).updatedAt, freshAt);
135
+ assert.deepEqual(JSON.parse(readFileSync(statusPath("own"), "utf8")).state, "working");
136
+ });
137
+ test("S5: a missing config home is created privately on first write", async () => {
138
+ const { createAgentStatusStore, agentStatus } = await import("../lib/agent-status.ts");
139
+ const home = join(temporaryDirectory("agent-status-new-"), "config");
140
+ const store = createAgentStatusStore(home, "s");
141
+ assert.equal(store.write(agentStatus(input, 0)), true);
142
+ assert.equal(JSON.parse(readFileSync(store.path, "utf8")).session, "../session");
143
+ });
@@ -5,6 +5,7 @@ import { join } from "node:path";
5
5
  import test, { after } from "node:test";
6
6
  import {
7
7
  AGENT_MODE,
8
+ PROVIDER_REVIEW_ROLES,
8
9
  THINKING_LEVEL,
9
10
  agentDirectories,
10
11
  discoverAgents,
@@ -14,9 +15,13 @@ import {
14
15
  parseFrontmatter,
15
16
  parseModelRef,
16
17
  resolveAgentProfile,
18
+ staleRoutingKeys,
19
+ removeRoutingKeys,
20
+ removeRoutingKeysFromProfilesFile,
17
21
  unmatchedProfileKeys,
18
22
  withPinnedModelProfiles,
19
23
  } from "../lib/agents-config.ts";
24
+ import type { AgentProfilesFile } from "../lib/agent-profiles.ts";
20
25
  import { THINKING_LEVELS } from "../lib/model-routing-authority.ts";
21
26
 
22
27
  // Gentle Agents configuration: markdown agent definitions (the same files
@@ -283,6 +288,97 @@ test("unmatchedProfileKeys reports profile keys that match no discovered agent",
283
288
  assert.deepEqual(unmatchedProfileKeys({}, [worker]), []);
284
289
  });
285
290
 
291
+ test("staleRoutingKeys returns sorted unmatched keys with no suggestion", () => {
292
+ const config = { zebra: {}, abandoned: {} };
293
+ assert.deepEqual(staleRoutingKeys(config, []), ["abandoned", "zebra"]);
294
+ assert.deepEqual(config, { zebra: {}, abandoned: {} });
295
+ assert.deepEqual(staleRoutingKeys({}, []), []);
296
+ });
297
+
298
+ test("staleRoutingKeys excludes exact matches and near-miss suggestions", () => {
299
+ const agents = [{ name: "gentle-ai-worker" }, { name: "gentle-ai-explore" }];
300
+ assert.deepEqual(staleRoutingKeys({
301
+ "gentle-ai-worker": {}, worker: {}, WORKER: {},
302
+ "GENTLE-AI-WORKER": {}, explore: {}, review_risk: {},
303
+ }, agents), ["review_risk"]);
304
+ });
305
+
306
+ test("staleRoutingKeys protects reserved routing targets without discovered definitions", () => {
307
+ const config = {
308
+ "review-refuter": { model: "refuter" },
309
+ "review-validator": { model: "validator" },
310
+ orchestrator: { model: "main" },
311
+ abandoned: { model: "old" },
312
+ };
313
+ const before = structuredClone(config);
314
+ for (const agents of [[], [{ name: "unrelated" }]]) {
315
+ assert.deepEqual(staleRoutingKeys(config, agents), ["abandoned"]);
316
+ assert.deepEqual(config, before);
317
+ }
318
+ });
319
+
320
+ test("staleRoutingKeys excludes every provider review role without discovered agents", () => {
321
+ const config = Object.fromEntries(PROVIDER_REVIEW_ROLES.map((role) => [role, { model: "provider/model" }]));
322
+ const before = structuredClone(config);
323
+ assert.deepEqual(staleRoutingKeys(config, []), []);
324
+ assert.deepEqual(config, before);
325
+ });
326
+
327
+ test("staleRoutingKeys protects provider review roles supplied by the caller", () => {
328
+ assert.deepEqual(staleRoutingKeys({
329
+ "review-refuter": {}, "review-validator": {}, abandoned: {},
330
+ }, [{ name: "review-refuter" }, { name: "review-validator" }]), ["abandoned"]);
331
+ });
332
+
333
+ test("removeRoutingKeys removes only selected own keys without cloning retained values", () => {
334
+ const config = { stale: { model: "old" }, keep: { model: "live" }, other: {} };
335
+ const result = removeRoutingKeys(config, ["stale", "missing", "stale"]);
336
+ assert.notEqual(result, config);
337
+ assert.deepEqual(result, { keep: config.keep, other: config.other });
338
+ assert.equal(result.keep, config.keep);
339
+ assert.equal(result.other, config.other);
340
+ assert.deepEqual(config, { stale: { model: "old" }, keep: { model: "live" }, other: {} });
341
+ });
342
+
343
+ test("removeRoutingKeys preserves identity for empty or absent selections", () => {
344
+ const config = { keep: {} };
345
+ assert.equal(removeRoutingKeys(config, []), config);
346
+ assert.equal(removeRoutingKeys(config, ["missing", "toString"]), config);
347
+ });
348
+
349
+ test("removeRoutingKeysFromProfilesFile changes only affected profiles and preserves metadata", () => {
350
+ const file: AgentProfilesFile = {
351
+ kind: "gentle-pi.agent_model_profiles", version: 1, active: "primary",
352
+ profiles: {
353
+ primary: { stale: { model: "old" }, keep: { model: "live" } },
354
+ secondary: { stale: {}, another: {} },
355
+ untouched: { keep: {} },
356
+ },
357
+ };
358
+ const result = removeRoutingKeysFromProfilesFile(file, ["stale", "missing"]);
359
+ assert.notEqual(result, file);
360
+ assert.notEqual(result.profiles, file.profiles);
361
+ assert.deepEqual(result, { ...file, profiles: {
362
+ primary: { keep: file.profiles.primary.keep },
363
+ secondary: { another: file.profiles.secondary.another },
364
+ untouched: file.profiles.untouched,
365
+ } });
366
+ assert.equal(result.profiles.untouched, file.profiles.untouched);
367
+ assert.equal(result.profiles.primary.keep, file.profiles.primary.keep);
368
+ assert.equal(result.active, file.active);
369
+ assert.ok(Object.hasOwn(file.profiles.primary, "stale"));
370
+ assert.ok(Object.hasOwn(file.profiles.secondary, "stale"));
371
+ });
372
+
373
+ test("removeRoutingKeysFromProfilesFile preserves identity when no profile changes", () => {
374
+ const file: AgentProfilesFile = {
375
+ kind: "gentle-pi.agent_model_profiles", version: 1, profiles: { main: { keep: {} } },
376
+ };
377
+ assert.equal(removeRoutingKeysFromProfilesFile(file, []), file);
378
+ assert.equal(removeRoutingKeysFromProfilesFile(file, ["missing"]), file);
379
+ assert.equal(removeRoutingKeysFromProfilesFile({ ...file, profiles: {} }, []).active, undefined);
380
+ });
381
+
286
382
  // Cortex QA adversarial follow-up (R5 pin): the did-you-mean mapping exists to
287
383
  // make a misconfiguration visible, never to resolve; a short key must keep
288
384
  // yielding an unresolved profile so the role inherits frontmatter and default
@@ -62,3 +62,34 @@ test("retired remediation payloads remain readable and are never automatically p
62
62
  assert.deepEqual((await loadStoredTask(legacyDir, "legacy"))?.task, JSON.parse(before).task);
63
63
  assert.equal(readFileSync(join(legacyDir, "legacy.json"), "utf8"), before);
64
64
  });
65
+
66
+ test("pruneHistory preserves in-flight unfinished tasks regardless of history cap", async () => {
67
+ const inFlightDir = join(root, "inflight-tasks");
68
+ const inFlightTask: TaskRecord = { ...task("inflight", 500), status: TASK_STATUS.RUNNING, endedAt: null };
69
+ const completedTask1 = task("c1", 1000);
70
+ const completedTask2 = task("c2", 2000);
71
+ await saveTask(inFlightDir, inFlightTask, emptyThread());
72
+ await saveTask(inFlightDir, completedTask1, emptyThread());
73
+ await saveTask(inFlightDir, completedTask2, emptyThread());
74
+
75
+ // Prune with maxTasks = 1 (should prune the older completed task c1, but keep inFlightTask)
76
+ await pruneHistory(inFlightDir, 1);
77
+ const remaining = await loadHistory(inFlightDir);
78
+ assert.ok(remaining.some((entry) => entry.task.id === "inflight"), "in-flight task is preserved");
79
+ assert.ok(remaining.some((entry) => entry.task.id === "c2"), "newest completed task is preserved");
80
+ assert.ok(!remaining.some((entry) => entry.task.id === "c1"), "older completed task is pruned");
81
+ });
82
+
83
+ test("concurrent saves of one task land on disk in call order, so a later terminal write always wins", async () => {
84
+ const orderedDir = join(root, "ordered-tasks");
85
+ const running: TaskRecord = { ...task("ordered", 3000), status: TASK_STATUS.RUNNING, endedAt: null, result: null };
86
+ // A large launch payload makes the stale write slower than the terminal one.
87
+ const slowThread = applyTaskEvent(emptyThread(), { type: TASK_EVENT.TEXT, text: "x".repeat(32 * 1024 * 1024) });
88
+ const launch = saveTask(orderedDir, running, slowThread);
89
+ const terminal = saveTask(orderedDir, task("ordered", 3000), emptyThread());
90
+ await Promise.all([launch, terminal]);
91
+ const stored = await loadStoredTask(orderedDir, "ordered");
92
+ assert.equal(stored?.task.status, TASK_STATUS.COMPLETED);
93
+ assert.deepEqual(stored?.thread.items, []);
94
+ assert.deepEqual(readdirSync(orderedDir).filter((name) => name.endsWith(".tmp")), []);
95
+ });