gentle-pi 4.6.0 → 4.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (290) hide show
  1. package/README.md +10 -11
  2. package/assets/agents/gentle-ai-explore.md +1 -0
  3. package/assets/agents/gentle-ai-verify.md +5 -2
  4. package/assets/agents/gentle-ai-worker.md +3 -0
  5. package/assets/agents/jd-fix-agent.md +1 -0
  6. package/assets/agents/jd-judge-a.md +1 -0
  7. package/assets/agents/jd-judge-b.md +1 -0
  8. package/assets/design-canvas/canvas.css +13 -1
  9. package/assets/design-canvas/canvas.js +11 -2
  10. package/assets/install-wizard/wizard.js +1 -0
  11. package/assets/migrations/agent-body-history.json +16 -1
  12. package/assets/orchestrator-delegation-reference.md +4 -4
  13. package/assets/orchestrator-delegation.md +1 -1
  14. package/assets/orchestrator-full-delegation-card.md +65 -0
  15. package/assets/orchestrator-full-delegation.md +34 -0
  16. package/assets/orchestrator-memory.md +3 -3
  17. package/assets/orchestrator-prompts.md +1 -1
  18. package/assets/orchestrator-skills.md +1 -1
  19. package/assets/orchestrator-verification.md +7 -5
  20. package/assets/orchestrator.md +3 -3
  21. package/bin/gentle-shell.mjs +164 -56
  22. package/docs/agent-status.md +61 -0
  23. package/docs/bundled-install.md +7 -5
  24. package/docs/delegated-verification.md +29 -7
  25. package/docs/gentle-agents-activity.md +14 -0
  26. package/docs/gentle-shell.md +54 -16
  27. package/docs/install-wizard.md +1 -1
  28. package/docs/permission-modes.md +9 -4
  29. package/docs/readme-reference.md +75 -30
  30. package/docs/render-cache-performance.md +11 -1
  31. package/docs/review-coordinator.md +33 -0
  32. package/docs/review-request-context.md +19 -0
  33. package/docs/review-windows-acl.md +18 -0
  34. package/docs/voice.md +6 -3
  35. package/docs/yolo-mode.md +5 -5
  36. package/extensions/ask-user-choice.ts +1 -0
  37. package/extensions/ask-user-question.ts +1 -0
  38. package/extensions/child-safety.ts +3 -0
  39. package/extensions/gentle-agent-status.ts +99 -0
  40. package/extensions/gentle-agents.ts +326 -34
  41. package/extensions/gentle-ai.ts +1496 -454
  42. package/extensions/gentle-shell.ts +293 -63
  43. package/extensions/gentle-todo.ts +18 -2
  44. package/extensions/gentle-tps.ts +48 -0
  45. package/extensions/quiet-tools.ts +38 -8
  46. package/extensions/skill-registry.ts +175 -18
  47. package/extensions/startup-banner.ts +30 -3
  48. package/lib/agent-profile-pin.ts +3 -3
  49. package/lib/agent-profiles.ts +160 -2
  50. package/lib/agent-status.ts +105 -0
  51. package/lib/agents-config.ts +46 -0
  52. package/lib/agents-history.ts +24 -5
  53. package/lib/agents-messaging.ts +47 -5
  54. package/lib/agents-runner.ts +183 -12
  55. package/lib/auto-permission-runtime.ts +1 -1
  56. package/lib/bounded-writer-admission.ts +13 -1
  57. package/lib/card-content-policy.ts +8 -6
  58. package/lib/command-palette.ts +133 -17
  59. package/lib/context-backstop.ts +14 -5
  60. package/lib/destructive-command-guard.ts +48 -4
  61. package/lib/execution-surface-guard.ts +20 -0
  62. package/lib/exploration-budget.ts +4 -2
  63. package/lib/gentle-ai-binary.ts +1 -1
  64. package/lib/gentle-design.ts +3 -0
  65. package/lib/gentle-shell-bundled.ts +6 -19
  66. package/lib/gentle-shell-launcher.ts +43 -8
  67. package/lib/herdr-activity.ts +14 -2
  68. package/lib/herdr-busy.ts +45 -0
  69. package/lib/image-attachments.ts +33 -0
  70. package/lib/image-disk-cache.ts +137 -0
  71. package/lib/inprocess-reviewer.ts +270 -140
  72. package/lib/jobs-view.ts +198 -11
  73. package/lib/model-routing-authority.ts +22 -4
  74. package/lib/native-choice-list.ts +20 -2
  75. package/lib/native-review-cli.ts +96 -19
  76. package/lib/orchestrator-mode-policy.ts +105 -0
  77. package/lib/questionnaire/questionnaire-view.ts +105 -12
  78. package/lib/rdd-mode-control.ts +32 -0
  79. package/lib/reply-language-anchor.ts +104 -0
  80. package/lib/review-blocker.ts +92 -0
  81. package/lib/review-candidate-symlink-scan.ts +136 -0
  82. package/lib/review-candidate-view-owner.ts +81 -44
  83. package/lib/review-continuation-registry.ts +99 -0
  84. package/lib/review-coordinator.ts +163 -0
  85. package/lib/review-failure-facts.ts +49 -0
  86. package/lib/review-host-relay.ts +46 -10
  87. package/lib/review-integration-v2.ts +7 -1
  88. package/lib/review-relay-phase-timing.ts +45 -0
  89. package/lib/review-start-context.ts +17 -0
  90. package/lib/session-profile-freeze.ts +4 -2
  91. package/lib/shell-bar.ts +140 -58
  92. package/lib/shell-changes.ts +2 -0
  93. package/lib/shell-panel.ts +17 -3
  94. package/lib/shell-sidebar-layout.ts +112 -40
  95. package/lib/shell-sidebar.ts +7 -0
  96. package/lib/shell-todo.ts +10 -3
  97. package/lib/verifier-admission.ts +1 -1
  98. package/lib/visual-customization-policy.ts +36 -16
  99. package/lib/visual-customize-view.ts +216 -21
  100. package/lib/visual-layout-preview.ts +9 -5
  101. package/lib/visual-profiles.ts +2 -2
  102. package/lib/windows-session-transport.ts +53 -2
  103. package/lib/yolo-session-policy.ts +40 -15
  104. package/package.json +2 -1
  105. package/runtime/gentle-ai-binary.mjs +1 -1
  106. package/runtime/gentle-shell-bundled.mjs +6 -19
  107. package/runtime/gentle-shell-launcher.mjs +42 -7
  108. package/runtime/native-review-cli.mjs +93 -16
  109. package/runtime/review-integration-v2.mjs +7 -1
  110. package/scripts/build-full-delegation-card.mjs +175 -0
  111. package/scripts/bundled-install.mjs +38 -8
  112. package/scripts/download-progress.mjs +68 -0
  113. package/scripts/gentle-ai-installer.mjs +41 -18
  114. package/scripts/gentle-ai-proxy.mjs +294 -0
  115. package/scripts/install-gentle-ai.mjs +14 -1
  116. package/scripts/installer-preflight.mjs +5 -5
  117. package/scripts/installer-runner.mjs +27 -12
  118. package/scripts/installer-server.mjs +8 -7
  119. package/scripts/render-cache-host.mjs +72 -0
  120. package/scripts/render-cache-performance-worker.mjs +5 -4
  121. package/scripts/render-cache-performance.mjs +6 -1
  122. package/scripts/run-test-suite.mjs +40 -28
  123. package/scripts/verify-package-files.mjs +12 -2
  124. package/scripts/voice-worker.cjs +32 -6
  125. package/skills/design/SKILL.md +11 -8
  126. package/skills/gentle-ai/SKILL.md +2 -2
  127. package/skills/gentle-ui-design/SKILL.md +46 -0
  128. package/skills/gentle-ui-design/references/adaptive-interfaces.md +46 -0
  129. package/skills/gentle-ui-design/references/browse-and-compare.md +62 -0
  130. package/skills/gentle-ui-design/references/composition-and-feedback.md +56 -0
  131. package/skills/gentle-ui-design/references/task-and-content.md +60 -0
  132. package/skills/skill-registry/SKILL.md +4 -2
  133. package/skills/work-unit-commits/SKILL.md +6 -7
  134. package/tests/agent-home.test.ts +28 -9
  135. package/tests/agent-profiles-workflow.test.ts +163 -0
  136. package/tests/agent-risk-escalation.test.ts +1 -1
  137. package/tests/agent-status.test.ts +143 -0
  138. package/tests/agents-config.test.ts +96 -0
  139. package/tests/agents-history.test.ts +31 -0
  140. package/tests/agents-jobs-frames.test.ts +93 -0
  141. package/tests/agents-prompt-lifecycle-runtime.test.ts +376 -0
  142. package/tests/agents-runner-drain.test.ts +193 -0
  143. package/tests/agents-runner.test.ts +178 -2
  144. package/tests/append-system-prompt-route.test.ts +4 -1
  145. package/tests/ask-user-choice.test.ts +4 -3
  146. package/tests/ask-user-question.test.ts +97 -0
  147. package/tests/auto-permission-runtime.test.ts +1 -1
  148. package/tests/autonomous-guard.test.ts +346 -10
  149. package/tests/bounded-stop-contract.test.ts +43 -3
  150. package/tests/bridge-cost.test.ts +19 -4
  151. package/tests/bundled-install.test.ts +30 -5
  152. package/tests/card-content-policy.test.ts +3 -3
  153. package/tests/chained-pr-skill.test.ts +8 -6
  154. package/tests/child-safety.test.ts +11 -0
  155. package/tests/codegraph-tools.test.ts +11 -5
  156. package/tests/command-palette.test.ts +284 -1
  157. package/tests/delegate-for-reason-contract.test.ts +3 -3
  158. package/tests/design-canvas-assets.test.ts +185 -2
  159. package/tests/destructive-command-guard.test.ts +52 -0
  160. package/tests/download-progress.test.ts +71 -0
  161. package/tests/execution-surface-guard.test.ts +55 -0
  162. package/tests/fixtures/primary-session-prompt/gentleman.golden.md +9 -5
  163. package/tests/fixtures/proxy-tls/proxy.crt +19 -0
  164. package/tests/fixtures/proxy-tls/proxy.key +28 -0
  165. package/tests/fixtures/session-profile-v1/gentle-ai-reviewer.ts +89 -0
  166. package/tests/fixtures/session-profile-v1/replay.ts +53 -6
  167. package/tests/full-delegation-closure.test.ts +131 -0
  168. package/tests/full-delegation-notices.test.ts +76 -0
  169. package/tests/generic-agent-tools.test.ts +3 -3
  170. package/tests/gentle-agent-status.test.ts +74 -0
  171. package/tests/gentle-agents-child-jobs.test.ts +237 -0
  172. package/tests/gentle-agents.test.ts +1070 -12
  173. package/tests/gentle-ai-binary.test.ts +3 -1
  174. package/tests/gentle-ai-elapsed-store.test.ts +19 -0
  175. package/tests/gentle-ai-exploration-budget.test.ts +18 -2
  176. package/tests/gentle-ai-installer.test.ts +134 -51
  177. package/tests/gentle-ai-proxy.test.ts +434 -0
  178. package/tests/gentle-ai.test.ts +113 -38
  179. package/tests/gentle-design.test.ts +21 -0
  180. package/tests/gentle-herdr-activity.test.ts +9 -6
  181. package/tests/gentle-shell-bin.test.ts +123 -0
  182. package/tests/gentle-shell-bundled.test.ts +207 -31
  183. package/tests/gentle-shell-launcher.test.ts +77 -10
  184. package/tests/gentle-shell.test.ts +899 -59
  185. package/tests/gentle-todo.test.ts +19 -2
  186. package/tests/gentle-tps.test.ts +123 -0
  187. package/tests/gentle-ui-design-skill.test.ts +59 -0
  188. package/tests/herdr-busy.test.ts +59 -0
  189. package/tests/herdr-task-summary-policy.test.ts +8 -4
  190. package/tests/image-disk-cache.test.ts +163 -0
  191. package/tests/independent-recovery-delivery.test.ts +83 -0
  192. package/tests/inprocess-reviewer.test.ts +176 -4
  193. package/tests/installer-posix-bootstrap.test.ts +1 -1
  194. package/tests/installer-preflight.test.ts +5 -4
  195. package/tests/installer-runner.test.ts +79 -44
  196. package/tests/installer-server.test.ts +14 -11
  197. package/tests/jobs-view.test.ts +260 -6
  198. package/tests/modal-mouse-boundaries.test.ts +136 -0
  199. package/tests/model-routing-authority.test.ts +178 -2
  200. package/tests/native-choice-list.test.ts +77 -2
  201. package/tests/native-review-capability-contract.test.ts +7 -1
  202. package/tests/native-review-cli.test.ts +269 -1
  203. package/tests/no-self-pause-contract.test.ts +4 -1
  204. package/tests/odd-routing-canonical-ratchet.test.ts +3 -3
  205. package/tests/orchestrator-budget.test.ts +7 -2
  206. package/tests/orchestrator-delegation-mode.test.ts +153 -0
  207. package/tests/orchestrator-mode-policy.test.ts +175 -0
  208. package/tests/orchestrator-prompt-budget.test.ts +3 -1
  209. package/tests/orchestrator-rdd-ownership.test.ts +2 -2
  210. package/tests/package-manifest.test.ts +11 -9
  211. package/tests/permission-allowlist.test.ts +202 -0
  212. package/tests/pi-update-launcher.test.ts +8 -0
  213. package/tests/pnpm-workspace-config.test.ts +58 -0
  214. package/tests/primary-session-prompt.test.ts +13 -0
  215. package/tests/profile-pin.test.ts +29 -2
  216. package/tests/profile-tier-footer.test.ts +5 -0
  217. package/tests/profiles-panel-delegation-mode.test.ts +422 -0
  218. package/tests/questionnaire-view.test.ts +115 -0
  219. package/tests/quiet-bash-runtime.test.ts +1 -1
  220. package/tests/quiet-tool-rendering.test.ts +48 -0
  221. package/tests/rdd-aware-verification-contract.test.ts +16 -11
  222. package/tests/rdd-customize.test.ts +287 -0
  223. package/tests/rdd-mode-cache.test.ts +450 -0
  224. package/tests/rdd-mode-control.test.ts +407 -0
  225. package/tests/rdd-mode-scope-regression.test.ts +137 -0
  226. package/tests/rdd-off-independent-regression.test.ts +69 -0
  227. package/tests/rdd-status-line.test.ts +18 -0
  228. package/tests/render-cache-performance.test.ts +171 -2
  229. package/tests/reply-language-anchor.test.ts +173 -0
  230. package/tests/review-agent-end-preflight.test.ts +1 -1
  231. package/tests/review-blocker.test.ts +193 -0
  232. package/tests/review-candidate-owner-retry.test.ts +1 -1
  233. package/tests/review-candidate-symlink-scan.test.ts +157 -0
  234. package/tests/review-candidate-view.test.ts +1 -1
  235. package/tests/review-candidate-windows-boundary.test.ts +131 -0
  236. package/tests/review-candidate-windows-probe.test.ts +63 -0
  237. package/tests/review-committed-restart-ack.test.ts +129 -0
  238. package/tests/review-continuation-registry.test.ts +76 -0
  239. package/tests/review-controller-native-routing.test.ts +261 -5
  240. package/tests/review-controller-workspace-root.test.ts +230 -3
  241. package/tests/review-controller.test.ts +96 -11
  242. package/tests/review-coordinator-runtime.test.ts +117 -0
  243. package/tests/review-coordinator.test.ts +195 -0
  244. package/tests/review-failure-facts.test.ts +87 -0
  245. package/tests/review-host-relay-routing.test.ts +258 -4
  246. package/tests/review-host-relay.test.ts +39 -0
  247. package/tests/review-integration-v2.test.ts +46 -3
  248. package/tests/review-json-arguments.test.ts +65 -10
  249. package/tests/review-last-event-closure.test.ts +68 -0
  250. package/tests/review-loadout-rdd-off-sdk.test.ts +65 -31
  251. package/tests/review-owner-identity.test.ts +60 -24
  252. package/tests/review-relay-phase-timing.test.ts +128 -0
  253. package/tests/review-relay-transport-agent.test.ts +12 -2
  254. package/tests/review-reviewer-evidence.test.ts +183 -0
  255. package/tests/review-risk-assessment.test.ts +74 -3
  256. package/tests/review-session-standing-permission-controller.test.ts +21 -1
  257. package/tests/review-start-context.test.ts +19 -0
  258. package/tests/review-tool-prose-budget.test.ts +121 -0
  259. package/tests/run-test-suite.test.ts +122 -1
  260. package/tests/runtime-harness.mjs +4 -1
  261. package/tests/sensitive-path-tools.test.ts +181 -5
  262. package/tests/session-profile-append-controller-pi.test.ts +60 -31
  263. package/tests/session-profile-binding.test.ts +19 -1
  264. package/tests/session-profile-disk-reader-pi.test.ts +58 -16
  265. package/tests/session-profile-v1-compat.test.ts +35 -1
  266. package/tests/shell-bar.test.ts +186 -42
  267. package/tests/shell-panel.test.ts +50 -22
  268. package/tests/shell-sidebar-fullscreen.test.ts +5 -5
  269. package/tests/shell-sidebar-layout.test.ts +294 -23
  270. package/tests/shell-sidebar-scroll-benchmark.test.ts +1 -1
  271. package/tests/shell-surface-transparent.test.ts +89 -0
  272. package/tests/shell-todo.test.ts +12 -0
  273. package/tests/skill-registry.test.ts +838 -5
  274. package/tests/startup-banner.test.ts +152 -1
  275. package/tests/startup-home-repo.test.ts +2 -0
  276. package/tests/support/review-coordinator-runtime.ts +69 -0
  277. package/tests/task-size-routing-contract.test.ts +5 -3
  278. package/tests/verifier-admission.test.ts +49 -0
  279. package/tests/verify-first-launch-contract.test.ts +78 -3
  280. package/tests/visual-customization-policy.test.ts +39 -6
  281. package/tests/visual-customize-view.test.ts +573 -9
  282. package/tests/visual-layout-preview.test.ts +15 -1
  283. package/tests/visual-profiles.test.ts +11 -0
  284. package/tests/voice-worker.test.ts +73 -2
  285. package/tests/windows-session-transport.test.ts +126 -0
  286. package/tests/work-continuity-contract.test.ts +28 -0
  287. package/tests/writer-feature-document-admission.test.ts +92 -0
  288. package/tests/yolo-customize.test.ts +27 -4
  289. package/tests/yolo-mode.test.ts +23 -18
  290. package/tests/yolo-session-policy.test.ts +270 -1
