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
@@ -0,0 +1,526 @@
1
+ import assert from "node:assert/strict";
2
+ import { readdirSync, readFileSync } from "node:fs";
3
+ import test from "node:test";
4
+ import { fileURLToPath } from "node:url";
5
+ import { init as i18nInit } from "../assets/design-canvas/canvas-i18n.js";
6
+ import { ES } from "../assets/design-canvas/canvas-i18n-es.js";
7
+ import { createStore } from "../assets/design-canvas/canvas-store.js";
8
+ import { DESIGN_CANVAS_ASSETS } from "../lib/design-canvas-assets.ts";
9
+ import { ASSET_DIR, boardsOf, click, FakeDocument, findAll, flush, loadCanvas, memoryStorage, read, texts, withClass, type FakeElement } from "./support/design-canvas-dom.ts";
10
+
11
+ // The canvas language (canvas-i18n.js, canvas-i18n-es.js; odd/tasks/canvas-i18n.md S1-S8): Español, English or
12
+ // Match the browser in the rail's Settings, saved in this browser, applied at once; the shell's strings in Spanish.
13
+
14
+ const LANGUAGE_KEY = "gentle-design:language";
15
+ const LANGUAGE_ITEMS = ["Español", "English", "Match the browser"];
16
+ const NOTE = "Messages to the agent stay in English.";
17
+ // Every canvas module with a TEXT block, by its ES name (canvas-<name>.js): the catalog covers them all.
18
+ const MODULE_FILES = readdirSync(ASSET_DIR).filter((name) => /^canvas-[a-z-]+\.js$/.test(name)).sort();
19
+ const COVERED = MODULE_FILES.filter((name) => read(name).includes("const TEXT = Object.freeze({")).map((name) => name.slice("canvas-".length, -".js".length));
20
+
21
+ type Browser = { languages?: string[]; language?: string } | null;
22
+
23
+ /** The canvas with index.html's language markup, a browser language and an in-memory (or throwing) localStorage. */
24
+ async function loadLanguage(options: { browser?: Browser; stored?: string; broken?: boolean; replies?: Record<string, unknown> } = {}) {
25
+ const storage = memoryStorage(options.stored === undefined ? {} : { [LANGUAGE_KEY]: options.stored }, options.broken);
26
+ const navigator = options.browser === null ? undefined : { languages: ["en-US"], language: "en-US", ...options.browser };
27
+ const canvas = await loadCanvas(300, options.replies ?? {}, {}, { localStorage: storage.localStorage, navigator }, true);
28
+ // The fake DOM starts every element visible; index.html starts these hidden.
29
+ canvas.document.getElementById("gd-popover").hidden = true;
30
+ canvas.document.getElementById("gd-menu").hidden = true;
31
+ const languageWrites = () => storage.writes.filter(([key]) => key === LANGUAGE_KEY).map(([, value]) => value);
32
+ return { ...canvas, storage, navigator, languageWrites };
33
+ }
34
+ type Canvas = Awaited<ReturnType<typeof loadLanguage>>;
35
+
36
+ const $ = (canvas: Canvas, id: string) => canvas.document.getElementById(id);
37
+ const lang = (canvas: Canvas) => canvas.document.documentElement.getAttribute("lang");
38
+ const menuEl = (canvas: Canvas) => $(canvas, "gd-menu");
39
+ const settingsItems = (canvas: Canvas) => findAll(menuEl(canvas), (element) => (element.getAttribute("role") ?? "").startsWith("menuitem"));
40
+ const labels = (items: FakeElement[]) => items.map((item) => texts(item, "gd-menu-label")[0]);
41
+ const openSettings = (canvas: Canvas) => {
42
+ $(canvas, "gd-rail-settings").dispatch("click");
43
+ return settingsItems(canvas);
44
+ };
45
+ const keyOn = (target: FakeElement, key: string) => target.dispatch("keydown", { key, shiftKey: false });
46
+ /** Opens Settings and chooses the language item `label` with Enter. */
47
+ function choose(canvas: Canvas, label: string) {
48
+ const items = openSettings(canvas);
49
+ const item = items[labels(items).indexOf(label)];
50
+ item.focus();
51
+ keyOn(item, "Enter");
52
+ }
53
+ /** The text of the markup element keyed `key` (data-i18n), and an attribute of one keyed by data-i18n-<attribute>. */
54
+ const marked = (canvas: Canvas, key: string) => findAll(canvas.document.body, (element) => element.getAttribute("data-i18n") === key).map((element) => element.textContent);
55
+ const markedAttribute = (canvas: Canvas, attribute: string, key: string) => findAll(canvas.document.body, (element) => element.getAttribute(`data-i18n-${attribute}`) === key).map((element) => element.getAttribute(attribute));
56
+ const settle = async () => { for (let i = 0; i < 10; i++) await flush(); };
57
+
58
+ /** What the shell shows, as strings: the surfaces this PR translates. */
59
+ function shell(canvas: Canvas) {
60
+ const board = boardsOf(canvas)[0];
61
+ const shield = withClass(board, "gd-shield")[0];
62
+ const start = withClass(board, "gd-implement-start")[0];
63
+ const confirm = withClass(board, "gd-implement-confirm")[0];
64
+ const tools = ["gd-tool-navigate", "gd-comment", "gd-rail-fit", "gd-panel-toggle"].map((id) => $(canvas, id).title);
65
+ const rows = findAll($(canvas, "gd-keys-custom"), (element) => element.classes.has("gd-key-row"));
66
+ return {
67
+ lang: lang(canvas),
68
+ tools,
69
+ railLabels: ["move", "comment", "overview", "settings"].flatMap((key) => marked(canvas, key)),
70
+ railName: markedAttribute(canvas, "aria-label", "tools"),
71
+ settingsTitle: markedAttribute(canvas, "title", "settingsTitle"),
72
+ artboards: markedAttribute(canvas, "aria-label", "artboards"),
73
+ back: [...marked(canvas, "back"), ...markedAttribute(canvas, "title", "backTitle")],
74
+ bar: [...marked(canvas, "fit"), ...marked(canvas, "sendNow"), ...marked(canvas, "collect"), ...marked(canvas, "comments"), ...markedAttribute(canvas, "aria-label", "zoomIn"), ...markedAttribute(canvas, "title", "arrangeGrid")],
75
+ dialog: [...marked(canvas, "shortcutsTitle"), ...marked(canvas, "fitAll"), ...marked(canvas, "restore"), ...marked(canvas, "close")],
76
+ row: [texts(rows[0], "gd-key-action")[0], withClass(rows[0], "gd-key-change")[0].textContent, withClass(rows[0], "gd-key-change")[0].getAttribute("aria-label"), withClass(rows[0], "gd-key-reset")[0].textContent],
77
+ nav: canvas.navMode.textContent,
78
+ implement: [start.textContent, start.getAttribute("aria-label"), confirm.getAttribute("aria-label"), confirm.children[0].textContent],
79
+ shield: [shield.getAttribute("aria-label"), texts(shield, "gd-shield-hint")[0], canvas.frames()[0].title],
80
+ docTitle: canvas.document.title,
81
+ };
82
+ }
83
+
84
+ const ENGLISH = {
85
+ lang: "en",
86
+ tools: ["Move around the canvas (V)", "Comment on an element (C)", "See all the directions (F)", "Comments panel (])"],
87
+ railLabels: ["Move", "Comment", "Overview", "Settings"],
88
+ railName: ["Tools"],
89
+ settingsTitle: ["Settings: design system, keyboard shortcuts and technical details"],
90
+ artboards: ["Artboards"],
91
+ back: ["Back to canvas", "Back to canvas (Shift+Esc)"],
92
+ bar: ["Fit", "Send now", "Collect", "Comments", "Zoom in", "Arrange in a grid"],
93
+ dialog: ["Keyboard shortcuts", "Fit all directions", "Restore defaults", "Close"],
94
+ row: ["Move around the canvas", "Change", "Change the key for “Move around the canvas” (V)", "Reset"],
95
+ nav: "Navigating",
96
+ implement: ["Implement this", "Implement First in the project", "Confirm implementing First", "Send it to the session to implement?"],
97
+ shield: ["Use First", "Click to use this design", "First artboard"],
98
+ docTitle: "Alpha · Gentle Design",
99
+ };
100
+
101
+ const SPANISH = {
102
+ lang: "es",
103
+ tools: ["Moverte por el canvas (V)", "Comentar un elemento (C)", "Ver todas las propuestas (F)", "Panel de comentarios (])"],
104
+ railLabels: ["Mover", "Comentar", "Ver todo", "Ajustes"],
105
+ railName: ["Herramientas"],
106
+ settingsTitle: ["Ajustes: design system, atajos de teclado y detalles técnicos"],
107
+ artboards: ["Propuestas"],
108
+ back: ["Volver al canvas", "Volver al canvas (Mayús+Esc)"],
109
+ bar: ["Ajustar", "Enviar ya", "Acumular", "Comentarios", "Acercar", "Organizar en cuadrícula"],
110
+ dialog: ["Atajos de teclado", "Ajustar todas las propuestas", "Restablecer valores predeterminados", "Cerrar"],
111
+ row: ["Moverte por el canvas", "Cambiar", "Cambiar la tecla de “Moverte por el canvas” (V)", "Restablecer"],
112
+ nav: "Navegando",
113
+ implement: ["Implementar", "Implementar First en el proyecto", "Confirmar la implementación de First", "¿Enviarla a la sesión para implementarla?"],
114
+ shield: ["Usar First", "Haz clic para usar este diseño", "Propuesta First"],
115
+ // The design's title and the product's name: nothing to translate.
116
+ docTitle: "Alpha · Gentle Design",
117
+ };
118
+
119
+ // ---- the default (S1)
120
+
121
+ test("the default is the browser's language: es* is Spanish, anything else or no browser language is English", async () => {
122
+ const cases: Array<[Browser, string]> = [
123
+ [{ languages: ["es-AR", "en"] }, "es"],
124
+ [{ languages: ["ES"] }, "es"],
125
+ [{ languages: [], language: "es-ES" }, "es"],
126
+ [{ languages: ["en-GB", "es"] }, "en"],
127
+ [{ languages: ["eu-ES"] }, "en"],
128
+ [{ languages: ["est"] }, "en"],
129
+ [null, "en"],
130
+ ];
131
+ for (const [browser, expected] of cases) {
132
+ const canvas = await loadLanguage({ browser });
133
+ assert.equal(lang(canvas), expected, JSON.stringify(browser));
134
+ assert.equal(canvas.navMode.textContent, expected === "es" ? "Navegando" : "Navigating", JSON.stringify(browser));
135
+ assert.deepEqual(canvas.languageWrites(), [], "the default is not saved");
136
+ }
137
+ });
138
+
139
+ // ---- the switch in Settings (S1, S8)
140
+
141
+ test("Settings ends with Español, English and Match the browser as radio items and the note, with the menu's keys", async () => {
142
+ const canvas = await loadLanguage();
143
+ const items = openSettings(canvas);
144
+ assert.deepEqual(labels(items), ["Design system board", "Keyboard shortcuts", "Technical details", ...LANGUAGE_ITEMS]);
145
+ assert.deepEqual(items.slice(3).map((item) => [item.getAttribute("role"), item.getAttribute("aria-checked")]), [["menuitemradio", "false"], ["menuitemradio", "false"], ["menuitemradio", "true"]], "Match the browser is the default");
146
+ assert.deepEqual(texts(menuEl(canvas), "gd-menu-note"), [NOTE]);
147
+ assert.deepEqual(withClass(menuEl(canvas), "gd-menu-note").map((note) => note.getAttribute("role")), ["none"], "a menu owns only items, groups and separators: the note is presentational");
148
+ assert.equal(withClass(menuEl(canvas), "gd-menu-separator").length, 1, "a separator before the language");
149
+ // The menu's keys: the arrows go from Technical details to the radios and wrap.
150
+ items[2].focus();
151
+ keyOn(items[2], "ArrowDown");
152
+ assert.equal(canvas.document.activeElement, items[3]);
153
+ keyOn(items[3], "End");
154
+ assert.equal(canvas.document.activeElement, items[5]);
155
+ keyOn(items[5], "ArrowDown");
156
+ assert.equal(canvas.document.activeElement, items[0]);
157
+ keyOn(items[0], "Escape");
158
+ assert.equal(menuEl(canvas).hidden, true);
159
+ assert.equal(lang(canvas), "en", "Esc changes nothing");
160
+
161
+ // Enter on Español: the menu closes, focus is back on Settings, and the canvas is Spanish at once.
162
+ choose(canvas, "Español");
163
+ assert.equal(menuEl(canvas).hidden, true);
164
+ assert.equal(canvas.document.activeElement?.id, "gd-rail-settings");
165
+ assert.equal(lang(canvas), "es");
166
+ assert.deepEqual(canvas.languageWrites(), ["es"]);
167
+ const spanish = openSettings(canvas);
168
+ assert.equal(menuEl(canvas).getAttribute("aria-label"), "Ajustes");
169
+ assert.deepEqual(labels(spanish), ["Tablero del design system", "Atajos de teclado", "Detalles técnicos", "Español", "English", "Igual que el navegador"]);
170
+ assert.deepEqual(spanish.slice(3).map((item) => item.getAttribute("aria-checked")), ["true", "false", "false"]);
171
+ assert.deepEqual(texts(menuEl(canvas), "gd-menu-note"), ["Los mensajes al agente siguen en inglés."]);
172
+ // Space chooses too.
173
+ const english = spanish[4];
174
+ english.focus();
175
+ keyOn(english, " ");
176
+ assert.equal(lang(canvas), "en");
177
+ choose(canvas, "Match the browser");
178
+ assert.equal(lang(canvas), "en", "the browser is English");
179
+ assert.deepEqual(canvas.languageWrites(), ["es", "en", "auto"]);
180
+ });
181
+
182
+ test("Settings heads the language radios with Language / Idioma: visible, out of the arrow keys, and the radios' group name", async () => {
183
+ const canvas = await loadLanguage();
184
+ const heading = () => {
185
+ const items = openSettings(canvas);
186
+ const [title] = withClass(menuEl(canvas), "gd-menu-heading");
187
+ const [group] = findAll(menuEl(canvas), (element) => element.getAttribute("role") === "group");
188
+ const grouped = labels(findAll(group, (element) => element.getAttribute("role") === "menuitemradio"));
189
+ // From Technical details the arrows go straight to the first radio and back: the heading is never a stop.
190
+ items[2].focus();
191
+ keyOn(items[2], "ArrowDown");
192
+ const down = canvas.document.activeElement === items[3];
193
+ keyOn(items[3], "ArrowUp");
194
+ const up = canvas.document.activeElement === items[2];
195
+ const result = [title.textContent, title.getAttribute("role"), title.getAttribute("tabindex"), group.getAttribute("aria-labelledby") === title.id && title.id !== "", grouped, down, up];
196
+ keyOn(canvas.document.activeElement!, "Escape");
197
+ return result;
198
+ };
199
+ assert.deepEqual(heading(), ["Language", null, null, true, LANGUAGE_ITEMS, true, true]);
200
+ choose(canvas, "Español");
201
+ assert.deepEqual(heading(), ["Idioma", null, null, true, ["Español", "English", "Igual que el navegador"], true, true]);
202
+ });
203
+
204
+ test("the saved choice wins over the browser; an unknown or unreadable one is Match the browser, and storage that throws still lets the page switch", async () => {
205
+ assert.equal(lang(await loadLanguage({ stored: "es" })), "es");
206
+ assert.equal(lang(await loadLanguage({ stored: "en", browser: { languages: ["es-MX"] } })), "en");
207
+ assert.equal(lang(await loadLanguage({ stored: "auto", browser: { languages: ["es-MX"] } })), "es");
208
+ assert.equal(lang(await loadLanguage({ stored: "fr", browser: { languages: ["es-MX"] } })), "es");
209
+
210
+ const broken = await loadLanguage({ broken: true, browser: { languages: ["es-CO"] } });
211
+ assert.equal(lang(broken), "es", "unreadable storage follows the browser");
212
+ const checked = () => {
213
+ const items = openSettings(broken);
214
+ const value = items.slice(3).map((item) => item.getAttribute("aria-checked"));
215
+ $(broken, "gd-rail-settings").dispatch("click");
216
+ return value;
217
+ };
218
+ assert.deepEqual(checked(), ["false", "false", "true"]);
219
+ choose(broken, "English");
220
+ assert.equal(lang(broken), "en", "the choice holds for the page");
221
+ assert.equal(broken.navMode.textContent, "Navigating");
222
+ assert.deepEqual(checked(), ["false", "true", "false"]);
223
+ });
224
+
225
+ test("switching the language reloads no artboard and fetches nothing", async () => {
226
+ const canvas = await loadLanguage();
227
+ const sources = () => canvas.frames().map((frame) => frame.src);
228
+ const before = sources();
229
+ const fetched = canvas.fetched.length;
230
+ const frames = canvas.frames();
231
+ choose(canvas, "Español");
232
+ choose(canvas, "English");
233
+ await settle();
234
+ assert.deepEqual(sources(), before);
235
+ assert.equal(canvas.fetched.length, fetched);
236
+ assert.equal(canvas.frames().length, frames.length);
237
+ assert.ok(canvas.frames().every((frame, index) => frame === frames[index]), "the same frames, relabeled in place");
238
+ });
239
+
240
+ // ---- the shell in Spanish, and back (S2, S6)
241
+
242
+ test("the shell in Spanish: rail labels and tooltips with their keys, top bar, nav chip, Implement this, the shortcuts list; English again gives the exact English", async () => {
243
+ const canvas = await loadLanguage({ browser: { languages: ["es-ES"] } });
244
+ assert.deepEqual(shell(canvas), SPANISH);
245
+ choose(canvas, "English");
246
+ assert.deepEqual(shell(canvas), ENGLISH);
247
+ choose(canvas, "Español");
248
+ assert.deepEqual(shell(canvas), SPANISH);
249
+
250
+ // Focus mode's chip names the artboard as written.
251
+ click(withClass(boardsOf(canvas)[0], "gd-shield")[0], 200, 200);
252
+ assert.equal(canvas.navMode.textContent, "Usando: First · Mayús+Esc para salir");
253
+ choose(canvas, "English");
254
+ assert.equal(canvas.navMode.textContent, "Using: First · Shift+Esc to exit");
255
+ });
256
+
257
+ test("an English canvas from the start shows the same English as before", async () => {
258
+ assert.deepEqual(shell(await loadLanguage()), ENGLISH);
259
+ });
260
+
261
+ test("the empty state, the feature line and the system board follow the language", async () => {
262
+ const replies = {
263
+ "/t/api/system": { exists: true, file: "system.html", width: 1440, height: 1200 },
264
+ "/t/api/designs/alpha": { slug: "alpha", title: "Alpha", feature: "checkout", brief: "", artboards: [] },
265
+ "/t/api/designs": { designs: [{ slug: "alpha", title: "Alpha", valid: true }, { slug: "broken", valid: false }] },
266
+ };
267
+ const canvas = await loadLanguage({ replies });
268
+ const system = () => {
269
+ const board = boardsOf(canvas)[0];
270
+ return [texts(board, "gd-artboard-title")[0], texts(board, "gd-artboard-tradeoff")[0], texts(board, "gd-system-note")[0], texts(board, "gd-shield-hint")[0], $(canvas, "gd-feature").textContent, ...$(canvas, "gd-design").children.map((option) => option.textContent)];
271
+ };
272
+ assert.deepEqual(system(), ["Design system", "Project tokens (design/system.md)", "Comments off on this board", "Click to view the design system", "Feature: checkout", "Alpha", "broken (invalid design.json)"]);
273
+ choose(canvas, "Español");
274
+ assert.deepEqual(system(), ["Design system", "Tokens del proyecto (design/system.md)", "Comentarios desactivados en este tablero", "Haz clic para ver el design system", "Funcionalidad: checkout", "Alpha", "broken (design.json no válido)"]);
275
+ assert.equal($(canvas, "gd-design").disabled, false, "the design list stays as it was");
276
+
277
+ const empty = await loadLanguage({ replies: { "/t/api/designs/alpha": replies["/t/api/designs/alpha"] }, stored: "es" });
278
+ assert.equal($(empty, "gd-empty").textContent, "Este diseño aún no tiene propuestas.");
279
+ choose(empty, "English");
280
+ assert.equal($(empty, "gd-empty").textContent, "This design has no artboards yet.");
281
+ });
282
+
283
+ test("languagechange re-resolves Match the browser, and leaves a saved choice alone", async () => {
284
+ const auto = await loadLanguage();
285
+ auto.navigator!.languages = ["es-419"];
286
+ auto.windowEvent("languagechange");
287
+ assert.equal(lang(auto), "es");
288
+ assert.equal(auto.navMode.textContent, "Navegando");
289
+ assert.deepEqual(auto.languageWrites(), [], "following the browser saves nothing");
290
+
291
+ const fixed = await loadLanguage({ stored: "en" });
292
+ fixed.navigator!.languages = ["es-419"];
293
+ fixed.windowEvent("languagechange");
294
+ assert.equal(lang(fixed), "en");
295
+ assert.equal(fixed.navMode.textContent, "Navigating");
296
+ });
297
+
298
+ // ---- agent-bound text stays English (S3)
299
+
300
+ test("Implement this in Spanish sends the same request and says it in Spanish", async () => {
301
+ const canvas = await loadLanguage({ stored: "es", replies: { "/t/api/designs/alpha/implement": { ok: true, slug: "alpha", file: "01-a.html", queued: false } } });
302
+ const [control] = withClass(boardsOf(canvas)[0], "gd-implement");
303
+ withClass(control, "gd-implement-start")[0].dispatch("click");
304
+ withClass(control, "gd-primary")[0].dispatch("click");
305
+ await settle();
306
+ assert.deepEqual(canvas.posts.at(-1), { url: "/t/api/designs/alpha/implement", body: { file: "01-a.html" } });
307
+ assert.equal($(canvas, "gd-toast").textContent, "Enviado: la sesión está implementando First ahora.");
308
+ });
309
+
310
+ test("a module's text view: Spanish per key with English fallback, nested keys, and session always English", () => {
311
+ const store = createStore();
312
+ const document = new FakeDocument();
313
+ const win = { addEventListener() {}, localStorage: { getItem: () => "es", setItem() {} }, navigator: { languages: ["en"] } };
314
+ const i18n = i18nInit({ win, doc: document, store }, { demo: { a: "A es", nested: { b: (n: number) => `${n} es` }, session: { ask: "pregunta" } }, html: {} }, () => {});
315
+ const T = i18n.text("demo", Object.freeze({ a: "A", c: "C", nested: Object.freeze({ b: (n: number) => `${n} en` }), session: Object.freeze({ ask: "Ask the agent" }) }));
316
+ assert.deepEqual([T.a, T.c, T.nested.b(2), T.session.ask], ["A", "C", "2 en", "Ask the agent"], "English before the language starts");
317
+ i18n.startLanguage();
318
+ assert.equal(store.state.language, "es");
319
+ assert.deepEqual([T.a, T.c, T.nested.b(2), T.session.ask], ["A es", "C", "2 es", "Ask the agent"]);
320
+ i18n.setLanguage("en");
321
+ assert.deepEqual([T.a, T.nested.b(2)], ["A", "2 en"]);
322
+ });
323
+
324
+ // ---- one catalog (S4, S8)
325
+
326
+ /** A module's English TEXT block, evaluated from its source. */
327
+ function englishText(module: string): Record<string, unknown> {
328
+ const source = read(`canvas-${module}.js`);
329
+ const start = source.indexOf("const TEXT = Object.freeze({");
330
+ assert.ok(start >= 0 && start < source.indexOf("export function init"), `canvas-${module}.js: one TEXT block before init`);
331
+ const block = source.slice(start + "const TEXT = ".length, source.indexOf("\n});", start) + 3);
332
+ return new Function(`return ${block}`)();
333
+ }
334
+
335
+ function sameShape(english: Record<string, unknown>, spanish: Record<string, unknown>, path: string) {
336
+ assert.deepEqual(Object.keys(spanish).sort(), Object.keys(english).filter((key) => key !== "session").sort(), `${path}: the same keys`);
337
+ for (const [key, value] of Object.entries(spanish)) {
338
+ const source = english[key];
339
+ if (typeof source === "function") {
340
+ assert.equal(typeof value, "function", `${path}.${key}`);
341
+ assert.equal((value as Function).length, source.length, `${path}.${key}: the same parameters`);
342
+ } else if (source && typeof source === "object") sameShape(source as Record<string, unknown>, value as Record<string, unknown>, `${path}.${key}`);
343
+ else assert.equal(typeof value, "string", `${path}.${key}`);
344
+ }
345
+ }
346
+
347
+ test("ES has every key of each covered module's TEXT, with the same parameters, and nothing else, never session", () => {
348
+ assert.deepEqual(COVERED, ["boards", "checks", "comments", "compare", "events", "export", "focus", "handoffs", "layout", "minimap", "parts", "popover", "rail", "sizes", "tokens"], "every module that shows text has a TEXT block");
349
+ assert.deepEqual(Object.keys(ES).filter((key) => key !== "html").sort(), [...COVERED].sort());
350
+ for (const module of COVERED) sameShape(englishText(module), ES[module as keyof typeof ES] as Record<string, unknown>, module);
351
+ assert.ok(!Object.hasOwn(ES, "session") && Object.values(ES).every((entry) => !Object.hasOwn(entry as object, "session")), "no session key");
352
+ assert.ok(Object.isFrozen(ES));
353
+ });
354
+
355
+ test("ES.html has exactly the keys index.html's data-i18n* attributes name", () => {
356
+ const html = read("index.html");
357
+ const keys = new Set([...html.matchAll(/\bdata-i18n(?:-[a-z-]+)?="([^"]+)"/g)].map((match) => match[1]));
358
+ assert.deepEqual(Object.keys(ES.html).sort(), [...keys].sort());
359
+ for (const match of html.matchAll(/\bdata-i18n-([a-z-]+)="/g)) assert.ok(["title", "aria-label", "placeholder", "alt"].includes(match[1]), match[1]);
360
+ // A data-i18n element holds only text: a child element would be wiped.
361
+ for (const match of html.matchAll(/<([a-z0-9]+)\s[^>]*\bdata-i18n="[^"]+"[^>]*>([^<]*)<\/([a-z0-9]+)>/g)) assert.equal(match[3], match[1], `${match[2]}: text only`);
362
+ assert.equal(html.match(/\bdata-i18n="/g)?.length, [...html.matchAll(/<([a-z0-9]+)\s[^>]*\bdata-i18n="[^"]+"[^>]*>([^<]*)<\/\1>/g)].length, "every data-i18n element holds only text");
363
+ });
364
+
365
+ test("the covered modules read their strings through ctx.i18n, and the language modules are allowlisted assets", () => {
366
+ for (const module of COVERED) {
367
+ const source = read(`canvas-${module}.js`);
368
+ const body = source.slice(source.indexOf("export function init"));
369
+ assert.match(body, new RegExp(`const T = ctx\\.i18n\\.text\\("${module}", TEXT\\);`), `canvas-${module}.js`);
370
+ assert.equal(body.match(/\bTEXT\b/g)?.length, 1, `canvas-${module}.js reads TEXT only through T`);
371
+ }
372
+ for (const name of ["canvas-i18n.js", "canvas-i18n-es.js"]) assert.equal(DESIGN_CANVAS_ASSETS[name], "text/javascript; charset=utf-8");
373
+ const i18n = read("canvas-i18n.js");
374
+ assert.ok(i18n.includes('"gentle-design:language"'));
375
+ assert.ok(!/state\.language(Choice)?\s*=(?!=)/.test(i18n), "store mutators only");
376
+ const boot = read("canvas-boot.js").replace(/\n\/\/ ?/g, " ");
377
+ assert.ok(boot.includes("relabel"), "canvas-boot.js documents the relabel rule");
378
+ });
379
+
380
+ // ---- every canvas string comes from the catalog (S4): a structural check over the modules and index.html
381
+
382
+ // Strings with letters that are no canvas text, each left out on purpose.
383
+ const NOT_TEXT = new Set([
384
+ // The keys the canvas compares event.key with.
385
+ "Escape", "Enter", "Tab", "Home", "End", "ArrowDown", "ArrowUp", "ArrowLeft", "ArrowRight",
386
+ "Shift", "Control", "Alt", "AltGraph", "Meta", "CapsLock", "NumLock", "ScrollLock", "Fn", "FnLock", "Hyper", "Super", "Symbol", "SymbolLock",
387
+ // Key caps, which read the same in both languages.
388
+ "Esc",
389
+ // An HTTP header and method, the DataTransfer type of dropped files, a link's rel, a CSS selector and a print rule.
390
+ "Content-Type", "POST", "Files", "noopener noreferrer", "button, a, input, select, textarea, iframe", "@page { size: px px; }",
391
+ // The product's name (the page title adds it after the design's).
392
+ "Gentle Design", "· Gentle Design",
393
+ // Errors for the developer, thrown only when the code itself is wrong.
394
+ "canvas: is exported by two modules", "cannot change",
395
+ ]);
396
+
397
+ /**
398
+ * The string literals of a module's code, comments left out: quoted strings, and each template literal's text with its
399
+ * interpolations blanked (the code inside them is read as code). Regular expression literals are skipped.
400
+ */
401
+ function literals(source: string): string[] {
402
+ const found: string[] = [];
403
+ let index = 0;
404
+ let previous = "";
405
+ const code = (end: string | null) => {
406
+ let depth = 0;
407
+ while (index < source.length) {
408
+ const char = source[index];
409
+ if (end && char === "}" && depth === 0) return;
410
+ if (source.startsWith("//", index)) index = source.indexOf("\n", index) === -1 ? source.length : source.indexOf("\n", index);
411
+ else if (source.startsWith("/*", index)) index = source.indexOf("*/", index) + 2;
412
+ else if (char === '"' || char === "'") {
413
+ let text = "";
414
+ for (index += 1; source[index] !== char; index += 1) text += source[index] === "\\" ? source[++index] : source[index];
415
+ index += 1;
416
+ found.push(text);
417
+ previous = "a";
418
+ } else if (char === "`") {
419
+ let text = "";
420
+ for (index += 1; source[index] !== "`"; ) {
421
+ if (source.startsWith("${", index)) {
422
+ index += 2;
423
+ code("}");
424
+ index += 1;
425
+ text += " ";
426
+ } else text += source[index] === "\\" ? source[(index += 2) - 1] : source[index++];
427
+ }
428
+ index += 1;
429
+ found.push(text);
430
+ previous = "a";
431
+ } else if (char === "/" && (previous === "" || "(,=:[!&|?{};+".includes(previous))) {
432
+ // A regular expression: up to its closing slash, past classes and escapes.
433
+ let inClass = false;
434
+ for (index += 1; inClass || source[index] !== "/"; index += 1) {
435
+ if (source[index] === "\\") index += 1;
436
+ else if (source[index] === "[") inClass = true;
437
+ else if (source[index] === "]") inClass = false;
438
+ }
439
+ index += 1;
440
+ previous = "a";
441
+ } else {
442
+ if (char === "{") depth += 1;
443
+ else if (char === "}") depth -= 1;
444
+ if (!/\s/.test(char)) previous = /[\w$)\]]/.test(char) ? "a" : char;
445
+ if (/\w/.test(char) && /^(return|typeof|case)\b/.test(source.slice(index)) && !/\w/.test(source[index - 1] ?? "")) {
446
+ const word = /^\w+/.exec(source.slice(index))![0];
447
+ index += word.length;
448
+ previous = "(";
449
+ continue;
450
+ }
451
+ index += 1;
452
+ }
453
+ }
454
+ };
455
+ code(null);
456
+ return found;
457
+ }
458
+
459
+ /**
460
+ * Whether a literal reads as words a person sees: a capitalized word, or two words in a row, once code-like tokens
461
+ * (class names, file names, message types, paths, selectors) are taken out. A single lowercase word is not caught; the
462
+ * per-surface tests in tests/design-canvas-i18n*.test.ts cover those.
463
+ */
464
+ function isText(literal: string) {
465
+ const words = literal.split(/\s+/).filter((token) => token && !/[-_:#./=*>[\]()@]|^\d|^[a-z]+[A-Z]/.test(token.replace(/[.,;?!…]+$/, ""))).join(" ");
466
+ return !NOT_TEXT.has(literal.trim()) && (/\p{Lu}\p{Ll}+/u.test(words) || /\p{Ll}{2,}[,;]? \p{Ll}{2,}/u.test(words));
467
+ }
468
+
469
+ test("every visible string of the canvas modules comes from their TEXT block: no word outside it", () => {
470
+ assert.deepEqual(literals('a("Hi", `x ${b ? `Inner text` : "y"} z`, /"no"/g); // "Gone"'), ["Hi", "Inner text", "y", "x z"], "the literal reader");
471
+ assert.deepEqual(["Sent", "the session did not take it.", "gd-check gd-check-fail", "api/designs/", "Escape", "#i-target", "gd:pins", "image/png"].map(isText), [true, true, false, false, false, false, false, false]);
472
+ const outside: string[] = [];
473
+ for (const name of MODULE_FILES.filter((file) => file !== "canvas-i18n-es.js")) {
474
+ const source = read(name);
475
+ const start = source.indexOf("const TEXT = Object.freeze({");
476
+ const code = start < 0 ? source : source.slice(0, start) + source.slice(source.indexOf("\n});", start) + 4);
477
+ for (const literal of literals(code)) if (isText(literal)) outside.push(`${name}: ${literal}`);
478
+ }
479
+ assert.deepEqual(outside, []);
480
+ });
481
+
482
+ /** index.html's text and words in title, aria-label, placeholder and alt, script, style and the icon sprite left out, each with whether it is keyed. */
483
+ function markupStrings(html: string) {
484
+ const body = html.slice(html.indexOf("<body>")).replace(/<svg id="gd-sprite"[^]*?<\/svg>/, "").replace(/<(script|style)\b[^]*?<\/\1>/g, "");
485
+ const strings: Array<{ text: string; keyed: boolean }> = [];
486
+ const open: string[] = [];
487
+ for (const [, closing, tag, attributes, text] of body.matchAll(/<(\/?)([a-z0-9]+)([^>]*)>|([^<]+)/g)) {
488
+ if (text !== undefined) {
489
+ const words = text.replace(/&[a-z]+;/g, "").trim();
490
+ if (/\p{L}{2,}/u.test(words) && !NOT_TEXT.has(words)) strings.push({ text: words, keyed: /\bdata-i18n="/.test(open.at(-1) ?? "") });
491
+ continue;
492
+ }
493
+ if (closing) {
494
+ open.pop();
495
+ continue;
496
+ }
497
+ for (const name of ["title", "aria-label", "placeholder", "alt"]) {
498
+ const value = new RegExp(`\\s${name}="([^"]*)"`).exec(attributes)?.[1];
499
+ if (value && /\p{L}{2,}/u.test(value)) strings.push({ text: `${name}=${value}`, keyed: new RegExp(`\\sdata-i18n-${name}="`).test(attributes) });
500
+ }
501
+ if (!attributes.endsWith("/") && !["meta", "link", "input", "img", "br", "use"].includes(tag)) open.push(attributes);
502
+ }
503
+ return strings;
504
+ }
505
+
506
+ test("every word index.html shows, as text or in a title, aria-label, placeholder or alt, is keyed for the language", () => {
507
+ const sample = markupStrings('<body><p data-i18n="a">One</p><p>Two <span id="x">3</span></p><b title="Tip" data-i18n-title="t">&minus;</b><img alt="Pic"><kbd>Esc</kbd></body>');
508
+ assert.deepEqual(sample, [{ text: "One", keyed: true }, { text: "Two", keyed: false }, { text: "title=Tip", keyed: true }, { text: "alt=Pic", keyed: false }], "the markup reader");
509
+ assert.deepEqual(markupStrings(read("index.html")).filter((entry) => !entry.keyed).map((entry) => entry.text), []);
510
+ });
511
+
512
+ test("the docs describe the language in Settings: the choices, the default, where it is saved and what stays as written", () => {
513
+ const docs = readFileSync(fileURLToPath(new URL("../docs/gentle-shell.md", import.meta.url)), "utf8");
514
+ const section = docs.slice(docs.indexOf("### Gentle Design"));
515
+ const start = section.indexOf("- **Tool rail**");
516
+ const rail = section.slice(start, section.indexOf("\n", start));
517
+ for (const part of ["**Español**", "**English**", "**Match the browser**", "browser's language", "`gentle-design:language`", "without reloading", "comment text", "artboard titles", "file names", "Messages to the agent stay in English"]) {
518
+ assert.ok(rail.includes(part), `the rail entry mentions ${part}`);
519
+ }
520
+ // Every surface switches; what goes to the agent, the accessibility findings included, stays English.
521
+ for (const part of ["every surface", "Comments panel", "comment box", "**Partial implementations**", "token inspector", "**Quality**", "**Ask the agent to fix** prefills", "findings"]) {
522
+ assert.ok(rail.includes(part), `the rail entry mentions ${part}`);
523
+ }
524
+ const quality = section.slice(section.indexOf("- **Quality**"), section.indexOf("\n", section.indexOf("- **Quality**")));
525
+ assert.ok(quality.includes("in the canvas language") && !quality.includes("(in English)"), "Quality shows each finding in the canvas language");
526
+ });