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
@@ -1,16 +1,34 @@
1
1
  import assert from "node:assert/strict";
2
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";
2
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, utimesSync, watch, writeFileSync } from "node:fs";
3
3
  import { request as httpRequest } from "node:http";
4
4
  import { tmpdir } from "node:os";
5
5
  import { join } from "node:path";
6
6
  import type { TestContext } from "node:test";
7
7
  import test from "node:test";
8
8
  import { fileURLToPath } from "node:url";
9
- import { designCommentBatchContent, designCommentContent, formatDesignComment, formatDesignCommentBatch, startDesignCanvasServer, type DesignCanvasServerOptions, type DesignComment } from "../lib/design-canvas-server.ts";
9
+ import { DESIGN_CANVAS_ASSETS } from "../lib/design-canvas-assets.ts";
10
+ import { designCommentBatchContent, designCommentContent, describeWatchFailure, formatDesignComment, formatDesignCommentBatch, startDesignCanvasServer, type DesignCanvasServerOptions, type DesignComment, type DesignImplementPartRequest } from "../lib/design-canvas-server.ts";
10
11
 
11
12
  const TOKEN = "test-token-0123456789abcdef";
12
13
  const ASSET_DIR = fileURLToPath(new URL("../assets/design-canvas/", import.meta.url));
13
14
 
15
+ // gentle-shell#3156: when the host's inotify limit is exhausted, fs.watch cannot register and the
16
+ // server's change events never fire; the server now says so per stream, and the tests that wait
17
+ // for those events skip naming the environment instead of failing like a canvas regression.
18
+ function probeFsWatch(): boolean {
19
+ const dir = mkdtempSync(join(tmpdir(), "fs-watch-probe-"));
20
+ try {
21
+ watch(dir, { persistent: false }, () => {}).close();
22
+ return true;
23
+ } catch {
24
+ return false;
25
+ } finally {
26
+ rmSync(dir, { recursive: true, force: true });
27
+ }
28
+ }
29
+ const FS_WATCH_AVAILABLE = probeFsWatch();
30
+ const FS_WATCH_SKIP = "fs.watch unavailable: inotify watch limit exhausted (ENOSPC); canvas change events cannot be observed on this host";
31
+
14
32
  type Reply = { status: number; headers: Record<string, string | string[] | undefined>; body: string; bytes: Buffer };
15
33
  type Options = { method?: string; headers?: Record<string, string>; body?: string; host?: string | null };
16
34
 
@@ -74,21 +92,25 @@ function fixture(t: TestContext) {
74
92
  return { root, outside };
75
93
  }
76
94
 