@@ -1,8 +1,8 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test, { mock } from "node:test";
3
3
  import {
4
- KeybindingsManager, stripTerminalSequences, Text, TUI_KEYBINDINGS,
5
- type Component, type TuiMouseEvent, visibleWidth,
4
+ KeybindingsManager, stripTerminalSequences, Text, TUI_KEYBINDINGS, TuiAltScreen,
5
+ type Component, type Terminal, type TuiMouseEvent, visibleWidth,
6
6
  } from "@earendil-works/pi-tui";
7
7
  import { NativeChoiceList } from "../lib/native-choice-list.ts";
8
8
  import {
@@ -85,6 +85,81 @@ test("native choice list presents one hovered wrapped option without changing se
85
85
  assert.doesNotMatch(list.render(56).join("\n"), new RegExp(hoverBackground.replace(/[\[\]]/g, "\\$&")));
86
86
  });
87
87
 
88
+ const warningForeground = "\u001b[33m";
89
+ const warningTheme = {
90
+ ...theme,
91
+ fg: (role: string, text: string) => role === "warning" ? `${warningForeground}${text}\u001b[39m` : text,
92
+ };
93
+
94
+ test("native choice hover uses the shared warning foreground without selecting or activating", () => {
95
+ const items = [
96
+ { id: "opaque-first", label: "First", description: "First detail." },
97
+ { id: "opaque-second", label: "Second", description: "Second detail." },
98
+ ];
99
+ const list = new NativeChoiceList(items, warningTheme);
100
+ const selected: string[] = [];
101
+ list.onSelect = (item) => selected.push(item.id);
102
+ let { lines, row } = layout(list, 40, "Second");
103
+ assert.equal(list.handleMouse(event("move", "none", row, 40, lines.length))?.render, true);
104
+ lines = list.render(40);
105
+ assert.match(lines[row]!, /\x1b\[33mSecond\x1b\[39m/);
106
+ assert.ok(!lines[row]!.includes(hoverBackground), "hover does not use toolPendingBg");
107
+ assert.equal(list.getSelectedItem(), items[0]);
108
+ assert.deepEqual(selected, []);
109
+ assert.equal(list.handleMouse(event("move", "none", row, 40, lines.length))?.render, false);
110
+ list.handleInput("\r");
111
+ assert.deepEqual(selected, ["opaque-first"], "Enter still selects the keyboard item");
112
+ list.invalidate();
113
+ assert.doesNotMatch(list.render(40).join("\n"), /\x1b\[33m/);
114
+ ({ lines, row } = layout(list, 40, "Second"));
115
+ list.handleMouse(event("move", "none", row, 40, lines.length));
116
+ list.dispose();
117
+ assert.equal(list.handleMouse(event("click", "left", row, 40, lines.length)), undefined);
118
+ list.handleInput("\r");
119
+ assert.deepEqual(selected, ["opaque-first"]);
120
+ });
121
+
122
+ test("choice overlay uses real SGR coordinates and documents the outside-overlay leave boundary", () => {
123
+ let input: ((data: string) => void) | undefined;
124
+ const terminal: Terminal = {
125
+ start(onInput) { input = onInput; }, stop() {}, async drainInput() {}, write() {},
126
+ get columns() { return 120; }, get rows() { return 30; }, get kittyProtocolActive() { return false; },
127
+ moveBy() {}, hideCursor() {}, showCursor() {}, clearLine() {}, clearFromCursor() {}, clearScreen() {},
128
+ setTitle() {}, setProgress() {}, setProgramStatus() {},
129
+ };
130
+ const list = new NativeChoiceList([{ id: "first", label: "First" }, { id: "second", label: "Second" }], warningTheme);
131
+ const selected: string[] = [];
132
+ list.onSelect = (item) => selected.push(item.id);
133
+ const root = createNativeFullscreenInteraction({
134
+ keyboardTarget: list, requestRender() {}, mouseObserver: list.createMouseObserver(() => {}),
135
+ });
136
+ root.addChild(new Text("Heading", 0, 0));
137
+ root.addChild(list);
138
+ root.addChild(new Text("Footer", 0, 0));
139
+ const tui = new TuiAltScreen(terminal, false, undefined, { mouse: true });
140
+ const overlay = tui.showOverlay(root, { anchor: "center", width: 60, maxHeight: 15 });
141
+ tui.start(); tui.renderNow(true);
142
+ try {
143
+ let lines = root.render(60);
144
+ const bounds = overlay.getBounds();
145
+ assert.ok(bounds && bounds.col > 0 && bounds.row > 0);
146
+ const second = lines.findIndex((line) => stripTerminalSequences(line).includes("Second"));
147
+ assert.ok(second >= 0);
148
+ const x = bounds.col + 3, y = bounds.row + second + 1;
149
+ input?.(`\x1b[<35;${x};${y}M`);
150
+ lines = root.render(60);
151
+ assert.match(lines[second]!, /\x1b\[33mSecond\x1b\[39m/);
152
+ assert.deepEqual(selected, []);
153
+ input?.("\x1b[<35;1;1M");
154
+ assert.match(root.render(60)[second]!, /\x1b\[33mSecond\x1b\[39m/, "outside-overlay motion is not delivered to the root observer");
155
+ input?.(`\x1b[<35;${bounds.col + 1};${bounds.row + 1}M`);
156
+ assert.doesNotMatch(root.render(60).join("\n"), /\x1b\[33m/, "inside-root heading motion clears hover");
157
+ input?.(`\x1b[<0;${x};${y}M`);
158
+ input?.(`\x1b[<0;${x};${y}m`);
159
+ assert.deepEqual(selected, ["second"]);
160
+ } finally { tui.stop(); }
161
+ });
162
+
88
163
  test("native choice list refreshes existing item content without changing selection", () => {
89
164
  const items = [
90
165
  { id: "first", label: "First", description: "Initial detail." },
@@ -392,11 +392,17 @@ test("4.3.1 explicitly repeats 4.2.0 because capabilities/v2.6 and provider cont
392
392
  assert.deepEqual(contract, NATIVE_CLI_CONTRACTS["4.2.0"] as Record<string, boolean>);
393
393
  });
394
394
 
395
+ test("4.4.0 explicitly repeats 4.3.1 because capabilities/v2.6 and provider contract 1.4.0 are unchanged", () => {
396
+ const contract = NATIVE_CLI_CONTRACTS["4.4.0"] as Record<string, boolean>;
397
+ assert.ok(contract);
398
+ assert.deepEqual(contract, NATIVE_CLI_CONTRACTS["4.3.1"] as Record<string, boolean>);
399
+ });
400
+
395
401
  test("no shipped version key was added beyond the pin bump", () => {
396
402
  // Rows are promises to consumers, so a new key only ever appears in a
397
403
  // dedicated commit alongside a pin bump, never as a side effect. v2.2.4 and
398
404
  // v2.3.0 shipped upstream while Pi stayed on 2.2.3 and were never pinned,
399
405
  // so they get no row: a row asserts ground truth measured against a binary
400
406
  // Pi actually ran, and the table only has to be ascending, not gapless.
401
- assert.deepEqual(Object.keys(NATIVE_CLI_CONTRACTS), [...DARK_VERSIONS, "2.2.0", "2.2.1", "2.2.2", "2.2.3", "2.4.0", "2.5.0-rc.3", "2.5.0", "2.6.0", "2.7.0", "2.8.0", "2.8.1", "2.8.2", "2.9.0", "2.9.1", "3.0.0", "3.0.1", "3.1.0", "3.2.1", "3.4.0", "3.5.0", "3.6.0", "3.6.1", "3.7.0", "4.0.0", "4.1.1", "4.2.0", "4.3.1"]);
407
+ assert.deepEqual(Object.keys(NATIVE_CLI_CONTRACTS), [...DARK_VERSIONS, "2.2.0", "2.2.1", "2.2.2", "2.2.3", "2.4.0", "2.5.0-rc.3", "2.5.0", "2.6.0", "2.7.0", "2.8.0", "2.8.1", "2.8.2", "2.9.0", "2.9.1", "3.0.0", "3.0.1", "3.1.0", "3.2.1", "3.4.0", "3.5.0", "3.6.0", "3.6.1", "3.7.0", "4.0.0", "4.1.1", "4.2.0", "4.3.1", "4.4.0"]);
402
408
  });
@@ -1,5 +1,6 @@
1
1
  import assert from "node:assert/strict";
2
- import { mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync } from "node:fs";
2
+ import { createHash } from "node:crypto";
3
+ import { mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
3
4
  import { tmpdir } from "node:os";
4
5
  import { join } from "node:path";
5
6
  import test from "node:test";
@@ -13,12 +14,15 @@ import {
13
14
  NativeReviewCliError,
14
15
  NativeReviewCliV216,
15
16
  NativeReviewIntegrationError,
17
+ NativeReviewConsentRequiredError,
18
+ createNativeReviewCli,
16
19
  createNodeExecFileAdapter,
17
20
  createWindowsProcessTreeKiller,
18
21
  windowsTaskkillPath,
19
22
  gentleAiProcessEnvironment,
20
23
  isNativeReviewUnachievableVerbRefused,
21
24
  type ExecFileAdapter,
25
+ type NativeReviewModeRequest,
22
26
  type NativeTargetStatusRequest,
23
27
  } from "../lib/native-review-cli.ts";
24
28
  import { setBundledInstallForTesting } from "../lib/gentle-shell-bundled.ts";
@@ -64,6 +68,114 @@ function client(adapter: ExecFileAdapter): NativeReviewCliV216 {
64
68
  return new NativeReviewCliV216(adapter, "/package/.gentle-ai/gentle-ai", 30_000, 1024 * 1024);
65
69
  }
66
70
 
71
+ const modeClients = [
72
+ ["factory", (adapter: ExecFileAdapter, executable: () => string) => createNativeReviewCli(adapter, executable)],
73
+ ["constructor", (adapter: ExecFileAdapter, executable: () => string) => new NativeReviewCliV216(adapter, executable)],
74
+ ] as const;
75
+ const modeCwd = "/isolated-review-mode-test";
76
+ const modeExecutable = "/package/.gentle-ai/gentle-ai";
77
+
78
+ function modeOutput(operation: "status" | "enable" | "disable", scope: "clone" | "global" | "both", global: "on" | "off", cloneLocal: "" | "off") {
79
+ const effective = cloneLocal === "off" || global === "off" ? "off" : "on";
80
+ const source = cloneLocal === "off" ? "clone_local" : "global";
81
+ return {
82
+ wire: JSON.stringify({ schema: "gentle-ai.review-mode/v1", operation, scope, status: { schema: "gentle-ai.rdd-mode-status/v1", global, clone_local: cloneLocal, effective, source } }),
83
+ decoded: { operation, scope, status: { global, cloneLocal, effective, source } },
84
+ };
85
+ }
86
+
87
+ test("native mode mutations honor each explicit clone or global scope", async (t) => {
88
+ const cases = [
89
+ { operation: "enable", scope: "clone", global: "off", cloneLocal: "" },
90
+ { operation: "disable", scope: "clone", global: "on", cloneLocal: "off" },
91
+ { operation: "enable", scope: "global", global: "on", cloneLocal: "off" },
92
+ { operation: "disable", scope: "global", global: "off", cloneLocal: "" },
93
+ ] as const;
94
+ for (const [name, makeClient] of modeClients) for (const scenario of cases) {
95
+ await t.test(`${name}: ${scenario.operation} ${scenario.scope}`, async () => {
96
+ const expected = modeOutput(scenario.operation, scenario.scope, scenario.global, scenario.cloneLocal);
97
+ const queue = queuedAdapter([{ stdout: expected.wire, stderr: "", exitCode: 0 }]);
98
+ const review = makeClient(queue.adapter, () => modeExecutable);
99
+ const result = await review.reviewMode!({ cwd: modeCwd, operation: scenario.operation, scope: scenario.scope });
100
+ assert.deepEqual(result, expected.decoded);
101
+ assert.deepEqual(queue.calls, [{ file: modeExecutable, arguments: ["review", "mode", scenario.operation, "--cwd", modeCwd, "--scope", scenario.scope, "--json"], cwd: modeCwd, timeoutMs: undefined }]);
102
+ });
103
+ }
104
+ });
105
+
106
+ test("native mode status and mutations without scope preserve their exact argv and decoded status", async (t) => {
107
+ for (const [name, makeClient] of modeClients) for (const operation of ["status", "enable", "disable"] as const) {
108
+ await t.test(`${name}: ${operation}`, async () => {
109
+ const expected = modeOutput(operation, operation === "status" ? "both" : "clone", "on", operation === "disable" ? "off" : "");
110
+ const queue = queuedAdapter([{ stdout: expected.wire, stderr: "", exitCode: 0 }]);
111
+ const review = makeClient(queue.adapter, () => modeExecutable);
112
+ assert.deepEqual(await review.reviewMode!({ cwd: modeCwd, operation }), expected.decoded);
113
+ assert.deepEqual(queue.calls, [{ file: modeExecutable, arguments: ["review", "mode", operation, "--cwd", modeCwd, ...(operation === "status" ? [] : ["--scope", "clone"]), "--json"], cwd: modeCwd, timeoutMs: operation === "status" ? 30_000 : undefined }]);
114
+ });
115
+ }
116
+ });
117
+
118
+ test("native mode rejects unsupported scopes and status scopes before cwd or native access", async (t) => {
119
+ const cases = [
120
+ ...(["enable", "disable"] as const).flatMap(operation => ["both", "", "GLOBAL", " global", null, 17].map(scope => ({ operation, scope, message: "Native review mode scope must be clone or global" }))),
121
+ ...(["clone", "global"] as const).map(scope => ({ operation: "status", scope, message: "Native review mode scope is only valid for enable or disable" })),
122
+ ];
123
+ for (const [name, makeClient] of modeClients) for (const scenario of cases) {
124
+ await t.test(`${name}: ${scenario.operation} ${String(scenario.scope)}`, async () => {
125
+ let cwdReads = 0, binaryResolutions = 0;
126
+ const expected = modeOutput(scenario.operation as "status" | "enable" | "disable", "clone", "on", "");
127
+ const queue = queuedAdapter([{ stdout: expected.wire }]);
128
+ const review = makeClient(queue.adapter, () => { binaryResolutions++; return modeExecutable; });
129
+ const request = { get cwd() { cwdReads++; return modeCwd; }, operation: scenario.operation, scope: scenario.scope } as unknown as NativeReviewModeRequest;
130
+ await assert.rejects(() => review.reviewMode!(request), { name: "TypeError", message: scenario.message });
131
+ assert.deepEqual({ cwdReads, binaryResolutions, calls: queue.calls.length }, { cwdReads: 0, binaryResolutions: 0, calls: 0 });
132
+ });
133
+ }
134
+ });
135
+
136
+ test("native mode binds operation and scope before asynchronous cwd resolution", async (t) => {
137
+ for (const [name, makeClient] of modeClients) for (const operation of ["status", "enable"] as const) {
138
+ await t.test(`${name}: ${operation}`, async () => {
139
+ const expected = modeOutput(operation, operation === "status" ? "both" : "global", "on", "off");
140
+ const queue = queuedAdapter([{ stdout: expected.wire }]);
141
+ const review = makeClient(queue.adapter, () => modeExecutable);
142
+ const request: NativeReviewModeRequest = { cwd: modeCwd, operation, ...(operation === "enable" ? { scope: "global" } : {}) };
143
+ const pending = review.reviewMode!(request);
144
+ request.operation = "disable";
145
+ request.scope = "clone";
146
+ assert.deepEqual(await pending, expected.decoded);
147
+ assert.deepEqual(queue.calls.map(call => call.arguments), [["review", "mode", operation, "--cwd", modeCwd, ...(operation === "enable" ? ["--scope", "global"] : []), "--json"]]);
148
+ });
149
+ }
150
+ });
151
+
152
+ test("scoped native mode surfaces stderr, exit, and malformed responses without claiming success", async (t) => {
153
+ const expected = modeOutput("enable", "global", "on", "off");
154
+ const cases = [
155
+ { name: "nonzero", result: { stdout: "{}", stderr: "native refused\n", exitCode: 17 }, code: NATIVE_REVIEW_ERROR_CODE.NON_ZERO, stderr: "native refused", exit: 17 },
156
+ { name: "stderr", result: { stdout: expected.wire, stderr: "unexpected notice\n", exitCode: 0 }, code: NATIVE_REVIEW_ERROR_CODE.UNEXPECTED_STDERR, stderr: "unexpected notice", exit: 0 },
157
+ { name: "malformed JSON", result: { stdout: "not-json", stderr: "", exitCode: 0 }, code: NATIVE_REVIEW_ERROR_CODE.MALFORMED_JSON, stderr: undefined, exit: 0 },
158
+ { name: "foreign operation", result: { stdout: modeOutput("disable", "global", "off", "").wire, stderr: "", exitCode: 0 }, code: NATIVE_REVIEW_ERROR_CODE.SCHEMA_INCOMPATIBLE, stderr: undefined, exit: undefined },
159
+ ] as const;
160
+ for (const [name, makeClient] of modeClients) for (const scenario of cases) {
161
+ await t.test(`${name}: ${scenario.name}`, async () => {
162
+ const queue = queuedAdapter([scenario.result]);
163
+ const review = makeClient(queue.adapter, () => modeExecutable);
164
+ const request = { cwd: modeCwd, operation: "enable", scope: "global" } as const;
165
+ await assert.rejects(() => review.reviewMode!(request), (error: unknown) => {
166
+ assert.ok(error instanceof NativeReviewCliError);
167
+ assert.equal(error.code, scenario.code);
168
+ assert.equal(error.operation, NATIVE_REVIEW_OPERATION.MODE);
169
+ assert.equal(error.mutationOutcome, "unknown");
170
+ assert.equal(error.diagnostics.stderr, scenario.stderr);
171
+ assert.equal(error.diagnostics.exit_code, scenario.exit);
172
+ return true;
173
+ });
174
+ assert.deepEqual(queue.calls.map(call => call.arguments), [["review", "mode", "enable", "--cwd", modeCwd, "--scope", "global", "--json"]]);
175
+ });
176
+ }
177
+ });
178
+
67
179
  test("negotiated STATUS accepts the pinned v5 receipt before routing its transition", async () => {
68
180
  const status = fixture("status-v5.captured.json");
69
181
  const queue = queuedAdapter([{ stdout: JSON.stringify(status) }]);
@@ -431,6 +543,120 @@ const LENS_SELECTION_UNSUPPORTED_FAILURE = {
431
543
  next_action: "correct_request", cause: "flag provided but not defined: -lenses",
432
544
  };
433
545
 
546
+ function contextClient(responses: QueuedResult[], features = ["start_request_context", "start_options_preflight"], executable = join(process.cwd(), "package.json")) {
547
+ const capabilities = JSON.parse(readFileSync(join(process.cwd(), "contracts/review-integration/v2/fixtures/capabilities.fixture.json"), "utf8"));
548
+ capabilities.executable.sha256 = "sha256:" + createHash("sha256").update(readFileSync(executable)).digest("hex");
549
+ capabilities.features.optional.push(...features.map(name => ({ name, supported: true, requires: [] })));
550
+ const queue = queuedAdapter([{ stdout: JSON.stringify(capabilities) }, ...responses]);
551
+ return { ...queue, client: new NativeReviewCliV216(queue.adapter, executable) };
552
+ }
553
+
554
+ test("START discovers capabilities before forwarding the explicit request file unchanged", async () => {
555
+ const path = "/repo/spec with spaces.md";
556
+ const tokens = ["--contract=gentle-ai.review-integration/v2", "--cwd=/repo", "--target=" + TARGET, "--projection=workspace", "--agent=pi", "--consent=relay", "--request-context=" + path];
557
+ const host = contextClient([
558
+ { stdout: JSON.stringify(negotiatedStartStatus(TARGET, tokens)) },
559
+ { stdout: JSON.stringify(fixture("start-v3-zero-lens-closed.captured.json")) },
560
+ ]);
561
+ await host.client.start({ cwd: "/repo", requestContextPath: path });
562
+ assert.deepEqual(host.calls[0].arguments, ["review", "capabilities", "--contract", "gentle-ai.review-integration/v2"]);
563
+ assert.deepEqual(host.calls[1].arguments.slice(-3), ["--request-context", path, "--next-transition"]);
564
+ assert.deepEqual(host.calls[2].arguments, ["review", "start", ...tokens]);
565
+ });
566
+
567
+ test("request context reuses capabilities while every STATUS remains fresh", async () => {
568
+ const host = contextClient([1, 2].map(() => ({ stdout: JSON.stringify(negotiatedStartStatus(TARGET, [])) })));
569
+ for (let i = 0; i < 2; i++) await host.client.targetStatus({ cwd: "/repo", requestContextPath: "/spec.md" });
570
+ assert.deepEqual(host.calls.map(call => call.arguments[1]), ["capabilities", "status", "status"]);
571
+ });
572
+
573
+ test("request context invalidates capabilities when executable bytes change", async t => {
574
+ const directory = mkdtempSync(join(tmpdir(), "context-capabilities-"));
575
+ t.after(() => rmSync(directory, { recursive: true, force: true }));
576
+ const executable = join(directory, "native");
577
+ writeFileSync(executable, "first executable");
578
+ const replacementCapabilities = JSON.parse(readFileSync(join(process.cwd(), "contracts/review-integration/v2/fixtures/capabilities.fixture.json"), "utf8"));
579
+ replacementCapabilities.executable.sha256 = "sha256:" + createHash("sha256").update("replacement executable").digest("hex");
580
+ const host = contextClient([{ stdout: JSON.stringify(negotiatedStartStatus(TARGET, [])) }, { stdout: JSON.stringify(replacementCapabilities) }], undefined, executable);
581
+ await host.client.targetStatus({ cwd: "/repo", requestContextPath: "/spec.md" });
582
+ writeFileSync(executable, "replacement executable");
583
+ // The old capability result cannot authorize a STATUS with the replacement.
584
+ await assert.rejects(host.client.targetStatus({ cwd: "/repo", requestContextPath: "/spec.md" }), /provider does not support request context/);
585
+ assert.deepEqual(host.calls.map(call => call.arguments[1]), ["capabilities", "status", "capabilities"]);
586
+ });
587
+
588
+ test("request context never caches malformed capability discovery", async () => {
589
+ const host = contextClient([]);
590
+ let discoveries = 0;
591
+ const adapter: ExecFileAdapter = async request => {
592
+ if (++discoveries === 1) return { stdout: "{}", stderr: "", exitCode: 0, signal: null, timedOut: false, outputLimitExceeded: false };
593
+ return host.adapter(request);
594
+ };
595
+ const subject = new NativeReviewCliV216(adapter, join(process.cwd(), "package.json"));
596
+ await assert.rejects(subject.targetStatus({ cwd: "/repo", requestContextPath: "/spec.md" }));
597
+ // The second discovery succeeds; only the subsequent unqueued STATUS fails.
598
+ await assert.rejects(subject.targetStatus({ cwd: "/repo", requestContextPath: "/spec.md" }));
599
+ assert.deepEqual(host.calls.map(call => call.arguments[1]), ["capabilities", "status"]);
600
+ });
601
+
602
+ test("Windows request paths preserve exact START and consent spelling and reject normalization drift", async () => {
603
+ for (const path of ["C:\\work\\spec with spaces.md", "C:\\work\\spec.md.", "C:\\work\\spec.md ", "\\\\?\\C:\\work\\spec.md"]) {
604
+ // A trailing space is an invalid process string even before negotiation.
605
+ if (path.endsWith(" ")) {
606
+ const queue = queuedAdapter([]);
607
+ await assert.rejects(client(queue.adapter).start({ cwd: "/repo", requestContextPath: path }));
608
+ assert.equal(queue.calls.length, 0);
609
+ continue;
610
+ }
611
+ const tokens = ["--contract=gentle-ai.review-integration/v2", "--cwd=/repo", "--target=" + TARGET, "--projection=workspace", "--agent=pi", "--consent=relay", "--request-context=" + path];
612
+ const host = contextClient([{ stdout: JSON.stringify(negotiatedStartStatus(TARGET, tokens)) }, { stdout: JSON.stringify(fixture("start-v3-zero-lens-closed.captured.json")) }]);
613
+ await host.client.start({ cwd: "/repo", requestContextPath: path });
614
+ assert.ok(host.calls[2].arguments.includes("--request-context=" + path));
615
+ const changed = path.startsWith("\\\\?\\") ? path.slice(4) : path.endsWith(".") ? path.slice(0, -1) : path.replaceAll("\\", "/");
616
+ const drift = contextClient([{ stdout: JSON.stringify(negotiatedStartStatus(TARGET, tokens.slice(0, -1).concat("--request-context=" + changed))) }]);
617
+ await assert.rejects(drift.client.start({ cwd: "/repo", requestContextPath: path }), /context/);
618
+ assert.equal(drift.calls.length, 2);
619
+ const raw = requestContextConsent(path);
620
+ const queue = queuedAdapter([{ stdout: JSON.stringify(reviewingStartV4(raw.target_identity)) }]);
621
+ await client(queue.adapter).answerConsent({ cwd: "/repo", consent: decodeReviewConsentV3(raw, "pi"), answer: "granted", requestContextPath: path });
622
+ assert.ok(queue.calls[0].arguments.includes(path));
623
+ const refused = queuedAdapter([]);
624
+ await assert.rejects(client(refused.adapter).answerConsent({ cwd: "/repo", consent: decodeReviewConsentV3(raw, "pi"), answer: "granted", requestContextPath: changed }), /context/);
625
+ assert.equal(refused.calls.length, 0);
626
+ }
627
+ });
628
+
629
+ test("request context refuses absent or unsupported advertised capabilities before STATUS or START", async () => {
630
+ for (const features of [[], ["start_request_context"], ["start_options_preflight"]]) {
631
+ const host = contextClient([], features);
632
+ await assert.rejects(host.client.start({ cwd: "/repo", requestContextPath: "/spec.md" }), /provider does not support request context/);
633
+ assert.equal(host.calls.length, 1);
634
+ }
635
+ const host = contextClient([]);
636
+ const adapter: ExecFileAdapter = async request => {
637
+ const response = await host.adapter(request);
638
+ const body = JSON.parse(response.stdout);
639
+ body.features.optional.find((f: { name: string }) => f.name === "start_request_context").supported = false;
640
+ return { ...response, stdout: JSON.stringify(body) };
641
+ };
642
+ await assert.rejects(new NativeReviewCliV216(adapter, join(process.cwd(), "package.json")).targetStatus({ cwd: "/repo", requestContextPath: "/spec.md" }), /provider does not support request context/);
643
+ assert.equal(host.calls.length, 1);
644
+ });
645
+
646
+ test("START never drops requested context from a malformed provider transition", async () => {
647
+ const host = contextClient([{ stdout: JSON.stringify(negotiatedStartStatus(TARGET, [])) }]);
648
+ await assert.rejects(host.client.start({ cwd: "/repo", requestContextPath: "/spec.md" }), /did not retain the requested context/);
649
+ assert.equal(host.calls.length, 2);
650
+ });
651
+
652
+ test("invalid request context paths are refused before any native invocation", async () => {
653
+ for (const path of ["", " spaced ", "bad\0path"]) {
654
+ const queue = queuedAdapter([]);
655
+ await assert.rejects(client(queue.adapter).start({ cwd: "/repo", requestContextPath: path }), /requestContextPath/);
656
+ assert.equal(queue.calls.length, 0);
657
+ }
658
+ });
659
+
434
660
  test("native START preflights the agent lens selection through STATUS", async () => {
435
661
  const tokens = [
436
662
  "--contract=gentle-ai.review-integration/v2", "--cwd=/repo", `--target=${TARGET}`,
@@ -1144,3 +1370,45 @@ test("the central gentle-ai environment carries Gentle AI's isolation variables
1144
1370
  const ordinary = gentleAiProcessEnvironment({ PATH: "/usr/bin" });
1145
1371
  assert.deepEqual(ordinary, { PATH: "/usr/bin", GENTLE_PI_REVIEW_RELAY_CONTRACT: "gentle-pi.review-relay/v1" });
1146
1372
  });
1373
+
1374
+ function requestContextConsent(path: string): Record<string, any> {
1375
+ const raw = fixture("consent-v3.captured.json") as Record<string, any>;
1376
+ raw.agent = "pi";
1377
+ for (const choice of raw.choices) choice.invocation = String(choice.invocation)
1378
+ .replace(/--cwd \S+ --target/, "--cwd /repo --target")
1379
+ .replace(" --consent ", " --agent pi --request-context '" + path + "' --consent ");
1380
+ return raw;
1381
+ }
1382
+
1383
+ test("request context is retained and checked before consent replay", async () => {
1384
+ const path = "/repo/spec with spaces.md";
1385
+ const raw = requestContextConsent(path);
1386
+ const tokens = ["--contract=gentle-ai.review-integration/v2", "--cwd=/repo", "--target=" + raw.target_identity, "--projection=workspace", "--agent=pi", "--consent=relay", "--request-context=" + path];
1387
+ const host = contextClient([{ stdout: JSON.stringify(negotiatedStartStatus(raw.target_identity, tokens)) }, { stdout: JSON.stringify(raw) }]);
1388
+ let pending: NativeReviewConsentRequiredError | undefined;
1389
+ try { await host.client.start({ cwd: "/repo", requestContextPath: path }); } catch (error) { assert.ok(error instanceof NativeReviewConsentRequiredError); pending = error; }
1390
+ assert.ok(pending);
1391
+ assert.equal(pending.requestContextPath, path);
1392
+ for (const mutation of ["missing", "changed", "duplicate"]) {
1393
+ const copy = requestContextConsent(path);
1394
+ copy.choices[0].invocation = mutation === "missing" ? copy.choices[0].invocation.replace(" --request-context '" + path + "'", "")
1395
+ : mutation === "changed" ? copy.choices[0].invocation.replace(path, "/other.md")
1396
+ : copy.choices[0].invocation.replace(" --consent ", " --request-context '/other.md' --consent ");
1397
+ const queue = queuedAdapter([]);
1398
+ await assert.rejects(client(queue.adapter).answerConsent({ cwd: "/repo", consent: decodeReviewConsentV3(copy, "pi"), answer: "granted", requestContextPath: path }), /context/);
1399
+ assert.equal(queue.calls.length, 0);
1400
+ }
1401
+ const queue = queuedAdapter([{ stdout: JSON.stringify(reviewingStartV4(raw.target_identity)) }]);
1402
+ assert.equal((await client(queue.adapter).answerConsent({ cwd: "/repo", consent: pending.consent, answer: "granted", requestContextPath: path } as any)).kind, "started");
1403
+ assert.ok(queue.calls[0].arguments.includes(path));
1404
+ });
1405
+
1406
+ test("START refuses consent choices that lose the requested context before presenting consent", async () => {
1407
+ const path = "/repo/spec.md";
1408
+ const raw = requestContextConsent(path);
1409
+ raw.choices[1].invocation = raw.choices[1].invocation.replace(" --request-context '" + path + "'", "");
1410
+ const tokens = ["--contract=gentle-ai.review-integration/v2", "--cwd=/repo", "--target=" + raw.target_identity, "--projection=workspace", "--agent=pi", "--consent=relay", "--request-context=" + path];
1411
+ const host = contextClient([{ stdout: JSON.stringify(negotiatedStartStatus(raw.target_identity, tokens)) }, { stdout: JSON.stringify(raw) }]);
1412
+ await assert.rejects(host.client.start({ cwd: "/repo", requestContextPath: path }), /context/);
1413
+ assert.equal(host.calls.length, 3);
1414
+ });
@@ -31,7 +31,10 @@ test("clarification preserves understanding without reopening informed approval"
31
31
  test("resolved subdecisions retain the original authorized objective", () => {
32
32
  const prompt = __testing.buildGentlePrompt("gentleman");
33
33
  assert.ok(prompt.includes("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."));
34
- assert.ok(prompt.includes("Stop only for an unresolved consequential scope/product decision, required explicit consent, a denied action, unavailable required proof, or the human's explicit stop."));
34
+ assert.ok(prompt.includes("Stop for an unresolved consequential scope/product decision, required explicit consent, a denied action, or the human's explicit stop."));
35
+ assert.ok(prompt.includes("Unavailable required proof blocks completion and delivery; it does not alone prohibit specifically authorized in-scope implementation where actual native authority and other limits permit it."));
36
+ assert.ok(prompt.includes("After a setup prerequisite is repaired, the human may explicitly request one new bounded verification attempt."));
37
+ assert.ok(prompt.includes("Never bypass consent, a denial, explicit one-run or no-retry limits, terminal native outcomes, or exhausted native budgets."));
35
38
  assert.ok(prompt.includes("Do not infer permission for publishing, destructive actions, unrelated scope or native consent from this continuity rule."));
36
39
  });
37
40
 
@@ -168,8 +168,8 @@ const ANCHORS: readonly RoutingAnchor[] = [
168
168
  canonical: "**Verification trigger:** only a change whose Risk line names a high-risk item gets an independent verifier",
169
169
  mirrors: [
170
170
  // Verification by named risk: the core row names the escalate-only verifier.
171
- { surface: CORE, includes: "**Verification rule** — only a named high-risk item (assess `escalate`) → independent `gentle-ai-verify`" },
172
- { surface: DELEGATION, includes: "only a change whose Risk line names a high-risk item (Task Size, assess `escalate`) gets an independent `gentle-ai-verify` run" },
171
+ { surface: CORE, includes: "**Verification rule** — only a named high-risk item (assess `escalate` when RDD is on or unknown) → independent `gentle-ai-verify`" },
172
+ { surface: DELEGATION, includes: "only a change whose Risk line names a high-risk item (Task Size, assess `escalate` when RDD is on or unknown) gets an independent `gentle-ai-verify` run" },
173
173
  ],
174
174
  },
175
175
  {
@@ -238,7 +238,7 @@ const ANCHORS: readonly RoutingAnchor[] = [
238
238
  // rows, so they are mirror-only and not anchors of the canonical routing block.
239
239
  const CORE_ONLY_TRIGGERS = [
240
240
  "**Incident rule** — diagnose wrong cwd/worktree/git/tooling incidents separately",
241
- "**Verification rule** — only a named high-risk item (assess `escalate`) → independent `gentle-ai-verify`",
241
+ "**Verification rule** — only a named high-risk item (assess `escalate` when RDD is on or unknown) → independent `gentle-ai-verify`",
242
242
  ] as const;
243
243
 
244
244
  // The verified mirrored routing/pi.md: the bundle tree must pass the strict
@@ -36,7 +36,10 @@ const FIXTURE_PATH = join(import.meta.dirname, "fixtures", "orchestrator.pre-die
36
36
  // Weak-model economy (small path reads one batch with no todo; item 1 excludes rebuildable dev/test data), measured in
37
37
  // gentle-shell-bench 1321c60 (DeepSeek -24-30% time on x2/x5, -70% on a dev-database rename; Sol unchanged), user decision
38
38
  // 2026-10-22: 9,100 -> 9,250 B.
39
- const BUDGET_BYTES = 9250;
39
+ // Issue #2935 (user decision 2026-11-06): 9,250 -> 9,350 B so the confinement clause keeps its full wording
40
+ // (registered same-clone worktrees, never-blanket grants) while adding the resolved-skill-read exception; the
41
+ // controlled 128-char assets root needs the headroom for platform-independent rendering.
42
+ const BUDGET_BYTES = 9350;
40
43
  const MIN_CONTROLLED_LONG_ASSETS_ROOT_CHARS = 93;
41
44
 
42
45
  const LAZY_ASSET_NAMES = [
@@ -129,7 +132,7 @@ function measureOrchestratorPromptBytes(assetsDir: string): number {
129
132
  // measuring a shorter render again.
130
133
  const RDD_WORST_CASE_LINE = "Receipt-driven development: unknown (native status unavailable)";
131
134
 
132
- test("getOrchestratorPrompt return value stays within the canonical 9,250 B budget at a short assets root", () => {
135
+ test("getOrchestratorPrompt return value stays within the canonical 9,350 B budget at a short assets root", () => {
133
136
  const rendered = __testing.renderOrchestratorPrompt(representativeProductionAssetsDir);
134
137
  assert.ok(
135
138
  rendered.includes(RDD_WORST_CASE_LINE),
@@ -332,6 +335,8 @@ for (const range of DISPOSITION_MAP) {
332
335
  if (raw === undefined || !isNormativeLine(raw)) continue;
333
336
  const trimmed = raw.trim();
334
337
  const expected =
338
+ // Preserve the synthesis rule while reserving core bytes for the RDD scope condition.
339
+ ln === 13 ? "Default to concise synthesis: decision, outcome, next action. Expand on request or when detail is needed." :
335
340
  ln === 36 ? "- Substantial authorized work: use ODD; track feature progress automatically." :
336
341
  trimmed;
337
342
  if (SUPERSEDED_LIFECYCLE_REVIEW_LINES.has(ln)) {
@@ -0,0 +1,153 @@
1
+ import assert from "node:assert/strict";
2
+ import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import test, { after } from "node:test";
6
+
7
+ // ---------------------------------------------------------------------------
8
+ // full-delegation-mode S1/S3/S4/S7: one workflow block per turn, chosen by the
9
+ // profile, never both at once.
10
+ //
11
+ // The organic path is the compatibility surface: a profile that did not opt in
12
+ // must render the asset byte for byte, because every existing session and every
13
+ // budget measurement was taken against exactly those bytes.
14
+ // ---------------------------------------------------------------------------
15
+
16
+ const REPO_ROOT = join(import.meta.dirname, "..");
17
+ const REAL_ASSETS_DIR = join(REPO_ROOT, "assets");
18
+ const VARIANT_FILE = "orchestrator-full-delegation.md";
19
+ const ORGANIC_START = "You are a COORDINATOR, not the default executor for substantial work.";
20
+ const ORGANIC_END = "{{GENTLE_PI_BACKGROUND_POLICY}}";
21
+
22
+ const { __testing } = await import("../extensions/gentle-ai.ts");
23
+
24
+ const scratch: string[] = [];
25
+ function assetsDirWith(transform: (files: Record<string, string>) => Record<string, string> = (files) => files): string {
26
+ const dir = mkdtempSync(join(tmpdir(), "gp-delegation-mode-"));
27
+ scratch.push(dir);
28
+ const files: Record<string, string> = {
29
+ "orchestrator.md": readFileSync(join(REAL_ASSETS_DIR, "orchestrator.md"), "utf8"),
30
+ [VARIANT_FILE]: readFileSync(join(REAL_ASSETS_DIR, VARIANT_FILE), "utf8"),
31
+ };
32
+ for (const [name, content] of Object.entries(transform(files))) {
33
+ mkdirSync(dir, { recursive: true });
34
+ writeFileSync(join(dir, name), content);
35
+ }
36
+ return dir;
37
+ }
38
+ after(() => {
39
+ for (const dir of scratch) rmSync(dir, { recursive: true, force: true });
40
+ });
41
+
42
+ const organic = (dir: string) => __testing.renderOrchestratorPrompt(dir);
43
+ const full = (dir: string) => __testing.renderOrchestratorPrompt(dir, undefined, undefined, "full-delegation");
44
+
45
+ test("a profile that did not opt in renders the organic workflow region byte for byte", () => {
46
+ const dir = assetsDirWith();
47
+ const raw = readFileSync(join(REAL_ASSETS_DIR, "orchestrator.md"), "utf8");
48
+ const region = raw.slice(raw.indexOf(ORGANIC_START), raw.indexOf(ORGANIC_END));
49
+ assert.ok(region.length > 1000, "the fixture must actually span the organic workflow rules");
50
+ const rendered = organic(dir);
51
+ assert.ok(rendered.includes(region), "the organic region must survive rendering unchanged");
52
+ assert.equal(rendered, __testing.renderOrchestratorPrompt(dir, undefined, undefined, "organic"));
53
+ assert.equal(rendered.includes("in full delegation mode: you never implement"), false);
54
+ });
55
+
56
+ test("full delegation mode replaces the organic rules instead of adding to them", () => {
57
+ const dir = assetsDirWith();
58
+ const rendered = full(dir);
59
+ const variant = readFileSync(join(REAL_ASSETS_DIR, VARIANT_FILE), "utf8").trim();
60
+ const [beforeRisk, afterRisk] = variant.split("{{GENTLE_PI_HIGH_RISK_ITEMS}}");
61
+ assert.ok(rendered.includes(beforeRisk!.trim()) && rendered.includes(afterRisk!.trim()), "the variant block must be injected around its high-risk items");
62
+ assert.equal(rendered.includes(ORGANIC_START), false, "the organic role text must be gone, not merely followed");
63
+ // Task Size survives as tracking and risk only; its inline route does not.
64
+ assert.match(rendered, /## Task Size\n\nTask size decides tracking and risk, never who writes\./);
65
+ assert.equal(rendered.includes("Small path: inline"), false);
66
+ assert.equal(rendered.split("in full delegation mode: you never implement").length - 1, 1, "exactly one mode block");
67
+ });
68
+
69
+ test("both modes keep the shared sections, the lazy pointers and the rendered tokens", () => {
70
+ for (const rendered of [organic(assetsDirWith()), full(assetsDirWith())]) {
71
+ for (const shared of ["## Memory Contract", "## Safety", "## Skill Registry Protocol"]) {
72
+ assert.ok(rendered.includes(shared), `missing shared section: ${shared}`);
73
+ }
74
+ assert.ok(rendered.includes("orchestrator-prompts.md"), "the shared lazy pointers stay reachable");
75
+ assert.equal(rendered.includes("{{"), false, "no unrendered token may leak into the prompt");
76
+ }
77
+ // Each mode names its own routing detail and never the other's.
78
+ assert.ok(organic(assetsDirWith()).includes("orchestrator-delegation-reference.md"));
79
+ assert.equal(full(assetsDirWith()).includes("orchestrator-delegation-reference.md"), false);
80
+ assert.ok(full(assetsDirWith()).includes("orchestrator-full-delegation-card.md"));
81
+ });
82
+
83
+ test("the high-risk items keep one definition, taken from the organic core", () => {
84
+ const dir = assetsDirWith();
85
+ const highRisk = readFileSync(join(REAL_ASSETS_DIR, "orchestrator.md"), "utf8").split("\n").find((line) => line.startsWith("**High risk**:"));
86
+ assert.ok(highRisk);
87
+ assert.ok(full(dir).includes(highRisk), "the variant carries the organic paragraph itself, not a copy");
88
+ });
89
+
90
+ test("a missing high-risk paragraph falls back to the organic rules instead of a variant with no risk list", () => {
91
+ const dir = assetsDirWith((files) => ({ ...files, "orchestrator.md": files["orchestrator.md"].replace("**High risk**:", "**Risk, reworded upstream**:") }));
92
+ const rendered = full(dir);
93
+ assert.ok(rendered.includes("Small path: inline"), "the organic rules stay whole when the variant cannot be completed");
94
+ assert.equal(rendered.includes("in full delegation mode: you never implement"), false);
95
+ });
96
+
97
+ test("full delegation mode is not more expensive in context than the rules it replaces", () => {
98
+ const dir = assetsDirWith();
99
+ const organicBytes = Buffer.byteLength(organic(dir), "utf8");
100
+ const fullBytes = Buffer.byteLength(full(dir), "utf8");
101
+ assert.ok(
102
+ fullBytes < organicBytes,
103
+ `full delegation must cost less context than organic (${fullBytes} B vs ${organicBytes} B)`,
104
+ );
105
+ });
106
+
107
+ test("a missing variant asset falls back to the organic rules instead of a broken splice", () => {
108
+ const dir = assetsDirWith((files) => {
109
+ const { [VARIANT_FILE]: _dropped, ...rest } = files;
110
+ return rest;
111
+ });
112
+ const rendered = full(dir);
113
+ assert.equal(rendered, organic(dir));
114
+ assert.ok(rendered.includes("## Task Size"));
115
+ });
116
+
117
+ test("a drifted organic anchor falls back to the organic rules instead of a broken splice", () => {
118
+ const dir = assetsDirWith((files) => ({
119
+ ...files,
120
+ "orchestrator.md": files["orchestrator.md"].replace(ORGANIC_START, "You are a COORDINATOR, reworded upstream."),
121
+ }));
122
+ const rendered = full(dir);
123
+ assert.ok(rendered.includes("## Task Size"), "the organic rules stay whole when the splice cannot be made");
124
+ assert.equal(rendered.includes("in full delegation mode: you never implement"), false);
125
+ });
126
+
127
+ test("an empty variant asset falls back to the organic rules", () => {
128
+ const dir = assetsDirWith((files) => ({ ...files, [VARIANT_FILE]: " \n\n" }));
129
+ assert.equal(full(dir), organic(dir));
130
+ });
131
+
132
+ test("the memoized core is keyed by the mode, so a switch cannot serve stale rules", () => {
133
+ const cwd = REPO_ROOT;
134
+ const organicPrompt = __testing.getOrchestratorPrompt(cwd);
135
+ const fullPrompt = __testing.getOrchestratorPrompt(cwd, undefined, undefined, undefined, "full-delegation");
136
+ assert.notEqual(organicPrompt, fullPrompt, "a stale cache entry would return the previous profile's rules");
137
+ assert.ok(organicPrompt.includes("Small path: inline"));
138
+ assert.equal(fullPrompt.includes("Small path: inline"), false);
139
+ // Repeating each call still hits its own cache entry and never mixes them.
140
+ assert.equal(__testing.getOrchestratorPrompt(cwd), organicPrompt);
141
+ assert.equal(__testing.getOrchestratorPrompt(cwd, undefined, undefined, undefined, "full-delegation"), fullPrompt);
142
+ });
143
+
144
+ // gentle-shell#379: delegation stays inside the current runtime. The open
145
+ // "another available delegation mechanism" fallback is gone from the routing
146
+ // detail and the reference docs, and each names the stop rule instead.
147
+ test("delegation fallback never leaves the current runtime", () => {
148
+ for (const path of [join(REAL_ASSETS_DIR, "orchestrator-delegation-reference.md"), join(REPO_ROOT, "docs", "readme-reference.md")]) {
149
+ const text = readFileSync(path, "utf8");
150
+ assert.equal(text.includes("another available delegation mechanism"), false, path);
151
+ assert.match(text, /never fall back to an external pane, terminal, session, window, or remote worker/, path);
152
+ }
153
+ });