gentle-pi 4.7.0 → 4.8.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 (365) hide show
  1. package/README.md +55 -44
  2. package/assets/agents/gentle-ai-explore.md +3 -3
  3. package/assets/agents/gentle-ai-verify.md +20 -6
  4. package/assets/agents/gentle-ai-worker.md +6 -6
  5. package/assets/agents/jd-judge-a.md +1 -3
  6. package/assets/agents/jd-judge-b.md +1 -3
  7. package/assets/agents/review-readability.md +1 -5
  8. package/assets/agents/review-reliability.md +1 -5
  9. package/assets/agents/review-resilience.md +1 -5
  10. package/assets/agents/review-risk.md +1 -5
  11. package/assets/design-canvas/canvas-api.js +45 -0
  12. package/assets/design-canvas/canvas-boards.js +456 -0
  13. package/assets/design-canvas/canvas-boot.js +217 -0
  14. package/assets/design-canvas/canvas-checks.js +491 -0
  15. package/assets/design-canvas/canvas-comments.js +315 -0
  16. package/assets/design-canvas/canvas-compare.js +159 -0
  17. package/assets/design-canvas/canvas-events.js +75 -0
  18. package/assets/design-canvas/canvas-export.js +393 -0
  19. package/assets/design-canvas/canvas-focus.js +203 -0
  20. package/assets/design-canvas/canvas-handoffs.js +150 -0
  21. package/assets/design-canvas/canvas-i18n-es.js +392 -0
  22. package/assets/design-canvas/canvas-i18n.js +108 -0
  23. package/assets/design-canvas/canvas-layout.js +526 -0
  24. package/assets/design-canvas/canvas-menu.js +213 -0
  25. package/assets/design-canvas/canvas-messages.js +86 -0
  26. package/assets/design-canvas/canvas-minimap.js +163 -0
  27. package/assets/design-canvas/canvas-parts.js +401 -0
  28. package/assets/design-canvas/canvas-popover.js +234 -0
  29. package/assets/design-canvas/canvas-rail.js +348 -0
  30. package/assets/design-canvas/canvas-sizes.js +524 -0
  31. package/assets/design-canvas/canvas-store.js +164 -0
  32. package/assets/design-canvas/canvas-tokens.js +674 -0
  33. package/assets/design-canvas/canvas-ui.js +24 -0
  34. package/assets/design-canvas/canvas-view.js +184 -0
  35. package/assets/design-canvas/canvas.css +746 -15
  36. package/assets/design-canvas/canvas.js +2 -1506
  37. package/assets/design-canvas/index.html +117 -36
  38. package/assets/design-canvas/inspector.js +546 -16
  39. package/assets/install-wizard/wizard.js +5 -1
  40. package/assets/migrations/agent-body-history.json +24 -0
  41. package/assets/orchestrator-delegation-reference.md +8 -14
  42. package/assets/orchestrator-delegation.md +4 -4
  43. package/assets/orchestrator-full-delegation-card.md +4 -5
  44. package/assets/orchestrator-full-delegation.md +8 -8
  45. package/assets/orchestrator-memory.md +2 -2
  46. package/assets/orchestrator-prompts.md +1 -1
  47. package/assets/orchestrator-quota-recovery.md +5 -0
  48. package/assets/orchestrator-skills.md +13 -12
  49. package/assets/orchestrator-tracking.md +10 -14
  50. package/assets/orchestrator-verification.md +10 -8
  51. package/assets/orchestrator-writer.md +4 -4
  52. package/assets/orchestrator.md +18 -22
  53. package/bin/gentle-shell.mjs +128 -9
  54. package/contracts/review-provider-contract-mirror/provider-contract.lock.json +8 -9
  55. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/manifest.json +3 -3
  56. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/orchestration/pi.md +1 -0
  57. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/routing/pi.md +6 -6
  58. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/generated/provider-capabilities.baseline.json +3 -3
  59. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/generated/provider-roles.baseline.json +1 -1
  60. package/docs/assets/brand/sponsor-banner.svg +60 -0
  61. package/docs/bundled-install.md +14 -6
  62. package/docs/delegated-verification.md +18 -2
  63. package/docs/desktop-rpc.md +1253 -0
  64. package/docs/gentle-agents-activity.md +26 -0
  65. package/docs/gentle-shell.md +39 -16
  66. package/docs/install-wizard.md +30 -21
  67. package/docs/odd-preparation-continuity.md +24 -0
  68. package/docs/permission-modes.md +9 -1
  69. package/docs/prompt-budget.md +12 -0
  70. package/docs/rdd-odd-friction-triage-2026-11-07.md +57 -0
  71. package/docs/readme-reference.md +76 -24
  72. package/docs/review-coordinator.md +29 -9
  73. package/docs/review-delivery-preflight.md +22 -0
  74. package/docs/work-continuity.md +11 -1
  75. package/extensions/ask-user-question.ts +2 -2
  76. package/extensions/child-context.ts +21 -7
  77. package/extensions/gentle-agents.ts +234 -33
  78. package/extensions/gentle-ai.ts +576 -135
  79. package/extensions/gentle-design.ts +69 -3
  80. package/extensions/gentle-desktop-rpc.ts +143 -0
  81. package/extensions/gentle-guide.ts +3 -0
  82. package/extensions/gentle-shell.ts +105 -52
  83. package/extensions/gentle-todo.ts +48 -25
  84. package/extensions/skill-registry.ts +248 -223
  85. package/lib/agent-assets.ts +30 -6
  86. package/lib/agent-tool-overlay.ts +117 -0
  87. package/lib/agents-config.ts +47 -6
  88. package/lib/agents-message-delivery.ts +17 -0
  89. package/lib/agents-messaging.ts +8 -2
  90. package/lib/agents-protocol.ts +15 -0
  91. package/lib/agents-report-cap.ts +115 -0
  92. package/lib/agents-runner.ts +91 -6
  93. package/lib/agents-session-transport.ts +17 -1
  94. package/lib/background-jobs-tools.ts +9 -4
  95. package/lib/bounded-writer-admission.ts +184 -31
  96. package/lib/child-context-files.ts +21 -6
  97. package/lib/codemode-renderer.ts +1 -0
  98. package/lib/delivery-conflict-markers.ts +349 -0
  99. package/lib/design-canvas-assets.ts +36 -0
  100. package/lib/design-canvas-server.ts +241 -23
  101. package/lib/design-comments.ts +94 -4
  102. package/lib/design-handoffs.ts +2 -1
  103. package/lib/design-layout.ts +125 -0
  104. package/lib/design-parts.ts +281 -0
  105. package/lib/design-system-tokens.ts +111 -0
  106. package/lib/desktop-agents-service.ts +294 -0
  107. package/lib/desktop-design-service.ts +233 -0
  108. package/lib/desktop-jobs-service.ts +263 -0
  109. package/lib/desktop-rpc-agents.ts +294 -0
  110. package/lib/desktop-rpc-config.ts +731 -0
  111. package/lib/desktop-rpc-design.ts +138 -0
  112. package/lib/desktop-rpc-jobs.ts +181 -0
  113. package/lib/desktop-rpc-permissions.ts +177 -0
  114. package/lib/desktop-rpc-profiles.ts +196 -0
  115. package/lib/desktop-rpc-usage.ts +229 -0
  116. package/lib/desktop-rpc.ts +225 -0
  117. package/lib/desktop-usage-service.ts +310 -0
  118. package/lib/destructive-command-guard.ts +188 -13
  119. package/lib/gentle-ai-renderer.ts +13 -1
  120. package/lib/gentle-design.ts +201 -14
  121. package/lib/gentle-shell-bundled.ts +100 -9
  122. package/lib/hidden-tools.ts +35 -0
  123. package/lib/inprocess-reviewer.ts +96 -12
  124. package/lib/model-fallback-policy.ts +9 -0
  125. package/lib/model-routing-authority.ts +9 -0
  126. package/lib/nan-provider.ts +42 -28
  127. package/lib/native-review-cli.ts +79 -4
  128. package/lib/orchestrator-discovery.ts +39 -2
  129. package/lib/reply-language-anchor.ts +27 -2
  130. package/lib/request-context-placement.ts +53 -0
  131. package/lib/review-candidate-view.ts +11 -1
  132. package/lib/review-continuation-registry.ts +17 -0
  133. package/lib/review-coordinator.ts +252 -8
  134. package/lib/review-delivery-preflight.ts +85 -0
  135. package/lib/review-host-relay.ts +5 -1
  136. package/lib/review-integration-v2.ts +56 -3
  137. package/lib/reviewer-stream.ts +87 -0
  138. package/lib/shell-prompt.ts +16 -3
  139. package/lib/shell-usage.ts +10 -0
  140. package/lib/vim-editor-adapter.ts +9 -2
  141. package/lib/writer-batch-admission.ts +55 -0
  142. package/lib/yolo-session-policy.ts +6 -1
  143. package/package.json +2 -2
  144. package/prompts/skill-creation.md +1 -10
  145. package/runtime/design-canvas-assets.mjs +37 -0
  146. package/runtime/gentle-shell-bundled.mjs +100 -9
  147. package/runtime/native-review-cli.mjs +79 -4
  148. package/runtime/review-integration-v2.mjs +56 -3
  149. package/scripts/bootstrap.cmd +2 -2
  150. package/scripts/bootstrap.sh +41 -4
  151. package/scripts/build-full-delegation-card.mjs +4 -0
  152. package/scripts/build-runtime-modules.mjs +1 -0
  153. package/scripts/gentle-ai-installer.mjs +10 -10
  154. package/scripts/gentle-ai-proxy.mjs +1 -1
  155. package/scripts/installer-downloads.mjs +34 -8
  156. package/scripts/installer-preflight.mjs +28 -17
  157. package/scripts/installer-probes.mjs +25 -5
  158. package/scripts/installer-server.mjs +38 -9
  159. package/scripts/installer-windows.mjs +2 -2
  160. package/scripts/pi-update.mjs +166 -27
  161. package/scripts/prepare-verifier.mjs +107 -0
  162. package/scripts/update-agent-body-history.mjs +55 -8
  163. package/scripts/verify-package-files.mjs +40 -19
  164. package/skills/branch-pr/SKILL.md +16 -16
  165. package/skills/comment-writer/SKILL.md +1 -1
  166. package/skills/design/SKILL.md +6 -6
  167. package/skills/gentle-ai/SKILL.md +5 -5
  168. package/skills/judgment-day/SKILL.md +2 -2
  169. package/skills/judgment-day/references/prompts-and-formats.md +1 -1
  170. package/skills/rdd-defect-workflow/SKILL.md +6 -6
  171. package/skills/skill-improver/SKILL.md +2 -2
  172. package/skills/skill-registry/SKILL.md +11 -13
  173. package/skills/tui-design/SKILL.md +1 -1
  174. package/skills/work-unit-commits/SKILL.md +5 -5
  175. package/tests/agent-prompt-diet-contract.test.ts +101 -0
  176. package/tests/agent-tool-overlay-acceptance.test.ts +158 -0
  177. package/tests/agent-tool-overlay.test.ts +89 -0
  178. package/tests/agents-config.test.ts +10 -1
  179. package/tests/agents-message-delivery.test.ts +36 -0
  180. package/tests/agents-queries.test.ts +144 -4
  181. package/tests/agents-report-cap.test.ts +126 -0
  182. package/tests/agents-runner.test.ts +37 -1
  183. package/tests/agents-session-transport.test.ts +34 -0
  184. package/tests/always-on-prompt-verdicts-contract.test.ts +188 -0
  185. package/tests/append-system-prompt-route.test.ts +10 -2
  186. package/tests/approved-text-leftovers-contract.test.ts +136 -0
  187. package/tests/artifact-language.test.ts +1 -1
  188. package/tests/ask-user-question.test.ts +2 -1
  189. package/tests/audit-leftovers-contract.test.ts +51 -0
  190. package/tests/bounded-stop-contract.test.ts +9 -1
  191. package/tests/branch-pr-skill.test.ts +10 -1
  192. package/tests/bundled-install.test.ts +1 -1
  193. package/tests/child-context-files.test.ts +64 -8
  194. package/tests/child-skills-catalog.test.ts +56 -0
  195. package/tests/codemode-rendering.test.ts +4 -1
  196. package/tests/delegate-for-reason-contract.test.ts +30 -8
  197. package/tests/delivery-conflict-markers.test.ts +348 -0
  198. package/tests/design-canvas-all-sizes.test.ts +631 -0
  199. package/tests/design-canvas-allowlist.test.ts +32 -0
  200. package/tests/design-canvas-assets.test.ts +11 -878
  201. package/tests/design-canvas-boards.test.ts +77 -0
  202. package/tests/design-canvas-checks.test.ts +655 -0
  203. package/tests/design-canvas-compare.test.ts +79 -0
  204. package/tests/design-canvas-events.test.ts +59 -0
  205. package/tests/design-canvas-export.test.ts +1168 -0
  206. package/tests/design-canvas-focus.test.ts +113 -0
  207. package/tests/design-canvas-handoffs.test.ts +59 -0
  208. package/tests/design-canvas-i18n-review.test.ts +513 -0
  209. package/tests/design-canvas-i18n-views.test.ts +259 -0
  210. package/tests/design-canvas-i18n.test.ts +526 -0
  211. package/tests/design-canvas-inspector.test.ts +937 -0
  212. package/tests/design-canvas-layout.test.ts +1222 -0
  213. package/tests/design-canvas-minimap.test.ts +413 -0
  214. package/tests/design-canvas-modules.test.ts +90 -0
  215. package/tests/design-canvas-parts.test.ts +721 -0
  216. package/tests/design-canvas-rail.test.ts +799 -0
  217. package/tests/design-canvas-server.test.ts +855 -17
  218. package/tests/design-canvas-sizes.test.ts +548 -0
  219. package/tests/design-canvas-store.test.ts +180 -0
  220. package/tests/design-canvas-tokens.test.ts +965 -0
  221. package/tests/design-canvas-view.test.ts +299 -0
  222. package/tests/design-comments.test.ts +201 -1
  223. package/tests/design-handoffs.test.ts +20 -0
  224. package/tests/design-layout.test.ts +100 -0
  225. package/tests/design-parts.test.ts +260 -0
  226. package/tests/design-system-tokens.test.ts +215 -0
  227. package/tests/desktop-rpc-agents.test.ts +893 -0
  228. package/tests/desktop-rpc-config.test.ts +1452 -0
  229. package/tests/desktop-rpc-design.test.ts +662 -0
  230. package/tests/desktop-rpc-jobs.test.ts +796 -0
  231. package/tests/desktop-rpc-permissions.test.ts +311 -0
  232. package/tests/desktop-rpc-profiles.test.ts +140 -0
  233. package/tests/desktop-rpc-safety.test.ts +119 -0
  234. package/tests/desktop-rpc-usage.test.ts +697 -0
  235. package/tests/desktop-rpc.test.ts +252 -0
  236. package/tests/devbinary/pi-host-relay.devtest.ts +149 -80
  237. package/tests/devbinary/review-session-consent.devtest.ts +84 -0
  238. package/tests/engram-safety.test.ts +111 -0
  239. package/tests/fixtures/devbinary/status-v9-escalated-non-blocking.captured.json +92 -0
  240. package/tests/fixtures/devbinary/status-v9-escalated-non-blocking.provenance.md +3 -0
  241. package/tests/fixtures/primary-session-prompt/gentleman.golden.md +20 -29
  242. package/tests/fixtures/refusal-identity.probe.mjs +139 -0
  243. package/tests/full-delegation-closure.test.ts +29 -0
  244. package/tests/gentle-agents.test.ts +329 -4
  245. package/tests/gentle-ai-binary.test.ts +1 -1
  246. package/tests/gentle-ai-child-guards.test.ts +1 -0
  247. package/tests/gentle-ai-installer.test.ts +52 -51
  248. package/tests/gentle-ai-renderer.test.ts +36 -2
  249. package/tests/gentle-ai.test.ts +121 -6
  250. package/tests/gentle-design.test.ts +365 -1
  251. package/tests/gentle-shell-bundled.test.ts +91 -5
  252. package/tests/gentle-shell-launcher.test.ts +1 -1
  253. package/tests/gentle-shell.test.ts +118 -87
  254. package/tests/gentle-todo.test.ts +32 -9
  255. package/tests/hidden-tools.test.ts +188 -0
  256. package/tests/independent-recovery-delivery.test.ts +19 -5
  257. package/tests/inprocess-reviewer.test.ts +73 -0
  258. package/tests/install-wizard.test.ts +27 -1
  259. package/tests/installer-downloads.test.ts +30 -1
  260. package/tests/installer-posix-bootstrap.test.ts +114 -13
  261. package/tests/installer-preflight.test.ts +49 -1
  262. package/tests/installer-probes.test.ts +146 -0
  263. package/tests/installer-server.test.ts +203 -4
  264. package/tests/installer-windows-bootstrap.test.ts +19 -1
  265. package/tests/judgment-day-severity-admission.test.ts +46 -0
  266. package/tests/lazy-module-contradictions-contract.test.ts +158 -0
  267. package/tests/maintainer/desktop-rpc.maintest.ts +632 -0
  268. package/tests/maintainer/pi-update-source.maintest.ts +48 -18
  269. package/tests/model-fallback-policy.test.ts +26 -7
  270. package/tests/nan-provider-runtime.test.ts +17 -3
  271. package/tests/nan-provider.test.ts +111 -56
  272. package/tests/native-review-capability-contract.test.ts +11 -1
  273. package/tests/native-review-cli-nonblocking-findings.test.ts +165 -0
  274. package/tests/native-review-parity.test.ts +24 -5
  275. package/tests/native-review-refusal-identity.test.ts +25 -0
  276. package/tests/no-self-pause-contract.test.ts +11 -3
  277. package/tests/odd-integration.test.ts +11 -3
  278. package/tests/odd-routing-contract.test.ts +80 -28
  279. package/tests/orchestrator-budget.test.ts +30 -5
  280. package/tests/orchestrator-consultation-sdk.test.ts +32 -6
  281. package/tests/orchestrator-delegation-mode.test.ts +2 -1
  282. package/tests/orchestrator-discovery.test.ts +28 -0
  283. package/tests/orchestrator-prompt-budget.test.ts +11 -2
  284. package/tests/orchestrator-prompt-diet-contract.test.ts +221 -0
  285. package/tests/orchestrator-rdd-ownership.test.ts +2 -1
  286. package/tests/orchestrator-work-search.test.ts +4 -2
  287. package/tests/package-files.test.ts +25 -1
  288. package/tests/package-manifest.test.ts +11 -10
  289. package/tests/parallel-reason-contract.test.ts +6 -3
  290. package/tests/permission-allowlist.test.ts +200 -30
  291. package/tests/persona-neutral-voseo.test.ts +4 -4
  292. package/tests/persona-reply-language.test.ts +1 -1
  293. package/tests/persona-single-channel.test.ts +13 -5
  294. package/tests/pi-update-launcher.test.ts +17 -7
  295. package/tests/pi-update-source.test.ts +113 -6
  296. package/tests/pi-update.test.ts +294 -19
  297. package/tests/pnpm-workspace-policy.test.ts +47 -0
  298. package/tests/primary-context-files.test.ts +233 -0
  299. package/tests/primary-context-three-files.test.ts +174 -0
  300. package/tests/provider-defect-handoff.test.ts +9 -2
  301. package/tests/rdd-aware-verification-contract.test.ts +1 -1
  302. package/tests/rdd-status-line.test.ts +94 -1
  303. package/tests/reply-language-anchor-placement.test.ts +184 -0
  304. package/tests/reply-language-anchor.test.ts +17 -1
  305. package/tests/request-context-append-only.test.ts +218 -0
  306. package/tests/request-context-placement.test.ts +148 -0
  307. package/tests/review-agent-end-preflight.test.ts +79 -1
  308. package/tests/review-candidate-view.test.ts +65 -0
  309. package/tests/review-continuation-registry.test.ts +31 -0
  310. package/tests/review-contract-prompt.test.ts +1 -1
  311. package/tests/review-controller.test.ts +2 -1
  312. package/tests/review-coordinator-correction-gate.test.ts +105 -0
  313. package/tests/review-coordinator-findings.test.ts +206 -0
  314. package/tests/review-coordinator-nonblocking-scope.test.ts +169 -0
  315. package/tests/review-coordinator.test.ts +271 -4
  316. package/tests/review-delivery-preflight.test.ts +462 -0
  317. package/tests/review-due-compaction.test.ts +31 -0
  318. package/tests/review-due-public-boundary.test.ts +26 -0
  319. package/tests/review-integration-nonblocking-findings.test.ts +108 -0
  320. package/tests/review-json-arguments.test.ts +41 -2
  321. package/tests/review-ledger-contract.test.ts +19 -40
  322. package/tests/review-loadout-rdd-off-sdk.test.ts +30 -1
  323. package/tests/review-one-call-findings.test.ts +131 -0
  324. package/tests/review-one-call-followups.test.ts +308 -0
  325. package/tests/review-one-call-reviewer-requests.test.ts +207 -0
  326. package/tests/review-one-call.test.ts +452 -0
  327. package/tests/review-relay-transport-agent.test.ts +28 -1
  328. package/tests/review-reviewer-evidence.test.ts +41 -1
  329. package/tests/review-risk-assessment.test.ts +52 -5
  330. package/tests/review-run-statement-guidance-independent.test.ts +54 -0
  331. package/tests/review-session-standing-permission-controller.test.ts +32 -2
  332. package/tests/review-tool-prose-budget.test.ts +1 -0
  333. package/tests/reviewer-stream.test.ts +149 -0
  334. package/tests/session-profile-extension.test.ts +2 -2
  335. package/tests/shell-prompt.test.ts +17 -0
  336. package/tests/shell-usage.test.ts +59 -10
  337. package/tests/skill-contradictions-contract.test.ts +122 -0
  338. package/tests/skill-registry-watcher.test.ts +216 -2
  339. package/tests/skill-registry.test.ts +929 -306
  340. package/tests/support/design-canvas-dom.ts +369 -0
  341. package/tests/support/review-coordinator-runtime.ts +212 -17
  342. package/tests/task-size-routing-contract.test.ts +42 -11
  343. package/tests/test-strength-contract.test.ts +2 -1
  344. package/tests/todo-request-append-only.test.ts +214 -0
  345. package/tests/tool-batching-contract.test.ts +3 -1
  346. package/tests/update-agent-body-history.test.ts +138 -0
  347. package/tests/verification-tiers-contract.test.ts +229 -0
  348. package/tests/verifier-preparation.test.ts +229 -0
  349. package/tests/verify-agent-contract.test.ts +20 -2
  350. package/tests/verify-first-launch-contract.test.ts +87 -11
  351. package/tests/vim-editor-adapter.test.ts +2 -2
  352. package/tests/work-continuity-contract.test.ts +54 -11
  353. package/tests/writer-admission-messages.test.ts +232 -0
  354. package/tests/writer-batch-admission.test.ts +66 -0
  355. package/tests/writer-edit-surface-scope.test.ts +52 -20
  356. package/tests/writer-feature-document-admission.test.ts +184 -0
  357. package/tests/yolo-mode.test.ts +39 -0
  358. package/skills/_shared/review-ledger-contract.md +0 -106
  359. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/README.md +0 -0
  360. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/lens.schema.json +0 -0
  361. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/refuter.schema.json +0 -0
  362. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/targeted-validator.schema.json +0 -0
  363. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/lens.json +0 -0
  364. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/refuter.json +0 -0
  365. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/targeted-validator.json +0 -0
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
2
2
  import { spawnSync } from "node:child_process";