77
- async function start(t: TestContext, extra: { initialSlug?: string; onImplement?: DesignCanvasServerOptions["onImplement"] } = {}) {
95
+ async function start(t: TestContext, extra: { initialSlug?: string; onComment?: DesignCanvasServerOptions["onComment"]; onImplement?: DesignCanvasServerOptions["onImplement"]; onVariant?: DesignCanvasServerOptions["onVariant"]; onImplementPart?: DesignCanvasServerOptions["onImplementPart"] } = {}) {
78
96
  const { root } = fixture(t);
79
97
  const comments: DesignComment[] = [];
80
98
  const batches: DesignComment[][] = [];
81
99
  const implements_: Array<{ slug: string; file: string }> = [];
100
+ const variants: Array<{ slug: string; file: string; instruction: string }> = [];
101
+ const parts: DesignImplementPartRequest[] = [];
82
102
  const server = await startDesignCanvasServer({
83
103
  designRoot: root,
84
104
  onComment: (comment) => { comments.push(comment); },
85
105
  onComments: (batch) => { batches.push(batch); },
86
106
  onImplement: (request) => { implements_.push(request); },
107
+ onVariant: (request) => { variants.push(request); },
108
+ onImplementPart: (request) => { parts.push(request); },
87
109
  randomToken: () => TOKEN,
88
110
  ...extra,
89
111
  });
90
112
  t.after(() => server.close());
91
- return { server, root, comments, batches, implements: implements_, port: server.port, base: `/${TOKEN}/` };
113
+ return { server, root, comments, batches, implements: implements_, variants, parts, port: server.port, base: `/${TOKEN}/` };
92
114
  }
93
115
 
94
116
  test("start returns a loopback URL with a random base64url token by default", async (t) => {
@@ -140,6 +162,10 @@ test("sandboxed artboards load their subresources with Origin null, but nothing
140
162
  }
141
163
  assert.equal((await rawRequest(port, `${base}assets/inspector.js`, { headers: { Origin: "http://evil.example" } })).status, 403);
142
164
  assert.equal((await rawRequest(port, `${base}files/alpha/01-hero.html`, { headers: { Origin: "http://evil.example" } })).status, 403);
165
+ // Every canvas asset behaves like canvas.js at the Origin gate; only inspector.js runs inside the sandbox.
166
+ for (const name of Object.keys(DESIGN_CANVAS_ASSETS)) {
167
+ assert.equal((await rawRequest(port, `${base}assets/${name}`, nullOrigin)).status, name === "inspector.js" ? 200 : 403, name);
168
+ }
143
169
  });
144
170
 
145
171
  test("the canvas page carries a strict CSP and a JSON config, never inline code", async (t) => {
@@ -154,11 +180,11 @@ test("the canvas page carries a strict CSP and a JSON config, never inline code"
154
180
  assert.ok(!csp.includes("unsafe-inline") && !csp.includes("unsafe-eval"));
155
181
  const config = /<script id="gd-config" type="application\/json">([^<]*)<\/script>/.exec(page.body);
156
182
  assert.ok(config, "config script present");
157
- assert.deepEqual(JSON.parse(config[1]), { base, slug: null });
183
+ assert.deepEqual(JSON.parse(config[1]), { base, slug: null, delivery: { comment: true, batch: true, implement: true, variant: true, part: true } });
158
184
  assert.ok(page.body.includes(`src="${base}assets/canvas.js"`));
159
185
  const slugPage = await rawRequest(port, `${base}d/alpha/`);
160
186
  assert.equal(slugPage.status, 200);
161
- assert.deepEqual(JSON.parse(/<script id="gd-config" type="application\/json">([^<]*)<\/script>/.exec(slugPage.body)![1]), { base, slug: "alpha" });
187
+ assert.deepEqual(JSON.parse(/<script id="gd-config" type="application\/json">([^<]*)<\/script>/.exec(slugPage.body)![1]), { base, slug: "alpha", delivery: { comment: true, batch: true, implement: true, variant: true, part: true } });
162
188
  assert.equal((await rawRequest(port, `${base}d/Bad_Slug/`)).status, 404);
163
189
  assert.equal((await rawRequest(port, `${base}d/alpha/extra`)).status, 404);
164
190
  assert.equal((await rawRequest(port, base, { method: "POST" })).status, 405);
@@ -175,6 +201,12 @@ test("only the fixed canvas assets are served", async (t) => {
175
201
  for (const name of ["index.html", "missing.js", "..%2Fpackage.json", "%2e%2e", "canvas.js/x"]) {
176
202
  assert.equal((await rawRequest(port, `${base}assets/${name}`)).status, 404, name);
177
203
  }
204
+ for (const [name, type] of Object.entries(DESIGN_CANVAS_ASSETS)) {
205
+ const asset = await rawRequest(port, `${base}assets/${name}`);
206
+ assert.equal(asset.status, 200, name);
207
+ assert.equal(asset.headers["content-type"], type, name);
208
+ assert.deepEqual(asset.bytes, readFileSync(join(ASSET_DIR, name)), `${name} is served byte for byte`);
209
+ }
178
210
  });
179
211
 
180
212
  test("designs are listed from design.json manifests, most recent first", async (t) => {
@@ -497,6 +529,34 @@ test("an excerpt of astral characters is truncated to the store limit without a
497
529
  assert.ok(second.isWellFormed());
498
530
  });
499
531
 
532
+ // S5: the agent's resolution reaches the canvas through the comments route.
533
+
534
+ test("S5: the comments route lists a comment's resolution, the status route clears it on reopen, and a malformed one is a 422", async (t) => {
535
+ const { port, root, base } = await start(t);
536
+ await postComment(port, { ...VALID, mode: "collect" });
537
+ await postComment(port, { ...VALID, mode: "collect" });
538
+ const path = join(root, "alpha", "comments.json");
539
+ const document = JSON.parse(readFileSync(path, "utf8"));
540
+ document.comments[0].status = "resolved";
541
+ document.comments[0].resolvedAt = "2026-10-28T10:00:00.000Z";
542
+ document.comments[0].resolution = "Made the title 32px.";
543
+ writeFileSync(path, JSON.stringify(document));
544
+ const listed = JSON.parse((await rawRequest(port, `${base}api/designs/alpha/comments`)).body).comments;
545
+ assert.equal(listed[0].resolution, "Made the title 32px.");
546
+ assert.equal("resolution" in listed[1], false);
547
+ const id = document.comments[0].id;
548
+ const reopened = await postJson(port, `api/designs/alpha/comments/${id}/status`, { status: "open" });
549
+ assert.equal(reopened.status, 200);
550
+ assert.equal("resolution" in JSON.parse(reopened.body).comment, false);
551
+ assert.equal("resolution" in storedComments(root)[0], false);
552
+ document.comments[1].resolution = 7;
553
+ writeFileSync(path, JSON.stringify(document));
554
+ const broken = await rawRequest(port, `${base}api/designs/alpha/comments`);
555
+ assert.equal(broken.status, 422);
556
+ assert.equal(JSON.parse(broken.body).error, "invalid-comments");
557
+ assert.match(JSON.parse(broken.body).reason, /resolution/);
558
+ });
559
+
500
560
  test("the status route resolves and reopens one comment", async (t) => {
501
561
  const { port, root } = await start(t);
502
562
  await postComment(port, { ...VALID, mode: "collect" });
@@ -563,7 +623,8 @@ function openEvents(port: number) {
563
623
  });
564
624
  req.end();
565
625
  // A waiter that never matches must fail loud, not hang the whole suite:
566
- // an exhausted inotify limit silently stops the server's change events.
626
+ // an exhausted inotify limit stops the server's change events, and the fs.watch
627
+ // preflight above skips these tests naming that environment when it cannot register.
567
628
  const waitFor = (pattern: RegExp) => new Promise<RegExpExecArray>((resolve, reject) => {
568
629
  const timeout = setTimeout(() => reject(new Error(`events never matched ${pattern} within 5s; got: ${JSON.stringify(buffer.slice(-200))}`)), 5000);
569
630
  const settle = (match: RegExpExecArray) => { clearTimeout(timeout); resolve(match); };
@@ -574,6 +635,7 @@ function openEvents(port: number) {
574
635
  }
575
636
 
576
637
  test("events stream a debounced change after an artboard write", async (t) => {
638
+ if (!FS_WATCH_AVAILABLE) return t.skip(FS_WATCH_SKIP);
577
639
  const { port, root } = await start(t);
578
640
  const events = openEvents(port);
579
641
  t.after(() => events.req.destroy());
@@ -629,6 +691,7 @@ test("show() tells every connected page which design to show, or the system-only
629
691
  });
630
692
 
631
693
  test("events stream a change when comments.json is written", async (t) => {
694
+ if (!FS_WATCH_AVAILABLE) return t.skip(FS_WATCH_SKIP);
632
695
  const { port } = await start(t);
633
696
  const events = openEvents(port);
634
697
  t.after(() => events.req.destroy());
@@ -704,6 +767,7 @@ test("the system routes keep the Host, token, Origin and method rules", async (t
704
767
  });
705
768
 
706
769
  test("events stream a change when system.html or system.md is written", async (t) => {
770
+ if (!FS_WATCH_AVAILABLE) return t.skip(FS_WATCH_SKIP);
707
771
  const { port, root } = await start(t);
708
772
  const events = openEvents(port);
709
773
  t.after(() => events.req.destroy());
@@ -763,6 +827,399 @@ test("implement is 501 without onImplement and 500 when it throws", async (t) =>
763
827
  assert.equal((await rawRequest(failing.port, `/${TOKEN}/api/designs`)).status, 200, "the server survives");
764
828
  });
765
829
 
830
+ // T2/S3: "Try another direction from this…" posts to api/designs/<slug>/variant.
831
+
832
+ const VARIANT = "api/designs/alpha/variant";
833
+
834
+ test("T2/S3: variant delivers exactly one request with the source file and the instruction, and answers 202", async (t) => {
835
+ const { port, variants } = await start(t);
836
+ const ok = await postJson(port, VARIANT, { file: "01-hero.html", instruction: " More compact\r\nfor phones " });
837
+ assert.equal(ok.status, 202);
838
+ assert.deepEqual(JSON.parse(ok.body), { ok: true, slug: "alpha", file: "01-hero.html", queued: false });
839
+ assert.deepEqual(variants, [{ slug: "alpha", file: "01-hero.html", instruction: "More compact\nfor phones" }], "trimmed, with LF line ends");
840
+ const edge = await postJson(port, VARIANT, { file: "02-bare.html", instruction: "x".repeat(2000) });
841
+ assert.equal(edge.status, 202, "2000 characters are allowed");
842
+ assert.equal(variants.length, 2);
843
+ assert.equal(variants[1].instruction.length, 2000);
844
+ });
845
+
846
+ test("T2/S3: variant refuses an empty or over-long instruction, a file outside the manifest and a bad design, delivering nothing", async (t) => {
847
+ const { port, root, variants } = await start(t);
848
+ for (const instruction of ["", " \n ", "x".repeat(2001), ` ${"x".repeat(2001)} `, 7, null, ["a"], undefined]) {
849
+ const reply = await postJson(port, VARIANT, { file: "01-hero.html", instruction });
850
+ assert.equal(reply.status, 400, JSON.stringify(instruction)?.slice(0, 20));
851
+ assert.equal(JSON.parse(reply.body).error, "invalid-instruction");
852
+ }
853
+ // sub/inner.html exists but is not an artboard of the manifest.
854
+ for (const file of ["sub/inner.html", "missing.html", "../beta/01-a.html", "styles.css", "alias.html", 7, "", undefined]) {
855
+ const reply = await postJson(port, VARIANT, { file, instruction: "Bolder" });
856
+ assert.equal(reply.status, 400, String(file));
857
+ assert.equal(JSON.parse(reply.body).error, "invalid-file");
858
+ }
859
+ assert.equal((await postJson(port, "api/designs/missing/variant", { file: "01-hero.html", instruction: "Bolder" })).status, 404);
860
+ assert.equal((await postJson(port, "api/designs/broken/variant", { file: "01-a.html", instruction: "Bolder" })).status, 422);
861
+ assert.equal((await postJson(port, "api/designs/Alpha/variant", { file: "01-hero.html", instruction: "Bolder" })).status, 404);
862
+ assert.equal((await postJson(port, "api/designs/Not_A_Slug/variant", { file: "01-a.html", instruction: "Bolder" })).status, 404);
863
+ assert.equal((await postJson(port, "api/designs/..%2Falpha/variant", { file: "01-hero.html", instruction: "Bolder" })).status, 404);
864
+ assert.equal(variants.length, 0, "no refused request reaches onVariant");
865
+ assert.equal(existsSync(join(root, "alpha", "handoffs.json")), false, "a variant is not a handoff: nothing is written");
866
+ });
867
+
868
+ test("T2/S3: the variant route keeps the Host, token, Origin, content-type, JSON, size and method rules", async (t) => {
869
+ const { port, variants } = await start(t);
870
+ const path = `/${TOKEN}/${VARIANT}`;
871
+ const body = JSON.stringify({ file: "01-hero.html", instruction: "Bolder" });
872
+ const own = { Origin: `http://127.0.0.1:${port}`, "Content-Type": "application/json" };
873
+ assert.equal((await rawRequest(port, path, { method: "POST", headers: { "Content-Type": "application/json" }, body })).status, 403, "no Origin");
874
+ for (const origin of ["http://evil.example", "null", `http://localhost:${port + 1}`]) {
875
+ assert.equal((await rawRequest(port, path, { method: "POST", headers: { ...own, Origin: origin }, body })).status, 403, origin);
876
+ }
877
+ assert.equal((await rawRequest(port, path, { method: "POST", headers: { ...own, "Content-Type": "text/plain" }, body })).status, 415);
878
+ assert.equal((await rawRequest(port, path, { method: "POST", headers: { "Origin": own.Origin }, body })).status, 415, "no content type");
879
+ assert.equal((await rawRequest(port, `/wrong-token-0123456789/${VARIANT}`, { method: "POST", headers: own, body })).status, 404, "wrong token");
880
+ assert.equal((await rawRequest(port, `/${VARIANT}`, { method: "POST", headers: own, body })).status, 404, "missing token");
881
+ assert.equal((await rawRequest(port, path, { method: "POST", headers: own, body, host: `evil.example:${port}` })).status, 421);
882
+ for (const text of ["not json", "[1]", "null", "\"x\""]) {
883
+ const reply = await rawRequest(port, path, { method: "POST", headers: own, body: text });
884
+ assert.equal(reply.status, 400, text);
885
+ }
886
+ assert.equal(JSON.parse((await rawRequest(port, path, { method: "POST", headers: own, body: "not json" })).body).error, "invalid-json");
887
+ assert.equal((await rawRequest(port, path, { method: "POST", headers: own, body: JSON.stringify({ file: "01-hero.html", instruction: "x".repeat(17 * 1024) }) })).status, 413);
888
+ assert.equal((await rawRequest(port, path)).status, 405);
889
+ assert.equal((await rawRequest(port, path, { method: "PUT", headers: own, body })).status, 405);
890
+ assert.equal(variants.length, 0, "nothing refused reaches onVariant");
891
+ assert.equal((await rawRequest(port, path, { method: "POST", headers: { ...own, Origin: `http://localhost:${port}` }, body })).status, 202);
892
+ assert.equal(variants.length, 1);
893
+ });
894
+
895
+ test("T2/S3: variant answers queued from the delivery, 501 without onVariant and 500 when it throws", async (t) => {
896
+ const { root } = fixture(t);
897
+ const request = { file: "01-hero.html", instruction: "Bolder" };
898
+ const bare = await startDesignCanvasServer({ designRoot: root, onComment: () => {}, onImplement: () => {}, randomToken: () => TOKEN });
899
+ t.after(() => bare.close());
900
+ const none = await postJson(bare.port, VARIANT, request);
901
+ assert.equal(none.status, 501);
902
+ assert.deepEqual(JSON.parse(none.body), { error: "variant-unavailable" });
903
+
904
+ const states = [{ queued: true }, { queued: false }, undefined];
905
+ const seen: unknown[] = [];
906
+ const queueing = await startDesignCanvasServer({ designRoot: root, onComment: () => {}, onVariant: async (call) => { seen.push(call); return states[seen.length - 1]; }, randomToken: () => TOKEN });
907
+ t.after(() => queueing.close());
908
+ assert.equal(JSON.parse((await postJson(queueing.port, VARIANT, request)).body).queued, true);
909
+ assert.equal(JSON.parse((await postJson(queueing.port, VARIANT, request)).body).queued, false);
910
+ assert.equal(JSON.parse((await postJson(queueing.port, VARIANT, request)).body).queued, false, "no answer means not queued");
911
+
912
+ const failing = await startDesignCanvasServer({ designRoot: root, onComment: () => {}, onVariant: () => { throw new Error("boom"); }, randomToken: () => TOKEN });
913
+ t.after(() => failing.close());
914
+ const reply = await postJson(failing.port, VARIANT, request);
915
+ assert.equal(reply.status, 500);
916
+ assert.deepEqual(JSON.parse(reply.body), { error: "delivery-failed", slug: "alpha", file: "01-hero.html", reason: "boom" });
917
+ assert.equal((await rawRequest(failing.port, `/${TOKEN}/api/designs`)).status, 200, "the server survives");
918
+ });
919
+
920
+ // canvas-trim S4: Mix is gone; its former route is an unknown path like any other.
921
+
922
+ test("canvas-trim S4: POST to the former mix route answers 404 not-found like an unknown route and reaches no session callback", async (t) => {
923
+ const { port, comments, batches, implements: implemented, variants, parts } = await start(t);
924
+ const body = { base: "01-hero.html", picks: [{ file: "02-bare.html", selector: "body > h1", excerpt: "Bare", note: "" }] };
925
+ const former = await postJson(port, "api/designs/alpha/mix", body);
926
+ const unknown = await postJson(port, "api/designs/alpha/no-such-route", body);
927
+ assert.equal(former.status, 404);
928
+ assert.deepEqual(JSON.parse(former.body), { error: "not-found" });
929
+ assert.deepEqual([former.status, former.body], [unknown.status, unknown.body], "the same answer as an unknown route");
930
+ assert.equal((await rawRequest(port, `/${TOKEN}/api/designs/alpha/mix`)).status, 404, "no method makes it a known route");
931
+ assert.deepEqual([comments, batches, implemented, variants, parts].map((calls) => calls.length), [0, 0, 0, 0, 0], "no session callback is called");
932
+ });
933
+
934
+ // canvas-implement-part S2, S4: "Implement only this" hands one element of an artboard to the session, recorded in
935
+ // design/<slug>/parts.json before delivery; handoffs.json and the chosen artboard stay as they are.
936
+ const PARTS = "api/designs/alpha/implement-part";
937
+ const PARTS_LIST = "api/designs/alpha/parts";
938
+ const SIDE = { file: "02-bare.html", selector: " nav.side\n > ul ", excerpt: " Home\n Tours ", note: " solo el menú\r\nsin la cabecera " };
939
+
940
+ test("implement-part S4: Implement only this records the part, delivers it once with its id, answers 202, and leaves handoffs.json alone", async (t) => {
941
+ const { port, root, parts } = await start(t);
942
+ const reply = await postJson(port, PARTS, SIDE);
943
+ assert.equal(reply.status, 202);
944
+ const body = JSON.parse(reply.body);
945
+ assert.deepEqual(Object.keys(body), ["ok", "id", "queued"]);
946
+ assert.equal(body.ok, true);
947
+ assert.equal(body.queued, false);
948
+ assert.match(body.id, /^[a-z0-9]{1,32}$/);
949
+ const onDisk = JSON.parse(readFileSync(join(root, "alpha", "parts.json"), "utf8"));
950
+ assert.equal(onDisk.parts.length, 1);
951
+ const [part] = onDisk.parts;
952
+ assert.deepEqual({ ...part, sentAt: "t" }, { id: body.id, file: "02-bare.html", selector: "nav.side > ul", excerpt: "Home Tours", instruction: "solo el menú\nsin la cabecera", status: "sent", queued: false, sentAt: "t", startedAt: null, implementedAt: null }, "selector and excerpt collapsed, the note trimmed with LF line ends");
953
+ assert.deepEqual(parts, [{ slug: "alpha", part }], "the session gets exactly the recorded part");
954
+ assert.equal(existsSync(join(root, "alpha", "handoffs.json")), false, "no direction is chosen");
955
+ const listed = await rawRequest(port, `/${TOKEN}/${PARTS_LIST}`);
956
+ assert.equal(listed.status, 200);
957
+ assert.deepEqual(JSON.parse(listed.body), onDisk);
958
+ const bare = await postJson(port, PARTS, { file: "01-hero.html", selector: "h1" });
959
+ assert.equal(bare.status, 202, "excerpt and note are optional");
960
+ assert.equal(JSON.parse(readFileSync(join(root, "alpha", "parts.json"), "utf8")).parts[1].instruction, undefined);
961
+ });
962
+
963
+ test("implement-part S4: the route takes a selector of 500 and a note of 2000 characters and cuts the excerpt to 300 (canvas-trim S6)", async (t) => {
964
+ const { port, parts } = await start(t);
965
+ const reply = await postJson(port, PARTS, { file: "02-bare.html", selector: "s".repeat(500), excerpt: "e".repeat(400), note: "n".repeat(2000) });
966
+ assert.equal(reply.status, 202);
967
+ assert.equal(parts.length, 1);
968
+ assert.equal(parts[0].part.selector.length, 500);
969
+ assert.equal(parts[0].part.excerpt.length, 300, "the excerpt is cut to its limit, like a comment's");
970
+ assert.equal(parts[0].part.instruction?.length, 2000);
971
+ });
972
+
973
+ test("implement-part S4: the route refuses a file outside the manifest and bad fields, delivering and recording nothing", async (t) => {
974
+ const { port, root, parts } = await start(t);
975
+ const refused = async (body: unknown, status: number, error: string, label: string) => {
976
+ const reply = await postJson(port, PARTS, body);
977
+ assert.equal(reply.status, status, label);
978
+ assert.equal(JSON.parse(reply.body).error, error, label);
979
+ };
980
+ for (const file of ["sub/inner.html", "missing.html", "../beta/01-a.html", "alias.html", 7, "", undefined]) await refused({ ...SIDE, file }, 400, "invalid-file", `file ${String(file)}`);
981
+ for (const selector of ["", " ", "s".repeat(501), 7, undefined]) await refused({ ...SIDE, selector }, 400, "invalid-selector", `selector ${String(selector).slice(0, 10)}`);
982
+ await refused({ ...SIDE, excerpt: 7 }, 400, "invalid-excerpt", "excerpt not text");
983
+ for (const note of ["n".repeat(2001), 7]) await refused({ ...SIDE, note }, 400, "invalid-note", `note ${String(note).slice(0, 10)}`);
984
+ assert.equal((await postJson(port, "api/designs/missing/implement-part", SIDE)).status, 404);
985
+ assert.equal((await postJson(port, "api/designs/Not_A_Slug/implement-part", SIDE)).status, 404);
986
+ assert.equal(parts.length, 0, "nothing refused reaches the session");
987
+ assert.equal(existsSync(join(root, "alpha", "parts.json")), false, "and nothing is recorded");
988
+ writeFileSync(join(root, "alpha", "parts.json"), "not json");
989
+ const broken = await postJson(port, PARTS, { file: "01-hero.html", selector: "h1" });
990
+ assert.equal(broken.status, 422);
991
+ assert.equal(JSON.parse(broken.body).error, "invalid-parts");
992
+ assert.equal(readFileSync(join(root, "alpha", "parts.json"), "utf8"), "not json", "a broken file is never overwritten");
993
+ assert.equal((await rawRequest(port, `/${TOKEN}/${PARTS_LIST}`)).status, 422);
994
+ });
995
+
996
+ test("implement-part S4: the route answers queued from the delivery, 501 without onImplementPart, and 500 when the delivery throws, taking the part back", async (t) => {
997
+ const { root } = fixture(t);
998
+ const request = { file: "01-hero.html", selector: "h1" };
999
+ const bare = await startDesignCanvasServer({ designRoot: root, onComment: () => {}, randomToken: () => TOKEN });
1000
+ t.after(() => bare.close());
1001
+ const none = await postJson(bare.port, PARTS, request);
1002
+ assert.equal(none.status, 501);
1003
+ assert.deepEqual(JSON.parse(none.body), { error: "implement-part-unavailable" });
1004
+ assert.equal(existsSync(join(root, "alpha", "parts.json")), false);
1005
+
1006
+ const queueing = await startDesignCanvasServer({ designRoot: root, onComment: () => {}, onImplementPart: () => ({ queued: true }), randomToken: () => TOKEN });
1007
+ t.after(() => queueing.close());
1008
+ const queued = await postJson(queueing.port, PARTS, request);
1009
+ assert.equal(JSON.parse(queued.body).queued, true);
1010
+ assert.equal(JSON.parse(readFileSync(join(root, "alpha", "parts.json"), "utf8")).parts[0].queued, true);
1011
+
1012
+ const failing = await startDesignCanvasServer({ designRoot: root, onComment: () => {}, onImplementPart: () => { throw new Error("session closed"); }, randomToken: () => TOKEN });
1013
+ t.after(() => failing.close());
1014
+ const reply = await postJson(failing.port, PARTS, request);
1015
+ assert.equal(reply.status, 500);
1016
+ assert.deepEqual(JSON.parse(reply.body), { error: "delivery-failed", slug: "alpha", file: "01-hero.html", reason: "session closed" });
1017
+ assert.equal(JSON.parse(readFileSync(join(root, "alpha", "parts.json"), "utf8")).parts.length, 1, "the failed part is taken back, the queued one stays");
1018
+ });
1019
+
1020
+ test("implement-part S4: the parts route keeps the Origin, content-type, JSON and method rules", async (t) => {
1021
+ const { port, parts } = await start(t);
1022
+ const path = `/${TOKEN}/${PARTS}`;
1023
+ const body = JSON.stringify({ file: "01-hero.html", selector: "h1" });
1024
+ const own = { Origin: `http://127.0.0.1:${port}`, "Content-Type": "application/json" };
1025
+ assert.equal((await rawRequest(port, path, { method: "POST", headers: { "Content-Type": "application/json" }, body })).status, 403, "no Origin");
1026
+ assert.equal((await rawRequest(port, path, { method: "POST", headers: { ...own, Origin: "http://evil.example" }, body })).status, 403);
1027
+ assert.equal((await rawRequest(port, path, { method: "POST", headers: { ...own, "Content-Type": "text/plain" }, body })).status, 415);
1028
+ assert.equal((await rawRequest(port, path, { method: "POST", headers: own, body: "not json" })).status, 400);
1029
+ assert.equal((await rawRequest(port, path, { method: "PUT", headers: own, body })).status, 405);
1030
+ assert.equal((await rawRequest(port, path)).status, 405, "the list is read from api/designs/<slug>/parts");
1031
+ assert.equal((await rawRequest(port, `/${TOKEN}/${PARTS_LIST}`, { method: "POST", headers: own, body })).status, 405, "and written only through implement-part");
1032
+ assert.equal(parts.length, 0);
1033
+ });
1034
+
1035
+ // canvas-server-data S2: "Remove" clears a part still `sent` from parts.json through the same writer; anything else is
1036
+ // refused without writing, and handoffs.json is never touched.
1037
+ const PARTS_REMOVE = "api/designs/alpha/parts/remove";
1038
+ const partsFile = (root: string) => join(root, "alpha", "parts.json");
1039
+
1040
+ test("S2: parts/remove takes out a sent part, answers 200 with its id, keeps the others and leaves handoffs.json byte for byte", async (t) => {
1041
+ const { port, root } = await start(t);
1042
+ assert.equal((await postJson(port, "api/designs/alpha/implement", { file: "01-hero.html" })).status, 202);
1043
+ const handoffs = readFileSync(join(root, "alpha", "handoffs.json"));
1044
+ const first = JSON.parse((await postJson(port, PARTS, SIDE)).body).id;
1045
+ const second = JSON.parse((await postJson(port, PARTS, { file: "01-hero.html", selector: "h1" })).body).id;
1046
+ const kept = JSON.parse(readFileSync(partsFile(root), "utf8")).parts[1];
1047
+ const reply = await postJson(port, PARTS_REMOVE, { id: first });
1048
+ assert.equal(reply.status, 200);
1049
+ assert.deepEqual(JSON.parse(reply.body), { ok: true, id: first });
1050
+ assert.equal(readFileSync(partsFile(root), "utf8"), `${JSON.stringify({ version: 1, parts: [kept] }, null, 2)}\n`);
1051
+ assert.equal(kept.id, second);
1052
+ assert.deepEqual(readFileSync(join(root, "alpha", "handoffs.json")), handoffs, "handoffs.json is never written");
1053
+ assert.deepEqual(JSON.parse((await rawRequest(port, `/${TOKEN}/${PARTS_LIST}`)).body), { version: 1, parts: [kept] });
1054
+ });
1055
+
1056
+ test("S2: parts/remove refuses a part not sent, an unknown or malformed id, a bad body, Origin or method, and a missing design, writing nothing", async (t) => {
1057
+ const { port, root } = await start(t);
1058
+ assert.equal((await postJson(port, "api/designs/alpha/implement", { file: "01-hero.html" })).status, 202);
1059
+ const at = "2026-10-31T10:00:00.000Z";
1060
+ const part = (id: string, status: string) => ({ id, file: "01-hero.html", selector: "h1", excerpt: "Hero", status, queued: false, sentAt: at, startedAt: status === "sent" ? null : at, implementedAt: status === "implemented" ? at : null });
1061
+ writeFileSync(partsFile(root), `${JSON.stringify({ version: 1, parts: [part("busy", "in_progress"), part("done", "implemented"), part("open", "sent")] }, null, 2)}\n`);
1062
+ const parts = readFileSync(partsFile(root));
1063
+ const handoffs = readFileSync(join(root, "alpha", "handoffs.json"));
1064
+ const refused = async (reply: Promise<{ status: number; body: string }>, status: number, body: unknown, label: string) => {
1065
+ const answer = await reply;
1066
+ assert.equal(answer.status, status, label);
1067
+ assert.deepEqual(JSON.parse(answer.body), body, label);
1068
+ assert.deepEqual(readFileSync(partsFile(root)), parts, `${label}: parts.json unchanged`);
1069
+ assert.deepEqual(readFileSync(join(root, "alpha", "handoffs.json")), handoffs, `${label}: handoffs.json untouched`);
1070
+ };
1071
+ await refused(postJson(port, PARTS_REMOVE, { id: "busy" }), 409, { error: "part-not-sent", reason: 'Part "busy" is in_progress, not sent; only a sent part can be removed.' }, "in progress");
1072
+ await refused(postJson(port, PARTS_REMOVE, { id: "done" }), 409, { error: "part-not-sent", reason: 'Part "done" is implemented, not sent; only a sent part can be removed.' }, "implemented");
1073
+ await refused(postJson(port, PARTS_REMOVE, { id: "nope" }), 404, { error: "not-found" }, "unknown id");
1074
+ for (const id of ["", "UPPER", "a".repeat(33), 7, undefined]) {
1075
+ await refused(postJson(port, PARTS_REMOVE, { id }), 400, { error: "invalid-part", reason: "id must be 1 to 32 lowercase letters or digits" }, `id ${String(id)}`);
1076
+ }
1077
+ await refused(postJson(port, PARTS_REMOVE, [1]), 400, { error: "invalid-body" }, "not an object");
1078
+ const path = `/${TOKEN}/${PARTS_REMOVE}`;
1079
+ const body = JSON.stringify({ id: "open" });
1080
+ const own = { Origin: `http://127.0.0.1:${port}`, "Content-Type": "application/json" };
1081
+ await refused(rawRequest(port, path, { method: "POST", headers: own, body: "not json" }), 400, { error: "invalid-json" }, "not JSON");
1082
+ await refused(rawRequest(port, path, { method: "POST", headers: { "Content-Type": "application/json" }, body }), 403, { error: "forbidden" }, "no Origin");
1083
+ await refused(rawRequest(port, path, { method: "POST", headers: { ...own, Origin: "http://evil.example" }, body }), 403, { error: "forbidden" }, "foreign Origin");
1084
+ await refused(rawRequest(port, path, { method: "POST", headers: { ...own, "Content-Type": "text/plain" }, body }), 415, { error: "unsupported-media-type" }, "not JSON content");
1085
+ await refused(rawRequest(port, path, { method: "POST", headers: own, body, host: `evil.example:${port}` }), 421, { error: "misdirected" }, "foreign Host");
1086
+ await refused(rawRequest(port, `/wrong-token-0123456789abcdef/${PARTS_REMOVE}`, { method: "POST", headers: own, body }), 404, { error: "not-found" }, "wrong token");
1087
+ const get = await rawRequest(port, path);
1088
+ assert.equal(get.headers.allow, "POST");
1089
+ await refused(Promise.resolve(get), 405, { error: "method-not-allowed" }, "GET");
1090
+ await refused(rawRequest(port, path, { method: "PUT", headers: own, body }), 405, { error: "method-not-allowed" }, "PUT");
1091
+ await refused(rawRequest(port, path, { method: "POST", headers: own, body: JSON.stringify({ id: "open", pad: "x".repeat(17 * 1024) }) }), 413, { error: "body-too-large" }, "over 16 KiB");
1092
+ await refused(postJson(port, "api/designs/missing/parts/remove", { id: "open" }), 404, { error: "not-found" }, "missing design");
1093
+ await refused(postJson(port, "api/designs/Not_A_Slug/parts/remove", { id: "open" }), 404, { error: "not-found" }, "bad slug");
1094
+ writeFileSync(partsFile(root), "not json");
1095
+ const broken = await postJson(port, PARTS_REMOVE, { id: "open" });
1096
+ assert.equal(broken.status, 422);
1097
+ assert.equal(JSON.parse(broken.body).error, "invalid-parts");
1098
+ assert.equal(readFileSync(partsFile(root), "utf8"), "not json", "a broken file is never overwritten");
1099
+ });
1100
+
1101
+ test("S2: removing a part streams one change for parts.json", async (t) => {
1102
+ if (!FS_WATCH_AVAILABLE) return t.skip(FS_WATCH_SKIP);
1103
+ const { port } = await start(t);
1104
+ const id = JSON.parse((await postJson(port, PARTS, SIDE)).body).id;
1105
+ // Let the change of that write go out before the stream opens, so only the removal can match.
1106
+ await new Promise((resolve) => setTimeout(resolve, 400));
1107
+ const events = openEvents(port);
1108
+ t.after(() => events.req.destroy());
1109
+ await events.ready;
1110
+ await events.waitFor(/: connected\n\n/);
1111
+ await new Promise((resolve) => setTimeout(resolve, 100));
1112
+ assert.equal((await postJson(port, PARTS_REMOVE, { id })).status, 200);
1113
+ await events.waitFor(/event: change\ndata: \{"slug":"alpha","file":"parts\.json"\}\n\n/);
1114
+ });
1115
+
1116
+ // canvas-server-data S9: parts.json holds at most 1 MiB, checked before the file is replaced.
1117
+ const MAX_PARTS_BYTES = 1024 * 1024;
1118
+ const CONTROL = "\u0001";
1119
+ const partsDocument = (parts: object[]) => `${JSON.stringify({ version: 1, parts }, null, 2)}\n`;
1120
+
1121
+ /** Valid sent parts whose parts.json is exactly `target` bytes, mostly control characters (six bytes each once escaped). */
1122
+ function partsOfSize(target: number): object[] {
1123
+ const fillers: Array<Record<string, unknown>> = [];
1124
+ const size = () => Buffer.byteLength(partsDocument(fillers));
1125
+ for (let i = 0; ; i++) {
1126
+ const part: Record<string, unknown> = { id: `fill${i}`, file: "01-hero.html", selector: "h1", excerpt: "", instruction: "", status: "sent", queued: false, sentAt: "2026-10-31T10:00:00.000Z", startedAt: null, implementedAt: null };
1127
+ const gap = target - size();
1128
+ fillers.push(part);
1129
+ const overhead = size() - Buffer.byteLength(partsDocument(fillers.slice(0, -1)));
1130
+ let length = Math.min(2000, Math.floor((gap - overhead) / 6));
1131
+ if (length === 2000 && gap - overhead - 12000 < overhead + 12) length = 1000;
1132
+ assert.ok(length >= 0 && fillers.length < 99, "the fillers fit in the parts a design can hold");
1133
+ part.instruction = CONTROL.repeat(length);
1134
+ const left = target - size();
1135
+ if (left >= 6) continue;
1136
+ part.excerpt = "x".repeat(left);
1137
+ assert.equal(size(), target);
1138
+ return fillers;
1139
+ }
1140
+ }
1141
+
1142
+ test("S9: implement-part refuses a part that would push parts.json past 1 MiB with 409 parts-too-large, delivering nothing and leaving the file byte for byte", async (t) => {
1143
+ const { port, root, parts } = await start(t);
1144
+ writeFileSync(partsFile(root), partsDocument(partsOfSize(MAX_PARTS_BYTES - 2000)));
1145
+ const before = readFileSync(partsFile(root));
1146
+ const reply = await postJson(port, PARTS, { file: "01-hero.html", selector: "h1", note: CONTROL.repeat(2000) });
1147
+ assert.equal(reply.status, 409);
1148
+ const body = JSON.parse(reply.body);
1149
+ assert.deepEqual(Object.keys(body), ["error", "reason"]);
1150
+ assert.equal(body.error, "parts-too-large");
1151
+ assert.match(body.reason, /^design\/alpha\/parts\.json would grow to \d+ bytes, past the 1 MiB it can hold; nothing was written\.$/);
1152
+ assert.deepEqual(readFileSync(partsFile(root)), before, "the previous file is intact");
1153
+ assert.equal(parts.length, 0, "a refused part never reaches the session");
1154
+ const small = await postJson(port, PARTS, { file: "01-hero.html", selector: "h1" });
1155
+ assert.equal(small.status, 202, "a part that still fits is recorded");
1156
+ assert.ok(readFileSync(partsFile(root)).length <= MAX_PARTS_BYTES);
1157
+ assert.equal((await rawRequest(port, `/${TOKEN}/${PARTS_LIST}`)).status, 200, "and the file still reads");
1158
+ assert.equal((await postJson(port, PARTS_REMOVE, { id: JSON.parse(small.body).id })).status, 200, "Remove still works on a nearly full file");
1159
+ });
1160
+
1161
+ // canvas-server-data S10: parts/remove runs under the same per-design exclusivity as the implement-part delivery, so a
1162
+ // Remove that arrives while a part is being delivered waits for that delivery to settle.
1163
+
1164
+ function deferred<T>() {
1165
+ let resolve!: (value: T) => void;
1166
+ let reject!: (error: unknown) => void;
1167
+ const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });
1168
+ return { promise, resolve, reject };
1169
+ }
1170
+
1171
+ async function inFlightPart(t: TestContext) {
1172
+ const { root } = fixture(t);
1173
+ const delivery = deferred<undefined>();
1174
+ const delivered: DesignImplementPartRequest[] = [];
1175
+ const server = await startDesignCanvasServer({
1176
+ designRoot: root,
1177
+ onComment: () => {},
1178
+ onImplementPart: (request) => { delivered.push(request); return delivery.promise; },
1179
+ randomToken: () => TOKEN,
1180
+ });
1181
+ t.after(() => server.close());
1182
+ const implement = postJson(server.port, PARTS, { file: "01-hero.html", selector: "h1" });
1183
+ // Bounded: a route that answers without delivering, or never delivers, fails here instead of hanging.
1184
+ let implementSettled = false;
1185
+ void implement.then(() => { implementSettled = true; }, () => { implementSettled = true; });
1186
+ const deadline = Date.now() + 5000;
1187
+ while (delivered.length === 0 && !implementSettled && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 5));
1188
+ if (delivered.length === 0) {
1189
+ assert.fail(implementSettled ? `implement-part answered ${(await implement).status} without delivering` : "implement-part did not deliver within 5 s");
1190
+ }
1191
+ assert.equal(delivered.length, 1, "the delivery callback ran once");
1192
+ const id = delivered[0].part.id;
1193
+ let removeSettled = false;
1194
+ const remove = postJson(server.port, PARTS_REMOVE, { id }).finally(() => { removeSettled = true; });
1195
+ await new Promise((resolve) => setTimeout(resolve, 150));
1196
+ assert.equal(removeSettled, false, "the Remove waits while the delivery is in flight");
1197
+ assert.deepEqual(JSON.parse(readFileSync(partsFile(root), "utf8")).parts.map((part: { id: string }) => part.id), [id], "the part is still on disk while it is delivered");
1198
+ return { root, delivery, implement, remove, id };
1199
+ }
1200
+
1201
+ test("S10: a Remove fired while implement-part is delivering waits for it, then removes the delivered part", async (t) => {
1202
+ const { root, delivery, implement, remove, id } = await inFlightPart(t);
1203
+ delivery.resolve(undefined);
1204
+ const [implemented, removed] = await Promise.all([implement, remove]);
1205
+ assert.equal(implemented.status, 202);
1206
+ assert.deepEqual(JSON.parse(implemented.body), { ok: true, id, queued: false });
1207
+ assert.equal(removed.status, 200);
1208
+ assert.deepEqual(JSON.parse(removed.body), { ok: true, id });
1209
+ assert.deepEqual(JSON.parse(readFileSync(partsFile(root), "utf8")), { version: 1, parts: [] });
1210
+ });
1211
+
1212
+ test("S10: a Remove fired while implement-part is delivering finds nothing once the failed delivery takes the part back", async (t) => {
1213
+ const { root, delivery, implement, remove } = await inFlightPart(t);
1214
+ delivery.reject(new Error("session closed"));
1215
+ const [implemented, removed] = await Promise.all([implement, remove]);
1216
+ assert.equal(implemented.status, 500);
1217
+ assert.deepEqual(JSON.parse(implemented.body), { error: "delivery-failed", slug: "alpha", file: "01-hero.html", reason: "session closed" });
1218
+ assert.equal(removed.status, 404, "the part was taken back before the Remove ran");
1219
+ assert.deepEqual(JSON.parse(removed.body), { error: "not-found" });
1220
+ assert.deepEqual(JSON.parse(readFileSync(partsFile(root), "utf8")), { version: 1, parts: [] });
1221
+ });
1222
+
766
1223
  // S15: the canvas Implement route records the handoff in design/<slug>/handoffs.json.
767
1224
 
768
1225
  const handoffsOf = (root: string, slug = "alpha") => JSON.parse(readFileSync(join(root, slug, "handoffs.json"), "utf8"));
@@ -865,6 +1322,7 @@ test("a refused implement request records no handoff", async (t) => {
865
1322
  });
866
1323
 
867
1324
  test("events stream a change when handoffs.json is written", async (t) => {
1325
+ if (!FS_WATCH_AVAILABLE) return t.skip(FS_WATCH_SKIP);
868
1326
  const { port } = await start(t);
869
1327
  const events = openEvents(port);
870
1328
  t.after(() => events.req.destroy());
@@ -883,7 +1341,8 @@ test("the canvas CSP frames only loopback previews, and the artboard CSP is unch
883
1341
  "style-src 'self'",
884
1342
  "img-src 'self' data:",
885
1343
  "connect-src 'self'",
886
- "frame-src 'self' http://localhost:* http://127.0.0.1:* http://[::1]:* https://localhost:* https://127.0.0.1:* https://[::1]:*",
1344
+ // No [::1]: CSP host sources have no IPv6 form, so browsers reject it and log an error on every load.
1345
+ "frame-src 'self' http://localhost:* http://127.0.0.1:* https://localhost:* https://127.0.0.1:*",
887
1346
  "base-uri 'none'",
888
1347
  "form-action 'none'",
889
1348
  "frame-ancestors 'none'",
@@ -950,7 +1409,7 @@ test("formatDesignComment builds the exact session message with the comment id",
950
1409
  "Make the headline shorter.",
951
1410
  "",
952
1411
  "Edit only the artboard design/landing/02-bold.html, following the gentle-design skill.",
953
- "When it is applied, mark it resolved with the gentle_design_comments tool (action \"resolve\", slug \"landing\", ids [\"k3x9p2\"]), or set its status to \"resolved\" in design/landing/comments.json.",
1412
+ "When it is applied, mark it resolved with the gentle_design_comments tool (action \"resolve\", slug \"landing\", ids [\"k3x9p2\"], note \"<one line on what you changed>\"), or set its status to \"resolved\" in design/landing/comments.json.",
954
1413
  ].join("\n"));
955
1414
  assert.match(formatDesignComment({ ...VALID, id: "a1", excerpt: "" }), /\nExcerpt: \(none\)\n/);
956
1415
  });
@@ -979,23 +1438,24 @@ test("formatDesignCommentBatch builds one exact message listing every comment",
979
1438
  " And bolder.",
980
1439
  "",
981
1440
  "Apply each comment following the gentle-design skill, editing only the artboard it names.",
982
- "When a comment is applied, mark it resolved with the gentle_design_comments tool (action \"resolve\", slug \"landing\", ids [\"aaa111\", \"bbb222\"]), or set its status to \"resolved\" in design/landing/comments.json.",
1441
+ "When a comment is applied, mark it resolved with the gentle_design_comments tool (action \"resolve\", slug \"landing\", ids [\"aaa111\", \"bbb222\"], note \"<one line on what you changed>\"), or set its status to \"resolved\" in design/landing/comments.json.",
983
1442
  ].join("\n"));
984
1443
  });
985
1444
 
986
1445
  test("canvas assets sandbox artboards without allow-same-origin and reference no remote URL", () => {
987
- const canvas = readFileSync(join(ASSET_DIR, "canvas.js"), "utf8");
988
- assert.match(canvas, /setAttribute\("sandbox", "allow-scripts"\)/);
1446
+ const boards = readFileSync(join(ASSET_DIR, "canvas-boards.js"), "utf8");
1447
+ assert.match(boards, /setAttribute\("sandbox", "allow-scripts"\)/);
989
1448
  // The one allow-same-origin is the Compare preview of the running app, another loopback origin (S15).
990
- assert.deepEqual(canvas.match(/"[^"\n]*allow-same-origin[^"\n]*"/g), ['"allow-scripts allow-same-origin allow-forms allow-popups"']);
991
- for (const name of ["index.html", "canvas.css", "canvas.js", "inspector.js"]) {
1449
+ const compare = readFileSync(join(ASSET_DIR, "canvas-compare.js"), "utf8");
1450
+ assert.deepEqual(compare.match(/"[^"\n]*allow-same-origin[^"\n]*"/g), ['"allow-scripts allow-same-origin allow-forms allow-popups"']);
1451
+ for (const name of ["index.html", ...Object.keys(DESIGN_CANVAS_ASSETS)]) {
992
1452
  const source = readFileSync(join(ASSET_DIR, name), "utf8");
993
- if (name !== "canvas.js") assert.ok(!source.includes("allow-same-origin"), `${name} must not grant allow-same-origin`);
1453
+ if (name !== "canvas-compare.js") assert.ok(!source.includes("allow-same-origin"), `${name} must not grant allow-same-origin`);
994
1454
  assert.ok(!/https?:\/\//i.test(source), `${name} must not reference remote URLs`);
995
1455
  }
996
1456
  const inspector = readFileSync(join(ASSET_DIR, "inspector.js"), "utf8");
997
1457
  assert.match(inspector, /gd:pick/);
998
- assert.match(canvas, /event\.source/);
1458
+ assert.match(readFileSync(join(ASSET_DIR, "canvas-messages.js"), "utf8"), /event\.source/);
999
1459
  });
1000
1460
 
1001
1461
  const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(64 * 1024, 7)]);
@@ -1071,7 +1531,7 @@ test("formatDesignComment names the screenshot, and the session content attaches
1071
1531
  "The button jumps mid-animation.",
1072
1532
  "",
1073
1533
  "Edit only the artboard design/landing/02-bold.html, following the gentle-design skill.",
1074
- "When it is applied, mark it resolved with the gentle_design_comments tool (action \"resolve\", slug \"landing\", ids [\"k3x9p2\"]), or set its status to \"resolved\" in design/landing/comments.json.",
1534
+ "When it is applied, mark it resolved with the gentle_design_comments tool (action \"resolve\", slug \"landing\", ids [\"k3x9p2\"], note \"<one line on what you changed>\"), or set its status to \"resolved\" in design/landing/comments.json.",
1075
1535
  ].join("\n");
1076
1536
  assert.equal(formatDesignComment(comment), text);
1077
1537
  assert.deepEqual(designCommentContent(comment), [{ type: "text", text }, { type: "image", data: "iVBORw0KGgo=", mimeType: "image/png" }]);
@@ -1098,3 +1558,381 @@ test("a batch attaches at most six screenshots, in order, and names the rest for
1098
1558
  const plain = batch.map(({ screenshot: _drop, ...rest }) => rest);
1099
1559
  assert.equal(designCommentBatchContent(plain), formatDesignCommentBatch(plain));
1100
1560
  });
1561
+
1562
+ test("module names are served only as one exact, flat segment", async (t) => {
1563
+ const { port, base } = await start(t);
1564
+ for (const path of ["sub/canvas-boot.js", "canvas-boot.js/", "canvas-boot.js%2F", "..%2Fcanvas-boot.js", "Canvas-Boot.js", "__proto__", "constructor"]) {
1565
+ assert.equal((await rawRequest(port, `${base}assets/${path}`)).status, 404, path);
1566
+ }
1567
+ });
1568
+
1569
+ test("the page config tells the canvas which deliveries exist, and the 501 checks stay", async (t) => {
1570
+ const { root } = fixture(t);
1571
+ const configOf = async (port: number, token: string) => JSON.parse(/<script id="gd-config" type="application\/json">([^<]*)<\/script>/.exec((await rawRequest(port, `/${token}/`)).body)![1]);
1572
+
1573
+ const bare = await startDesignCanvasServer({ designRoot: root, onComment: () => {}, randomToken: () => TOKEN });
1574
+ t.after(() => bare.close());
1575
+ assert.deepEqual((await configOf(bare.port, TOKEN)).delivery, { comment: true, batch: false, implement: false, variant: false, part: false });
1576
+ const batchOnly = await postJson(bare.port, "api/designs/alpha/comments/send-all", {});
1577
+ // Nothing unsent: the batch capability is only checked when there is something to deliver.
1578
+ assert.equal(batchOnly.status, 200);
1579
+ await postComment(bare.port, { ...VALID, mode: "collect" });
1580
+ const refused = await postJson(bare.port, "api/designs/alpha/comments/send-all", {});
1581
+ assert.equal(refused.status, 501);
1582
+ assert.equal(JSON.parse(refused.body).error, "batch-delivery-unavailable");
1583
+ const noImplement = await postJson(bare.port, "api/designs/alpha/implement", { file: "01-a.html" });
1584
+ assert.equal(noImplement.status, 501);
1585
+ assert.equal(JSON.parse(noImplement.body).error, "implement-unavailable");
1586
+
1587
+ const batch = await startDesignCanvasServer({ designRoot: root, onComment: () => {}, onComments: () => {}, randomToken: () => "b".repeat(32) });
1588
+ t.after(() => batch.close());
1589
+ assert.deepEqual((await configOf(batch.port, "b".repeat(32))).delivery, { comment: true, batch: true, implement: false, variant: false, part: false });
1590
+ const implement = await startDesignCanvasServer({ designRoot: root, onComment: () => {}, onImplement: () => ({ queued: false }), randomToken: () => "i".repeat(32) });
1591
+ t.after(() => implement.close());
1592
+ assert.deepEqual((await configOf(implement.port, "i".repeat(32))).delivery, { comment: true, batch: false, implement: true, variant: false, part: false });
1593
+ const variant = await startDesignCanvasServer({ designRoot: root, onComment: () => {}, onVariant: () => ({ queued: false }), randomToken: () => "v".repeat(32) });
1594
+ t.after(() => variant.close());
1595
+ assert.deepEqual((await configOf(variant.port, "v".repeat(32))).delivery, { comment: true, batch: false, implement: false, variant: true, part: false });
1596
+ const noVariant = await postJson(bare.port, "api/designs/alpha/variant", { file: "01-a.html", instruction: "Bolder" });
1597
+ assert.equal(noVariant.status, 501);
1598
+ assert.equal(JSON.parse(noVariant.body).error, "variant-unavailable");
1599
+ const part = await startDesignCanvasServer({ designRoot: root, onComment: () => {}, onImplementPart: () => ({ queued: false }), randomToken: () => "p".repeat(32) });
1600
+ t.after(() => part.close());
1601
+ assert.deepEqual((await configOf(part.port, "p".repeat(32))).delivery, { comment: true, batch: false, implement: false, variant: false, part: true });
1602
+ });
1603
+
1604
+ // S7: the viewport a comment was made at.
1605
+
1606
+ const VIEWPORT = { width: 390, height: 844 };
1607
+
1608
+ test("S7: a comment with a viewport is stored with it and delivered with it; without one the key is absent", async (t) => {
1609
+ const { port, root, comments } = await start(t);
1610
+ const reply = await postComment(port, { ...VALID, viewport: VIEWPORT });
1611
+ assert.equal(reply.status, 202);
1612
+ const { id } = JSON.parse(reply.body);
1613
+ assert.deepEqual(comments, [{ ...VALID, id, viewport: VIEWPORT }], "the session comment carries the viewport");
1614
+ assert.deepEqual((storedComments(root)[0] as Stored & { viewport?: unknown }).viewport, VIEWPORT);
1615
+ assert.equal((await postComment(port, VALID)).status, 202);
1616
+ assert.equal("viewport" in comments[1], false);
1617
+ assert.equal("viewport" in storedComments(root)[1], false, "never written when absent");
1618
+ // Collected comments keep it too, and a Send all delivers it.
1619
+ const collected = await postComment(port, { ...VALID, mode: "collect", viewport: { width: 720, height: 820 } });
1620
+ assert.equal(collected.status, 201);
1621
+ assert.deepEqual((storedComments(root)[2] as Stored & { viewport?: unknown }).viewport, { width: 720, height: 820 });
1622
+ });
1623
+
1624
+ test("S7: an invalid viewport is refused with 400 invalid-viewport and leaves comments.json unchanged", async (t) => {
1625
+ const { port, root, comments } = await start(t);
1626
+ const invalid: unknown[] = [
1627
+ { width: 239, height: 844 }, { width: 4097, height: 844 }, { width: 390, height: 0 }, { width: 390, height: 20001 },
1628
+ { width: 390.5, height: 844 }, { width: "390", height: 844 }, { width: 390 }, {}, null, [], "390x844", 390,
1629
+ ];
1630
+ for (const viewport of invalid) {
1631
+ const reply = await postComment(port, { ...VALID, viewport });
1632
+ assert.equal(reply.status, 400, JSON.stringify(viewport));
1633
+ assert.equal(JSON.parse(reply.body).error, "invalid-viewport");
1634
+ }
1635
+ assert.deepEqual(comments, [], "nothing was delivered");
1636
+ assert.equal(existsSync(join(root, "alpha", "comments.json")), false, "nothing was stored");
1637
+ // A stored file stays byte for byte as it was.
1638
+ assert.equal((await postComment(port, VALID)).status, 202);
1639
+ const before = readFileSync(join(root, "alpha", "comments.json"), "utf8");
1640
+ assert.equal((await postComment(port, { ...VALID, viewport: { width: 1, height: 1 } })).status, 400);
1641
+ assert.equal(readFileSync(join(root, "alpha", "comments.json"), "utf8"), before);
1642
+ });
1643
+
1644
+ test("S7: formatDesignComment names the viewport so the agent edits for that width, and says nothing without one", () => {
1645
+ const comment: DesignComment = { id: "k3x9p2", slug: "landing", file: "02-bold.html", selector: "#cta", excerpt: "Go", comment: "Too wide.", viewport: { width: 390, height: 844 } };
1646
+ const text = formatDesignComment(comment);
1647
+ assert.match(text, /\nExcerpt: "Go"\nViewport: Phone 390 × 844 \(the comment was made at this size; make the change hold at this width\)\n\nComment:\n/);
1648
+ assert.match(formatDesignComment({ ...comment, viewport: { width: 720, height: 820 } }), /\nViewport: 720 × 820 \(/);
1649
+ const { viewport: _drop, ...plain } = comment;
1650
+ assert.ok(!formatDesignComment(plain).includes("Viewport:"));
1651
+ });
1652
+
1653
+ test("S7: formatDesignCommentBatch names each comment's viewport, and only those that have one", () => {
1654
+ const batch: DesignComment[] = [
1655
+ { id: "aaa111", slug: "landing", file: "01-calm.html", selector: "#cta", excerpt: "Start", comment: "Make it green.", viewport: { width: 820, height: 1180 } },
1656
+ { id: "bbb222", slug: "landing", file: "02-bold.html", selector: "body > h1", excerpt: "", comment: "Shorter." },
1657
+ ];
1658
+ const text = formatDesignCommentBatch(batch);
1659
+ assert.match(text, /\n Excerpt: "Start"\n Viewport: Tablet 820 × 1180 \(the comment was made at this size; make the change hold at this width\)\n Comment:\n/);
1660
+ assert.equal(text.match(/Viewport:/g)?.length, 1);
1661
+ assert.match(text, /\n Excerpt: \(none\)\n Comment:\n Shorter\.\n/);
1662
+ });
1663
+
1664
+ // Token inspector (T1): the tokens of design/system.md, read-only.
1665
+
1666
+ const SYSTEM_MD = "# System\n\n## Colors\n\n| Token | Value |\n| --- | --- |\n| `--bg` | `#1a1218` |\n| `--accent` | `#f095c8` |\n";
1667
+
1668
+ test("S1: GET api/system/tokens gives the tokens of design/system.md, and none when it is missing", async (t) => {
1669
+ const { port, base, root } = await start(t);
1670
+ const missing = await rawRequest(port, `${base}api/system/tokens`);
1671
+ assert.equal(missing.status, 200);
1672
+ assert.deepEqual(JSON.parse(missing.body), { exists: false, tokens: [] });
1673
+ writeFileSync(join(root, "system.md"), SYSTEM_MD);
1674
+ const present = await rawRequest(port, `${base}api/system/tokens`);
1675
+ assert.equal(present.status, 200);
1676
+ assert.match(String(present.headers["content-type"]), /^application\/json/);
1677
+ assert.deepEqual(JSON.parse(present.body), { exists: true, tokens: [
1678
+ { name: "--bg", value: "#1a1218", section: "Colors", group: "color" },
1679
+ { name: "--accent", value: "#f095c8", section: "Colors", group: "color" },
1680
+ ] });
1681
+ // The file is read on every request, so a change shows without restarting the server.
1682
+ writeFileSync(join(root, "system.md"), `${SYSTEM_MD}| \`--text\` | \`#f6eff3\` |\n`);
1683
+ assert.equal(JSON.parse((await rawRequest(port, `${base}api/system/tokens`)).body).tokens.length, 3);
1684
+ });
1685
+
1686
+ test("S1: an empty, malformed, huge, linked or directory system.md never fails the route", async (t) => {
1687
+ const { port, base, root } = await start(t);
1688
+ const tokens = async () => rawRequest(port, `${base}api/system/tokens`);
1689
+ writeFileSync(join(root, "system.md"), "");
1690
+ assert.deepEqual(JSON.parse((await tokens()).body), { exists: true, tokens: [] });
1691
+ writeFileSync(join(root, "system.md"), "| `--a\n|||`| `\u0000\n");
1692
+ const malformed = await tokens();
1693
+ assert.equal(malformed.status, 200);
1694
+ assert.deepEqual(JSON.parse(malformed.body).tokens, []);
1695
+ writeFileSync(join(root, "system.md"), `${SYSTEM_MD}${"x".repeat(300 * 1024)}`);
1696
+ assert.deepEqual(JSON.parse((await tokens()).body), { exists: true, tokens: [], problem: "too-large" });
1697
+ rmSync(join(root, "system.md"));
1698
+ const outside = scratch(t, "gentle-design-tokens-outside-");
1699
+ writeFileSync(join(outside, "system.md"), SYSTEM_MD);
1700
+ symlinkSync(join(outside, "system.md"), join(root, "system.md"));
1701
+ assert.deepEqual(JSON.parse((await tokens()).body), { exists: false, tokens: [] }, "a link out of the design root is not read");
1702
+ rmSync(join(root, "system.md"));
1703
+ mkdirSync(join(root, "system.md"));
1704
+ assert.deepEqual(JSON.parse((await tokens()).body), { exists: false, tokens: [] });
1705
+ });
1706
+
1707
+ test("S1: the tokens route keeps the Host, token, Origin and method rules, and system.md stays unserved", async (t) => {
1708
+ const { port, base, root } = await start(t);
1709
+ writeFileSync(join(root, "system.md"), SYSTEM_MD);
1710
+ const path = "api/system/tokens";
1711
+ assert.equal((await rawRequest(port, `${base}${path}`, { host: `evil.example:${port}` })).status, 421);
1712
+ assert.equal((await rawRequest(port, `/wrong-token-0123456789/${path}`)).status, 404);
1713
+ assert.equal((await rawRequest(port, `${base}${path}`, { headers: { Origin: "http://evil.example" } })).status, 403);
1714
+ assert.equal((await rawRequest(port, `${base}${path}`, { headers: { Origin: "null" } })).status, 403, "a sandboxed artboard may not read the tokens");
1715
+ assert.equal((await rawRequest(port, `${base}${path}`, { headers: { Origin: `http://localhost:${port}` } })).status, 200);
1716
+ assert.equal((await rawRequest(port, `${base}${path}`, { method: "POST", headers: { Origin: `http://127.0.0.1:${port}`, "Content-Type": "application/json" }, body: "{}" })).status, 405);
1717
+ for (const extra of ["api/system/tokens/x", "api/system/token", "system.md"]) assert.equal((await rawRequest(port, `${base}${extra}`)).status, 404, extra);
1718
+ });
1719
+
1720
+
1721
+ // canvas-trim S3: version history is gone; its routes answer like any unknown path.
1722
+
1723
+ test("canvas-trim S3: the history routes are unknown paths (404 whatever the method) and seeing a design writes no .history", async (t) => {
1724
+ const { server, port, base, root } = await start(t);
1725
+ assert.equal((await rawRequest(port, `${base}api/designs/alpha`)).status, 200);
1726
+ server.show("alpha");
1727
+ for (const path of ["api/designs/alpha/history", "history/alpha/1/01-hero.html"]) {
1728
+ const reply = await rawRequest(port, `${base}${path}`);
1729
+ assert.equal(reply.status, 404, path);
1730
+ assert.deepEqual(JSON.parse(reply.body), { error: "not-found" }, path);
1731
+ assert.equal((await rawRequest(port, `${base}${path}`, { method: "POST", headers: { Origin: `http://127.0.0.1:${port}`, "Content-Type": "application/json" }, body: "{}" })).status, 404, `POST ${path}`);
1732
+ }
1733
+ const restore = await postJson(port, "api/designs/alpha/history/restore", { file: "01-hero.html", n: 1 });
1734
+ assert.equal(restore.status, 404);
1735
+ assert.deepEqual(JSON.parse(restore.body), { error: "not-found" });
1736
+ assert.equal((await rawRequest(port, `${base}api/designs/alpha/history/restore`)).status, 404, "GET restore");
1737
+ await new Promise((resolve) => setTimeout(resolve, 100));
1738
+ assert.equal(existsSync(join(root, "alpha", ".history")), false);
1739
+ });
1740
+
1741
+ // canvas-layout S3: design/<slug>/layout.json, read and written whole by the canvas through the server.
1742
+
1743
+ const LAYOUT_PATH = "api/designs/alpha/layout";
1744
+ const SAVED_LAYOUT = { arrangement: "free", positions: { system: { x: 0, y: 0 }, "01-hero.html": { x: 1520, y: 0 }, "02-bare.html": { x: 0, y: 1280 } } };
1745
+
1746
+ test("canvas-layout S3: GET layout is null without layout.json; POST validates and saves it whole; GET gives it back", async (t) => {
1747
+ const { port, base, root } = await start(t);
1748
+ const missing = await rawRequest(port, `${base}${LAYOUT_PATH}`);
1749
+ assert.equal(missing.status, 200);
1750
+ assert.deepEqual(JSON.parse(missing.body), { layout: null });
1751
+ const saved = await postJson(port, LAYOUT_PATH, SAVED_LAYOUT);
1752
+ assert.equal(saved.status, 200);
1753
+ assert.deepEqual(JSON.parse(saved.body), { ok: true, layout: SAVED_LAYOUT });
1754
+ assert.equal(readFileSync(join(root, "alpha", "layout.json"), "utf8"), `${JSON.stringify(SAVED_LAYOUT, null, 2)}\n`);
1755
+ const read = await rawRequest(port, `${base}${LAYOUT_PATH}`);
1756
+ assert.equal(read.status, 200);
1757
+ assert.deepEqual(JSON.parse(read.body), { layout: SAVED_LAYOUT });
1758
+ // A broken file is no layout the canvas can use, but it is no missing one either (S17); the next save replaces it.
1759
+ writeFileSync(join(root, "alpha", "layout.json"), "{ broken");
1760
+ assert.equal((await rawRequest(port, `${base}${LAYOUT_PATH}`)).status, 422);
1761
+ assert.equal((await postJson(port, LAYOUT_PATH, SAVED_LAYOUT)).status, 200);
1762
+ assert.deepEqual(JSON.parse(readFileSync(join(root, "alpha", "layout.json"), "utf8")), SAVED_LAYOUT);
1763
+ });
1764
+
1765
+ test("canvas-layout S17: GET layout tells a missing layout.json (null) from one it cannot read or use (422 with the reason), and changes nothing on disk", async (t) => {
1766
+ const { port, base, root } = await start(t);
1767
+ const file = join(root, "alpha", "layout.json");
1768
+ const get = async () => {
1769
+ const reply = await rawRequest(port, `${base}${LAYOUT_PATH}`);
1770
+ return { status: reply.status, body: JSON.parse(reply.body) };
1771
+ };
1772
+ assert.deepEqual(await get(), { status: 200, body: { layout: null } }, "a missing file is no layout");
1773
+ const cases: Array<[string, string]> = [
1774
+ ["{ broken", "not valid JSON"],
1775
+ ["[]", "layout must be a JSON object"],
1776
+ [JSON.stringify({ arrangement: "row" }), "positions must be an object"],
1777
+ [JSON.stringify({ arrangement: "diagonal", positions: {} }), 'arrangement must be "row", "column", "grid" or "free"'],
1778
+ ["x".repeat(300 * 1024), "larger than 262144 bytes"],
1779
+ ];
1780
+ for (const [content, reason] of cases) {
1781
+ writeFileSync(file, content);
1782
+ assert.deepEqual(await get(), { status: 422, body: { error: "unreadable-layout", reason } }, content.slice(0, 40));
1783
+ assert.equal(readFileSync(file, "utf8"), content, "the file is left as it was");
1784
+ }
1785
+ rmSync(file);
1786
+ writeFileSync(join(root, "elsewhere.json"), JSON.stringify(SAVED_LAYOUT));
1787
+ symlinkSync(join(root, "elsewhere.json"), file);
1788
+ assert.deepEqual(await get(), { status: 422, body: { error: "unreadable-layout", reason: "not a regular file" } }, "a link is never followed");
1789
+ rmSync(file);
1790
+ mkdirSync(file);
1791
+ assert.deepEqual(await get(), { status: 422, body: { error: "unreadable-layout", reason: "not a regular file" } }, "a directory named layout.json");
1792
+ assert.equal((await rawRequest(port, `${base}api/designs/missing/layout`)).status, 404, "an unknown design is still not found");
1793
+ });
1794
+
1795
+ test("canvas-layout S23: a position far out of range (1e300) is a layout.json the server cannot use on GET (422) and refuses on POST", async (t) => {
1796
+ const { port, base, root } = await start(t);
1797
+ const far = { arrangement: "free", positions: { "01-hero.html": { x: 1e300, y: 0 } } };
1798
+ const file = join(root, "alpha", "layout.json");
1799
+ writeFileSync(file, JSON.stringify(far));
1800
+ const read = await rawRequest(port, `${base}${LAYOUT_PATH}`);
1801
+ assert.deepEqual({ status: read.status, body: JSON.parse(read.body) }, { status: 422, body: { error: "unreadable-layout", reason: 'positions["01-hero.html"] x and y must be integers between -2000000 and 2000000' } });
1802
+ const save = await postJson(port, LAYOUT_PATH, far);
1803
+ assert.deepEqual({ status: save.status, body: JSON.parse(save.body) }, { status: 400, body: { error: "invalid-layout", reason: 'positions["01-hero.html"] x and y must be integers between -2000000 and 2000000' } });
1804
+ assert.equal(readFileSync(file, "utf8"), JSON.stringify(far), "the file is left as it was");
1805
+ });
1806
+
1807
+ test("canvas-layout S3: an invalid layout is refused with its reason and nothing is written", async (t) => {
1808
+ const { port, root } = await start(t);
1809
+ const refuse = async (body: unknown, reason: RegExp) => {
1810
+ const reply = await postJson(port, LAYOUT_PATH, body);
1811
+ assert.equal(reply.status, 400, JSON.stringify(body));
1812
+ const answer = JSON.parse(reply.body);
1813
+ assert.equal(answer.error, "invalid-layout");
1814
+ assert.match(answer.reason, reason);
1815
+ };
1816
+ await refuse({ arrangement: "diagonal", positions: {} }, /^arrangement must be "row", "column", "grid" or "free"$/);
1817
+ await refuse({ arrangement: "row", positions: { "01-hero.html": { x: 1.5, y: 0 } } }, /x and y must be integers/);
1818
+ await refuse({ arrangement: "row", positions: { "../beta/01-a.html": { x: 0, y: 0 } } }, /keys must be relative \.html artboard paths/);
1819
+ await refuse({ arrangement: "row", positions: {}, extra: true }, /unknown keys: extra/);
1820
+ assert.equal(existsSync(join(root, "alpha", "layout.json")), false, "nothing is written");
1821
+ assert.equal((await postJson(port, LAYOUT_PATH, SAVED_LAYOUT)).status, 200);
1822
+ const before = readFileSync(join(root, "alpha", "layout.json"), "utf8");
1823
+ await refuse({ arrangement: "row", positions: { "01-hero.html": { x: 0, y: 3_000_000 } } }, /between -2000000 and 2000000/);
1824
+ assert.equal(readFileSync(join(root, "alpha", "layout.json"), "utf8"), before, "the saved layout stays as it was");
1825
+ assert.equal((await postJson(port, "api/designs/missing/layout", SAVED_LAYOUT)).status, 404);
1826
+ assert.equal((await postJson(port, "api/designs/Not_A_Slug/layout", SAVED_LAYOUT)).status, 404);
1827
+ assert.equal(existsSync(join(root, "missing")), false);
1828
+ });
1829
+
1830
+ test("canvas-layout S3: the layout route keeps the Origin, content-type, JSON and method rules", async (t) => {
1831
+ const { port, base, root } = await start(t);
1832
+ const path = `${base}${LAYOUT_PATH}`;
1833
+ const body = JSON.stringify(SAVED_LAYOUT);
1834
+ const own = { Origin: `http://127.0.0.1:${port}`, "Content-Type": "application/json" };
1835
+ assert.equal((await rawRequest(port, path, { method: "POST", headers: { "Content-Type": "application/json" }, body })).status, 403, "no Origin");
1836
+ assert.equal((await rawRequest(port, path, { method: "POST", headers: { ...own, Origin: "http://evil.example" }, body })).status, 403);
1837
+ assert.equal((await rawRequest(port, path, { method: "POST", headers: { ...own, "Content-Type": "text/plain" }, body })).status, 415);
1838
+ assert.equal((await rawRequest(port, path, { method: "POST", headers: own, body: "not json" })).status, 400);
1839
+ const put = await rawRequest(port, path, { method: "PUT", headers: own, body });
1840
+ assert.equal(put.status, 405);
1841
+ assert.equal(put.headers.allow, "GET, POST");
1842
+ assert.equal((await rawRequest(port, path, { headers: { Origin: "http://evil.example" } })).status, 403, "only this server's pages read it");
1843
+ assert.equal((await rawRequest(port, path, { headers: { Origin: "null" } })).status, 403, "a sandboxed artboard may not read it");
1844
+ assert.equal((await rawRequest(port, `${base}api/designs/missing/layout`)).status, 404);
1845
+ assert.equal(existsSync(join(root, "alpha", "layout.json")), false);
1846
+ // The other GET-only and POST-only routes keep answering 405 with their one method.
1847
+ const comments = await rawRequest(port, `${base}api/designs/alpha/comments`, { method: "POST", headers: own, body: "{}" });
1848
+ assert.equal(comments.status, 405);
1849
+ assert.equal(comments.headers.allow, "GET");
1850
+ const implement = await rawRequest(port, `${base}api/designs/alpha/implement`);
1851
+ assert.equal(implement.status, 405);
1852
+ assert.equal(implement.headers.allow, "POST");
1853
+ });
1854
+
1855
+ test("canvas-layout S3: saving the layout streams one change for layout.json", async (t) => {
1856
+ if (!FS_WATCH_AVAILABLE) return t.skip(FS_WATCH_SKIP);
1857
+ const { port } = await start(t);
1858
+ const events = openEvents(port);
1859
+ t.after(() => events.req.destroy());
1860
+ await events.ready;
1861
+ await events.waitFor(/: connected\n\n/);
1862
+ await new Promise((resolve) => setTimeout(resolve, 100));
1863
+ assert.equal((await postJson(port, LAYOUT_PATH, SAVED_LAYOUT)).status, 200);
1864
+ await events.waitFor(/event: change\ndata: \{"slug":"alpha","file":"layout\.json"\}\n\n/);
1865
+ });
1866
+
1867
+ test("canvas-layout S17: the text route edits an open comment; a changed sent one reaches the session as an edit, an unsent one waits, a resolved, unknown, invalid or cross-origin edit is refused without writing", async (t) => {
1868
+ const { port, root, comments } = await start(t);
1869
+ await postComment(port, { ...VALID, mode: "collect" });
1870
+ await postComment(port, { ...VALID, mode: "collect" });
1871
+ await postComment(port, { ...VALID, mode: "collect" });
1872
+ const [open, sent, resolved] = storedComments(root);
1873
+ const path = join(root, "alpha", "comments.json");
1874
+ const document = JSON.parse(readFileSync(path, "utf8"));
1875
+ document.comments[1].sentAt = "2026-11-08T10:00:00.000Z";
1876
+ document.comments[2].status = "resolved";
1877
+ document.comments[2].resolvedAt = "2026-11-08T10:00:00.000Z";
1878
+ writeFileSync(path, JSON.stringify(document));
1879
+ const edited = await postJson(port, `api/designs/alpha/comments/${open.id}/text`, { comment: " Make it\r\nmuch bigger " });
1880
+ assert.equal(edited.status, 200);
1881
+ assert.equal(JSON.parse(edited.body).comment.comment, "Make it\nmuch bigger", "line endings normalized and trimmed like a new comment");
1882
+ assert.equal(JSON.parse(edited.body).sent, false, "an unsent comment waits for Send all");
1883
+ assert.equal(storedComments(root)[0].comment, "Make it\nmuch bigger");
1884
+ assert.equal(comments.length, 0, "nothing reaches the session for an unsent comment");
1885
+
1886
+ const resent = await postJson(port, `api/designs/alpha/comments/${sent.id}/text`, { comment: "Smaller" });
1887
+ assert.equal(resent.status, 200);
1888
+ assert.equal(JSON.parse(resent.body).sent, true);
1889
+ assert.equal(storedComments(root)[1].comment, "Smaller");
1890
+ assert.equal(storedComments(root)[1].sentAt, "2026-11-08T10:00:00.000Z", "it stays sent");
1891
+ assert.equal(comments.length, 1);
1892
+ assert.deepEqual([comments[0].id, comments[0].comment, comments[0].edited], [sent.id, "Smaller", { previous: "Make it bigger" }]);
1893
+ const same = await postJson(port, `api/designs/alpha/comments/${sent.id}/text`, { comment: "Smaller" });
1894
+ assert.deepEqual([same.status, JSON.parse(same.body).sent], [200, false]);
1895
+ assert.equal(comments.length, 1, "an unchanged text is not sent again");
1896
+
1897
+ const before = readFileSync(path, "utf8");
1898
+ const refusal = async (id: string, body: unknown) => {
1899
+ const reply = await postJson(port, `api/designs/alpha/comments/${id}/text`, body);
1900
+ return [reply.status, JSON.parse(reply.body || "{}").error];
1901
+ };
1902
+ assert.deepEqual(await refusal(resolved.id, { comment: "New" }), [409, "comment-resolved"]);
1903
+ assert.deepEqual(await refusal("zzzzzz", { comment: "New" }), [404, "not-found"]);
1904
+ assert.deepEqual(await refusal(open.id, { comment: " " }), [400, "invalid-comment"]);
1905
+ assert.deepEqual(await refusal(open.id, { comment: "x".repeat(2001) }), [400, "invalid-comment"]);
1906
+ assert.deepEqual(await refusal(open.id, { comment: 7 }), [400, "invalid-comment"]);
1907
+ const foreign = await rawRequest(port, `/${TOKEN}/api/designs/alpha/comments/${open.id}/text`, { method: "POST", headers: { Origin: "http://evil.example", "Content-Type": "application/json" }, body: JSON.stringify({ comment: "New" }) });
1908
+ assert.equal(foreign.status, 403);
1909
+ assert.equal(readFileSync(path, "utf8"), before, "no refused edit writes comments.json");
1910
+ assert.equal(comments.length, 1);
1911
+ });
1912
+
1913
+ test("canvas-layout S17: when the session refuses the edit of a sent comment, the new text stays saved and the reply says it was not sent", async (t) => {
1914
+ const { port, root } = await start(t, { onComment: () => { throw new Error("offline"); } });
1915
+ await postComment(port, { ...VALID, mode: "collect" });
1916
+ const [saved] = storedComments(root);
1917
+ const path = join(root, "alpha", "comments.json");
1918
+ const document = JSON.parse(readFileSync(path, "utf8"));
1919
+ document.comments[0].sentAt = "2026-11-08T10:00:00.000Z";
1920
+ writeFileSync(path, JSON.stringify(document));
1921
+ const reply = await postJson(port, `api/designs/alpha/comments/${saved.id}/text`, { comment: "Smaller" });
1922
+ assert.equal(reply.status, 500);
1923
+ assert.deepEqual(JSON.parse(reply.body), { error: "edit-not-delivered", id: saved.id, saved: true, sent: false });
1924
+ assert.equal(storedComments(root)[0].comment, "Smaller");
1925
+ });
1926
+
1927
+ test("canvas-layout S17: an edited comment's message names it as an edit and quotes the previous text", () => {
1928
+ const text = formatDesignComment({ id: "k3x9p2", slug: "landing", file: "02-bold.html", selector: "h1", excerpt: "", comment: "Make it shorter.", edited: { previous: "Make it bigger." } });
1929
+ assert.ok(text.startsWith("Design comment edited for design/landing/02-bold.html\n"));
1930
+ assert.ok(text.includes("\nComment (edited; it replaces the text you received earlier for this id):\nMake it shorter.\n"));
1931
+ assert.ok(text.includes("\nPrevious text:\nMake it bigger.\n"));
1932
+ assert.ok(!formatDesignComment({ id: "k3x9p2", slug: "landing", file: "02-bold.html", selector: "h1", excerpt: "", comment: "x" }).includes("edited"));
1933
+ });
1934
+
1935
+ test("describeWatchFailure names the exhausted inotify limit (gentle-shell#3156)", () => {
1936
+ assert.match(describeWatchFailure(Object.assign(new Error("watch failed"), { code: "ENOSPC" })), /fs\.watch failed: ENOSPC .*fs\.inotify\.max_user_watches/);
1937
+ assert.match(describeWatchFailure(new Error("boom")), /fs\.watch failed: /);
1938
+ });