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,7 +2,7 @@ import { lstatSync, readdirSync, readFileSync, realpathSync, mkdirSync, writeFil
2
2
  import { dirname, extname, join, parse, resolve, win32 } from "node:path";
3
3
  import { spawnSync } from "node:child_process";
4
4
  import { gunzipSync } from "node:zlib";
5
- import { artifactFor, verifiedDownload, compatibleEngine, launchWizard, pinnedPnpmCompatible } from "./installer-downloads.mjs";
5
+ import { artifactFor, verifiedDownload, compatibleEngine, launchWizard, nodeRequirementSatisfied, pinnedPnpmCompatible } from "./installer-downloads.mjs";
6
6
 
7
7
  export const windowsNodeFloor = ">=24.3.0";
8
8
  const maxExpandedBytes = 128 * 1024 * 1024;
@@ -765,7 +765,7 @@ export async function bootstrapWindows({ bundle, tools, env }) {
765
765
  if (!regular(join(bundle, file))) throw new Error("Required wizard bundle file missing");
766
766
  }
767
767
  const metadata = JSON.parse(readFileSync(join(bundle, "package.json"), "utf8"));
768
- if (!compatibleEngine(windowsNodeFloor, process.versions.node) || !compatibleEngine(metadata.engines?.node, process.versions.node) || metadata.packageManager !== `pnpm@${artifactFor("pnpm").version}`) throw new Error("Windows repository prerequisite rejected");
768
+ if (!compatibleEngine(windowsNodeFloor, process.versions.node) || !nodeRequirementSatisfied(metadata.engines?.node, process.versions.node) || metadata.packageManager !== `pnpm@${artifactFor("pnpm").version}`) throw new Error("Windows repository prerequisite rejected");
769
769
  step = "tools-storage";
770
770
  verifyWindowsStorage(tools, env);
771
771
  const result = await ensureWindowsPnpm({ tools, env, onStep: (next) => { step = next; } });
@@ -9,6 +9,7 @@ const object = value => value !== null && typeof value === 'object' && !Array.is
9
9
  const succeeded = result => result?.code === 0 && !result.timedOut && result.signal == null;
10
10
  const refusal = detail => new Error(`gentle-shell update: ownership ${detail}; update Pi with the package manager or source checkout that supplies the selected runtime. No installation changed.`);
11
11
  const LINKED = /^(?:file|link|workspace):/i;
12
+ const STABLE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
12
13
  // A main-channel Shell (`<version>-main.<sha12>`, scripts/main-channel.mjs
13
14
  // mainVersion) is never published; it exists only as the packed tarball.
14
15
  const MAIN_BUILD = /^[0-9A-Za-z.+-]+-main\.[0-9a-f]{12}$/;
@@ -130,7 +131,7 @@ async function listedEntries(groups, {adapters, path, key, canonical}) {
130
131
  const set = members.get(key(groupRoot)) ?? new Set();
131
132
  set.add(pkg);
132
133
  members.set(key(groupRoot), set);
133
- if (pkg === PI || pkg === SHELL) entries.push({pkg, dependency, groupRoot});
134
+ if (pkg === PI || pkg === SHELL) entries.push({pkg, dependency, groupRoot, listingRoot: path.isAbsolute(group.path) ? key(group.path) : null});
134
135
  }
135
136
  }
136
137
  return {entries, members};
@@ -231,9 +232,9 @@ async function sourceOwner({root, linkPath, manifest, selected, adapters, path,
231
232
  if (!succeeded(listing) || !Array.isArray(projects) || projects.length !== 1 || key(await canonical(projects[0]?.path)) !== key(root)) throw refusal('source workspace has other or unknown projects; update Pi from the workspace owner');
232
233
  }
233
234
  const flags = pin[1] === 'pnpm' ? ['--dir', root, '--lockfile-dir', root, '--recursive=false', '--ignore-pnpmfile', ...(sourceConfig === undefined ? [] : ['--workspace-root'])] : ['--prefix', root, '--workspaces=false', '--no-audit', '--no-fund'];
234
- return {name:pin[1], ...invocation, package:SHELL, spec:PI, sourceRoot:root, sourceConfig, sourceEnv, linkPath,
235
+ return {name:pin[1], ...invocation, package:SHELL, spec:PI, sourceRoot:root, sourceConfig, sourceEnv, sourceOptions, linkPath,
235
236
  manifest:await adapters.fs.readFile(path.join(root, 'package.json'), 'utf8'),
236
- args:['update', PI, '--no-save', '--ignore-scripts', '--global=false', ...flags, ...sourceOptions]};
237
+ args:[pin[1] === 'pnpm' ? 'update' : 'install', PI, '--no-save', '--ignore-scripts', '--global=false', ...flags, ...sourceOptions]};
237
238
  }
238
239
 