3
3
  import { existsSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
4
4
  import { tmpdir } from "node:os";
5
+ import { createServer } from "node:net";
5
6
  import { join } from "node:path";
6
7
  import test, { after, before } from "node:test";
7
8
  import { blockChildDestructiveCommand } from "../extensions/child-safety.ts";
@@ -43,33 +44,42 @@ function containsAll(text: string, clauses: readonly string[], label: string): v
43
44
  test("S1: verifier makes one isolated preparation attempt before checks", () => {
44
45
  containsAll(verify, [
45
46
  "Make one isolated preparation attempt",
46
- "If preparation succeeds, run the authorized checks and independent spec-derived probes",
47
+ // Cost-speed P8 B2: the verifier runs its evidence commands and probes, never the writer's reported suite.
48
+ "If preparation succeeds, run your evidence commands and independent spec-derived probes",
47
49
  ], "preparation bound");
48
50
  });
49
51
 
50
52
  test("S2: preparation failure reports a concrete blocker and exact unrun checks", () => {
51
53
  containsAll(verify, [
52
- "At the first inability to prepare a required copy, environment, dependency, or helper, stop setup",
54
+ "At a second failure, or at any missing or unavailable prerequisite (a tool, network, space, permission), stop setup",
53
55
  "report one concrete setup blocker and the exact checks left unrun as unverified, not passed",
54
56
  "list every scratch directory you created by exact path",
55
57
  ], "setup failure");
56
58
  });
57
59
 
58
60
  test("S3: setup failures do not trigger repair loops or automatic relaunch", () => {
59
- containsAll(verify, ["Do not retry setup or enter repair-helper loops"], "verifier setup");
61
+ containsAll(verify, [
62
+ "When it fails on a deterministic error in a command or environment you constructed (a wrong flag, conflicting config, a typo, a path you chose), make exactly one corrected attempt without asking anyone and report both attempts.",
63
+ "No further setup retries and no repair-helper loops.",
64
+ ], "verifier setup");
65
+ assert.ok(!verify.includes("Do not retry setup"), "verifier self-correction replaces the blanket no-retry rule");
60
66
  containsAll(verification, [
61
- "Do not automatically relaunch the verifier for the same missing prerequisite",
62
- "Distinguish setup or infrastructure failure from genuine code findings",
63
- "stop with one **Needs your decision** result identifying the missing prerequisite and exact unrun checks",
64
- "Do not keep repairing helpers",
65
- "Auxiliary tooling defects remain subject to the existing correction bound",
67
+ "A verifier's self-fix of its own setup error (one correction in the same verification) needs no decision; if it made none, relaunch once with the corrected command, unasked.",
68
+ "If setup still fails or lacks prerequisites, stop: one **Needs your decision** naming the blocker and exact unrun checks as unverified",
69
+ "never repair helpers more or auto-relaunch for it",
70
+ "Setup/infrastructure failures aren't code findings; tooling defects keep the correction bound.",
66
71
  ], "parent setup");
67
72
  });
68
73
 
74
+ test("S3: parent setup rule keeps the human-requested relaunch after a repaired prerequisite", () => {
75
+ assert.doesNotMatch(verification, /never[^.]*\brelaunch for (that|the same)[^.]*prerequisite/);
76
+ assert.match(verification, /auto-?(matically )?relaunch/);
77
+ });
78
+
69
79
  test("S2-S3: setup recovery references the always-on bounded policy", () => {
70
80
  containsAll(verification, [
71
81
  "Follow **Authorized work continuity** for setup and worker recovery; scratch: `gentle-ai-verify`.",
72
- "Do not automatically relaunch the verifier for the same missing prerequisite",
82
+ "auto-relaunch for it",
73
83
  ], "parent setup recovery");
74
84
  });
75
85
 
@@ -89,6 +99,9 @@ test("S5: documentation identifies the instruction as policy rather than runtime
89
99
  const docs = read("docs/delegated-verification.md");
90
100
  containsAll(docs, [
91
101
  "one isolated preparation attempt",
102
+ "the verifier makes exactly one corrected attempt without asking and reports both",
103
+ "the parent relaunches it once with the corrected command, without asking a human",
104
+ "automatically relaunching for the same prerequisite",
92
105
  "prompt policy, not a runtime-enforced limit",
93
106
  "unverified, not passed",
94
107
  ], "delegated verification documentation");
@@ -141,7 +154,7 @@ test("T16/W1: the scratch copy method cannot write outside the scratch directory
141
154
  // `cp -a --reflink=auto`, which cannot exclude anything. Verifiers then ran
142
155
  // `rm -rf "$s/work/.git"` (blocked by child safety) or `cp --exclude` (no such
143
156
  // option), so no probe ran. The prompt names one exact guard-compatible form.
144
- const SCRATCH_COPY = /`(mkdir -p "\$s\/work" && tar --exclude=\.\/\.git [^`]+)`/;
157
+ const SCRATCH_COPY = /`((?:set -o pipefail && )?mkdir -p "\$s\/work" && tar --exclude=\.\/\.git [^`]+)`/;
145
158
 
146
159
  test("#2818: the scratch copy names one exact command the child guard allows", () => {
147
160
  const command = verify.match(SCRATCH_COPY)?.[1];
@@ -155,7 +168,7 @@ test("#2818: the scratch copy names one exact command the child guard allows", (
155
168
  ], "scratch copy method");
156
169
  });
157
170
 
158
- test("#2818: the named scratch copy omits top-level .git and keeps dotfiles, dependencies and symlinks", () => {
171
+ test("#2818: the named scratch copy omits top-level .git and keeps dotfiles, dependencies and symlinks", (t) => {
159
172
  const command = verify.match(SCRATCH_COPY)?.[1];
160
173
  assert.ok(command);
161
174
  const workspace = join(scratch, "workspace");
@@ -164,17 +177,80 @@ test("#2818: the named scratch copy omits top-level .git and keeps dotfiles, dep
164
177
  writeFileSync(join(workspace, ".env.example"), "KEY=\n");
165
178
  mkdirSync(join(workspace, "node_modules", "dep"), { recursive: true });
166
179
  writeFileSync(join(workspace, "node_modules", "dep", "index.js"), "module.exports = 1;\n");
180
+ mkdirSync(join(workspace, "app"));
181
+ mkdirSync(join(workspace, "shared"));
182
+ writeFileSync(join(workspace, "shared", "value.cjs"), "module.exports = 2;\n");
183
+ writeFileSync(join(workspace, "app", "intended-untracked.cjs"), 'if (require("dep") + require("../shared/value.cjs") !== 3) process.exit(1);\n');
167
184
  mkdirSync(join(workspace, "node_modules", ".bin"));
168
185
  symlinkSync("../dep/index.js", join(workspace, "node_modules", ".bin", "dep"));
169
186
  const s = mkdtempSync(join(scratch, "probe-"));
187
+ const started = performance.now();
170
188
  const result = spawnSync("bash", ["-c", command], { cwd: workspace, env: { ...process.env, s }, encoding: "utf8" });
189
+ const elapsedMs = performance.now() - started;
171
190
  assert.equal(result.status, 0, result.stderr);
172
191
  const work = join(s, "work");
173
192
  assert.equal(existsSync(join(work, ".git")), false);
174
193
  assert.equal(readFileSync(join(work, ".env.example"), "utf8"), "KEY=\n");
175
194
  assert.equal(readFileSync(join(work, "node_modules", "dep", "index.js"), "utf8"), "module.exports = 1;\n");
176
195
  assert.equal(readlinkSync(join(work, "node_modules", ".bin", "dep")), "../dep/index.js");
196
+ const probe = spawnSync(process.execPath, [join(work, "app", "intended-untracked.cjs")], { cwd: work, encoding: "utf8" });
197
+ assert.equal(probe.status, 0, probe.stderr);
177
198
  assert.equal(existsSync(join(workspace, ".git", "HEAD")), true);
199
+ const payloadBytes = [".env.example", "node_modules/dep/index.js", "shared/value.cjs", "app/intended-untracked.cjs"]
200
+ .reduce((bytes, path) => bytes + readFileSync(join(workspace, path)).byteLength, 0);
201
+ t.diagnostic(`fixture copy: ${elapsedMs.toFixed(1)} ms, ${payloadBytes} regular-file bytes plus one symlink; no production throughput claim`);
202
+ });
203
+
204
+ // #3009: a producer read failure can still leave a valid partial tar stream.
205
+ // Without pipefail, a successful extractor hides that failure and admits probes
206
+ // against missing candidate inputs. Reproduced on Windows with a locked file;
207
+ // a missing required input gives the same deterministic producer failure here.
208
+ test("#3009: a failed archive producer cannot run probes against its partial payload", () => {
209
+ const command = verify.match(SCRATCH_COPY)?.[1];
210
+ assert.ok(command);
211
+ const workspace = mkdtempSync(join(scratch, "producer-source-"));
212
+ writeFileSync(join(workspace, "intended-untracked.txt"), "candidate\n");
213
+ const s = mkdtempSync(join(scratch, "producer-copy-"));
214
+ const producerFailure = 'tar() { if [[ "$*" == *"-cf -"* ]]; then command tar "$@" missing-required-input; else command tar "$@"; fi; }';
215
+ const result = spawnSync("bash", ["-c", `${producerFailure}\n${command} && printf probe-ran > "$s/probe-ran"`], {
216
+ cwd: workspace, env: { ...process.env, s }, encoding: "utf8",
217
+ });
218
+ assert.notEqual(result.status, 0, "a successful extractor must not mask its failed producer");
219
+ assert.match(result.stderr, /missing-required-input/);
220
+ assert.equal(readFileSync(join(s, "work", "intended-untracked.txt"), "utf8"), "candidate\n", "the failure produced a readable but incomplete copy");
221
+ assert.equal(existsSync(join(s, "probe-ran")), false, "no verification runs after setup failure");
222
+ });
223
+
224
+ test("#3009: a failed extractor cannot run probes", () => {
225
+ const command = verify.match(SCRATCH_COPY)?.[1];
226
+ assert.ok(command);
227
+ const workspace = mkdtempSync(join(scratch, "extractor-source-"));
228
+ writeFileSync(join(workspace, "candidate.txt"), "candidate\n");
229
+ const s = mkdtempSync(join(scratch, "extractor-copy-"));
230
+ const extractorFailure = 'tar() { if [[ "$*" == *"-xf -"* ]]; then cat > /dev/null; return 2; else command tar "$@"; fi; }';
231
+ const result = spawnSync("bash", ["-c", `${extractorFailure}\n${command} && printf probe-ran > "$s/probe-ran"`], {
232
+ cwd: workspace, env: { ...process.env, s }, encoding: "utf8",
233
+ });
234
+ assert.notEqual(result.status, 0);
235
+ assert.equal(existsSync(join(s, "probe-ran")), false);
236
+ });
237
+
238
+ test("#3009: the prescribed tar copy skips a live Unix socket and keeps candidate input", { skip: process.platform === "win32" }, async (t) => {
239
+ const command = verify.match(SCRATCH_COPY)?.[1];
240
+ assert.ok(command);
241
+ const workspace = mkdtempSync(join(scratch, "socket-source-"));
242
+ mkdirSync(join(workspace, ".codegraph"));
243
+ writeFileSync(join(workspace, "intended-untracked.txt"), "candidate\n");
244
+ const socket = join(workspace, ".codegraph", "daemon.sock");
245
+ const server = createServer();
246
+ await new Promise<void>((resolve, reject) => { server.once("error", reject); server.listen(socket, resolve); });
247
+ t.after(() => new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve())));
248
+ const s = mkdtempSync(join(scratch, "socket-copy-"));
249
+ const result = spawnSync("bash", ["-c", command], { cwd: workspace, env: { ...process.env, s }, encoding: "utf8" });
250
+ assert.equal(result.status, 0, result.stderr);
251
+ assert.equal(existsSync(join(s, "work", ".codegraph", "daemon.sock")), false);
252
+ assert.equal(readFileSync(join(s, "work", "intended-untracked.txt"), "utf8"), "candidate\n");
253
+ assert.equal(existsSync(socket), true, "the live source socket is untouched");
178
254
  });
179
255
 
180
256
  // T21 (L44): in after4, verify reported a behavior already present at the
@@ -277,12 +277,12 @@ test("resolveVimRuntime resolves local bundle cli entrypoint when provided", ()
277
277
  });
278
278
 
279
279
  test("audited Pi editor releases are one frozen exact allowlist that includes the installed TUI", () => {
280
- assert.deepEqual([...AUDITED_PI_EDITOR_VERSIONS], ["0.99.1", "0.99.2", "1.0.0", "1.1.0", "1.2.0", "1.3.0", "1.4.0", "1.5.0"]);
280
+ assert.deepEqual([...AUDITED_PI_EDITOR_VERSIONS], ["0.99.1", "0.99.2", "1.0.0", "1.1.0", "1.2.0", "1.3.0", "1.4.0", "1.5.0", "1.5.1", "1.5.2"]);
281
281
  assert.equal(bundledAgent.VERSION, INSTALLED_PI, "bundled and local metadata must describe the same actual installed release");
282
282
  assert.ok(Object.isFrozen(AUDITED_PI_EDITOR_VERSIONS));
283
283
  assert.throws(() => (AUDITED_PI_EDITOR_VERSIONS as unknown as string[]).push("0.99.3"), TypeError);
284
284
  assert.ok(isAuditedPiEditorVersion(INSTALLED_PI), `installed pi-tui ${INSTALLED_PI} must be audited`);
285
- for (const unknown of ["0.99.3", "0.99.10", "0.99", "v0.99.2", " 0.99.2", "0.99.2-rc.1", ">=0.99.2", "1.0.1", ">=1.0.0", "v1.0.0", " 1.0.0", "1.0.0-rc.1", "1.2.1", "1.2.0-rc.1", "v1.2.0", ">=1.2.0", "1.4.1", "1.5.1", "1.4.0-rc.1", undefined, 99.2]) {
285
+ for (const unknown of ["0.99.3", "0.99.10", "0.99", "v0.99.2", " 0.99.2", "0.99.2-rc.1", ">=0.99.2", "1.0.1", ">=1.0.0", "v1.0.0", " 1.0.0", "1.0.0-rc.1", "1.2.1", "1.2.0-rc.1", "v1.2.0", ">=1.2.0", "1.4.1", "1.5.3", "1.5.2-rc.1", "1.4.0-rc.1", undefined, 99.2]) {
286
286
  assert.equal(isAuditedPiEditorVersion(unknown), false, String(unknown));
287
287
  }
288
288
  });
@@ -1,5 +1,6 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test, { after, before } from "node:test";
3
+ import { readFileSync } from "node:fs";
3
4
  import { mkdir, mkdtemp, rm } from "node:fs/promises";
4
5
  import { tmpdir } from "node:os";
5
6
  import { join } from "node:path";
@@ -32,17 +33,40 @@ after(async () => {
32
33
  });
33
34
 
34
35
  async function delivered(): Promise<string> {
36
+ const prompt = await deliveredPrompt();
37
+ const start = prompt.indexOf("## Authorized work continuity");
38
+ const end = prompt.indexOf("# el Gentleman Orchestrator", start);
39
+ assert.ok(start >= 0 && end > start, "always-on parent continuity block is delivered before the core");
40
+ return prompt.slice(start, end);
41
+ }
42
+
43
+ // cost-speed-painpoints S15 P4: the verifier-setup rules load with the Verification rule (lazy module), and the
44
+ // unavailable-verifier rule stays always-on in the mirrored Close step (step 7).
45
+ const VERIFIER_SETUP_FAILURE = "A failed verifier setup is a preparation failure";
46
+ function verifierPreparation(): string {
47
+ const module = readFileSync(new URL("../assets/orchestrator-verification.md", import.meta.url), "utf8");
48
+ const heading = "## Verifier preparation failure\n\n";
49
+ const start = module.indexOf(heading);
50
+ assert.ok(start >= 0, "verification module keeps its preparation-failure section");
51
+ const body = module.slice(start + heading.length);
52
+ const end = body.indexOf("\n## ");
53
+ return end < 0 ? body : body.slice(0, end);
54
+ }
55
+ async function closeStep(): Promise<string> {
56
+ const close = (await deliveredPrompt()).split("\n").find((line) => line.startsWith("7. **Close.**"));
57
+ assert.ok(close, "the always-on prompt delivers the Close step");
58
+ return close;
59
+ }
60
+ const UNAVAILABLE_VERIFIER = "an unavailable verifier or subagent is reported as unavailable, never retried or escalated into extra ceremony";
61
+
62
+ async function deliveredPrompt(): Promise<string> {
35
63
  const handlers = new Map<string, (event: unknown, ctx: ExtensionContext) => unknown>();
36
64
  const pi = { on(name: string, handler: (event: unknown, ctx: ExtensionContext) => unknown) { handlers.set(name, handler); }, events: { emit() {} }, registerCommand() {}, registerTool() {} } as unknown as ExtensionAPI;
37
65
  createGentleAiExtension({ nativeReviewCli: null, processEnv: { ...env, GENTLE_PI_AGENTS_CHILD: "0", GENTLE_AI_TELEMETRY: "0" }, resolveTelemetryTriggerBinary: () => join(cwd, "never-executed"), telemetryTriggerSpawn: () => assert.fail("fixture must not spawn telemetry") })(pi);
38
66
  const event = { systemPrompt: "base", systemPromptOptions: { appendSystemPrompt: "" } };
39
67
  const ctx = { cwd, hasUI: true, ui: { notify() {}, setWidget() {} }, sessionManager: { getSessionId: () => "continuity-test", getBranch: () => [] } } as unknown as ExtensionContext;
40
68
  await handlers.get("before_agent_start")!(event, ctx);
41
- const prompt = event.systemPromptOptions.appendSystemPrompt;
42
- const start = prompt.indexOf("## Authorized work continuity");
43
- const end = prompt.indexOf("# el Gentleman Orchestrator", start);
44
- assert.ok(start >= 0 && end > start, "always-on parent continuity block is delivered before the core");
45
- return prompt.slice(start, end);
69
+ return event.systemPromptOptions.appendSystemPrompt;
46
70
  }
47
71
 
48
72
  function includesAll(text: string, clauses: string[]): void {
@@ -60,25 +84,44 @@ test("recoverable failure is distinguished from terminal missing proof within ex
60
84
  "never reset budgets, add retry allowances, weaken checks, or override final outcomes",
61
85
  "subject to every applicable limit",
62
86
  "Respect terminal review and verification outcomes and existing bounded-stop rules",
63
- "An unavailable verifier remains unavailable; do not retry or escalate it.",
64
87
  ]);
88
+ includesAll(await closeStep(), [UNAVAILABLE_VERIFIER]);
65
89
  });
66
90
 
67
91
  test("S2: setup failure preserves unrun proof without calling the verifier unavailable", async () => {
68
- includesAll(await delivered(), [
92
+ assert.ok(!(await deliveredPrompt()).includes(VERIFIER_SETUP_FAILURE), "the setup paragraph left the always-on prompt");
93
+ includesAll(verifierPreparation(), [
69
94
  "A failed verifier setup is a preparation failure, not an unavailable verifier capability.",
70
95
  "If setup fails before probes, preserve the failed attempt and report zero tests run; the checks remain unverified.",
71
- "An unavailable verifier remains unavailable; do not retry or escalate it.",
72
96
  ]);
97
+ includesAll(await closeStep(), [UNAVAILABLE_VERIFIER]);
73
98
  });
74
99
 
75
100
  test("S3: a repaired setup needs one explicit request and keeps every existing limit", async () => {
76
- includesAll(await delivered(), [
101
+ includesAll(verifierPreparation(), [
77
102
  "After a setup prerequisite is repaired, the human may explicitly request one new bounded verification attempt.",
78
- "This is a new request, not an automatic retry, and it does not reset the prior attempt or unrelated budgets.",
103
+ "This is a new request, not an automatic retry; it does not reset the prior attempt or unrelated budgets.",
79
104
  "Before proceeding, confirm no child is active or has an uncertain status.",
80
- "Never bypass consent, a denial, explicit one-run or no-retry limits, terminal native outcomes, or exhausted native budgets.",
105
+ "Never bypass consent, a denial, explicit one-run or no-retry limits, terminal native outcomes, or exhausted native budgets",
106
+ ]);
107
+ });
108
+
109
+ test("#3049: explicit quota recovery permits only the missing proof without reopening authority", async () => {
110
+ const parent = await delivered();
111
+ assert.ok(parent.includes("Quota recovery: `orchestrator-quota-recovery.md`."));
112
+ assert.ok(!parent.includes("A temporary verifier quota failure"), "recovery details load only on demand");
113
+ const recovery = readFileSync(new URL("../assets/orchestrator-quota-recovery.md", import.meta.url), "utf8");
114
+ includesAll(recovery, [
115
+ "A temporary verifier quota failure with no verdict still ends the automatic cycle.",
116
+ "After the human reports restored availability and explicitly requests the missing verification, allow one new bounded attempt for the same candidate.",
117
+ "Preserve the failed attempt and still-valid passed checks; do not replay passed suites.",
118
+ "Confirm no child is active or uncertain.",
119
+ "This is not an automatic retry, provider/model fallback, or reset of correction/native budgets.",
120
+ "Consent, denials, explicit one-run/no-retry limits and terminal native outcomes remain binding; failure never counts as approval.",
81
121
  ]);
122
+ includesAll(await closeStep(), [UNAVAILABLE_VERIFIER]);
123
+ const docs = readFileSync(new URL("../docs/work-continuity.md", import.meta.url), "utf8");
124
+ assert.ok(docs.includes("This guidance changes no runtime quota detection, provider selection, or native review authority."));
82
125
  });
83
126
 
84
127
  test("S4-S5: worker exhaustion exposes a bounded continuation without waiving proof", async () => {
@@ -0,0 +1,232 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { allowedEditSurfaces, rejectUnscopedBoundedWriterDispatch, WRITER_EDIT_SURFACE_REJECTION } from "../lib/bounded-writer-admission.ts";
4
+
5
+ // cost-speed P9b: a rejected `## Allowed edit surfaces` section names the invalid entry (quoted, bounded,
6
+ // control characters escaped), its position, why it is invalid and the fix, then one short rule sentence.
7
+ // The tool hook (extensions/gentle-ai.ts) and the executor (extensions/gentle-agents.ts) both call this function.
8
+
9
+ const H = "## Allowed edit surfaces\n";
10
+ const RULE = "Fix only that section, then relaunch with the rest of the task unchanged, never shortened or re-summarized; derive the surfaces from the task (narrow repository-relative paths or globs, one per line, until the next Markdown heading) and do not ask the human to author paths or globs.";
11
+
12
+ function reason(task: string, context?: string): string {
13
+ const result = rejectUnscopedBoundedWriterDispatch({ agent: "gentle-ai-worker", mode: "task", task, context });
14
+ assert.equal(result?.block, true, `rejected: ${JSON.stringify(task)}`);
15
+ return result!.reason;
16
+ }
17
+
18
+ const LIST_TEXT = "is text under a list marker, not a path; move it below another Markdown heading, as a line of its own outside the list";
19
+ const CONTROL = "contains a control or line-separator character; retype it without that character";
20
+ // The quote keeps every character but ASCII spaces at the ends, with invisible characters escaped.
21
+ const quote = (line: string) => line.replace(/^ +| +$/g, "").replace(/\p{Cc}|\p{Zl}|\p{Zp}/gu, char => `\\u${char.codePointAt(0)!.toString(16).padStart(4, "0")}`);
22
+ const entry = (shown: string, position: string, why: string) => `Allowed edit surfaces entry "${shown}" (${position}) ${why}. ${RULE}`;
23
+
24
+ test("the rule sentence is the exported constant, sent once, after the specific part", () => {
25
+ assert.equal(WRITER_EDIT_SURFACE_REJECTION, RULE);
26
+ const text = reason(`${H}/etc/passwd`);
27
+ assert.ok(text.endsWith(` ${RULE}`));
28
+ assert.equal(text.split(RULE).length, 2, "rule appears exactly once");
29
+ });
30
+
31
+ for (const [label, section, expected] of [
32
+ ["prose after a blank line", "src/a.ts\n\nRequirements: one parent transaction.", entry("Requirements: one parent transaction.", "non-empty line 2", "looks like prose; move it below another Markdown heading")],
33
+ ["list-marked prose", "- src/a.ts\n- Then run the focused test file.", entry("- Then run the focused test file.", "non-empty line 2", "looks like prose; move it below another Markdown heading")],
34
+ ["trailing comment after a path", "src/a.ts # the model", entry("src/a.ts # the model", "non-empty line 1", "has text after the path; move that text below another Markdown heading")],
35
+ ["path with spaces, no backticks", "- docs/with space.md", entry("- docs/with space.md", "non-empty line 1", "has spaces outside backticks; if it is one path, wrap the whole entry in backticks, otherwise move it below another Markdown heading")],
36
+ ["prose that is never a path", "- ~ notes for later", entry("- ~ notes for later", "non-empty line 1", "is not a path; move it below another Markdown heading")],
37
+ ["absolute path", "- /etc/passwd", entry("- /etc/passwd", "non-empty line 1", "is absolute or home-relative; use a repository-relative path")],
38
+ ["home path", "~/x.ts", entry("~/x.ts", "non-empty line 1", "is absolute or home-relative; use a repository-relative path")],
39
+ ["drive path", "C:\\x.ts", entry("C:\\x.ts", "non-empty line 1", "is absolute or home-relative; use a repository-relative path")],
40
+ ["repository root", "src/a.ts\n.", entry(".", "non-empty line 2", "names the whole repository; list only the paths or narrow globs the task edits")],
41
+ ["dot-slash root", "./", entry("./", "non-empty line 1", "names the whole repository; list only the paths or narrow globs the task edits")],
42
+ ["parent segment", "src/../../x.ts", entry("src/../../x.ts", "non-empty line 1", "has a `..` segment; use a path inside the repository")],
43
+ ["root glob", "**/*.ts", entry("**/*.ts", "non-empty line 1", "starts with a glob, so it spans the whole repository; start with a directory, for example `src/**/*.ts`")],
44
+ ["stray backtick", "src/`odd.ts", entry("src/`odd.ts", "non-empty line 1", "has stray backticks; remove them")],
45
+ ["partial backticks", "`lib/a.ts` trailing", entry("`lib/a.ts` trailing", "non-empty line 1", "has text outside its backticked path; move that text below another Markdown heading")],
46
+ ["control character", "src/a\u0007.ts", entry("src/a\\u0007.ts", "non-empty line 1", "contains a control or line-separator character; retype it without that character")],
47
+ ["line separator", "`Dir\u2028x/a.md`", entry("`Dir\\u2028x/a.md`", "non-empty line 1", "contains a control or line-separator character; retype it without that character")],
48
+ ["marker only", "src/a.ts\n-", entry("-", "non-empty line 2", "is a list marker with no path; put the path after it or delete the line")],
49
+ ["numbered marker only", "1.", entry("1.", "non-empty line 1", "is a list marker with no path; put the path after it or delete the line")],
50
+ ["heading indented four spaces", "src/a.ts\n ## Return", entry("## Return", "non-empty line 2", "is a heading indented 4+ spaces, so it does not end the section; start it at the line start")],
51
+ ["heading-like text under a dash marker", "src/a.ts\n- # foo", entry("- # foo", "non-empty line 2", LIST_TEXT)],
52
+ ["heading-like text under a star marker", "* ## notes", entry("* ## notes", "non-empty line 1", LIST_TEXT)],
53
+ ["leading tab", "\tsrc/a.ts", entry("\\u0009src/a.ts", "non-empty line 1", CONTROL)],
54
+ ["trailing tab", "src/a.ts\t", entry("src/a.ts\\u0009", "non-empty line 1", CONTROL)],
55
+ ["tab-indented list entry", "src/b.ts\n\t- src/a.ts", entry("\\u0009- src/a.ts", "non-empty line 2", CONTROL)],
56
+ ] as const) {
57
+ test(`invalid entry names line, position, reason and fix: ${label}`, () => {
58
+ assert.equal(reason(`Task.\n\n${H}${section}\n\n## Return\nReport`), expected);
59
+ });
60
+ }
61
+
62
+ test("several invalid entries: the first is named and the rest are counted", () => {
63
+ assert.equal(reason(`${H}src/a.ts\n/abs\nnote one\n..`), entry("/abs", "non-empty line 2", "is absolute or home-relative; use a repository-relative path").replace(`. ${RULE}`, `. 2 more invalid lines follow. ${RULE}`));
64
+ assert.equal(reason(`${H}/abs\n..`), entry("/abs", "non-empty line 1", "is absolute or home-relative; use a repository-relative path").replace(`. ${RULE}`, `. 1 more invalid line follows. ${RULE}`));
65
+ });
66
+
67
+ test("an invalid entry in a later section names that section", () => {
68
+ assert.equal(reason(`${H}src/a.ts`, `${H}src/a.ts\n/abs`), entry("/abs", "non-empty line 2 of section 2", "is absolute or home-relative; use a repository-relative path"));
69
+ });
70
+
71
+ test("section-level problems name what to change", () => {
72
+ assert.equal(reason("Implement it."), `No \`## Allowed edit surfaces\` heading was found; add it with one path per line. ${RULE}`);
73
+ assert.equal(reason("Implement it.\n\n## Allowed edit surfaces:\nsrc/a.ts"), `No \`## Allowed edit surfaces\` heading was found; "## Allowed edit surfaces:" is close: rename it to exactly \`## Allowed edit surfaces\`. ${RULE}`);
74
+ assert.equal(reason("### Edit surfaces\nsrc/a.ts"), `No \`## Allowed edit surfaces\` heading was found; "### Edit surfaces" is close: rename it to exactly \`## Allowed edit surfaces\`. ${RULE}`);
75
+ assert.equal(reason(`${H}\n## Return\nReport`), `The \`## Allowed edit surfaces\` section has no entries; add one path per line before the next heading. ${RULE}`);
76
+ assert.equal(reason(`${H}src/a.ts`, `${H}src/b.ts`), `Repeated \`## Allowed edit surfaces\` sections disagree on "src/a.ts"; keep one section or list the same entries in each. ${RULE}`);
77
+ });
78
+
79
+ test("echo is bounded to 80 UTF-8 bytes and secret-looking values are masked", () => {
80
+ const long = `Then ${"verify every requirement ".repeat(8)}carefully.`;
81
+ const text = reason(`${H}${long}`);
82
+ const shown = text.match(/^Allowed edit surfaces entry "(.*)" \(non-empty line 1\)/)![1];
83
+ assert.ok(shown.endsWith("…"));
84
+ assert.ok(Buffer.byteLength(shown) <= 80, shown);
85
+ assert.equal(shown, `${long.slice(0, 77)}…`);
86
+ const wide = reason(`${H}${"é".repeat(30)} notes here`).match(/"(.*)"/)![1];
87
+ assert.ok(Buffer.byteLength(wide) <= 80 && !wide.includes("\ufffd"), wide);
88
+ const secret = reason(`${H}API_KEY = sk-live-abcdefghijklmnopqrstuvwxyz0123456789`);
89
+ assert.doesNotMatch(secret, /sk-live|abcdefghij/);
90
+ assert.match(secret, /^Allowed edit surfaces entry "API_KEY = \*\*\*" \(non-empty line 1\)/);
91
+ const token = reason(`${H}- use ghp_0123456789abcdefghijABCDEFGHIJklmnop here`);
92
+ assert.doesNotMatch(token, /ghp_0123/);
93
+ assert.match(token, /"- use \*\*\* here"/);
94
+ });
95
+
96
+ // Messages only: the accept/reject decision is the one the existing pins hold.
97
+ test("accepted inputs stay accepted", () => {
98
+ for (const [section, paths] of [
99
+ ["src/a.ts", ["src/a.ts"]],
100
+ ["src/**/*.test.ts", ["src/**/*.test.ts"]],
101
+ ["`docs/with space.md`", ["docs/with space.md"]],
102
+ ["- src/a.ts\n* src/b.ts\n+ src/c.ts\n1. src/d.ts\n2) src/e.ts", ["src/a.ts", "src/b.ts", "src/c.ts", "src/d.ts", "src/e.ts"]],
103
+ ["src/a.ts\n\n\nsrc/b.ts", ["src/a.ts", "src/b.ts"]],
104
+ ["- `-`", ["-"]],
105
+ ["./src/a.ts", ["./src/a.ts"]],
106
+ ["#Return", ["#Return"]],
107
+ [" src/a.ts ", ["src/a.ts"]],
108
+ ] as const) {
109
+ const task = `Task.\n${H}${section}\n## Return\nReport`;
110
+ assert.deepEqual(allowedEditSurfaces(task), [...paths], section);
111
+ assert.equal(rejectUnscopedBoundedWriterDispatch({ agent: "worker", task }), undefined, section);
112
+ }
113
+ });
114
+
115
+ test("rejected inputs stay rejected", () => {
116
+ for (const section of ["", "Requirements: x.", "src/a.ts # c", "/abs", ".", "..", "**/*.ts", "a b/c.md", "src/a\u0007.ts", "-", "`x", " ## Return", "``"]) {
117
+ const task = `${H}${section}`;
118
+ assert.equal(allowedEditSurfaces(task), undefined, JSON.stringify(section));
119
+ assert.equal(rejectUnscopedBoundedWriterDispatch({ agent: "gentle-ai-worker", task })?.block, true, JSON.stringify(section));
120
+ }
121
+ assert.equal(rejectUnscopedBoundedWriterDispatch({ agent: "gentle-ai-explore", task: "no heading" }), undefined, "non-writers are untouched");
122
+ });
123
+
124
+ // Verifier blocker 3: the fix a message suggests, applied literally to the offending entry, yields the path the
125
+ // author meant or an input that is still rejected; never a different accepted surface.
126
+ function applyFix(entry: string, message: string, intent: "path" | "prose"): string | undefined {
127
+ const marker = /^(?:[-*+]|\d+[.)]) +/.exec(entry)?.[0] ?? "";
128
+ const body = entry.slice(marker.length);
129
+ if (message.includes("if it is one path, wrap")) return intent === "path" ? `${marker}\`${body}\`` : undefined;
130
+ if (message.includes("move that text below")) return `${marker}${/`[^`]+`/.exec(body)?.[0] ?? body.split(/\s+/)[0].replace(/:$/, "")}`;
131
+ if (message.includes("keep only the path")) return `${marker}${body.split(/\s+/).at(-1)}`;
132
+ if (message.includes("put one path per line")) return body.split(/\s*,\s*/).map(path => `${marker}${path}`).join("\n");
133
+ if (message.includes("remove them")) return entry.replace(/`/g, "");
134
+ if (message.includes("retype it without that character")) return entry.replace(/\p{Cc}|\p{Zl}|\p{Zp}/gu, "");
135
+ if (/move it below another Markdown heading|delete the line/.test(message)) return undefined;
136
+ if (message.includes("start it at the line start")) return entry.trimStart();
137
+ return "not mechanical";
138
+ }
139
+
140
+ for (const [entry, why, intent, expected] of [
141
+ ["- `src/a.ts` \u2014 new file", "has text outside its backticked path; move that text below another Markdown heading", "path", ["src/a.ts"]],
142
+ ["`src/a.ts` (new)", "has text outside its backticked path; move that text below another Markdown heading", "path", ["src/a.ts"]],
143
+ ["src/a.ts (new file)", "has text after the path; move that text below another Markdown heading", "path", ["src/a.ts"]],
144
+ ["src/a.ts # the model", "has text after the path; move that text below another Markdown heading", "path", ["src/a.ts"]],
145
+ ["src/a.ts: the parser", "has text after the path; move that text below another Markdown heading", "path", ["src/a.ts"]],
146
+ ["src/a.ts, src/b.ts", "lists several paths; put one path per line", "path", ["src/a.ts", "src/b.ts"]],
147
+ ["Files: src/a.ts", "has a label before the path; keep only the path", "path", ["src/a.ts"]],
148
+ ["docs/my file.md", "has spaces outside backticks; if it is one path, wrap the whole entry in backticks, otherwise move it below another Markdown heading", "path", ["docs/my file.md"]],
149
+ ["Then run tests/a.test.ts", "has spaces outside backticks; if it is one path, wrap the whole entry in backticks, otherwise move it below another Markdown heading", "prose", []],
150
+ ["edit the parser module", "looks like prose; move it below another Markdown heading", "prose", []],
151
+ ["Requirements: one parent transaction.", "looks like prose; move it below another Markdown heading", "prose", []],
152
+ ["- ~ notes for later", "is not a path; move it below another Markdown heading", "prose", []],
153
+ ["`src/a.ts", "has stray backticks; remove them", "path", ["src/a.ts"]],
154
+ ["``", "has stray backticks; remove them", "path", []],
155
+ ["src/a\u0007.ts", "contains a control or line-separator character; retype it without that character", "path", ["src/a.ts"]],
156
+ ["-", "is a list marker with no path; put the path after it or delete the line", "prose", []],
157
+ [" ## Notes", "is a heading indented 4+ spaces, so it does not end the section; start it at the line start", "prose", []],
158
+ ["- # foo", LIST_TEXT, "prose", []],
159
+ ["* ## notes", LIST_TEXT, "prose", []],
160
+ ["\tsrc/a.ts", CONTROL, "path", ["src/a.ts"]],
161
+ ["src/a.ts\t", CONTROL, "path", ["src/a.ts"]],
162
+ ["\t- src/a.ts", CONTROL, "path", ["src/a.ts"]],
163
+ ["~/my repo/a.ts", "is absolute or home-relative; use a repository-relative path", "path", null],
164
+ ["C:\\Users\\me\\my repo\\a.ts", "is absolute or home-relative; use a repository-relative path", "path", null],
165
+ ["/Users/x/repo/src/a.ts", "is absolute or home-relative; use a repository-relative path", "path", null],
166
+ ["**/my file.ts", "starts with a glob, so it spans the whole repository; start with a directory, for example `src/**/*.ts`", "path", null],
167
+ ["**/*.ts", "starts with a glob, so it spans the whole repository; start with a directory, for example `src/**/*.ts`", "path", null],
168
+ ["../my file.ts", "has a `..` segment; use a path inside the repository", "path", null],
169
+ ["src/../x", "has a `..` segment; use a path inside the repository", "path", null],
170
+ ["./", "names the whole repository; list only the paths or narrow globs the task edits", "path", null],
171
+ ] as const) {
172
+ test(`the suggested fix never admits a different surface: ${JSON.stringify(entry)}`, () => {
173
+ const message = reason(`${H}src/keep.ts\n${entry}`);
174
+ assert.equal(message, `Allowed edit surfaces entry "${quote(entry)}" (non-empty line 2) ${why}. ${RULE}`);
175
+ const fixed = applyFix(entry, message, intent);
176
+ if (expected === null) {
177
+ // Not mechanical: the author supplies a new value. Wrapping it instead never admits it.
178
+ assert.equal(fixed, "not mechanical");
179
+ assert.doesNotMatch(message, /wrap/);
180
+ assert.equal(allowedEditSurfaces(`${H}src/keep.ts\n\`${entry}\``), undefined);
181
+ return;
182
+ }
183
+ const section = `${H}src/keep.ts${fixed === undefined ? "" : `\n${fixed}`}\n## Return`;
184
+ assert.deepEqual(allowedEditSurfaces(section), ["src/keep.ts", ...expected].sort(), String(fixed));
185
+ });
186
+ }
187
+
188
+ test("the quoted entry, ellipsis included, is at most 80 UTF-8 bytes", () => {
189
+ for (const line of [`Then ${"verify every requirement ".repeat(8)}carefully.`, `${"é".repeat(60)} notes here`, `${"😀".repeat(40)} x`]) {
190
+ const shown = reason(`${H}${line}`).match(/^Allowed edit surfaces entry "(.*)" \(non-empty line 1\)/)![1];
191
+ assert.ok(shown.endsWith("…"), shown);
192
+ assert.ok(Buffer.byteLength(shown) <= 80, `${Buffer.byteLength(shown)} ${shown}`);
193
+ assert.ok(!shown.includes("\ufffd"));
194
+ }
195
+ });
196
+
197
+ test("a tab at either end of an entry stays in the quote, escaped, within the 80-byte bound", () => {
198
+ const shown = (line: string) => reason(`${H}${line}`).match(/^Allowed edit surfaces entry "(.*)" \(non-empty line 1\)/)![1];
199
+ assert.equal(shown("\tsrc/a.ts"), "\\u0009src/a.ts");
200
+ assert.equal(shown("src/a.ts\t"), "src/a.ts\\u0009");
201
+ assert.equal(shown(" \t- src/a.ts "), "\\u0009- src/a.ts");
202
+ const long = shown(`\t${"x".repeat(200)}\t`);
203
+ assert.ok(long.startsWith("\\u0009x") && long.endsWith("…") && Buffer.byteLength(long) <= 80, long);
204
+ });
205
+
206
+ // Review of PR #3114: the quote is produced in time linear in the entry length, and a masked token never leaks a prefix.
207
+ // 64 KiB runs first: a superlinear regression fails that size's time assertion in seconds instead of hanging
208
+ // the job on the 1 MiB input.
209
+ test("a 64 KiB and a 1 MiB invalid entry are quoted quickly and masked tokens never leak", () => {
210
+ for (const size of [64 << 10, 1 << 20]) quotesQuickly(size);
211
+ });
212
+
213
+ function quotesQuickly(MiB: number) {
214
+ const token = (n: number) => "Ab3".repeat(Math.ceil(n / 3)).slice(0, n);
215
+ for (const [label, line, expected] of [
216
+ ["prose", `${"lorem ipsum dolor ".repeat(MiB / 18)}end.`, `${"lorem ipsum dolor ".repeat(5).slice(0, 77)}…`],
217
+ ["one word with no secret label", `see ${"a".repeat(MiB)} later`, `see ${"a".repeat(73)}…`],
218
+ ["a single token-like run", `/${token(MiB)}`, "/***"],
219
+ ["a token-like run after prose", `then use ${token(MiB)} here`, "then use *** here"],
220
+ ["a secret label before a long value", `api_token = ${token(MiB)}`, "api_token = ***"],
221
+ ["a long non-breaking space run with no comma", `a b${"\u00a0".repeat(MiB)}c`, `a b${"\u00a0".repeat(37)}…`],
222
+ ["short words then a long token", `${"word ".repeat(10)}${token(MiB)} end`, `${"word ".repeat(10)}*** end`],
223
+ ] as const) {
224
+ const started = performance.now();
225
+ const text = reason(`${H}src/keep.ts\n${line}`);
226
+ const elapsed = performance.now() - started;
227
+ assert.ok(elapsed < 500, `${label} at ${MiB} bytes: ${Math.round(elapsed)} ms`);
228
+ const shown = text.match(/^Allowed edit surfaces entry "(.*)" \(non-empty line 2\)/)![1];
229
+ assert.equal(shown, expected, label);
230
+ assert.ok(Buffer.byteLength(shown) <= 80, label);
231
+ }
232
+ }
@@ -0,0 +1,66 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { sameMessageToolCalls } from "../lib/writer-batch-admission.ts";
4
+
5
+ // cost-speed P6: the batch is read from the session branch at `tool_call`, where Pi already persisted the assistant
6
+ // message (on `message_end`). Results of earlier calls of the same message may follow it; an older message never
7
+ // lends its calls.
8
+
9
+ type Entry = { type: string; id: string; parentId: string | null; message?: Record<string, unknown> };
10
+
11
+ function branch(entries: Entry[]) {
12
+ const byId = new Map(entries.map(entry => [entry.id, entry]));
13
+ return { getLeafEntry: () => entries.at(-1), getEntry: (id: string) => byId.get(id) };
14
+ }
15
+
16
+ const assistant = (id: string, parentId: string | null, calls: string[]): Entry => ({ type: "message", id, parentId, message: { role: "assistant", content: [{ type: "text", text: "go" }, ...calls.map(call => ({ type: "toolCall", id: call, name: "subagent_run", arguments: { agent: "worker", task: call } }))] } });
17
+ const result = (id: string, parentId: string, toolCallId: string): Entry => ({ type: "message", id, parentId, message: { role: "toolResult", toolCallId, content: [] } });
18
+
19
+ test("P6: the batch is the issuing message's tool calls, past results and extension entries of the same turn", () => {
20
+ const session = branch([
21
+ assistant("a1", null, ["c1", "c2"]),
22
+ result("r1", "a1", "c1"),
23
+ { type: "custom", id: "x1", parentId: "r1" },
24
+ ]);
25
+ assert.deepEqual(sameMessageToolCalls(session, "c2"), [
26
+ { name: "subagent_run", arguments: { agent: "worker", task: "c1" } },
27
+ { name: "subagent_run", arguments: { agent: "worker", task: "c2" } },
28
+ ]);
29
+ });
30
+
31
+ test("P6: a call missing from the nearest assistant message gets no batch, and neither does an unreadable session", () => {
32
+ const session = branch([assistant("a1", null, ["old1", "old2"]), result("r1", "a1", "old1"), result("r2", "r1", "old2"), assistant("a2", "r2", ["new1"])]);
33
+ assert.equal(sameMessageToolCalls(session, "old1"), undefined, "an older message never lends its calls");
34
+ assert.equal(sameMessageToolCalls(session, "nested-in-codemode"), undefined);
35
+ assert.equal(sameMessageToolCalls(undefined, "new1"), undefined);
36
+ assert.equal(sameMessageToolCalls(session, undefined), undefined);
37
+ assert.equal(sameMessageToolCalls({ getLeafEntry: () => { throw new Error("closed"); }, getEntry: () => undefined }, "new1"), undefined);
38
+ });
39
+
40
+ // Verifier mwb9qlc5-22-nfsa probes, kept as regression tests.
41
+ const custom = (id: string, parentId: string): Entry => ({ type: "custom", id, parentId });
42
+
43
+ test("P6: a compaction leaf behind the current message still yields its calls", () => {
44
+ const session = branch([assistant("a1", null, ["c1", "c2"]), { type: "compaction", id: "k1", parentId: "a1" }]);
45
+ assert.deepEqual(sameMessageToolCalls(session, "c1")?.map(call => (call.arguments as { task: string }).task), ["c1", "c2"]);
46
+ });
47
+
48
+ test("P6: a message more than 64 entries behind the leaf gives no batch", () => {
49
+ const entries: Entry[] = [assistant("a1", null, ["c1", "c2"])];
50
+ for (let index = 0; index < 64; index++) entries.push(custom(`x${index}`, entries.at(-1)!.id));
51
+ assert.equal(sameMessageToolCalls(branch(entries), "c1"), undefined);
52
+ assert.ok(sameMessageToolCalls(branch(entries.slice(0, 64)), "c1"), "63 entries behind is still within the bound");
53
+ });
54
+
55
+ test("P6: repeated ids fail closed: an older message whose call already has its result is not the one executing", () => {
56
+ // Providers repeat call ids across messages (a resumed session repeated `a_1`/`b_2`); if the current message were
57
+ // not persisted yet, the nearest assistant would be an older one carrying the same id, already answered.
58
+ const session = branch([assistant("a1", null, ["c1", "c2"]), result("r1", "a1", "c1"), result("r2", "r1", "c2"), { type: "message", id: "u1", parentId: "r2", message: { role: "user", content: "next" } }]);
59
+ assert.equal(sameMessageToolCalls(session, "c1"), undefined);
60
+ assert.equal(sameMessageToolCalls(session, "c2"), undefined);
61
+ });
62
+
63
+ test("P6 preserve: in Pi's sequential path an earlier call's result does not void the current call's batch", () => {
64
+ const session = branch([assistant("a1", null, ["c1", "c2", "c3"]), result("r1", "a1", "c1"), result("r2", "r1", "c2")]);
65
+ assert.equal(sameMessageToolCalls(session, "c3")?.length, 3);
66
+ });