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
@@ -0,0 +1,183 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { setImmediate as nextTurn } from "node:timers/promises";
6
+ import test from "node:test";
7
+ import { runInProcessReviewer, type InProcessReviewerDeps, type InProcessReviewerOutcome } from "../lib/inprocess-reviewer.ts";
8
+ import { prepareReviewHostRelaySlot, submitReviewHostRelayPreparedResult, ReviewHostRelayError, REVIEW_HOST_RELAY_FAILURE, type ReviewHostRelayRequest } from "../lib/review-host-relay.ts";
9
+
10
+ const model = { id: "fixture-model", provider: "fixture", api: "openai-completions", baseUrl: "https://PRIVATE.invalid", reasoning: false, input: ["text"], cost: { input: 1, output: 1, cacheRead: 1, cacheWrite: 1 }, contextWindow: 1000, maxTokens: 100 };
11
+ const raw = '{"findings":[],"evidence":["fixture"]}\n';
12
+ const request = { selection: "fixture/fixture-model", prompt: Buffer.from("PRIVATE PROMPT"), timeoutMs: 30_000, routingKey: "review-risk" };
13
+ const assistant = (overrides: Record<string, unknown> = {}) => ({ role: "assistant", content: [{ type: "text", text: raw }], api: "openai-completions", provider: "fixture", model: "fixture-model", stopReason: "stop", timestamp: 0,
14
+ usage: { input: 12, output: 3, cacheRead: 2, totalTokens: 17, private: "PRIVATE USAGE", cost: { input: 0.12, output: 0.03, total: 0.15, totalFromProvider: false, private: "PRIVATE COST" } }, ...overrides });
15
+ const deps = (overrides: Record<string, unknown> = {}): InProcessReviewerDeps => ({
16
+ registry: { find: () => model, getApiKeyAndHeaders: async () => ({ ok: true, apiKey: "PRIVATE KEY", headers: { private: "PRIVATE HEADER" }, env: { private: "PRIVATE ENV" } }) },
17
+ complete: async () => assistant(), ...overrides,
18
+ } as unknown as InProcessReviewerDeps);
19
+ /** Require host evidence without narrowing away refused reviewer outcomes. */
20
+ function evidence(outcome: InProcessReviewerOutcome): Record<string, any> {
21
+ const value = (outcome as { evidence?: Record<string, unknown> }).evidence;
22
+ assert.ok(value, "a resolved reviewer run must carry host evidence");
23
+ return value;
24
+ }
25
+ /** Check available phase measurements while preserving unknown completion time. */
26
+ function timings(value: Record<string, any>, completion: boolean) {
27
+ assert.equal(typeof value.durationMs, "number"); assert.ok(value.durationMs >= 0);
28
+ assert.equal(typeof value.authDurationMs, "number"); assert.ok(value.authDurationMs >= 0);
29
+ assert.equal(typeof value.completionDurationMs, completion ? "number" : "undefined");
30
+ }
31
+
32
+ test("reviewer success carries allowlisted reported usage/cost and effective identity without private payloads", async () => {
33
+ const outcome = await runInProcessReviewer(request, deps());
34
+ assert.equal(outcome.kind, "text");
35
+ const value = evidence(outcome);
36
+ assert.equal(value.reviewerModel, "fixture/fixture-model"); assert.equal(value.provider, "fixture"); assert.equal(value.phase, "completion");
37
+ assert.deepEqual(value.usage, { input: 12, output: 3, cacheRead: 2, totalTokens: 17 });
38
+ assert.deepEqual(value.cost, { input: 0.12, output: 0.03, total: 0.15, totalFromProvider: false });
39
+ timings(value, true);
40
+ assert.doesNotMatch(JSON.stringify(value), /PRIVATE|baseUrl|apiKey|headers|signature|prompt|findings|private/);
41
+ });
42
+
43
+ test("reviewer evidence leaves unavailable usage and cost unknown instead of manufacturing zeros", async () => {
44
+ const value = evidence(await runInProcessReviewer(request, deps({ complete: async () => assistant({ usage: undefined }) })));
45
+ assert.equal(Object.hasOwn(value, "usage"), false); assert.equal(Object.hasOwn(value, "cost"), false);
46
+ const partial = evidence(await runInProcessReviewer(request, deps({ complete: async () => assistant({ usage: { input: 0, output: -1, cacheRead: Infinity, totalTokens: "4", cost: { total: NaN, input: -1, private: "PRIVATE" } } }) })));
47
+ assert.deepEqual(partial.usage, { input: 0 }); assert.equal(Object.hasOwn(partial, "cost"), false);
48
+ });
49
+
50
+ test("reviewer refusals preserve available completion usage without promoting private error text to evidence", async () => {
51
+ for (const response of [assistant({ stopReason: "error", errorMessage: "PRIVATE PROVIDER ERROR" }), assistant({ content: [], stopReason: "length" }), assistant({ content: [{ type: "toolCall", name: "PRIVATE TOOL", arguments: { private: "PRIVATE ARG" } }], stopReason: "toolUse" })]) {
52
+ const outcome = await runInProcessReviewer(request, deps({ complete: async () => response }));
53
+ assert.equal(outcome.kind, "refused");
54
+ const value = evidence(outcome); assert.equal(value.phase, "completion"); assert.equal(value.usage.output, 3); assert.equal(value.cost.total, 0.15);
55
+ assert.doesNotMatch(JSON.stringify(value), /PRIVATE|errorMessage|arguments/);
56
+ }
57
+ });
58
+
59
+ test("auth failure and non-cooperative auth timeout carry auth phase without fabricated completion usage", async t => {
60
+ t.mock.timers.enable({ apis: ["setTimeout"] });
61
+ for (const never of [false, true]) {
62
+ let entered!: () => void;
63
+ const began = new Promise<void>(resolve => { entered = resolve; });
64
+ const getApiKeyAndHeaders = async () => { entered(); return never ? await new Promise(() => {}) : { ok: false, error: "fixture auth unavailable" }; };
65
+ const pending = runInProcessReviewer(request, deps({ registry: { find: () => model, getApiKeyAndHeaders }, complete: async () => { throw new Error("must not dispatch"); } }));
66
+ await began;
67
+ if (never) t.mock.timers.tick(request.timeoutMs);
68
+ const outcome = await pending;
69
+ assert.equal(outcome.kind, "refused"); const value = evidence(outcome);
70
+ assert.equal(value.phase, "auth"); timings(value, false);
71
+ assert.equal(Object.hasOwn(value, "usage"), false); assert.equal(Object.hasOwn(value, "cost"), false);
72
+ }
73
+ });
74
+
75
+ test("timeout and abort snapshots keep each phase within the total duration", async t => {
76
+ for (const phase of ["auth", "completion"] as const) for (const stop of ["timeout", "abort"] as const) {
77
+ await t.test(`${phase} ${stop}`, async child => {
78
+ child.mock.timers.enable({ apis: ["setTimeout"] });
79
+ let advancing = false, clock = 0, entered!: () => void;
80
+ child.mock.method(performance, "now", () => advancing ? clock++ : 0);
81
+ const started = new Promise<void>(resolve => { entered = resolve; });
82
+ const hold = async () => { entered(); return await new Promise<never>(() => {}); };
83
+ const controller = new AbortController();
84
+ const pending = runInProcessReviewer({ ...request, timeoutMs: 1000, signal: controller.signal }, deps({
85
+ registry: { find: () => model, getApiKeyAndHeaders: phase === "auth" ? hold : async () => ({ ok: true, apiKey: "fixture" }) },
86
+ complete: phase === "completion" ? hold : async () => assistant(),
87
+ }));
88
+ await started;
89
+ advancing = true; clock = stop === "timeout" ? 1000 : 100;
90
+ if (stop === "timeout") child.mock.timers.tick(1000); else controller.abort();
91
+ const outcome = await pending;
92
+ assert.equal(outcome.kind, "refused");
93
+ if (outcome.kind === "refused") assert.equal(outcome.code, stop === "timeout" ? "timed-out" : "aborted");
94
+ const value = evidence(outcome);
95
+ assert.equal(value.phase, phase);
96
+ for (const key of ["authDurationMs", "completionDurationMs"]) if (typeof value[key] === "number") {
97
+ assert.ok(value.durationMs >= value[key], `${key} must fit within durationMs`);
98
+ }
99
+ });
100
+ }
101
+ });
102
+
103
+ test("evidence observers cannot mutate returned facts, change classification, throw or delay settlement", async () => {
104
+ let observed: unknown;
105
+ const outcome = await runInProcessReviewer(request, deps({ onEvidence: (value: Record<string, any>) => { observed = value; value.usage.input = 999; throw new Error("PRIVATE OBSERVER ERROR"); } }));
106
+ assert.ok(observed); assert.equal(outcome.kind, "text"); assert.equal(evidence(outcome).usage.input, 12);
107
+ const thrown = new Error("PRIVATE AUTH ERROR"); let failureEvidence: Record<string, any> | undefined;
108
+ await assert.rejects(runInProcessReviewer(request, deps({ registry: { find: () => model, getApiKeyAndHeaders: async () => { throw thrown; } }, onEvidence: async (value: Record<string, any>) => { failureEvidence = value; throw new Error("PRIVATE ASYNC OBSERVER ERROR"); } })), error => error === thrown);
109
+ await nextTurn(); assert.equal(failureEvidence?.phase, "auth"); assert.doesNotMatch(JSON.stringify(failureEvidence), /PRIVATE/);
110
+ const controller = new AbortController(); controller.abort();
111
+ const cancelled = await runInProcessReviewer({ ...request, signal: controller.signal }, deps({ onEvidence: async () => await new Promise(() => {}) }));
112
+ assert.equal(cancelled.kind, "refused"); if (cancelled.kind === "refused") assert.equal(cancelled.code, "aborted");
113
+ });
114
+
115
+ test("late completion cannot publish usage or notify observers after cancellation settled the run", async () => {
116
+ let release!: (value: unknown) => void, entered!: () => void;
117
+ const started = new Promise<void>(resolve => { entered = resolve; });
118
+ const completion = new Promise(resolve => { release = resolve; });
119
+ const controller = new AbortController(), observed: Record<string, unknown>[] = [];
120
+ const pending = runInProcessReviewer({ ...request, signal: controller.signal }, deps({
121
+ complete: async () => { entered(); return await completion; }, onEvidence: value => { observed.push(value); },
122
+ }));
123
+ await started; controller.abort();
124
+ const outcome = await pending;
125
+ assert.equal(outcome.kind, "refused"); if (outcome.kind === "refused") assert.equal(outcome.code, "aborted");
126
+ const before = structuredClone(evidence(outcome)); assert.equal(before.phase, "completion");
127
+ assert.equal(Object.hasOwn(before, "usage"), false); assert.equal(observed.length, 1);
128
+ release(assistant()); await nextTurn();
129
+ assert.deepEqual(evidence(outcome), before); assert.equal(observed.length, 1);
130
+ });
131
+
132
+ test("malformed diagnostic getters cannot invalidate an otherwise usable completion", async () => {
133
+ const usage = { input: 4 };
134
+ Object.defineProperty(usage, "cost", { get() { throw new Error("PRIVATE DIAGNOSTIC GETTER"); } });
135
+ const outcome = await runInProcessReviewer(request, deps({ complete: async () => assistant({ usage }) }));
136
+ assert.equal(outcome.kind, "text"); if (outcome.kind === "text") assert.equal(outcome.text, raw);
137
+ assert.equal(evidence(outcome).phase, "completion");
138
+ assert.doesNotMatch(JSON.stringify(evidence(outcome)), /PRIVATE/);
139
+ });
140
+
141
+ /** Build a disposable Node-backed native transport fixture with no model calls. */
142
+ function relayFixture(t: test.TestContext, rejectSubmission = false): ReviewHostRelayRequest {
143
+ const cwd = mkdtempSync(join(tmpdir(), "reviewer-evidence-"));
144
+ t.after(() => rmSync(cwd, { recursive: true, force: true }));
145
+ // Portable executable fixture: node runs cwd/review. No shebang, fake pi,
146
+ // native state, real model, credentials or network are involved.
147
+ writeFileSync(join(cwd, "review"), `const fs=require('node:fs');const args=process.argv.slice(2);if(args.includes('--materialize=true'))process.stdout.write('PRIVATE FROZEN PROMPT');else{const input=args.find(v=>v.startsWith('--input=')).slice(8);fs.writeFileSync('submitted.raw',fs.readFileSync(input));${rejectSubmission ? "process.stderr.write('fixture refused [invalid_request]');process.exitCode=1;" : "process.stdout.write('{\"admission_decision\":\"completed\"}');"}}`);
148
+ return { captureArgumentTokens: ["--agent=pi", "--materialize=true"], submission: { operationToken: "capture-result", argumentTokens: ["--input={{value}}"], values: [{ slot: "reviewer_result", domain: "artifact_path_or_stdin", substitutionLocation: 0 }] },
149
+ gentleAiExecutable: process.execPath, targetCwd: cwd, reviewerRegistry: deps().registry,
150
+ selection: request.selection, routingKey: request.routingKey, environment: { ...process.env }, gentleAiTimeoutMs: 5_000, piTimeoutMs: 30_000 };
151
+ }
152
+
153
+ test("relay preserves reviewer evidence through prepare and submission without altering native artifact bytes", async t => {
154
+ const fixture = relayFixture(t);
155
+ let completionEvidence: Record<string, any> | undefined;
156
+ const prepared = await prepareReviewHostRelaySlot(fixture, async (req, dependencies) => {
157
+ const outcome = await runInProcessReviewer(req, { ...dependencies, complete: deps().complete });
158
+ completionEvidence = evidence(outcome); return outcome;
159
+ });
160
+ assert.equal((prepared as any).reviewerEvidence?.phase, "completion");
161
+ assert.equal((prepared as any).reviewerEvidence?.usage.totalTokens, 17);
162
+ completionEvidence!.usage.totalTokens = 999;
163
+ assert.equal((prepared as any).reviewerEvidence?.usage.totalTokens, 17, "prepare snapshots host facts independently of the completion outcome");
164
+ const result = await submitReviewHostRelayPreparedResult(prepared);
165
+ assert.deepEqual((result as any).reviewerEvidence, (prepared as any).reviewerEvidence);
166
+ assert.equal(readFileSync(join(fixture.targetCwd!, "submitted.raw"), "utf8"), raw);
167
+ assert.equal(result.submission, '{"admission_decision":"completed"}');
168
+ assert.doesNotMatch(JSON.stringify((result as any).reviewerEvidence), /PRIVATE|headers|apiKey|prompt|submission|findings/);
169
+ });
170
+
171
+ test("relay auth throw and admission refusal retain host evidence while preserving failure classification", async t => {
172
+ const fixture = relayFixture(t);
173
+ await assert.rejects(prepareReviewHostRelaySlot(fixture, (req, dependencies) => runInProcessReviewer(req, { ...dependencies, registry: { find: () => model as never, getApiKeyAndHeaders: async () => { throw new Error("fixture auth throw"); } } })), error => {
174
+ assert.ok(error instanceof ReviewHostRelayError); assert.equal(error.kind, REVIEW_HOST_RELAY_FAILURE.PI_FAILED); assert.equal(error.stage, "pi"); assert.equal(error.mutationOutcome, "none");
175
+ assert.equal(error.reviewerEvidence?.phase, "auth"); return true;
176
+ });
177
+ const rejectedFixture = relayFixture(t, true);
178
+ const prepared = await prepareReviewHostRelaySlot(rejectedFixture, (req, dependencies) => runInProcessReviewer(req, { ...dependencies, complete: deps().complete }));
179
+ await assert.rejects(submitReviewHostRelayPreparedResult(prepared), error => {
180
+ assert.ok(error instanceof ReviewHostRelayError); assert.equal(error.kind, REVIEW_HOST_RELAY_FAILURE.SUBMISSION_REFUSED); assert.equal(error.stage, "submit"); assert.equal(error.mutationOutcome, "none");
181
+ assert.equal(error.reviewerEvidence?.phase, "completion"); assert.equal((error.reviewerEvidence?.cost as any)?.total, 0.15); return true;
182
+ });
183
+ });
@@ -1,6 +1,8 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { execFileSync } from "node:child_process";
3
- import { realpathSync } from "node:fs";
3
+ import { mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
4
6
  import test from "node:test";
5
7
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
6
8
  import { createGentleAiExtension, __testing } from "../extensions/gentle-ai.ts";
@@ -636,6 +638,75 @@ const ctx = { cwd: process.cwd() } as ExtensionContext;
636
638
  // removes the verifier the plan requires" pass it so a verifier is required.
637
639
  const ESCALATE = { escalate: { item: 3, reason: "changes a published export" } } as const;
638
640
 
641
+ for (const [label, input] of [["normal", undefined], ["escalated", ESCALATE], ["untrusted closure", { nativeReviewOutcome: "closed" }]] as const) test(`RDD off registered assess ${label} skips native calls and retains verification`, async (t) => {
642
+ const root = mkdtempSync(join(tmpdir(), "rdd-off-assess-"));
643
+ t.after(() => rmSync(root, { recursive: true, force: true }));
644
+ execFileSync("git", ["init", "-q"], { cwd: root, env: { PATH: process.env.PATH, HOME: root, GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null" } });
645
+ const state = join(root, "state.json");
646
+ writeFileSync(state, '{"unchanged":true}\n');
647
+ const calls = { mode: 0, assess: 0, target: 0 };
648
+ const cli = {
649
+ reviewMode: async () => { calls.mode++; return { operation: "status", scope: "clone", status: { global: "off", cloneLocal: "", effective: "off", source: "global" } }; },
650
+ assess: async () => { calls.assess++; return decodeReviewAssessmentV1(newEnvelope()); },
651
+ targetStatus: async () => { calls.target++; return { applicability: "current_target", targetIdentity: "fixture" }; },
652
+ } as unknown as NativeReviewCli;
653
+ const tool = reviewControllerTool(cli);
654
+ const context = { cwd: root } as ExtensionContext;
655
+ {
656
+ const result = await tool.execute("off", { operation: "assess", workspaceRoot: root, ...(input === undefined ? {} : { input: JSON.stringify(input) }) }, undefined, undefined, context);
657
+ const escalated = input !== undefined && "escalate" in input;
658
+ const risk = escalated ? VERIFICATION_TIER.HIGH : VERIFICATION_TIER.MEDIUM;
659
+ assert.deepEqual(result.details, {
660
+ operation: "assess", schema: "gentle-pi.review-assessment-plan/v1", risk, nativeRisk: "unassessable",
661
+ ...(escalated ? { agentEscalation: { item: 3, label: "changing or removing contracts others already consume", reason: ESCALATE.escalate.reason, applied: true } } : {}),
662
+ reasons: [{ code: "rdd-off-assessment-skipped", detail: "Native assessment skipped because receipt-driven development is off; changed counts were not measured." }],
663
+ changedPaths: 0, changedLines: 0, candidate: null, rddLine: "off", nativeReviewOutcome: "unknown", outcome_source: "unknown",
664
+ writerProfile: "small", writerProfileSource: "fallback",
665
+ plan: verificationPlan({ rddLine: RDD_LINE.OFF, risk, writerProfile: WRITER_PROFILE.SMALL, nativeReviewOutcome: NATIVE_REVIEW_OUTCOME.UNKNOWN }),
666
+ workspace_root: realpathSync(root),
667
+ });
668
+ assert.deepEqual(result.content, [{ type: "text", text: JSON.stringify(result.details) }]);
669
+ }
670
+ assert.deepEqual(calls, { mode: 1, assess: 0, target: 0 });
671
+ await assert.rejects(() => tool.execute("invalid", { operation: "assess", input: JSON.stringify({ baseRef: "HEAD" }) }, undefined, undefined, context), { message: "Review assess baseRef requires committedOnly: true" });
672
+ await assert.rejects(() => tool.execute("cancelled", { operation: "assess" }, AbortSignal.abort(), undefined, context), { message: "Review controller operation was cancelled" });
673
+ assert.deepEqual(calls, { mode: 1, assess: 0, target: 0 });
674
+ assert.equal(readFileSync(state, "utf8"), '{"unchanged":true}\n');
675
+ });
676
+
677
+ test("registered assess preserves on, malformed and failed mode paths without using a prior off result", async (t) => {
678
+ const root = mkdtempSync(join(tmpdir(), "rdd-assess-modes-"));
679
+ t.after(() => rmSync(root, { recursive: true, force: true }));
680
+ execFileSync("git", ["init", "-q"], { cwd: root, env: { PATH: process.env.PATH, HOME: root, GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null" } });
681
+ for (const mode of ["on", "malformed", "failed"] as const) {
682
+ const calls = { mode: 0, assess: 0, target: 0 };
683
+ let first = true;
684
+ const cli = {
685
+ reviewMode: async () => {
686
+ calls.mode++;
687
+ if (first) { first = false; return { status: { effective: "off", source: "global" } }; }
688
+ if (mode === "failed") throw new Error("mode unavailable");
689
+ return { status: { effective: mode === "on" ? "on" : "off", source: mode === "malformed" ? "invalid" : "global" } };
690
+ },
691
+ assess: async () => { calls.assess++; return decodeReviewAssessmentV1(newEnvelope()); },
692
+ targetStatus: async () => { calls.target++; return { applicability: "current_target", targetIdentity: "fixture" }; },
693
+ } as unknown as NativeReviewCli;
694
+ const tool = reviewControllerTool(cli);
695
+ const context = { cwd: root } as ExtensionContext;
696
+ await tool.execute("off", { operation: "assess" }, undefined, undefined, context);
697
+ assert.deepEqual(calls, { mode: 1, assess: 0, target: 0 });
698
+ const result = await tool.execute(mode, { operation: "assess" }, undefined, undefined, context);
699
+ const details = result.details as Record<string, unknown>;
700
+ assert.deepEqual(calls, { mode: 2, assess: 1, target: 1 }, mode);
701
+ assert.equal(details.rddLine, mode === "on" ? "on" : "unknown");
702
+ assert.equal(details.nativeRisk, "high");
703
+ assert.equal(details.risk, "medium");
704
+ assert.equal(details.reviewDue, true);
705
+ assert.deepEqual(details.nextTransition, nextTransition());
706
+ assert.deepEqual(result.content, [{ type: "text", text: JSON.stringify(result.details) }]);
707
+ }
708
+ });
709
+
639
710
  // Changed with verification by named risk: an unassessable candidate no longer
640
711
  // verifies like high; the plan is medium and the native tier stays visible.
641
712
  test("gentle_review assess: an older binary without the assess verb informs only (no verifier without escalate)", async () => {
@@ -1028,9 +1099,9 @@ test("gentle_review assess: an unassessable candidate is never closed", async ()
1028
1099
  test("gentle_review assess: derived closure only changes the RDD on-path; RDD off plans are unchanged", async () => {
1029
1100
  for (const risk of ["passive", "medium", "high"] as const) {
1030
1101
  for (const consumed of [true, false]) {
1031
- // The plan follows verificationRisk (native high without escalate is medium).
1102
+ // Off skips native assessment, so its fallback is unassessable even for a passive fixture.
1032
1103
  const off = await assessWith(closureCli({ rdd: "off", risk, consumed }), { writerModelId: "claude-sonnet-5", writerEffort: "high" });
1033
- const expectedOff = verificationPlan({ rddLine: RDD_LINE.OFF, risk: verificationRisk(risk, undefined), writerProfile: WRITER_PROFILE.LARGE });
1104
+ const expectedOff = verificationPlan({ rddLine: RDD_LINE.OFF, risk: verificationRisk(VERIFICATION_TIER.UNASSESSABLE, undefined), writerProfile: WRITER_PROFILE.LARGE });
1034
1105
  assert.deepEqual(off.plan, { ...expectedOff }, `off ${risk} consumed ${consumed}`);
1035
1106
  const on = await assessWith(closureCli({ rdd: "on", risk, consumed }), { writerModelId: "claude-sonnet-5", writerEffort: "high" });
1036
1107
  const expectedOn = verificationPlan({ rddLine: RDD_LINE.ON, risk: verificationRisk(risk, undefined), writerProfile: WRITER_PROFILE.LARGE, nativeReviewOutcome: consumed ? NATIVE_REVIEW_OUTCOME.CLOSED : NATIVE_REVIEW_OUTCOME.UNKNOWN });
@@ -267,6 +267,7 @@ function controllerHarness(cwd: string, processEnv: NodeJS.ProcessEnv = {}, opti
267
267
  childStandingReviewPermissionClient?: ChildStandingReviewPermissionClient;
268
268
  consent?: ReviewConsentEnvelope;
269
269
  targetStatus?: (request: Record<string, unknown>) => Promise<ReviewStatusV3>;
270
+ emitted?: Array<{ channel: string; data: unknown }>;
270
271
  } = {}) {
271
272
  const tools = new Map<string, RegisteredTool>();
272
273
  const commands = new Map<string, RegisteredCommand>();
@@ -300,7 +301,7 @@ function controllerHarness(cwd: string, processEnv: NodeJS.ProcessEnv = {}, opti
300
301
  on(name: string, handler: RegisteredEvent) { events.set(name, handler); },
301
302
  registerCommand(name: string, definition: RegisteredCommand) { commands.set(name, definition); },
302
303
  registerTool(definition: RegisteredTool & { name: string }) { tools.set(definition.name, definition); },
303
- events: { emit() {} },
304
+ events: { emit(channel: string, data: unknown) { options.emitted?.push({ channel, data }); } },
304
305
  } as unknown as ExtensionAPI);
305
306
  const controller = tools.get("gentle_review");
306
307
  assert.ok(controller);
@@ -413,6 +414,25 @@ test("provider grant and decline remain candidate-only and cancellation stores n
413
414
  assert.equal(prompts, 3, "neither provider choice creates standing host permission");
414
415
  });
415
416
 
417
+ test("the review consent prompt projects one balanced Herdr blocker while it awaits the human", async (t) => {
418
+ const cwd = reviewRepository(t);
419
+ const emitted: Array<{ channel: string; data: unknown }> = [];
420
+ const runtime = controllerHarness(cwd, {}, { emitted });
421
+ const herdr = () => emitted.filter(({ channel }) => channel === "herdr:blocked").map(({ data }) => data);
422
+ const observedWhilePrompting: unknown[][] = [];
423
+ const ctx = interactiveContext(cwd, {}, async (_title, options) => {
424
+ observedWhilePrompting.push(herdr());
425
+ return options[0];
426
+ });
427
+ await runtime.controller.execute("herdr-consent", { operation: "start", input: JSON.stringify({ mode: "ordinary" }) }, undefined, undefined, ctx);
428
+ assert.deepEqual(observedWhilePrompting, [[{ active: true, label: "Review authorization awaiting input" }]], "Herdr sees the pane as blocked while the authorization is open");
429
+ assert.deepEqual(herdr(), [
430
+ { active: true, label: "Review authorization awaiting input" },
431
+ { active: false },
432
+ ], "the blocker is released once the human answers");
433
+ assert.deepEqual(runtime.answers, ["granted"]);
434
+ });
435
+
416
436
  test("explicit revocation ends the host grant without changing provider mode or authority", async (t) => {
417
437
  const cwd = reviewRepository(t);
418
438
  const runtime = controllerHarness(cwd);
@@ -0,0 +1,19 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { snapshotReviewStartContext } from "../lib/review-start-context.ts";
4
+
5
+ test("retained intent cannot be changed through caller-owned lens arrays", () => {
6
+ const lenses = ["review-risk"];
7
+ const context = snapshotReviewStartContext({ lenses, lensesReason: "permission checks", requestContextPath: "/repo/spec.md", policyPath: "/repo/policy.json" });
8
+ lenses.push("review-readability");
9
+ assert.deepEqual(context.lenses, ["review-risk"]);
10
+ assert.equal(Object.isFrozen(context), true);
11
+ assert.equal(Object.isFrozen(context.lenses), true);
12
+ assert.throws(() => { (context.lenses as string[]).push("review-reliability"); }, TypeError);
13
+ });
14
+
15
+ test("intent snapshot never retains provider authority, scope or executable state", () => {
16
+ const request = { focus: "risk", targetIdentity: "stale-target", baseRef: "stale-base", intendedUntracked: ["stale-file"], consentBinding: "old-consent", signal: new AbortController().signal };
17
+ assert.deepEqual(snapshotReviewStartContext(request), { focus: "risk" });
18
+ assert.deepEqual(snapshotReviewStartContext({}), {});
19
+ });
@@ -0,0 +1,121 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { createGentleAiExtension } from "../extensions/gentle-ai.ts";
4
+
5
+ // The review-family tool declarations are injected into every session's
6
+ // system prompt (description + snippet + guidelines + parameter schemas).
7
+ // They were historically unbudgeted while orchestrator declarations had a
8
+ // hard byte budget (tests/orchestrator-prompt-budget.test.ts), so their
9
+ // operational prose grew until it duplicated the runtime RDD contract.
10
+ // This test pins a hard budget and the security invariants that must
11
+ // survive any future trim. Operational detail lives in the mirrored
12
+ // review contract (contracts/review-provider-contract-mirror) and in
13
+ // docs/delegated-verification.md; the always-on surface keeps only
14
+ // invariants and routing.
15
+
16
+ interface RegisteredDeclaration {
17
+ name: string;
18
+ description?: string;
19
+ promptSnippet?: string;
20
+ promptGuidelines?: readonly string[];
21
+ parameters?: unknown;
22
+ }
23
+
24
+ const REVIEW_FAMILY_TOOLS = [
25
+ "gentle_review",
26
+ "gentle_review_capture",
27
+ "gentle_review_capture_group",
28
+ "gentle_review_scope",
29
+ "gentle_odd_phase",
30
+ ] as const;
31
+
32
+ // The whole-declaration JSON (schemas, property names, the operation enum,
33
+ // and test-contracted fragments such as the S5 escalate shape) is
34
+ // irreducible or contract-pinned surface; the budget pins the prose trim:
35
+ // the historical unbudgeted surface was ~21.3 KB and the trimmed surface
36
+ // lands ~16.6 KB. Regrowth past 16.8 KB fails here. Prose-only bytes are
37
+ // reported in the diagnostic for visibility.
38
+ // The original trim measured 16,638 B; rebasing onto main added the requestContextPath
39
+ // guideline and the abandon parameter prose (+~0.5 KB of new upstream capability text),
40
+ // so the cap tracks that state rather than the earlier main.
41
+ // Shared guidance (REVIEW_BLOCKER_GUIDANCE) is declared once on gentle_review:
42
+ // Pi dedupes identical guidelines, so per-tool copies only inflate this count.
43
+ const REVIEW_FAMILY_PROSE_BUDGET_BYTES = 17300;
44
+
45
+ function registerReviewFamily(): Map<string, RegisteredDeclaration> {
46
+ const tools = new Map<string, RegisteredDeclaration>();
47
+ createGentleAiExtension({ nativeReviewCli: null })({
48
+ on() {},
49
+ registerCommand() {},
50
+ registerTool(definition: RegisteredDeclaration) {
51
+ tools.set(definition.name, definition);
52
+ },
53
+ } as never);
54
+ for (const name of REVIEW_FAMILY_TOOLS) {
55
+ assert.ok(tools.get(name), `missing registered review tool ${name}`);
56
+ }
57
+ return tools;
58
+ }
59
+
60
+ function surfaceBytes(tools: Map<string, RegisteredDeclaration>): number {
61
+ const selected = REVIEW_FAMILY_TOOLS.map((name) => tools.get(name)!);
62
+ return Buffer.byteLength(JSON.stringify(selected), "utf8");
63
+ }
64
+
65
+ function reviewSurface(tool: RegisteredDeclaration | undefined): string {
66
+ assert.ok(tool, "review tool must be registered");
67
+ return [
68
+ tool.description ?? "",
69
+ tool.promptSnippet ?? "",
70
+ ...(tool.promptGuidelines ?? []),
71
+ JSON.stringify(tool.parameters),
72
+ ].join("\n");
73
+ }
74
+
75
+ test("review-family tool declarations fit the always-on prose budget", t => {
76
+ const tools = registerReviewFamily();
77
+ const bytes = surfaceBytes(tools);
78
+ const proseBytes = REVIEW_FAMILY_TOOLS.reduce((sum, name) => {
79
+ const tool = tools.get(name)!;
80
+ return sum + Buffer.byteLength([tool.description ?? "", tool.promptSnippet ?? "", ...(tool.promptGuidelines ?? [])].join("\n"), "utf8");
81
+ }, 0);
82
+ t.diagnostic(`review-family declarations: ${bytes} B (budget ${REVIEW_FAMILY_PROSE_BUDGET_BYTES} B); prose-only ${proseBytes} B`);
83
+ assert.ok(
84
+ bytes <= REVIEW_FAMILY_PROSE_BUDGET_BYTES,
85
+ `review-family declarations ${bytes} B exceed the always-on budget ${REVIEW_FAMILY_PROSE_BUDGET_BYTES} B`,
86
+ );
87
+ });
88
+
89
+ test("trimmed review surface keeps the security and authority invariants", () => {
90
+ const tools = registerReviewFamily();
91
+ const controller = reviewSurface(tools.get("gentle_review"));
92
+ const capture = reviewSurface(tools.get("gentle_review_capture"));
93
+ const family = [controller, capture, reviewSurface(tools.get("gentle_review_capture_group")),
94
+ reviewSurface(tools.get("gentle_review_scope")), reviewSurface(tools.get("gentle_odd_phase"))].join("\n");
95
+
96
+ // Delivery boundary.
97
+ assert.match(family, /Review outcomes never authorize delivery/);
98
+ // Provider-issued opaque values are authoritative; never invent tokens.
99
+ assert.match(controller, /native-input-required.*never.*invent/is);
100
+ // Ambiguous output handling is declared, not improvised.
101
+ assert.match(
102
+ controller,
103
+ /ambiguous START output.*target-scoped native status.*declared action.*ambiguous gentle_review_capture.*never replays/is,
104
+ );
105
+ // RESET/RECOVER stay destructive and authorization-gated.
106
+ assert.match(controller, /RESET or RECOVER only after explicit user authorization/is);
107
+ assert.match(controller, /destructive/is);
108
+ // Host consent is host-owned; permission is never created from prose or arguments.
109
+ assert.match(controller, /never create host permission from tool arguments|host-owned/is);
110
+ // Correction-budget units stay named (diff lines vs logical budget).
111
+ assert.match(controller, /diff lines/);
112
+ assert.match(controller, /logical correction/);
113
+ for (const [label, text] of [["capture schema", capture.split("\n").at(-1)!], ["capture guidance", (tools.get("gentle_review_capture")!.promptGuidelines ?? []).join("\n")]] as const) {
114
+ assert.match(text, /diff lines/, label);
115
+ assert.match(text, /logical correction budget/, label);
116
+ }
117
+ assert.ok(controller.includes("The plan adds an independent verifier only when escalate names a Task Size high-risk item; it can never lower a tier."));
118
+ // Native review never removes a tier-required verifier (S1) and stays an outside view.
119
+ assert.match(controller, /native review is an additional outside view/);
120
+ assert.match(controller, /verify-always-rdd-high/);
121
+ });
@@ -125,6 +125,7 @@ console.log("ENV_PROBE=" + JSON.stringify({
125
125
  xdg: xdgPath ?? null,
126
126
  agents: Object.fromEntries(Object.entries(process.env).filter(([key]) => key.toUpperCase().startsWith("GENTLE_PI_AGENTS_"))),
127
127
  home,
128
+ shellMarker: process.env.GENTLE_SHELL_CONFIG_HOME ?? null,
128
129
  files: home && existsSync(home) ? readdirSync(home) : null,
129
130
  sentinel: process.env.TEST_ENV_SENTINEL,
130
131
  tmp: process.env.TMPDIR ?? null,
@@ -134,6 +135,7 @@ console.log("ENV_PROBE=" + JSON.stringify({
134
135
  writeFileSync(stagesPath, JSON.stringify([
135
136
  { name: "unit-tests", command: `node "${probePath}"` },
136
137
  { name: "provider-contract", command: `node "${probePath}"` },
138
+ { name: "runtime-harness", command: `node "${probePath}"` },
137
139
  ]));
138
140
  const result = spawnSync(process.execPath, [runnerPath, stagesPath], {
139
141
  encoding: "utf8", env: { ...process.env, ...env, TEST_ENV_SENTINEL: "preserved" },
@@ -142,9 +144,10 @@ console.log("ENV_PROBE=" + JSON.stringify({
142
144
  assert.equal(result.stderr, "");
143
145
  assert.match(result.stdout, /PASS unit-tests/);
144
146
  assert.match(result.stdout, /PASS provider-contract/);
147
+ assert.match(result.stdout, /PASS runtime-harness/);
145
148
  const probes = result.stdout.split(/\r?\n/).filter((line) => line.startsWith("ENV_PROBE="))
146
149
  .map((line) => JSON.parse(line.slice("ENV_PROBE=".length)));
147
- assert.equal(probes.length, 2);
150
+ assert.equal(probes.length, 3);
148
151
  for (const probe of probes) assert.equal(probe.sentinel, "preserved");
149
152
  return probes;
150
153
  }
@@ -220,6 +223,19 @@ test("unit stage strips inherited subagent context without changing later stages
220
223
  for (const [key, value] of Object.entries(env)) assert.equal(provider.agents[key], value);
221
224
  });
222
225
 
226
+ test("unit stage removes the launcher marker without changing later stages", (t) => {
227
+ const marker = mkdtempSync(join(tmpdir(), "gentle-pi-shell-marker-"));
228
+ t.after(() => rmSync(marker, { recursive: true, force: true }));
229
+ const sentinel = join(marker, "sentinel");
230
+ writeFileSync(sentinel, "untouched");
231
+ const [unit, provider, runtime] = probeStageEnvironment(t, { GENTLE_SHELL_CONFIG_HOME: marker });
232
+ assert.equal(unit.shellMarker, null);
233
+ assert.equal(provider.shellMarker, marker);
234
+ assert.equal(runtime.shellMarker, marker);
235
+ assert.equal(existsSync(unit.home), false);
236
+ assert.equal(readFileSync(sentinel, "utf8"), "untouched");
237
+ });
238
+
223
239
  test("unit stage accepts an uncreated inherited config home without creating it", (t) => {
224
240
  const dir = mkdtempSync(join(tmpdir(), "gentle-pi-caller-config-"));
225
241
  t.after(() => rmSync(dir, { recursive: true, force: true }));
@@ -271,3 +287,108 @@ test("unit stage gets a private TMPDIR removed after the stage; later stages kee
271
287
  assert.equal(existsSync(unit.tmp), false, "the private TMPDIR is removed after the stage");
272
288
  assert.equal(provider.tmp, inherited);
273
289
  });
290
+
291
+ test("long inherited TMPDIR permits a real unit socket and preserves later stage outputs and environments", (t) => {
292
+ const root = mkdtempSync(join(tmpdir(), "gentle-pi-long-tmp-"));
293
+ t.after(() => rmSync(root, { recursive: true, force: true }));
294
+ const inherited = join(root, "long".repeat(20), "temp".repeat(20));
295
+ mkdirSync(inherited, { recursive: true });
296
+ const marker = join(root, "shell-marker");
297
+ const callerConfig = join(root, "caller-config");
298
+ const xdg = join(root, "xdg");
299
+ const gitConfig = join(root, "gitconfig");
300
+ mkdirSync(marker);
301
+ mkdirSync(callerConfig);
302
+ mkdirSync(xdg);
303
+ writeFileSync(join(marker, "sentinel"), "untouched");
304
+ writeFileSync(gitConfig, "# caller config\n");
305
+
306
+ const stagesPath = writeStagesFile(t, []);
307
+ const dir = dirname(stagesPath);
308
+ const probePath = join(dir, "socket-probe.mjs");
309
+ const hostPath = join(dir, "runner-host.mjs");
310
+ writeFileSync(probePath, `
311
+ import { mkdtempSync, statSync } from "node:fs";
312
+ import { createConnection, createServer } from "node:net";
313
+ import { tmpdir } from "node:os";
314
+ import { join } from "node:path";
315
+ const name = process.argv[2];
316
+ const env = process.env;
317
+ const snapshot = { tmp: env.TMPDIR, home: env.GENTLE_PI_CONFIG_HOME, marker: env.GENTLE_SHELL_CONFIG_HOME ?? null,
318
+ gitGlobal: env.GIT_CONFIG_GLOBAL, gitNoSystem: env.GIT_CONFIG_NOSYSTEM, xdg: env.XDG_CONFIG_HOME };
319
+ if (name === "unit") {
320
+ snapshot.mode = statSync(env.TMPDIR).mode & 0o777;
321
+ snapshot.socket = join(mkdtempSync(join(tmpdir(), "pulse-client-")), "native");
322
+ console.log("UNIT=" + JSON.stringify(snapshot));
323
+ const server = createServer(socket => socket.end("connected"));
324
+ server.once("error", error => { console.error("SOCKET_ERROR=" + error.code); process.exitCode = 7; });
325
+ server.listen(snapshot.socket, () => {
326
+ const client = createConnection(snapshot.socket);
327
+ let response = "";
328
+ client.on("data", chunk => { response += chunk; });
329
+ client.once("error", error => { console.error("CLIENT_ERROR=" + error.code); server.close(); process.exitCode = 7; });
330
+ client.once("end", () => { console.log("SOCKET=" + response); console.error("unit-stderr"); process.exitCode = 3; server.close(); });
331
+ });
332
+ } else {
333
+ console.log(name.toUpperCase() + "=" + JSON.stringify(snapshot));
334
+ console.error(name + "-stderr");
335
+ process.exitCode = name === "provider" ? 4 : 0;
336
+ }
337
+ `);
338
+ const stages = [
339
+ { name: "unit-tests", command: `node "${probePath}" unit` },
340
+ { name: "provider-contract", command: `node "${probePath}" provider` },
341
+ { name: "runtime-harness", command: `node "${probePath}" runtime` },
342
+ ];
343
+ writeFileSync(stagesPath, JSON.stringify(stages));
344
+ writeFileSync(hostPath, `
345
+ import { readFileSync } from "node:fs";
346
+ import { runTestSuite } from ${JSON.stringify(new URL("../scripts/run-test-suite.mjs", import.meta.url).href)};
347
+ const stages = JSON.parse(readFileSync(process.argv[2], "utf8"));
348
+ const results = await runTestSuite(stages);
349
+ console.log("RESULTS=" + JSON.stringify(results));
350
+ process.exitCode = results.some(result => result.code !== 0) ? 1 : 0;
351
+ `);
352
+ const result = spawnSync(process.execPath, [hostPath, stagesPath], {
353
+ encoding: "utf8",
354
+ env: { ...process.env, TMPDIR: inherited, GENTLE_PI_CONFIG_HOME: callerConfig, GENTLE_SHELL_CONFIG_HOME: marker,
355
+ GIT_CONFIG_GLOBAL: gitConfig, GIT_CONFIG_NOSYSTEM: "0", XDG_CONFIG_HOME: xdg },
356
+ });
357
+ assert.equal(result.status, 1);
358
+ const lines = result.stdout.split(/\r?\n/);
359
+ const value = (prefix: string) => {
360
+ const line = lines.find((item) => item.startsWith(`${prefix}=`));
361
+ assert.ok(line, `${prefix} output missing: ${result.stderr}`);
362
+ return JSON.parse(line.slice(prefix.length + 1));
363
+ };
364
+ const unit = value("UNIT");
365
+ const provider = value("PROVIDER");
366
+ const runtime = value("RUNTIME");
367
+ const results = value("RESULTS");
368
+ assert.deepEqual(results, [{ name: "unit-tests", code: 3 }, { name: "provider-contract", code: 4 }, { name: "runtime-harness", code: 0 }]);
369
+ assert.notEqual(unit.tmp, inherited);
370
+ assert.equal(dirname(dirname(unit.socket)), unit.tmp, "the socket uses the unit's private temp directory");
371
+ assert.ok(Buffer.byteLength(unit.socket) < 104, "the fixture socket path fits the shortest Unix socket limit");
372
+ assert.ok(process.platform === "win32" || (unit.mode & 0o077) === 0, "the unit temp directory is private on POSIX");
373
+ assert.equal(existsSync(unit.tmp), false, "the unit temp directory and socket fixture are removed after failure");
374
+ assert.equal(existsSync(unit.home), false, "the isolated config is removed after failure");
375
+ assert.equal(unit.marker, null);
376
+ assert.equal(unit.gitGlobal, join(unit.home, "empty.gitconfig"));
377
+ assert.equal(unit.gitNoSystem, "1");
378
+ assert.equal(unit.xdg, unit.home);
379
+ const inheritedEnv = { tmp: inherited, home: callerConfig, marker, gitGlobal: gitConfig, gitNoSystem: "0", xdg };
380
+ assert.deepEqual(provider, inheritedEnv);
381
+ assert.deepEqual(runtime, inheritedEnv);
382
+ assert.equal(existsSync(inherited), true);
383
+ assert.equal(existsSync(callerConfig), true);
384
+ assert.equal(readFileSync(join(marker, "sentinel"), "utf8"), "untouched");
385
+ assert.equal(readFileSync(gitConfig, "utf8"), "# caller config\n");
386
+ assert.equal(result.stderr, "unit-stderr\nprovider-stderr\nruntime-stderr\n");
387
+ assert.equal(result.stdout, [
388
+ "", `=== [unit-tests] ${stages[0].command} ===`, `UNIT=${JSON.stringify(unit)}`, "SOCKET=connected",
389
+ "", `=== [provider-contract] ${stages[1].command} ===`, `PROVIDER=${JSON.stringify(provider)}`,
390
+ "", `=== [runtime-harness] ${stages[2].command} ===`, `RUNTIME=${JSON.stringify(runtime)}`,
391
+ "", "=== test suite summary ===", "FAIL unit-tests", "FAIL provider-contract", "PASS runtime-harness",
392
+ "2 stage(s) failed: unit-tests, provider-contract", `RESULTS=${JSON.stringify(results)}`, "",
393
+ ].join("\n"));
394
+ });