239
240
  export async function resolveUpdateOwner({runtime, packageRoot, platform = process.platform, adapters, cwd, env, home}) {
@@ -248,7 +249,7 @@ export async function resolveUpdateOwner({runtime, packageRoot, platform = proce
248
249
  if (!invocation) continue;
249
250
  const groups = await globalListing(name, invocation, adapters, cwd);
250
251
  const {entries, members} = await listedEntries(groups, {adapters, path, key, canonical});
251
- for (const {pkg, dependency, groupRoot} of entries) {
252
+ for (const {pkg, dependency, groupRoot, listingRoot} of entries) {
252
253
  if ((pkg === SHELL) !== adjacent) continue;
253
254
  const linked = dependency.link === true || [dependency.resolved, dependency.version].some(value => typeof value === 'string' && LINKED.test(value));
254
255
  const root = await canonical(dependency.path);
@@ -280,34 +281,169 @@ export async function resolveUpdateOwner({runtime, packageRoot, platform = proce
280
281
  }
281
282
  if (key(cli) !== key(selected)) continue;
282
283
  if (name === 'pnpm' && members.get(key(groupRoot)).size !== 1) throw refusal('selected supplier shares its global install group');
283
- candidates.push({name, ...invocation, package:pkg, spec, artifact});
284
+ // Keep the listing snapshot and selected identity: pnpm may replace both
285
+ // this group and the versioned store root during the same installation.
286
+ candidates.push({name, ...invocation, package:pkg, spec, artifact, groupRoot, listingRoot, members,
287
+ from:dependency.from, shellVersion:pkg === SHELL ? manifest.version : undefined});
284
288
  }
285
289
  }
286
290
  if (candidates.length !== 1) throw refusal(candidates.length > 1 ? 'is ambiguous' : 'could not be verified from global listings');
287
291
  return candidates[0];
288
292
  }
289
293
 
294
+ // Registry queries run in the same manager/config context as the install.
295
+ function viewIn(owner, input, args) {
296
+ const scope = owner.sourceRoot
297
+ ? owner.name === 'pnpm' ? ['--dir', owner.sourceRoot, ...owner.sourceOptions] : ['--prefix', owner.sourceRoot, '--workspaces=false']
298
+ : owner.name === 'pnpm' ? ['--config.global=true'] : [];
299
+ return input.adapters.run(owner.command, [...owner.prefix, 'view', ...args, ...scope],
300
+ {deadlineMs:60_000, cwd:owner.sourceRoot ?? input.cwd, ...(owner.sourceEnv ? {env:owner.sourceEnv} : {})});
301
+ }
302
+
303
+ // Only a stable registry tag may become an install argument; never trust arbitrary output.
304
+ async function latestPublishedPi(owner, input) {
305
+ const result = await viewIn(owner, input, [`${PI}@latest`, 'version']);
306
+ if (!succeeded(result) || result.truncated) throw new Error(`gentle-shell update: the latest published Pi could not be resolved (${owner.name} view failed). No installation changed.`);
307
+ const version = String(result.stdout ?? '').trim();
308
+ if (!STABLE.test(version)) throw new Error(`gentle-shell update: the latest published Pi version ${JSON.stringify(version)} was rejected. No installation changed.`);
309
+ return version;
310
+ }
311
+
312
+ const SIBLING = /^@earendil-works\/[a-z0-9][a-z0-9._-]*$/;
313
+ const MAX_SIBLINGS = 32;
314
+ // An exact version as pnpm accepts it in a minimumReleaseAgeExclude union.
315
+ const EXACT = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
316
+
317
+ // The published dependencies of one exact version, checked against its identity.
318
+ async function publishedDependencies(owner, input, name, version) {
319
+ const result = await viewIn(owner, input, [`${name}@${version}`, '--json']);
320
+ try {
321
+ const manifest = JSON.parse(String(result.stdout ?? ''));
322
+ const dependencies = manifest?.dependencies ?? {};
323
+ if (!succeeded(result) || result.truncated || !object(manifest) || manifest.name !== name || manifest.version !== version ||
324
+ !object(dependencies) || Object.values(dependencies).some(range => typeof range !== 'string')) throw new Error('invalid');
325
+ return Object.entries(dependencies).filter(([dependency, range]) => SIBLING.test(dependency) && dependency !== PI && STABLE.test(range));
326
+ } catch { throw new Error(`gentle-shell update: the published dependencies of ${name === PI ? 'Pi ' : `${name}@`}${version} could not be verified. No installation changed.`); }
327
+ }
328
+
329
+ /** Every Pi-scope package, as [name, version], that the selected Pi pins to an
330
+ * exact stable version directly or through such a pinned package (pi-ai pins
331
+ * pi-schema). They are published with Pi, so no older version can satisfy
332
+ * them, and pnpm's strict release-age mode cannot approve them under
333
+ * --no-save. Ranges, prereleases and other scopes stay age-filtered. The walk
334
+ * visits each package version once and is bounded.
335
+ */
336
+ async function piSiblings(owner, input, version) {
337
+ const found = new Map();
338
+ let pending = await publishedDependencies(owner, input, PI, version);
339
+ while (pending.length) {
340
+ const level = [];
341
+ for (const [name, exact] of pending) {
342
+ if (found.has(`${name}@${exact}`)) continue;
343
+ if (found.size >= MAX_SIBLINGS) throw new Error(`gentle-shell update: Pi ${version} pins more than ${MAX_SIBLINGS} @earendil-works packages; their release age could not be verified. No installation changed.`);
344
+ found.set(`${name}@${exact}`, [name, exact]);
345
+ level.push([name, exact]);
346
+ }
347
+ pending = (await Promise.all(level.map(([name, exact]) => publishedDependencies(owner, input, name, exact)))).flat();
348
+ }
349
+ return [...found.values()];
350
+ }
351
+
352
+ // pnpm's matcher (parseVersionPolicyRule) splits a rule at the `@` after a scope.
353
+ function exclusionName(entry) {
354
+ const at = entry.startsWith('@') ? entry.indexOf('@', 1) : entry.indexOf('@');
355
+ return at === -1 ? {name:entry, versions:null} : {name:entry.slice(0, at), versions:entry.slice(at + 1)};
356
+ }
357
+
358
+ // CLI values replace pnpm's configured list, so read the effective list in the
359
+ // install context and pass it back intact with Pi and its exact siblings added.
360
+ // pnpm applies only the first rule naming a package, so a new version joins
361
+ // that name's existing rule as one `name@a || b` union (a bare name already
362
+ // covers every version); a rule it cannot merge safely is refused. pnpm
363
+ // represents a single CLI value as a string, not an array; repeat it when the
364
+ // list has one entry.
365
+ async function piAgeExclusion(owner, input, siblings) {
366
+ const scope = owner.sourceRoot ? ['--dir', owner.sourceRoot, ...owner.sourceOptions] : ['--global'];
367
+ const result = await input.adapters.run(owner.command, [...owner.prefix, 'config', 'get', 'minimumReleaseAgeExclude', '--json', ...scope],
368
+ {deadlineMs:30_000, cwd:owner.sourceRoot ?? input.cwd, ...(owner.sourceEnv ? {env:owner.sourceEnv} : {})});
369
+ const invalid = () => new Error('gentle-shell update: pnpm release-age exclusions could not be verified. No installation changed.');
370
+ let entries;
371
+ try {
372
+ const text = String(result.stdout ?? '').trim();
373
+ entries = text === '' || text === 'undefined' ? [] : JSON.parse(text);
374
+ if (typeof entries === 'string') entries = [entries];
375
+ if (!succeeded(result) || result.truncated || !Array.isArray(entries) || entries.some(entry => typeof entry !== 'string' || !entry)) throw new Error('invalid');
376
+ } catch { throw invalid(); }
377
+ // Wanted versions per name, in order; null means every version (Pi itself).
378
+ const wanted = new Map([[PI, null]]);
379
+ for (const [name, version] of siblings) if (wanted.get(name) !== null) wanted.set(name, [...(wanted.get(name) ?? []), version]);
380
+ const merged = new Map();
381
+ for (const entry of entries) {
382
+ const {name, versions} = exclusionName(entry);
383
+ if (!wanted.has(name)) continue;
384
+ const listed = versions === null ? null : versions.split('||').map(version => version.trim());
385
+ if (listed?.some(version => !EXACT.test(version))) throw invalid();
386
+ const before = merged.has(name) ? merged.get(name) : [];
387
+ merged.set(name, before === null || listed === null ? null : [...before, ...listed]);
388
+ }
389
+ const rule = name => {
390
+ const versions = merged.has(name) && merged.get(name) === null || wanted.get(name) === null ? null : [...new Set([...(merged.get(name) ?? []), ...wanted.get(name)])];
391
+ return versions === null ? name : `${name}@${versions.join(' || ')}`;
392
+ };
393
+ const placed = new Set();
394
+ const list = [];
395
+ for (const entry of entries) {
396
+ const {name} = exclusionName(entry);
397
+ if (!wanted.has(name)) list.push(entry);
398
+ else if (!placed.has(name)) { placed.add(name); list.push(rule(name)); }
399
+ }
400
+ for (const name of wanted.keys()) if (!placed.has(name)) list.push(rule(name));
401
+ if (list.length === 1) list.push(list[0]);
402
+ return list.map(entry => `--config.minimum-release-age-exclude=${entry}`);
403
+ }
404
+
290
405
  /** The Pi version the owner's package now supplies, read back from a fresh
291
- * listing after the install; null when it cannot be read.
406
+ * listing after the install; null when continuity or identity is uncertain.
292
407
  */
293
408
  async function suppliedPiVersion(owner, {platform, adapters, cwd}) {
294
409
  const {path, key} = pathsFor(platform);
295
410
  const canonical = canonicalWith(adapters, path);
296
411
  try {
297
412
  const groups = await globalListing(owner.name, owner, adapters, cwd);
298
- const {entries} = await listedEntries(groups, {adapters, path, key, canonical});
299
- for (const {pkg, dependency, groupRoot} of entries) {
300
- if (pkg !== owner.package) continue;
301
- const root = await canonical(dependency.path);
302
- if (pkg === PI) return (await manifestOf(adapters, path, root)).version ?? null;
303
- if ((await manifestOf(adapters, path, root)).name !== SHELL) continue;
304
- const peer = await adjacentPeer({shellRoot: root, groupRoot, adapters, path, key, canonical});
305
- if (peer) return peer.manifest.version ?? null;
413
+ const {entries, members} = await listedEntries(groups, {adapters, path, key, canonical});
414
+ const removed = [...owner.members.keys()].filter(group => !members.has(group));
415
+ const added = [...members.keys()].filter(group => !owner.members.has(group));
416
+ // An unchanged group must keep its complete membership. A replacement can
417
+ // be attributed only when the selected group alone disappeared and exactly
418
+ // one group appeared; never select a package just because it is first/latest.
419
+ for (const [group, before] of owner.members) {
420
+ const after = members.get(group);
421
+ if (after && (before.size !== after.size || [...before].some(pkg => !after.has(pkg)))) return null;
422
+ }
423
+ let target;
424
+ if (removed.length === 0 && added.length === 0) target = key(owner.groupRoot);
425
+ else if (owner.name === 'pnpm' && owner.listingRoot && removed.length === 1 && removed[0] === key(owner.groupRoot) && added.length === 1) target = added[0];
426
+ else return null;
427
+ const matches = entries.filter(entry => entry.pkg === owner.package && key(entry.groupRoot) === target);
428
+ if (matches.length !== 1 || (owner.name === 'pnpm' && members.get(target)?.size !== 1)) return null;
429
+ const {pkg, dependency, groupRoot, listingRoot} = matches[0];
430
+ if (listingRoot !== owner.listingRoot || (owner.from !== undefined && typeof owner.from !== 'string') || dependency.from !== owner.from ||
431
+ dependency.link === true || [dependency.resolved, dependency.version].some(value => typeof value === 'string' && LINKED.test(value))) return null;
432
+ const root = await canonical(dependency.path);
433
+ const manifest = await manifestOf(adapters, path, root);
434
+ if (manifest.name !== pkg || typeof manifest.version !== 'string' || !manifest.version ||
435
+ (dependency.version !== undefined && dependency.version !== manifest.version)) return null;
436
+ if (pkg === PI) {
437
+ if (manifest.bin?.pi !== 'dist/bundle/cli.js') return null;
438
+ const cli = await canonical(path.join(root, manifest.bin.pi));
439
+ return key(cli) === key(path.join(root, manifest.bin.pi)) ? manifest.version : null;
306
440
  }
441
+ if (manifest.version !== owner.shellVersion) return null;
442
+ const peer = await adjacentPeer({shellRoot: root, groupRoot, adapters, path, key, canonical});
443
+ return typeof peer?.manifest.version === 'string' && peer.manifest.version ? peer.manifest.version : null;
307
444
  } catch {
308
445
  return null;
309
446
  }
310
- return null;
311
447
  }
312
448
 
313
449
  export async function updateSelectedPi(input) {
@@ -318,9 +454,15 @@ export async function updateSelectedPi(input) {
318
454
  try { await input.adapters.fs.realpath(owner.spec); }
319
455
  catch { throw new Error(`gentle-shell update: the main-channel build ${owner.spec} is missing, and this unpublished build cannot be reinstalled from the registry; run 'gentle-shell upgrade --channel release' and then 'gentle-shell upgrade --channel main' to rebuild it. No installation changed.`); }
320
456
  }
457
+ const latest = await latestPublishedPi(owner, input);
458
+ const ageExclusion = owner.name === 'pnpm' ? await piAgeExclusion(owner, input, await piSiblings(owner, input, latest)) : [];
321
459
  // Exactly one approved package per command; never create a comma group or
322
- // reinstall arbitrary dependencies merely because they share a store.
323
- const args = owner.args ?? (owner.name === 'pnpm' ? ['add', '-g', owner.spec, ...(owner.package === SHELL ? ['--allow-build=gentle-pi'] : [])] : ['install', '-g', owner.spec, ...(owner.package === PI ? ['--ignore-scripts'] : [])]);
460
+ // reinstall arbitrary dependencies merely because they share a store. The
461
+ // exact global Pi version is transient, not a source manifest pin.
462
+ const spec = owner.package === PI ? `${PI}@${latest}` : owner.spec;
463
+ const args = owner.args ? owner.args.map(arg => arg === PI ? `${PI}@${latest}` : arg)
464
+ : (owner.name === 'pnpm' ? ['add', '-g', spec, ...(owner.package === SHELL ? ['--allow-build=gentle-pi'] : [])] : ['install', '-g', spec, ...(owner.package === PI ? ['--ignore-scripts'] : [])]);
465
+ args.push(...ageExclusion);
324
466
  const result = await input.adapters.run(owner.command, [...owner.prefix, ...args], {deadlineMs:20 * 60_000, cwd: owner.sourceRoot ?? input.cwd, stderrTail:4096, ...(owner.sourceEnv ? {env:owner.sourceEnv} : {})});
325
467
  if (!succeeded(result)) {
326
468
  // One sanitized line of the manager's own error: npm prints it on stderr,
@@ -328,7 +470,7 @@ export async function updateSelectedPi(input) {
328
470
  // error line in either stream wins over a stderr warning, stderr's on a tie.
329
471
  const output = [result?.stdout, result?.stderrTail].filter(text => typeof text === 'string').join('\n');
330
472
  const detail = setupErrorDetail(output, input.home, input.platform);
331
- throw new Error(`gentle-shell update: ${owner.name} (${[owner.command, ...owner.prefix].join(' ')}) could not install ${owner.spec}${detail ? `\n${detail}` : ''}`);
473
+ throw new Error(`gentle-shell update: ${owner.name} (${[owner.command, ...owner.prefix].join(' ')}) could not install ${owner.sourceRoot ? `${PI}@${latest}` : spec}${detail ? `\n${detail}` : ''}`);
332
474
  }
333
475
  if (owner.sourceRoot) {
334
476
  const {path, key} = pathsFor(input.platform ?? process.platform);
@@ -345,19 +487,16 @@ export async function updateSelectedPi(input) {
345
487
  if (peer && key(peer.cli) === key(nested)) after = peer.manifest.version ?? null;
346
488
  } catch { /* Never invent readback after a successful manager invocation. */ }
347
489
  const location = `${owner.name} updated ${PI} in ${owner.sourceRoot}`;
490
+ if (after !== null && after !== latest) throw new Error(`gentle-shell update: ${owner.name} supplied Pi ${after}, not the latest published Pi ${latest}; inspect the source checkout before retrying.`);
348
491
  if (after === null) input.out?.(`${location}. The Pi version could not be read back; run 'gentle-shell --version' to check it.`);
349
- else {
350
- input.out?.(`${location}; the selected Pi is ${after === input.currentVersion ? 'still' : 'now'} ${after}${after !== input.currentVersion && input.currentVersion !== undefined ? ` (was ${input.currentVersion})` : ''}.`);
351
- if (after === input.currentVersion && owner.name === 'pnpm') input.out?.('The declared version range and pnpm minimumReleaseAge setting still apply; neither was overridden.');
352
- }
492
+ else input.out?.(`${location}; the selected Pi is ${after === input.currentVersion ? 'still' : 'now'} ${after}${after !== input.currentVersion && input.currentVersion !== undefined ? ` (was ${input.currentVersion})` : ''}.`);
353
493
  return 0;
354
494
  }
355
495
  const after = await suppliedPiVersion(owner, input);
356
496
  const before = input.currentVersion;
357
- if (after === null) input.out?.(`${owner.name} installed ${owner.spec}. The Pi version it now supplies could not be read back; run 'gentle-shell --version' to check it.`);
358
- else if (before !== undefined && after === before) {
359
- input.out?.(`${owner.name} installed ${owner.spec}, and the selected Pi is still ${after}.`);
360
- if (owner.name === 'pnpm') input.out?.('pnpm installs only releases older than its minimumReleaseAge setting (pnpm 11 defaults to 4320 minutes); a newer Pi release is picked up once it is old enough.');
361
- } else input.out?.(`${owner.name} installed ${owner.spec}; the selected Pi is now ${after}${before !== undefined ? ` (was ${before})` : ''}.`);
497
+ if (after !== null && after !== latest) throw new Error(`gentle-shell update: ${owner.name} supplied Pi ${after}, not the latest published Pi ${latest}; inspect the installation before retrying.`);
498
+ if (after === null) input.out?.(`${owner.name} installed ${spec}. The Pi version it now supplies could not be read back; run 'gentle-shell --version' to check it.`);
499
+ else if (before !== undefined && after === before) input.out?.(`${owner.name} installed ${spec}, and the selected Pi is still ${after}.`);
500
+ else input.out?.(`${owner.name} installed ${spec}; the selected Pi is now ${after}${before !== undefined ? ` (was ${before})` : ''}.`);
362
501
  return 0;
363
502
  }
@@ -0,0 +1,107 @@
1
+ #!/usr/bin/env node
2
+ // Offline, single-root Git preparation. Never runs probes or removes failed scratch.
3
+ import { execFileSync } from "node:child_process";
4
+ import { createHash } from "node:crypto";
5
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, statfsSync, writeFileSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
7
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
8
+
9
+ const started = performance.now(), MAX_BYTES = 256 * 1024 * 1024, MAX_FILES = 20_000, MAX_MS = 60_000;
10
+ let plan, scratch, payloadBytes = 0;
11
+ const fail = reason => { throw new Error(reason); };
12
+ const hash = bytes => createHash("sha256").update(bytes).digest("hex");
13
+ const inside = (root, path) => { const rel = relative(root, path); return rel !== "" && !isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`); };
14
+ const remaining = () => { const ms = MAX_MS - (performance.now() - started); if (ms <= 0) fail("preparation deadline exceeded (60000ms)"); return Math.ceil(ms); };
15
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.toUpperCase().startsWith("GIT_")));
16
+ Object.assign(env, { GIT_CONFIG_GLOBAL: process.platform === "win32" ? "NUL" : "/dev/null", GIT_CONFIG_NOSYSTEM: "1", GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0", GIT_ALLOW_PROTOCOL: "file", GIT_NO_LAZY_FETCH: "1", GIT_NO_REPLACE_OBJECTS: "1" });
17
+ const git = (cwd, args, input, encoding = "utf8", maxBuffer = 16 * 1024 * 1024) => execFileSync("git", ["-c", "core.hooksPath=", "-c", "core.fsmonitor=false", "-c", "core.autocrlf=false", ...args], {
18
+ cwd, env, input, encoding, timeout: remaining(), maxBuffer, stdio: ["pipe", "pipe", "pipe"], windowsHide: true,
19
+ });
20
+ const names = text => text.split("\0").filter(Boolean);
21
+ const statAt = path => { try { return lstatSync(path); } catch (error) { if (error.code === "ENOENT") return undefined; throw error; } };
22
+
23
+ try {
24
+ const [sourceArg, scratchArg, planArg, ...extra] = process.argv.slice(2);
25
+ plan = JSON.parse(planArg);
26
+ if (extra.length || !plan || !Array.isArray(plan.include) || !Array.isArray(plan.checks) || !plan.checks.length ||
27
+ !plan.checks.every(command => typeof command === "string" && command.trim()) ||
28
+ (plan.runtimeArtifacts !== undefined && !Array.isArray(plan.runtimeArtifacts)) ||
29
+ Object.keys(plan).some(key => !["include", "checks", "baseline", "runtimeArtifacts"].includes(key))) fail("expected source, fresh scratch, and {include, checks, baseline?, runtimeArtifacts?} plan");
30
+ const source = realpathSync(sourceArg);
31
+ scratch = realpathSync(scratchArg);
32
+ const scratchPath = scratchArg.replace(process.platform === "win32" ? /[\\/]+$/ : /\/+$/, "");
33
+ const scratchStat = lstatSync(scratchPath);
34
+ if (scratchStat.isSymbolicLink() || !scratchStat.isDirectory() || !inside(realpathSync(tmpdir()), scratch) || inside(source, scratch) || inside(scratch, source) || source === scratch || readdirSync(scratch).length) fail("scratch must be an empty real directory under system temp, outside source");
35
+ if (!lstatSync(join(source, ".git")).isDirectory() || lstatSync(join(source, ".git")).isSymbolicLink() ||
36
+ realpathSync(git(source, ["rev-parse", "--show-toplevel"]).trim()) !== source ||
37
+ resolve(source, git(source, ["rev-parse", "--git-common-dir"]).trim()) !== join(source, ".git")) fail("unsupported repository: ordinary single-root Git directory required");
38
+ const head = git(source, ["rev-parse", "--verify", "HEAD^{commit}"]).trim();
39
+ const config = git(source, ["config", "--local", "--list"]);
40
+ if (existsSync(join(source, ".git", "shallow")) || existsSync(join(source, ".git", "objects", "info", "alternates")) ||
41
+ /^(core\.sparsecheckout=true|extensions\.partialclone=|remote\..*\.promisor=true)/mi.test(config) || git(source, ["for-each-ref", "--format=%(refname)", "refs/replace"]).trim()) fail("unsupported shallow, shared, sparse, partial or replaced Git history");
42
+ if (plan.baseline !== undefined && (typeof plan.baseline !== "string" || !/^[a-f0-9]{40,64}$/.test(plan.baseline))) fail("baseline must be a full commit object ID");
43
+ const indexPath = join(source, ".git", "index"), indexHash = hash(readFileSync(indexPath));
44
+ const staged = git(source, ["ls-files", "--stage", "-z"]);
45
+ if (names(staged).some(entry => !/^100(644|755) [a-f0-9]+ 0\t/.test(entry))) fail("unsupported index: links, submodules or conflicts");
46
+ if (names(git(source, ["ls-files", "-v", "-z"])).some(entry => !entry.startsWith("H "))) fail("unsupported index flags: sparse or assume-unchanged entries");
47
+ const tracked = names(git(source, ["ls-files", "-z"]));
48
+ const files = new Map(), missing = [], excludedRuntimeArtifacts = [];
49
+ function resolveInput(path) {
50
+ remaining();
51
+ if (typeof path !== "string" || !path || path.includes("\\") || path.split("/").some(part => !part || part === "." || part === ".." || part.toLowerCase() === ".git") || isAbsolute(path)) fail("unsupported input path: use literal repository-relative paths outside .git");
52
+ const absolute = join(source, path);
53
+ if (!inside(source, absolute)) fail("unsupported input outside repository");
54
+ // Check each ancestor before following directories, including dependency junctions.
55
+ for (let current = absolute; current !== source; current = dirname(current)) {
56
+ if (statAt(current)?.isSymbolicLink()) fail("unsupported linked input; provide an independent regular-file dependency payload");
57
+ }
58
+ return absolute;
59
+ }
60
+ function collect(path, required) {
61
+ const absolute = resolveInput(path), stat = statAt(absolute);
62
+ if (!stat) { if (required) fail(`required input missing: ${path}`); missing.push(path); return; }
63
+ if (stat.isDirectory()) {
64
+ if (!required) fail("unsupported tracked file replaced by directory; no implicit untracked expansion");
65
+ for (const entry of readdirSync(absolute)) collect(`${path}/${entry}`, true);
66
+ return;
67
+ }
68
+ if (!stat.isFile()) fail(`unsupported required runtime artifact: ${path}`);
69
+ if (files.has(path)) return;
70
+ payloadBytes += stat.size;
71
+ if (files.size >= MAX_FILES || payloadBytes > MAX_BYTES) fail("payload exceeds preparation limit (20000 files / 256MiB); narrow the complete required payload");
72
+ files.set(path, { absolute, mode: stat.mode, digest: hash(readFileSync(absolute)) });
73
+ }
74
+ for (const path of tracked) collect(path, false);
75
+ for (const path of plan.include) collect(path, true);
76
+ for (const path of plan.runtimeArtifacts ?? []) {
77
+ const stat = statAt(resolveInput(path));
78
+ if (!stat || stat.isFile() || stat.isDirectory()) fail(`runtime artifact must name an existing non-regular input: ${path}`);
79
+ excludedRuntimeArtifacts.push(path);
80
+ }
81
+ const capacity = statfsSync(scratch);
82
+ if (Number(capacity.bavail) * Number(capacity.bsize) < payloadBytes || (Number(capacity.ffree) > 0 && Number(capacity.ffree) < files.size)) fail("insufficient scratch capacity for required regular-file payload");
83
+ const work = join(scratch, "work");
84
+ // --no-local transfers reachable Git objects instead of sharing objects or copying config/hooks.
85
+ git(scratch, ["clone", "--no-local", "--no-checkout", "--template=", "--", source, work]);
86
+ if (git(work, ["rev-parse", "HEAD"]).trim() !== head) fail("source HEAD changed during preparation");
87
+ if (plan.baseline) git(work, ["cat-file", "-e", `${plan.baseline}^{commit}`]);
88
+ git(work, ["read-tree", head]);
89
+ const patch = git(source, ["diff", "--cached", "--binary", "--full-index", "--no-ext-diff", "--no-textconv", "--src-prefix=a/", "--dst-prefix=b/", head, "--"], undefined, null, 2 * MAX_BYTES);
90
+ if (patch.length) git(work, ["apply", "--cached", "--binary", "-"], patch);
91
+ for (const [path, file] of files) {
92
+ remaining();
93
+ const bytes = readFileSync(file.absolute);
94
+ if (hash(bytes) !== file.digest) fail("source input changed during preparation");
95
+ mkdirSync(dirname(join(work, path)), { recursive: true });
96
+ writeFileSync(join(work, path), bytes, { mode: file.mode });
97
+ }
98
+ if (git(work, ["ls-files", "--stage", "-z"]) !== staged || hash(readFileSync(indexPath)) !== indexHash || git(source, ["rev-parse", "HEAD"]).trim() !== head ||
99
+ [...files.values()].some(file => hash(readFileSync(file.absolute)) !== file.digest) || missing.some(path => statAt(join(source, path)))) fail("source/index changed or copied index differs; no probes permitted");
100
+ remaining();
101
+ console.log(JSON.stringify({ status: "ready", work, head, baseline: plan.baseline ?? head, fileCount: files.size, payloadBytes,
102
+ durationMs: performance.now() - started, excludedRuntimeArtifacts, probesRun: 0 }));
103
+ } catch (error) {
104
+ console.log(JSON.stringify({ status: "setup-failed", scratch, reason: error instanceof Error ? error.message : String(error),
105
+ probesRun: 0, unrunChecks: Array.isArray(plan?.checks) ? plan.checks : [], payloadBytes, durationMs: performance.now() - started }));
106
+ process.exitCode = 1;
107
+ }
@@ -1,11 +1,17 @@
1
1
  #!/usr/bin/env node
2
- // Regenerates assets/migrations/agent-body-history.json: the sha256 of every
3
- // body (text after the frontmatter) each packaged agent has had in git
4
- // history. Installation uses it to keep refreshing package agents whose
5
- // frontmatter was edited locally. Run after changing any assets/agents file.
2
+ // Updates assets/migrations/agent-body-history.json: the sha256 of every body
3
+ // (text after the frontmatter) each packaged agent has shipped with.
4
+ // Installation uses it to keep refreshing package agents whose frontmatter was
5
+ // edited locally. Run after changing any assets/agents file.
6
+ //
7
+ // The file is append-only. Git history from HEAD is not a complete record of
8
+ // shipped bodies: a squash merge leaves the bodies of the branch's own commits
9
+ // unreachable (#2970 recorded bodies from commits that only exist on its
10
+ // branch), yet an installation may still carry one. Recorded hashes are
11
+ // therefore always kept and only new bodies are added.
6
12
  import { execFileSync } from "node:child_process";
7
13
  import { createHash } from "node:crypto";
8
- import { readdirSync, readFileSync, writeFileSync } from "node:fs";
14
+ import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
9
15
  import { dirname, join } from "node:path";
10
16
  import { fileURLToPath } from "node:url";
11
17
 
@@ -23,7 +29,33 @@ function agentBody(content) {
23
29
  const hash = (content) => createHash("sha256").update(agentBody(content)).digest("hex");
24
30
  const git = (...args) => execFileSync("git", args, { cwd: root, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
25
31
 
26
- const bodies = {};
32
+ // An existing file that cannot be read as a history must stop the run: writing
33
+ // over it would lose every recorded hash.
34
+ function readRecorded() {
35
+ if (!existsSync(output)) return {};
36
+ const parsed = JSON.parse(readFileSync(output, "utf8"));
37
+ const bodies = parsed?.bodies;
38
+ if (
39
+ parsed?.schemaVersion !== 1 ||
40
+ typeof bodies !== "object" ||
41
+ bodies === null ||
42
+ Array.isArray(bodies) ||
43
+ !Object.values(bodies).every((hashes) => Array.isArray(hashes) && hashes.every((h) => typeof h === "string"))
44
+ ) {
45
+ throw new Error("unexpected shape (schemaVersion 1 with string arrays under bodies)");
46
+ }
47
+ return bodies;
48
+ }
49
+
50
+ let recorded;
51
+ try {
52
+ recorded = readRecorded();
53
+ } catch (error) {
54
+ console.error(`cannot read ${output}: ${error.message}; not rewriting it`);
55
+ process.exit(1);
56
+ }
57
+
58
+ const found = {};
27
59
  for (const file of readdirSync(agentsDir).filter((name) => name.endsWith(".md")).sort()) {
28
60
  const path = `assets/agents/${file}`;
29
61
  const hashes = new Set([hash(readFileSync(join(agentsDir, file), "utf8"))]);
@@ -34,8 +66,23 @@ for (const file of readdirSync(agentsDir).filter((name) => name.endsWith(".md"))
34
66
  if (git("ls-tree", commit, "--", path).trim() === "") continue;
35
67
  hashes.add(hash(git("show", `${commit}:${path}`)));
36
68
  }
37
- bodies[`agents/${file}`] = [...hashes].sort();
69
+ found[`agents/${file}`] = hashes;
70
+ }
71
+
72
+ const bodies = {};
73
+ let kept = 0;
74
+ let added = 0;
75
+ let notInHistory = 0;
76
+ for (const key of [...new Set([...Object.keys(recorded), ...Object.keys(found)])].sort()) {
77
+ const known = new Set(recorded[key] ?? []);
78
+ const fromHistory = found[key] ?? new Set();
79
+ kept += known.size;
80
+ for (const h of known) if (!fromHistory.has(h)) notInHistory++;
81
+ for (const h of fromHistory) if (!known.has(h)) added++;
82
+ bodies[key] = [...new Set([...known, ...fromHistory])].sort();
38
83
  }
39
84
 
40
85
  writeFileSync(output, `${JSON.stringify({ schemaVersion: 1, bodies }, null, 2)}\n`);
41
- console.log(`agent body history: ${Object.values(bodies).flat().length} hashes for ${Object.keys(bodies).length} agents`);
86
+ console.log(
87
+ `agent body history: ${Object.values(bodies).flat().length} hashes for ${Object.keys(bodies).length} agents (kept ${kept}, added ${added}, kept although not in git history ${notInHistory})`,
88
+ );