@bendyline/gilde 0.3.3 → 0.3.5

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 (489) hide show
  1. package/authoring/page-demo-bootstrap.js +151 -7
  2. package/data/craftbook-templates/au/audit-evidence-pack/manifest.json +28 -0
  3. package/data/craftbook-templates/au/audit-evidence-pack/versions/1.0.0/craftbook.json +197 -0
  4. package/data/craftbook-templates/au/audit-evidence-pack/versions/1.0.0/test.json +101 -0
  5. package/data/craftbook-templates/index.json +1 -1
  6. package/data/craftbook-templates/raw-index.json +1 -1
  7. package/data/craftbook-templates/re/reorder-run/manifest.json +28 -0
  8. package/data/craftbook-templates/re/reorder-run/versions/1.0.0/craftbook.json +205 -0
  9. package/data/craftbook-templates/re/reorder-run/versions/1.0.0/test.json +125 -0
  10. package/data/craftbook-templates/re/review-reply-batch/manifest.json +27 -0
  11. package/data/craftbook-templates/re/review-reply-batch/versions/1.0.0/craftbook.json +208 -0
  12. package/data/craftbook-templates/re/review-reply-batch/versions/1.0.0/test.json +127 -0
  13. package/data/craftbook-templates/ru/run-of-show/manifest.json +29 -0
  14. package/data/craftbook-templates/ru/run-of-show/versions/1.0.0/craftbook.json +205 -0
  15. package/data/craftbook-templates/ru/run-of-show/versions/1.0.0/test.json +111 -0
  16. package/data/craftbook-templates/st/structured-interview-kit/manifest.json +28 -0
  17. package/data/craftbook-templates/st/structured-interview-kit/versions/1.0.0/craftbook.json +213 -0
  18. package/data/craftbook-templates/st/structured-interview-kit/versions/1.0.0/test.json +123 -0
  19. package/data/craftbook-templates/we/weekly-schedule-draft/manifest.json +28 -0
  20. package/data/craftbook-templates/we/weekly-schedule-draft/versions/1.0.0/craftbook.json +213 -0
  21. package/data/craftbook-templates/we/weekly-schedule-draft/versions/1.0.0/test.json +119 -0
  22. package/data/gezel-templates/ac/account-manager/manifest.json +21 -0
  23. package/data/gezel-templates/ac/account-manager/versions/1.0.0/about.md +23 -0
  24. package/data/gezel-templates/ac/account-manager/versions/1.0.0/manifest.json +10 -0
  25. package/data/gezel-templates/bo/bookkeeper/manifest.json +21 -0
  26. package/data/gezel-templates/bo/bookkeeper/versions/1.0.0/about.md +29 -0
  27. package/data/gezel-templates/bo/bookkeeper/versions/1.0.0/manifest.json +10 -0
  28. package/data/gezel-templates/ca/campaign-manager/manifest.json +21 -0
  29. package/data/gezel-templates/ca/campaign-manager/versions/1.0.0/about.md +23 -0
  30. package/data/gezel-templates/ca/campaign-manager/versions/1.0.0/manifest.json +10 -0
  31. package/data/gezel-templates/co/compliance-officer/manifest.json +21 -0
  32. package/data/gezel-templates/co/compliance-officer/versions/1.0.0/about.md +20 -0
  33. package/data/gezel-templates/co/compliance-officer/versions/1.0.0/manifest.json +10 -0
  34. package/data/gezel-templates/es/estimator/manifest.json +21 -0
  35. package/data/gezel-templates/es/estimator/versions/1.0.0/about.md +25 -0
  36. package/data/gezel-templates/es/estimator/versions/1.0.0/manifest.json +10 -0
  37. package/data/gezel-templates/index.json +1 -1
  38. package/data/gezel-templates/ma/maaltijdplanner/versions/1.0.2/about.md +23 -0
  39. package/data/gezel-templates/ma/maaltijdplanner/versions/1.0.2/manifest.json +10 -0
  40. package/data/gezel-templates/ma/managing-editor/manifest.json +21 -0
  41. package/data/gezel-templates/ma/managing-editor/versions/1.0.0/about.md +22 -0
  42. package/data/gezel-templates/ma/managing-editor/versions/1.0.0/manifest.json +10 -0
  43. package/data/gezel-templates/raw-index.json +1 -1
  44. package/data/gezel-templates/re/recruiter/manifest.json +21 -0
  45. package/data/gezel-templates/re/recruiter/versions/1.0.0/about.md +27 -0
  46. package/data/gezel-templates/re/recruiter/versions/1.0.0/manifest.json +10 -0
  47. package/data/gezel-templates/sh/shift-scheduler/manifest.json +21 -0
  48. package/data/gezel-templates/sh/shift-scheduler/versions/1.0.0/about.md +23 -0
  49. package/data/gezel-templates/sh/shift-scheduler/versions/1.0.0/manifest.json +10 -0
  50. package/data/gezel-templates/st/stock-keeper/manifest.json +21 -0
  51. package/data/gezel-templates/st/stock-keeper/versions/1.0.0/about.md +20 -0
  52. package/data/gezel-templates/st/stock-keeper/versions/1.0.0/manifest.json +10 -0
  53. package/data/gezel-templates/su/support-lead/manifest.json +21 -0
  54. package/data/gezel-templates/su/support-lead/versions/1.0.0/about.md +22 -0
  55. package/data/gezel-templates/su/support-lead/versions/1.0.0/manifest.json +10 -0
  56. package/data/gezel-templates/tr/training-coordinator/manifest.json +21 -0
  57. package/data/gezel-templates/tr/training-coordinator/versions/1.0.0/about.md +20 -0
  58. package/data/gezel-templates/tr/training-coordinator/versions/1.0.0/manifest.json +10 -0
  59. package/data/project-types/bo/books-and-close/art.json +17 -0
  60. package/data/project-types/bo/books-and-close/logo.webp +0 -0
  61. package/data/project-types/bo/books-and-close/manifest.json +26 -0
  62. package/data/project-types/bo/books-and-close/versions/1.0.0/about.md +16 -0
  63. package/data/project-types/bo/books-and-close/versions/1.0.0/close.json +8 -0
  64. package/data/project-types/bo/books-and-close/versions/1.0.0/ledger.json +5 -0
  65. package/data/project-types/bo/books-and-close/versions/1.0.0/manifest.json +496 -0
  66. package/data/project-types/bo/books-and-close/versions/1.0.0/mission.md +5 -0
  67. package/data/project-types/bo/books-and-close/versions/1.0.0/pages/books/application.js +314 -0
  68. package/data/project-types/bo/books-and-close/versions/1.0.0/pages/books/demo-chat.js +515 -0
  69. package/data/project-types/bo/books-and-close/versions/1.0.0/pages/books/index.html +821 -0
  70. package/data/project-types/ca/campaign-room/art.json +17 -0
  71. package/data/project-types/ca/campaign-room/logo.webp +0 -0
  72. package/data/project-types/ca/campaign-room/manifest.json +21 -0
  73. package/data/project-types/ca/campaign-room/versions/1.0.0/about.md +13 -0
  74. package/data/project-types/ca/campaign-room/versions/1.0.0/assets.json +11 -0
  75. package/data/project-types/ca/campaign-room/versions/1.0.0/campaign.json +13 -0
  76. package/data/project-types/ca/campaign-room/versions/1.0.0/manifest.json +610 -0
  77. package/data/project-types/ca/campaign-room/versions/1.0.0/mission.md +6 -0
  78. package/data/project-types/ca/campaign-room/versions/1.0.0/pages/campaign/application.js +269 -0
  79. package/data/project-types/ca/campaign-room/versions/1.0.0/pages/campaign/demo-chat.js +290 -0
  80. package/data/project-types/ca/campaign-room/versions/1.0.0/pages/campaign/index.html +584 -0
  81. package/data/project-types/ca/campaign-room/versions/1.0.0/results.json +4 -0
  82. package/data/project-types/ca/caregiving-binder/versions/1.1.4/about.md +7 -0
  83. package/data/project-types/ca/caregiving-binder/versions/1.1.4/care.json +4 -0
  84. package/data/project-types/ca/caregiving-binder/versions/1.1.4/manifest.json +232 -0
  85. package/data/project-types/ca/caregiving-binder/versions/1.1.4/meds.json +8 -0
  86. package/data/project-types/ca/caregiving-binder/versions/1.1.4/mission.md +7 -0
  87. package/data/project-types/ca/caregiving-binder/versions/1.1.4/pages/dashboard/application.js +78 -0
  88. package/data/project-types/ca/caregiving-binder/versions/1.1.4/pages/dashboard/demo-chat.js +224 -0
  89. package/data/project-types/ca/caregiving-binder/versions/1.1.4/pages/dashboard/index.html +279 -0
  90. package/data/project-types/ca/cash-flow-planner/art.json +17 -0
  91. package/data/project-types/ca/cash-flow-planner/logo.webp +0 -0
  92. package/data/project-types/ca/cash-flow-planner/manifest.json +25 -0
  93. package/data/project-types/ca/cash-flow-planner/versions/1.0.0/about.md +15 -0
  94. package/data/project-types/ca/cash-flow-planner/versions/1.0.0/cashflow.json +11 -0
  95. package/data/project-types/ca/cash-flow-planner/versions/1.0.0/manifest.json +443 -0
  96. package/data/project-types/ca/cash-flow-planner/versions/1.0.0/mission.md +6 -0
  97. package/data/project-types/ca/cash-flow-planner/versions/1.0.0/pages/forecast/application.js +314 -0
  98. package/data/project-types/ca/cash-flow-planner/versions/1.0.0/pages/forecast/demo-chat.js +517 -0
  99. package/data/project-types/ca/cash-flow-planner/versions/1.0.0/pages/forecast/index.html +812 -0
  100. package/data/project-types/ch/checkers/versions/1.2.7/about.md +9 -0
  101. package/data/project-types/ch/checkers/versions/1.2.7/game.json +77 -0
  102. package/data/project-types/ch/checkers/versions/1.2.7/manifest.json +182 -0
  103. package/data/project-types/ch/checkers/versions/1.2.7/mission.md +9 -0
  104. package/data/project-types/ch/checkers/versions/1.2.7/pages/board/application.js +31 -0
  105. package/data/project-types/ch/checkers/versions/1.2.7/pages/board/demo-chat.js +252 -0
  106. package/data/project-types/ch/checkers/versions/1.2.7/pages/board/index.html +1330 -0
  107. package/data/project-types/ch/chess/versions/1.0.9/about.md +9 -0
  108. package/data/project-types/ch/chess/versions/1.0.9/game.json +127 -0
  109. package/data/project-types/ch/chess/versions/1.0.9/manifest.json +196 -0
  110. package/data/project-types/ch/chess/versions/1.0.9/mission.md +8 -0
  111. package/data/project-types/ch/chess/versions/1.0.9/pages/board/application.js +31 -0
  112. package/data/project-types/ch/chess/versions/1.0.9/pages/board/demo-chat.js +359 -0
  113. package/data/project-types/ch/chess/versions/1.0.9/pages/board/index.html +1141 -0
  114. package/data/project-types/cl/client-delivery/art.json +17 -0
  115. package/data/project-types/cl/client-delivery/logo.webp +0 -0
  116. package/data/project-types/cl/client-delivery/manifest.json +23 -0
  117. package/data/project-types/cl/client-delivery/versions/1.0.0/about.md +13 -0
  118. package/data/project-types/cl/client-delivery/versions/1.0.0/manifest.json +376 -0
  119. package/data/project-types/cl/client-delivery/versions/1.0.0/milestones.json +10 -0
  120. package/data/project-types/cl/client-delivery/versions/1.0.0/mission.md +5 -0
  121. package/data/project-types/cl/client-delivery/versions/1.0.0/pages/delivery/application.js +176 -0
  122. package/data/project-types/cl/client-delivery/versions/1.0.0/pages/delivery/demo-chat.js +185 -0
  123. package/data/project-types/cl/client-delivery/versions/1.0.0/pages/delivery/index.html +546 -0
  124. package/data/project-types/cl/client-delivery/versions/1.0.0/projects.json +10 -0
  125. package/data/project-types/co/compliance-register/art.json +17 -0
  126. package/data/project-types/co/compliance-register/logo.webp +0 -0
  127. package/data/project-types/co/compliance-register/manifest.json +23 -0
  128. package/data/project-types/co/compliance-register/versions/1.0.0/about.md +12 -0
  129. package/data/project-types/co/compliance-register/versions/1.0.0/evidence.json +4 -0
  130. package/data/project-types/co/compliance-register/versions/1.0.0/manifest.json +361 -0
  131. package/data/project-types/co/compliance-register/versions/1.0.0/mission.md +5 -0
  132. package/data/project-types/co/compliance-register/versions/1.0.0/obligations.json +9 -0
  133. package/data/project-types/co/compliance-register/versions/1.0.0/pages/register/application.js +152 -0
  134. package/data/project-types/co/compliance-register/versions/1.0.0/pages/register/demo-chat.js +156 -0
  135. package/data/project-types/co/compliance-register/versions/1.0.0/pages/register/index.html +355 -0
  136. package/data/project-types/co/content-studio/art.json +17 -0
  137. package/data/project-types/co/content-studio/logo.webp +0 -0
  138. package/data/project-types/co/content-studio/manifest.json +23 -0
  139. package/data/project-types/co/content-studio/versions/1.0.0/about.md +12 -0
  140. package/data/project-types/co/content-studio/versions/1.0.0/calendar.json +10 -0
  141. package/data/project-types/co/content-studio/versions/1.0.0/manifest.json +541 -0
  142. package/data/project-types/co/content-studio/versions/1.0.0/mission.md +6 -0
  143. package/data/project-types/co/content-studio/versions/1.0.0/pages/studio/application.js +226 -0
  144. package/data/project-types/co/content-studio/versions/1.0.0/pages/studio/demo-chat.js +247 -0
  145. package/data/project-types/co/content-studio/versions/1.0.0/pages/studio/index.html +436 -0
  146. package/data/project-types/co/content-studio/versions/1.0.0/pieces.json +12 -0
  147. package/data/project-types/cu/customer-voice/art.json +17 -0
  148. package/data/project-types/cu/customer-voice/logo.webp +0 -0
  149. package/data/project-types/cu/customer-voice/manifest.json +21 -0
  150. package/data/project-types/cu/customer-voice/versions/1.0.0/about.md +15 -0
  151. package/data/project-types/cu/customer-voice/versions/1.0.0/actions.json +9 -0
  152. package/data/project-types/cu/customer-voice/versions/1.0.0/feedback.json +4 -0
  153. package/data/project-types/cu/customer-voice/versions/1.0.0/manifest.json +512 -0
  154. package/data/project-types/cu/customer-voice/versions/1.0.0/mission.md +6 -0
  155. package/data/project-types/cu/customer-voice/versions/1.0.0/pages/voice/application.js +173 -0
  156. package/data/project-types/cu/customer-voice/versions/1.0.0/pages/voice/demo-chat.js +276 -0
  157. package/data/project-types/cu/customer-voice/versions/1.0.0/pages/voice/index.html +781 -0
  158. package/data/project-types/cu/customer-voice/versions/1.0.0/themes.json +8 -0
  159. package/data/project-types/da/data-analysis/versions/1.0.2/about.md +20 -0
  160. package/data/project-types/da/data-analysis/versions/1.0.2/manifest.json +70 -0
  161. package/data/project-types/da/data-analysis/versions/1.0.2/mission.md +4 -0
  162. package/data/project-types/da/data-analysis/versions/1.0.2/pages/analytics.js +63 -0
  163. package/data/project-types/da/data-analysis/versions/1.0.2/pages/application.js +31 -0
  164. package/data/project-types/da/data-analysis/versions/1.0.2/pages/dashboard.css +86 -0
  165. package/data/project-types/da/data-analysis/versions/1.0.2/pages/dashboard.js +160 -0
  166. package/data/project-types/da/data-analysis/versions/1.0.2/pages/datasets.js +44 -0
  167. package/data/project-types/da/data-analysis/versions/1.0.2/pages/demo-chat.js +181 -0
  168. package/data/project-types/da/data-analysis/versions/1.0.2/pages/demo.js +27 -0
  169. package/data/project-types/da/data-analysis/versions/1.0.2/pages/index.html +120 -0
  170. package/data/project-types/da/data-analysis/versions/1.0.2/pages/insights.js +122 -0
  171. package/data/project-types/de/design-scheme/versions/1.0.4/about.md +6 -0
  172. package/data/project-types/de/design-scheme/versions/1.0.4/manifest.json +95 -0
  173. package/data/project-types/de/design-scheme/versions/1.0.4/mission.md +3 -0
  174. package/data/project-types/de/design-scheme/versions/1.0.4/pages/gallery/application.js +56 -0
  175. package/data/project-types/de/design-scheme/versions/1.0.4/pages/gallery/demo-chat.js +236 -0
  176. package/data/project-types/de/design-scheme/versions/1.0.4/pages/gallery/index.html +151 -0
  177. package/data/project-types/de/design-scheme/versions/1.0.4/schemes/index.json +9 -0
  178. package/data/project-types/de/design-scheme/versions/1.0.4/schemes/warm-dusk.json +4 -0
  179. package/data/project-types/ev/event-desk/art.json +17 -0
  180. package/data/project-types/ev/event-desk/logo.webp +0 -0
  181. package/data/project-types/ev/event-desk/manifest.json +23 -0
  182. package/data/project-types/ev/event-desk/versions/1.0.0/about.md +14 -0
  183. package/data/project-types/ev/event-desk/versions/1.0.0/budget.json +5 -0
  184. package/data/project-types/ev/event-desk/versions/1.0.0/event.json +12 -0
  185. package/data/project-types/ev/event-desk/versions/1.0.0/guests.json +9 -0
  186. package/data/project-types/ev/event-desk/versions/1.0.0/manifest.json +785 -0
  187. package/data/project-types/ev/event-desk/versions/1.0.0/mission.md +7 -0
  188. package/data/project-types/ev/event-desk/versions/1.0.0/pages/desk/application.js +915 -0
  189. package/data/project-types/ev/event-desk/versions/1.0.0/pages/desk/demo-chat.js +229 -0
  190. package/data/project-types/ev/event-desk/versions/1.0.0/pages/desk/index.html +817 -0
  191. package/data/project-types/ev/event-desk/versions/1.0.0/vendors.json +10 -0
  192. package/data/project-types/ev/event-desk/versions/1.0.0/venues.json +11 -0
  193. package/data/project-types/ev/event-planner/versions/1.0.5/about.md +7 -0
  194. package/data/project-types/ev/event-planner/versions/1.0.5/budget.json +5 -0
  195. package/data/project-types/ev/event-planner/versions/1.0.5/guests.json +10 -0
  196. package/data/project-types/ev/event-planner/versions/1.0.5/manifest.json +260 -0
  197. package/data/project-types/ev/event-planner/versions/1.0.5/mission.md +6 -0
  198. package/data/project-types/ev/event-planner/versions/1.0.5/pages/dashboard/application.js +133 -0
  199. package/data/project-types/ev/event-planner/versions/1.0.5/pages/dashboard/demo-chat.js +231 -0
  200. package/data/project-types/ev/event-planner/versions/1.0.5/pages/dashboard/index.html +250 -0
  201. package/data/project-types/fi/fitness-coach/versions/1.1.2/about.md +8 -0
  202. package/data/project-types/fi/fitness-coach/versions/1.1.2/craftbooks/training-recap.json +34 -0
  203. package/data/project-types/fi/fitness-coach/versions/1.1.2/manifest.json +249 -0
  204. package/data/project-types/fi/fitness-coach/versions/1.1.2/mission.md +7 -0
  205. package/data/project-types/fi/fitness-coach/versions/1.1.2/pages/dashboard/application.js +48 -0
  206. package/data/project-types/fi/fitness-coach/versions/1.1.2/pages/dashboard/demo-chat.js +250 -0
  207. package/data/project-types/fi/fitness-coach/versions/1.1.2/pages/dashboard/index.html +375 -0
  208. package/data/project-types/fi/fitness-coach/versions/1.1.2/training.json +6 -0
  209. package/data/project-types/fl/flashcards/manifest.json +3 -1
  210. package/data/project-types/fl/flashcards/versions/1.2.3/about.md +8 -0
  211. package/data/project-types/fl/flashcards/versions/1.2.3/deck.json +7 -0
  212. package/data/project-types/fl/flashcards/versions/1.2.3/manifest.json +243 -0
  213. package/data/project-types/fl/flashcards/versions/1.2.3/mission.md +6 -0
  214. package/data/project-types/fl/flashcards/versions/1.2.3/pages/review/application.js +52 -0
  215. package/data/project-types/fl/flashcards/versions/1.2.3/pages/review/index.html +475 -0
  216. package/data/project-types/fl/flashcards/versions/1.2.4/about.md +8 -0
  217. package/data/project-types/fl/flashcards/versions/1.2.4/deck.json +7 -0
  218. package/data/project-types/fl/flashcards/versions/1.2.4/manifest.json +243 -0
  219. package/data/project-types/fl/flashcards/versions/1.2.4/mission.md +6 -0
  220. package/data/project-types/fl/flashcards/versions/1.2.4/pages/review/application.js +52 -0
  221. package/data/project-types/fl/flashcards/versions/1.2.4/pages/review/demo-chat.js +331 -0
  222. package/data/project-types/fl/flashcards/versions/1.2.4/pages/review/index.html +560 -0
  223. package/data/project-types/fr/freelance-office/versions/1.0.5/about.md +6 -0
  224. package/data/project-types/fr/freelance-office/versions/1.0.5/invoices.json +9 -0
  225. package/data/project-types/fr/freelance-office/versions/1.0.5/manifest.json +215 -0
  226. package/data/project-types/fr/freelance-office/versions/1.0.5/mission.md +6 -0
  227. package/data/project-types/fr/freelance-office/versions/1.0.5/pages/dashboard/application.js +110 -0
  228. package/data/project-types/fr/freelance-office/versions/1.0.5/pages/dashboard/demo-chat.js +244 -0
  229. package/data/project-types/fr/freelance-office/versions/1.0.5/pages/dashboard/index.html +232 -0
  230. package/data/project-types/fu/fundraiser-hq/versions/1.0.5/about.md +7 -0
  231. package/data/project-types/fu/fundraiser-hq/versions/1.0.5/donations.json +7 -0
  232. package/data/project-types/fu/fundraiser-hq/versions/1.0.5/manifest.json +175 -0
  233. package/data/project-types/fu/fundraiser-hq/versions/1.0.5/mission.md +6 -0
  234. package/data/project-types/fu/fundraiser-hq/versions/1.0.5/pages/dashboard/application.js +74 -0
  235. package/data/project-types/fu/fundraiser-hq/versions/1.0.5/pages/dashboard/demo-chat.js +171 -0
  236. package/data/project-types/fu/fundraiser-hq/versions/1.0.5/pages/dashboard/index.html +208 -0
  237. package/data/project-types/go/go/versions/1.0.7/about.md +9 -0
  238. package/data/project-types/go/go/versions/1.0.7/game.json +103 -0
  239. package/data/project-types/go/go/versions/1.0.7/manifest.json +182 -0
  240. package/data/project-types/go/go/versions/1.0.7/mission.md +8 -0
  241. package/data/project-types/go/go/versions/1.0.7/pages/board/application.js +31 -0
  242. package/data/project-types/go/go/versions/1.0.7/pages/board/demo-chat.js +302 -0
  243. package/data/project-types/go/go/versions/1.0.7/pages/board/index.html +943 -0
  244. package/data/project-types/gr/grants-and-proposals/art.json +17 -0
  245. package/data/project-types/gr/grants-and-proposals/logo.webp +0 -0
  246. package/data/project-types/gr/grants-and-proposals/manifest.json +20 -0
  247. package/data/project-types/gr/grants-and-proposals/versions/1.0.0/about.md +14 -0
  248. package/data/project-types/gr/grants-and-proposals/versions/1.0.0/manifest.json +549 -0
  249. package/data/project-types/gr/grants-and-proposals/versions/1.0.0/mission.md +6 -0
  250. package/data/project-types/gr/grants-and-proposals/versions/1.0.0/opportunities.json +12 -0
  251. package/data/project-types/gr/grants-and-proposals/versions/1.0.0/pages/grants/application.js +230 -0
  252. package/data/project-types/gr/grants-and-proposals/versions/1.0.0/pages/grants/demo-chat.js +197 -0
  253. package/data/project-types/gr/grants-and-proposals/versions/1.0.0/pages/grants/index.html +453 -0
  254. package/data/project-types/gr/grants-and-proposals/versions/1.0.0/requirements.json +8 -0
  255. package/data/project-types/hi/hiring-desk/art.json +17 -0
  256. package/data/project-types/hi/hiring-desk/logo.webp +0 -0
  257. package/data/project-types/hi/hiring-desk/manifest.json +22 -0
  258. package/data/project-types/hi/hiring-desk/versions/1.0.0/about.md +20 -0
  259. package/data/project-types/hi/hiring-desk/versions/1.0.0/candidates.json +12 -0
  260. package/data/project-types/hi/hiring-desk/versions/1.0.0/feedback.json +4 -0
  261. package/data/project-types/hi/hiring-desk/versions/1.0.0/manifest.json +428 -0
  262. package/data/project-types/hi/hiring-desk/versions/1.0.0/mission.md +5 -0
  263. package/data/project-types/hi/hiring-desk/versions/1.0.0/pages/desk/application.js +231 -0
  264. package/data/project-types/hi/hiring-desk/versions/1.0.0/pages/desk/demo-chat.js +231 -0
  265. package/data/project-types/hi/hiring-desk/versions/1.0.0/pages/desk/index.html +476 -0
  266. package/data/project-types/hi/hiring-desk/versions/1.0.0/roles.json +10 -0
  267. package/data/project-types/ho/household-budget/versions/1.0.6/about.md +6 -0
  268. package/data/project-types/ho/household-budget/versions/1.0.6/ledger.json +5 -0
  269. package/data/project-types/ho/household-budget/versions/1.0.6/manifest.json +191 -0
  270. package/data/project-types/ho/household-budget/versions/1.0.6/mission.md +5 -0
  271. package/data/project-types/ho/household-budget/versions/1.0.6/pages/dashboard/application.js +62 -0
  272. package/data/project-types/ho/household-budget/versions/1.0.6/pages/dashboard/demo-chat.js +207 -0
  273. package/data/project-types/ho/household-budget/versions/1.0.6/pages/dashboard/index.html +298 -0
  274. package/data/project-types/ho/household-manual/versions/1.0.5/about.md +7 -0
  275. package/data/project-types/ho/household-manual/versions/1.0.5/manifest.json +236 -0
  276. package/data/project-types/ho/household-manual/versions/1.0.5/mission.md +8 -0
  277. package/data/project-types/ho/household-manual/versions/1.0.5/pages/dashboard/application.js +125 -0
  278. package/data/project-types/ho/household-manual/versions/1.0.5/pages/dashboard/demo-chat.js +178 -0
  279. package/data/project-types/ho/household-manual/versions/1.0.5/pages/dashboard/index.html +250 -0
  280. package/data/project-types/ho/household-manual/versions/1.0.5/systems.json +8 -0
  281. package/data/project-types/im/image-feed/versions/1.0.4/about.md +21 -0
  282. package/data/project-types/im/image-feed/versions/1.0.4/manifest.json +330 -0
  283. package/data/project-types/im/image-feed/versions/1.0.4/mission.md +10 -0
  284. package/data/project-types/im/image-feed/versions/1.0.4/pages/gallery/application.js +32 -0
  285. package/data/project-types/im/image-feed/versions/1.0.4/pages/gallery/demo-chat.js +269 -0
  286. package/data/project-types/im/image-feed/versions/1.0.4/pages/gallery/index.html +800 -0
  287. package/data/project-types/im/image-feed/versions/1.0.4/posts/index.json +4 -0
  288. package/data/project-types/im/image-feed/versions/1.0.4/style-guide.md +24 -0
  289. package/data/project-types/in/inventory-reorder/art.json +17 -0
  290. package/data/project-types/in/inventory-reorder/logo.webp +0 -0
  291. package/data/project-types/in/inventory-reorder/manifest.json +22 -0
  292. package/data/project-types/in/inventory-reorder/versions/1.0.0/about.md +12 -0
  293. package/data/project-types/in/inventory-reorder/versions/1.0.0/items.json +9 -0
  294. package/data/project-types/in/inventory-reorder/versions/1.0.0/manifest.json +381 -0
  295. package/data/project-types/in/inventory-reorder/versions/1.0.0/mission.md +6 -0
  296. package/data/project-types/in/inventory-reorder/versions/1.0.0/orders.json +10 -0
  297. package/data/project-types/in/inventory-reorder/versions/1.0.0/pages/stock/application.js +217 -0
  298. package/data/project-types/in/inventory-reorder/versions/1.0.0/pages/stock/demo-chat.js +200 -0
  299. package/data/project-types/in/inventory-reorder/versions/1.0.0/pages/stock/index.html +321 -0
  300. package/data/project-types/in/inventory-reorder/versions/1.0.0/pages/stock/rules.js +665 -0
  301. package/data/project-types/index.json +1 -1
  302. package/data/project-types/jo/job-hunt/versions/1.0.6/about.md +10 -0
  303. package/data/project-types/jo/job-hunt/versions/1.0.6/activity.json +4 -0
  304. package/data/project-types/jo/job-hunt/versions/1.0.6/manifest.json +296 -0
  305. package/data/project-types/jo/job-hunt/versions/1.0.6/mission.md +9 -0
  306. package/data/project-types/jo/job-hunt/versions/1.0.6/pages/dashboard/application.js +120 -0
  307. package/data/project-types/jo/job-hunt/versions/1.0.6/pages/dashboard/demo-chat.js +176 -0
  308. package/data/project-types/jo/job-hunt/versions/1.0.6/pages/dashboard/index.html +382 -0
  309. package/data/project-types/jo/job-hunt/versions/1.0.6/pipeline.json +6 -0
  310. package/data/project-types/la/language-trainer/versions/1.1.2/about.md +8 -0
  311. package/data/project-types/la/language-trainer/versions/1.1.2/manifest.json +245 -0
  312. package/data/project-types/la/language-trainer/versions/1.1.2/mission.md +4 -0
  313. package/data/project-types/la/language-trainer/versions/1.1.2/pages/dashboard/application.js +33 -0
  314. package/data/project-types/la/language-trainer/versions/1.1.2/pages/dashboard/demo-chat.js +439 -0
  315. package/data/project-types/la/language-trainer/versions/1.1.2/pages/dashboard/index.html +476 -0
  316. package/data/project-types/la/language-trainer/versions/1.1.2/progress.json +10 -0
  317. package/data/project-types/la/language-trainer/versions/1.1.2/reviews.json +3 -0
  318. package/data/project-types/la/language-trainer/versions/1.1.2/scenarios.json +84 -0
  319. package/data/project-types/li/life-binder/versions/1.0.6/about.md +7 -0
  320. package/data/project-types/li/life-binder/versions/1.0.6/documents.json +145 -0
  321. package/data/project-types/li/life-binder/versions/1.0.6/manifest.json +206 -0
  322. package/data/project-types/li/life-binder/versions/1.0.6/mission.md +6 -0
  323. package/data/project-types/li/life-binder/versions/1.0.6/pages/dashboard/application.js +100 -0
  324. package/data/project-types/li/life-binder/versions/1.0.6/pages/dashboard/demo-chat.js +184 -0
  325. package/data/project-types/li/life-binder/versions/1.0.6/pages/dashboard/index.html +239 -0
  326. package/data/project-types/me/meal-planner/versions/1.0.5/about.md +10 -0
  327. package/data/project-types/me/meal-planner/versions/1.0.5/manifest.json +245 -0
  328. package/data/project-types/me/meal-planner/versions/1.0.5/menu.json +5 -0
  329. package/data/project-types/me/meal-planner/versions/1.0.5/mission.md +5 -0
  330. package/data/project-types/me/meal-planner/versions/1.0.5/pages/dashboard/application.js +115 -0
  331. package/data/project-types/me/meal-planner/versions/1.0.5/pages/dashboard/demo-chat.js +139 -0
  332. package/data/project-types/me/meal-planner/versions/1.0.5/pages/dashboard/index.html +186 -0
  333. package/data/project-types/me/meal-planner/versions/1.0.5/pantry.json +9 -0
  334. package/data/project-types/me/media-library/versions/1.0.2/about.md +17 -0
  335. package/data/project-types/me/media-library/versions/1.0.2/manifest.json +73 -0
  336. package/data/project-types/me/media-library/versions/1.0.2/mission.md +6 -0
  337. package/data/project-types/me/media-library/versions/1.0.2/pages/application.js +30 -0
  338. package/data/project-types/me/media-library/versions/1.0.2/pages/assets/alpine.svg +1 -0
  339. package/data/project-types/me/media-library/versions/1.0.2/pages/assets/coast.svg +1 -0
  340. package/data/project-types/me/media-library/versions/1.0.2/pages/assets/evening.svg +1 -0
  341. package/data/project-types/me/media-library/versions/1.0.2/pages/assets/forest.svg +1 -0
  342. package/data/project-types/me/media-library/versions/1.0.2/pages/assets/light.webm +0 -0
  343. package/data/project-types/me/media-library/versions/1.0.2/pages/assets/notes.wav +0 -0
  344. package/data/project-types/me/media-library/versions/1.0.2/pages/assets/study.svg +1 -0
  345. package/data/project-types/me/media-library/versions/1.0.2/pages/gallery.css +76 -0
  346. package/data/project-types/me/media-library/versions/1.0.2/pages/gallery.js +153 -0
  347. package/data/project-types/me/media-library/versions/1.0.2/pages/index.html +49 -0
  348. package/data/project-types/me/media-library/versions/1.0.2/pages/media-files.js +41 -0
  349. package/data/project-types/ne/new-hire-onboarding/art.json +17 -0
  350. package/data/project-types/ne/new-hire-onboarding/logo.webp +0 -0
  351. package/data/project-types/ne/new-hire-onboarding/manifest.json +23 -0
  352. package/data/project-types/ne/new-hire-onboarding/versions/1.0.0/about.md +14 -0
  353. package/data/project-types/ne/new-hire-onboarding/versions/1.0.0/hires.json +8 -0
  354. package/data/project-types/ne/new-hire-onboarding/versions/1.0.0/manifest.json +325 -0
  355. package/data/project-types/ne/new-hire-onboarding/versions/1.0.0/mission.md +5 -0
  356. package/data/project-types/ne/new-hire-onboarding/versions/1.0.0/pages/plans/application.js +160 -0
  357. package/data/project-types/ne/new-hire-onboarding/versions/1.0.0/pages/plans/demo-chat.js +188 -0
  358. package/data/project-types/ne/new-hire-onboarding/versions/1.0.0/pages/plans/index.html +391 -0
  359. package/data/project-types/ne/new-hire-onboarding/versions/1.0.0/tasks.json +8 -0
  360. package/data/project-types/no/novel-writing-room/versions/1.0.5/about.md +7 -0
  361. package/data/project-types/no/novel-writing-room/versions/1.0.5/chapters.json +10 -0
  362. package/data/project-types/no/novel-writing-room/versions/1.0.5/manifest.json +233 -0
  363. package/data/project-types/no/novel-writing-room/versions/1.0.5/mission.md +7 -0
  364. package/data/project-types/no/novel-writing-room/versions/1.0.5/pages/dashboard/application.js +113 -0
  365. package/data/project-types/no/novel-writing-room/versions/1.0.5/pages/dashboard/demo-chat.js +283 -0
  366. package/data/project-types/no/novel-writing-room/versions/1.0.5/pages/dashboard/index.html +253 -0
  367. package/data/project-types/no/novel-writing-room/versions/1.0.5/sessions.json +6 -0
  368. package/data/project-types/qu/quotes-and-bids/art.json +17 -0
  369. package/data/project-types/qu/quotes-and-bids/logo.webp +0 -0
  370. package/data/project-types/qu/quotes-and-bids/manifest.json +22 -0
  371. package/data/project-types/qu/quotes-and-bids/versions/1.0.0/about.md +15 -0
  372. package/data/project-types/qu/quotes-and-bids/versions/1.0.0/manifest.json +614 -0
  373. package/data/project-types/qu/quotes-and-bids/versions/1.0.0/mission.md +3 -0
  374. package/data/project-types/qu/quotes-and-bids/versions/1.0.0/pages/quotes/application.js +278 -0
  375. package/data/project-types/qu/quotes-and-bids/versions/1.0.0/pages/quotes/demo-chat.js +263 -0
  376. package/data/project-types/qu/quotes-and-bids/versions/1.0.0/pages/quotes/index.html +894 -0
  377. package/data/project-types/qu/quotes-and-bids/versions/1.0.0/quotes.json +10 -0
  378. package/data/project-types/qu/quotes-and-bids/versions/1.0.0/rates.json +8 -0
  379. package/data/project-types/raw-index.json +1 -1
  380. package/data/project-types/sa/sales-pipeline/art.json +17 -0
  381. package/data/project-types/sa/sales-pipeline/logo.webp +0 -0
  382. package/data/project-types/sa/sales-pipeline/manifest.json +23 -0
  383. package/data/project-types/sa/sales-pipeline/versions/1.0.0/about.md +10 -0
  384. package/data/project-types/sa/sales-pipeline/versions/1.0.0/activity.json +4 -0
  385. package/data/project-types/sa/sales-pipeline/versions/1.0.0/deals.json +12 -0
  386. package/data/project-types/sa/sales-pipeline/versions/1.0.0/manifest.json +450 -0
  387. package/data/project-types/sa/sales-pipeline/versions/1.0.0/mission.md +3 -0
  388. package/data/project-types/sa/sales-pipeline/versions/1.0.0/pages/pipeline/application.js +183 -0
  389. package/data/project-types/sa/sales-pipeline/versions/1.0.0/pages/pipeline/demo-chat.js +219 -0
  390. package/data/project-types/sa/sales-pipeline/versions/1.0.0/pages/pipeline/index.html +668 -0
  391. package/data/project-types/sh/shift-roster/art.json +17 -0
  392. package/data/project-types/sh/shift-roster/logo.webp +0 -0
  393. package/data/project-types/sh/shift-roster/manifest.json +22 -0
  394. package/data/project-types/sh/shift-roster/versions/1.0.0/about.md +13 -0
  395. package/data/project-types/sh/shift-roster/versions/1.0.0/availability.json +8 -0
  396. package/data/project-types/sh/shift-roster/versions/1.0.0/manifest.json +544 -0
  397. package/data/project-types/sh/shift-roster/versions/1.0.0/mission.md +5 -0
  398. package/data/project-types/sh/shift-roster/versions/1.0.0/pages/roster/application.js +311 -0
  399. package/data/project-types/sh/shift-roster/versions/1.0.0/pages/roster/demo-chat.js +218 -0
  400. package/data/project-types/sh/shift-roster/versions/1.0.0/pages/roster/index.html +428 -0
  401. package/data/project-types/sh/shift-roster/versions/1.0.0/pages/roster/rules.js +878 -0
  402. package/data/project-types/sh/shift-roster/versions/1.0.0/rules.json +4 -0
  403. package/data/project-types/sh/shift-roster/versions/1.0.0/shifts.json +8 -0
  404. package/data/project-types/sh/shift-roster/versions/1.0.0/staff.json +8 -0
  405. package/data/project-types/so/social-feed/versions/1.0.5/about.md +19 -0
  406. package/data/project-types/so/social-feed/versions/1.0.5/manifest.json +348 -0
  407. package/data/project-types/so/social-feed/versions/1.0.5/mission.md +10 -0
  408. package/data/project-types/so/social-feed/versions/1.0.5/pages/dashboard/application.js +31 -0
  409. package/data/project-types/so/social-feed/versions/1.0.5/pages/dashboard/demo-chat.js +321 -0
  410. package/data/project-types/so/social-feed/versions/1.0.5/pages/dashboard/index.html +746 -0
  411. package/data/project-types/so/social-feed/versions/1.0.5/posts/index.json +4 -0
  412. package/data/project-types/so/social-feed/versions/1.0.5/voice-guide.md +22 -0
  413. package/data/project-types/so/sop-library/art.json +17 -0
  414. package/data/project-types/so/sop-library/logo.webp +0 -0
  415. package/data/project-types/so/sop-library/manifest.json +22 -0
  416. package/data/project-types/so/sop-library/versions/1.0.0/about.md +15 -0
  417. package/data/project-types/so/sop-library/versions/1.0.0/manifest.json +347 -0
  418. package/data/project-types/so/sop-library/versions/1.0.0/mission.md +4 -0
  419. package/data/project-types/so/sop-library/versions/1.0.0/pages/library/application.js +144 -0
  420. package/data/project-types/so/sop-library/versions/1.0.0/pages/library/demo-chat.js +184 -0
  421. package/data/project-types/so/sop-library/versions/1.0.0/pages/library/index.html +480 -0
  422. package/data/project-types/so/sop-library/versions/1.0.0/sops/index.json +10 -0
  423. package/data/project-types/su/support-desk/art.json +17 -0
  424. package/data/project-types/su/support-desk/logo.webp +0 -0
  425. package/data/project-types/su/support-desk/manifest.json +22 -0
  426. package/data/project-types/su/support-desk/versions/1.0.0/about.md +15 -0
  427. package/data/project-types/su/support-desk/versions/1.0.0/manifest.json +395 -0
  428. package/data/project-types/su/support-desk/versions/1.0.0/mission.md +5 -0
  429. package/data/project-types/su/support-desk/versions/1.0.0/pages/desk/application.js +181 -0
  430. package/data/project-types/su/support-desk/versions/1.0.0/pages/desk/demo-chat.js +206 -0
  431. package/data/project-types/su/support-desk/versions/1.0.0/pages/desk/index.html +542 -0
  432. package/data/project-types/su/support-desk/versions/1.0.0/tickets.json +10 -0
  433. package/data/project-types/te/team-goals/art.json +17 -0
  434. package/data/project-types/te/team-goals/logo.webp +0 -0
  435. package/data/project-types/te/team-goals/manifest.json +23 -0
  436. package/data/project-types/te/team-goals/versions/1.0.0/about.md +12 -0
  437. package/data/project-types/te/team-goals/versions/1.0.0/actions.json +8 -0
  438. package/data/project-types/te/team-goals/versions/1.0.0/checkins.json +4 -0
  439. package/data/project-types/te/team-goals/versions/1.0.0/goals.json +9 -0
  440. package/data/project-types/te/team-goals/versions/1.0.0/keyresults.json +8 -0
  441. package/data/project-types/te/team-goals/versions/1.0.0/manifest.json +528 -0
  442. package/data/project-types/te/team-goals/versions/1.0.0/mission.md +5 -0
  443. package/data/project-types/te/team-goals/versions/1.0.0/pages/goals/application.js +262 -0
  444. package/data/project-types/te/team-goals/versions/1.0.0/pages/goals/demo-chat.js +206 -0
  445. package/data/project-types/te/team-goals/versions/1.0.0/pages/goals/index.html +504 -0
  446. package/data/project-types/tr/training-tracker/art.json +17 -0
  447. package/data/project-types/tr/training-tracker/logo.webp +0 -0
  448. package/data/project-types/tr/training-tracker/manifest.json +23 -0
  449. package/data/project-types/tr/training-tracker/versions/1.0.0/about.md +15 -0
  450. package/data/project-types/tr/training-tracker/versions/1.0.0/completions.json +4 -0
  451. package/data/project-types/tr/training-tracker/versions/1.0.0/courses.json +8 -0
  452. package/data/project-types/tr/training-tracker/versions/1.0.0/manifest.json +428 -0
  453. package/data/project-types/tr/training-tracker/versions/1.0.0/mission.md +5 -0
  454. package/data/project-types/tr/training-tracker/versions/1.0.0/pages/tracker/application.js +204 -0
  455. package/data/project-types/tr/training-tracker/versions/1.0.0/pages/tracker/demo-chat.js +225 -0
  456. package/data/project-types/tr/training-tracker/versions/1.0.0/pages/tracker/index.html +508 -0
  457. package/data/project-types/tr/training-tracker/versions/1.0.0/people.json +8 -0
  458. package/data/project-types/tr/training-tracker/versions/1.0.0/quizzes.json +8 -0
  459. package/data/project-types/tr/trip-planner/versions/1.0.6/about.md +7 -0
  460. package/data/project-types/tr/trip-planner/versions/1.0.6/journal.json +4 -0
  461. package/data/project-types/tr/trip-planner/versions/1.0.6/manifest.json +296 -0
  462. package/data/project-types/tr/trip-planner/versions/1.0.6/mission.md +4 -0
  463. package/data/project-types/tr/trip-planner/versions/1.0.6/packing.json +8 -0
  464. package/data/project-types/tr/trip-planner/versions/1.0.6/pages/dashboard/application.js +76 -0
  465. package/data/project-types/tr/trip-planner/versions/1.0.6/pages/dashboard/demo-chat.js +264 -0
  466. package/data/project-types/tr/trip-planner/versions/1.0.6/pages/dashboard/index.html +326 -0
  467. package/data/project-types/tr/trip-planner/versions/1.0.6/trip.json +8 -0
  468. package/data/project-types/ve/vendor-contracts/art.json +17 -0
  469. package/data/project-types/ve/vendor-contracts/logo.webp +0 -0
  470. package/data/project-types/ve/vendor-contracts/manifest.json +22 -0
  471. package/data/project-types/ve/vendor-contracts/versions/1.0.0/about.md +15 -0
  472. package/data/project-types/ve/vendor-contracts/versions/1.0.0/contracts.json +10 -0
  473. package/data/project-types/ve/vendor-contracts/versions/1.0.0/manifest.json +545 -0
  474. package/data/project-types/ve/vendor-contracts/versions/1.0.0/mission.md +5 -0
  475. package/data/project-types/ve/vendor-contracts/versions/1.0.0/pages/desk/application.js +222 -0
  476. package/data/project-types/ve/vendor-contracts/versions/1.0.0/pages/desk/demo-chat.js +236 -0
  477. package/data/project-types/ve/vendor-contracts/versions/1.0.0/pages/desk/index.html +493 -0
  478. package/data/project-types/ve/vendor-contracts/versions/1.0.0/vendors.json +8 -0
  479. package/data/project-types/wo/word-clues/versions/1.0.4/about.md +7 -0
  480. package/data/project-types/wo/word-clues/versions/1.0.4/game.json +14 -0
  481. package/data/project-types/wo/word-clues/versions/1.0.4/manifest.json +205 -0
  482. package/data/project-types/wo/word-clues/versions/1.0.4/mission.md +3 -0
  483. package/data/project-types/wo/word-clues/versions/1.0.4/pages/board/application.js +31 -0
  484. package/data/project-types/wo/word-clues/versions/1.0.4/pages/board/demo-chat.js +202 -0
  485. package/data/project-types/wo/word-clues/versions/1.0.4/pages/board/index.html +391 -0
  486. package/data/project-types/wo/word-clues/versions/1.0.4/words.json +216 -0
  487. package/package.json +1 -1
  488. package/schemas/craftbook-test.schema.json +9 -0
  489. package/schemas/project-type-identity.schema.json +1 -0
@@ -1 +1 @@
1
- {"schemaVersion":1,"kind":"project-type","count":26,"entries":[{"manifest":{"schemaVersion":1,"kind":"project-type","id":"caregiving-binder","name":"Caregiving Binder","description":"Coordinate a loved one's care without losing the thread. A discreet care coordinator keeps meds, appointments, and the day-to-day journal — and preps every doctor visit from the record.","tags":["caregiving","health","family","medications","appointments"],"category":"home","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.1.3","releasedAt":"2026-11-01T06:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"person":{"type":"string","title":"Who is the care for?","description":"A first name is enough — e.g. 'Mom', 'Jan'.","default":"Mom"}},"required":["person"]},"nameTemplate":"Caregiving Binder","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"zorgcoordinator","voorman":true}],"toolsets":[],"craftbooks":["visit-prep"],"scripts":{"care-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { logStore, rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'care-store',\n description:\n \"Read and update the care record: medications (meds.json) and the care journal (care.json). Call action:'status' for active meds + upcoming appointments; 'add_med' / 'stop_med' on changes; 'log_entry' for journal notes and symptoms; 'log_appointment' with when (ISO); 'visit_prep' before a doctor visit.\",\n inputs: {\n action: {\n type: 'string',\n description:\n \"One of 'status', 'add_med', 'stop_med', 'log_entry', 'log_appointment', or 'visit_prep'.\",\n required: true,\n },\n name: { type: 'string', description: 'Medication name.' },\n dose: { type: 'string', description: \"Dose and schedule, e.g. '10mg mornings'.\" },\n prescriber: { type: 'string', description: 'Who prescribed it.' },\n id: { type: 'string', description: \"Medication id, e.g. 'med-2'.\" },\n kind: { type: 'string', description: \"Journal kind: 'note', 'symptom', or 'update'.\" },\n note: { type: 'string', description: 'The journal entry or appointment description.' },\n when: { type: 'string', description: 'Appointment time (ISO), e.g. 2026-08-02T14:00.' },\n },\n outputs: {\n meds: { type: 'number', description: 'Active medications.' },\n upcoming: { type: 'number', description: 'Upcoming appointments.' },\n summary: { type: 'string', description: 'The care picture (or the visit prep).' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── care-rules-start ──\n// Pure derivations: upcoming appointments (journal events kind\n// 'appointment' with data.whenAt in the future) and the since-last-visit\n// window for visit prep.\n\nfunction upcomingAppointments(events, nowMs) {\n return events\n .filter(function (e) {\n var when = e.data && typeof e.data.whenAt === 'string' ? Date.parse(e.data.whenAt) : NaN;\n return e.kind === 'appointment' && isFinite(when) && when >= nowMs;\n })\n .sort(function (a, b) {\n return Date.parse(a.data.whenAt) - Date.parse(b.data.whenAt);\n });\n}\n\nfunction lastVisitMs(events, nowMs) {\n var past = events.filter(function (e) {\n var when = e.data && typeof e.data.whenAt === 'string' ? Date.parse(e.data.whenAt) : NaN;\n return e.kind === 'appointment' && isFinite(when) && when < nowMs;\n });\n if (past.length === 0) return null;\n return Math.max.apply(\n null,\n past.map(function (e) {\n return Date.parse(e.data.whenAt);\n }),\n );\n}\n\nfunction sinceWindow(events, nowMs) {\n var last = lastVisitMs(events, nowMs);\n return events.filter(function (e) {\n return e.kind !== 'appointment' && (last === null || Date.parse(e.at) > last);\n });\n}\n// ── care-rules-end ──\n\nconst meds = rosterStore(gezel.fs, 'meds.json', {\n stages: ['active', 'stopped'],\n idPrefix: 'med',\n});\nconst journal = logStore(gezel.fs, 'care.json');\n\nasync function resolveMed(): Promise<string> {\n if (input.id) return input.id;\n if (input.name) {\n const wanted = input.name.toLowerCase();\n const matches = (await meds.list({ status: 'active' })).filter(\n (r) => String(r.fields.name ?? '').toLowerCase() === wanted,\n );\n if (matches.length === 1) return matches[0]!.id;\n }\n throw new Error(\"Pass 'id' (e.g. 'med-2') or an exact active medication 'name'.\");\n}\n\nif (input.action === 'add_med') {\n if (!input.name || !input.dose) throw new Error(\"add_med needs 'name' and 'dose'.\");\n await meds.add({\n status: 'active',\n fields: {\n name: input.name,\n dose: input.dose,\n ...(input.prescriber ? { prescriber: input.prescriber } : {}),\n },\n });\n await journal.append({ kind: 'update', note: `Started ${input.name} (${input.dose}).` });\n} else if (input.action === 'stop_med') {\n const id = await resolveMed();\n const med = await meds.get(id);\n await meds.transition(id, 'stopped', input.note ? { note: input.note } : {});\n await journal.append({\n kind: 'update',\n note: `Stopped ${String(med?.fields.name ?? id)}${input.note ? ` — ${input.note}` : ''}.`,\n });\n} else if (input.action === 'log_entry') {\n if (!input.note) throw new Error(\"log_entry needs 'note'.\");\n const kind = input.kind === 'symptom' || input.kind === 'update' ? input.kind : 'note';\n await journal.append({ kind, note: input.note });\n} else if (input.action === 'log_appointment') {\n if (!input.note || !input.when) throw new Error(\"log_appointment needs 'note' and 'when' (ISO).\");\n await journal.append({ kind: 'appointment', note: input.note, data: { whenAt: input.when } });\n} else if (input.action !== 'status' && input.action !== 'visit_prep') {\n throw new Error(\n `Unknown action '${input.action}'. Use status, add_med, stop_med, log_entry, log_appointment, or visit_prep.`,\n );\n}\n\nconst activeMeds = await meds.list({ status: 'active' });\nconst events = await journal.list();\nconst nowMs = Date.now();\nconst upcoming = upcomingAppointments(events, nowMs);\n\nlet summary: string;\nif (input.action === 'visit_prep') {\n const since = sinceWindow(events, nowMs);\n const medLines = activeMeds\n .map((m) => `- ${String(m.fields.name)} ${String(m.fields.dose ?? '')}`.trim())\n .join('\\n');\n const noteLines = since\n .map((e) => `- [${e.kind}] ${String(e.at).slice(0, 10)}: ${e.note ?? ''}`)\n .join('\\n');\n summary = `VISIT PREP\\nActive medications:\\n${medLines || '- none recorded'}\\nSince the last visit:\\n${noteLines || '- quiet — nothing logged'}\\nUpcoming:\\n${upcoming.map((e) => `- ${String(e.data?.whenAt).slice(0, 16)} ${e.note ?? ''}`).join('\\n') || '- none scheduled'}`;\n} else {\n const next = upcoming[0];\n summary = `${activeMeds.length} active medication(s). ${upcoming.length} upcoming appointment(s)${\n next ? ` — next: ${String(next.data?.whenAt).slice(0, 16)} ${next.note ?? ''}` : ''\n }. ${events.filter((e) => e.kind !== 'appointment').length} journal entr(ies).`;\n}\n\ngezel.output({\n meds: activeMeds.length,\n upcoming: upcoming.length,\n summary,\n});\n"},"tools":[{"name":"add_med","description":"Record a medication (name, dose/schedule, prescriber).","script":"care-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"dose":{"type":"string"},"prescriber":{"type":"string"}},"required":["name","dose"]},"bind":{"action":"add_med"}},{"name":"stop_med","description":"Mark a medication stopped (with why, when known).","script":"care-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"note":{"type":"string"}}},"bind":{"action":"stop_med"}},{"name":"log_entry","description":"Add a journal entry — a note, a symptom observation, an update.","script":"care-store","inputs":{"type":"object","properties":{"kind":{"type":"string","enum":["note","symptom","update"]},"note":{"type":"string"}},"required":["note"]},"bind":{"action":"log_entry"}},{"name":"log_appointment","description":"Record an appointment (what and when, ISO).","script":"care-store","inputs":{"type":"object","properties":{"note":{"type":"string"},"when":{"type":"string"}},"required":["note","when"]},"bind":{"action":"log_appointment"}},{"name":"care_status","description":"Active meds, upcoming appointments, journal count.","script":"care-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"}},{"name":"visit_prep","description":"The one-page brief for the next doctor visit: meds + what happened since the last one.","script":"care-store","inputs":{"type":"object","properties":{}},"bind":{"action":"visit_prep"}},{"name":"page_log_entry","description":"Add a journal entry — a note, a symptom observation, an update.","script":"care-store","inputs":{"type":"object","properties":{"kind":{"type":"string","enum":["note","symptom","update"]},"note":{"type":"string"}},"required":["note"]},"bind":{"action":"log_entry"}},{"name":"page_log_appointment","description":"Record an appointment (what and when, ISO).","script":"care-store","inputs":{"type":"object","properties":{"note":{"type":"string"},"when":{"type":"string"}},"required":["note","when"]},"bind":{"action":"log_appointment"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"meds.json"},{"source":"workspace","path":"care.json"}],"tools":["page_log_entry","page_log_appointment"]},"schedules":[],"workspaceSeed":["meds.json","care.json"],"artifactsSeed":[],"availableVersions":["1.1.3","1.1.2","1.1.1","1.1.0","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"just-chat","name":"Chat","description":"A quiet room for talking — no tasks, no workspace, no deliverables. Just an open thread with a gezel of your choosing: brainstorming, writing back and forth, asking questions, thinking out loud. Ideal for a warm companion gezel or a small on-device model that's happiest simply conversing.","tags":["chat","conversation","companion","casual","writing"],"category":"general","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26279","version":"1.0.2","releasedAt":"2026-10-05T00:00:00Z","meesterManaged":false,"tabVisibility":{"overview":false,"tasks":false,"approvals":false,"workspace":false,"artifacts":false,"map":false},"nameTemplate":"Chat","aboutTemplate":"about.md","gezels":[{"templateId":"conversationalist","voorman":false}],"toolsets":[],"craftbooks":[],"tools":[],"schedules":[],"workspaceSeed":[],"artifactsSeed":[],"availableVersions":["1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"checkers","name":"Checkers","description":"Play checkers against a gezel opponent on a live board. You move on the board; the checkers player sees the position, plays back, and keeps the table talk going.","tags":["checkers","game","board-game","play"],"category":"game","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.2.6","releasedAt":"2026-11-01T06:00:00.000Z","meesterManaged":false,"tabVisibility":{"overview":false,"tasks":false,"approvals":false,"workspace":false,"artifacts":false,"map":false},"mode":"solo","leadLabel":"Opponent","leanProfile":true,"params":{"type":"object","properties":{"personality":{"type":"string","title":"Table-talk style","description":"How your opponent talks between moves. In-character follows the gezel's own character when social mode is on.","enum":["in-character","peppy","cheeky","zen","gracious"],"default":"in-character"},"playStyle":{"type":"string","title":"How should the checkers player play?","description":"An opponent keeps their strategy to themselves; an instructor offers light teaching notes.","enum":["Opponent","Instructor"],"default":"Opponent"}},"required":["personality","playStyle"]},"nameTemplate":"Checkers Table","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"checkers-player","voorman":true}],"toolsets":[],"craftbooks":[],"scripts":{"game-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\n\nexport const meta = defineScript({\n name: 'game-store',\n description:\n \"Read and update the checkers game (game.json). Call action:'board' to see the position, the side to move, and every legal move; action:'ai_move' to play your move (from/to, optional moveThought); action:'state' for a light summary; action:'new_game' to reset, optionally with forceCaptures:false. An illegal ai_move fails with the full legal-move list — pick one of those and call again.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'state', 'board', 'user_move', 'ai_move', or 'new_game'.\",\n required: true,\n },\n from: { type: 'string', description: \"Origin square, e.g. 'c3'.\" },\n to: { type: 'string', description: \"Destination square (a jump sequence's final square).\" },\n moveThought: { type: 'string', description: 'A short line of table talk to show on the board (max 140 chars).' },\n forceCaptures: {\n type: 'boolean',\n description: \"For new_game: true for standard forced captures; false to keep ordinary moves legal when a capture is available.\",\n },\n },\n outputs: {\n board: { type: 'string', description: 'Legacy human-readable ASCII board with coordinates.' },\n modelState: {\n type: 'object',\n description:\n 'Authoritative model-facing state: orientation, square lists, capture availability, and structured legal moves.',\n },\n turn: { type: 'string', description: \"Whose move: 'user' or 'ai'.\" },\n status: { type: 'string', description: 'playing, user_won, or ai_won.' },\n lastMove: { type: 'string', description: \"The move just played, e.g. 'c3-d4' or 'b6xd4'.\" },\n legalMoves: { type: 'string', description: 'Rendered legal moves for the side to move.' },\n captureRule: { type: 'string', description: \"Either 'forced' or 'optional'.\" },\n summary: { type: 'string', description: 'Human-readable game summary.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── checkers-rules-start ──\n// Pure, annotation-free rules engine (American/English draughts, 8x8).\n// Squares: 64-char row-major string, index = y*8+x, y0 = rank 8, x0 = file a.\n// 'r'/'R' = red (the user, moving toward rank 8 / decreasing y);\n// 'b'/'B' = black (the AI, moving toward rank 1 / increasing y); '.' empty.\n// Kept self-contained between these sentinels so unit tests execute the\n// shipped bytes directly (new Function) on every platform.\n\nvar FILES = 'abcdefgh';\n\nfunction sqName(x, y) {\n return FILES[x] + String(8 - y);\n}\n\nfunction parseSq(name) {\n if (typeof name !== 'string' || name.length !== 2) return null;\n var x = FILES.indexOf(name[0].toLowerCase());\n var rank = Number(name[1]);\n if (x < 0 || !(rank >= 1 && rank <= 8)) return null;\n return { x: x, y: 8 - rank };\n}\n\nfunction pieceAt(squares, x, y) {\n return squares[y * 8 + x];\n}\n\nfunction withPiece(squares, x, y, ch) {\n var i = y * 8 + x;\n return squares.slice(0, i) + ch + squares.slice(i + 1);\n}\n\nfunction sideOf(ch) {\n if (ch === 'r' || ch === 'R') return 'user';\n if (ch === 'b' || ch === 'B') return 'ai';\n return null;\n}\n\nfunction isKing(ch) {\n return ch === 'R' || ch === 'B';\n}\n\nfunction kingRowY(side) {\n return side === 'user' ? 0 : 7;\n}\n\nfunction dirsFor(ch) {\n if (isKing(ch)) {\n return [\n { dx: -1, dy: -1 },\n { dx: 1, dy: -1 },\n { dx: -1, dy: 1 },\n { dx: 1, dy: 1 },\n ];\n }\n var dy = ch === 'r' ? -1 : 1;\n return [\n { dx: -1, dy: dy },\n { dx: 1, dy: dy },\n ];\n}\n\nfunction inBounds(x, y) {\n return x >= 0 && x < 8 && y >= 0 && y < 8;\n}\n\nfunction buildInitial() {\n var out = '';\n for (var y = 0; y < 8; y += 1) {\n for (var x = 0; x < 8; x += 1) {\n var dark = (x + y) % 2 === 1;\n if (dark && y <= 2) out += 'b';\n else if (dark && y >= 5) out += 'r';\n else out += '.';\n }\n }\n return out;\n}\n\n// All complete jump sequences for the piece at (x, y). A sequence keeps\n// jumping with the same piece while another capture is available; a man\n// that reaches the king row STOPS there (standard rule — the move ends on\n// crowning). Each result: { from, to, path, captures } (square names).\nfunction jumpSequencesFrom(squares, x, y, ch) {\n var side = sideOf(ch);\n var results = [];\n\n function explore(sq, cx, cy, curCh, path, captures) {\n var extended = false;\n var dirs = dirsFor(curCh);\n for (var i = 0; i < dirs.length; i += 1) {\n var mx = cx + dirs[i].dx;\n var my = cy + dirs[i].dy;\n var lx = cx + dirs[i].dx * 2;\n var ly = cy + dirs[i].dy * 2;\n if (!inBounds(lx, ly)) continue;\n var mid = pieceAt(sq, mx, my);\n if (sideOf(mid) === null || sideOf(mid) === side) continue;\n if (pieceAt(sq, lx, ly) !== '.') continue;\n\n var nextCh = curCh;\n var crowned = false;\n if (!isKing(curCh) && ly === kingRowY(side)) {\n nextCh = side === 'user' ? 'R' : 'B';\n crowned = true;\n }\n var nextSq = withPiece(withPiece(withPiece(sq, cx, cy, '.'), mx, my, '.'), lx, ly, nextCh);\n var nextPath = path.concat([sqName(lx, ly)]);\n var nextCaptures = captures.concat([sqName(mx, my)]);\n extended = true;\n if (crowned) {\n results.push({\n from: path[0],\n to: sqName(lx, ly),\n path: nextPath,\n captures: nextCaptures,\n });\n } else {\n explore(nextSq, lx, ly, nextCh, nextPath, nextCaptures);\n }\n }\n if (!extended && captures.length > 0) {\n results.push({ from: path[0], to: path[path.length - 1], path: path, captures: captures });\n }\n }\n\n explore(squares, x, y, ch, [sqName(x, y)], []);\n return results;\n}\n\n// Every legal move for `side`. With standard forced captures, any jump\n// masks quiet moves. In the optional-capture variant, both remain legal.\n// Simple moves are single diagonal steps.\nfunction legalMovesFor(squares, side, forceCaptures) {\n var jumps = [];\n var steps = [];\n for (var y = 0; y < 8; y += 1) {\n for (var x = 0; x < 8; x += 1) {\n var ch = pieceAt(squares, x, y);\n if (sideOf(ch) !== side) continue;\n var seqs = jumpSequencesFrom(squares, x, y, ch);\n for (var j = 0; j < seqs.length; j += 1) jumps.push(seqs[j]);\n var dirs = dirsFor(ch);\n for (var i = 0; i < dirs.length; i += 1) {\n var nx = x + dirs[i].dx;\n var ny = y + dirs[i].dy;\n if (!inBounds(nx, ny) || pieceAt(squares, nx, ny) !== '.') continue;\n steps.push({\n from: sqName(x, y),\n to: sqName(nx, ny),\n path: [sqName(x, y), sqName(nx, ny)],\n captures: [],\n });\n }\n }\n }\n return forceCaptures !== false && jumps.length > 0 ? jumps : jumps.concat(steps);\n}\n\n// Apply a legal sequence, returning the new squares string. Crowns a man\n// that ends on the king row (mid-sequence crowning already ended the\n// sequence in jumpSequencesFrom, so end-of-path crowning is complete).\nfunction applySequence(squares, seq) {\n var start = parseSq(seq.from);\n var end = parseSq(seq.to);\n var ch = pieceAt(squares, start.x, start.y);\n var side = sideOf(ch);\n var next = withPiece(squares, start.x, start.y, '.');\n for (var i = 0; i < seq.captures.length; i += 1) {\n var cap = parseSq(seq.captures[i]);\n next = withPiece(next, cap.x, cap.y, '.');\n }\n var finalCh = ch;\n if (!isKing(ch) && end.y === kingRowY(side)) finalCh = side === 'user' ? 'R' : 'B';\n return withPiece(next, end.x, end.y, finalCh);\n}\n\n// The side to move with no legal move has lost (covers zero pieces too).\nfunction statusAfter(squares, sideToMove, forceCaptures) {\n if (legalMovesFor(squares, sideToMove, forceCaptures).length > 0) return 'playing';\n return sideToMove === 'user' ? 'ai_won' : 'user_won';\n}\n\nfunction describeMove(seq) {\n var joiner = seq.captures.length > 0 ? 'x' : '-';\n var text = seq.path.join(joiner);\n if (seq.captures.length > 0) text += ' (captures ' + seq.captures.join(', ') + ')';\n return text;\n}\n\nfunction renderAscii(squares) {\n var lines = [' a b c d e f g h'];\n for (var y = 0; y < 8; y += 1) {\n var row = String(8 - y);\n for (var x = 0; x < 8; x += 1) {\n row += ' ' + pieceAt(squares, x, y);\n }\n lines.push(row);\n }\n lines.push('r/R = red (your opponent, moving up). b/B = black (you, moving down). Capitals are kings.');\n return lines.join('\\n');\n}\n\nfunction renderPieces(squares) {\n var redMen = [];\n var redKings = [];\n var blackMen = [];\n var blackKings = [];\n for (var y = 0; y < 8; y += 1) {\n for (var x = 0; x < 8; x += 1) {\n var ch = pieceAt(squares, x, y);\n var name = sqName(x, y);\n if (ch === 'r') redMen.push(name);\n else if (ch === 'R') redKings.push(name);\n else if (ch === 'b') blackMen.push(name);\n else if (ch === 'B') blackKings.push(name);\n }\n }\n return { redMen: redMen, redKings: redKings, blackMen: blackMen, blackKings: blackKings };\n}\n// ── checkers-rules-end ──\n\nconst STATE_FILE = 'game.json';\nconst STAGE_SIDES = { user: 'red', ai: 'black' };\n\ninterface GameState {\n version: number;\n squares: string;\n turn: 'user' | 'ai';\n status: 'playing' | 'user_won' | 'ai_won' | 'draw';\n userColor: string;\n forceCaptures: boolean;\n legalMoves: Array<{ from: string; to: string; path: string[]; captures: string[] }>;\n moveLog: Array<{\n by: 'user' | 'ai';\n from: string;\n to: string;\n captures: string[];\n at: string;\n moveThought?: string;\n }>;\n lastMove: { by: 'user' | 'ai'; from: string; to: string; captures: string[] } | null;\n lastMoveThought: string;\n updatedAt: string;\n}\n\nfunction freshState(forceCaptures = true): GameState {\n const squares = buildInitial();\n return {\n version: 1,\n squares,\n turn: 'user',\n status: 'playing',\n userColor: 'red',\n forceCaptures,\n legalMoves: legalMovesFor(squares, 'user', forceCaptures),\n moveLog: [],\n lastMove: null,\n lastMoveThought: '',\n updatedAt: new Date().toISOString(),\n };\n}\n\nasync function load(): Promise<GameState> {\n let raw: string;\n try {\n raw = await gezel.fs.read(STATE_FILE);\n } catch {\n return freshState();\n }\n const parsed = JSON.parse(raw) as Partial<GameState>;\n if (typeof parsed.squares !== 'string' || parsed.squares.length !== 64) {\n throw new Error(`${STATE_FILE} is corrupt (squares missing); call action:'new_game' to reset.`);\n }\n return { ...freshState(parsed.forceCaptures !== false), ...parsed, forceCaptures: parsed.forceCaptures !== false } as GameState;\n}\n\nasync function persist(state: GameState): Promise<GameState> {\n state.legalMoves = state.status === 'playing' ? legalMovesFor(state.squares, state.turn, state.forceCaptures) : [];\n state.updatedAt = new Date().toISOString();\n await gezel.fs.write(STATE_FILE, `${JSON.stringify(state, null, 2)}\\n`);\n return state;\n}\n\nfunction summarize(state: GameState): string {\n const counts = { r: 0, b: 0 };\n for (const ch of state.squares) {\n if (ch === 'r' || ch === 'R') counts.r += 1;\n if (ch === 'b' || ch === 'B') counts.b += 1;\n }\n if (state.status === 'user_won') return `Game over — the user (red) won. Red ${counts.r} pieces, black ${counts.b}.`;\n if (state.status === 'ai_won') return `Game over — you (black) won. Red ${counts.r} pieces, black ${counts.b}.`;\n return `Move ${state.moveLog.length + 1}: ${STAGE_SIDES[state.turn]} (${state.turn}) to move. Red ${counts.r} pieces, black ${counts.b}. Captures are ${state.forceCaptures ? 'forced' : 'optional'}.`;\n}\n\nfunction renderLegal(state: GameState): string {\n if (state.status !== 'playing') return '(game over)';\n return state.legalMoves.map(describeMove).join(', ') || '(none)';\n}\n\nfunction renderModelState(state: GameState) {\n return {\n status: state.status,\n sideToMove: STAGE_SIDES[state.turn],\n coordinateFormat: 'file-rank (for example e3)',\n orientation: { redForwardRankDelta: 1, blackForwardRankDelta: -1 },\n pieces: renderPieces(state.squares),\n capturePolicy: state.forceCaptures ? 'mandatory-if-available' : 'optional',\n capturesAvailable: state.legalMoves.some((move) => move.captures.length > 0),\n legalMoves: state.legalMoves.map((move) => ({\n from: move.from,\n to: move.to,\n path: move.path,\n captures: move.captures,\n type: move.captures.length > 0 ? 'capture' : 'step',\n })),\n };\n}\n\nfunction applyTurn(state: GameState, by: 'user' | 'ai', moveThought?: string): GameState {\n if (state.status !== 'playing') {\n throw new Error(`The game is over (${state.status}). Call action:'new_game' to start another.`);\n }\n if (state.turn !== by) {\n throw new Error(\n by === 'ai'\n ? \"It's not your turn — the user has not moved yet.\"\n : \"It's not your turn — the AI is still to move.\",\n );\n }\n if (!input.from || !input.to) throw new Error(\"Pass 'from' and 'to' squares, e.g. from:'c3' to:'d4'.\");\n const seq = state.legalMoves.find(\n (m) => m.from === input.from!.toLowerCase() && m.to === input.to!.toLowerCase(),\n );\n if (!seq) {\n throw new Error(\n `Illegal move ${input.from}-${input.to}. Legal moves for ${STAGE_SIDES[by]}: ${renderLegal(state)}`,\n );\n }\n state.squares = applySequence(state.squares, seq);\n const nextTurn = by === 'user' ? 'ai' : 'user';\n state.status = statusAfter(state.squares, nextTurn, state.forceCaptures) as GameState['status'];\n state.turn = nextTurn;\n const entry = {\n by,\n from: seq.from,\n to: seq.to,\n captures: seq.captures,\n at: new Date().toISOString(),\n ...(moveThought ? { moveThought } : {}),\n };\n state.moveLog.push(entry);\n state.lastMove = { by, from: seq.from, to: seq.to, captures: seq.captures };\n if (by === 'ai' && moveThought) state.lastMoveThought = moveThought;\n return state;\n}\n\nlet state = await load();\nlet lastMoveText = state.lastMove\n ? describeMove({ ...state.lastMove, path: [state.lastMove.from, state.lastMove.to] })\n : '(none)';\n\nif (input.action === 'new_game') {\n state = await persist(freshState(input.forceCaptures !== false));\n lastMoveText = '(none)';\n} else if (input.action === 'user_move' || input.action === 'ai_move') {\n const by = input.action === 'user_move' ? 'user' : 'ai';\n const moveThought = input.moveThought ? input.moveThought.trim().slice(0, 140) : undefined;\n const before = state.legalMoves.find(\n (m) => m.from === (input.from ?? '').toLowerCase() && m.to === (input.to ?? '').toLowerCase(),\n );\n applyTurn(state, by, moveThought);\n state = await persist(state);\n lastMoveText = before ? describeMove(before) : `${input.from}-${input.to}`;\n} else if (input.action !== 'state' && input.action !== 'board') {\n throw new Error(`Unknown action '${input.action}'. Use state, board, user_move, ai_move, or new_game.`);\n}\n\ngezel.output({\n board:\n input.action === 'state'\n ? `${renderAscii(state.squares).split('\\n').slice(0, 9).join('\\n')}`\n : `${renderAscii(state.squares)}\\nCapture rule: ${state.forceCaptures ? 'forced' : 'optional'}.\\nTurn: ${STAGE_SIDES[state.turn]} (${state.turn}). Legal moves: ${renderLegal(state)}`,\n modelState: renderModelState(state),\n turn: state.turn,\n status: state.status,\n lastMove: lastMoveText,\n legalMoves: renderLegal(state),\n captureRule: state.forceCaptures ? 'forced' : 'optional',\n summary: summarize(state),\n});\n"},"tools":[{"name":"get_board","description":"See the authoritative structured checkers position, whose turn it is, capture availability, and every legal move. A legacy ASCII board is included for human readability.","script":"game-store","inputs":{"type":"object","properties":{}},"bind":{"action":"board"},"state":true},{"name":"make_move","description":"Play your (black's) move. Pass the from/to squares of a legal move; include a short moveThought to show on the board.","script":"game-store","inputs":{"type":"object","properties":{"from":{"type":"string","description":"Origin square, e.g. 'b6'."},"to":{"type":"string","description":"Destination square (a jump's final landing square)."},"moveThought":{"type":"string","description":"A short line of table talk (max 140 chars)."}},"required":["from","to"]},"bind":{"action":"ai_move"},"turn":{"say":"moveThought","fallback":"Move made — your turn."}},{"name":"user_move","description":"The user's move, played from the board page.","script":"game-store","inputs":{"type":"object","properties":{"from":{"type":"string"},"to":{"type":"string"}},"required":["from","to"]},"bind":{"action":"user_move"},"reaction":{"gezel":"checkers-player","prompt":"Your opponent played {{output.lastMove}}. The game engine returned this authoritative state:\n```json\n{{output.modelState}}\n```\nEvery `legalMoves` entry is legal. Its `type` and `captures` fields explicitly say whether it is a jump. Do not redraw the position as a grid, re-derive legality, recalculate capture availability, recount pieces, or question the stated orientation. Spend any thinking only on which listed move is strongest.\nStyle: {{playStyle}}. In Opponent style, do not volunteer advice or reveal the user's available moves, captures, threats, or tactics; comment only about your own move or the atmosphere. In Instructor style, offer at most one brief teaching observation without choosing the user's move. Answer strategy questions when asked.\nAct on the state above. If the game is over, do not move — one gracious line and offer new_game. Otherwise it is your turn: choose one listed move and call make_move with its `from` and `to` strings, including a short {{personality}} moveThought that follows the selected style. If make_move rejects it, choose one move from the legal list in the error and try again. After moving, reply with ONE short line of table talk that follows the selected style.","hideSeed":true,"standalone":true,"turn":{"tool":"make_move","when":{"op":"equals","field":"status","value":"playing"}}}},{"name":"new_game","description":"Reset the board to the opening position (user moves first).","script":"game-store","inputs":{"type":"object","properties":{"forceCaptures":{"type":"boolean","description":"Whether captures are required when available. Defaults to true."}}},"bind":{"action":"new_game"}}],"pages":{"entry":"board/index.html","api":1,"reads":[{"source":"workspace","path":"game.json"}],"tools":["user_move","new_game"]},"schedules":[],"workspaceSeed":["game.json"],"artifactsSeed":[],"availableVersions":["1.2.6","1.2.5","1.2.4","1.2.3","1.2.2","1.2.1","1.2.0","1.1.2","1.1.1","1.1.0","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"chess","name":"Chess","description":"Play a complete game of chess against a gezel opponent on a live board. You move white; the chess player sees the exact position, replies with a legal move, and shares the table without spoiling your plans.","tags":["chess","game","board-game","strategy","play"],"category":"game","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.8","releasedAt":"2026-11-01T06:00:00.000Z","meesterManaged":false,"tabVisibility":{"overview":false,"tasks":false,"approvals":false,"workspace":false,"artifacts":false,"map":false},"mode":"solo","leadLabel":"Opponent","leanProfile":true,"params":{"type":"object","properties":{"personality":{"type":"string","title":"Table-talk style","description":"How your opponent talks between moves. In-character follows the gezel's own character when social mode is on.","enum":["in-character","peppy","cheeky","zen","gracious"],"default":"in-character"},"playStyle":{"type":"string","title":"How should the chess player play?","description":"An opponent keeps their strategy to themselves; an instructor offers light teaching notes.","enum":["Opponent","Instructor"],"default":"Opponent"}},"required":["personality","playStyle"]},"nameTemplate":"Chess Table","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"chess-player","voorman":true}],"toolsets":[],"craftbooks":[],"scripts":{"game-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\n\nexport const meta = defineScript({\n name: 'game-store',\n description:\n \"Read and update the chess game (game.json). Call action:'board' to see the position and every legal move; action:'ai_move' to play your move (from/to, optional promotion and moveThought); action:'state' for a light summary; action:'new_game' to reset. Illegal moves fail with the engine's legal-move list.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'state', 'board', 'user_move', 'ai_move', or 'new_game'.\",\n required: true,\n },\n from: { type: 'string', description: \"Origin square, e.g. 'e7'.\" },\n to: { type: 'string', description: \"Destination square, e.g. 'e5'.\" },\n promotion: {\n type: 'string',\n description: \"Promotion piece: 'q', 'r', 'b', or 'n'. Defaults to queen.\",\n },\n moveThought: {\n type: 'string',\n description: 'A short line of table talk to show on the board (max 140 chars).',\n },\n },\n outputs: {\n board: { type: 'string', description: 'ASCII board with coordinates.' },\n turn: { type: 'string', description: \"Whose move: 'user' (white) or 'ai' (black).\" },\n status: {\n type: 'string',\n description: 'playing, user_won, ai_won, or draw.',\n },\n lastMove: { type: 'string', description: \"The move just played, e.g. 'e2-e4'.\" },\n legalMoves: { type: 'string', description: 'Rendered legal moves for the side to move.' },\n summary: { type: 'string', description: 'Human-readable game summary.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── chess-rules-start ──\n// Pure, annotation-free chess engine. Squares are a 64-character row-major\n// string: y0 is rank 8, x0 is file a. Uppercase pieces are white (the user);\n// lowercase pieces are black (the AI).\n\nvar FILES = 'abcdefgh';\nvar PROMOTIONS = ['q', 'r', 'b', 'n'];\n\nfunction sqName(x, y) {\n return FILES[x] + String(8 - y);\n}\n\nfunction parseSq(name) {\n if (typeof name !== 'string' || name.length !== 2) return null;\n var x = FILES.indexOf(name[0].toLowerCase());\n var rank = Number(name[1]);\n if (x < 0 || !(rank >= 1 && rank <= 8)) return null;\n return { x: x, y: 8 - rank };\n}\n\nfunction inBounds(x, y) {\n return x >= 0 && x < 8 && y >= 0 && y < 8;\n}\n\nfunction pieceAt(squares, x, y) {\n return squares[y * 8 + x];\n}\n\nfunction withPiece(squares, x, y, ch) {\n var i = y * 8 + x;\n return squares.slice(0, i) + ch + squares.slice(i + 1);\n}\n\nfunction sideOf(ch) {\n if (!ch || ch === '.') return null;\n return ch === ch.toUpperCase() ? 'user' : 'ai';\n}\n\nfunction otherSide(side) {\n return side === 'user' ? 'ai' : 'user';\n}\n\nfunction kindOf(ch) {\n return ch && ch !== '.' ? ch.toLowerCase() : '';\n}\n\nfunction buildInitial() {\n return 'rnbqkbnr' + 'pppppppp' + '.'.repeat(32) + 'PPPPPPPP' + 'RNBQKBNR';\n}\n\nfunction findKing(squares, side) {\n var needle = side === 'user' ? 'K' : 'k';\n var i = squares.indexOf(needle);\n return i < 0 ? null : { x: i % 8, y: Math.floor(i / 8) };\n}\n\nfunction isAttacked(squares, x, y, bySide) {\n var pawn = bySide === 'user' ? 'P' : 'p';\n var pawnY = y - (bySide === 'user' ? -1 : 1);\n for (var pdx of [-1, 1]) {\n var px = x - pdx;\n if (inBounds(px, pawnY) && pieceAt(squares, px, pawnY) === pawn) return true;\n }\n\n var knight = bySide === 'user' ? 'N' : 'n';\n var knightSteps = [\n [-2, -1],\n [-2, 1],\n [-1, -2],\n [-1, 2],\n [1, -2],\n [1, 2],\n [2, -1],\n [2, 1],\n ];\n for (var n of knightSteps) {\n if (inBounds(x + n[0], y + n[1]) && pieceAt(squares, x + n[0], y + n[1]) === knight) {\n return true;\n }\n }\n\n var rays = [\n [-1, 0, 'rq'],\n [1, 0, 'rq'],\n [0, -1, 'rq'],\n [0, 1, 'rq'],\n [-1, -1, 'bq'],\n [-1, 1, 'bq'],\n [1, -1, 'bq'],\n [1, 1, 'bq'],\n ];\n for (var ray of rays) {\n var rx = x + ray[0];\n var ry = y + ray[1];\n while (inBounds(rx, ry)) {\n var seen = pieceAt(squares, rx, ry);\n if (seen !== '.') {\n if (sideOf(seen) === bySide && ray[2].indexOf(kindOf(seen)) >= 0) return true;\n break;\n }\n rx += ray[0];\n ry += ray[1];\n }\n }\n\n var king = bySide === 'user' ? 'K' : 'k';\n for (var ky = -1; ky <= 1; ky += 1) {\n for (var kx = -1; kx <= 1; kx += 1) {\n if (\n (kx !== 0 || ky !== 0) &&\n inBounds(x + kx, y + ky) &&\n pieceAt(squares, x + kx, y + ky) === king\n ) {\n return true;\n }\n }\n }\n return false;\n}\n\nfunction inCheck(squares, side) {\n var king = findKing(squares, side);\n return !king || isAttacked(squares, king.x, king.y, otherSide(side));\n}\n\nfunction pushMove(out, fromX, fromY, toX, toY, extra) {\n out.push(\n Object.assign(\n {\n from: sqName(fromX, fromY),\n to: sqName(toX, toY),\n capture: false,\n },\n extra || {},\n ),\n );\n}\n\nfunction pseudoMovesFor(squares, side, castling, enPassant) {\n var out = [];\n for (var y = 0; y < 8; y += 1) {\n for (var x = 0; x < 8; x += 1) {\n var ch = pieceAt(squares, x, y);\n if (sideOf(ch) !== side) continue;\n var kind = kindOf(ch);\n\n if (kind === 'p') {\n var dir = side === 'user' ? -1 : 1;\n var startY = side === 'user' ? 6 : 1;\n var promotionY = side === 'user' ? 0 : 7;\n var oneY = y + dir;\n if (inBounds(x, oneY) && pieceAt(squares, x, oneY) === '.') {\n if (oneY === promotionY) {\n for (var promotion of PROMOTIONS) {\n pushMove(out, x, y, x, oneY, { promotion: promotion });\n }\n } else {\n pushMove(out, x, y, x, oneY);\n var twoY = y + dir * 2;\n if (y === startY && pieceAt(squares, x, twoY) === '.') {\n pushMove(out, x, y, x, twoY, { doublePawn: true });\n }\n }\n }\n for (var dx of [-1, 1]) {\n var cx = x + dx;\n var cy = y + dir;\n if (!inBounds(cx, cy)) continue;\n var target = pieceAt(squares, cx, cy);\n var targetName = sqName(cx, cy);\n var isEp = targetName === enPassant && target === '.';\n if ((target !== '.' && sideOf(target) === otherSide(side)) || isEp) {\n if (cy === promotionY) {\n for (var capturePromotion of PROMOTIONS) {\n pushMove(out, x, y, cx, cy, {\n capture: true,\n promotion: capturePromotion,\n enPassant: isEp,\n });\n }\n } else {\n pushMove(out, x, y, cx, cy, { capture: true, enPassant: isEp });\n }\n }\n }\n continue;\n }\n\n if (kind === 'n') {\n var jumps = [\n [-2, -1],\n [-2, 1],\n [-1, -2],\n [-1, 2],\n [1, -2],\n [1, 2],\n [2, -1],\n [2, 1],\n ];\n for (var jump of jumps) {\n var nx = x + jump[0];\n var ny = y + jump[1];\n if (!inBounds(nx, ny) || sideOf(pieceAt(squares, nx, ny)) === side) continue;\n pushMove(out, x, y, nx, ny, { capture: pieceAt(squares, nx, ny) !== '.' });\n }\n continue;\n }\n\n if (kind === 'b' || kind === 'r' || kind === 'q') {\n var dirs = [];\n if (kind === 'b' || kind === 'q') dirs.push([-1, -1], [-1, 1], [1, -1], [1, 1]);\n if (kind === 'r' || kind === 'q') dirs.push([-1, 0], [1, 0], [0, -1], [0, 1]);\n for (var d of dirs) {\n var sx = x + d[0];\n var sy = y + d[1];\n while (inBounds(sx, sy)) {\n var occupant = pieceAt(squares, sx, sy);\n if (sideOf(occupant) === side) break;\n pushMove(out, x, y, sx, sy, { capture: occupant !== '.' });\n if (occupant !== '.') break;\n sx += d[0];\n sy += d[1];\n }\n }\n continue;\n }\n\n if (kind === 'k') {\n for (var kdy = -1; kdy <= 1; kdy += 1) {\n for (var kdx = -1; kdx <= 1; kdx += 1) {\n if (kdx === 0 && kdy === 0) continue;\n var ktx = x + kdx;\n var kty = y + kdy;\n if (!inBounds(ktx, kty) || sideOf(pieceAt(squares, ktx, kty)) === side) continue;\n pushMove(out, x, y, ktx, kty, { capture: pieceAt(squares, ktx, kty) !== '.' });\n }\n }\n\n var homeY = side === 'user' ? 7 : 0;\n var kingChar = side === 'user' ? 'K' : 'k';\n var rookChar = side === 'user' ? 'R' : 'r';\n var enemy = otherSide(side);\n if (x === 4 && y === homeY && ch === kingChar && !isAttacked(squares, 4, homeY, enemy)) {\n var kingRight = side === 'user' ? castling.indexOf('K') >= 0 : castling.indexOf('k') >= 0;\n if (\n kingRight &&\n pieceAt(squares, 7, homeY) === rookChar &&\n pieceAt(squares, 5, homeY) === '.' &&\n pieceAt(squares, 6, homeY) === '.' &&\n !isAttacked(squares, 5, homeY, enemy) &&\n !isAttacked(squares, 6, homeY, enemy)\n ) {\n pushMove(out, x, y, 6, homeY, { castle: 'king' });\n }\n var queenRight = side === 'user' ? castling.indexOf('Q') >= 0 : castling.indexOf('q') >= 0;\n if (\n queenRight &&\n pieceAt(squares, 0, homeY) === rookChar &&\n pieceAt(squares, 1, homeY) === '.' &&\n pieceAt(squares, 2, homeY) === '.' &&\n pieceAt(squares, 3, homeY) === '.' &&\n !isAttacked(squares, 3, homeY, enemy) &&\n !isAttacked(squares, 2, homeY, enemy)\n ) {\n pushMove(out, x, y, 2, homeY, { castle: 'queen' });\n }\n }\n }\n }\n }\n return out;\n}\n\nfunction applyUnchecked(squares, move, side) {\n var from = parseSq(move.from);\n var to = parseSq(move.to);\n var ch = pieceAt(squares, from.x, from.y);\n var next = withPiece(squares, from.x, from.y, '.');\n if (move.enPassant) {\n next = withPiece(next, to.x, from.y, '.');\n }\n if (move.castle === 'king') {\n next = withPiece(next, 7, from.y, '.');\n next = withPiece(next, 5, from.y, side === 'user' ? 'R' : 'r');\n } else if (move.castle === 'queen') {\n next = withPiece(next, 0, from.y, '.');\n next = withPiece(next, 3, from.y, side === 'user' ? 'R' : 'r');\n }\n if (move.promotion) ch = side === 'user' ? move.promotion.toUpperCase() : move.promotion;\n return withPiece(next, to.x, to.y, ch);\n}\n\nfunction legalMovesFor(squares, side, castling, enPassant) {\n return pseudoMovesFor(squares, side, castling || '', enPassant || null).filter(function (move) {\n return !inCheck(applyUnchecked(squares, move, side), side);\n });\n}\n\nfunction nextCastling(castling, squares, move) {\n var rights = castling || '';\n var ch = pieceAt(squares, parseSq(move.from).x, parseSq(move.from).y);\n if (ch === 'K') rights = rights.replace(/K|Q/g, '');\n if (ch === 'k') rights = rights.replace(/k|q/g, '');\n if (move.from === 'a1' || move.to === 'a1') rights = rights.replace('Q', '');\n if (move.from === 'h1' || move.to === 'h1') rights = rights.replace('K', '');\n if (move.from === 'a8' || move.to === 'a8') rights = rights.replace('q', '');\n if (move.from === 'h8' || move.to === 'h8') rights = rights.replace('k', '');\n return rights;\n}\n\nfunction nextEnPassant(move, side) {\n if (!move.doublePawn) return null;\n var from = parseSq(move.from);\n var to = parseSq(move.to);\n return sqName(from.x, (from.y + to.y) / 2);\n}\n\nfunction isInsufficientMaterial(squares) {\n var pieces = [];\n for (var i = 0; i < squares.length; i += 1) {\n var ch = squares[i];\n if (ch !== '.' && kindOf(ch) !== 'k') pieces.push({ ch: ch, x: i % 8, y: Math.floor(i / 8) });\n }\n if (pieces.length === 0) return true;\n if (pieces.length === 1 && (kindOf(pieces[0].ch) === 'b' || kindOf(pieces[0].ch) === 'n')) {\n return true;\n }\n if (\n pieces.length > 0 &&\n pieces.every(function (p) {\n return kindOf(p.ch) === 'b';\n })\n ) {\n var color = (pieces[0].x + pieces[0].y) % 2;\n return pieces.every(function (p) {\n return (p.x + p.y) % 2 === color;\n });\n }\n return false;\n}\n\nfunction positionKey(squares, side, castling, enPassant) {\n var effectiveEnPassant =\n enPassant &&\n legalMovesFor(squares, side, castling, enPassant).some(function (move) {\n return move.enPassant;\n })\n ? enPassant\n : '-';\n return [squares, side, castling || '-', effectiveEnPassant].join('|');\n}\n\nfunction statusAfter(squares, sideToMove, castling, enPassant) {\n if (isInsufficientMaterial(squares)) return 'draw';\n var moves = legalMovesFor(squares, sideToMove, castling, enPassant);\n if (moves.length > 0) return 'playing';\n if (!inCheck(squares, sideToMove)) return 'draw';\n return sideToMove === 'user' ? 'ai_won' : 'user_won';\n}\n\nfunction describeMove(move) {\n if (move.castle === 'king') return move.from + '-' + move.to + ' (O-O)';\n if (move.castle === 'queen') return move.from + '-' + move.to + ' (O-O-O)';\n var text = move.from + (move.capture ? 'x' : '-') + move.to;\n if (move.promotion) text += '=' + move.promotion.toUpperCase();\n if (move.enPassant) text += ' e.p.';\n return text;\n}\n\nfunction renderAscii(squares) {\n var lines = [' a b c d e f g h'];\n for (var y = 0; y < 8; y += 1) {\n var row = String(8 - y);\n for (var x = 0; x < 8; x += 1) row += ' ' + pieceAt(squares, x, y);\n lines.push(row + ' ' + String(8 - y));\n }\n lines.push(' a b c d e f g h');\n lines.push('Uppercase = white (user). Lowercase = black (you).');\n return lines.join('\\n');\n}\n// ── chess-rules-end ──\n\nconst STATE_FILE = 'game.json';\nconst SIDE_NAMES = { user: 'white', ai: 'black' };\n\ninterface ChessMove {\n from: string;\n to: string;\n capture: boolean;\n promotion?: string;\n doublePawn?: boolean;\n enPassant?: boolean;\n castle?: string;\n}\n\ninterface GameState {\n version: number;\n squares: string;\n turn: 'user' | 'ai';\n status: 'playing' | 'user_won' | 'ai_won' | 'draw';\n castling: string;\n enPassant: string | null;\n halfmoveClock: number;\n fullmoveNumber: number;\n positionHistory: string[];\n legalMoves: ChessMove[];\n moveLog: Array<{\n by: 'user' | 'ai';\n from: string;\n to: string;\n promotion?: string;\n notation: string;\n at: string;\n moveThought?: string;\n }>;\n lastMove: {\n by: 'user' | 'ai';\n from: string;\n to: string;\n promotion?: string;\n notation: string;\n } | null;\n lastMoveThought: string;\n updatedAt: string;\n}\n\nfunction freshState(): GameState {\n const squares = buildInitial();\n const castling = 'KQkq';\n return {\n version: 1,\n squares,\n turn: 'user',\n status: 'playing',\n castling,\n enPassant: null,\n halfmoveClock: 0,\n fullmoveNumber: 1,\n positionHistory: [positionKey(squares, 'user', castling, null)],\n legalMoves: legalMovesFor(squares, 'user', castling, null),\n moveLog: [],\n lastMove: null,\n lastMoveThought: '',\n updatedAt: new Date().toISOString(),\n };\n}\n\nasync function load(): Promise<GameState> {\n let raw: string;\n try {\n raw = await gezel.fs.read(STATE_FILE);\n } catch {\n return freshState();\n }\n const parsed = JSON.parse(raw) as Partial<GameState>;\n if (typeof parsed.squares !== 'string' || parsed.squares.length !== 64) {\n throw new Error(`${STATE_FILE} is corrupt; call action:'new_game' to reset.`);\n }\n return {\n ...freshState(),\n ...parsed,\n castling: typeof parsed.castling === 'string' ? parsed.castling : '',\n enPassant: parsed.enPassant ?? null,\n } as GameState;\n}\n\nasync function persist(state: GameState): Promise<GameState> {\n state.legalMoves =\n state.status === 'playing'\n ? legalMovesFor(state.squares, state.turn, state.castling, state.enPassant)\n : [];\n state.updatedAt = new Date().toISOString();\n await gezel.fs.write(STATE_FILE, `${JSON.stringify(state, null, 2)}\\n`);\n return state;\n}\n\nfunction renderLegal(state: GameState): string {\n if (state.status !== 'playing') return '(game over)';\n return state.legalMoves.map(describeMove).join(', ') || '(none)';\n}\n\nfunction summarize(state: GameState): string {\n if (state.status === 'user_won') return 'Checkmate — the user (white) won.';\n if (state.status === 'ai_won') return 'Checkmate — you (black) won.';\n if (state.status === 'draw') return 'Game over — draw.';\n const check = inCheck(state.squares, state.turn) ? ' The king is in check.' : '';\n return `Move ${state.fullmoveNumber}: ${SIDE_NAMES[state.turn]} (${state.turn}) to move.${check}`;\n}\n\nfunction applyTurn(\n state: GameState,\n by: 'user' | 'ai',\n moveThought?: string,\n): { state: GameState; move: ChessMove } {\n if (state.status !== 'playing') {\n throw new Error(`The game is over (${state.status}). Call action:'new_game' to start another.`);\n }\n if (state.turn !== by) {\n throw new Error(by === 'ai' ? \"It's not your turn yet.\" : 'The opponent is still to move.');\n }\n if (!input.from || !input.to) throw new Error(\"Pass 'from' and 'to' squares.\");\n const wantedPromotion = (input.promotion || 'q').toLowerCase();\n const candidates = state.legalMoves.filter(\n (move) =>\n move.from === input.from!.toLowerCase() &&\n move.to === input.to!.toLowerCase(),\n );\n const move =\n candidates.find((candidate) => (candidate.promotion || 'q') === wantedPromotion) ??\n candidates.find((candidate) => !candidate.promotion);\n if (!move) {\n throw new Error(\n `Illegal move ${input.from}-${input.to}. Legal moves for ${SIDE_NAMES[by]}: ${renderLegal(state)}`,\n );\n }\n\n const movingPiece = pieceAt(\n state.squares,\n parseSq(move.from)!.x,\n parseSq(move.from)!.y,\n );\n const oldSquares = state.squares;\n state.castling = nextCastling(state.castling, oldSquares, move);\n state.squares = applyUnchecked(oldSquares, move, by);\n state.enPassant = nextEnPassant(move, by);\n state.halfmoveClock =\n kindOf(movingPiece) === 'p' || move.capture ? 0 : state.halfmoveClock + 1;\n if (by === 'ai') state.fullmoveNumber += 1;\n state.turn = otherSide(by) as 'user' | 'ai';\n const key = positionKey(state.squares, state.turn, state.castling, state.enPassant);\n state.positionHistory.push(key);\n state.status = statusAfter(\n state.squares,\n state.turn,\n state.castling,\n state.enPassant,\n ) as GameState['status'];\n if (\n state.status === 'playing' &&\n (state.halfmoveClock >= 100 ||\n state.positionHistory.filter((candidate) => candidate === key).length >= 3)\n ) {\n state.status = 'draw';\n }\n\n const notation = describeMove(move);\n const entry = {\n by,\n from: move.from,\n to: move.to,\n ...(move.promotion ? { promotion: move.promotion } : {}),\n notation,\n at: new Date().toISOString(),\n ...(moveThought ? { moveThought } : {}),\n };\n state.moveLog.push(entry);\n state.lastMove = {\n by,\n from: move.from,\n to: move.to,\n ...(move.promotion ? { promotion: move.promotion } : {}),\n notation,\n };\n if (by === 'ai' && moveThought) state.lastMoveThought = moveThought;\n return { state, move };\n}\n\nlet state = await load();\nlet lastMoveText = state.lastMove?.notation ?? '(none)';\n\nif (input.action === 'new_game') {\n state = await persist(freshState());\n lastMoveText = '(none)';\n} else if (input.action === 'user_move' || input.action === 'ai_move') {\n const by = input.action === 'user_move' ? 'user' : 'ai';\n const moveThought = input.moveThought?.trim().slice(0, 140);\n const applied = applyTurn(state, by, moveThought);\n state = await persist(applied.state);\n lastMoveText = describeMove(applied.move);\n} else if (input.action !== 'state' && input.action !== 'board') {\n throw new Error(`Unknown action '${input.action}'. Use state, board, user_move, ai_move, or new_game.`);\n}\n\ngezel.output({\n board:\n `${renderAscii(state.squares)}\\nTurn: ${SIDE_NAMES[state.turn]} (${state.turn}).` +\n `${inCheck(state.squares, state.turn) && state.status === 'playing' ? ' CHECK.' : ''}\\n` +\n `Legal moves: ${renderLegal(state)}`,\n turn: state.turn,\n status: state.status,\n lastMove: lastMoveText,\n legalMoves: renderLegal(state),\n summary: summarize(state),\n});\n"},"tools":[{"name":"get_board","description":"See the authoritative chess position, whose turn it is, and every legal move.","script":"game-store","inputs":{"type":"object","properties":{}},"bind":{"action":"board"},"state":true},{"name":"make_move","description":"Play your black move. Pass from/to; for promotion optionally choose 'q', 'r', 'b', or 'n'. Include a short moveThought for the board.","script":"game-store","inputs":{"type":"object","properties":{"from":{"type":"string","description":"Origin square, e.g. 'e7'."},"to":{"type":"string","description":"Destination square, e.g. 'e5'."},"promotion":{"type":"string","enum":["q","r","b","n"],"description":"Promotion piece. Defaults to queen."},"moveThought":{"type":"string","description":"A short line of table talk (max 140 chars)."}},"required":["from","to"]},"bind":{"action":"ai_move"},"turn":{"say":"moveThought","fallback":"Move made — your turn."}},{"name":"user_move","description":"The user's white move, played from the chess board.","script":"game-store","inputs":{"type":"object","properties":{"from":{"type":"string"},"to":{"type":"string"},"promotion":{"type":"string","enum":["q","r","b","n"]}},"required":["from","to"]},"bind":{"action":"user_move"},"reaction":{"gezel":"chess-player","prompt":"Your opponent played {{output.lastMove}}. Status: {{output.status}}. Board now:\n{{output.board}}\nThe board and Legal moves line come directly from the chess engine and are always correct. Do not re-derive the position, dispute a listed move, or invent a move outside that list. Spend your thought on choosing among the listed legal moves.\nStyle: {{playStyle}}. In Opponent style, do not volunteer advice or reveal the user’s available moves, threats, tactics, or your plan; comment only about your own move or the atmosphere. In Instructor style, offer at most one brief teaching observation without choosing the user’s move. Answer strategy questions when asked.\nAct on this latest position. If the game is over, do not move — give one gracious line and offer a new game. Otherwise choose a strong legal move and play it with make_move, including a short {{personality}} moveThought that follows the selected style. If make_move rejects it, choose one move verbatim from the legal list in the error and retry. After moving, reply with ONE short line of table talk.","hideSeed":true,"standalone":true,"turn":{"tool":"make_move","when":{"op":"equals","field":"status","value":"playing"}}}},{"name":"new_game","description":"Reset the chess board to the standard opening position.","script":"game-store","inputs":{"type":"object","properties":{}},"bind":{"action":"new_game"}}],"pages":{"entry":"board/index.html","api":1,"reads":[{"source":"workspace","path":"game.json"}],"tools":["user_move","new_game"]},"schedules":[],"workspaceSeed":["game.json"],"artifactsSeed":[],"availableVersions":["1.0.8","1.0.7","1.0.6","1.0.5","1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"data-analysis","name":"Data Analysis","description":"Explore the datasets in a project folder. A live dashboard finds spreadsheets and data files and opens them in Gezel's file viewers.","tags":["data","analysis","spreadsheets","csv","dashboard","reports"],"category":"data","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.1","releasedAt":"2026-11-01T06:00:00.000Z","extends":"data-analysis","nameTemplate":"Data Analysis","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"researcher","voorman":true}],"toolsets":[],"craftbooks":[],"tools":[],"pages":{"imports":[{"id":"data","source":"workspace","path":".","accept":[".csv",".tsv",".tab",".xlsx",".xls",".xlsm",".xlsb",".ods",".numbers",".json",".jsonl",".ndjson",".parquet",".arrow",".feather",".sqlite",".sqlite3",".db",".duckdb",".h5",".hdf5",".rds",".rdata",".sav",".dta",".sas7bdat",".xml",".html",".htm",".pdf",".md",".docx",".pptx",".ipynb"],"maxFileBytes":268435456}],"entry":"index.html","api":1,"reads":[{"source":"workspace","path":".","subtree":true}]},"schedules":[],"workspaceSeed":[],"artifactsSeed":[],"availableVersions":["1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"design-scheme","name":"Design Scheme","description":"Explore color schemes and design directions with a designer. Palettes are saved as artifacts and shown on a live gallery.","tags":["design","color","palette","branding","prototype"],"category":"creative","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.3","releasedAt":"2026-11-01T06:00:00.000Z","extends":"design-prototype","params":{"type":"object","properties":{"brief":{"type":"string","title":"What are you designing?","description":"A short brief — e.g. \"a calm meditation app\", \"a bold sports brand\".","default":"a new brand"}},"required":["brief"]},"nameTemplate":"Design Scheme: {{brief}}","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"designer","voorman":true}],"toolsets":[],"craftbooks":[],"scripts":{"scheme-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\n\nexport const meta = defineScript({\n name: 'scheme-store',\n description:\n \"Save and list the project's design color schemes. Call action:'save' with a name and an array of hex colors to add a scheme (it lands in artifacts/schemes/ and shows on the project's gallery). Call action:'list' to see what's saved.\",\n inputs: {\n action: { type: 'string', description: \"'save' or 'list'.\", required: true },\n name: { type: 'string', description: \"Scheme name (required for 'save'), e.g. 'Dusk'.\" },\n colors: {\n type: 'json',\n description: \"Array of hex colors for 'save', e.g. [\\\"#1b1a2e\\\", \\\"#e0894a\\\", \\\"#f5f0e8\\\"].\",\n },\n },\n outputs: {\n count: { type: 'number', description: 'How many schemes are saved.' },\n message: { type: 'string', description: 'Human-readable summary.' },\n },\n requires: ['artifacts.read', 'artifacts.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\ninterface Scheme {\n name: string;\n file: string;\n colors: string[];\n}\n\nconst INDEX = 'schemes/index.json';\n\nasync function loadIndex(): Promise<Scheme[]> {\n try {\n const raw = await gezel.artifacts.read(INDEX);\n const parsed = JSON.parse(raw) as { schemes?: Scheme[] };\n return Array.isArray(parsed.schemes) ? parsed.schemes : [];\n } catch {\n return [];\n }\n}\n\nfunction slugify(s: string): string {\n return (\n s\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '') || 'scheme'\n );\n}\n\nconst schemes = await loadIndex();\n\nif (input.action === 'save') {\n const name = (input.name ?? '').trim();\n const colors = Array.isArray(input.colors) ? input.colors.map(String) : [];\n if (!name || colors.length === 0) {\n gezel.output({ count: schemes.length, message: 'save needs a name and a non-empty colors array.' });\n } else {\n const file = `schemes/${slugify(name)}.json`;\n await gezel.artifacts.write(file, `${JSON.stringify({ name, colors }, null, 2)}\\n`);\n const next = [...schemes.filter((s) => s.file !== file), { name, file, colors }];\n await gezel.artifacts.write(INDEX, `${JSON.stringify({ schemes: next }, null, 2)}\\n`);\n gezel.output({ count: next.length, message: `Saved \"${name}\" (${colors.length} colors). ${next.length} scheme(s) total.` });\n }\n} else {\n gezel.output({\n count: schemes.length,\n message: schemes.length\n ? `${schemes.length} scheme(s): ${schemes.map((s) => s.name).join(', ')}.`\n : 'No schemes saved yet.',\n });\n}\n"},"tools":[{"name":"save_scheme","description":"Save a named color scheme so it shows on the gallery.","script":"scheme-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"colors":{"type":"array","items":{"type":"string"}}}},"bind":{"action":"save"}},{"name":"page_save_scheme","description":"Save a named color scheme so it shows on the gallery.","script":"scheme-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"colors":{"type":"array","items":{"type":"string"}}}},"bind":{"action":"save"}}],"pages":{"entry":"gallery/index.html","api":1,"reads":[{"source":"artifacts","path":"schemes/index.json"}],"tools":["page_save_scheme"]},"schedules":[],"workspaceSeed":[],"artifactsSeed":["schemes/index.json","schemes/warm-dusk.json"],"availableVersions":["1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"email","name":"Email / Inbox","description":"Sync an email account into a project as canonical markdown, then triage, draft, and summarize correspondence with a gezel.","tags":["email","inbox","triage","correspondence","builtin"],"category":"communication","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.0","releasedAt":"2026-07-06T00:00:00Z","extends":"email","aboutTemplate":"about.md","gezels":[],"toolsets":[],"craftbooks":[],"tools":[],"schedules":[],"workspaceSeed":[],"artifactsSeed":[],"notes":"Wraps the native mail pipeline (packages/service/src/mail) as a catalog entry so it appears in the New Project gallery alongside custom project types. Mailbox linking (IMAP / OAuth) remains a native creation step; this manifest carries no toolsets or scripts.","availableVersions":["1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"event-planner","name":"Event Planner","description":"Plan the wedding, the milestone birthday, the reunion. A composed event planner keeps the guest list sacred, the budget honest, and the day-of runbook ready — with a live countdown board.","tags":["event","wedding","party","guests","planning"],"category":"events","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.4","releasedAt":"2026-11-01T06:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"occasion":{"type":"string","title":"What are we celebrating?","description":"e.g. 'our wedding', 'Dad's 70th', 'the class reunion'.","default":"a big celebration"},"date":{"type":"string","title":"When is it?","description":"The date, e.g. 2026-09-12. A rough date is fine — change it later.","default":"2026-12-31"}},"required":["occasion","date"]},"nameTemplate":"Event: {{occasion}}","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"ceremoniemeester","voorman":true}],"toolsets":[],"craftbooks":["runbook"],"scripts":{"event-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { ledgerStore, rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'event-store',\n description:\n \"Read and update the event: guests (guests.json) and spending (budget.json). Call action:'status' for headcount + budget + countdown; 'add_guest' as invitations go out; 'guest_status' as RSVPs land (invited/yes/no); 'record_spend' when money is committed (ordinary units); 'guest_list' to read everyone.\",\n inputs: {\n action: {\n type: 'string',\n description:\n \"One of 'status', 'add_guest', 'guest_status', 'record_spend', or 'guest_list'.\",\n required: true,\n },\n name: { type: 'string', description: 'Guest name (party name is fine).' },\n party: { type: 'number', description: 'How many people this entry covers (default 1).' },\n status: { type: 'string', description: \"RSVP status: 'invited', 'yes', or 'no'.\" },\n id: { type: 'string', description: \"Guest id, e.g. 'guest-4'.\" },\n amount: { type: 'number', description: 'Spend amount in ordinary units.' },\n category: { type: 'string', description: \"Spend category, e.g. 'venue', 'catering'.\" },\n note: { type: 'string', description: 'Short note.' },\n },\n outputs: {\n invited: { type: 'number', description: 'People invited (sum of parties).' },\n coming: { type: 'number', description: \"People who said yes.\" },\n spentCents: { type: 'number', description: 'Total committed spend, in cents.' },\n summary: { type: 'string', description: 'The event picture.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── event-rules-start ──\n// Pure derivations: headcounts weighted by party size, and the countdown.\n\nfunction toCents(amount) {\n if (typeof amount !== 'number' || !isFinite(amount) || amount <= 0) return null;\n return Math.round(amount * 100);\n}\n\nfunction fmtCents(cents) {\n var abs = Math.abs(cents);\n return (cents < 0 ? '-' : '') + Math.floor(abs / 100) + '.' + String(abs % 100).padStart(2, '0');\n}\n\nfunction partyOf(record) {\n var p = record.fields && record.fields.party;\n return typeof p === 'number' && p >= 1 ? Math.floor(p) : 1;\n}\n\nfunction headcounts(records) {\n var invited = 0;\n var coming = 0;\n var awaiting = 0;\n records.forEach(function (r) {\n var size = partyOf(r);\n invited += size;\n if (r.status === 'yes') coming += size;\n if (r.status === 'invited') awaiting += size;\n });\n return { invited: invited, coming: coming, awaiting: awaiting };\n}\n\nfunction daysUntil(dateStr, nowMs) {\n var when = Date.parse(dateStr);\n if (!isFinite(when)) return null;\n return Math.ceil((when - nowMs) / (24 * 60 * 60 * 1000));\n}\n\nfunction eventLine(records, spentCents, eventDate, nowMs) {\n var heads = headcounts(records);\n var days = daysUntil(eventDate, nowMs);\n return (\n (days === null ? '' : days >= 0 ? days + ' day(s) to go. ' : 'The day has passed. ') +\n heads.coming +\n ' coming, ' +\n heads.awaiting +\n ' awaiting reply (' +\n heads.invited +\n ' invited). Spent ' +\n fmtCents(spentCents) +\n '.'\n );\n}\n// ── event-rules-end ──\n\nconst guests = rosterStore(gezel.fs, 'guests.json', {\n stages: ['invited', 'yes', 'no'],\n idPrefix: 'guest',\n});\nconst budget = ledgerStore(gezel.fs, 'budget.json');\n\nasync function readEventDate(): Promise<string> {\n try {\n const parsed = JSON.parse(await gezel.fs.read('guests.json')) as { eventDate?: string };\n return typeof parsed.eventDate === 'string' ? parsed.eventDate : '';\n } catch {\n return '';\n }\n}\n\nasync function resolveGuest(): Promise<string> {\n if (input.id) return input.id;\n if (input.name) {\n const wanted = input.name.toLowerCase();\n const matches = (await guests.list()).filter(\n (r) => String(r.fields.name ?? '').toLowerCase() === wanted,\n );\n if (matches.length === 1) return matches[0]!.id;\n }\n throw new Error(\"Pass 'id' (e.g. 'guest-4') or an exact guest 'name'.\");\n}\n\nif (input.action === 'add_guest') {\n if (!input.name) throw new Error(\"add_guest needs 'name'.\");\n await guests.add({\n status: 'invited',\n fields: {\n name: input.name,\n ...(typeof input.party === 'number' && input.party >= 1 ? { party: Math.floor(input.party) } : {}),\n ...(input.note ? { note: input.note } : {}),\n },\n });\n} else if (input.action === 'guest_status') {\n if (!input.status || !['invited', 'yes', 'no'].includes(input.status)) {\n throw new Error(\"guest_status needs status 'invited', 'yes', or 'no'.\");\n }\n await guests.transition(await resolveGuest(), input.status, input.note ? { note: input.note } : {});\n} else if (input.action === 'record_spend') {\n const cents = toCents(input.amount);\n if (cents === null || !input.category) {\n throw new Error(\"record_spend needs a positive 'amount' and a 'category' (e.g. 'venue').\");\n }\n await budget.add({\n amountCents: cents,\n kind: 'out',\n category: input.category.toLowerCase(),\n ...(input.note ? { note: input.note } : {}),\n });\n} else if (input.action !== 'status' && input.action !== 'guest_list') {\n throw new Error(\n `Unknown action '${input.action}'. Use status, add_guest, guest_status, record_spend, or guest_list.`,\n );\n}\n\nconst records = await guests.list();\nconst totals = await budget.totals();\nconst heads = headcounts(records);\nconst eventDate = await readEventDate();\nconst listing =\n input.action === 'guest_list'\n ? records\n .map(\n (r) =>\n `${r.id} [${r.status}] ${String(r.fields.name ?? '?')}${partyOf(r) > 1 ? ` (party of ${partyOf(r)})` : ''}`,\n )\n .join('\\n') || 'The guest list is empty.'\n : '';\n\ngezel.output({\n invited: heads.invited,\n coming: heads.coming,\n spentCents: totals.outCents,\n summary: listing || eventLine(records, totals.outCents, eventDate, Date.now()),\n});\n"},"tools":[{"name":"add_guest","description":"Add a guest or party to the list (status starts at invited).","script":"event-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"party":{"type":"number"},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"add_guest"}},{"name":"guest_status","description":"Record an RSVP: 'yes', 'no', or back to 'invited'.","script":"event-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"status":{"type":"string","enum":["invited","yes","no"]},"note":{"type":"string"}},"required":["status"]},"bind":{"action":"guest_status"}},{"name":"record_spend","description":"Record committed spending (deposit, balance, purchase) in ordinary units.","script":"event-store","inputs":{"type":"object","properties":{"amount":{"type":"number"},"category":{"type":"string"},"note":{"type":"string"}},"required":["amount","category"]},"bind":{"action":"record_spend"}},{"name":"event_status","description":"Countdown, headcount, and budget in one line.","script":"event-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"}},{"name":"guest_list","description":"Read the whole guest list with statuses.","script":"event-store","inputs":{"type":"object","properties":{}},"bind":{"action":"guest_list"}},{"name":"page_add_guest","description":"Add a guest or party to the list (status starts at invited).","script":"event-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"party":{"type":"number"},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"add_guest"}},{"name":"page_guest_status","description":"Record an RSVP: 'yes', 'no', or back to 'invited'.","script":"event-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"status":{"type":"string","enum":["invited","yes","no"]},"note":{"type":"string"}},"required":["status"]},"bind":{"action":"guest_status"}},{"name":"page_record_spend","description":"Record committed spending (deposit, balance, purchase) in ordinary units.","script":"event-store","inputs":{"type":"object","properties":{"amount":{"type":"number"},"category":{"type":"string"},"note":{"type":"string"}},"required":["amount","category"]},"bind":{"action":"record_spend"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"guests.json"},{"source":"workspace","path":"budget.json"}],"tools":["page_add_guest","page_guest_status","page_record_spend"]},"schedules":[],"workspaceSeed":["guests.json","budget.json"],"artifactsSeed":[],"availableVersions":["1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"fitness-coach","name":"Fitness Coach","description":"A training habit that survives real life. A steady Coach logs every session, guards the streak, and adjusts the weekly plan to fit your schedule — with a live board showing the week and the streak.","tags":["fitness","training","habits","streak","health"],"category":"growth","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.1.1","releasedAt":"2026-11-01T06:00:00.000Z","meesterManaged":false,"leanProfile":true,"params":{"type":"object","properties":{"goal":{"type":"string","title":"What are you training toward?","description":"e.g. 'feel strong again', 'a 10k in October'.","default":"feeling strong and consistent"},"weeklyTarget":{"type":"number","title":"Sessions per week","description":"How many training sessions a week to aim for.","default":3}},"required":["goal","weeklyTarget"]},"nameTemplate":"Fitness: {{goal}}","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"coach","voorman":true}],"toolsets":[],"craftbooks":["training-recap"],"scripts":{"training-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { logStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'training-store',\n description:\n \"Read and update the training log (training.json). Call action:'status' for streak + this week vs the target; 'log_workout' the moment a session is reported (activity + minutes); 'set_target' to change the weekly session target; 'history' for the recent sessions; 'recap_numbers' for this week against last; 'save_recap' to write the weekly recap with one suggestion.\",\n inputs: {\n action: {\n type: 'string',\n description:\n \"One of 'status', 'log_workout', 'set_target', 'history', 'recap_numbers', 'request_recap', or 'save_recap'.\",\n required: true,\n },\n activity: { type: 'string', description: \"What they did, e.g. 'run', 'gym', 'long walk'.\" },\n minutes: { type: 'number', description: 'How long the session ran, in minutes.' },\n note: { type: 'string', description: 'Anything worth remembering about the session.' },\n weeklyTarget: { type: 'number', description: 'Sessions per week to aim for (set_target).' },\n suggestion: { type: 'string', description: 'For save_recap: one concrete suggestion for next week.' },\n },\n outputs: {\n streakDays: { type: 'number', description: 'Consecutive days with a session, ending at the latest.' },\n thisWeek: { type: 'number', description: 'Sessions logged this week (Monday UTC start).' },\n weeklyTarget: { type: 'number', description: 'The current weekly session target.' },\n summary: { type: 'string', description: 'The training picture.' },\n personalBest: { type: 'boolean', description: 'For log_workout: the longest session on record.' },\n recap: { type: 'json', description: 'This week against last: sessions, minutes, longest session.' },\n display: { type: 'string', description: 'For save_recap: the recap as shown.' },\n status: { type: 'string', description: \"'recap_wanted' after request_recap, else 'ok'.\" },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── fitness-rules-start ──\n// Pure derivations over logStore-shaped workout events: kind 'workout',\n// data {activity, minutes}. Weeks start Monday 00:00 UTC; nowIso is a\n// parameter so the rules stay clock-independent and testable.\n\nfunction weekStartMs(nowIso) {\n var day = new Date(nowIso.slice(0, 10) + 'T00:00:00Z');\n var sinceMonday = (day.getUTCDay() + 6) % 7;\n return day.getTime() - sinceMonday * 86400000;\n}\n\nfunction thisWeekCount(events, nowIso) {\n var start = weekStartMs(nowIso);\n return events.filter(function (e) {\n return Date.parse(e.at) >= start;\n }).length;\n}\n\nfunction trainingLine(stats, weekCount, weeklyTarget) {\n var target = weeklyTarget > 0 ? weeklyTarget : 0;\n var weekPart =\n 'This week: ' +\n weekCount +\n (target > 0 ? ' of ' + target + ' session(s)' : ' session(s)') +\n (target > 0 && weekCount >= target ? ' — target met.' : '.');\n var streakPart =\n stats.total === 0\n ? 'No sessions logged yet.'\n : 'Streak: ' + stats.streakDays + ' day(s); ' + stats.total + ' session(s) all time.';\n return weekPart + ' ' + streakPart;\n}\n\n// The week's numbers against the week before: what a recap reports, so the\n// coach only adds a suggestion. Weeks start Monday UTC, as above.\nfunction weekRecap(events, nowIso, weeklyTarget) {\n var start = weekStartMs(nowIso);\n var prevStart = start - 7 * 86400000;\n function minutesOf(e) {\n var m = e.data && Number(e.data.minutes);\n return isFinite(m) && m > 0 ? m : 0;\n }\n var week = events.filter(function (e) { return Date.parse(e.at) >= start; });\n var prev = events.filter(function (e) {\n var t = Date.parse(e.at);\n return t >= prevStart && t < start;\n });\n var minutes = week.reduce(function (n, e) { return n + minutesOf(e); }, 0);\n var prevMinutes = prev.reduce(function (n, e) { return n + minutesOf(e); }, 0);\n var longest = week.reduce(function (best, e) {\n return !best || minutesOf(e) > minutesOf(best) ? e : best;\n }, null);\n return {\n weekOf: new Date(start).toISOString().slice(0, 10),\n sessions: week.length,\n target: weeklyTarget,\n minutes: minutes,\n sessionsChange: week.length - prev.length,\n minutesChange: minutes - prevMinutes,\n longest: longest\n ? { activity: String((longest.data && longest.data.activity) || 'session'), minutes: minutesOf(longest) }\n : null,\n };\n}\n\nfunction recapLine(recap, suggestion) {\n var change = recap.minutesChange === 0 ? 'same as last week' : (recap.minutesChange > 0 ? '+' : '') + recap.minutesChange + ' min vs last week';\n return (\n 'Week of ' + recap.weekOf + ': ' + recap.sessions + (recap.target > 0 ? ' of ' + recap.target : '') +\n ' session(s), ' + recap.minutes + ' min (' + change + ').' +\n (suggestion ? ' Next week: ' + suggestion : '')\n );\n}\n// ── fitness-rules-end ──\n\nconst training = logStore(gezel.fs, 'training.json');\n\nasync function readWeeklyTarget(): Promise<number> {\n try {\n const parsed = JSON.parse(await gezel.fs.read('training.json')) as { weeklyTarget?: unknown };\n const target = Number(parsed.weeklyTarget);\n return Number.isFinite(target) && target > 0 ? Math.round(target) : 0;\n } catch {\n return 0;\n }\n}\n\nlet personalBest = false;\nlet display = '';\nlet status = 'ok';\nif (input.action === 'log_workout') {\n if (!input.activity) throw new Error(\"log_workout needs 'activity' (what they did).\");\n const minutes = typeof input.minutes === 'number' && input.minutes > 0 ? Math.round(input.minutes) : 0;\n const before = await training.list();\n const longestBefore = before.reduce((n, e) => Math.max(n, Number(e.data?.minutes) || 0), 0);\n personalBest = minutes > 0 && before.length > 0 && minutes > longestBefore;\n await training.append({\n kind: 'workout',\n ...(input.note ? { note: input.note } : {}),\n data: {\n activity: input.activity,\n ...(typeof input.minutes === 'number' && input.minutes > 0\n ? { minutes: Math.round(input.minutes) }\n : {}),\n },\n });\n} else if (input.action === 'set_target') {\n const target = Number(input.weeklyTarget);\n if (!Number.isFinite(target) || target <= 0) {\n throw new Error(\"set_target needs a positive 'weeklyTarget' (sessions per week).\");\n }\n // logStore has no field API; the passenger key flips via a targeted\n // read-modify-write that preserves the rest of the file.\n const raw = JSON.parse(await gezel.fs.read('training.json')) as Record<string, unknown>;\n raw.weeklyTarget = Math.round(target);\n await gezel.fs.write('training.json', `${JSON.stringify(raw, null, 2)}\\n`);\n} else if (input.action === 'request_recap') {\n status = 'recap_wanted';\n} else if (input.action === 'save_recap') {\n const suggestion = String(input.suggestion ?? '').replace(/\\s+/g, ' ').trim().slice(0, 240);\n if (suggestion.length < 10) throw new Error(\"save_recap needs a one-sentence 'suggestion' for next week.\");\n const recap = weekRecap(await training.list(), new Date().toISOString(), await readWeeklyTarget());\n const doc = { ...recap, suggestion, writtenAt: new Date().toISOString() };\n const body = `${JSON.stringify(doc, null, 2)}\\n`;\n await gezel.fs.write(`recaps/${recap.weekOf}.json`, body);\n await gezel.fs.write('recaps/latest.json', body);\n display = recapLine(recap, suggestion);\n} else if (!['status', 'history', 'recap_numbers'].includes(String(input.action))) {\n throw new Error(\n `Unknown action '${input.action}'. Use status, log_workout, set_target, history, recap_numbers, or save_recap.`,\n );\n}\n\nconst events = await training.list();\nconst stats = await training.stats();\nconst weeklyTarget = await readWeeklyTarget();\nconst nowIso = new Date().toISOString();\nconst weekCount = thisWeekCount(events, nowIso);\nconst listing =\n input.action === 'history'\n ? events\n .slice(-12)\n .map(\n (e) =>\n `${e.at.slice(0, 10)} ${String(e.data?.activity ?? 'session')}${typeof e.data?.minutes === 'number' ? ` (${e.data.minutes} min)` : ''}${e.note ? ` — ${e.note}` : ''}`,\n )\n .join('\\n') || 'No sessions yet.'\n : '';\n\nconst recap = weekRecap(events, nowIso, weeklyTarget);\ngezel.output({\n streakDays: stats.streakDays,\n thisWeek: weekCount,\n weeklyTarget,\n summary:\n listing ||\n (input.action === 'recap_numbers' || input.action === 'request_recap'\n ? recapLine(recap, '')\n : trainingLine(stats, weekCount, weeklyTarget)),\n personalBest,\n recap,\n display,\n status,\n});\n"},"tools":[{"name":"log_workout","description":"Log a training session the moment it is reported (activity + minutes).","script":"training-store","inputs":{"type":"object","properties":{"activity":{"type":"string"},"minutes":{"type":"number"},"note":{"type":"string"}},"required":["activity"]},"bind":{"action":"log_workout"}},{"name":"set_target","description":"Change the weekly session target.","script":"training-store","inputs":{"type":"object","properties":{"weeklyTarget":{"type":"number"}},"required":["weeklyTarget"]},"bind":{"action":"set_target"}},{"name":"training_status","description":"Streak, this week against the target, all-time count.","script":"training-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"}},{"name":"workout_history","description":"The recent sessions, most recent last.","script":"training-store","inputs":{"type":"object","properties":{}},"bind":{"action":"history"}},{"name":"training_recap","description":"This week's training against last week: sessions, minutes, and the longest session.","script":"training-store","inputs":{"type":"object","properties":{}},"bind":{"action":"recap_numbers"}},{"name":"save_recap","description":"Save the weekly recap with ONE concrete suggestion for next week, in one sentence, grounded in this week's numbers. The app adds the numbers.","script":"training-store","inputs":{"type":"object","properties":{"suggestion":{"type":"string","description":"One sentence for next week."}},"required":["suggestion"]},"bind":{"action":"save_recap"},"turn":{"fallback":"Recap saved.","show":"display"}},{"name":"page_log_workout","description":"Log a session from the dashboard.","script":"training-store","inputs":{"type":"object","properties":{"activity":{"type":"string"},"minutes":{"type":"number"},"note":{"type":"string"}},"required":["activity"]},"bind":{"action":"log_workout"}},{"name":"request_recap","description":"Ask the coach for this week's recap from the dashboard.","script":"training-store","inputs":{"type":"object","properties":{}},"bind":{"action":"request_recap"},"reaction":{"gezel":"coach","prompt":"The person asked for this week's training recap. The numbers, from their log:\n```json\n{{output.recap}}\n```\nCall save_recap once with ONE concrete suggestion for next week, in one sentence, grounded in these numbers. Their goal: {{goal}}.","hideSeed":true,"standalone":true,"turn":{"tool":"save_recap","when":{"op":"equals","field":"status","value":"recap_wanted"}}}},{"name":"page_set_target","description":"Change the weekly session target.","script":"training-store","inputs":{"type":"object","properties":{"weeklyTarget":{"type":"number"}},"required":["weeklyTarget"]},"bind":{"action":"set_target"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"training.json"},{"source":"workspace","path":"recaps/latest.json"}],"tools":["page_log_workout","request_recap","page_set_target"]},"schedules":[{"runMode":"scheduled","cron":"0 18 * * 0","craftbook":"training-recap","consent":"ask"}],"workspaceSeed":["training.json"],"artifactsSeed":[],"availableVersions":["1.1.1","1.1.0","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"flashcards","name":"Flashcards","description":"Learn anything with spaced-repetition flashcards. Your study partner writes the cards in chat; you review them on a live card-flip page that schedules what comes back and when.","tags":["flashcards","study","learning","spaced-repetition"],"category":"growth","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.2.2","releasedAt":"2026-11-01T06:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"subject":{"type":"string","title":"What are you learning?","description":"The deck's subject — e.g. Spanish vocabulary, AWS certification, organic chemistry.","default":"Spanish vocabulary"}},"required":["subject"]},"nameTemplate":"{{subject}} Flashcards","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"study-buddy","voorman":true}],"toolsets":[],"craftbooks":[],"scripts":{"deck-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\n\nexport const meta = defineScript({\n name: 'deck-store',\n description:\n \"Read and update the flashcard deck (deck.json). Call action:'add_cards' with a cards array ([{front, back}, ...]) to add practice cards; action:'state' to see due counts and box distribution; action:'list_deck' to read every card. The review page drives 'record_review', 'finish_session' and 'stage_notes' itself.\",\n inputs: {\n action: {\n type: 'string',\n description:\n \"One of 'state', 'list_deck', 'add_cards', 'record_review', 'finish_session', or 'stage_notes'.\",\n required: true,\n },\n cards: {\n type: 'json',\n description: 'For add_cards: an array of {front, back} objects.',\n },\n cardId: { type: 'string', description: \"For record_review: the card id, e.g. 'card-3'.\" },\n verdict: { type: 'string', description: \"For record_review: 'got-it' or 'missed'.\" },\n reviewed: { type: 'number', description: 'For finish_session: how many cards were reviewed.' },\n missedIds: { type: 'json', description: 'For finish_session: array of card ids that were missed.' },\n notes: { type: 'string', description: 'For stage_notes: notes the student pasted to turn into cards.' },\n },\n outputs: {\n total: { type: 'number', description: 'Cards in the deck.' },\n due: { type: 'number', description: 'Cards due for review now.' },\n summary: { type: 'string', description: 'Human-readable deck or session summary.' },\n missedList: { type: 'string', description: 'Fronts of the cards missed this session (finish_session).' },\n status: { type: 'string', description: \"'forging' after stage_notes, else 'idle'.\" },\n notes: { type: 'string', description: 'The staged notes (stage_notes), clipped to 3000 characters.' },\n },\n requires: ['workspace.read', 'workspace.write', 'reminders'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── leitner-rules-start ──\n// Pure Leitner-box scheduling (3 boxes). Box 1 reviews daily, box 2 every\n// 3 days, box 3 weekly. A got-it promotes (capped at 3); a miss goes back\n// to box 1. Never-reviewed cards are always due. Kept self-contained\n// between these sentinels so unit tests execute the shipped bytes.\n\nvar BOX_INTERVAL_DAYS = { 1: 1, 2: 3, 3: 7 };\nvar DAY_MS = 24 * 60 * 60 * 1000;\n\nfunction isDue(card, nowMs) {\n if (!card.lastReviewedAt) return true;\n var interval = BOX_INTERVAL_DAYS[card.box] || 1;\n return nowMs - Date.parse(card.lastReviewedAt) >= interval * DAY_MS;\n}\n\nfunction computeDueIds(cards, nowMs) {\n return cards\n .filter(function (c) {\n return isDue(c, nowMs);\n })\n .sort(function (a, b) {\n if (a.box !== b.box) return a.box - b.box;\n return a.createdAt < b.createdAt ? -1 : a.createdAt > b.createdAt ? 1 : 0;\n })\n .map(function (c) {\n return c.id;\n });\n}\n\nfunction applyReview(card, verdict, nowIso) {\n if (verdict === 'got-it') card.box = Math.min(3, card.box + 1);\n else card.box = 1;\n card.lastReviewedAt = nowIso;\n card.stats = card.stats || { gotIt: 0, missed: 0 };\n if (verdict === 'got-it') card.stats.gotIt += 1;\n else card.stats.missed += 1;\n return card;\n}\n\nfunction nextCardId(cards) {\n var max = 0;\n for (var i = 0; i < cards.length; i += 1) {\n var m = /^card-(\\d+)$/.exec(cards[i].id);\n if (m) max = Math.max(max, Number(m[1]));\n }\n return 'card-' + (max + 1);\n}\n// ── leitner-rules-end ──\n\nconst DECK_FILE = 'deck.json';\n\ninterface Card {\n id: string;\n front: string;\n back: string;\n box: number;\n lastReviewedAt: string | null;\n createdAt: string;\n stats: { gotIt: number; missed: number };\n}\n\ninterface Deck {\n version: number;\n subject: string;\n cards: Card[];\n dueCardIds: string[];\n updatedAt: string;\n}\n\nasync function load(): Promise<Deck> {\n let raw: string;\n try {\n raw = await gezel.fs.read(DECK_FILE);\n } catch {\n return { version: 1, subject: 'your subject', cards: [], dueCardIds: [], updatedAt: new Date().toISOString() };\n }\n const parsed = JSON.parse(raw) as Partial<Deck>;\n return {\n version: 1,\n subject: typeof parsed.subject === 'string' ? parsed.subject : 'your subject',\n cards: Array.isArray(parsed.cards) ? (parsed.cards as Card[]) : [],\n dueCardIds: [],\n updatedAt: new Date().toISOString(),\n };\n}\n\n// ── reminder-start ──\n// The next time a reviewed card comes due, worked out from the deck itself:\n// the one moment a reminder is earned. Nothing left to come due clears it.\n// Kept self-contained between these sentinels so unit tests execute the\n// shipped bytes.\nasync function remind(deck, nowMs) {\n var next = Infinity;\n for (var i = 0; i < deck.cards.length; i += 1) {\n var card = deck.cards[i];\n if (!card.lastReviewedAt) continue;\n var dueAt = Date.parse(card.lastReviewedAt) + (BOX_INTERVAL_DAYS[card.box] || 1) * DAY_MS;\n if (dueAt > nowMs && dueAt < next) next = dueAt;\n }\n try {\n if (!isFinite(next)) {\n await gezel.reminder.clear();\n return;\n }\n var count = computeDueIds(deck.cards, next).length;\n await gezel.reminder.set({\n at: new Date(next).toISOString(),\n title: 'Flashcards are due',\n body: count + (count === 1 ? ' card' : ' cards') + ' on \"' + deck.subject + '\" ready to review.',\n });\n } catch (err) {\n // A host without reminders still keeps the deck.\n }\n}\n// ── reminder-end ──\n\nasync function persist(deck: Deck): Promise<Deck> {\n const nowMs = Date.now();\n deck.dueCardIds = computeDueIds(deck.cards, nowMs);\n deck.updatedAt = new Date(nowMs).toISOString();\n await gezel.fs.write(DECK_FILE, `${JSON.stringify(deck, null, 2)}\\n`);\n await remind(deck, nowMs);\n return deck;\n}\n\nconst deck = await load();\ndeck.dueCardIds = computeDueIds(deck.cards, Date.now());\nlet summary = '';\nlet missedList = '';\nlet status = 'idle';\nlet notes = '';\n// Cards from one call: enough for a set of notes, short enough that a small\n// model writes them in one turn.\nconst MAX_NEW_CARDS = 8;\n\nif (input.action === 'add_cards') {\n const raw = Array.isArray(input.cards) ? input.cards : [];\n const added: string[] = [];\n for (const entry of raw.slice(0, MAX_NEW_CARDS)) {\n const front = typeof (entry as { front?: unknown }).front === 'string' ? (entry as { front: string }).front.trim() : '';\n const back = typeof (entry as { back?: unknown }).back === 'string' ? (entry as { back: string }).back.trim() : '';\n if (!front || !back) continue;\n const card: Card = {\n id: nextCardId(deck.cards),\n front: front.slice(0, 300),\n back: back.slice(0, 500),\n box: 1,\n lastReviewedAt: null,\n createdAt: new Date().toISOString(),\n stats: { gotIt: 0, missed: 0 },\n };\n deck.cards.push(card);\n added.push(card.id);\n }\n if (added.length === 0) {\n throw new Error(\"add_cards needs a non-empty 'cards' array of {front, back} objects.\");\n }\n await persist(deck);\n summary = `Added ${added.length} card(s). ${deck.cards.length} in the deck, ${deck.dueCardIds.length} due now.`;\n} else if (input.action === 'record_review') {\n if (!input.cardId || (input.verdict !== 'got-it' && input.verdict !== 'missed')) {\n throw new Error(\"record_review needs 'cardId' and verdict 'got-it' or 'missed'.\");\n }\n const card = deck.cards.find((c) => c.id === input.cardId);\n if (!card) throw new Error(`No card '${input.cardId}' in the deck.`);\n applyReview(card, input.verdict, new Date().toISOString());\n await persist(deck);\n summary = `${card.id} marked ${input.verdict} (now box ${card.box}). ${deck.dueCardIds.length} still due.`;\n} else if (input.action === 'finish_session') {\n const reviewed = typeof input.reviewed === 'number' ? input.reviewed : 0;\n const missedIds = Array.isArray(input.missedIds) ? input.missedIds.map(String) : [];\n const missedFronts = missedIds\n .map((id) => deck.cards.find((c) => c.id === id)?.front)\n .filter((f): f is string => typeof f === 'string');\n missedList = missedFronts.length ? missedFronts.join(' | ') : '(none)';\n summary = `Reviewed ${reviewed} card(s): ${reviewed - missedIds.length} got it, ${missedIds.length} missed. ${deck.dueCardIds.length} due next.`;\n} else if (input.action === 'list_deck') {\n summary = deck.cards.length\n ? deck.cards\n .map((c) => `${c.id} [box ${c.box}] ${c.front} -> ${c.back}`)\n .join('\\n')\n : 'The deck is empty — add cards with add_cards.';\n} else if (input.action === 'state') {\n const boxes = { 1: 0, 2: 0, 3: 0 } as Record<number, number>;\n for (const c of deck.cards) boxes[c.box] = (boxes[c.box] ?? 0) + 1;\n summary = deck.cards.length\n ? `${deck.cards.length} card(s) on \"${deck.subject}\": ${deck.dueCardIds.length} due now. Boxes: ${boxes[1]} daily, ${boxes[2]} every-3-days, ${boxes[3]} weekly.`\n : `The deck for \"${deck.subject}\" is empty — offer to write the first cards.`;\n} else if (input.action === 'stage_notes') {\n notes = String(input.notes ?? '').trim().slice(0, 3000);\n if (notes.length < 20) throw new Error('Paste a few sentences of notes to make cards from.');\n status = 'forging';\n summary = `Notes staged for \"${deck.subject}\". ${deck.cards.length} card(s) in the deck so far.`;\n} else {\n throw new Error(\n `Unknown action '${input.action}'. Use state, list_deck, add_cards, record_review, finish_session, or stage_notes.`,\n );\n}\n\ngezel.output({\n total: deck.cards.length,\n due: deck.dueCardIds.length,\n summary,\n missedList,\n status,\n notes,\n});\n"},"tools":[{"name":"add_cards","description":"Add flashcards to the deck: a cards array of {front, back} objects, one fact per card, at most 8 at a time. The deck's summary becomes your reply.","script":"deck-store","inputs":{"type":"object","properties":{"cards":{"type":"array","items":{"type":"object","properties":{"front":{"type":"string"},"back":{"type":"string"}},"required":["front","back"]},"description":"The cards to add."}},"required":["cards"]},"bind":{"action":"add_cards"},"turn":{"fallback":"Cards added to the deck.","show":"summary"}},{"name":"deck_status","description":"See the deck: how many cards, how many due, and the box distribution.","script":"deck-store","inputs":{"type":"object","properties":{}},"bind":{"action":"state"}},{"name":"list_deck","description":"Read every card in the deck (id, box, front, back).","script":"deck-store","inputs":{"type":"object","properties":{}},"bind":{"action":"list_deck"}},{"name":"record_review","description":"The review page's per-card verdict.","script":"deck-store","inputs":{"type":"object","properties":{"cardId":{"type":"string"},"verdict":{"type":"string","enum":["got-it","missed"]}},"required":["cardId","verdict"]},"bind":{"action":"record_review"}},{"name":"finish_session","description":"The review page's end-of-session summary.","script":"deck-store","inputs":{"type":"object","properties":{"reviewed":{"type":"number"},"missedIds":{"type":"array","items":{"type":"string"}}},"required":["reviewed"]},"bind":{"action":"finish_session"},"reaction":{"gezel":"study-buddy","prompt":"The user finished a flashcard review session. {{output.summary}}\nMissed cards: {{output.missedList}}\nReply with ONE short encouraging line — specific beats generic. If any cards were missed, offer to add fresh practice cards that come at those same ideas from a new angle (add them with your deck capabilities if the user agrees)."}},{"name":"forge_from_notes","description":"The review page's notes-to-cards request.","script":"deck-store","inputs":{"type":"object","properties":{"notes":{"type":"string"}},"required":["notes"]},"bind":{"action":"stage_notes"},"reaction":{"gezel":"study-buddy","prompt":"The student pasted notes to turn into flashcards for \"{{subject}}\":\n<<<\n{{output.notes}}\n>>>\nMake 4 to 8 cards that test the key facts in these notes, one fact per card: the front a short question, the back its answer (a name, number or short fact from the notes), for example front \"What produces ATP?\", back \"Mitochondria\". Save them with add_cards.","hideSeed":true,"standalone":true,"turn":{"tool":"add_cards","when":{"op":"equals","field":"status","value":"forging"}}}},{"name":"page_add_cards","description":"Add flashcards to the deck: a cards array of {front, back} objects, one fact per card, at most 8 at a time. The deck's summary becomes your reply.","script":"deck-store","inputs":{"type":"object","properties":{"cards":{"type":"array","items":{"type":"object","properties":{"front":{"type":"string"},"back":{"type":"string"}},"required":["front","back"]},"description":"The cards to add."}},"required":["cards"]},"bind":{"action":"add_cards"},"turn":{"fallback":"Cards added to the deck.","show":"summary"}}],"pages":{"entry":"review/index.html","api":1,"reads":[{"source":"workspace","path":"deck.json"}],"tools":["record_review","finish_session","forge_from_notes","page_add_cards"]},"schedules":[],"workspaceSeed":["deck.json"],"artifactsSeed":[],"availableVersions":["1.2.2","1.2.1","1.2.0","1.1.2","1.1.1","1.1.0","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"freelance-office","name":"Freelance Office","description":"Run a one-person business without dropping anything. Your office administrator tracks every invoice to paid, drafts the polite chase, and keeps the income picture one question away.","tags":["freelance","invoices","clients","business","income"],"category":"money","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.4","releasedAt":"2026-11-01T06:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"business":{"type":"string","title":"What do you do?","description":"One line about the business — e.g. 'freelance brand design'.","default":"freelance work"}},"required":["business"]},"nameTemplate":"Freelance Office","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"kantoormeester","voorman":true}],"toolsets":[],"craftbooks":["proposal-sow","weekly-review"],"scripts":{"office-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'office-store',\n description:\n \"Read and update the invoice book (invoices.json). Call action:'status' for outstanding/overdue/paid-this-month; 'record_invoice' when work is billed (amount in ordinary units, e.g. 1200.00); 'invoice_sent' / 'invoice_paid' as reality moves; 'list_invoices' to read the book.\",\n inputs: {\n action: {\n type: 'string',\n description:\n \"One of 'status', 'record_invoice', 'invoice_sent', 'invoice_paid', or 'list_invoices'.\",\n required: true,\n },\n client: { type: 'string', description: 'Client name.' },\n amount: { type: 'number', description: 'Invoice amount in ordinary units, e.g. 1200.00.' },\n due: { type: 'string', description: 'Due date (ISO), e.g. 2026-08-15.' },\n note: { type: 'string', description: 'Short note (what the invoice covers).' },\n id: { type: 'string', description: \"Invoice id, e.g. 'inv-3'.\" },\n },\n outputs: {\n invoices: { type: 'number', description: 'Invoices in the book.' },\n outstandingCents: { type: 'number', description: 'Total sent-but-unpaid, in cents.' },\n overdue: { type: 'number', description: 'Count of overdue invoices.' },\n summary: { type: 'string', description: 'Human-readable office summary.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── office-rules-start ──\n// Pure derivations over rosterStore-shaped invoice records: statuses are\n// draft -> sent -> paid; fields carry {client, amountCents, dueAt, note}.\n\nfunction toCents(amount) {\n if (typeof amount !== 'number' || !isFinite(amount) || amount <= 0) return null;\n return Math.round(amount * 100);\n}\n\nfunction fmtCents(cents) {\n var sign = cents < 0 ? '-' : '';\n var abs = Math.abs(cents);\n return sign + Math.floor(abs / 100) + '.' + String(abs % 100).padStart(2, '0');\n}\n\nfunction officeShape(records, nowMs) {\n var outstanding = 0;\n var overdue = [];\n var paidMonth = 0;\n var month = new Date(nowMs).toISOString().slice(0, 7);\n records.forEach(function (r) {\n var cents = typeof r.fields.amountCents === 'number' ? r.fields.amountCents : 0;\n if (r.status === 'sent') {\n outstanding += cents;\n var due = typeof r.fields.dueAt === 'string' ? Date.parse(r.fields.dueAt) : NaN;\n if (isFinite(due) && due < nowMs) overdue.push(r);\n }\n if (r.status === 'paid' && r.updatedAt.slice(0, 7) === month) paidMonth += cents;\n });\n return { outstanding: outstanding, overdue: overdue, paidMonth: paidMonth, month: month };\n}\n\nfunction officeLine(records, nowMs) {\n var shape = officeShape(records, nowMs);\n var chase = shape.overdue\n .map(function (r) {\n return r.fields.client + ' (' + r.id + ', ' + fmtCents(r.fields.amountCents || 0) + ')';\n })\n .join(', ');\n return (\n 'Outstanding ' +\n fmtCents(shape.outstanding) +\n ' across ' +\n records.filter(function (r) {\n return r.status === 'sent';\n }).length +\n ' sent invoice(s); ' +\n shape.overdue.length +\n ' overdue' +\n (chase ? ' (' + chase + ')' : '') +\n '. Paid this month: ' +\n fmtCents(shape.paidMonth) +\n '.'\n );\n}\n// ── office-rules-end ──\n\nconst invoices = rosterStore(gezel.fs, 'invoices.json', {\n stages: ['draft', 'sent', 'paid'],\n idPrefix: 'inv',\n});\n\nif (input.action === 'record_invoice') {\n const cents = toCents(input.amount);\n if (!input.client || cents === null) {\n throw new Error(\"record_invoice needs 'client' and a positive 'amount' (ordinary units).\");\n }\n await invoices.add({\n fields: {\n client: input.client,\n amountCents: cents,\n ...(input.due ? { dueAt: input.due } : {}),\n ...(input.note ? { note: input.note } : {}),\n },\n });\n} else if (input.action === 'invoice_sent' || input.action === 'invoice_paid') {\n if (!input.id) throw new Error(\"Pass the invoice 'id', e.g. 'inv-3'.\");\n await invoices.transition(input.id, input.action === 'invoice_sent' ? 'sent' : 'paid');\n} else if (input.action !== 'status' && input.action !== 'list_invoices') {\n throw new Error(\n `Unknown action '${input.action}'. Use status, record_invoice, invoice_sent, invoice_paid, or list_invoices.`,\n );\n}\n\nconst records = await invoices.list();\nconst shape = officeShape(records, Date.now());\nconst listing =\n input.action === 'list_invoices'\n ? records\n .map(\n (r) =>\n `${r.id} [${r.status}] ${String(r.fields.client ?? '?')} ${fmtCents(Number(r.fields.amountCents ?? 0))}${r.fields.dueAt ? ` due ${String(r.fields.dueAt).slice(0, 10)}` : ''}`,\n )\n .join('\\n') || 'The invoice book is empty.'\n : '';\n\ngezel.output({\n invoices: records.length,\n outstandingCents: shape.outstanding,\n overdue: shape.overdue.length,\n summary: listing || officeLine(records, Date.now()),\n});\n"},"tools":[{"name":"record_invoice","description":"Add an invoice to the book (amount in ordinary units).","script":"office-store","inputs":{"type":"object","properties":{"client":{"type":"string"},"amount":{"type":"number"},"due":{"type":"string"},"note":{"type":"string"}},"required":["client","amount"]},"bind":{"action":"record_invoice"}},{"name":"invoice_sent","description":"Mark an invoice sent to the client.","script":"office-store","inputs":{"type":"object","properties":{"id":{"type":"string"}},"required":["id"]},"bind":{"action":"invoice_sent"}},{"name":"invoice_paid","description":"Mark an invoice paid.","script":"office-store","inputs":{"type":"object","properties":{"id":{"type":"string"}},"required":["id"]},"bind":{"action":"invoice_paid"}},{"name":"office_status","description":"The money picture: outstanding, overdue, paid this month.","script":"office-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"}},{"name":"list_invoices","description":"Read the whole invoice book.","script":"office-store","inputs":{"type":"object","properties":{}},"bind":{"action":"list_invoices"}},{"name":"page_record_invoice","description":"Add an invoice to the book (amount in ordinary units).","script":"office-store","inputs":{"type":"object","properties":{"client":{"type":"string"},"amount":{"type":"number"},"due":{"type":"string"},"note":{"type":"string"}},"required":["client","amount"]},"bind":{"action":"record_invoice"}},{"name":"page_invoice_sent","description":"Mark an invoice sent to the client.","script":"office-store","inputs":{"type":"object","properties":{"id":{"type":"string"}},"required":["id"]},"bind":{"action":"invoice_sent"}},{"name":"page_invoice_paid","description":"Mark an invoice paid.","script":"office-store","inputs":{"type":"object","properties":{"id":{"type":"string"}},"required":["id"]},"bind":{"action":"invoice_paid"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"invoices.json"}],"tools":["page_record_invoice","page_invoice_sent","page_invoice_paid"]},"schedules":[],"workspaceSeed":["invoices.json"],"artifactsSeed":[],"availableVersions":["1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"fundraiser-hq","name":"Fundraiser HQ","description":"Rally a community drive. An infectious fundraiser keeps the thermometer honest, drafts warm sponsor outreach and progress posts, and makes sure every single donor gets thanked.","tags":["fundraiser","donations","community","charity","drive"],"category":"events","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.4","releasedAt":"2026-11-01T06:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"cause":{"type":"string","title":"What are you raising for?","description":"e.g. 'new jerseys for the team', 'the library roof'.","default":"a good cause"},"goalCents":{"type":"number","title":"Goal (in cents)","description":"The target, in cents — e.g. 500000 for 5,000.00.","default":100000}},"required":["cause","goalCents"]},"nameTemplate":"Fundraiser: {{cause}}","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"aanjager","voorman":true}],"toolsets":[],"craftbooks":["social-thread","drive-wrap-up"],"scripts":{"drive-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { ledgerStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'drive-store',\n description:\n \"Read and update the fundraising drive (donations.json). Call action:'status' for the thermometer + unthanked list; 'record_donation' the moment a gift lands (ordinary units, donor name); 'mark_thanked' once the thank-you goes out.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'status', 'record_donation', 'mark_thanked', or 'donor_list'.\",\n required: true,\n },\n donor: { type: 'string', description: \"Donor name ('anonymous' is fine).\" },\n amount: { type: 'number', description: 'Gift amount in ordinary units.' },\n note: { type: 'string', description: 'Anything worth remembering about the gift.' },\n id: { type: 'string', description: \"Donation id, e.g. 'ledger-4'.\" },\n },\n outputs: {\n raisedCents: { type: 'number', description: 'Total raised, in cents.' },\n donors: { type: 'number', description: 'Number of gifts.' },\n unthanked: { type: 'number', description: 'Gifts still awaiting a thank-you.' },\n summary: { type: 'string', description: 'The drive picture.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── drive-rules-start ──\n// Pure derivations over ledgerStore-shaped donation entries: entries are\n// kind 'in', category 'donation', data {donor, thanked}.\n\nfunction toCents(amount) {\n if (typeof amount !== 'number' || !isFinite(amount) || amount <= 0) return null;\n return Math.round(amount * 100);\n}\n\nfunction fmtCents(cents) {\n var abs = Math.abs(cents);\n return (cents < 0 ? '-' : '') + Math.floor(abs / 100) + '.' + String(abs % 100).padStart(2, '0');\n}\n\nfunction driveShape(entries) {\n var raised = 0;\n var unthanked = [];\n entries.forEach(function (e) {\n raised += e.amountCents;\n if (!e.data || e.data.thanked !== true) unthanked.push(e);\n });\n return { raised: raised, unthanked: unthanked };\n}\n\nfunction driveLine(entries, goalCents) {\n var shape = driveShape(entries);\n var pct = goalCents > 0 ? Math.min(100, Math.round((shape.raised / goalCents) * 100)) : null;\n return (\n 'Raised ' +\n fmtCents(shape.raised) +\n (goalCents > 0 ? ' of ' + fmtCents(goalCents) + ' (' + pct + ' percent)' : '') +\n ' across ' +\n entries.length +\n ' gift(s). ' +\n (shape.unthanked.length === 0\n ? 'Everyone thanked.'\n : shape.unthanked.length + ' thank-you(s) still owed.')\n );\n}\n// ── drive-rules-end ──\n\nconst donations = ledgerStore(gezel.fs, 'donations.json');\n\nasync function readGoalCents(): Promise<number> {\n try {\n const parsed = JSON.parse(await gezel.fs.read('donations.json')) as { goalCents?: unknown };\n const goal = Number(parsed.goalCents);\n return Number.isFinite(goal) && goal > 0 ? Math.round(goal) : 0;\n } catch {\n return 0;\n }\n}\n\nif (input.action === 'record_donation') {\n const cents = toCents(input.amount);\n if (cents === null) throw new Error(\"record_donation needs a positive 'amount' (ordinary units).\");\n await donations.add({\n amountCents: cents,\n kind: 'in',\n category: 'donation',\n ...(input.note ? { note: input.note } : {}),\n data: { donor: input.donor || 'anonymous', thanked: false },\n });\n} else if (input.action === 'mark_thanked') {\n if (!input.id && !input.donor) throw new Error(\"Pass 'id' (e.g. 'ledger-4') or a unique 'donor'.\");\n // ledgerStore is append-only by design; thanked flips via a targeted\n // read-modify-write on the entry's data (the one mutation this drive needs).\n const raw = JSON.parse(await gezel.fs.read('donations.json')) as {\n entries: Array<{ id: string; data?: { donor?: string; thanked?: boolean } }>;\n };\n const matches = raw.entries.filter((e) =>\n input.id\n ? e.id === input.id\n : String(e.data?.donor ?? '').toLowerCase() === String(input.donor).toLowerCase() &&\n e.data?.thanked !== true,\n );\n if (matches.length === 0) throw new Error('No matching unthanked donation found.');\n if (matches.length > 1 && !input.id) {\n throw new Error(\n `Multiple unthanked gifts from '${input.donor}': ${matches.map((m) => m.id).join(', ')}. Pass id.`,\n );\n }\n matches[0]!.data = { ...(matches[0]!.data ?? {}), thanked: true };\n await gezel.fs.write('donations.json', `${JSON.stringify(raw, null, 2)}\\n`);\n} else if (input.action !== 'status' && input.action !== 'donor_list') {\n throw new Error(\n `Unknown action '${input.action}'. Use status, record_donation, mark_thanked, or donor_list.`,\n );\n}\n\nconst entries = await donations.list();\nconst goalCents = await readGoalCents();\nconst shape = driveShape(entries);\nconst listing =\n input.action === 'donor_list'\n ? entries\n .map(\n (e) =>\n `${e.id} ${fmtCents(e.amountCents)} from ${String(e.data?.donor ?? 'anonymous')}${e.data?.thanked === true ? '' : ' (thank-you owed)'}`,\n )\n .join('\\n') || 'No gifts yet.'\n : '';\n\ngezel.output({\n raisedCents: shape.raised,\n donors: entries.length,\n unthanked: shape.unthanked.length,\n summary: listing || driveLine(entries, goalCents),\n});\n"},"tools":[{"name":"record_donation","description":"Record a gift the moment it lands (ordinary units, donor name).","script":"drive-store","inputs":{"type":"object","properties":{"donor":{"type":"string"},"amount":{"type":"number"},"note":{"type":"string"}},"required":["amount"]},"bind":{"action":"record_donation"}},{"name":"mark_thanked","description":"Record that a thank-you went out for a gift.","script":"drive-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"donor":{"type":"string"}}},"bind":{"action":"mark_thanked"}},{"name":"drive_status","description":"The thermometer and the thank-you debt.","script":"drive-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"}},{"name":"donor_list","description":"Every gift, with thank-you state.","script":"drive-store","inputs":{"type":"object","properties":{}},"bind":{"action":"donor_list"}},{"name":"page_record_donation","description":"Record a gift the moment it lands (ordinary units, donor name).","script":"drive-store","inputs":{"type":"object","properties":{"donor":{"type":"string"},"amount":{"type":"number"},"note":{"type":"string"}},"required":["amount"]},"bind":{"action":"record_donation"}},{"name":"page_mark_thanked","description":"Record that a thank-you went out for a gift.","script":"drive-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"donor":{"type":"string"}}},"bind":{"action":"mark_thanked"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"donations.json"}],"tools":["page_record_donation","page_mark_thanked"]},"schedules":[],"workspaceSeed":["donations.json"],"artifactsSeed":[],"availableVersions":["1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"go","name":"Go","description":"Play Go against a gezel opponent on a live 9×9, 13×13, or 19×19 board. Place black stones; the Go player reads the exact position, replies in white, and keeps the conversation calm and sporting.","tags":["go","baduk","weiqi","game","board-game","strategy","play"],"category":"game","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.6","releasedAt":"2026-11-01T06:00:00.000Z","meesterManaged":false,"tabVisibility":{"overview":false,"tasks":false,"approvals":false,"workspace":false,"artifacts":false,"map":false},"mode":"solo","leadLabel":"Opponent","leanProfile":true,"params":{"type":"object","properties":{"personality":{"type":"string","title":"Table-talk style","description":"How your opponent talks between moves. In-character follows the gezel's own character when social mode is on.","enum":["in-character","peppy","cheeky","zen","gracious"],"default":"in-character"},"playStyle":{"type":"string","title":"How should the Go player play?","description":"An opponent keeps their strategy to themselves; an instructor offers light teaching notes.","enum":["Opponent","Instructor"],"default":"Opponent"}},"required":["personality","playStyle"]},"nameTemplate":"Go Table","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"go-player","voorman":true}],"toolsets":[],"craftbooks":[],"scripts":{"game-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\n\nexport const meta = defineScript({\n name: 'game-store',\n description:\n \"Read and update the Go game (game.json). Call action:'board' to see the position and every legal move; action:'ai_move' to play a coordinate such as D4 or 'pass' (optional moveThought); action:'state' for a light summary; action:'new_game' to reset with boardSize 9, 13, or 19 and optional komi. The engine enforces captures, suicide, simple ko, passing, and area scoring.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'state', 'board', 'user_move', 'ai_move', or 'new_game'.\",\n required: true,\n },\n move: {\n type: 'string',\n description: \"A board coordinate such as 'D4', or 'pass'.\",\n },\n boardSize: {\n type: 'number',\n description: 'For new_game: 9, 13, or 19. Defaults to 9.',\n },\n komi: {\n type: 'number',\n description: 'For new_game: points added to white. Defaults to 6.5.',\n },\n moveThought: {\n type: 'string',\n description: 'A short line of table talk to show on the board (max 140 chars).',\n },\n },\n outputs: {\n board: { type: 'string', description: 'ASCII board with coordinates.' },\n turn: { type: 'string', description: \"Whose move: 'user' (black) or 'ai' (white).\" },\n status: {\n type: 'string',\n description: 'playing, user_won, ai_won, or draw.',\n },\n lastMove: { type: 'string', description: \"The move just played, e.g. 'D4' or 'pass'.\" },\n legalMoves: { type: 'string', description: 'Legal placements plus pass.' },\n score: { type: 'string', description: 'Area score when the game has ended.' },\n summary: { type: 'string', description: 'Human-readable game summary.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── go-rules-start ──\n// Pure, annotation-free Go engine. Supports 9x9, 13x13, and 19x19.\n// Squares are row-major, y0 at the top. X = black/user; O = white/AI.\n// Coordinates follow Go convention and skip the letter I.\n\nvar GO_FILES = 'ABCDEFGHJKLMNOPQRST';\n\nfunction buildInitial(size) {\n return '.'.repeat(size * size);\n}\n\nfunction inBounds(x, y, size) {\n return x >= 0 && x < size && y >= 0 && y < size;\n}\n\nfunction pointName(x, y, size) {\n return GO_FILES[x] + String(size - y);\n}\n\nfunction parsePoint(name, size) {\n if (typeof name !== 'string') return null;\n var text = name.trim().toUpperCase();\n var match = /^([A-HJ-T])(\\d{1,2})$/.exec(text);\n if (!match) return null;\n var x = GO_FILES.indexOf(match[1]);\n var rank = Number(match[2]);\n if (x < 0 || x >= size || rank < 1 || rank > size) return null;\n return { x: x, y: size - rank, index: (size - rank) * size + x };\n}\n\nfunction neighbors(index, size) {\n var x = index % size;\n var y = Math.floor(index / size);\n var out = [];\n if (x > 0) out.push(index - 1);\n if (x + 1 < size) out.push(index + 1);\n if (y > 0) out.push(index - size);\n if (y + 1 < size) out.push(index + size);\n return out;\n}\n\nfunction groupAt(squares, index, size) {\n var color = squares[index];\n var stones = [];\n var liberties = {};\n var seen = {};\n var queue = [index];\n seen[index] = true;\n while (queue.length) {\n var current = queue.pop();\n stones.push(current);\n for (var next of neighbors(current, size)) {\n if (squares[next] === '.') liberties[next] = true;\n else if (squares[next] === color && !seen[next]) {\n seen[next] = true;\n queue.push(next);\n }\n }\n }\n return { stones: stones, liberties: Object.keys(liberties).map(Number) };\n}\n\nfunction replaceAt(squares, index, ch) {\n return squares.slice(0, index) + ch + squares.slice(index + 1);\n}\n\nfunction applyPlacement(squares, size, side, name, previousPosition) {\n var point = parsePoint(name, size);\n if (!point) return { error: 'bad-coordinate' };\n if (squares[point.index] !== '.') return { error: 'occupied' };\n var stone = side === 'user' ? 'X' : 'O';\n var enemy = side === 'user' ? 'O' : 'X';\n var next = replaceAt(squares, point.index, stone);\n var captures = [];\n var checked = {};\n for (var adjacent of neighbors(point.index, size)) {\n if (next[adjacent] !== enemy || checked[adjacent]) continue;\n var enemyGroup = groupAt(next, adjacent, size);\n for (var member of enemyGroup.stones) checked[member] = true;\n if (enemyGroup.liberties.length === 0) {\n for (var captured of enemyGroup.stones) {\n next = replaceAt(next, captured, '.');\n captures.push(pointName(captured % size, Math.floor(captured / size), size));\n }\n }\n }\n if (groupAt(next, point.index, size).liberties.length === 0) return { error: 'suicide' };\n if (previousPosition && next === previousPosition) return { error: 'ko' };\n return { squares: next, captures: captures };\n}\n\nfunction legalMovesFor(squares, size, side, previousPosition) {\n var moves = [];\n for (var y = 0; y < size; y += 1) {\n for (var x = 0; x < size; x += 1) {\n if (squares[y * size + x] !== '.') continue;\n var name = pointName(x, y, size);\n var result = applyPlacement(squares, size, side, name, previousPosition);\n if (!result.error) moves.push(name);\n }\n }\n moves.push('pass');\n return moves;\n}\n\nfunction scoreArea(squares, size, komi) {\n var blackStones = 0;\n var whiteStones = 0;\n var blackTerritory = 0;\n var whiteTerritory = 0;\n var seen = {};\n for (var i = 0; i < squares.length; i += 1) {\n if (squares[i] === 'X') {\n blackStones += 1;\n continue;\n }\n if (squares[i] === 'O') {\n whiteStones += 1;\n continue;\n }\n if (seen[i]) continue;\n var region = [];\n var borders = {};\n var queue = [i];\n seen[i] = true;\n while (queue.length) {\n var current = queue.pop();\n region.push(current);\n for (var next of neighbors(current, size)) {\n if (squares[next] === '.' && !seen[next]) {\n seen[next] = true;\n queue.push(next);\n } else if (squares[next] === 'X' || squares[next] === 'O') {\n borders[squares[next]] = true;\n }\n }\n }\n if (borders.X && !borders.O) blackTerritory += region.length;\n if (borders.O && !borders.X) whiteTerritory += region.length;\n }\n var black = blackStones + blackTerritory;\n var white = whiteStones + whiteTerritory + komi;\n return {\n black: black,\n white: white,\n blackStones: blackStones,\n whiteStones: whiteStones,\n blackTerritory: blackTerritory,\n whiteTerritory: whiteTerritory,\n winner: black === white ? 'draw' : black > white ? 'user' : 'ai',\n margin: Math.abs(black - white),\n };\n}\n\nfunction statusAfter(squares, size, komi, consecutivePasses) {\n if (consecutivePasses < 2) return 'playing';\n var score = scoreArea(squares, size, komi);\n return score.winner === 'draw' ? 'draw' : score.winner === 'user' ? 'user_won' : 'ai_won';\n}\n\nfunction renderAscii(squares, size) {\n var labels = [];\n for (var x = 0; x < size; x += 1) labels.push(GO_FILES[x]);\n var pad = size >= 10 ? ' ' : ' ';\n var lines = [pad + labels.join(' ')];\n for (var y = 0; y < size; y += 1) {\n var rank = String(size - y).padStart(size >= 10 ? 2 : 1, ' ');\n var row = [];\n for (var x = 0; x < size; x += 1) row.push(squares[y * size + x]);\n lines.push(rank + ' ' + row.join(' ') + ' ' + rank);\n }\n lines.push(pad + labels.join(' '));\n lines.push('X = black (user). O = white (you).');\n return lines.join('\\n');\n}\n// ── go-rules-end ──\n\nconst STATE_FILE = 'game.json';\nconst SIDE_NAMES = { user: 'black', ai: 'white' };\n\ninterface GameState {\n version: number;\n boardSize: number;\n squares: string;\n turn: 'user' | 'ai';\n status: 'playing' | 'user_won' | 'ai_won' | 'draw';\n komi: number;\n consecutivePasses: number;\n previousPosition: string | null;\n legalMoves: string[];\n captures: { user: number; ai: number };\n score: ReturnType<typeof scoreArea> | null;\n moveLog: Array<{\n by: 'user' | 'ai';\n move: string;\n captures: string[];\n at: string;\n moveThought?: string;\n }>;\n lastMove: { by: 'user' | 'ai'; move: string; captures: string[] } | null;\n lastMoveThought: string;\n updatedAt: string;\n}\n\nfunction validSize(value: unknown): number {\n const size = Number(value);\n return size === 13 || size === 19 ? size : 9;\n}\n\nfunction validKomi(value: unknown): number {\n const komi = Number(value);\n return Number.isFinite(komi) && komi >= 0 && komi <= 20 ? komi : 6.5;\n}\n\nfunction freshState(boardSize = 9, komi = 6.5): GameState {\n const size = validSize(boardSize);\n const nextKomi = validKomi(komi);\n const squares = buildInitial(size);\n return {\n version: 1,\n boardSize: size,\n squares,\n turn: 'user',\n status: 'playing',\n komi: nextKomi,\n consecutivePasses: 0,\n previousPosition: null,\n legalMoves: legalMovesFor(squares, size, 'user', null),\n captures: { user: 0, ai: 0 },\n score: null,\n moveLog: [],\n lastMove: null,\n lastMoveThought: '',\n updatedAt: new Date().toISOString(),\n };\n}\n\nasync function load(): Promise<GameState> {\n let raw: string;\n try {\n raw = await gezel.fs.read(STATE_FILE);\n } catch {\n return freshState();\n }\n const parsed = JSON.parse(raw) as Partial<GameState>;\n const size = validSize(parsed.boardSize);\n if (typeof parsed.squares !== 'string' || parsed.squares.length !== size * size) {\n throw new Error(`${STATE_FILE} is corrupt; call action:'new_game' to reset.`);\n }\n return {\n ...freshState(size, parsed.komi),\n ...parsed,\n boardSize: size,\n komi: validKomi(parsed.komi),\n } as GameState;\n}\n\nasync function persist(state: GameState): Promise<GameState> {\n state.legalMoves =\n state.status === 'playing'\n ? legalMovesFor(\n state.squares,\n state.boardSize,\n state.turn,\n state.previousPosition,\n )\n : [];\n state.updatedAt = new Date().toISOString();\n await gezel.fs.write(STATE_FILE, `${JSON.stringify(state, null, 2)}\\n`);\n return state;\n}\n\nfunction renderLegal(state: GameState): string {\n if (state.status !== 'playing') return '(game over)';\n return state.legalMoves.join(', ');\n}\n\nfunction renderScore(state: GameState): string {\n if (!state.score) return '(not scored — play continues)';\n const result =\n state.score.winner === 'draw'\n ? 'draw'\n : `${SIDE_NAMES[state.score.winner]} wins by ${state.score.margin}`;\n return `Black ${state.score.black}; white ${state.score.white} (includes ${state.komi} komi): ${result}.`;\n}\n\nfunction summarize(state: GameState): string {\n if (state.status !== 'playing') return `Game over. ${renderScore(state)}`;\n return `Move ${state.moveLog.length + 1}: ${SIDE_NAMES[state.turn]} (${state.turn}) to move on ${state.boardSize}x${state.boardSize}. Captures — black ${state.captures.user}, white ${state.captures.ai}.`;\n}\n\nfunction applyTurn(\n state: GameState,\n by: 'user' | 'ai',\n moveThought?: string,\n): GameState {\n if (state.status !== 'playing') {\n throw new Error(`The game is over (${state.status}). Call action:'new_game' to start another.`);\n }\n if (state.turn !== by) {\n throw new Error(by === 'ai' ? \"It's not your turn yet.\" : 'The opponent is still to move.');\n }\n const move = input.move?.trim() || '';\n const normalized = move.toLowerCase() === 'pass' ? 'pass' : move.toUpperCase();\n if (!state.legalMoves.includes(normalized)) {\n throw new Error(\n `Illegal move '${move}'. Legal moves for ${SIDE_NAMES[by]}: ${renderLegal(state)}`,\n );\n }\n\n let captured: string[] = [];\n const before = state.squares;\n if (normalized === 'pass') {\n state.consecutivePasses += 1;\n } else {\n const applied = applyPlacement(\n state.squares,\n state.boardSize,\n by,\n normalized,\n state.previousPosition,\n );\n if (applied.error || !applied.squares) {\n throw new Error(`Illegal move '${move}' (${applied.error || 'unknown'}).`);\n }\n state.squares = applied.squares;\n captured = applied.captures || [];\n state.captures[by] += captured.length;\n state.consecutivePasses = 0;\n }\n state.previousPosition = before;\n state.turn = (by === 'user' ? 'ai' : 'user') as 'user' | 'ai';\n state.status = statusAfter(\n state.squares,\n state.boardSize,\n state.komi,\n state.consecutivePasses,\n ) as GameState['status'];\n if (state.status !== 'playing') {\n state.score = scoreArea(state.squares, state.boardSize, state.komi);\n }\n const entry = {\n by,\n move: normalized,\n captures: captured,\n at: new Date().toISOString(),\n ...(moveThought ? { moveThought } : {}),\n };\n state.moveLog.push(entry);\n state.lastMove = { by, move: normalized, captures: captured };\n if (by === 'ai' && moveThought) state.lastMoveThought = moveThought;\n return state;\n}\n\nlet state = await load();\nlet lastMoveText = state.lastMove?.move ?? '(none)';\n\nif (input.action === 'new_game') {\n state = await persist(freshState(input.boardSize, input.komi));\n lastMoveText = '(none)';\n} else if (input.action === 'user_move' || input.action === 'ai_move') {\n const by = input.action === 'user_move' ? 'user' : 'ai';\n const moveThought = input.moveThought?.trim().slice(0, 140);\n state = await persist(applyTurn(state, by, moveThought));\n lastMoveText = state.lastMove?.move ?? '(none)';\n} else if (input.action !== 'state' && input.action !== 'board') {\n throw new Error(`Unknown action '${input.action}'. Use state, board, user_move, ai_move, or new_game.`);\n}\n\ngezel.output({\n board:\n `${renderAscii(state.squares, state.boardSize)}\\nTurn: ${SIDE_NAMES[state.turn]} (${state.turn}).\\n` +\n `Komi: ${state.komi}. Consecutive passes: ${state.consecutivePasses}.\\n` +\n `Legal moves: ${renderLegal(state)}`,\n turn: state.turn,\n status: state.status,\n lastMove: lastMoveText,\n legalMoves: renderLegal(state),\n score: renderScore(state),\n summary: summarize(state),\n});\n"},"tools":[{"name":"get_board","description":"See the authoritative Go position, board size, captures, whose turn it is, and every legal move.","script":"game-store","inputs":{"type":"object","properties":{}},"bind":{"action":"board"},"state":true},{"name":"make_move","description":"Play your white move. Pass a coordinate such as 'D4', or 'pass', plus optional moveThought.","script":"game-store","inputs":{"type":"object","properties":{"move":{"type":"string","description":"A legal coordinate such as 'D4', or 'pass'."},"moveThought":{"type":"string","description":"A short line of table talk (max 140 chars)."}},"required":["move"]},"bind":{"action":"ai_move"},"turn":{"say":"moveThought","fallback":"Move made — your turn."}},{"name":"user_move","description":"The user's black move or pass, played from the Go board.","script":"game-store","inputs":{"type":"object","properties":{"move":{"type":"string"}},"required":["move"]},"bind":{"action":"user_move"},"reaction":{"gezel":"go-player","prompt":"Your opponent played {{output.lastMove}}. Status: {{output.status}}. Board now:\n{{output.board}}\nThe board and Legal moves line come directly from the Go engine and are always correct. Do not re-derive captures, liberties, ko, scoring, or legality, and do not invent a coordinate outside the legal list. Spend your thought on choosing among the listed moves.\nStyle: {{playStyle}}. In Opponent style, do not volunteer advice or reveal the user’s available moves, weak groups, threats, or your plan; comment only about your own move or the atmosphere. In Instructor style, offer at most one brief teaching observation without choosing the user’s move. Answer strategy questions when asked.\nAct on this latest position. If the game is over, do not move — give one gracious line about the result and offer a new game. Otherwise choose a strong legal move (or pass when strategically sound) and play it with make_move, including a short {{personality}} moveThought. If make_move rejects it, choose one move verbatim from the legal list in the error and retry. After moving, reply with ONE short line of table talk.","hideSeed":true,"standalone":true,"turn":{"tool":"make_move","when":{"op":"equals","field":"status","value":"playing"}}}},{"name":"new_game","description":"Reset the Go board. Choose 9, 13, or 19 lines and optional komi; defaults to 9×9 with 6.5 komi.","script":"game-store","inputs":{"type":"object","properties":{"boardSize":{"type":"number","enum":[9,13,19]},"komi":{"type":"number","minimum":0,"maximum":20}}},"bind":{"action":"new_game"}}],"pages":{"entry":"board/index.html","api":1,"reads":[{"source":"workspace","path":"game.json"}],"tools":["user_move","new_game"]},"schedules":[],"workspaceSeed":["game.json"],"artifactsSeed":[],"availableVersions":["1.0.6","1.0.5","1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"household-budget","name":"Household Budget","description":"Know where the money actually goes. A calm household treasurer keeps the ledger, closes each month in minutes, and the live dashboard shows in, out, net, and the categories that matter.","tags":["budget","money","household","spending","ledger"],"category":"money","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.5","releasedAt":"2026-11-01T06:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"currency":{"type":"string","title":"Currency","description":"Shown on the dashboard; entries are unit-agnostic.","default":"USD"}},"required":["currency"]},"nameTemplate":"Household Budget","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"penningmeester","voorman":true}],"toolsets":[],"craftbooks":["subscription-audit","month-close"],"scripts":{"budget-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { ledgerStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'budget-store',\n description:\n \"Read and update the household ledger (ledger.json). Call action:'status' for this month's shape (in/out/net, top categories); 'add_expense' or 'add_income' the moment money moves (amount in ordinary units, e.g. 12.50); 'month_summary' with month 'YYYY-MM' for any past month.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'status', 'add_expense', 'add_income', or 'month_summary'.\",\n required: true,\n },\n amount: { type: 'number', description: 'Amount in ordinary currency units, e.g. 12.50.' },\n category: { type: 'string', description: \"Category, e.g. 'groceries', 'rent', 'salary'.\" },\n note: { type: 'string', description: 'Short note on the entry.' },\n month: { type: 'string', description: \"Month for month_summary, e.g. '2026-06'.\" },\n },\n outputs: {\n entries: { type: 'number', description: 'Total ledger entries.' },\n summary: { type: 'string', description: 'Human-readable money summary.' },\n netCents: { type: 'number', description: 'Net for the summarized month, in cents.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── budget-rules-start ──\n// Pure derivations shared with tests: cents conversion and the month\n// summary line, kept engine-side so the dashboard, the tools, and the\n// tests agree on one rendering.\n\nfunction toCents(amount) {\n if (typeof amount !== 'number' || !isFinite(amount) || amount <= 0) return null;\n return Math.round(amount * 100);\n}\n\nfunction fmtCents(cents) {\n var sign = cents < 0 ? '-' : '';\n var abs = Math.abs(cents);\n return sign + Math.floor(abs / 100) + '.' + String(abs % 100).padStart(2, '0');\n}\n\nfunction topCategories(byCategory, kind, limit) {\n return Object.entries(byCategory)\n .map(function (pair) {\n return { category: pair[0], cents: kind === 'out' ? pair[1].outCents : pair[1].inCents };\n })\n .filter(function (row) {\n return row.cents > 0;\n })\n .sort(function (a, b) {\n return b.cents - a.cents;\n })\n .slice(0, limit);\n}\n\nfunction monthLine(month, totals) {\n var top = topCategories(totals.byCategory, 'out', 3)\n .map(function (row) {\n return row.category + ' ' + fmtCents(row.cents);\n })\n .join(', ');\n return (\n month +\n ': in ' +\n fmtCents(totals.inCents) +\n ', out ' +\n fmtCents(totals.outCents) +\n ', net ' +\n fmtCents(totals.netCents) +\n (top ? '. Biggest: ' + top + '.' : '. No spending recorded.')\n );\n}\n// ── budget-rules-end ──\n\nconst ledger = ledgerStore(gezel.fs, 'ledger.json');\nconst currentMonth = new Date().toISOString().slice(0, 7);\n\nif (input.action === 'add_expense' || input.action === 'add_income') {\n const cents = toCents(input.amount);\n if (cents === null) throw new Error(\"Pass a positive 'amount' in ordinary units, e.g. 12.50.\");\n if (!input.category) throw new Error(\"Pass a 'category', e.g. 'groceries' or 'salary'.\");\n await ledger.add({\n amountCents: cents,\n kind: input.action === 'add_expense' ? 'out' : 'in',\n category: input.category.toLowerCase(),\n ...(input.note ? { note: input.note } : {}),\n });\n} else if (input.action !== 'status' && input.action !== 'month_summary') {\n throw new Error(\n `Unknown action '${input.action}'. Use status, add_expense, add_income, or month_summary.`,\n );\n}\n\nconst month =\n input.action === 'month_summary' && input.month ? input.month : currentMonth;\nconst totals = await ledger.totals({ month });\nconst all = await ledger.list();\n\ngezel.output({\n entries: all.length,\n summary: monthLine(month, totals),\n netCents: totals.netCents,\n});\n"},"tools":[{"name":"add_expense","description":"Record spending the moment it happens (amount in ordinary units).","script":"budget-store","inputs":{"type":"object","properties":{"amount":{"type":"number"},"category":{"type":"string"},"note":{"type":"string"}},"required":["amount","category"]},"bind":{"action":"add_expense"}},{"name":"add_income","description":"Record money coming in.","script":"budget-store","inputs":{"type":"object","properties":{"amount":{"type":"number"},"category":{"type":"string"},"note":{"type":"string"}},"required":["amount","category"]},"bind":{"action":"add_income"}},{"name":"budget_status","description":"This month's shape: in, out, net, and the biggest categories.","script":"budget-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"}},{"name":"month_summary","description":"Summarize any month ('YYYY-MM').","script":"budget-store","inputs":{"type":"object","properties":{"month":{"type":"string"}},"required":["month"]},"bind":{"action":"month_summary"}},{"name":"record_expense","description":"The dashboard's quick-add expense entry.","script":"budget-store","inputs":{"type":"object","properties":{"amount":{"type":"number"},"category":{"type":"string"},"note":{"type":"string"}},"required":["amount","category"]},"bind":{"action":"add_expense"}},{"name":"page_add_income","description":"Record money coming in.","script":"budget-store","inputs":{"type":"object","properties":{"amount":{"type":"number"},"category":{"type":"string"},"note":{"type":"string"}},"required":["amount","category"]},"bind":{"action":"add_income"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"ledger.json"}],"tools":["record_expense","page_add_income"]},"schedules":[],"workspaceSeed":["ledger.json"],"artifactsSeed":[],"availableVersions":["1.0.5","1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"household-manual","name":"Household Manual","description":"The living manual for your home. A home keeper keeps a card for every system — what care it needs and when — turns problems into flagged history, and the dashboard shows what the house needs this season.","tags":["home","maintenance","appliances","household"],"category":"home","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.4","releasedAt":"2026-11-01T06:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"home":{"type":"string","title":"What kind of home?","description":"e.g. 'a 1960s house', 'a third-floor apartment'.","default":"our home"}},"required":["home"]},"nameTemplate":"Household Manual","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"huismeester","voorman":true}],"toolsets":[],"craftbooks":["seasonal-maintenance-sweep"],"scripts":{"house-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'house-store',\n description:\n \"Read and update the home's system cards (systems.json). Call action:'status' for what's due or flagged; 'record_system' when an appliance/system comes up (with care interval in days when known); 'log_maintenance' when care happens; 'flag_attention' for problems; 'house_list' to read every card.\",\n inputs: {\n action: {\n type: 'string',\n description:\n \"One of 'status', 'record_system', 'log_maintenance', 'flag_attention', or 'house_list'.\",\n required: true,\n },\n name: { type: 'string', description: \"System name, e.g. 'Furnace', 'Smoke alarms'.\" },\n kind: { type: 'string', description: 'What it is (appliance, safety, structure, utility).' },\n location: { type: 'string', description: 'Where it lives in the house.' },\n care: { type: 'string', description: \"The care it needs, e.g. 'replace filter'.\" },\n intervalDays: { type: 'number', description: 'Care interval in days, when known.' },\n note: { type: 'string', description: 'Maintenance or attention note.' },\n id: { type: 'string', description: \"System id, e.g. 'sys-2'.\" },\n },\n outputs: {\n systems: { type: 'number', description: 'System cards in the manual.' },\n due: { type: 'number', description: 'Systems with care due.' },\n flagged: { type: 'number', description: 'Systems flagged for attention.' },\n summary: { type: 'string', description: 'What the house needs.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── house-rules-start ──\n// Pure derivations over rosterStore-shaped system cards: statuses are\n// ok -> attention; \"due\" derives from lastDoneAt + intervalDays.\n\nvar DAY_MS = 24 * 60 * 60 * 1000;\n\nfunction isDue(record, nowMs) {\n var f = record.fields || {};\n if (typeof f.intervalDays !== 'number' || f.intervalDays <= 0) return false;\n var last = typeof f.lastDoneAt === 'string' ? Date.parse(f.lastDoneAt) : Date.parse(record.createdAt);\n return isFinite(last) && nowMs - last >= f.intervalDays * DAY_MS;\n}\n\nfunction houseShape(records, nowMs) {\n var due = [];\n var flagged = [];\n records.forEach(function (r) {\n if (isDue(r, nowMs)) due.push(r);\n if (r.status === 'attention') flagged.push(r);\n });\n return { due: due, flagged: flagged };\n}\n\nfunction houseLine(records, nowMs) {\n var shape = houseShape(records, nowMs);\n var names = function (rows) {\n return rows\n .map(function (r) {\n return (r.fields && r.fields.name) || r.id;\n })\n .join(', ');\n };\n if (records.length === 0) return 'No systems recorded yet — start with the ones that need regular care.';\n var bits = [];\n if (shape.due.length) bits.push('care due: ' + names(shape.due));\n if (shape.flagged.length) bits.push('flagged: ' + names(shape.flagged));\n return records.length + ' system(s) on record. ' + (bits.length ? bits.join('; ') + '.' : 'Nothing due — the house is quiet.');\n}\n// ── house-rules-end ──\n\nconst house = rosterStore(gezel.fs, 'systems.json', {\n stages: ['ok', 'attention'],\n idPrefix: 'sys',\n});\n\nasync function resolveSystem(): Promise<string> {\n if (input.id) return input.id;\n if (input.name) {\n const wanted = input.name.toLowerCase();\n const matches = (await house.list()).filter(\n (r) => String(r.fields.name ?? '').toLowerCase() === wanted,\n );\n if (matches.length === 1) return matches[0]!.id;\n }\n throw new Error(\"Pass 'id' (e.g. 'sys-2') or an exact system 'name'.\");\n}\n\nif (input.action === 'record_system') {\n if (!input.name) throw new Error(\"record_system needs 'name'.\");\n await house.add({\n status: 'ok',\n fields: {\n name: input.name,\n ...(input.kind ? { kind: input.kind } : {}),\n ...(input.location ? { location: input.location } : {}),\n ...(input.care ? { care: input.care } : {}),\n ...(typeof input.intervalDays === 'number' ? { intervalDays: input.intervalDays } : {}),\n lastDoneAt: new Date().toISOString(),\n },\n });\n} else if (input.action === 'log_maintenance') {\n const id = await resolveSystem();\n await house.update(id, {\n fields: { lastDoneAt: new Date().toISOString() },\n ...(input.note ? { note: input.note } : {}),\n });\n await house.transition(id, 'ok');\n} else if (input.action === 'flag_attention') {\n const id = await resolveSystem();\n await house.transition(id, 'attention', input.note ? { note: input.note } : {});\n} else if (input.action !== 'status' && input.action !== 'house_list') {\n throw new Error(\n `Unknown action '${input.action}'. Use status, record_system, log_maintenance, flag_attention, or house_list.`,\n );\n}\n\nconst records = await house.list();\nconst shape = houseShape(records, Date.now());\nconst listing =\n input.action === 'house_list'\n ? records\n .map(\n (r) =>\n `${r.id} [${r.status}${isDue(r, Date.now()) ? ', due' : ''}] ${String(r.fields.name ?? '?')}${r.fields.location ? ` — ${String(r.fields.location)}` : ''}${r.fields.care ? ` (${String(r.fields.care)}${r.fields.intervalDays ? ` every ${String(r.fields.intervalDays)}d` : ''})` : ''}`,\n )\n .join('\\n') || 'No systems recorded yet.'\n : '';\n\ngezel.output({\n systems: records.length,\n due: shape.due.length,\n flagged: shape.flagged.length,\n summary: listing || houseLine(records, Date.now()),\n});\n"},"tools":[{"name":"record_system","description":"Add a system or appliance card (with a care interval in days when known).","script":"house-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"kind":{"type":"string"},"location":{"type":"string"},"care":{"type":"string"},"intervalDays":{"type":"number"}},"required":["name"]},"bind":{"action":"record_system"}},{"name":"log_maintenance","description":"Log that care happened (resets the due clock).","script":"house-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"note":{"type":"string"}}},"bind":{"action":"log_maintenance"}},{"name":"flag_attention","description":"Flag a problem on a system (a noise, a drip, a trip).","script":"house-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"note":{"type":"string"}},"required":["note"]},"bind":{"action":"flag_attention"}},{"name":"house_status","description":"What the house needs: care due and flagged problems.","script":"house-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"}},{"name":"house_list","description":"Read every system card.","script":"house-store","inputs":{"type":"object","properties":{}},"bind":{"action":"house_list"}},{"name":"page_record_system","description":"Add a system or appliance card (with a care interval in days when known).","script":"house-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"kind":{"type":"string"},"location":{"type":"string"},"care":{"type":"string"},"intervalDays":{"type":"number"}},"required":["name"]},"bind":{"action":"record_system"}},{"name":"page_log_maintenance","description":"Log that care happened (resets the due clock).","script":"house-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"note":{"type":"string"}}},"bind":{"action":"log_maintenance"}},{"name":"page_flag_attention","description":"Flag a problem on a system (a noise, a drip, a trip).","script":"house-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"note":{"type":"string"}},"required":["note"]},"bind":{"action":"flag_attention"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"systems.json"}],"tools":["page_record_system","page_log_maintenance","page_flag_attention"]},"schedules":[],"workspaceSeed":["systems.json"],"artifactsSeed":[],"availableVersions":["1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"image-feed","name":"Image Feed","description":"A visual feed with a working rhythm — your social media writer runs the posting pipeline, an image maker turns notions into pictures in the feed's own style, and a live gallery shows every post from first idea to published.","tags":["social","instagram","images","visual","posts"],"category":"creative","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.3","releasedAt":"2026-11-01T06:00:00.000Z","extends":"social-media","meesterManaged":true,"mode":"crew","leadLabel":"Social Media Writer","params":{"type":"object","properties":{"brand":{"type":"string","title":"Who does this feed speak for?","description":"The name, brand, or studio this feed speaks for.","default":"Our studio"},"instagramHandle":{"type":"string","title":"Instagram handle","description":"Instagram handle (e.g. @studio). Leave empty if unused.","default":""},"visualStyle":{"type":"string","title":"Visual style","description":"One sentence on how the feed should look — seeded into style-guide.md.","default":"Natural light, honest color, one subject per image."},"voice":{"type":"string","title":"Tone of voice","description":"One sentence on tone of voice for captions.","default":"Warm, plain, and human — never corporate."},"cadence":{"type":"string","title":"Posting cadence","description":"Target posting cadence (e.g. 4 images a week).","default":"4 images a week"}},"required":["brand"]},"nameTemplate":"{{brand}} Image Feed","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"omroeper","voorman":true},{"templateId":"image-generator","voorman":false}],"toolsets":[],"craftbooks":["draft-social-post","social-digest","reception-report"],"scripts":{"posts-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\n\nexport const meta = defineScript({\n name: 'posts-store',\n description:\n \"Read and update the post pipeline under posts/. Call action:'list' to see every post (optional status/platform filters); 'get' for one post's frontmatter, body, variants, and media; 'create' to commit the staged posts/_drafting/ folder as a real post; 'update' to patch frontmatter or move a post one pipeline stage (idea, draft, in-review, approved, scheduled, published, archived from anywhere); 'record_publication' to stamp a platform variant with its permalink after it goes live. Illegal stage jumps fail with the legal next stages — move one stage at a time.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'list', 'get', 'create', 'update', or 'record_publication'.\",\n required: true,\n },\n id: { type: 'string', description: \"Post id — its folder name under posts/, e.g. '2026-08-12-launch-teaser'.\" },\n status: {\n type: 'string',\n description: \"Target status: idea, draft, in-review, approved, scheduled, published, or archived. For 'create', the initial status (defaults to approved).\",\n },\n platform: { type: 'string', description: \"Platform filter for 'list', or the published variant for 'record_publication' (e.g. 'bluesky').\" },\n fields: {\n type: 'json',\n description: \"For 'update': an object of frontmatter patches, e.g. {\\\"scheduledFor\\\": \\\"2026-08-15T09:00:00Z\\\", \\\"campaign\\\": \\\"autumn\\\"}. A null value clears the key.\",\n },\n permalink: { type: 'string', description: 'Public URL of the live post, for record_publication.' },\n postId: { type: 'string', description: \"The platform's own id for the live post, for record_publication.\" },\n corpusRef: { type: 'string', description: 'Connector corpus record reference for the live post, when one exists.' },\n publishedAt: { type: 'string', description: 'ISO timestamp the post went live (defaults to now).' },\n markPublished: {\n type: 'boolean',\n description: 'For record_publication: force the post to published even if other target platforms are not stamped yet.',\n },\n },\n // Only what every action returns is declared: the runtime requires each\n // declared output on every run, so listing per-action fields here failed\n // every call. 'list' also returns posts + total, 'get' returns post, and\n // the writes return id + status.\n outputs: {\n summary: { type: 'string', description: 'Human-readable result.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\nconst POSTS_DIR = 'posts';\nconst DRAFTING = 'posts/_drafting';\nconst INDEX_FILE = 'posts/index.json';\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,99}$/;\nconst PLATFORM_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;\nconst STAGES = ['idea', 'draft', 'in-review', 'approved', 'scheduled', 'published'] as const;\nconst STATUSES: string[] = [...STAGES, 'archived'];\n\n// ── frontmatter ──\n// Hand-rolled, deliberately simple: `---`-delimited `key: value` lines,\n// arrays as [a, b]. Unknown keys and even unparseable lines are preserved\n// in order so a round-trip never loses what a human or another tool wrote.\n\ntype FmEntry = { key: string; value: string | string[] } | { raw: string };\ninterface FmDoc {\n entries: FmEntry[];\n body: string;\n}\n\nfunction parseArrayish(value: string): string[] {\n return value\n .slice(1, -1)\n .split(',')\n .map((part) => part.trim().replace(/^[\"']|[\"']$/g, ''))\n .filter((part) => part.length > 0);\n}\n\nfunction parseFrontmatter(text: string): FmDoc {\n const lines = text.split(/\\r?\\n/);\n if (lines[0]?.trim() !== '---') return { entries: [], body: text };\n const entries: FmEntry[] = [];\n let at = 1;\n for (; at < lines.length; at += 1) {\n const line = lines[at]!;\n if (line.trim() === '---') {\n return { entries, body: lines.slice(at + 1).join('\\n').replace(/^\\n/, '') };\n }\n const sep = line.indexOf(':');\n if (sep <= 0) {\n if (line.trim().length > 0) entries.push({ raw: line });\n continue;\n }\n const key = line.slice(0, sep).trim();\n const value = line.slice(sep + 1).trim();\n if (!key) {\n entries.push({ raw: line });\n continue;\n }\n entries.push({\n key,\n value: value.startsWith('[') && value.endsWith(']') ? parseArrayish(value) : value,\n });\n }\n return { entries: [], body: text };\n}\n\nfunction serializeFrontmatter(doc: FmDoc): string {\n const lines = doc.entries.map((entry) => {\n if ('raw' in entry) return entry.raw;\n const value = Array.isArray(entry.value) ? `[${entry.value.join(', ')}]` : entry.value;\n return `${entry.key}: ${value}`;\n });\n return `---\\n${lines.join('\\n')}\\n---\\n\\n${doc.body.replace(/^\\n+/, '')}`;\n}\n\nfunction fmGet(doc: FmDoc, key: string): string | string[] | undefined {\n for (const entry of doc.entries) {\n if ('key' in entry && entry.key === key) return entry.value;\n }\n return undefined;\n}\n\nfunction fmGetString(doc: FmDoc, key: string): string {\n const value = fmGet(doc, key);\n if (Array.isArray(value)) return value.join(', ');\n return value ?? '';\n}\n\nfunction fmGetArray(doc: FmDoc, key: string): string[] {\n const value = fmGet(doc, key);\n if (Array.isArray(value)) return value;\n if (typeof value === 'string' && value.length > 0) return [value];\n return [];\n}\n\nfunction fmSet(doc: FmDoc, key: string, value: string | string[]): void {\n for (const entry of doc.entries) {\n if ('key' in entry && entry.key === key) {\n entry.value = value;\n return;\n }\n }\n doc.entries.push({ key, value });\n}\n\nfunction fmDelete(doc: FmDoc, key: string): void {\n doc.entries = doc.entries.filter((entry) => !('key' in entry && entry.key === key));\n}\n\n// ── pipeline rules ──\n\nfunction legalNext(from: string): string[] {\n if (from === 'archived') return [];\n const at = STAGES.indexOf(from as (typeof STAGES)[number]);\n const forward = at >= 0 && at < STAGES.length - 1 ? [STAGES[at + 1]!] : [];\n return [...forward, 'archived'];\n}\n\nfunction assertTransition(id: string, from: string, to: string): void {\n if (to === from) return;\n if (!STATUSES.includes(to)) {\n throw new Error(`Unknown status '${to}'. Statuses: ${STATUSES.join(', ')}.`);\n }\n if (!legalNext(from).includes(to)) {\n const next = legalNext(from);\n throw new Error(\n `Cannot move '${id}' from ${from} to ${to} — posts move one stage at a time. ` +\n (next.length > 0 ? `Legal next: ${next.join(', ')}.` : `'${from}' is final; create a new post instead.`),\n );\n }\n}\n\nfunction requireId(): string {\n const id = (input.id ?? '').trim();\n if (!id) throw new Error(\"Pass 'id' — the post's folder name under posts/ (see action:'list').\");\n if (!ID_RE.test(id)) {\n throw new Error(`Invalid post id '${id}'. Ids are lowercase [a-z0-9-], no slashes or dots.`);\n }\n return id;\n}\n\nfunction today(): string {\n return new Date().toISOString().slice(0, 10);\n}\n\nfunction slugify(text: string): string {\n return text\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 60);\n}\n\n// ── store ──\n\ninterface IndexEntry {\n id: string;\n title: string;\n status: string;\n platforms: string[];\n created: string;\n scheduledFor?: string;\n campaign?: string;\n}\n\nasync function readPostDoc(id: string): Promise<FmDoc> {\n let raw: string;\n try {\n raw = await gezel.fs.read(`${POSTS_DIR}/${id}/post.md`);\n } catch {\n throw new Error(`No post '${id}' — posts/${id}/post.md does not exist. Call action:'list' to see what does.`);\n }\n return parseFrontmatter(raw);\n}\n\nasync function writePostDoc(id: string, doc: FmDoc): Promise<void> {\n await gezel.fs.write(`${POSTS_DIR}/${id}/post.md`, serializeFrontmatter(doc));\n}\n\nfunction toIndexEntry(id: string, doc: FmDoc): IndexEntry {\n const entry: IndexEntry = {\n id,\n title: fmGetString(doc, 'title') || id,\n status: fmGetString(doc, 'status') || 'idea',\n platforms: fmGetArray(doc, 'platforms'),\n created: fmGetString(doc, 'created') || today(),\n };\n const scheduledFor = fmGetString(doc, 'scheduledFor');\n if (scheduledFor) entry.scheduledFor = scheduledFor;\n const campaign = fmGetString(doc, 'campaign');\n if (campaign) entry.campaign = campaign;\n return entry;\n}\n\nasync function regenerateIndex(): Promise<IndexEntry[]> {\n let names: string[] = [];\n try {\n names = (await gezel.fs.list(POSTS_DIR))\n .filter((entry) => entry.isDirectory && entry.name !== '_drafting' && ID_RE.test(entry.name))\n .map((entry) => entry.name);\n } catch {\n names = [];\n }\n const posts: IndexEntry[] = [];\n for (const name of names) {\n try {\n posts.push(toIndexEntry(name, await readPostDoc(name)));\n } catch {\n // A folder without a parseable post.md is not a post; leave it be.\n }\n }\n posts.sort((a, b) => (a.created === b.created ? (a.id < b.id ? 1 : -1) : a.created < b.created ? 1 : -1));\n await gezel.fs.write(INDEX_FILE, `${JSON.stringify({ version: 1, posts }, null, 2)}\\n`);\n return posts;\n}\n\nasync function readIndex(): Promise<IndexEntry[]> {\n try {\n const parsed = JSON.parse(await gezel.fs.read(INDEX_FILE)) as { posts?: IndexEntry[] };\n return Array.isArray(parsed.posts) ? parsed.posts : [];\n } catch {\n return [];\n }\n}\n\nasync function listVariants(id: string): Promise<Record<string, Record<string, unknown>>> {\n let names: string[] = [];\n try {\n names = (await gezel.fs.list(`${POSTS_DIR}/${id}/variants`))\n .filter((entry) => !entry.isDirectory && entry.name.endsWith('.md'))\n .map((entry) => entry.name);\n } catch {\n return {};\n }\n const variants: Record<string, Record<string, unknown>> = {};\n for (const name of names) {\n const platform = name.slice(0, -3);\n const doc = parseFrontmatter(await gezel.fs.read(`${POSTS_DIR}/${id}/variants/${name}`));\n const body = doc.body.trim();\n const variant: Record<string, unknown> = {\n charCount: Number(fmGetString(doc, 'charCount')) || body.length,\n body,\n };\n for (const key of ['publishedAt', 'permalink', 'postId', 'corpusRef']) {\n const value = fmGetString(doc, key);\n if (value) variant[key] = value;\n }\n variants[platform] = variant;\n }\n return variants;\n}\n\nasync function listMedia(id: string): Promise<string[]> {\n try {\n return (await gezel.fs.list(`${POSTS_DIR}/${id}/media`))\n .filter((entry) => !entry.isDirectory)\n .map((entry) => entry.name);\n } catch {\n return [];\n }\n}\n\n// ── actions ──\n\nif (input.action === 'list') {\n const all = await readIndex();\n let posts = all;\n if (input.status) posts = posts.filter((post) => post.status === input.status);\n if (input.platform) posts = posts.filter((post) => post.platforms.includes(input.platform!));\n const counts = STATUSES.map((status) => {\n const n = all.filter((post) => post.status === status).length;\n return n > 0 ? `${status} ${n}` : null;\n })\n .filter((line) => line !== null)\n .join(', ');\n gezel.output({\n posts,\n total: all.length,\n summary: all.length === 0 ? 'No posts yet — stage one in posts/_drafting/ and call create.' : `${all.length} post(s): ${counts}.`,\n });\n} else if (input.action === 'get') {\n const id = requireId();\n const doc = await readPostDoc(id);\n const fields: Record<string, unknown> = {};\n for (const entry of doc.entries) {\n if ('key' in entry) fields[entry.key] = entry.value;\n }\n const post = {\n id,\n ...fields,\n status: fmGetString(doc, 'status') || 'idea',\n platforms: fmGetArray(doc, 'platforms'),\n body: doc.body.trim(),\n variants: await listVariants(id),\n media: await listMedia(id),\n };\n gezel.output({\n post,\n id,\n status: post.status,\n summary: `'${fmGetString(doc, 'title') || id}' is ${post.status}; ${Object.keys(post.variants).length} variant(s), ${post.media.length} media file(s).`,\n });\n} else if (input.action === 'create') {\n let staged: FmDoc;\n try {\n staged = parseFrontmatter(await gezel.fs.read(`${DRAFTING}/post.md`));\n } catch {\n throw new Error('Nothing is staged — write posts/_drafting/post.md (frontmatter + body) first, then call create again.');\n }\n const slug = slugify(fmGetString(staged, 'slug') || fmGetString(staged, 'title'));\n if (!slug) throw new Error(\"The staged post.md needs a 'slug' or a 'title' in its frontmatter to name the post folder.\");\n const createdRaw = fmGetString(staged, 'created');\n const created = /^\\d{4}-\\d{2}-\\d{2}$/.test(createdRaw) ? createdRaw : today();\n const id = `${created}-${slug}`;\n if (!ID_RE.test(id)) throw new Error(`Derived post id '${id}' is invalid — keep slug to lowercase letters, digits, and dashes.`);\n const siblings = await gezel.fs.list(POSTS_DIR).catch(() => []);\n if (siblings.some((entry) => entry.name === id)) {\n throw new Error(`posts/${id}/ already exists. Change the staged slug (or created date) and call create again.`);\n }\n const status = input.status ?? 'approved';\n if (!STATUSES.includes(status)) {\n throw new Error(`'${status}' is not a status. Statuses: ${STATUSES.join(', ')}.`);\n }\n fmSet(staged, 'status', status);\n fmSet(staged, 'slug', slug);\n fmSet(staged, 'created', created);\n await gezel.fs.write(`${DRAFTING}/post.md`, serializeFrontmatter(staged));\n await gezel.fs.rename(DRAFTING, `${POSTS_DIR}/${id}`);\n await regenerateIndex();\n gezel.output({\n id,\n status,\n summary: `Committed posts/_drafting/ as posts/${id}/ with status ${status}.`,\n });\n} else if (input.action === 'update') {\n const id = requireId();\n const doc = await readPostDoc(id);\n const patches = (input.fields && typeof input.fields === 'object' && !Array.isArray(input.fields) ? input.fields : {}) as Record<string, unknown>;\n let nextStatus = input.status;\n if (typeof patches.status === 'string' && !nextStatus) nextStatus = patches.status;\n delete patches.status;\n if (!nextStatus && Object.keys(patches).length === 0) {\n throw new Error(\"Nothing to change — pass 'status' and/or a 'fields' object of frontmatter patches.\");\n }\n const from = fmGetString(doc, 'status') || 'idea';\n if (nextStatus) assertTransition(id, from, nextStatus);\n for (const [key, value] of Object.entries(patches)) {\n if (value === null || value === undefined) fmDelete(doc, key);\n else if (Array.isArray(value)) fmSet(doc, key, value.map((item) => String(item)));\n else fmSet(doc, key, String(value));\n }\n if (nextStatus) fmSet(doc, 'status', nextStatus);\n await writePostDoc(id, doc);\n await regenerateIndex();\n const status = nextStatus ?? from;\n gezel.output({\n id,\n status,\n summary: nextStatus && nextStatus !== from ? `Moved '${id}' from ${from} to ${status}.` : `Updated '${id}' (${status}).`,\n });\n} else if (input.action === 'record_publication') {\n const id = requireId();\n const platform = (input.platform ?? '').trim();\n if (!PLATFORM_RE.test(platform)) {\n throw new Error(\"Pass 'platform' — the variant that went live, e.g. 'bluesky', 'x', or 'instagram'.\");\n }\n const doc = await readPostDoc(id);\n const variantPath = `${POSTS_DIR}/${id}/variants/${platform}.md`;\n const variant = parseFrontmatter(await gezel.fs.read(variantPath).catch(() => '---\\n---\\n'));\n fmSet(variant, 'publishedAt', input.publishedAt ?? new Date().toISOString());\n if (input.permalink) fmSet(variant, 'permalink', input.permalink);\n if (input.postId) fmSet(variant, 'postId', input.postId);\n if (input.corpusRef) fmSet(variant, 'corpusRef', input.corpusRef);\n await gezel.fs.write(variantPath, serializeFrontmatter(variant));\n const targets = fmGetArray(doc, 'platforms');\n const stamped = await listVariants(id);\n const allLive = targets.length > 0 && targets.every((target) => typeof stamped[target]?.publishedAt === 'string');\n let status = fmGetString(doc, 'status') || 'idea';\n // Recording reality bypasses the stage chain: once every target variant\n // is live (or the caller says so), the post IS published.\n if (allLive || input.markPublished === true) {\n status = 'published';\n fmSet(doc, 'status', status);\n await writePostDoc(id, doc);\n }\n await regenerateIndex();\n const waiting = targets.filter((target) => typeof stamped[target]?.publishedAt !== 'string');\n gezel.output({\n id,\n status,\n summary:\n status === 'published'\n ? `Recorded ${platform} publication for '${id}' — the post is published.`\n : `Recorded ${platform} publication for '${id}'; still waiting on: ${waiting.join(', ') || '(none)'}.`,\n });\n} else {\n throw new Error(`Unknown action '${input.action}'. Use list, get, create, update, or record_publication.`);\n}\n"},"tools":[{"name":"list_posts","description":"See the whole post pipeline: every post with its status, platforms, and dates. Optionally filter by status or platform.","script":"posts-store","inputs":{"type":"object","properties":{"status":{"type":"string","enum":["idea","draft","in-review","approved","scheduled","published","archived"],"description":"Only posts currently in this status."},"platform":{"type":"string","description":"Only posts targeting this platform, e.g. 'bluesky'."}}},"bind":{"action":"list"}},{"name":"get_post","description":"Read one post in full: frontmatter, body, each platform variant with its character count (and permalink once live), and media files.","script":"posts-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Post id — its folder name under posts/, e.g. '2026-08-12-launch-teaser'."}},"required":["id"]},"bind":{"action":"get"}},{"name":"create_post","description":"Commit the staged posts/_drafting/ folder as a real post. Stage post.md (frontmatter + body), variants/, and media/ there first; the post folder is named from the created date and slug.","script":"posts-store","inputs":{"type":"object","properties":{"status":{"type":"string","enum":["idea","draft","in-review","approved","scheduled","published","archived"],"description":"Initial status for the new post. Defaults to approved."}}},"bind":{"action":"create"}},{"name":"update_post","description":"Patch a post's frontmatter (fields object; null clears a key) and/or move it one pipeline stage. Stages run idea, draft, in-review, approved, scheduled, published — archived from anywhere.","script":"posts-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Post id."},"fields":{"type":"object","description":"Frontmatter patches, e.g. {\"scheduledFor\": \"2026-08-15T09:00:00Z\", \"campaign\": \"autumn\"}."},"status":{"type":"string","enum":["idea","draft","in-review","approved","scheduled","published","archived"],"description":"Target status (one stage at a time)."}},"required":["id"]},"bind":{"action":"update"}},{"name":"record_publication","description":"The moment a variant goes live, stamp it with its permalink and platform post id. The post flips to published once every target platform is stamped (or markPublished is passed).","script":"posts-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Post id."},"platform":{"type":"string","description":"The platform that went live, e.g. 'bluesky'."},"permalink":{"type":"string","description":"Public URL of the live post."},"postId":{"type":"string","description":"The platform's own id for the live post."},"corpusRef":{"type":"string","description":"Connector corpus record reference, when one exists."},"publishedAt":{"type":"string","description":"ISO timestamp it went live (defaults to now)."},"markPublished":{"type":"boolean","description":"Force the post to published even with unstamped platforms."}},"required":["id","platform"]},"bind":{"action":"record_publication"}},{"name":"page_set_status","description":"Page-only: move a post between pipeline columns on the gallery.","script":"posts-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Post id."},"status":{"type":"string","enum":["idea","draft","in-review","approved","scheduled","published","archived"],"description":"The column the post was moved to."}},"required":["id","status"]},"bind":{"action":"update"},"reaction":{"gezel":"omroeper","prompt":"[Feed gallery]: The user moved post {{output.id}} to '{{output.status}}' on the gallery. Reply with ONE short line acknowledging the move. If it landed in 'draft', offer to run the draft-social-post craftbook on it. Do not restate the pipeline.","hideSeed":true}},{"name":"page_get_post","description":"Page-only: the detail drawer's read of one post with variants and media.","script":"posts-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Post id."}},"required":["id"]},"bind":{"action":"get"}}],"pages":{"entry":"gallery/index.html","api":1,"reads":[{"source":"workspace","path":"posts","subtree":true},{"source":"workspace","path":"style-guide.md"},{"source":"artifacts","path":"data","subtree":true}],"tools":["page_set_status","page_get_post"]},"schedules":[{"runMode":"night-shift","craftbook":"social-digest","consent":"ask","overlap":"skip"},{"runMode":"scheduled","cron":"0 15 * * 1","craftbook":"reception-report","consent":"ask","overlap":"skip"}],"workspaceSeed":["style-guide.md","posts/index.json"],"artifactsSeed":[],"notes":"posts/index.json is seeded at its subpath (applyProjectType preserves seed subpaths and creates parents) and is ALSO regenerated by posts-store on every mutation, so the gallery tolerates a missing or stale index. Posts live one folder per post under posts/ (post.md + variants/ + media/), staged in posts/_drafting/ until create_post commits them. page_set_status and page_get_post are the page-only twins of update_post/get_post — pages.tools names are removed from the model surface, so the model keeps its own read tools.","availableVersions":["1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"job-hunt","name":"Job Hunt","description":"Run your job search like a campaign — a career coach tracks every application through the pipeline, a mock interviewer gets you ready, and a live board keeps the whole slog navigable.","tags":["job","career","interview","resume","offer"],"category":"growth","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.5","releasedAt":"2026-11-01T06:00:00.000Z","extends":"job-hunt","meesterManaged":false,"params":{"type":"object","properties":{"role":{"type":"string","title":"What role are you hunting for?","description":"The role or title you're targeting — e.g. Staff Engineer, Product Designer, Data Analyst.","default":"Software Engineer"},"focus":{"type":"string","title":"Anything about your search?","description":"Optional context for your coach — location constraints, timeline, dream companies.","default":"Just getting started."}},"required":["role"]},"nameTemplate":"{{role}} Job Hunt","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"career-coach","voorman":true},{"templateId":"mock-interviewer","voorman":false}],"toolsets":[],"craftbooks":["tailor-resume","company-research-brief","mock-interview","offer-compare","weekly-pipeline-review"],"scripts":{"application-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { logStore, rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'application-store',\n description:\n \"Read and update the job-search pipeline (applications in pipeline.json, activity in activity.json). Call action:'status' at the start of a session to see where the search stands; 'record_application' the moment the user mentions applying somewhere; 'advance_stage' when reality moves; 'log_activity' for follow-ups, scheduled interviews, and thank-yous.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'status', 'record_application', 'advance_stage', or 'log_activity'.\",\n required: true,\n },\n company: { type: 'string', description: 'Company name (identifies the application when id is omitted).' },\n role: { type: 'string', description: 'Role title for a new application.' },\n link: { type: 'string', description: 'Posting or application link.' },\n notes: { type: 'string', description: 'Free-form notes for a new application.' },\n id: { type: 'string', description: \"Application id (e.g. 'acme-staff-engineer') when advancing or logging.\" },\n stage: {\n type: 'string',\n description: 'Target stage for advance_stage: applied, screening, interview, offer, or closed.',\n },\n outcome: { type: 'string', description: \"With stage 'closed': signed, rejected, or withdrawn.\" },\n kind: {\n type: 'string',\n description: \"Activity kind for log_activity: follow-up, interview-scheduled, thank-you, offer-received, or note.\",\n },\n note: { type: 'string', description: 'The activity note for log_activity, or a note on a stage change.' },\n due: { type: 'string', description: 'Due date (ISO) for a follow-up.' },\n },\n outputs: {\n applications: { type: 'number', description: 'Total applications tracked.' },\n summary: { type: 'string', description: 'Human-readable pipeline summary.' },\n stale: { type: 'json', description: 'Active applications untouched for over 7 days.' },\n followUps: { type: 'json', description: 'Follow-ups due within 7 days or overdue.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\nconst STAGES: [string, ...string[]] = ['applied', 'screening', 'interview', 'offer', 'closed'];\nconst OUTCOMES = ['signed', 'rejected', 'withdrawn'];\nconst WEEK_MS = 7 * 24 * 60 * 60 * 1000;\n\nconst roster = rosterStore(gezel.fs, 'pipeline.json', { stages: STAGES, idPrefix: 'app' });\nconst activity = logStore(gezel.fs, 'activity.json');\n\nfunction slugify(s: string): string {\n return (\n s\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '') || 'application'\n );\n}\n\nasync function freshId(company: string, role?: string): Promise<string> {\n const base = slugify(role ? `${company} ${role}` : company);\n let candidate = base;\n for (let n = 2; (await roster.get(candidate)) !== null; n += 1) {\n candidate = `${base}-${n}`;\n }\n return candidate;\n}\n\nasync function resolveId(): Promise<string> {\n if (input.id) {\n if ((await roster.get(input.id)) === null) throw new Error(`No application '${input.id}'.`);\n return input.id;\n }\n if (input.company) {\n const wanted = input.company.toLowerCase();\n const matches = (await roster.list()).filter(\n (r) => String(r.fields.company ?? '').toLowerCase() === wanted,\n );\n if (matches.length === 1) return matches[0]!.id;\n if (matches.length > 1) {\n throw new Error(\n `Multiple applications match company '${input.company}': ${matches.map((m) => m.id).join(', ')}. Pass id.`,\n );\n }\n }\n throw new Error(\"Pass 'id' or a unique 'company' to identify the application.\");\n}\n\nasync function summarize(): Promise<{\n applications: number;\n summary: string;\n stale: unknown[];\n followUps: unknown[];\n}> {\n const records = await roster.list();\n const counts = await roster.counts();\n const now = Date.now();\n const stale = records\n .filter((r) => r.status !== 'closed' && now - Date.parse(r.updatedAt) > WEEK_MS)\n .map((r) => ({\n id: r.id,\n company: r.fields.company ?? r.id,\n stage: r.status,\n daysQuiet: Math.floor((now - Date.parse(r.updatedAt)) / (24 * 60 * 60 * 1000)),\n }));\n const followUps = (await activity.list({ kind: 'follow-up' }))\n .filter((e) => {\n const due = typeof e.data?.dueAt === 'string' ? Date.parse(e.data.dueAt) : null;\n return due !== null && due <= now + WEEK_MS;\n })\n .map((e) => ({\n note: e.note ?? '',\n dueAt: e.data?.dueAt,\n applicationId: e.data?.applicationId,\n overdue: typeof e.data?.dueAt === 'string' && Date.parse(e.data.dueAt) < now,\n }));\n const active = records.filter((r) => r.status !== 'closed').length;\n const stageLine = STAGES.filter((s) => (counts[s] ?? 0) > 0)\n .map((s) => `${s} ${counts[s]}`)\n .join(', ');\n const summary = records.length\n ? `${active} application(s) in play (${stageLine || 'none'}). ${stale.length} stale, ${followUps.length} follow-up(s) due this week.`\n : 'No applications tracked yet.';\n return { applications: records.length, summary, stale, followUps };\n}\n\nif (input.action === 'record_application') {\n if (!input.company) throw new Error(\"record_application needs 'company'.\");\n const id = await freshId(input.company, input.role);\n const record = await roster.add({\n id,\n fields: {\n company: input.company,\n ...(input.role ? { role: input.role } : {}),\n ...(input.link ? { link: input.link } : {}),\n ...(input.notes ? { notes: input.notes } : {}),\n },\n });\n await activity.append({\n kind: 'applied',\n note: `Applied to ${input.company}${input.role ? ` for ${input.role}` : ''}.`,\n data: { applicationId: record.id },\n });\n} else if (input.action === 'advance_stage') {\n if (!input.stage) throw new Error(\"advance_stage needs 'stage'.\");\n if (!STAGES.includes(input.stage)) {\n throw new Error(`Unknown stage '${input.stage}'. Stages: ${STAGES.join(', ')}.`);\n }\n if (input.outcome && input.stage !== 'closed') {\n throw new Error(\"'outcome' only applies when closing (stage 'closed').\");\n }\n if (input.outcome && !OUTCOMES.includes(input.outcome)) {\n throw new Error(`Unknown outcome '${input.outcome}'. Outcomes: ${OUTCOMES.join(', ')}.`);\n }\n const id = await resolveId();\n await roster.transition(id, input.stage, input.note ? { note: input.note } : {});\n if (input.outcome) await roster.update(id, { fields: { outcome: input.outcome } });\n const company = String((await roster.get(id))?.fields.company ?? id);\n await activity.append({\n kind: 'stage',\n note: `${company} moved to ${input.stage}${input.outcome ? ` (${input.outcome})` : ''}.`,\n data: { applicationId: id },\n });\n} else if (input.action === 'log_activity') {\n if (!input.note) throw new Error(\"log_activity needs 'note'.\");\n let applicationId: string | undefined;\n if (input.id || input.company) {\n applicationId = await resolveId();\n // A logged touch counts as attention — it resets the staleness clock.\n await roster.update(applicationId, input.note ? { note: input.note } : {});\n }\n await activity.append({\n kind: input.kind ?? 'note',\n note: input.note,\n data: {\n ...(applicationId ? { applicationId } : {}),\n ...(input.due ? { dueAt: input.due } : {}),\n },\n });\n} else if (input.action !== 'status') {\n throw new Error(\n `Unknown action '${input.action}'. Use status, record_application, advance_stage, or log_activity.`,\n );\n}\n\ngezel.output(await summarize());\n"},"tools":[{"name":"record_application","description":"Track a new job application the moment it happens.","script":"application-store","inputs":{"type":"object","properties":{"company":{"type":"string","description":"Company name."},"role":{"type":"string","description":"Role title."},"link":{"type":"string","description":"Posting or application link."},"notes":{"type":"string","description":"Anything worth remembering about this one."}},"required":["company"]},"bind":{"action":"record_application"}},{"name":"advance_stage","description":"Move an application to a new pipeline stage (applied, screening, interview, offer, closed).","script":"application-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Application id."},"company":{"type":"string","description":"Company name (when id is omitted)."},"stage":{"type":"string","enum":["applied","screening","interview","offer","closed"],"description":"The stage reality moved to."},"note":{"type":"string","description":"What happened."},"outcome":{"type":"string","enum":["signed","rejected","withdrawn"],"description":"Only when closing: how it ended."}},"required":["stage"]},"bind":{"action":"advance_stage"}},{"name":"log_activity","description":"Log activity on the search — a follow-up to send, an interview scheduled, a thank-you sent.","script":"application-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Application id this activity belongs to."},"company":{"type":"string","description":"Company name (when id is omitted)."},"kind":{"type":"string","enum":["follow-up","interview-scheduled","thank-you","offer-received","note"],"description":"What kind of activity this is."},"note":{"type":"string","description":"The activity itself."},"due":{"type":"string","description":"Due date (ISO) for a follow-up."}},"required":["note"]},"bind":{"action":"log_activity"}},{"name":"pipeline_status","description":"See the whole pipeline: counts per stage, stale applications, and follow-ups due this week.","script":"application-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"}},{"name":"page_record_application","description":"Track a new job application the moment it happens.","script":"application-store","inputs":{"type":"object","properties":{"company":{"type":"string","description":"Company name."},"role":{"type":"string","description":"Role title."},"link":{"type":"string","description":"Posting or application link."},"notes":{"type":"string","description":"Anything worth remembering about this one."}},"required":["company"]},"bind":{"action":"record_application"}},{"name":"page_advance_stage","description":"Move an application to a new pipeline stage (applied, screening, interview, offer, closed).","script":"application-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Application id."},"company":{"type":"string","description":"Company name (when id is omitted)."},"stage":{"type":"string","enum":["applied","screening","interview","offer","closed"],"description":"The stage reality moved to."},"note":{"type":"string","description":"What happened."},"outcome":{"type":"string","enum":["signed","rejected","withdrawn"],"description":"Only when closing: how it ended."}},"required":["stage"]},"bind":{"action":"advance_stage"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"pipeline.json"},{"source":"workspace","path":"activity.json"}],"tools":["page_record_application","page_advance_stage"]},"schedules":[{"runMode":"scheduled","cron":"0 17 * * 5","craftbook":"weekly-pipeline-review","consent":"ask","overlap":"skip"}],"workspaceSeed":["pipeline.json","activity.json"],"artifactsSeed":[],"availableVersions":["1.0.5","1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"language-trainer","name":"Language Trainer","description":"Practice a new language by chatting with a patient tutor who corrects gently and tracks your progress. Comes with a progress dashboard.","tags":["language","learning","tutor","conversation"],"category":"growth","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.1.1","releasedAt":"2026-11-01T06:00:00.000Z","extends":"content-writing","meesterManaged":false,"leanProfile":true,"params":{"type":"object","properties":{"language":{"type":"string","title":"Which language?","description":"The language you want to practice, e.g. Spanish, Japanese, French.","default":"Spanish"}},"required":["language"]},"nameTemplate":"{{language}} Language Trainer","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"language-trainer","voorman":true}],"toolsets":[],"craftbooks":[],"scripts":{"progress-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\n\nexport const meta = defineScript({\n name: 'progress-store',\n description:\n \"The language trainer's state: progress, the role-play scene in play, and the review deck of the student's corrections. action:'state' reads it; 'begin' starts a scene; 'reply' records the tutor's line and the errors it found in the student's last message; 'review' grades a review card; 'end' closes the scene; 'advance' moves up a level.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'state', 'begin', 'reply', 'review', 'end', 'advance' (or the older 'status', 'record').\",\n required: true,\n },\n scenario: { type: 'string', description: \"For begin: a scenario id or title, e.g. 'coffee'.\" },\n say: { type: 'string', description: \"For reply: the tutor's next line, in the language being practiced.\" },\n errors: {\n type: 'json',\n description: \"For reply: mistakes in the student's last message, [{ wrong, right, note? }], at most 3.\",\n },\n done: { type: 'boolean', description: \"For reply: true when the scene's goal is reached.\" },\n id: { type: 'string', description: \"For review: the review card id, e.g. 'r-3'.\" },\n verdict: { type: 'string', description: \"For review: 'got-it' or 'missed'.\" },\n note: { type: 'string', description: 'For advance or record: a short note.' },\n },\n outputs: {\n status: { type: 'string', description: \"'active' while a scene is in play, else 'idle' (or 'started' / 'done').\" },\n display: { type: 'string', description: \"For reply: the tutor's line plus the corrections, as shown.\" },\n level: { type: 'number', description: 'Current level (1+).' },\n streak: { type: 'number', description: 'Days in a row with practice.' },\n dueCount: { type: 'number', description: 'Review cards due now.' },\n message: { type: 'string', description: 'A short summary of the state.' },\n scene: { type: 'json', description: 'The scene in play: title, the part the tutor plays, setting, goal.' },\n dueReviews: { type: 'json', description: 'Up to three corrections due for review, { wrong, right }.' },\n scenarios: { type: 'json', description: 'Scenario ids open at this level (when no scene is in play).' },\n opening: { type: 'boolean', description: 'True right after begin: the tutor opens the scene.' },\n },\n requires: ['workspace.read', 'workspace.write', 'memory.write', 'reminders'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── review-rules-start ──\n// Corrections become review cards on three Leitner boxes: box 1 comes back\n// the next day, box 2 after three days, box 3 after a week. A card the\n// student gets right moves up; a miss, or the same mistake made again in\n// conversation, sends it back to box 1. Kept self-contained between these\n// sentinels so unit tests execute the shipped bytes.\nvar REVIEW_INTERVAL_DAYS = { 1: 1, 2: 3, 3: 7 };\nvar REVIEW_DAY_MS = 24 * 60 * 60 * 1000;\n\nfunction reviewDueAt(card) {\n if (!card.lastSeenAt) return 0;\n return Date.parse(card.lastSeenAt) + (REVIEW_INTERVAL_DAYS[card.box] || 1) * REVIEW_DAY_MS;\n}\n\nfunction dueReviews(cards, nowMs) {\n return cards\n .filter(function (c) {\n return reviewDueAt(c) <= nowMs;\n })\n .sort(function (a, b) {\n return a.box - b.box || reviewDueAt(a) - reviewDueAt(b);\n });\n}\n\nfunction nextReviewAt(cards, nowMs) {\n var next = Infinity;\n for (var i = 0; i < cards.length; i += 1) {\n var at = reviewDueAt(cards[i]);\n if (at > nowMs && at < next) next = at;\n }\n return next;\n}\n\nfunction cleanText(value, max) {\n return typeof value === 'string' ? value.replace(/\\s+/g, ' ').trim().slice(0, max) : '';\n}\n\n// The grading the model returned, made safe to store: at most three\n// mistakes, each a real change, without duplicates.\nfunction normalizeErrors(raw) {\n var list = Array.isArray(raw) ? raw : [];\n var out = [];\n for (var i = 0; i < list.length && out.length < 3; i += 1) {\n var e = list[i] || {};\n var wrong = cleanText(e.wrong, 80);\n var right = cleanText(e.right, 80);\n if (!wrong || !right || wrong.toLowerCase() === right.toLowerCase()) continue;\n if (out.some(function (o) { return o.wrong.toLowerCase() === wrong.toLowerCase(); })) continue;\n var note = cleanText(e.note, 80);\n out.push(note ? { wrong: wrong, right: right, note: note } : { wrong: wrong, right: right });\n }\n return out;\n}\n\n// Each mistake joins the deck, or sends its card back to box 1.\nfunction addCorrections(cards, errors, nowIso) {\n var max = 0;\n for (var i = 0; i < cards.length; i += 1) {\n var m = /^r-(\\d+)$/.exec(cards[i].id);\n if (m) max = Math.max(max, Number(m[1]));\n }\n for (var j = 0; j < errors.length; j += 1) {\n var e = errors[j];\n var found = cards.find(function (c) {\n return c.wrong.toLowerCase() === e.wrong.toLowerCase() && c.right.toLowerCase() === e.right.toLowerCase();\n });\n if (found) {\n found.box = 1;\n found.lastSeenAt = nowIso;\n found.repeats = (found.repeats || 0) + 1;\n } else {\n max += 1;\n cards.push({\n id: 'r-' + max,\n wrong: e.wrong,\n right: e.right,\n note: e.note || '',\n box: 1,\n lastSeenAt: nowIso,\n createdAt: nowIso,\n repeats: 0,\n });\n }\n }\n return cards;\n}\n\nfunction gradeReview(card, verdict, nowIso) {\n card.box = verdict === 'got-it' ? Math.min(3, card.box + 1) : 1;\n card.lastSeenAt = nowIso;\n return card;\n}\n\n// What the student sees: the tutor's line, then the corrections the app\n// recorded, so feedback never depends on the model writing it out.\nfunction displayLine(say, errors, done) {\n var text = say;\n if (errors.length) {\n text +=\n ' — Corrections: ' +\n errors\n .map(function (e) {\n return '\"' + e.wrong + '\" → \"' + e.right + '\"' + (e.note ? ' (' + e.note + ')' : '');\n })\n .join('; ') +\n '.';\n }\n if (done) text += ' Scene complete.';\n return text;\n}\n\n// The streak counts calendar days with practice, in the device's time zone.\nfunction practiceDay(nowMs) {\n var d = new Date(nowMs);\n return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');\n}\n\nfunction nextStreak(streak, lastDay, nowMs) {\n var today = practiceDay(nowMs);\n if (lastDay === today) return streak || 1;\n return lastDay === practiceDay(nowMs - REVIEW_DAY_MS) ? (streak || 0) + 1 : 1;\n}\n// ── review-rules-end ──\n\ninterface Scene {\n id: string;\n title: string;\n role: string;\n setting: string;\n goal: string;\n level: number;\n status: 'active' | 'done';\n turns: number;\n mistakes: number;\n startedAt: string;\n}\n\ninterface Progress {\n language: string;\n level: number;\n sessions: number;\n streak: number;\n lastPracticeDay: string | null;\n scene: Scene | null;\n history: Array<{ day: string; scene: string; turns: number; mistakes: number }>;\n notes: string[];\n}\n\ninterface Scenario {\n id: string;\n title: string;\n level: number;\n role: string;\n setting: string;\n goal: string;\n}\n\ninterface ReviewCard {\n id: string;\n wrong: string;\n right: string;\n note: string;\n box: number;\n lastSeenAt: string | null;\n createdAt: string;\n repeats: number;\n}\n\nasync function readJson<T>(path: string, fallback: T): Promise<T> {\n try {\n return JSON.parse(await gezel.fs.read(path)) as T;\n } catch {\n return fallback;\n }\n}\n\nasync function writeJson(path: string, value: unknown): Promise<void> {\n await gezel.fs.write(path, `${JSON.stringify(value, null, 2)}\\n`);\n}\n\nconst nowMs = Date.now();\nconst nowIso = new Date(nowMs).toISOString();\nconst raw = await readJson<Partial<Progress>>('progress.json', {});\nconst progress: Progress = {\n language: raw.language ?? 'your language',\n level: raw.level ?? 1,\n sessions: raw.sessions ?? 0,\n streak: raw.streak ?? 0,\n lastPracticeDay: raw.lastPracticeDay ?? null,\n scene: raw.scene ?? null,\n history: Array.isArray(raw.history) ? raw.history : [],\n notes: Array.isArray(raw.notes) ? raw.notes : [],\n};\nconst scenarios = (await readJson<{ scenarios?: Scenario[] }>('scenarios.json', {})).scenarios ?? [];\nconst deck = await readJson<{ items?: ReviewCard[] }>('reviews.json', {});\nconst cards: ReviewCard[] = Array.isArray(deck.items) ? deck.items : [];\n\nlet status: string = progress.scene?.status === 'active' ? 'active' : 'idle';\nlet display = '';\nlet progressChanged = false;\nlet cardsChanged = false;\n\nfunction findScenario(query: string): Scenario | undefined {\n const q = query.trim().toLowerCase();\n return (\n scenarios.find((s) => s.id === q) ??\n scenarios.find((s) => s.title.toLowerCase() === q) ??\n scenarios.find((s) => s.title.toLowerCase().includes(q) || q.includes(s.id))\n );\n}\n\nfunction practiced(): void {\n progress.streak = nextStreak(progress.streak, progress.lastPracticeDay, nowMs);\n progress.lastPracticeDay = practiceDay(nowMs);\n}\n\nfunction closeScene(): void {\n const scene = progress.scene;\n if (!scene || scene.status !== 'active') return;\n scene.status = 'done';\n progress.sessions += 1;\n progress.history = [\n ...progress.history,\n { day: practiceDay(nowMs), scene: scene.title, turns: scene.turns, mistakes: scene.mistakes },\n ].slice(-30);\n status = 'done';\n}\n\nswitch (input.action) {\n case 'begin': {\n const scenario = findScenario(String(input.scenario ?? ''));\n if (!scenario) {\n throw new Error(\n `No scenario '${input.scenario ?? ''}'. Choose one of: ${scenarios.map((s) => s.id).join(', ')}.`,\n );\n }\n progress.scene = {\n id: scenario.id,\n title: scenario.title,\n role: scenario.role,\n setting: scenario.setting,\n goal: scenario.goal,\n level: progress.level,\n status: 'active',\n turns: 0,\n mistakes: 0,\n startedAt: nowIso,\n };\n status = 'started';\n progressChanged = true;\n break;\n }\n case 'reply': {\n const say = String(input.say ?? '').replace(/\\s+/g, ' ').trim().slice(0, 240);\n if (!say) throw new Error(\"reply needs 'say': your next line, in the language being practiced.\");\n const errors = normalizeErrors(input.errors);\n if (errors.length) {\n addCorrections(cards, errors, nowIso);\n cardsChanged = true;\n for (const e of errors) {\n const text = `Said \"${e.wrong}\"; it is \"${e.right}\"${e.note ? ` (${e.note})` : ''}`.slice(0, 200);\n try {\n await gezel.memory.save(text, { kind: 'correction', scope: 'gezel' });\n } catch {\n // Memory is a bonus; the deck already holds the correction.\n }\n }\n }\n if (progress.scene?.status === 'active') {\n progress.scene.turns += 1;\n progress.scene.mistakes += errors.length;\n }\n practiced();\n // A scene ends once the student has played it: never on the opener, and\n // not before two lines of their own (a small model marked its first line done).\n const finished = input.done === true && (progress.scene?.turns ?? 0) >= 3;\n if (finished) closeScene();\n display = displayLine(say, errors, finished);\n progressChanged = true;\n break;\n }\n case 'review': {\n const card = cards.find((c) => c.id === input.id);\n if (!card || (input.verdict !== 'got-it' && input.verdict !== 'missed'))\n throw new Error(\"review needs a card 'id' and verdict 'got-it' or 'missed'.\");\n gradeReview(card, input.verdict, nowIso);\n cardsChanged = true;\n practiced();\n progressChanged = true;\n break;\n }\n case 'end': {\n closeScene();\n progressChanged = true;\n break;\n }\n case 'advance': {\n progress.level += 1;\n progress.notes = [\n ...progress.notes,\n `Advanced to level ${progress.level}${input.note ? `: ${input.note}` : ''}`,\n ].slice(-20);\n progressChanged = true;\n break;\n }\n case 'record': {\n practiced();\n if (input.note) progress.notes = [...progress.notes, String(input.note)].slice(-20);\n progressChanged = true;\n break;\n }\n case 'state':\n case 'status':\n break;\n default:\n throw new Error(`Unknown action '${input.action}'.`);\n}\n\nif (progressChanged) await writeJson('progress.json', progress);\nif (cardsChanged) {\n await writeJson('reviews.json', { items: cards });\n // The next card coming due is the one moment a reminder is earned.\n const next = nextReviewAt(cards, nowMs);\n try {\n if (Number.isFinite(next)) {\n const count = dueReviews(cards, next).length;\n await gezel.reminder.set({\n at: new Date(next).toISOString(),\n title: `${progress.language} review`,\n body: `${count} correction${count === 1 ? '' : 's'} ready to practice.`,\n });\n } else await gezel.reminder.clear();\n } catch {\n // A host without reminders still keeps the deck.\n }\n}\n\nconst due = dueReviews(cards, nowMs);\nconst scene = progress.scene;\nconst levelScenes = scenarios.filter((s) => s.level <= progress.level).map((s) => s.id);\ngezel.output({\n status,\n display,\n level: progress.level,\n streak: progress.streak,\n dueCount: due.length,\n scene:\n scene && scene.status === 'active'\n ? {\n title: scene.title,\n youPlay: scene.role,\n setting: scene.setting,\n studentGoal: scene.goal,\n turnsSoFar: scene.turns,\n }\n : null,\n opening: status === 'started',\n dueReviews: due.slice(0, 3).map((c) => ({ wrong: c.wrong, right: c.right })),\n scenarios: status === 'idle' ? levelScenes : [],\n message:\n status === 'active' || status === 'started'\n ? `Scene \"${scene?.title}\": you play the ${scene?.role}. First check the student's last message for mistakes (word gender, verb forms, agreement, word choice) and list each one in errors as { wrong, right }. Then answer in character, only in ${progress.language}.`\n : `Learning ${progress.language}: level ${progress.level}, ${progress.sessions} scene(s), ${progress.streak}-day streak, ${due.length} review(s) due.`,\n});\n"},"tools":[{"name":"practice_state","description":"Read the practice state: the scene in play (the part you play, the setting, the student's goal), the student's level and streak, and corrections due for review.","script":"progress-store","inputs":{"type":"object","properties":{}},"bind":{"action":"state"},"state":true,"answer":{"tool":"reply","when":{"op":"equals","field":"status","value":"active"}}},{"name":"reply","description":"Answer the student during a scene. `say` is your next line in the language being practiced, in character and at their level (one or two short sentences). `errors` lists up to three mistakes in the student's last message as { wrong, right, note? }, quoting their exact words in `wrong`; leave it empty when they made none. Set `done` only after the student has reached the scene's goal, never on your opening line.","script":"progress-store","inputs":{"type":"object","properties":{"say":{"type":"string","description":"Your next line, in the language being practiced (max 240 characters)."},"errors":{"type":"array","description":"Mistakes in the student's last message, at most three; an empty list when there were none.","items":{"type":"object","properties":{"wrong":{"type":"string","description":"The student's exact words."},"right":{"type":"string","description":"The corrected form."},"note":{"type":"string","description":"A very short reason, in English."}},"required":["wrong","right"]}},"done":{"type":"boolean","description":"True when the student reached the scene's goal."}},"required":["say","errors"]},"bind":{"action":"reply"},"turn":{"say":"say","fallback":"Your turn.","show":"display"}},{"name":"begin_scene","description":"Start a role-play scene the student asked for, by scenario id or title (coffee, market, neighbor, directions, pharmacy, luggage, restaurant, hotel, doctor, return). Then open it with reply.","script":"progress-store","inputs":{"type":"object","properties":{"scenario":{"type":"string","description":"Scenario id or title."}},"required":["scenario"]},"bind":{"action":"begin"}},{"name":"advance_level","description":"Advance the student to the next level when the current scenes feel comfortable.","script":"progress-store","inputs":{"type":"object","properties":{"note":{"type":"string"}}},"bind":{"action":"advance"}},{"name":"start_scene","description":"Start a scene from the dashboard.","script":"progress-store","inputs":{"type":"object","properties":{"scenario":{"type":"string"}},"required":["scenario"]},"bind":{"action":"begin"},"reaction":{"gezel":"language-trainer","prompt":"The student started the scene \"{{output.scene.title}}\". You play the {{output.scene.youPlay}}. Setting: {{output.scene.setting}} The student's goal: {{output.scene.studentGoal}} Open the scene with one short line in {{language}}, in character and at level {{output.level}}, through reply with no errors. The scene has only begun: do not set done.","hideSeed":true,"standalone":true,"turn":{"tool":"reply","when":{"op":"equals","field":"status","value":"started"}}}},{"name":"review_card","description":"Grade a review card from the dashboard.","script":"progress-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"verdict":{"type":"string"}},"required":["id","verdict"]},"bind":{"action":"review"}},{"name":"end_scene","description":"End the scene in play from the dashboard.","script":"progress-store","inputs":{"type":"object","properties":{}},"bind":{"action":"end"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"progress.json"},{"source":"workspace","path":"scenarios.json"},{"source":"workspace","path":"reviews.json"}],"tools":["start_scene","review_card","end_scene"]},"schedules":[],"workspaceSeed":["progress.json","scenarios.json","reviews.json"],"artifactsSeed":[],"availableVersions":["1.1.1","1.1.0","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"life-binder","name":"Life Binder","description":"The \"in case of emergency\" file, actually complete. A gentle archivist tracks wills, policies, accounts, and instructions — what exists, where it lives, what's missing.","tags":["estate","documents","emergency","family","insurance"],"category":"money","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.5","releasedAt":"2026-11-01T06:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"household":{"type":"string","title":"Who is this binder for?","description":"e.g. 'our family', 'Mom', 'me'.","default":"our family"}},"required":["household"]},"nameTemplate":"Life Binder","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"archivaris","voorman":true}],"toolsets":[],"craftbooks":["annual-document-review"],"scripts":{"binder-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'binder-store',\n description:\n \"Read and update the life binder (documents.json). Call action:'status' for the completeness picture; 'record_document' when a document exists (name + where the original lives); 'mark_missing' / 'mark_reviewed' as reality changes; 'checklist' to read everything.\",\n inputs: {\n action: {\n type: 'string',\n description:\n \"One of 'status', 'record_document', 'mark_missing', 'mark_reviewed', or 'checklist'.\",\n required: true,\n },\n name: { type: 'string', description: \"Document name, e.g. 'Will', 'Home insurance policy'.\" },\n location: { type: 'string', description: 'Where the original lives (drawer, safe, provider).' },\n note: { type: 'string', description: 'Anything a trusted person should know about it.' },\n id: { type: 'string', description: \"Document id, e.g. 'doc-2'.\" },\n },\n outputs: {\n total: { type: 'number', description: 'Documents on the checklist.' },\n present: { type: 'number', description: 'Recorded as existing.' },\n missing: { type: 'number', description: 'Known gaps.' },\n stale: { type: 'number', description: 'Present but unreviewed for over a year.' },\n summary: { type: 'string', description: 'The completeness picture.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── binder-rules-start ──\n// Pure derivations over rosterStore-shaped document records: statuses are\n// missing -> present; staleness is derived (present + unreviewed > 365d).\n\nvar YEAR_MS = 365 * 24 * 60 * 60 * 1000;\n\nfunction isStale(record, nowMs) {\n if (record.status !== 'present') return false;\n var reviewed = record.fields && typeof record.fields.reviewedAt === 'string'\n ? Date.parse(record.fields.reviewedAt)\n : Date.parse(record.updatedAt);\n return isFinite(reviewed) && nowMs - reviewed > YEAR_MS;\n}\n\nfunction binderShape(records, nowMs) {\n var present = 0;\n var missing = [];\n var stale = [];\n records.forEach(function (r) {\n if (r.status === 'present') {\n present += 1;\n if (isStale(r, nowMs)) stale.push(r);\n } else {\n missing.push(r);\n }\n });\n return { present: present, missing: missing, stale: stale };\n}\n\nfunction binderLine(records, nowMs) {\n var shape = binderShape(records, nowMs);\n var gaps = shape.missing\n .map(function (r) {\n return r.fields && r.fields.name ? r.fields.name : r.id;\n })\n .join(', ');\n var staleNames = shape.stale\n .map(function (r) {\n return r.fields && r.fields.name ? r.fields.name : r.id;\n })\n .join(', ');\n return (\n shape.present +\n ' of ' +\n records.length +\n ' in place' +\n (gaps ? '. Missing: ' + gaps : '. Nothing missing') +\n (staleNames ? '. Due a review: ' + staleNames + '.' : '.')\n );\n}\n// ── binder-rules-end ──\n\nconst binder = rosterStore(gezel.fs, 'documents.json', {\n stages: ['missing', 'present'],\n idPrefix: 'doc',\n});\n\nasync function resolveDoc(): Promise<string> {\n if (input.id) return input.id;\n if (input.name) {\n const wanted = input.name.toLowerCase();\n const matches = (await binder.list()).filter(\n (r) => String(r.fields.name ?? '').toLowerCase() === wanted,\n );\n if (matches.length === 1) return matches[0]!.id;\n }\n throw new Error(\"Pass 'id' (e.g. 'doc-2') or an exact document 'name'.\");\n}\n\nif (input.action === 'record_document') {\n if (!input.name) throw new Error(\"record_document needs 'name'.\");\n const existing = (await binder.list()).find(\n (r) => String(r.fields.name ?? '').toLowerCase() === input.name!.toLowerCase(),\n );\n if (existing) {\n await binder.update(existing.id, {\n fields: {\n ...(input.location ? { location: input.location } : {}),\n ...(input.note ? { note: input.note } : {}),\n reviewedAt: new Date().toISOString(),\n },\n });\n await binder.transition(existing.id, 'present');\n } else {\n await binder.add({\n status: 'present',\n fields: {\n name: input.name,\n ...(input.location ? { location: input.location } : {}),\n ...(input.note ? { note: input.note } : {}),\n reviewedAt: new Date().toISOString(),\n },\n });\n }\n} else if (input.action === 'mark_missing') {\n await binder.transition(await resolveDoc(), 'missing');\n} else if (input.action === 'mark_reviewed') {\n const id = await resolveDoc();\n await binder.update(id, { fields: { reviewedAt: new Date().toISOString() } });\n await binder.transition(id, 'present');\n} else if (input.action !== 'status' && input.action !== 'checklist') {\n throw new Error(\n `Unknown action '${input.action}'. Use status, record_document, mark_missing, mark_reviewed, or checklist.`,\n );\n}\n\nconst records = await binder.list();\nconst shape = binderShape(records, Date.now());\nconst listing =\n input.action === 'checklist'\n ? records\n .map(\n (r) =>\n `${r.id} [${r.status}${isStale(r, Date.now()) ? ', stale' : ''}] ${String(r.fields.name ?? '?')}${r.fields.location ? ` — ${String(r.fields.location)}` : ''}`,\n )\n .join('\\n') || 'The checklist is empty.'\n : '';\n\ngezel.output({\n total: records.length,\n present: shape.present,\n missing: shape.missing.length,\n stale: shape.stale.length,\n summary: listing || binderLine(records, Date.now()),\n});\n"},"tools":[{"name":"record_document","description":"Record that a document exists and where the original lives.","script":"binder-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"location":{"type":"string"},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"record_document"}},{"name":"mark_missing","description":"Mark a checklist item as a known gap.","script":"binder-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"}}},"bind":{"action":"mark_missing"}},{"name":"mark_reviewed","description":"Confirm a document was just reviewed and is current.","script":"binder-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"}}},"bind":{"action":"mark_reviewed"}},{"name":"binder_status","description":"The completeness picture: what's in place, missing, or due a review.","script":"binder-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"}},{"name":"checklist","description":"Read the whole checklist with locations.","script":"binder-store","inputs":{"type":"object","properties":{}},"bind":{"action":"checklist"}},{"name":"page_record_document","description":"Record that a document exists and where the original lives.","script":"binder-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"location":{"type":"string"},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"record_document"}},{"name":"page_mark_reviewed","description":"Confirm a document was just reviewed and is current.","script":"binder-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"}}},"bind":{"action":"mark_reviewed"}},{"name":"page_mark_missing","description":"Mark a checklist item as a known gap.","script":"binder-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"}}},"bind":{"action":"mark_missing"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"documents.json"}],"tools":["page_record_document","page_mark_reviewed","page_mark_missing"]},"schedules":[],"workspaceSeed":["documents.json"],"artifactsSeed":[],"availableVersions":["1.0.5","1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"meal-planner","name":"Meal Planner & Pantry","description":"Answer \"what's for dinner?\" once a week. A meal planner plans menus from what's actually in the pantry, keeps taste memory, and the grocery list writes itself.","tags":["meals","cooking","pantry","groceries","menu"],"category":"home","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.4","releasedAt":"2026-11-01T06:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"household":{"type":"string","title":"Who eats here?","description":"e.g. 'two adults, two picky kids', 'just me, vegetarian'.","default":"the household"}},"required":["household"]},"nameTemplate":"Meal Planner","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"maaltijdplanner","voorman":true}],"toolsets":[],"craftbooks":["weekly-menu-plan"],"scripts":{"kitchen-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'kitchen-store',\n description:\n \"Read and update the week's menu (menu.json) and the pantry (pantry.json). Call action:'status' for today's dinner + the grocery gap; 'set_menu' day by day; 'pantry_add' / 'pantry_level' as staples change; 'grocery_list' for the run.\",\n inputs: {\n action: {\n type: 'string',\n description:\n \"One of 'status', 'set_menu', 'pantry_add', 'pantry_level', or 'grocery_list'.\",\n required: true,\n },\n day: {\n type: 'string',\n description: \"Day for set_menu: monday..sunday.\",\n },\n meal: { type: 'string', description: 'The dinner for that day.' },\n name: { type: 'string', description: 'Pantry item name.' },\n level: { type: 'string', description: \"Pantry level: 'stocked', 'low', or 'out'.\" },\n id: { type: 'string', description: \"Pantry item id, e.g. 'item-3'.\" },\n },\n outputs: {\n planned: { type: 'number', description: 'Days with a planned dinner.' },\n groceries: { type: 'number', description: 'Items on the grocery list.' },\n summary: { type: 'string', description: 'The kitchen picture.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── kitchen-rules-start ──\n// Pure derivations: the weekly menu shape and the grocery gap (pantry\n// items marked low or out).\n\nvar DAYS = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];\n\nfunction normalizeDay(day) {\n if (typeof day !== 'string') return null;\n var d = day.toLowerCase();\n return DAYS.indexOf(d) >= 0 ? d : null;\n}\n\nfunction todayName(nowMs) {\n // getUTCDay: 0=Sunday.\n var idx = new Date(nowMs).getUTCDay();\n return DAYS[(idx + 6) % 7];\n}\n\nfunction groceryGap(records) {\n return records.filter(function (r) {\n return r.status === 'low' || r.status === 'out';\n });\n}\n\nfunction kitchenLine(menu, records, nowMs) {\n var today = todayName(nowMs);\n var tonight = menu.days && menu.days[today];\n var gap = groceryGap(records);\n var planned = DAYS.filter(function (d) {\n return menu.days && menu.days[d];\n }).length;\n return (\n (tonight ? \"Tonight: \" + tonight + '.' : 'Nothing planned for tonight.') +\n ' ' +\n planned +\n ' of 7 dinners planned. Grocery list: ' +\n (gap.length\n ? gap\n .map(function (r) {\n return (r.fields && r.fields.name) || r.id;\n })\n .join(', ')\n : 'empty')\n );\n}\n// ── kitchen-rules-end ──\n\nconst MENU_FILE = 'menu.json';\nconst pantry = rosterStore(gezel.fs, 'pantry.json', {\n stages: ['stocked', 'low', 'out'],\n idPrefix: 'item',\n});\n\ninterface Menu {\n version: number;\n days: Record<string, string>;\n updatedAt: string;\n}\n\nasync function loadMenu(): Promise<Menu> {\n try {\n const parsed = JSON.parse(await gezel.fs.read(MENU_FILE)) as Partial<Menu>;\n return {\n version: 1,\n days: parsed.days && typeof parsed.days === 'object' ? (parsed.days as Record<string, string>) : {},\n updatedAt: new Date().toISOString(),\n };\n } catch {\n return { version: 1, days: {}, updatedAt: new Date().toISOString() };\n }\n}\n\nasync function saveMenu(menu: Menu): Promise<void> {\n menu.updatedAt = new Date().toISOString();\n await gezel.fs.write(MENU_FILE, `${JSON.stringify(menu, null, 2)}\\n`);\n}\n\nasync function resolveItem(): Promise<string> {\n if (input.id) return input.id;\n if (input.name) {\n const wanted = input.name.toLowerCase();\n const matches = (await pantry.list()).filter(\n (r) => String(r.fields.name ?? '').toLowerCase() === wanted,\n );\n if (matches.length === 1) return matches[0]!.id;\n }\n throw new Error(\"Pass 'id' (e.g. 'item-3') or an exact pantry item 'name'.\");\n}\n\nconst menu = await loadMenu();\n\nif (input.action === 'set_menu') {\n const day = normalizeDay(input.day);\n if (!day || !input.meal) throw new Error(\"set_menu needs 'day' (monday..sunday) and 'meal'.\");\n menu.days[day] = input.meal;\n await saveMenu(menu);\n} else if (input.action === 'pantry_add') {\n if (!input.name) throw new Error(\"pantry_add needs 'name'.\");\n const level = input.level && ['stocked', 'low', 'out'].includes(input.level) ? input.level : 'stocked';\n await pantry.add({ status: level, fields: { name: input.name } });\n} else if (input.action === 'pantry_level') {\n if (!input.level || !['stocked', 'low', 'out'].includes(input.level)) {\n throw new Error(\"pantry_level needs level 'stocked', 'low', or 'out'.\");\n }\n await pantry.transition(await resolveItem(), input.level);\n} else if (input.action !== 'status' && input.action !== 'grocery_list') {\n throw new Error(\n `Unknown action '${input.action}'. Use status, set_menu, pantry_add, pantry_level, or grocery_list.`,\n );\n}\n\nconst records = await pantry.list();\nconst gap = groceryGap(records);\nconst listing =\n input.action === 'grocery_list'\n ? gap\n .map((r) => `${String(r.fields.name ?? r.id)} (${r.status})`)\n .join('\\n') || 'The grocery list is empty.'\n : '';\n\ngezel.output({\n planned: DAYS.filter((d) => menu.days[d]).length,\n groceries: gap.length,\n summary: listing || kitchenLine(menu, records, Date.now()),\n});\n"},"tools":[{"name":"set_menu","description":"Set a day's dinner (monday..sunday).","script":"kitchen-store","inputs":{"type":"object","properties":{"day":{"type":"string"},"meal":{"type":"string"}},"required":["day","meal"]},"bind":{"action":"set_menu"}},{"name":"pantry_add","description":"Add a pantry staple (level stocked, low, or out).","script":"kitchen-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"level":{"type":"string","enum":["stocked","low","out"]}},"required":["name"]},"bind":{"action":"pantry_add"}},{"name":"pantry_level","description":"Update a staple's level as the kitchen changes.","script":"kitchen-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"level":{"type":"string","enum":["stocked","low","out"]}},"required":["level"]},"bind":{"action":"pantry_level"}},{"name":"kitchen_status","description":"Tonight's dinner, the week's coverage, and the grocery gap.","script":"kitchen-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"}},{"name":"grocery_list","description":"The shopping run: everything low or out.","script":"kitchen-store","inputs":{"type":"object","properties":{}},"bind":{"action":"grocery_list"}},{"name":"page_set_menu","description":"Set a day's dinner (monday..sunday).","script":"kitchen-store","inputs":{"type":"object","properties":{"day":{"type":"string"},"meal":{"type":"string"}},"required":["day","meal"]},"bind":{"action":"set_menu"}},{"name":"page_pantry_add","description":"Add a pantry staple (level stocked, low, or out).","script":"kitchen-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"level":{"type":"string","enum":["stocked","low","out"]}},"required":["name"]},"bind":{"action":"pantry_add"}},{"name":"page_pantry_level","description":"Update a staple's level as the kitchen changes.","script":"kitchen-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"level":{"type":"string","enum":["stocked","low","out"]}},"required":["level"]},"bind":{"action":"pantry_level"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"menu.json"},{"source":"workspace","path":"pantry.json"}],"tools":["page_set_menu","page_pantry_add","page_pantry_level"]},"schedules":[],"workspaceSeed":["menu.json","pantry.json"],"artifactsSeed":[],"availableVersions":["1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"media-library","name":"Media Library","description":"Browse a folder of images, videos, and audio in a live gallery. Preview and play your media without importing or moving the originals.","tags":["photos","images","video","audio","gallery","library","folder"],"category":"creative","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.1","releasedAt":"2026-11-01T06:00:00.000Z","extends":"media-production","nameTemplate":"Media Library","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[],"toolsets":[],"craftbooks":[],"tools":[],"pages":{"imports":[{"id":"library","source":"workspace","path":".","accept":[".jpg",".jpeg",".png",".gif",".webp",".avif",".bmp",".svg",".ico",".heic",".heif",".tif",".tiff",".dng",".raw",".cr2",".cr3",".nef",".arw",".orf",".raf",".mp4",".webm",".mov",".m4v",".ogv",".avi",".mkv",".mpg",".mpeg",".mts",".m2ts",".mp3",".wav",".ogg",".oga",".m4a",".aac",".flac",".opus",".aif",".aiff",".wma"],"maxFileBytes":268435456}],"entry":"index.html","api":1,"reads":[{"source":"workspace","path":".","subtree":true}]},"schedules":[],"workspaceSeed":[],"artifactsSeed":[],"availableVersions":["1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"novel-writing-room","name":"Novel Writing Room","description":"A room for the long haul of a novel. A warm writing partner logs every writing session, keeps the chapter board honest, and reads drafts like a friend who wants the book to exist — with a live board of words and chapters.","tags":["writing","novel","fiction","drafting","wordcount"],"category":"writing","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.4","releasedAt":"2026-11-01T06:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"title":{"type":"string","title":"Working title","description":"The novel, as it is known today. Change it any time.","default":"Untitled"},"weeklyWordGoal":{"type":"number","title":"Words per week","description":"The weekly writing rhythm to aim for.","default":5000}},"required":["title","weeklyWordGoal"]},"nameTemplate":"Novel: {{title}}","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"schrijfmaat","voorman":true}],"toolsets":[],"craftbooks":["copy-review","ebook-compile"],"scripts":{"manuscript-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { logStore, rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'manuscript-store',\n description:\n \"Read and update the manuscript record (sessions.json + chapters.json). Call action:'status' for total words, weekly pace, and the chapter board; 'log_session' after every writing session (words written); 'add_chapter' / 'chapter_stage' to keep the board honest; 'outline' to list every chapter.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'status', 'log_session', 'add_chapter', 'chapter_stage', or 'outline'.\",\n required: true,\n },\n words: { type: 'number', description: 'Words written this session (log_session).' },\n note: { type: 'string', description: 'Anything worth remembering.' },\n title: { type: 'string', description: 'Chapter title (add_chapter).' },\n summary: { type: 'string', description: 'One-line chapter summary (add_chapter).' },\n id: { type: 'string', description: \"Chapter id, e.g. 'ch-3' (chapter_stage).\" },\n stage: {\n type: 'string',\n description: \"Target stage: 'outline', 'drafting', 'revised', or 'done' (chapter_stage).\",\n },\n },\n outputs: {\n totalWords: { type: 'number', description: 'Words logged across all sessions.' },\n thisWeekWords: { type: 'number', description: 'Words logged this week (Monday UTC start).' },\n chapters: { type: 'number', description: 'Chapters on the board.' },\n summary: { type: 'string', description: 'The manuscript picture.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── novel-rules-start ──\n// Pure derivations over logStore-shaped writing sessions (kind 'writing',\n// data {words}) and rosterStore-shaped chapters (stages outline → drafting\n// → revised → done). Weeks start Monday 00:00 UTC; nowIso is a parameter\n// so the rules stay clock-independent and testable.\n\nfunction sessionWords(e) {\n var words = e && e.data ? Number(e.data.words) : NaN;\n return isFinite(words) && words > 0 ? Math.round(words) : 0;\n}\n\nfunction totalWords(events) {\n return events.reduce(function (sum, e) {\n return sum + sessionWords(e);\n }, 0);\n}\n\nfunction weekStartMs(nowIso) {\n var day = new Date(nowIso.slice(0, 10) + 'T00:00:00Z');\n var sinceMonday = (day.getUTCDay() + 6) % 7;\n return day.getTime() - sinceMonday * 86400000;\n}\n\nfunction thisWeekWords(events, nowIso) {\n var start = weekStartMs(nowIso);\n return totalWords(\n events.filter(function (e) {\n return Date.parse(e.at) >= start;\n }),\n );\n}\n\nfunction chapterShape(records) {\n var byStage = { outline: 0, drafting: 0, revised: 0, done: 0 };\n records.forEach(function (r) {\n if (byStage[r.status] !== undefined) byStage[r.status] += 1;\n });\n return byStage;\n}\n\nfunction novelLine(events, records, nowIso, weeklyWordGoal) {\n var total = totalWords(events);\n var week = thisWeekWords(events, nowIso);\n var shape = chapterShape(records);\n var goal = weeklyWordGoal > 0 ? weeklyWordGoal : 0;\n return (\n total +\n ' words logged; ' +\n week +\n (goal > 0 ? ' of ' + goal : '') +\n ' this week. Chapters: ' +\n shape.outline +\n ' outlined, ' +\n shape.drafting +\n ' drafting, ' +\n shape.revised +\n ' revised, ' +\n shape.done +\n ' done.'\n );\n}\n// ── novel-rules-end ──\n\nconst sessions = logStore(gezel.fs, 'sessions.json');\nconst chapters = rosterStore(gezel.fs, 'chapters.json', {\n stages: ['outline', 'drafting', 'revised', 'done'],\n idPrefix: 'ch',\n});\n\nasync function readWeeklyWordGoal(): Promise<number> {\n try {\n const parsed = JSON.parse(await gezel.fs.read('sessions.json')) as { weeklyWordGoal?: unknown };\n const goal = Number(parsed.weeklyWordGoal);\n return Number.isFinite(goal) && goal > 0 ? Math.round(goal) : 0;\n } catch {\n return 0;\n }\n}\n\nif (input.action === 'log_session') {\n const words = Number(input.words);\n if (!Number.isFinite(words) || words <= 0) {\n throw new Error(\"log_session needs a positive 'words' count.\");\n }\n await sessions.append({\n kind: 'writing',\n ...(input.note ? { note: input.note } : {}),\n data: { words: Math.round(words) },\n });\n} else if (input.action === 'add_chapter') {\n if (!input.title) throw new Error(\"add_chapter needs a 'title'.\");\n await chapters.add({\n fields: { title: input.title, ...(input.summary ? { summary: input.summary } : {}) },\n ...(input.note ? { note: input.note } : {}),\n });\n} else if (input.action === 'chapter_stage') {\n if (!input.id || !input.stage) {\n throw new Error(\"chapter_stage needs 'id' (e.g. 'ch-3') and 'stage'.\");\n }\n await chapters.transition(input.id, input.stage, input.note ? { note: input.note } : undefined);\n} else if (input.action !== 'status' && input.action !== 'outline') {\n throw new Error(\n `Unknown action '${input.action}'. Use status, log_session, add_chapter, chapter_stage, or outline.`,\n );\n}\n\nconst events = await sessions.list();\nconst records = await chapters.list();\nconst weeklyWordGoal = await readWeeklyWordGoal();\nconst nowIso = new Date().toISOString();\nconst listing =\n input.action === 'outline'\n ? records\n .map(\n (r) =>\n `${r.id} [${r.status}] ${String(r.fields.title ?? '')}${r.fields.summary ? ` — ${String(r.fields.summary)}` : ''}`,\n )\n .join('\\n') || 'No chapters on the board yet.'\n : '';\n\ngezel.output({\n totalWords: totalWords(events),\n thisWeekWords: thisWeekWords(events, nowIso),\n chapters: records.length,\n summary: listing || novelLine(events, records, nowIso, weeklyWordGoal),\n});\n"},"tools":[{"name":"log_session","description":"Log a writing session (words written) the moment it is reported.","script":"manuscript-store","inputs":{"type":"object","properties":{"words":{"type":"number"},"note":{"type":"string"}},"required":["words"]},"bind":{"action":"log_session"}},{"name":"add_chapter","description":"Put a chapter on the board (starts in outline).","script":"manuscript-store","inputs":{"type":"object","properties":{"title":{"type":"string"},"summary":{"type":"string"}},"required":["title"]},"bind":{"action":"add_chapter"}},{"name":"chapter_stage","description":"Move a chapter between stages: 'outline', 'drafting', 'revised', 'done'.","script":"manuscript-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"stage":{"type":"string"},"note":{"type":"string"}},"required":["id","stage"]},"bind":{"action":"chapter_stage"}},{"name":"novel_status","description":"Total words, this week against the goal, the chapter shape.","script":"manuscript-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"}},{"name":"outline","description":"Every chapter with its stage and summary.","script":"manuscript-store","inputs":{"type":"object","properties":{}},"bind":{"action":"outline"}},{"name":"page_log_session","description":"Log a writing session (words written) the moment it is reported.","script":"manuscript-store","inputs":{"type":"object","properties":{"words":{"type":"number"},"note":{"type":"string"}},"required":["words"]},"bind":{"action":"log_session"}},{"name":"page_add_chapter","description":"Put a chapter on the board (starts in outline).","script":"manuscript-store","inputs":{"type":"object","properties":{"title":{"type":"string"},"summary":{"type":"string"}},"required":["title"]},"bind":{"action":"add_chapter"}},{"name":"page_chapter_stage","description":"Move a chapter between stages: 'outline', 'drafting', 'revised', 'done'.","script":"manuscript-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"stage":{"type":"string"},"note":{"type":"string"}},"required":["id","stage"]},"bind":{"action":"chapter_stage"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"sessions.json"},{"source":"workspace","path":"chapters.json"}],"tools":["page_log_session","page_add_chapter","page_chapter_stage"]},"schedules":[],"workspaceSeed":["sessions.json","chapters.json"],"artifactsSeed":[],"availableVersions":["1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"social-feed","name":"Social Feed","description":"Run a social feed like a small newsroom — a social media writer keeps every post moving through a real pipeline (idea to published, nothing by accident), a copywriter sharpens each variant for its platform, and a live board shows exactly where every post stands.","tags":["social","bluesky","x","linkedin","posts","publishing"],"category":"communication","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.4","releasedAt":"2026-11-01T06:00:00.000Z","extends":"social-media","meesterManaged":true,"mode":"crew","leadLabel":"Social Media Writer","params":{"type":"object","properties":{"brand":{"type":"string","title":"Who does this feed speak for?","description":"The name or brand this feed speaks for.","default":"Our brand"},"blueskyHandle":{"type":"string","title":"Bluesky handle","description":"Bluesky handle (e.g. you.bsky.social). Leave empty if unused.","default":""},"xHandle":{"type":"string","title":"X handle","description":"X handle (e.g. @brand). Leave empty if unused.","default":""},"linkedinHandle":{"type":"string","title":"LinkedIn profile or page","description":"LinkedIn profile or page name (e.g. in/yourname). Leave empty if unused.","default":""},"voice":{"type":"string","title":"Tone of voice","description":"One sentence on tone of voice — seeded into voice-guide.md.","default":"Warm, plain, and human — never corporate."},"cadence":{"type":"string","title":"Posting cadence","description":"Target posting cadence (e.g. 3 posts a week).","default":"3 posts a week"}},"required":["brand"]},"nameTemplate":"{{brand}} Social Feed","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"omroeper","voorman":true},{"templateId":"copywriter","voorman":false}],"toolsets":[],"craftbooks":["draft-social-post","social-digest","reception-report"],"scripts":{"posts-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\n\nexport const meta = defineScript({\n name: 'posts-store',\n description:\n \"Read and update the post pipeline under posts/. Call action:'list' to see every post (optional status/platform filters); 'get' for one post's frontmatter, body, variants, and media; 'create' to add a post from a title and body, or to commit the staged posts/_drafting/ folder as a real post; 'update' to patch frontmatter or move a post one pipeline stage (idea, draft, in-review, approved, scheduled, published, archived from anywhere); 'record_publication' to stamp a platform variant with its permalink after it goes live. Illegal stage jumps fail with the legal next stages — move one stage at a time.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'list', 'get', 'create', 'update', or 'record_publication'.\",\n required: true,\n },\n id: { type: 'string', description: \"Post id — its folder name under posts/, e.g. '2026-08-12-launch-teaser'.\" },\n status: {\n type: 'string',\n description: \"Target status: idea, draft, in-review, approved, scheduled, published, or archived. For 'create', the initial status (defaults to approved).\",\n },\n platform: { type: 'string', description: \"Platform filter for 'list', or the published variant for 'record_publication' (e.g. 'bluesky').\" },\n fields: {\n type: 'json',\n description: \"For 'update': an object of frontmatter patches, e.g. {\\\"scheduledFor\\\": \\\"2026-08-15T09:00:00Z\\\", \\\"campaign\\\": \\\"autumn\\\"}. A null value clears the key.\",\n },\n title: { type: 'string', description: \"For 'create': the post's title, to write it in one call.\" },\n body: { type: 'string', description: \"For 'create': the post's text, to write it in one call.\" },\n platforms: { type: 'string', description: \"For 'create': comma-separated platforms, e.g. 'linkedin, bluesky'.\" },\n permalink: { type: 'string', description: 'Public URL of the live post, for record_publication.' },\n postId: { type: 'string', description: \"The platform's own id for the live post, for record_publication.\" },\n corpusRef: { type: 'string', description: 'Connector corpus record reference for the live post, when one exists.' },\n publishedAt: { type: 'string', description: 'ISO timestamp the post went live (defaults to now).' },\n markPublished: {\n type: 'boolean',\n description: 'For record_publication: force the post to published even if other target platforms are not stamped yet.',\n },\n },\n // Only what every action returns is declared: the runtime requires each\n // declared output on every run, so listing per-action fields here failed\n // every call. 'list' also returns posts + total, 'get' returns post, and\n // the writes return id + status.\n outputs: {\n summary: { type: 'string', description: 'Human-readable result.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\nconst POSTS_DIR = 'posts';\nconst DRAFTING = 'posts/_drafting';\nconst INDEX_FILE = 'posts/index.json';\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,99}$/;\nconst PLATFORM_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;\nconst STAGES = ['idea', 'draft', 'in-review', 'approved', 'scheduled', 'published'] as const;\nconst STATUSES: string[] = [...STAGES, 'archived'];\n\n// ── frontmatter ──\n// Hand-rolled, deliberately simple: `---`-delimited `key: value` lines,\n// arrays as [a, b]. Unknown keys and even unparseable lines are preserved\n// in order so a round-trip never loses what a human or another tool wrote.\n\ntype FmEntry = { key: string; value: string | string[] } | { raw: string };\ninterface FmDoc {\n entries: FmEntry[];\n body: string;\n}\n\nfunction parseArrayish(value: string): string[] {\n return value\n .slice(1, -1)\n .split(',')\n .map((part) => part.trim().replace(/^[\"']|[\"']$/g, ''))\n .filter((part) => part.length > 0);\n}\n\nfunction parseFrontmatter(text: string): FmDoc {\n const lines = text.split(/\\r?\\n/);\n if (lines[0]?.trim() !== '---') return { entries: [], body: text };\n const entries: FmEntry[] = [];\n let at = 1;\n for (; at < lines.length; at += 1) {\n const line = lines[at]!;\n if (line.trim() === '---') {\n return { entries, body: lines.slice(at + 1).join('\\n').replace(/^\\n/, '') };\n }\n const sep = line.indexOf(':');\n if (sep <= 0) {\n if (line.trim().length > 0) entries.push({ raw: line });\n continue;\n }\n const key = line.slice(0, sep).trim();\n const value = line.slice(sep + 1).trim();\n if (!key) {\n entries.push({ raw: line });\n continue;\n }\n entries.push({\n key,\n value: value.startsWith('[') && value.endsWith(']') ? parseArrayish(value) : value,\n });\n }\n return { entries: [], body: text };\n}\n\nfunction serializeFrontmatter(doc: FmDoc): string {\n const lines = doc.entries.map((entry) => {\n if ('raw' in entry) return entry.raw;\n const value = Array.isArray(entry.value) ? `[${entry.value.join(', ')}]` : entry.value;\n return `${entry.key}: ${value}`;\n });\n return `---\\n${lines.join('\\n')}\\n---\\n\\n${doc.body.replace(/^\\n+/, '')}`;\n}\n\nfunction fmGet(doc: FmDoc, key: string): string | string[] | undefined {\n for (const entry of doc.entries) {\n if ('key' in entry && entry.key === key) return entry.value;\n }\n return undefined;\n}\n\nfunction fmGetString(doc: FmDoc, key: string): string {\n const value = fmGet(doc, key);\n if (Array.isArray(value)) return value.join(', ');\n return value ?? '';\n}\n\nfunction fmGetArray(doc: FmDoc, key: string): string[] {\n const value = fmGet(doc, key);\n if (Array.isArray(value)) return value;\n if (typeof value === 'string' && value.length > 0) return [value];\n return [];\n}\n\nfunction fmSet(doc: FmDoc, key: string, value: string | string[]): void {\n for (const entry of doc.entries) {\n if ('key' in entry && entry.key === key) {\n entry.value = value;\n return;\n }\n }\n doc.entries.push({ key, value });\n}\n\nfunction fmDelete(doc: FmDoc, key: string): void {\n doc.entries = doc.entries.filter((entry) => !('key' in entry && entry.key === key));\n}\n\n// ── pipeline rules ──\n\nfunction legalNext(from: string): string[] {\n if (from === 'archived') return [];\n const at = STAGES.indexOf(from as (typeof STAGES)[number]);\n const forward = at >= 0 && at < STAGES.length - 1 ? [STAGES[at + 1]!] : [];\n return [...forward, 'archived'];\n}\n\nfunction assertTransition(id: string, from: string, to: string): void {\n if (to === from) return;\n if (!STATUSES.includes(to)) {\n throw new Error(`Unknown status '${to}'. Statuses: ${STATUSES.join(', ')}.`);\n }\n if (!legalNext(from).includes(to)) {\n const next = legalNext(from);\n throw new Error(\n `Cannot move '${id}' from ${from} to ${to} — posts move one stage at a time. ` +\n (next.length > 0 ? `Legal next: ${next.join(', ')}.` : `'${from}' is final; create a new post instead.`),\n );\n }\n}\n\nfunction requireId(): string {\n const id = (input.id ?? '').trim();\n if (!id) throw new Error(\"Pass 'id' — the post's folder name under posts/ (see action:'list').\");\n if (!ID_RE.test(id)) {\n throw new Error(`Invalid post id '${id}'. Ids are lowercase [a-z0-9-], no slashes or dots.`);\n }\n return id;\n}\n\nfunction today(): string {\n return new Date().toISOString().slice(0, 10);\n}\n\nfunction slugify(text: string): string {\n return text\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 60);\n}\n\n// ── store ──\n\ninterface IndexEntry {\n id: string;\n title: string;\n status: string;\n platforms: string[];\n created: string;\n scheduledFor?: string;\n campaign?: string;\n}\n\nasync function readPostDoc(id: string): Promise<FmDoc> {\n let raw: string;\n try {\n raw = await gezel.fs.read(`${POSTS_DIR}/${id}/post.md`);\n } catch {\n throw new Error(`No post '${id}' — posts/${id}/post.md does not exist. Call action:'list' to see what does.`);\n }\n return parseFrontmatter(raw);\n}\n\nasync function writePostDoc(id: string, doc: FmDoc): Promise<void> {\n await gezel.fs.write(`${POSTS_DIR}/${id}/post.md`, serializeFrontmatter(doc));\n}\n\nfunction toIndexEntry(id: string, doc: FmDoc): IndexEntry {\n const entry: IndexEntry = {\n id,\n title: fmGetString(doc, 'title') || id,\n status: fmGetString(doc, 'status') || 'idea',\n platforms: fmGetArray(doc, 'platforms'),\n created: fmGetString(doc, 'created') || today(),\n };\n const scheduledFor = fmGetString(doc, 'scheduledFor');\n if (scheduledFor) entry.scheduledFor = scheduledFor;\n const campaign = fmGetString(doc, 'campaign');\n if (campaign) entry.campaign = campaign;\n return entry;\n}\n\nasync function regenerateIndex(): Promise<IndexEntry[]> {\n let names: string[] = [];\n try {\n names = (await gezel.fs.list(POSTS_DIR))\n .filter((entry) => entry.isDirectory && entry.name !== '_drafting' && ID_RE.test(entry.name))\n .map((entry) => entry.name);\n } catch {\n names = [];\n }\n const posts: IndexEntry[] = [];\n for (const name of names) {\n try {\n posts.push(toIndexEntry(name, await readPostDoc(name)));\n } catch {\n // A folder without a parseable post.md is not a post; leave it be.\n }\n }\n posts.sort((a, b) => (a.created === b.created ? (a.id < b.id ? 1 : -1) : a.created < b.created ? 1 : -1));\n await gezel.fs.write(INDEX_FILE, `${JSON.stringify({ version: 1, posts }, null, 2)}\\n`);\n return posts;\n}\n\nasync function readIndex(): Promise<IndexEntry[]> {\n try {\n const parsed = JSON.parse(await gezel.fs.read(INDEX_FILE)) as { posts?: IndexEntry[] };\n return Array.isArray(parsed.posts) ? parsed.posts : [];\n } catch {\n return [];\n }\n}\n\nasync function listVariants(id: string): Promise<Record<string, Record<string, unknown>>> {\n let names: string[] = [];\n try {\n names = (await gezel.fs.list(`${POSTS_DIR}/${id}/variants`))\n .filter((entry) => !entry.isDirectory && entry.name.endsWith('.md'))\n .map((entry) => entry.name);\n } catch {\n return {};\n }\n const variants: Record<string, Record<string, unknown>> = {};\n for (const name of names) {\n const platform = name.slice(0, -3);\n const doc = parseFrontmatter(await gezel.fs.read(`${POSTS_DIR}/${id}/variants/${name}`));\n const body = doc.body.trim();\n const variant: Record<string, unknown> = {\n charCount: Number(fmGetString(doc, 'charCount')) || body.length,\n body,\n };\n for (const key of ['publishedAt', 'permalink', 'postId', 'corpusRef']) {\n const value = fmGetString(doc, key);\n if (value) variant[key] = value;\n }\n variants[platform] = variant;\n }\n return variants;\n}\n\nasync function listMedia(id: string): Promise<string[]> {\n try {\n return (await gezel.fs.list(`${POSTS_DIR}/${id}/media`))\n .filter((entry) => !entry.isDirectory)\n .map((entry) => entry.name);\n } catch {\n return [];\n }\n}\n\n// ── actions ──\n\nif (input.action === 'list') {\n const all = await readIndex();\n let posts = all;\n if (input.status) posts = posts.filter((post) => post.status === input.status);\n if (input.platform) posts = posts.filter((post) => post.platforms.includes(input.platform!));\n const counts = STATUSES.map((status) => {\n const n = all.filter((post) => post.status === status).length;\n return n > 0 ? `${status} ${n}` : null;\n })\n .filter((line) => line !== null)\n .join(', ');\n gezel.output({\n posts,\n total: all.length,\n summary: all.length === 0 ? 'No posts yet — stage one in posts/_drafting/ and call create.' : `${all.length} post(s): ${counts}.`,\n });\n} else if (input.action === 'get') {\n const id = requireId();\n const doc = await readPostDoc(id);\n const fields: Record<string, unknown> = {};\n for (const entry of doc.entries) {\n if ('key' in entry) fields[entry.key] = entry.value;\n }\n const post = {\n id,\n ...fields,\n status: fmGetString(doc, 'status') || 'idea',\n platforms: fmGetArray(doc, 'platforms'),\n body: doc.body.trim(),\n variants: await listVariants(id),\n media: await listMedia(id),\n };\n gezel.output({\n post,\n id,\n status: post.status,\n summary: `'${fmGetString(doc, 'title') || id}' is ${post.status}; ${Object.keys(post.variants).length} variant(s), ${post.media.length} media file(s).`,\n });\n} else if (input.action === 'create') {\n let staged: FmDoc;\n if (input.title && input.body) {\n // The post itself in one call: a project's first draft is made with its\n // own tools, and a lead without file tools could never stage a draft.\n staged = { entries: [], body: String(input.body).trim() };\n fmSet(staged, 'title', String(input.title).replace(/\\s+/g, ' ').trim());\n const platforms = String(input.platforms ?? '')\n .split(',')\n .map((platform) => platform.trim().toLowerCase())\n .filter((platform) => PLATFORM_RE.test(platform));\n if (platforms.length > 0) fmSet(staged, 'platforms', platforms);\n await gezel.fs.write(`${DRAFTING}/post.md`, serializeFrontmatter(staged));\n } else {\n try {\n staged = parseFrontmatter(await gezel.fs.read(`${DRAFTING}/post.md`));\n } catch {\n throw new Error('Nothing is staged — give a title and body, or write posts/_drafting/post.md (frontmatter + body) first, then call create again.');\n }\n }\n const slug = slugify(fmGetString(staged, 'slug') || fmGetString(staged, 'title'));\n if (!slug) throw new Error(\"The staged post.md needs a 'slug' or a 'title' in its frontmatter to name the post folder.\");\n const createdRaw = fmGetString(staged, 'created');\n const created = /^\\d{4}-\\d{2}-\\d{2}$/.test(createdRaw) ? createdRaw : today();\n const id = `${created}-${slug}`;\n if (!ID_RE.test(id)) throw new Error(`Derived post id '${id}' is invalid — keep slug to lowercase letters, digits, and dashes.`);\n const siblings = await gezel.fs.list(POSTS_DIR).catch(() => []);\n if (siblings.some((entry) => entry.name === id)) {\n throw new Error(`posts/${id}/ already exists. Change the staged slug (or created date) and call create again.`);\n }\n const status = input.status ?? 'approved';\n if (!STATUSES.includes(status)) {\n throw new Error(`'${status}' is not a status. Statuses: ${STATUSES.join(', ')}.`);\n }\n fmSet(staged, 'status', status);\n fmSet(staged, 'slug', slug);\n fmSet(staged, 'created', created);\n await gezel.fs.write(`${DRAFTING}/post.md`, serializeFrontmatter(staged));\n await gezel.fs.rename(DRAFTING, `${POSTS_DIR}/${id}`);\n await regenerateIndex();\n gezel.output({\n id,\n status,\n summary: `Committed posts/_drafting/ as posts/${id}/ with status ${status}.`,\n });\n} else if (input.action === 'update') {\n const id = requireId();\n const doc = await readPostDoc(id);\n const patches = (input.fields && typeof input.fields === 'object' && !Array.isArray(input.fields) ? input.fields : {}) as Record<string, unknown>;\n let nextStatus = input.status;\n if (typeof patches.status === 'string' && !nextStatus) nextStatus = patches.status;\n delete patches.status;\n if (!nextStatus && Object.keys(patches).length === 0) {\n throw new Error(\"Nothing to change — pass 'status' and/or a 'fields' object of frontmatter patches.\");\n }\n const from = fmGetString(doc, 'status') || 'idea';\n if (nextStatus) assertTransition(id, from, nextStatus);\n for (const [key, value] of Object.entries(patches)) {\n if (value === null || value === undefined) fmDelete(doc, key);\n else if (Array.isArray(value)) fmSet(doc, key, value.map((item) => String(item)));\n else fmSet(doc, key, String(value));\n }\n if (nextStatus) fmSet(doc, 'status', nextStatus);\n await writePostDoc(id, doc);\n await regenerateIndex();\n const status = nextStatus ?? from;\n gezel.output({\n id,\n status,\n summary: nextStatus && nextStatus !== from ? `Moved '${id}' from ${from} to ${status}.` : `Updated '${id}' (${status}).`,\n });\n} else if (input.action === 'record_publication') {\n const id = requireId();\n const platform = (input.platform ?? '').trim();\n if (!PLATFORM_RE.test(platform)) {\n throw new Error(\"Pass 'platform' — the variant that went live, e.g. 'bluesky', 'x', or 'instagram'.\");\n }\n const doc = await readPostDoc(id);\n const variantPath = `${POSTS_DIR}/${id}/variants/${platform}.md`;\n const variant = parseFrontmatter(await gezel.fs.read(variantPath).catch(() => '---\\n---\\n'));\n fmSet(variant, 'publishedAt', input.publishedAt ?? new Date().toISOString());\n if (input.permalink) fmSet(variant, 'permalink', input.permalink);\n if (input.postId) fmSet(variant, 'postId', input.postId);\n if (input.corpusRef) fmSet(variant, 'corpusRef', input.corpusRef);\n await gezel.fs.write(variantPath, serializeFrontmatter(variant));\n const targets = fmGetArray(doc, 'platforms');\n const stamped = await listVariants(id);\n const allLive = targets.length > 0 && targets.every((target) => typeof stamped[target]?.publishedAt === 'string');\n let status = fmGetString(doc, 'status') || 'idea';\n // Recording reality bypasses the stage chain: once every target variant\n // is live (or the caller says so), the post IS published.\n if (allLive || input.markPublished === true) {\n status = 'published';\n fmSet(doc, 'status', status);\n await writePostDoc(id, doc);\n }\n await regenerateIndex();\n const waiting = targets.filter((target) => typeof stamped[target]?.publishedAt !== 'string');\n gezel.output({\n id,\n status,\n summary:\n status === 'published'\n ? `Recorded ${platform} publication for '${id}' — the post is published.`\n : `Recorded ${platform} publication for '${id}'; still waiting on: ${waiting.join(', ') || '(none)'}.`,\n });\n} else {\n throw new Error(`Unknown action '${input.action}'. Use list, get, create, update, or record_publication.`);\n}\n"},"tools":[{"name":"list_posts","description":"See the whole post pipeline: every post with its status, platforms, and dates. Optionally filter by status or platform.","script":"posts-store","inputs":{"type":"object","properties":{"status":{"type":"string","enum":["idea","draft","in-review","approved","scheduled","published","archived"],"description":"Only posts currently in this status."},"platform":{"type":"string","description":"Only posts targeting this platform, e.g. 'bluesky'."}}},"bind":{"action":"list"}},{"name":"get_post","description":"Read one post in full: frontmatter, body, each platform variant with its character count (and permalink once live), and media files.","script":"posts-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Post id — its folder name under posts/, e.g. '2026-08-12-launch-teaser'."}},"required":["id"]},"bind":{"action":"get"}},{"name":"create_post","description":"Add a post: give its title and body (and platforms) to write it in one call, or commit a draft staged in posts/_drafting/ (post.md with frontmatter + body, variants/, media/). The post folder is named from the created date and slug.","script":"posts-store","inputs":{"type":"object","properties":{"title":{"type":"string","description":"The post's title."},"body":{"type":"string","description":"The post's text, in the voice guide's voice."},"platforms":{"type":"string","description":"Comma-separated platforms, e.g. 'linkedin, bluesky'."},"status":{"type":"string","enum":["idea","draft","in-review","approved","scheduled","published","archived"],"description":"Initial status for the new post. Defaults to approved."}}},"bind":{"action":"create"}},{"name":"update_post","description":"Patch a post's frontmatter (fields object; null clears a key) and/or move it one pipeline stage. Stages run idea, draft, in-review, approved, scheduled, published — archived from anywhere.","script":"posts-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Post id."},"fields":{"type":"object","description":"Frontmatter patches, e.g. {\"scheduledFor\": \"2026-08-15T09:00:00Z\", \"campaign\": \"autumn\"}."},"status":{"type":"string","enum":["idea","draft","in-review","approved","scheduled","published","archived"],"description":"Target status (one stage at a time)."}},"required":["id"]},"bind":{"action":"update"}},{"name":"record_publication","description":"The moment a variant goes live, stamp it with its permalink and platform post id. The post flips to published once every target platform is stamped (or markPublished is passed).","script":"posts-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Post id."},"platform":{"type":"string","description":"The platform that went live, e.g. 'bluesky'."},"permalink":{"type":"string","description":"Public URL of the live post."},"postId":{"type":"string","description":"The platform's own id for the live post."},"corpusRef":{"type":"string","description":"Connector corpus record reference, when one exists."},"publishedAt":{"type":"string","description":"ISO timestamp it went live (defaults to now)."},"markPublished":{"type":"boolean","description":"Force the post to published even with unstamped platforms."}},"required":["id","platform"]},"bind":{"action":"record_publication"}},{"name":"page_set_status","description":"Page-only: move a post between pipeline columns on the board.","script":"posts-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Post id."},"status":{"type":"string","enum":["idea","draft","in-review","approved","scheduled","published","archived"],"description":"The column the post was moved to."}},"required":["id","status"]},"bind":{"action":"update"},"reaction":{"gezel":"omroeper","prompt":"[Feed board]: The user moved post {{output.id}} to '{{output.status}}' on the board. Reply with ONE short line acknowledging the move. If it landed in 'draft', offer to run the draft-social-post craftbook on it. Do not restate the pipeline.","hideSeed":true}},{"name":"page_get_post","description":"Page-only: the detail drawer's read of one post with variants and media.","script":"posts-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Post id."}},"required":["id"]},"bind":{"action":"get"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"posts","subtree":true},{"source":"workspace","path":"voice-guide.md"},{"source":"artifacts","path":"data","subtree":true}],"tools":["page_set_status","page_get_post"]},"schedules":[{"runMode":"night-shift","craftbook":"social-digest","consent":"ask","overlap":"skip"},{"runMode":"scheduled","cron":"0 15 * * 1","craftbook":"reception-report","consent":"ask","overlap":"skip"}],"workspaceSeed":["voice-guide.md","posts/index.json"],"artifactsSeed":[],"notes":"posts/index.json is seeded at its subpath (applyProjectType preserves seed subpaths and creates parents) and is ALSO regenerated by posts-store on every mutation, so the board tolerates a missing or stale index. Posts live one folder per post under posts/ (post.md + variants/ + media/), staged in posts/_drafting/ until create_post commits them. page_set_status and page_get_post are the page-only twins of update_post/get_post — pages.tools names are removed from the model surface, so the model keeps its own read tools.","availableVersions":["1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"software-project","name":"Software Project","description":"A working codebase with a real crew: a lead developer who builds and fixes, a reviewer who checks the work, and a librarian who reads the code while you sleep and files what it finds. Weekly dependency and documentation sweeps keep the quiet rot out.","tags":["code","software","development","engineering","repository"],"category":"code","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26236","version":"1.0.1","releasedAt":"2026-10-25T16:48:51Z","meesterManaged":true,"gezels":[{"templateId":"developer","voorman":true},{"templateId":"reviewer","voorman":false},{"templateId":"boekwachter","voorman":false}],"toolsets":[],"craftbooks":["bug-fix-tdd","refactor-module","test-suite-backfill","code-review","root-cause-investigation","release-readiness-review"],"tools":[],"schedules":[{"runMode":"scheduled","cron":"0 9 * * 1","craftbook":"dependency-audit","consent":"ask","overlap":"skip"},{"runMode":"scheduled","cron":"0 9 * * 3","craftbook":"documentation-drift-review","consent":"ask","overlap":"skip"}],"workspaceSeed":[],"artifactsSeed":[],"availableVersions":["1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"trip-planner","name":"Trip Planner","description":"Plan a trip you'll actually be present for. A trip planner builds the day-by-day itinerary with slack in it, keeps the packing list checkable on a live board, and helps the journal happen.","tags":["travel","trip","itinerary","packing","journal"],"category":"events","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.5","releasedAt":"2026-11-01T06:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"destination":{"type":"string","title":"Where to?","description":"e.g. 'Kyoto', 'the Scottish Highlands'.","default":"somewhere wonderful"},"start":{"type":"string","title":"Departure date","description":"e.g. 2026-09-12. A rough date is fine.","default":"2026-12-01"},"travellers":{"type":"string","title":"Who's going?","description":"e.g. '4', or 'two adults and a toddler'. Leave empty if you're not sure yet.","default":""}},"required":["destination","start"]},"nameTemplate":"Trip: {{destination}}","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"reisleider","voorman":true}],"toolsets":[],"craftbooks":["pre-departure-countdown"],"scripts":{"trip-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { logStore, rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'trip-store',\n description:\n \"Read and update the trip: itinerary + packing (trip.json) and the journal (journal.json). Call action:'status' for the shape of the trip; 'set_trip' with start / travellers / destination as the traveller tells you; 'plan_day' with date + plan; 'pack_add' / 'pack_check' for the packing list; 'journal_entry' during the trip.\",\n inputs: {\n action: {\n type: 'string',\n description:\n \"One of 'status', 'set_trip', 'plan_day', 'pack_add', 'pack_check', 'journal_entry', or 'itinerary'.\",\n required: true,\n },\n date: {\n type: 'string',\n description: \"The day being planned: 2026-09-14 once the dates are known, otherwise 'Day 1', 'Day 2', ...\",\n },\n plan: {\n type: 'string',\n description:\n \"The day in plain sentences, one per line: what the day is for, then a couple of alternatives, then the free time. No 'Anchor:' or 'Options:' labels.\",\n },\n start: {\n type: 'string',\n description: \"The departure date they gave: 2026-09-12 when they named a day, otherwise their words ('next spring'). Never choose one for them.\",\n },\n travellers: { type: 'string', description: \"Who is going: a number ('4') or a phrase ('two adults and a toddler').\" },\n destination: { type: 'string', description: 'Where the trip goes.' },\n item: { type: 'string', description: 'Packing item name.' },\n id: { type: 'string', description: \"Packing item id, e.g. 'pack-3'.\" },\n note: { type: 'string', description: 'Journal entry text.' },\n },\n outputs: {\n daysPlanned: { type: 'number', description: 'Days with a plan.' },\n unpacked: { type: 'number', description: 'Packing items still unpacked.' },\n summary: { type: 'string', description: 'The trip picture (or the itinerary).' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── trip-rules-start ──\n// Pure derivations over the trip doc: countdown, day keys and itinerary rendering.\n\nfunction plural(n, one, many) {\n return n + ' ' + (n === 1 ? one : many);\n}\n\nfunction daysUntil(dateStr, nowMs) {\n if (!/^\\d{4}-\\d{2}-\\d{2}/.test(String(dateStr || ''))) return null;\n var when = Date.parse(dateStr);\n if (!isFinite(when)) return null;\n return Math.ceil((when - nowMs) / (24 * 60 * 60 * 1000));\n}\n\n// \"2026-09-14T10:00\" -> \"2026-09-14\"; \"day 3\" / \"Day3\" / \"3\" -> \"Day 3\".\nfunction dayKey(raw) {\n var text = String(raw || '').trim();\n var iso = text.match(/^\\d{4}-\\d{2}-\\d{2}/);\n if (iso) return iso[0];\n var numbered = text.match(/^(?:day\\s*)?(\\d{1,3})$/i);\n if (numbered) return 'Day ' + Number(numbered[1]);\n return text;\n}\n\n// Numbered days sort by number (\"Day 10\" after \"Day 9\"); dates sort as text.\nfunction sortedDays(days) {\n return Object.keys(days).sort(function (a, b) {\n var na = a.match(/^Day (\\d+)$/);\n var nb = b.match(/^Day (\\d+)$/);\n if (na && nb) return Number(na[1]) - Number(nb[1]);\n return a < b ? -1 : a > b ? 1 : 0;\n });\n}\n\n// \"4 people\" / \"4 travellers\" -> \"4\", so the board can say \"4 travellers\";\n// a phrase (\"two adults and a toddler\") is kept as written.\nfunction partyCount(raw) {\n var text = String(raw || '').trim();\n var counted = text.match(/^(\\d{1,3})\\s*(?:people|persons|travell?ers|adults|guests|of us)?$/i);\n return counted ? String(Number(counted[1])) : text;\n}\n\nfunction travellersLine(travellers) {\n var text = String(travellers || '').trim();\n if (!text) return '';\n if (/^\\d+$/.test(text)) return plural(Number(text), 'traveller', 'travellers');\n return text;\n}\n\nfunction renderItinerary(days) {\n var keys = sortedDays(days);\n if (keys.length === 0) return 'No days planned yet.';\n return keys\n .map(function (d) {\n return d + ': ' + days[d];\n })\n .join('\\n');\n}\n\nfunction tripLine(trip, unpackedCount, nowMs) {\n var start = daysUntil(trip.startDate, nowMs);\n var planned = Object.keys(trip.days || {}).length;\n var who = travellersLine(trip.travellers);\n var lead =\n start === null\n ? trip.startDate && trip.startDate !== 'soon'\n ? 'Leaving ' + trip.startDate + '. '\n : 'No departure date yet. '\n : start > 0\n ? plural(start, 'day', 'days') + ' until departure. '\n : start === 0\n ? 'Departure day! '\n : 'On the road (or home again). ';\n return (\n (who ? who + '. ' : '') +\n lead +\n plural(planned, 'day', 'days') + ' planned. Packing: ' +\n (unpackedCount === 0 ? 'all packed.' : plural(unpackedCount, 'item', 'items') + ' still unpacked.')\n );\n}\n// ── trip-rules-end ──\n\nconst TRIP_FILE = 'trip.json';\nconst packing = rosterStore(gezel.fs, 'packing.json', {\n stages: ['unpacked', 'packed'],\n idPrefix: 'pack',\n});\nconst journal = logStore(gezel.fs, 'journal.json');\n\ninterface Trip {\n version: number;\n destination: string;\n startDate: string;\n travellers: string;\n days: Record<string, string>;\n updatedAt: string;\n}\n\nasync function loadTrip(): Promise<Trip> {\n try {\n const parsed = JSON.parse(await gezel.fs.read(TRIP_FILE)) as Partial<Trip>;\n return {\n version: 1,\n destination: typeof parsed.destination === 'string' ? parsed.destination : '',\n startDate: typeof parsed.startDate === 'string' ? parsed.startDate : '',\n travellers: typeof parsed.travellers === 'string' ? parsed.travellers : '',\n days: parsed.days && typeof parsed.days === 'object' ? (parsed.days as Record<string, string>) : {},\n updatedAt: new Date().toISOString(),\n };\n } catch {\n return {\n version: 1,\n destination: '',\n startDate: '',\n travellers: '',\n days: {},\n updatedAt: new Date().toISOString(),\n };\n }\n}\n\nasync function saveTrip(trip: Trip): Promise<void> {\n trip.updatedAt = new Date().toISOString();\n await gezel.fs.write(TRIP_FILE, `${JSON.stringify(trip, null, 2)}\\n`);\n}\n\nconst trip = await loadTrip();\n\nif (input.action === 'set_trip') {\n if (!input.start && !input.travellers && !input.destination) {\n throw new Error(\"set_trip needs at least one of 'start', 'travellers', or 'destination'.\");\n }\n if (input.start) trip.startDate = input.start.trim();\n if (input.travellers) trip.travellers = partyCount(input.travellers);\n if (input.destination) trip.destination = input.destination.trim();\n await saveTrip(trip);\n} else if (input.action === 'plan_day') {\n if (!input.date || !input.plan) throw new Error(\"plan_day needs 'date' (YYYY-MM-DD, or 'Day 1') and 'plan'.\");\n trip.days[dayKey(input.date)] = input.plan;\n await saveTrip(trip);\n} else if (input.action === 'pack_add') {\n if (!input.item) throw new Error(\"pack_add needs 'item'.\");\n await packing.add({ status: 'unpacked', fields: { name: input.item } });\n} else if (input.action === 'pack_check') {\n let id = input.id;\n if (!id && input.item) {\n const wanted = input.item.toLowerCase();\n const matches = (await packing.list()).filter(\n (r) => String(r.fields.name ?? '').toLowerCase() === wanted,\n );\n if (matches.length === 1) id = matches[0]!.id;\n }\n if (!id) throw new Error(\"Pass 'id' (e.g. 'pack-3') or an exact packing 'item'.\");\n await packing.transition(id, 'packed');\n} else if (input.action === 'journal_entry') {\n if (!input.note) throw new Error(\"journal_entry needs 'note'.\");\n await journal.append({ kind: 'entry', note: input.note });\n} else if (input.action !== 'status' && input.action !== 'itinerary') {\n throw new Error(\n `Unknown action '${input.action}'. Use status, set_trip, plan_day, pack_add, pack_check, journal_entry, or itinerary.`,\n );\n}\n\nconst packItems = await packing.list();\nconst unpacked = packItems.filter((r) => r.status === 'unpacked').length;\n\ngezel.output({\n daysPlanned: Object.keys(trip.days).length,\n unpacked,\n summary:\n input.action === 'itinerary' ? renderItinerary(trip.days) : tripLine(trip, unpacked, Date.now()),\n});\n"},"tools":[{"name":"set_trip","description":"Change the trip's details when the traveller gives new ones: the departure date, who is going, or the destination. Record their words; never choose a date for them.","script":"trip-store","inputs":{"type":"object","properties":{"start":{"type":"string","description":"The departure date they gave: YYYY-MM-DD when they named a day, otherwise their words ('next spring')."},"travellers":{"type":"string","description":"How many are going ('4'), or who ('two adults and a toddler')."},"destination":{"type":"string"}}},"bind":{"action":"set_trip"}},{"name":"plan_day","description":"Set one day's plan in plain sentences, one per line: what the day is for, then a couple of alternatives, then the free time. Use the date (YYYY-MM-DD) once it is known, otherwise 'Day 1', 'Day 2', … Never write 'Anchor:' or 'Options:' labels.","script":"trip-store","inputs":{"type":"object","properties":{"date":{"type":"string","description":"YYYY-MM-DD, or 'Day 1' when the dates are not set yet."},"plan":{"type":"string","description":"The day in plain sentences, one per line."}},"required":["date","plan"]},"bind":{"action":"plan_day"}},{"name":"pack_add","description":"Add an item to the packing list.","script":"trip-store","inputs":{"type":"object","properties":{"item":{"type":"string"}},"required":["item"]},"bind":{"action":"pack_add"}},{"name":"pack_check","description":"Mark an item packed.","script":"trip-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"item":{"type":"string"}}},"bind":{"action":"pack_check"}},{"name":"journal_entry","description":"Capture a trip moment — a line a day.","script":"trip-store","inputs":{"type":"object","properties":{"note":{"type":"string"}},"required":["note"]},"bind":{"action":"journal_entry"}},{"name":"trip_status","description":"Who is going, the countdown, days planned, and the packing state.","script":"trip-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"}},{"name":"itinerary","description":"Read the full day-by-day itinerary.","script":"trip-store","inputs":{"type":"object","properties":{}},"bind":{"action":"itinerary"}},{"name":"mark_packed","description":"The dashboard's packing checkbox.","script":"trip-store","inputs":{"type":"object","properties":{"id":{"type":"string"}},"required":["id"]},"bind":{"action":"pack_check"}},{"name":"page_plan_day","description":"Set one day's plan in plain sentences, one per line: what the day is for, then a couple of alternatives, then the free time. Use the date (YYYY-MM-DD) once it is known, otherwise 'Day 1', 'Day 2', … Never write 'Anchor:' or 'Options:' labels.","script":"trip-store","inputs":{"type":"object","properties":{"date":{"type":"string","description":"YYYY-MM-DD, or 'Day 1' when the dates are not set yet."},"plan":{"type":"string","description":"The day in plain sentences, one per line."}},"required":["date","plan"]},"bind":{"action":"plan_day"}},{"name":"page_pack_add","description":"Add an item to the packing list.","script":"trip-store","inputs":{"type":"object","properties":{"item":{"type":"string"}},"required":["item"]},"bind":{"action":"pack_add"}},{"name":"page_journal_entry","description":"Capture a trip moment — a line a day.","script":"trip-store","inputs":{"type":"object","properties":{"note":{"type":"string"}},"required":["note"]},"bind":{"action":"journal_entry"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"trip.json"},{"source":"workspace","path":"packing.json"},{"source":"workspace","path":"journal.json"}],"tools":["mark_packed","page_plan_day","page_pack_add","page_journal_entry"]},"schedules":[],"workspaceSeed":["trip.json","packing.json","journal.json"],"artifactsSeed":[],"availableVersions":["1.0.5","1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"word-clues","name":"Word Clues","description":"Find your six words on a board of sixteen from one-word clues, and steer clear of the trap. Two gezels take turns giving clues: a lively clue giver and a careful puzzler.","tags":["game","words","clues","play"],"category":"game","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.0.3","releasedAt":"2026-11-01T06:00:00.000Z","meesterManaged":false,"tabVisibility":{"overview":false,"tasks":false,"approvals":false,"workspace":false,"artifacts":false,"map":false},"leanProfile":true,"nameTemplate":"Word Clues","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"woordsmid","voorman":true},{"templateId":"puzzelaar","voorman":false}],"toolsets":[],"craftbooks":[],"scripts":{"clue-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\n\nexport const meta = defineScript({\n name: 'clue-store',\n description:\n \"The word-clue game's engine (game.json). action:'board' reads the game; 'give_clue' records a clue; 'guess' reveals a word the player picked; 'pass' ends the player's guessing; 'new_game' deals a fresh board.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'board', 'give_clue', 'guess', 'pass', 'new_game'.\",\n required: true,\n },\n clue: { type: 'string', description: 'For give_clue: one word, not on the board.' },\n count: { type: 'number', description: 'For give_clue: how many of the player’s words it points at.' },\n say: { type: 'string', description: 'For give_clue: one short line of table talk.' },\n word: { type: 'string', description: 'For guess: the board word the player picked.' },\n },\n outputs: {\n status: {\n type: 'string',\n description: \"'clue_needed', 'guessing', 'won', 'lost' or 'new'.\",\n },\n giver: { type: 'string', description: \"Whose clue is next: 'a' (Clue Giver) or 'b' (Puzzler).\" },\n result: { type: 'string', description: \"For guess: 'target', 'neutral', 'trap', or ''.\" },\n display: { type: 'string', description: 'For give_clue: the clue as shown to the player.' },\n modelState: { type: 'json', description: 'What the clue-giver sees: its words, the trap, the rest.' },\n summary: { type: 'string', description: 'A short summary of the game.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── clue-rules-start ──\n// The board is sixteen words: six are the player's, nine are neutral, one\n// is the trap. A clue-giver who knows the board gives one word and a count;\n// the player then picks up to count + 1 words. A neutral word ends their\n// turn, the trap ends the game, and finding all six wins it. Kept\n// self-contained between these sentinels so unit tests execute the shipped\n// bytes.\nvar BOARD_SIZE = 16;\nvar TARGETS = 6;\n\nfunction shuffle(list, random) {\n var out = list.slice();\n for (var i = out.length - 1; i > 0; i -= 1) {\n var j = Math.floor(random() * (i + 1));\n var t = out[i];\n out[i] = out[j];\n out[j] = t;\n }\n return out;\n}\n\nfunction deal(bank, random) {\n var picked = shuffle(bank, random).slice(0, BOARD_SIZE);\n var cells = picked.map(function (word, i) {\n return { word: word, kind: i < TARGETS ? 'target' : i === TARGETS ? 'trap' : 'neutral', revealed: false };\n });\n return shuffle(cells, random);\n}\n\nfunction remaining(words, kind) {\n return words.filter(function (w) { return w.kind === kind && !w.revealed; }).map(function (w) { return w.word; });\n}\n\n// Why a clue is not allowed on this board, or '' when it is.\nfunction clueProblem(words, clue, count) {\n var c = String(clue || '').trim().toLowerCase();\n if (!/^[a-zÀ-ɏ'-]{2,24}$/.test(c)) return 'A clue is one word of letters, like \"ocean\".';\n for (var i = 0; i < words.length; i += 1) {\n var w = words[i].word.toLowerCase();\n if (w === c) return '\"' + c + '\" is on the board.';\n // Forms of a board word (plurals, compounds that start with it) give the\n // answer away; a word that merely contains one (\"planet\", \"net\") does not.\n var shorter = c.length < w.length ? c : w;\n var longer = c.length < w.length ? w : c;\n if (shorter.length >= 3 && longer.indexOf(shorter) === 0)\n return '\"' + c + '\" is a form of the board word \"' + w + '\".';\n }\n var left = remaining(words, 'target').length;\n if (!(count >= 1 && count <= left && Math.floor(count) === count))\n return 'The count must be a whole number from 1 to ' + left + '.';\n return '';\n}\n\nfunction applyGuess(game, word) {\n var pick = String(word || '').trim().toLowerCase();\n var cell = game.words.find(function (w) { return w.word.toLowerCase() === pick; });\n if (!cell) return { error: '\"' + word + '\" is not on the board.' };\n if (cell.revealed) return { error: '\"' + cell.word + '\" is already revealed.' };\n cell.revealed = true;\n var result = cell.kind;\n if (result === 'trap') {\n game.status = 'lost';\n } else if (remaining(game.words, 'target').length === 0) {\n game.status = 'won';\n } else if (result === 'neutral') {\n endGuessing(game);\n } else {\n game.clue.guessesLeft -= 1;\n if (game.clue.guessesLeft <= 0) endGuessing(game);\n }\n return { result: result };\n}\n\nfunction endGuessing(game) {\n game.status = 'clue_needed';\n game.giver = game.giver === 'a' ? 'b' : 'a';\n}\n// ── clue-rules-end ──\n\ninterface Cell {\n word: string;\n kind: 'target' | 'neutral' | 'trap';\n revealed: boolean;\n}\n\ninterface Game {\n version: number;\n status: 'new' | 'clue_needed' | 'guessing' | 'won' | 'lost';\n giver: 'a' | 'b';\n words: Cell[];\n clue: { word: string; count: number; guessesLeft: number; giver: 'a' | 'b' } | null;\n round: number;\n history: Array<{ round: number; clue: string; count: number; found: string[] }>;\n stats: { played: number; won: number; lost: number };\n}\n\nconst GAME_FILE = 'game.json';\n\nasync function load(): Promise<Game> {\n let parsed: Partial<Game> = {};\n try {\n parsed = JSON.parse(await gezel.fs.read(GAME_FILE)) as Partial<Game>;\n } catch {\n // A missing game is a new one.\n }\n return {\n version: 1,\n status: parsed.status ?? 'new',\n giver: parsed.giver === 'b' ? 'b' : 'a',\n words: Array.isArray(parsed.words) ? parsed.words : [],\n clue: parsed.clue ?? null,\n round: parsed.round ?? 0,\n history: Array.isArray(parsed.history) ? parsed.history : [],\n stats: parsed.stats ?? { played: 0, won: 0, lost: 0 },\n };\n}\n\nasync function save(game: Game): Promise<void> {\n await gezel.fs.write(GAME_FILE, `${JSON.stringify(game, null, 2)}\\n`);\n}\n\n// A table nobody has dealt yet gets its first board from the first look at\n// it, so a clue-giver asked to start a game can (new_game is the page's).\nasync function dealInto(game: Game): Promise<void> {\n let bank: string[] = [];\n try {\n bank = (JSON.parse(await gezel.fs.read('words.json')) as { words?: string[] }).words ?? [];\n } catch {\n bank = [];\n }\n if (bank.length < BOARD_SIZE) throw new Error('words.json needs at least 16 words.');\n game.words = deal(bank, Math.random);\n game.status = 'clue_needed';\n game.giver = game.stats.played % 2 === 0 ? 'a' : 'b';\n game.clue = null;\n game.round = 0;\n game.history = [];\n}\n\nconst game = await load();\nlet result = '';\nlet display = '';\nlet changed = false;\n\nswitch (input.action) {\n case 'new_game': {\n await dealInto(game);\n changed = true;\n break;\n }\n case 'give_clue': {\n if (game.status !== 'clue_needed')\n throw new Error(\n game.status === 'guessing'\n ? 'The player is still guessing; no clue is needed yet.'\n : game.status === 'new'\n ? 'No board is dealt yet. Call board first; it deals one.'\n : 'The game is over. Offer a new game instead of a clue.',\n );\n const count = Number(input.count);\n const problem = clueProblem(game.words, input.clue, count);\n if (problem) {\n // Point a struggling clue-giver at one word to hint at: a small model\n // given the whole board tends to offer a board word back.\n const left = remaining(game.words, 'target');\n const hint = left[Math.floor(Math.random() * left.length)];\n throw new Error(\n `${problem} Your clue must be a new word that is not on the board. Think of a word linked to \"${hint}\", and give it with count 1.`,\n );\n }\n const word = String(input.clue).trim().toUpperCase();\n game.clue = { word, count, guessesLeft: count + 1, giver: game.giver };\n game.status = 'guessing';\n game.round += 1;\n game.history = [...game.history, { round: game.round, clue: word, count, found: [] }];\n const say = String(input.say ?? '').replace(/\\s+/g, ' ').trim().slice(0, 160);\n display = `Clue: ${word}, ${count}.${say ? ` ${say}` : ''}`;\n changed = true;\n break;\n }\n case 'guess': {\n if (game.status !== 'guessing') throw new Error('Wait for a clue before guessing.');\n const outcome = applyGuess(game, input.word);\n if (outcome.error) throw new Error(outcome.error);\n result = outcome.result;\n if (result === 'target') game.history[game.history.length - 1]?.found.push(String(input.word));\n if (game.status === 'won' || game.status === 'lost') {\n game.stats.played += 1;\n if (game.status === 'won') game.stats.won += 1;\n else game.stats.lost += 1;\n }\n changed = true;\n break;\n }\n case 'pass': {\n if (game.status !== 'guessing') throw new Error('There is no guessing turn to end.');\n endGuessing(game);\n changed = true;\n break;\n }\n case 'board': {\n if (game.status === 'new' && game.words.length === 0) {\n await dealInto(game);\n changed = true;\n }\n break;\n }\n default:\n throw new Error(`Unknown action '${input.action}'.`);\n}\n\nif (changed) await save(game);\n\nconst over = game.status === 'won' || game.status === 'lost';\ngezel.output({\n status: game.status,\n giver: game.giver,\n result,\n display,\n modelState: {\n status: game.status,\n yourWords: remaining(game.words, 'target'),\n trap: game.words.find((w) => w.kind === 'trap')?.word ?? '',\n otherWords: remaining(game.words, 'neutral'),\n rule: 'Your clue must be a word that is NOT in yourWords, otherWords or trap.',\n found: game.words.filter((w) => w.kind === 'target' && w.revealed).map((w) => w.word),\n round: game.round,\n ...(game.clue && game.status === 'guessing' ? { currentClue: `${game.clue.word} ${game.clue.count}` } : {}),\n },\n summary: over\n ? `The player ${game.status === 'won' ? 'found all six words' : 'hit the trap'} in ${game.round} round(s). Games: ${game.stats.won} won, ${game.stats.lost} lost.`\n : `Round ${game.round}: ${remaining(game.words, 'target').length} of 6 words still to find.`,\n});\n"},"tools":[{"name":"board","description":"Read the game: your words still to find, the trap, the other words, and whether a clue is needed. Deals the first board when none is on the table.","script":"clue-store","inputs":{"type":"object","properties":{}},"bind":{"action":"board"},"state":true,"answer":{"tool":"give_clue","when":{"op":"equals","field":"status","value":"clue_needed"}}},{"name":"give_clue","description":"Give the player's next clue: one word that is not on the board, the number of their words it points at, and one short line of table talk.","script":"clue-store","inputs":{"type":"object","properties":{"clue":{"type":"string","description":"One word, not on the board."},"count":{"type":"number","description":"How many of the player's words it points at."},"say":{"type":"string","description":"One short line of table talk (max 160 characters)."}},"required":["clue","count"]},"bind":{"action":"give_clue"},"turn":{"say":"say","fallback":"Your clue is on the board.","show":"display"}},{"name":"new_game","description":"Deal a fresh board.","script":"clue-store","inputs":{"type":"object","properties":{}},"bind":{"action":"new_game"}},{"name":"guess","description":"The player picks a word on the board.","script":"clue-store","inputs":{"type":"object","properties":{"word":{"type":"string"}},"required":["word"]},"bind":{"action":"guess"}},{"name":"pass","description":"The player stops guessing this turn.","script":"clue-store","inputs":{"type":"object","properties":{}},"bind":{"action":"pass"}},{"name":"ask_clue_a","description":"The board asks for the next clue.","script":"clue-store","inputs":{"type":"object","properties":{}},"bind":{"action":"board"},"reaction":{"gezel":"woordsmid","prompt":"It is your turn in Word Clues. The game engine returned this state:\n```json\n{{output.modelState}}\n```\nIf `status` is `clue_needed`, call give_clue once: `clue` is one NEW word, not on the board, that links some of `yourWords`, `count` is how many it points at, and `say` is one short line of table talk. Never pick a clue that also fits `trap`, and avoid ones that fit `otherWords`. If the game is over, give no clue: say one warm line about how it went and offer another game.","hideSeed":true,"standalone":true,"turn":{"tool":"give_clue","when":{"op":"equals","field":"status","value":"clue_needed"}}}},{"name":"ask_clue_b","description":"The board asks for the next clue.","script":"clue-store","inputs":{"type":"object","properties":{}},"bind":{"action":"board"},"reaction":{"gezel":"puzzelaar","prompt":"It is your turn in Word Clues. The game engine returned this state:\n```json\n{{output.modelState}}\n```\nIf `status` is `clue_needed`, call give_clue once: `clue` is one NEW word, not on the board, that links some of `yourWords`, `count` is how many it points at, and `say` is one short line of table talk. Never pick a clue that also fits `trap`, and avoid ones that fit `otherWords`. If the game is over, give no clue: say one warm line about how it went and offer another game.","hideSeed":true,"standalone":true,"turn":{"tool":"give_clue","when":{"op":"equals","field":"status","value":"clue_needed"}}}}],"pages":{"entry":"board/index.html","api":1,"reads":[{"source":"workspace","path":"game.json"}],"tools":["new_game","guess","pass","ask_clue_a","ask_clue_b"]},"schedules":[],"workspaceSeed":["game.json","words.json"],"artifactsSeed":[],"availableVersions":["1.0.3","1.0.2","1.0.1","1.0.0"]}}]}
1
+ {"schemaVersion":1,"kind":"project-type","count":46,"entries":[{"manifest":{"schemaVersion":1,"kind":"project-type","id":"books-and-close","name":"Books & Month Close","description":"Keep the books tidy and close each month on time. A bookkeeper books every receipt and sale into a categorized ledger, works through a month-close checklist with you, and keeps a P&L snapshot one glance away.","tags":["bookkeeping","accounting","receipts","month-close","profit-and-loss","small-business"],"category":"money","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.0.0","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"business":{"type":"string","title":"What kind of business is this?","description":"e.g. 'a three-person electrical contractor', 'a café in Portland'.","default":"the business"},"currency":{"type":"string","title":"Which currency are the books kept in?","description":"A three-letter code, e.g. USD, EUR or GBP.","default":"USD"}},"required":["business","currency"]},"nameTemplate":"Books & Month Close","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"bookkeeper","voorman":true}],"toolsets":[],"craftbooks":["receipt-intake"],"scripts":{"books-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { ledgerStore, rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'books-store',\n description:\n \"Read and update the books: the ledger (ledger.json), the month-close checklist (close.json) and the receipts inbox (inbox/). action:'status' for last month's P&L, the close checklist and what is waiting; 'record' to book money in or out (the same receipt, or the same payee, date and amount, updates the entry instead of adding it twice); 'categorize' to give an entry its category; 'tick' to check off a close step; 'close' to close a finished month once every step is done; 'reopen' to reopen a closed month; 'list' for the entries.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'status', 'record', 'categorize', 'tick', 'close', 'reopen', or 'list'.\",\n required: true,\n },\n id: { type: 'string', description: \"Ledger entry id, e.g. 'ledger-7'.\" },\n payee: {\n type: 'string',\n description: \"Who was paid, or who paid, e.g. 'Hillside Hardware'. Also finds an entry when no id is given.\",\n },\n amount: { type: 'number', description: 'Amount in ordinary units, e.g. 284.17. Always positive.' },\n kind: {\n type: 'string',\n description: \"expense or income. Defaults from the category; a supplier's refund is income on its expense category.\",\n },\n category: { type: 'string', description: 'materials, subcontractors, payroll, vehicle, tools, insurance, rent, utilities, software, marketing, office, professional-fees, bank-fees, licenses, meals, other, sales, other-income, owner-draw, uncategorized.' },\n date: { type: 'string', description: 'The day the money moved, YYYY-MM-DD (default today).' },\n file: { type: 'string', description: \"The receipt's path in the inbox, e.g. 'inbox/hillside-1029.jpg'.\" },\n note: { type: 'string', description: 'What it was for, with any reference number exactly as written.' },\n month: { type: 'string', description: 'A month, YYYY-MM (default: the month being closed).' },\n step: { type: 'string', description: 'A close step: receipts, categories, bank, card, payroll, income, review.' },\n done: { type: 'boolean', description: 'For tick: false unticks the step.' },\n },\n outputs: {\n waiting: { type: 'number', description: 'Receipts in the inbox not booked yet.' },\n uncategorized: { type: 'number', description: 'Entries that still need a category.' },\n closeMonth: { type: 'string', description: 'The month being closed, YYYY-MM.' },\n stepsLeft: { type: 'number', description: 'Close steps still to do for that month.' },\n net: { type: 'number', description: \"That month's net profit, in ordinary units like amount (negative for a loss).\" },\n summary: { type: 'string', description: 'What changed, then the books picture; or the listing.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── books-rules-start ──\n// Pure derivations shared by the script, the page and the sample conversation:\n// integer-cent money, the P&L by category group, the receipts still waiting in\n// the inbox, and the month-close checklist. Kept self-contained between these\n// sentinels so unit tests execute the shipped bytes.\nvar CATEGORY_GROUP = {\n materials: 'cost',\n subcontractors: 'cost',\n payroll: 'expense',\n vehicle: 'expense',\n tools: 'expense',\n insurance: 'expense',\n rent: 'expense',\n utilities: 'expense',\n software: 'expense',\n marketing: 'expense',\n office: 'expense',\n 'professional-fees': 'expense',\n 'bank-fees': 'expense',\n licenses: 'expense',\n meals: 'expense',\n other: 'expense',\n sales: 'income',\n 'other-income': 'income',\n 'owner-draw': 'equity',\n uncategorized: 'unsorted',\n};\nvar CATEGORIES = Object.keys(CATEGORY_GROUP);\nvar CATEGORY_WORDS = {\n income: 'sales', revenue: 'sales', sale: 'sales', job: 'sales', jobs: 'sales', interest: 'other-income', refund: 'other-income',\n material: 'materials', supplies: 'materials', supply: 'materials', parts: 'materials', stock: 'materials',\n subcontractor: 'subcontractors', contractor: 'subcontractors', contractors: 'subcontractors',\n wages: 'payroll', salary: 'payroll', salaries: 'payroll',\n fuel: 'vehicle', gas: 'vehicle', van: 'vehicle', truck: 'vehicle', mileage: 'vehicle',\n tool: 'tools', equipment: 'tools',\n advertising: 'marketing', ads: 'marketing',\n phone: 'utilities', internet: 'utilities', electric: 'utilities',\n legal: 'professional-fees', accounting: 'professional-fees', accountant: 'professional-fees',\n fees: 'bank-fees', 'bank-fee': 'bank-fees', license: 'licenses', permit: 'licenses', permits: 'licenses',\n meal: 'meals', food: 'meals', draw: 'owner-draw', 'owner-draws': 'owner-draw',\n unknown: 'uncategorized', 'not-sure': 'uncategorized',\n};\nvar GROUP_ORDER = ['income', 'cost', 'expense', 'equity'];\nvar STEPS = [\n { id: 'receipts', label: 'Book every receipt in the inbox', words: ['receipt', 'inbox'] },\n { id: 'categories', label: 'Give every entry a category', words: ['categor'] },\n { id: 'bank', label: 'Match the bank statement', words: ['bank', 'checking'] },\n { id: 'card', label: 'Match the card statement', words: ['card', 'credit'] },\n { id: 'payroll', label: 'Record payroll and subcontractor payments', words: ['payroll', 'wage', 'subcontract'] },\n { id: 'income', label: 'Record every customer payment', words: ['customer', 'payment', 'invoice', 'income', 'deposit'] },\n { id: 'review', label: 'Review the P&L with the owner', words: ['review', 'p&l', 'owner', 'profit'] },\n];\nvar MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];\n\nfunction pad(n) {\n return n < 10 ? '0' + n : String(n);\n}\nfunction localDay(ms) {\n var d = new Date(ms);\n return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());\n}\nfunction normalizeDate(text) {\n var raw = String(text || '').trim();\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(raw)) return raw;\n var parsed = Date.parse(raw);\n return isFinite(parsed) ? localDay(parsed) : null;\n}\nfunction prevMonth(month) {\n var y = Number(month.slice(0, 4));\n var m = Number(month.slice(5, 7)) - 1;\n if (m < 1) {\n m = 12;\n y -= 1;\n }\n return y + '-' + pad(m);\n}\nfunction monthName(month) {\n return MONTHS[Number(String(month).slice(5, 7)) - 1] + ' ' + String(month).slice(0, 4);\n}\n// 'YYYY-MM', a date, 'last month', or a month name; a bare name means its latest past or current occurrence.\nfunction normalizeMonth(text, nowMs) {\n var raw = String(text || '').trim().toLowerCase();\n var current = localDay(nowMs).slice(0, 7);\n if (/^\\d{4}-\\d{2}$/.test(raw)) return raw;\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(raw)) return raw.slice(0, 7);\n if (/last|previous/.test(raw)) return prevMonth(current);\n if (/this|current/.test(raw)) return current;\n for (var i = 0; i < 12; i++) {\n if (raw.indexOf(MONTHS[i].toLowerCase().slice(0, 3)) === 0) {\n var year = raw.match(/\\d{4}/);\n var candidate = (year ? year[0] : current.slice(0, 4)) + '-' + pad(i + 1);\n if (!year && candidate > current) candidate = Number(current.slice(0, 4)) - 1 + '-' + pad(i + 1);\n return candidate;\n }\n }\n return null;\n}\n// Integer cents from 284.17, '284.17' or '$1,912.40', with no float arithmetic; null unless positive.\nfunction toCents(value) {\n var text = typeof value === 'number' ? (isFinite(value) ? String(value) : '') : String(value == null ? '' : value);\n var m = /^(\\d+)(?:\\.(\\d*))?$/.exec(text.replace(/[$,\\s]/g, ''));\n if (!m) return null;\n var frac = (m[2] || '') + '000';\n var cents = Number(m[1]) * 100 + Number(frac.slice(0, 2)) + (Number(frac.charAt(2)) >= 5 ? 1 : 0);\n return cents > 0 ? cents : null;\n}\nfunction money(cents) {\n var abs = Math.abs(Math.round(cents));\n var whole = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\n return (cents < 0 ? '-' : '') + whole + '.' + pad(abs % 100);\n}\nfunction normalizeCategory(text) {\n var key = String(text || '').trim().toLowerCase().replace(/&/g, 'and').replace(/[\\s_]+/g, '-');\n if (Object.prototype.hasOwnProperty.call(CATEGORY_GROUP, key)) return key;\n if (Object.prototype.hasOwnProperty.call(CATEGORY_WORDS, key)) return CATEGORY_WORDS[key];\n var words = key.split('-');\n for (var i = 0; i < words.length; i++) {\n if (Object.prototype.hasOwnProperty.call(CATEGORY_GROUP, words[i])) return words[i];\n if (Object.prototype.hasOwnProperty.call(CATEGORY_WORDS, words[i])) return CATEGORY_WORDS[words[i]];\n }\n return null;\n}\nfunction normalizeStep(text) {\n var raw = String(text || '').trim().toLowerCase();\n for (var i = 0; i < STEPS.length; i++) if (STEPS[i].id === raw) return STEPS[i].id;\n for (var j = 0; j < STEPS.length; j++) {\n for (var k = 0; k < STEPS[j].words.length; k++) if (raw.indexOf(STEPS[j].words[k]) >= 0) return STEPS[j].id;\n }\n return null;\n}\nfunction stepLabel(id) {\n for (var i = 0; i < STEPS.length; i++) if (STEPS[i].id === id) return STEPS[i].label;\n return id;\n}\nfunction entryDate(entry) {\n return String((entry.data && entry.data.date) || entry.at || '').slice(0, 10);\n}\nfunction monthOf(entry) {\n return entryDate(entry).slice(0, 7);\n}\nfunction payeeOf(entry) {\n return String((entry.data && entry.data.payee) || entry.note || '');\n}\nfunction groupOf(entry) {\n var group = CATEGORY_GROUP[entry.category] || 'expense';\n return group === 'unsorted' ? (entry.kind === 'in' ? 'income' : 'expense') : group;\n}\nfunction entryLine(entry) {\n return (\n entry.id + ' ' + entryDate(entry) + ' ' + payeeOf(entry) + ' ' + money(entry.amountCents) +\n (entry.kind === 'in' ? ' in, ' : ' out, ') + entry.category +\n (entry.data && entry.data.file ? ' (receipt ' + entry.data.file + ')' : '')\n );\n}\n// The month's P&L: income less cost of jobs is gross profit; less expenses is net profit. Owner draws stay off it.\nfunction pnl(entries, month) {\n var rows = {};\n var totals = { income: 0, cost: 0, expense: 0, equity: 0 };\n var count = 0;\n entries.forEach(function (e) {\n if (monthOf(e) !== month) return;\n count += 1;\n var group = groupOf(e);\n var cents = e.kind === (group === 'income' ? 'in' : 'out') ? e.amountCents : -e.amountCents;\n totals[group] += cents;\n var key = group + ':' + e.category;\n if (!rows[key]) rows[key] = { group: group, category: e.category, cents: 0 };\n rows[key].cents += cents;\n });\n var lines = Object.keys(rows)\n .map(function (k) { return rows[k]; })\n .sort(function (a, b) { return GROUP_ORDER.indexOf(a.group) - GROUP_ORDER.indexOf(b.group) || b.cents - a.cents; });\n var gross = totals.income - totals.cost;\n return {\n month: month, count: count, incomeCents: totals.income, costCents: totals.cost, grossCents: gross,\n expenseCents: totals.expense, netCents: gross - totals.expense, drawCents: totals.equity, lines: lines,\n };\n}\nfunction pnlLine(p) {\n if (!p.count) return monthName(p.month) + ': nothing booked.';\n var part = function (group) {\n var rows = p.lines.filter(function (l) { return l.group === group; }).map(function (l) { return l.category + ' ' + money(l.cents); });\n return rows.length ? ' (' + rows.join(', ') + ')' : '';\n };\n return (\n monthName(p.month) + ': income ' + money(p.incomeCents) + part('income') +\n '; cost of jobs ' + money(p.costCents) + part('cost') +\n '; gross profit ' + money(p.grossCents) +\n '; expenses ' + money(p.expenseCents) + part('expense') +\n '; net profit ' + money(p.netCents) + (p.netCents < 0 ? ' (a loss)' : '') +\n (p.drawCents ? '; owner draws ' + money(p.drawCents) + ', not on the P&L' : '') + '.'\n );\n}\n// Inbox files that no entry names as its receipt yet.\nfunction waitingFiles(names, entries) {\n var booked = {};\n entries.forEach(function (e) {\n if (e.data && e.data.file) booked[String(e.data.file)] = true;\n });\n return names\n .filter(function (n) { return n.charAt(0) !== '.' && !booked['inbox/' + n]; })\n .map(function (n) { return 'inbox/' + n; });\n}\nfunction needsCategory(entries, month) {\n return entries.filter(function (e) { return e.category === 'uncategorized' && (!month || monthOf(e) === month); });\n}\nfunction closeRecord(closes, month) {\n for (var i = 0; i < closes.length; i++) if (closes[i].fields && closes[i].fields.month === month) return closes[i];\n return null;\n}\nfunction isClosed(closes, month) {\n var r = closeRecord(closes, month);\n return !!r && r.status === 'closed';\n}\n// The month to close: the earliest finished month with entries that is still open, else last month.\nfunction monthToClose(entries, closes, nowMs) {\n var current = localDay(nowMs).slice(0, 7);\n var months = {};\n entries.forEach(function (e) {\n var m = monthOf(e);\n if (m && m < current) months[m] = true;\n });\n closes.forEach(function (r) {\n if (r.fields && r.fields.month && r.fields.month < current) months[r.fields.month] = true;\n });\n var open = Object.keys(months).filter(function (m) { return !isClosed(closes, m); }).sort();\n return open.length ? open[0] : prevMonth(current);\n}\nfunction closeView(month, entries, closes, waiting) {\n var rec = closeRecord(closes, month);\n var fields = (rec && rec.fields) || {};\n var done = fields.done || {};\n var notes = fields.notes || {};\n var closed = !!rec && rec.status === 'closed';\n var unsorted = needsCategory(entries, month);\n var steps = STEPS.map(function (s) {\n var ticked = !!done[s.id];\n var auto = s.id === 'receipts' ? waiting.length === 0 : s.id === 'categories' ? unsorted.length === 0 : false;\n var ok = closed || (s.id === 'categories' ? auto : auto || ticked);\n return { id: s.id, label: s.label, done: ok, on: done[s.id] || '', note: notes[s.id] || '', auto: auto && !ticked };\n });\n var left = steps.filter(function (s) { return !s.done; });\n return { month: month, closed: closed, closedOn: fields.closedOn || '', steps: steps, left: left, ready: !closed && left.length === 0, unsorted: unsorted };\n}\nfunction closeLine(view) {\n if (view.closed) return monthName(view.month) + ' is closed' + (view.closedOn ? ' (closed ' + view.closedOn + ')' : '') + '.';\n var count = view.steps.length - view.left.length;\n return (\n 'Close of ' + monthName(view.month) + ': ' + count + ' of ' + view.steps.length + ' steps done. ' +\n (view.ready\n ? 'Every step is done, so it is ready to close.'\n : 'Still to do: ' + view.left.map(function (s) { return s.label + ' (' + s.id + ')'; }).join('; ') + '.')\n );\n}\nfunction picture(entries, closes, inboxNames, nowMs, focusMonth) {\n var current = localDay(nowMs).slice(0, 7);\n var last = prevMonth(current);\n var closing = monthToClose(entries, closes, nowMs);\n var waiting = waitingFiles(inboxNames, entries);\n var unsorted = needsCategory(entries);\n var view = closeView(closing, entries, closes, waiting);\n var parts = [];\n var shown = [];\n function addPnl(month) {\n if (!month || shown.indexOf(month) >= 0) return;\n shown.push(month);\n var label = month === last ? 'P&L for last month, ' : month === current ? 'This month so far, ' : 'P&L for ';\n parts.push(label + pnlLine(pnl(entries, month)));\n }\n addPnl(focusMonth);\n addPnl(last);\n addPnl(closing);\n parts.push(closeLine(view));\n parts.push(\n waiting.length\n ? waiting.length + (waiting.length === 1 ? ' receipt is' : ' receipts are') + ' waiting in the inbox to be booked: ' + waiting.join(', ') + '.'\n : 'No receipts are waiting in the inbox.',\n );\n parts.push(\n unsorted.length\n ? unsorted.length + (unsorted.length === 1 ? ' entry needs' : ' entries need') + ' a category: ' + unsorted.map(entryLine).join(' | ') + '.'\n : 'Every entry has a category.',\n );\n addPnl(current);\n var closedMonths = closes\n .filter(function (r) { return r.status === 'closed' && r.fields && r.fields.month; })\n .map(function (r) { return r.fields.month; })\n .sort();\n if (closedMonths.length) parts.push('Closed months: ' + closedMonths.map(monthName).join(', ') + '.');\n return { closing: closing, view: view, waiting: waiting, unsorted: unsorted, netCents: pnl(entries, closing).netCents, summary: parts.join(' ') };\n}\n// ── books-rules-end ──\n\ntype Entry = {\n id: string;\n at: string;\n amountCents: number;\n kind: 'in' | 'out';\n category: string;\n note?: string;\n data?: Record<string, unknown>;\n};\n\nconst ledger = ledgerStore(gezel.fs, 'ledger.json');\nconst closeBook = rosterStore(gezel.fs, 'close.json', { stages: ['open', 'closed'], idPrefix: 'close' });\nconst now = Date.now();\nconst today = localDay(now);\nconst currentMonth = today.slice(0, 7);\n\nasync function inboxNames(): Promise<string[]> {\n try {\n return (await gezel.fs.list('inbox')).filter((e) => !e.isDirectory).map((e) => e.name).sort();\n } catch {\n return [];\n }\n}\n\n// ledgerStore only appends; a correction rewrites the one entry in place, in the store's own file format.\nasync function patchEntry(id: string, patch: (entry: Entry) => void): Promise<Entry> {\n const file = JSON.parse(await gezel.fs.read('ledger.json')) as { entries: Entry[] };\n const entry = file.entries.find((e) => e.id === id);\n if (!entry) throw new Error('No ledger entry ' + id + '.');\n patch(entry);\n await gezel.fs.write('ledger.json', JSON.stringify(file, null, 2) + '\\n');\n return entry;\n}\n\nfunction resolveEntry(all: Entry[]): Entry {\n if (input.id) {\n const hit = all.find((e) => e.id === input.id);\n if (hit) return hit;\n throw new Error(\"No entry '\" + input.id + \"'. Call action:'list' to see the entries.\");\n }\n const wanted = (input.payee ?? '').trim().toLowerCase();\n if (wanted) {\n let hits = all.filter((e) => payeeOf(e).toLowerCase() === wanted);\n if (!hits.length) {\n hits = all.filter((e) => {\n const p = payeeOf(e).toLowerCase();\n return !!p && (p.includes(wanted) || wanted.includes(p));\n });\n }\n const cents = toCents(input.amount);\n if (hits.length > 1 && cents) {\n const same = hits.filter((e) => e.amountCents === cents);\n if (same.length) hits = same;\n }\n if (hits.length > 1) {\n const unsorted = hits.filter((e) => e.category === 'uncategorized');\n if (unsorted.length === 1) hits = unsorted;\n }\n if (hits.length === 1) return hits[0]!;\n if (hits.length > 1) {\n throw new Error(\"More than one entry matches '\" + input.payee + \"': \" + hits.map(entryLine).join(' | ') + '. Pass id.');\n }\n }\n throw new Error(\"Pass 'id' (e.g. 'ledger-7') or the entry's 'payee'. Call action:'list' to see the entries.\");\n}\n\nfunction kindOf(text: string | undefined): 'in' | 'out' | null {\n const k = String(text ?? '').trim().toLowerCase();\n return k === 'income' || k === 'in' ? 'in' : k === 'expense' || k === 'out' ? 'out' : null;\n}\nfunction naturalKind(category: string): 'in' | 'out' {\n return CATEGORY_GROUP[category] === 'income' ? 'in' : 'out';\n}\nfunction normalizeFile(file: string): string {\n const clean = file.trim().replace(/\\\\/g, '/').replace(/^\\.?\\//, '');\n return clean.includes('/') ? clean : 'inbox/' + clean;\n}\nfunction pickMonth(all: Entry[], closes: unknown[]): string {\n const month = input.month ? normalizeMonth(input.month, now) : monthToClose(all, closes, now);\n if (!month) throw new Error(\"month must be YYYY-MM, e.g. '\" + prevMonth(currentMonth) + \"'.\");\n if (month >= currentMonth) throw new Error(monthName(month) + \" isn't over yet. Close steps are for a finished month.\");\n return month;\n}\nasync function ensureClose(month: string, closes: unknown[]) {\n const found = closeRecord(closes, month);\n if (found) return found;\n return closeBook.add({ id: 'close-' + month, status: 'open', fields: { month, done: {}, notes: {} } });\n}\nfunction lockedMessage(month: string): string {\n return monthName(month) + ' is closed. Reopen it first (reopen_month), or date the entry in an open month.';\n}\n\nconst closeList = await closeBook.list();\nlet note = '';\n\nif (input.action === 'record') {\n const cents = toCents(input.amount);\n if (cents === null) throw new Error(\"record needs a positive 'amount' in ordinary units, e.g. 284.17.\");\n const payee = (input.payee ?? '').trim();\n if (!payee) throw new Error(\"record needs 'payee': who was paid, or who paid.\");\n const date = input.date ? normalizeDate(input.date) : today;\n if (!date) throw new Error(\"date must be a date, e.g. '\" + today + \"'.\");\n const category = input.category ? normalizeCategory(input.category) : null;\n if (input.category && !category) {\n throw new Error(\"Unknown category '\" + input.category + \"'. Use one of: \" + CATEGORIES.join(', ') + '.');\n }\n const explicit = kindOf(input.kind);\n const kind = explicit ?? naturalKind(category ?? 'uncategorized');\n const file = input.file ? normalizeFile(input.file) : undefined;\n if (isClosed(closeList, date.slice(0, 7))) throw new Error(lockedMessage(date.slice(0, 7)));\n const all = (await ledger.list()) as Entry[];\n const same = all.find(\n (e) =>\n (file && e.data?.file === file) ||\n (entryDate(e) === date && e.amountCents === cents && payeeOf(e).toLowerCase() === payee.toLowerCase()),\n );\n if (same) {\n if (isClosed(closeList, monthOf(same))) throw new Error(lockedMessage(monthOf(same)));\n const updated = await patchEntry(same.id, (entry) => {\n entry.amountCents = cents;\n entry.at = date + 'T12:00:00.000Z';\n if (category) entry.category = category;\n if (explicit || category) entry.kind = kind;\n if (input.note) entry.note = input.note.trim();\n // A payee typed differently keeps its booked spelling; a re-read receipt may correct it.\n entry.data = { ...(entry.data ?? {}), date, ...(file && same.data?.file === file ? { payee } : {}), ...(file ? { file } : {}) };\n });\n note = 'Already in the books, so updated it instead of adding it twice: ' + entryLine(updated) + '.';\n } else {\n const added = await ledger.add({\n amountCents: cents,\n kind,\n category: category ?? 'uncategorized',\n at: date + 'T12:00:00.000Z',\n ...(input.note ? { note: input.note.trim() } : {}),\n data: { date, payee, ...(file ? { file } : {}) },\n });\n note = 'Booked ' + entryLine(added) + '.' + (category ? '' : ' It needs a category: ask what it was for.');\n }\n} else if (input.action === 'categorize') {\n const category = normalizeCategory(input.category ?? '');\n if (!category || category === 'uncategorized') {\n throw new Error(\"categorize needs 'category', one of: \" + CATEGORIES.filter((c) => c !== 'uncategorized').join(', ') + '.');\n }\n const entry = resolveEntry((await ledger.list()) as Entry[]);\n if (isClosed(closeList, monthOf(entry))) throw new Error(lockedMessage(monthOf(entry)));\n const updated = await patchEntry(entry.id, (e) => {\n const explicit = kindOf(input.kind);\n if (explicit) e.kind = explicit;\n else if (e.category === 'uncategorized') e.kind = naturalKind(category);\n e.category = category;\n if (input.note) e.note = input.note.trim();\n });\n note = payeeOf(updated) + ' (' + updated.id + ', ' + money(updated.amountCents) + ' on ' + entryDate(updated) + ') is now under ' + category + '.';\n} else if (input.action === 'tick') {\n const step = normalizeStep(input.step ?? '');\n if (!step) throw new Error(\"tick needs 'step': \" + STEPS.map((s) => s.id).join(', ') + '.');\n const all = (await ledger.list()) as Entry[];\n const month = pickMonth(all, closeList);\n if (step === 'categories') {\n const left = needsCategory(all, month);\n if (left.length) {\n throw new Error(left.length + ' entries in ' + monthName(month) + ' still need a category: ' + left.map(entryLine).join(' | ') + '. Give each one its category; this step checks itself.');\n }\n note = 'Every entry in ' + monthName(month) + ' has a category, so that step checks itself.';\n } else {\n const rec = await ensureClose(month, closeList);\n if (rec.status === 'closed') throw new Error(monthName(month) + ' is already closed. Reopen it to change its checklist.');\n const done: Record<string, string> = { ...((rec.fields.done as Record<string, string>) ?? {}) };\n const notes: Record<string, string> = { ...((rec.fields.notes as Record<string, string>) ?? {}) };\n if (input.done === false) {\n delete done[step];\n delete notes[step];\n } else {\n done[step] = today;\n if (input.note) notes[step] = input.note.trim();\n }\n await closeBook.update(rec.id, { fields: { done, notes }, note: stepLabel(step) + (input.done === false ? ': unticked' : ': done') });\n note = stepLabel(step) + (input.done === false ? ' is unticked' : ' is done') + ' for ' + monthName(month) + '.';\n }\n} else if (input.action === 'close') {\n const all = (await ledger.list()) as Entry[];\n const month = pickMonth(all, closeList);\n const existing = closeRecord(closeList, month);\n if (existing && existing.status === 'closed') {\n note = monthName(month) + ' was already closed.';\n } else {\n const view = closeView(month, all, closeList, waitingFiles(await inboxNames(), all));\n if (!view.ready) {\n throw new Error(monthName(month) + ' is not ready to close. Still to do: ' + view.left.map((s) => s.label + ' (' + s.id + ')').join('; ') + '.');\n }\n const rec = existing ?? (await ensureClose(month, closeList));\n const result = pnl(all, month);\n await closeBook.update(rec.id, { fields: { closedOn: today, netCents: result.netCents } });\n await closeBook.transition(rec.id, 'closed', { note: 'Closed with net profit ' + money(result.netCents) });\n note = monthName(month) + ' is closed with net profit ' + money(result.netCents) + '. Its entries are locked until it is reopened.';\n }\n} else if (input.action === 'reopen') {\n const closed = closeList.filter((r) => r.status === 'closed').map((r) => String(r.fields.month)).sort();\n const month = input.month ? normalizeMonth(input.month, now) : closed[closed.length - 1];\n if (!month) throw new Error('No month is closed.');\n const rec = closeRecord(closeList, month);\n if (!rec || rec.status !== 'closed') throw new Error(monthName(month) + ' is not closed.');\n await closeBook.transition(rec.id, 'open', { note: input.note ?? 'Reopened' });\n note = monthName(month) + ' is open again. Close it once the change is booked.';\n} else if (input.action !== 'status' && input.action !== 'list') {\n throw new Error(\"Unknown action '\" + input.action + \"'. Use status, record, categorize, tick, close, reopen, or list.\");\n}\n\nconst entries = (await ledger.list()) as Entry[];\nconst closes = await closeBook.list();\nconst focus = input.month ? normalizeMonth(input.month, now) : null;\nconst view = picture(entries, closes, await inboxNames(), now, input.action === 'status' ? focus : null);\nconst rows = entries.filter((e) => !focus || monthOf(e) === focus);\nconst listing =\n input.action === 'list'\n ? (focus ? 'Entries in ' + monthName(focus) + ' (' + rows.length + '):\\n' : 'Latest entries (' + Math.min(rows.length, 80) + ' of ' + rows.length + '):\\n') +\n (rows.slice(-80).map(entryLine).join('\\n') || 'None.')\n : '';\n\ngezel.output({\n waiting: view.waiting.length,\n uncategorized: view.unsorted.length,\n closeMonth: view.closing,\n stepsLeft: view.view.left.length,\n net: view.netCents / 100,\n summary: listing || (note ? note + ' ' : '') + view.summary,\n});\n"},"tools":[{"name":"books_status","description":"Last month's P&L (income, cost of jobs, gross and net profit by category), the month-close checklist with the steps still to do, receipts waiting in the inbox, and entries that need a category, each with its id. Call it first for any question about the books.","script":"books-store","inputs":{"type":"object","properties":{"month":{"type":"string"}}},"bind":{"action":"status"},"state":true},{"name":"record_entry","description":"Book money in or out: payee, amount in ordinary units (e.g. 284.17), date (YYYY-MM-DD), category, and the receipt's inbox path when there is one. The same receipt, or the same payee, date and amount, updates the entry instead of adding it twice. Call it as soon as a payment, sale or receipt is mentioned, before you describe it. When the category is unclear, leave it out and ask.","script":"books-store","inputs":{"type":"object","properties":{"payee":{"type":"string"},"amount":{"type":"number"},"date":{"type":"string"},"category":{"type":"string","enum":["materials","subcontractors","payroll","vehicle","tools","insurance","rent","utilities","software","marketing","office","professional-fees","bank-fees","licenses","meals","other","sales","other-income","owner-draw","uncategorized"]},"kind":{"type":"string","enum":["expense","income"]},"file":{"type":"string"},"note":{"type":"string"}},"required":["payee","amount"]},"bind":{"action":"record"}},{"name":"categorize_entry","description":"Give an entry its category, or change it, found by id or payee. Call it the moment the person says what a charge was for.","script":"books-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"payee":{"type":"string"},"category":{"type":"string","enum":["materials","subcontractors","payroll","vehicle","tools","insurance","rent","utilities","software","marketing","office","professional-fees","bank-fees","licenses","meals","other","sales","other-income","owner-draw"]},"kind":{"type":"string","enum":["expense","income"]},"note":{"type":"string"}},"required":["category"]},"bind":{"action":"categorize"}},{"name":"tick_close_step","description":"Check off a month-close step for the month being closed: bank, card, payroll, income, review, or receipts (when the leftover inbox files are set aside). Call it as soon as the person says a step is done.","script":"books-store","inputs":{"type":"object","properties":{"step":{"type":"string","enum":["receipts","categories","bank","card","payroll","income","review"]},"month":{"type":"string"},"done":{"type":"boolean"},"note":{"type":"string"}},"required":["step"]},"bind":{"action":"tick"}},{"name":"close_month","description":"Close a finished month once every step on its checklist is done; its entries are then locked. If steps are left, the error names them.","script":"books-store","inputs":{"type":"object","properties":{"month":{"type":"string"}}},"bind":{"action":"close"}},{"name":"reopen_month","description":"Reopen a closed month so an entry in it can be fixed. Close it again afterward.","script":"books-store","inputs":{"type":"object","properties":{"month":{"type":"string"},"note":{"type":"string"}}},"bind":{"action":"reopen"}},{"name":"list_entries","description":"Every entry for a month (YYYY-MM), with ids, payees, amounts, categories and receipts.","script":"books-store","inputs":{"type":"object","properties":{"month":{"type":"string"}}},"bind":{"action":"list"}},{"name":"page_record_entry","description":"Book money in or out.","script":"books-store","inputs":{"type":"object","properties":{"payee":{"type":"string"},"amount":{"type":"number"},"date":{"type":"string"},"category":{"type":"string","enum":["materials","subcontractors","payroll","vehicle","tools","insurance","rent","utilities","software","marketing","office","professional-fees","bank-fees","licenses","meals","other","sales","other-income","owner-draw","uncategorized"]},"kind":{"type":"string","enum":["expense","income"]},"file":{"type":"string"},"note":{"type":"string"}},"required":["payee","amount"]},"bind":{"action":"record"}},{"name":"page_categorize_entry","description":"Give an entry its category.","script":"books-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"payee":{"type":"string"},"category":{"type":"string","enum":["materials","subcontractors","payroll","vehicle","tools","insurance","rent","utilities","software","marketing","office","professional-fees","bank-fees","licenses","meals","other","sales","other-income","owner-draw"]},"kind":{"type":"string","enum":["expense","income"]},"note":{"type":"string"}},"required":["category"]},"bind":{"action":"categorize"}},{"name":"page_tick_close_step","description":"Check off a month-close step.","script":"books-store","inputs":{"type":"object","properties":{"step":{"type":"string","enum":["receipts","categories","bank","card","payroll","income","review"]},"month":{"type":"string"},"done":{"type":"boolean"},"note":{"type":"string"}},"required":["step"]},"bind":{"action":"tick"}},{"name":"page_close_month","description":"Close the month being closed.","script":"books-store","inputs":{"type":"object","properties":{"month":{"type":"string"}}},"bind":{"action":"close"},"reaction":{"gezel":"bookkeeper","prompt":"The person just closed a month on the books page. The books now read (the first sentence is what changed):\n{{output.summary}}\nIn two short sentences, confirm which month is closed and its net profit, and name the first thing to do for the next close. Do not call tools.","hideSeed":true}}],"pages":{"imports":[{"id":"inbox","source":"workspace","path":"inbox","accept":[".pdf",".png",".jpg",".jpeg",".webp",".heic",".txt",".md"],"maxFileBytes":26214400}],"entry":"books/index.html","api":1,"reads":[{"source":"workspace","path":"ledger.json"},{"source":"workspace","path":"close.json"},{"source":"workspace","path":"inbox","subtree":true}],"tools":["page_record_entry","page_categorize_entry","page_tick_close_step","page_close_month"]},"schedules":[],"workspaceSeed":["ledger.json","close.json"],"artifactsSeed":[],"availableVersions":["1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"campaign-room","name":"Campaign Room","description":"Run one marketing campaign from plan to results. A campaign manager keeps the goal, a channel calendar, every asset from idea to live, the budget against what was spent, and the results day by day in one room, so a launch never rests on anyone’s memory.","tags":["marketing","campaign","launch","promotion","small-business"],"category":"business","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.0.0","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"business":{"type":"string","title":"What business is running the campaign?","description":"e.g. 'a small press in Portland', 'a three-person bakery'.","default":"the business"},"campaign":{"type":"string","title":"What are you launching or promoting?","description":"e.g. 'our autumn novel', 'the new spring menu'.","default":"the next launch"}},"required":["business"]},"nameTemplate":"Campaign Room","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"campaign-manager","voorman":true},{"templateId":"omroeper","voorman":false},{"templateId":"copywriter","voorman":false},{"templateId":"designer","voorman":false}],"toolsets":[],"craftbooks":["ad-variations","email-sequence","landing-copy","social-thread"],"scripts":{"campaign-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { logStore, rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'campaign-store',\n description:\n \"Read and update the campaign room: the campaign (campaign.json), its assets (assets.json) and its results and spend (results.json). action:'status' for the whole picture; 'set_campaign' for the goal, audience, dates and budget (budgetChange adds to the budget); 'add_asset' to plan an asset (an existing title is updated, never duplicated); 'move_asset' to change an asset's stage, date or owner; 'log_result' for an asset's numbers on a day; 'log_spend' for money spent; 'list' for every asset.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'status', 'set_campaign', 'add_asset', 'move_asset', 'log_result', 'log_spend', or 'list'.\",\n required: true,\n },\n name: { type: 'string', description: \"The campaign's name, e.g. 'The Salt Road launch'.\" },\n goal: { type: 'string', description: \"The goal in the person's words, e.g. '600 preorders by launch day'.\" },\n audience: { type: 'string', description: 'Who the campaign is for.' },\n goalMetric: { type: 'string', description: \"What the goal counts, e.g. 'preorders', 'signups', 'bookings'.\" },\n goalTarget: { type: 'number', description: 'The number to reach, e.g. 600.' },\n goalBy: { type: 'string', description: 'When the goal should be met, YYYY-MM-DD (defaults to the launch date).' },\n launchAt: { type: 'string', description: 'Launch day, YYYY-MM-DD.' },\n startAt: { type: 'string', description: 'First day of the campaign, YYYY-MM-DD.' },\n endAt: { type: 'string', description: 'Last day of the campaign, YYYY-MM-DD.' },\n budget: { type: 'number', description: 'The whole budget in dollars; replaces the current budget.' },\n budgetChange: {\n type: 'number',\n description: 'Dollars to add to the current budget (negative to cut it). The campaign does the sum.',\n },\n id: { type: 'string', description: \"Asset id, e.g. 'as-3'.\" },\n title: {\n type: 'string',\n description: \"The asset's name, e.g. 'Launch-day email'. Also finds an asset when no id is given.\",\n },\n channel: {\n type: 'string',\n description: 'email, instagram, facebook, linkedin, bluesky, x, tiktok, youtube, website, ads, print, press, event, or other.',\n },\n kind: {\n type: 'string',\n description: 'post, email, ad, landing-page, video, graphic, print, press-release, event, or other.',\n },\n goesOutAt: { type: 'string', description: 'The day the asset goes out, YYYY-MM-DD.' },\n shiftDays: {\n type: 'number',\n description: \"Move the asset's date by this many days (2 = two days later, -1 = a day earlier).\",\n },\n owner: { type: 'string', description: 'Who makes or sends it.' },\n status: { type: 'string', description: 'Asset stage: idea, draft, approved, scheduled, or live.' },\n note: { type: 'string', description: 'What happened, in the person’s words.' },\n day: { type: 'string', description: 'The day the numbers or the spend are for, YYYY-MM-DD (default today).' },\n reach: { type: 'number', description: 'People reached: opens, views or impressions.' },\n clicks: { type: 'number', description: 'Clicks through.' },\n conversions: { type: 'number', description: \"What the goal counts (preorders, signups) on that day for that asset.\" },\n amount: { type: 'number', description: 'Dollars spent, e.g. 250 or 249.99.' },\n withinDays: { type: 'number', description: 'How many days ahead the calendar covers (default 14).' },\n },\n outputs: {\n daysToLaunch: { type: 'number', description: 'Days until launch; negative once launched, 0 when no date is set.' },\n assets: { type: 'number', description: 'Assets in the campaign.' },\n ready: { type: 'number', description: 'Assets approved, scheduled or live.' },\n budget: { type: 'number', description: 'The budget, in dollars.' },\n spent: { type: 'number', description: 'Spent so far, in dollars.' },\n conversions: { type: 'number', description: 'Goal results so far.' },\n summary: { type: 'string', description: 'What changed, then the campaign picture; or the listing.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── campaign-rules-start ──\n// Pure derivations: local calendar days, money in integer cents, the newest\n// figures per asset and day, and the campaign picture the crew reads. Kept\n// self-contained between these sentinels so tests execute the shipped bytes.\nvar DAY_MS = 86400000;\nvar STAGES = ['idea', 'draft', 'approved', 'scheduled', 'live'];\nvar READY = ['approved', 'scheduled', 'live'];\nvar CHANNELS = ['email', 'instagram', 'facebook', 'linkedin', 'bluesky', 'x', 'tiktok', 'youtube', 'website', 'ads', 'print', 'press', 'event', 'other'];\nvar CHANNEL_ALIASES = {\n newsletter: 'email', mail: 'email', 'e-mail': 'email', twitter: 'x', web: 'website', site: 'website', blog: 'website',\n 'landing page': 'website', ad: 'ads', paid: 'ads', 'paid ads': 'ads', 'google ads': 'ads', 'meta ads': 'ads',\n 'instagram ads': 'ads', 'facebook ads': 'ads', poster: 'print', flyer: 'print', pr: 'press', 'press release': 'press',\n ig: 'instagram', insta: 'instagram', fb: 'facebook',\n};\nvar KINDS = ['post', 'email', 'ad', 'landing-page', 'video', 'graphic', 'print', 'press-release', 'event', 'other'];\nvar WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\nvar MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\nvar STOP = ['the', 'and', 'our', 'for', 'with', 'from', 'this', 'that', 'asset'];\n\nfunction pad(n) {\n return n < 10 ? '0' + n : String(n);\n}\nfunction localDay(ms) {\n var d = new Date(ms);\n return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());\n}\nfunction addDays(day, n) {\n var d = new Date(String(day).slice(0, 10) + 'T12:00:00');\n d.setDate(d.getDate() + n);\n return localDay(d.getTime());\n}\nfunction daysLeft(day, nowMs) {\n var due = Date.parse(String(day).slice(0, 10) + 'T00:00:00');\n var today = Date.parse(localDay(nowMs) + 'T00:00:00');\n return Math.round((due - today) / DAY_MS);\n}\n// YYYY-MM-DD, or today/tomorrow/yesterday, or a weekday ('friday' is the next one, 'last tuesday' the one before).\nfunction normalizeDate(text, nowMs) {\n var raw = String(text || '').trim();\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(raw)) return raw;\n var lower = raw.toLowerCase();\n var today = localDay(nowMs);\n if (lower === 'today') return today;\n if (lower === 'tomorrow') return addDays(today, 1);\n if (lower === 'yesterday') return addDays(today, -1);\n var m = lower.match(/^(next |this |last )?(sunday|monday|tuesday|wednesday|thursday|friday|saturday)$/);\n if (m) {\n var target = WEEKDAYS.map(function (w) { return w.toLowerCase(); }).indexOf(m[2]);\n var dow = new Date(today + 'T12:00:00').getDay();\n if (m[1] === 'last ') return addDays(today, -(((dow - target + 6) % 7) + 1));\n return addDays(today, ((target - dow + 6) % 7) + 1);\n }\n var parsed = Date.parse(raw);\n if (!isFinite(parsed)) return null;\n if (/\\d{4}/.test(raw)) return localDay(parsed);\n // 'Nov 20' parses into some default year: take this year's, or next year's once it is well past.\n var d = new Date(parsed);\n var year = new Date(nowMs).getFullYear();\n var guess = year + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());\n return daysLeft(guess, nowMs) < -60 ? year + 1 + guess.slice(4) : guess;\n}\nfunction monthDay(day) {\n var d = new Date(String(day).slice(0, 10) + 'T12:00:00');\n return MONTHS[d.getMonth()] + ' ' + d.getDate();\n}\nfunction weekday(day) {\n return WEEKDAYS[new Date(String(day).slice(0, 10) + 'T12:00:00').getDay()];\n}\n// A day as a person says it, weekday included so 'how did Tuesday do' finds it:\n// 'yesterday, Tuesday (Nov 3)', 'Tuesday (Oct 27)', 'last Tuesday (Oct 20)', 'Fri Nov 6'.\nfunction dayLabel(day, nowMs) {\n var d = daysLeft(day, nowMs);\n if (d === 0) return 'today, ' + weekday(day) + ' (' + monthDay(day) + ')';\n if (d === -1) return 'yesterday, ' + weekday(day) + ' (' + monthDay(day) + ')';\n if (d === 1) return 'tomorrow, ' + weekday(day) + ' (' + monthDay(day) + ')';\n if (d < -1 && d > -7) return weekday(day) + ' (' + monthDay(day) + ')';\n if (d === -7) return 'last ' + weekday(day) + ' (' + monthDay(day) + ')';\n return weekday(day).slice(0, 3) + ' ' + monthDay(day);\n}\nfunction inDays(d) {\n if (d < 0) return -d + (d === -1 ? ' day ago' : ' days ago');\n if (d === 0) return 'today';\n return 'in ' + d + (d === 1 ? ' day' : ' days');\n}\nfunction toCents(value) {\n if (typeof value === 'number') return isFinite(value) ? Math.round(value * 100) : null;\n var text = String(value == null ? '' : value).replace(/[$,\\s]/g, '').replace(/^usd/i, '');\n if (!/^[-+]?\\d+(\\.\\d+)?$/.test(text)) return null;\n return Math.round(Number(text) * 100);\n}\nfunction money(cents) {\n var abs = Math.abs(Math.round(cents));\n var whole = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\n return (cents < 0 ? '-' : '') + '$' + whole + '.' + pad(abs % 100);\n}\nfunction count(n) {\n return String(Math.round(n || 0)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\n}\nfunction wholeNumber(value) {\n var n = typeof value === 'string' ? Number(String(value).replace(/,/g, '')) : value;\n return typeof n === 'number' && isFinite(n) && n >= 0 ? Math.round(n) : null;\n}\nfunction channelOf(text) {\n var key = String(text || '').trim().toLowerCase();\n if (!key) return null;\n if (CHANNELS.indexOf(key) >= 0) return key;\n return CHANNEL_ALIASES[key] || 'other';\n}\nfunction stem(word) {\n return word.replace(/(ing|ed|es|s|e)$/, '');\n}\nfunction words(text) {\n return (String(text || '').toLowerCase().match(/[a-z0-9]+/g) || []).map(stem).filter(function (w) {\n return w.length > 2 && STOP.indexOf(w) < 0;\n });\n}\n// The record a person means: its id, its exact title, a unique part of its\n// title, or the title sharing the most words with what they wrote.\nfunction findRecord(records, key) {\n var text = String(key || '').trim();\n if (!text) return { record: null, matches: [] };\n var lower = text.toLowerCase();\n var titleOf = function (r) { return String((r.fields && r.fields.title) || '').toLowerCase(); };\n var byId = records.filter(function (r) { return String(r.id).toLowerCase() === lower; });\n if (byId.length) return { record: byId[0], matches: byId };\n var exact = records.filter(function (r) { return titleOf(r) === lower; });\n if (exact.length === 1) return { record: exact[0], matches: exact };\n var partial = records.filter(function (r) { return titleOf(r).indexOf(lower) >= 0; });\n if (partial.length === 1) return { record: partial[0], matches: partial };\n if (partial.length > 1) return { record: null, matches: partial };\n var want = words(text);\n var best = 0;\n var hits = [];\n records.forEach(function (r) {\n var have = words(titleOf(r));\n var score = want.filter(function (w) { return have.indexOf(w) >= 0; }).length;\n if (score > best) { best = score; hits = [r]; } else if (score === best && score > 0) hits.push(r);\n });\n return { record: hits.length === 1 ? hits[0] : null, matches: hits };\n}\n// The newest figures per asset and day: a second report for the same day replaces the first.\nfunction latestResults(events) {\n var byKey = {};\n var order = [];\n events.forEach(function (e) {\n if (e.kind !== 'result' || !e.data || !e.data.day) return;\n var key = (e.data.assetId || '-') + '@' + e.data.day;\n if (!(key in byKey)) order.push(key);\n byKey[key] = e;\n });\n return order.map(function (k) { return byKey[k]; });\n}\nfunction sumResults(list) {\n var t = { reach: 0, clicks: 0, conversions: 0 };\n list.forEach(function (e) {\n t.reach += Number(e.data.reach) || 0;\n t.clicks += Number(e.data.clicks) || 0;\n t.conversions += Number(e.data.conversions) || 0;\n });\n return t;\n}\nfunction spendOf(events) {\n var total = 0;\n var byChannel = {};\n events.forEach(function (e) {\n if (e.kind !== 'spend' || !e.data) return;\n var cents = Number(e.data.amountCents) || 0;\n total += cents;\n var ch = e.data.channel || 'other';\n byChannel[ch] = (byChannel[ch] || 0) + cents;\n });\n return { totalCents: total, byChannel: byChannel };\n}\nfunction figures(t, metric) {\n return count(t.conversions) + ' ' + metric + ', ' + count(t.reach) + ' reach, ' + count(t.clicks) + ' clicks';\n}\nfunction assetLine(r, results, metric, nowMs) {\n var f = r.fields || {};\n var mine = results.filter(function (e) { return e.data.assetId === r.id; });\n return (\n f.title + ' (' + r.id + ', ' + (f.channel || 'other') + ', ' + r.status +\n (f.goesOutAt ? ', ' + dayLabel(f.goesOutAt, nowMs) : ', no date yet') +\n ', owner ' + (f.owner || 'unassigned') + ')' +\n (mine.length ? ': ' + figures(sumResults(mine), metric) : '')\n );\n}\nfunction picture(campaign, records, events, nowMs, withinDays, focusDay) {\n var metric = campaign.goalMetric || 'conversions';\n var results = latestResults(events);\n var totals = sumResults(results);\n var spend = spendOf(events);\n var today = localDay(nowMs);\n var titleOf = function (id) {\n var r = records.find(function (x) { return x.id === id; });\n return r ? r.fields.title + ' (' + id + ')' : id;\n };\n var dayLine = function (day) {\n var list = results.filter(function (e) { return e.data.day === day; });\n if (!list.length) return dayLabel(day, nowMs) + ': no results logged';\n return dayLabel(day, nowMs) + ': ' + figures(sumResults(list), metric) + ' (from ' + list.map(function (e) {\n return titleOf(e.data.assetId) + ' ' + count(e.data.conversions);\n }).join(', ') + ')';\n };\n var parts = [];\n if (focusDay) parts.push('Results on ' + dayLine(focusDay) + '.');\n var launchIn = campaign.launchAt ? daysLeft(campaign.launchAt, nowMs) : null;\n if (!campaign.name && !campaign.goal) {\n parts.push('No campaign set yet: call set_campaign with its name, goal, launch date and budget.');\n } else {\n parts.push(\n (campaign.name || 'The campaign') + (campaign.goal ? '. Goal: ' + campaign.goal : '') + '.' +\n (campaign.audience ? ' Audience: ' + campaign.audience + '.' : '') +\n (campaign.launchAt ? ' Launch ' + dayLabel(campaign.launchAt, nowMs) + ', ' + inDays(launchIn) + '.' : ' No launch date yet.') +\n (campaign.endAt ? ' Runs until ' + dayLabel(campaign.endAt, nowMs) + '.' : ''),\n );\n }\n var target = Number(campaign.goalTarget) || 0;\n parts.push(\n 'Results so far: ' + (target ? count(totals.conversions) + ' of ' + count(target) + ' ' + metric + ' (' + Math.round((totals.conversions / target) * 100) + '%)' : count(totals.conversions) + ' ' + metric) +\n ', ' + count(totals.reach) + ' reach, ' + count(totals.clicks) + ' clicks.',\n );\n var goalBy = campaign.goalBy || campaign.launchAt || campaign.endAt;\n if (target && goalBy) {\n var toGo = target - totals.conversions;\n var daysToGoal = daysLeft(goalBy, nowMs);\n var firstDay = results.map(function (e) { return e.data.day; }).sort()[0];\n var start = campaign.startAt && campaign.startAt <= today ? campaign.startAt : firstDay;\n var elapsed = start ? Math.max(1, -daysLeft(start, nowMs) + 1) : 0;\n if (toGo <= 0) parts.push('Goal met.');\n else if (daysToGoal < 0) parts.push('The goal date passed ' + inDays(daysToGoal) + ' with ' + count(toGo) + ' ' + metric + ' still to go.');\n else {\n var pace = elapsed ? Math.round(totals.conversions / elapsed) : 0;\n var need = Math.ceil(toGo / Math.max(1, daysToGoal));\n parts.push(\n 'Pace: ' + count(totals.conversions) + ' ' + metric + (elapsed ? ' in ' + elapsed + (elapsed === 1 ? ' day' : ' days') + ', about ' + count(pace) + ' a day' : '') +\n '; ' + count(toGo) + ' to go by ' + dayLabel(goalBy, nowMs) + ' needs ' + count(need) + ' a day. ' +\n (pace >= need ? 'On pace.' : 'Behind pace.'),\n );\n }\n }\n var days = [];\n for (var i = 0; i <= 7; i++) days.push(addDays(today, -i));\n var logged = days.filter(function (day) { return results.some(function (e) { return e.data.day === day; }); });\n parts.push(\n logged.length\n ? 'Results by day, last 8 days, newest first: ' + logged.map(dayLine).join(' | ') + '. Other days have no results logged.'\n : 'No results logged in the last 8 days.',\n );\n var byDay = {};\n results.forEach(function (e) { byDay[e.data.day] = (byDay[e.data.day] || 0) + (Number(e.data.conversions) || 0); });\n var bestDay = Object.keys(byDay).sort(function (a, b) { return byDay[b] - byDay[a] || b.localeCompare(a); })[0];\n if (bestDay) parts.push('Best day so far: ' + dayLabel(bestDay, nowMs) + ', ' + count(byDay[bestDay]) + ' ' + metric + '.');\n var budget = Number(campaign.budgetCents) || 0;\n var channels = Object.keys(spend.byChannel).sort(function (a, b) { return spend.byChannel[b] - spend.byChannel[a]; });\n parts.push(\n (budget\n ? 'Budget ' + money(budget) + ': spent ' + money(spend.totalCents) + ' (' + Math.round((spend.totalCents / budget) * 100) + '%), ' +\n (budget - spend.totalCents >= 0 ? money(budget - spend.totalCents) + ' left.' : money(spend.totalCents - budget) + ' over.')\n : 'No budget set; spent ' + money(spend.totalCents) + '.') +\n (channels.length ? ' Spent by channel: ' + channels.map(function (c) { return c + ' ' + money(spend.byChannel[c]); }).join(', ') + '.' : ''),\n );\n var dated = records.filter(function (r) { return r.fields && r.fields.goesOutAt; });\n var overdue = dated.filter(function (r) { return r.status !== 'live' && daysLeft(r.fields.goesOutAt, nowMs) < 0; });\n var upcoming = dated.filter(function (r) {\n var d = daysLeft(r.fields.goesOutAt, nowMs);\n return d >= 0 && d <= withinDays;\n });\n var byDate = function (a, b) { return String(a.fields.goesOutAt).localeCompare(String(b.fields.goesOutAt)); };\n overdue.sort(byDate);\n upcoming.sort(byDate);\n // One list, late items first: a question about the coming days must see what slipped.\n var calendar = overdue.concat(upcoming);\n parts.push(\n calendar.length\n ? 'Calendar, next ' + withinDays + ' days, late items first: ' + calendar.map(function (r) {\n var d = daysLeft(r.fields.goesOutAt, nowMs);\n return assetLine(r, [], metric, nowMs) + (d < 0 && r.status !== 'live' ? ', ' + -d + (d === -1 ? ' day late' : ' days late') : '');\n }).join(' | ') + '.'\n : 'Nothing on the calendar in the next ' + withinDays + ' days.',\n );\n var later = dated.filter(function (r) { return daysLeft(r.fields.goesOutAt, nowMs) > withinDays; }).sort(byDate);\n if (later.length) parts.push('Next after that: ' + later[0].fields.title + ' (' + later[0].id + ') on ' + dayLabel(later[0].fields.goesOutAt, nowMs) + '.');\n var undated = records.filter(function (r) { return !r.fields || !r.fields.goesOutAt; });\n if (undated.length) parts.push('Not dated yet: ' + undated.map(function (r) { return r.fields.title + ' (' + r.id + ', ' + r.status + ')'; }).join(', ') + '.');\n var stageCounts = STAGES.map(function (s) {\n var n = records.filter(function (r) { return r.status === s; }).length;\n return n ? n + ' ' + s : '';\n }).filter(Boolean);\n parts.push(records.length ? 'Assets: ' + records.length + ' (' + stageCounts.join(', ') + ').' : 'No assets yet.');\n return {\n daysToLaunch: launchIn === null ? 0 : launchIn,\n ready: records.filter(function (r) { return READY.indexOf(r.status) >= 0; }).length,\n spentCents: spend.totalCents,\n conversions: totals.conversions,\n summary: parts.join(' '),\n };\n}\n// ── campaign-rules-end ──\n\ninterface Campaign {\n version: number;\n name: string;\n goal: string;\n audience: string;\n goalMetric: string;\n goalTarget: number;\n goalBy: string;\n launchAt: string;\n startAt: string;\n endAt: string;\n budgetCents: number;\n updatedAt?: string;\n}\n\nconst CAMPAIGN_FILE = 'campaign.json';\nconst assets = rosterStore(gezel.fs, 'assets.json', {\n stages: ['idea', 'draft', 'approved', 'scheduled', 'live'],\n idPrefix: 'as',\n});\nconst results = logStore(gezel.fs, 'results.json');\n\nasync function loadCampaign(): Promise<Campaign> {\n const blank: Campaign = {\n version: 1,\n name: '',\n goal: '',\n audience: '',\n goalMetric: '',\n goalTarget: 0,\n goalBy: '',\n launchAt: '',\n startAt: '',\n endAt: '',\n budgetCents: 0,\n };\n let raw: string;\n try {\n raw = await gezel.fs.read(CAMPAIGN_FILE);\n } catch {\n return blank;\n }\n let parsed: Partial<Campaign>;\n try {\n parsed = JSON.parse(raw) as Partial<Campaign>;\n } catch {\n throw new Error('campaign.json is not valid JSON. Fix or remove it; it will not be overwritten.');\n }\n return {\n ...blank,\n ...parsed,\n version: 1,\n goalTarget: Number(parsed.goalTarget) || 0,\n budgetCents: Number(parsed.budgetCents) || 0,\n };\n}\n\nasync function saveCampaign(campaign: Campaign): Promise<void> {\n campaign.updatedAt = new Date().toISOString();\n await gezel.fs.write(CAMPAIGN_FILE, `${JSON.stringify(campaign, null, 2)}\\n`);\n}\n\nasync function resolve() {\n const all = await assets.list();\n const keys = [input.id, input.title].filter((k): k is string => typeof k === 'string' && k.trim() !== '');\n for (const key of keys) {\n const found = findRecord(all, key);\n if (found.record) return found.record;\n if (found.matches.length > 1) {\n throw new Error(\n \"More than one asset matches '\" + key + \"': \" + found.matches.map((r) => r.id + ' ' + String(r.fields.title)).join(', ') + '. Pass id.',\n );\n }\n }\n const known = all.map((r) => r.id + ' ' + String(r.fields.title)).join(', ') || 'none yet';\n throw new Error(\n (keys.length ? \"No asset matches '\" + keys.join(\"' or '\") + \"'. \" : \"Pass 'id' (e.g. 'as-3') or the asset's 'title'. \") + 'Assets: ' + known + '.',\n );\n}\n\nfunction dateInput(value: string | undefined, label: string): string | null {\n if (value === undefined || String(value).trim() === '') return null;\n const day = normalizeDate(value, Date.now());\n if (!day) throw new Error(label + \" must be a date, e.g. '2026-12-01'.\");\n return day;\n}\n\nconst now = Date.now();\nconst today = localDay(now);\nconst withinDays = typeof input.withinDays === 'number' && input.withinDays > 0 ? Math.round(input.withinDays) : 14;\nlet note = '';\nlet focusDay: string | null = null;\n\nif (input.action === 'set_campaign') {\n const campaign = await loadCampaign();\n const changed: string[] = [];\n for (const key of ['name', 'goal', 'audience', 'goalMetric'] as const) {\n const value = input[key];\n if (typeof value === 'string' && value.trim()) {\n campaign[key] = value.trim();\n changed.push(key === 'goalMetric' ? 'what the goal counts' : key);\n }\n }\n for (const [key, label] of [\n ['launchAt', 'launch date'],\n ['startAt', 'start date'],\n ['endAt', 'end date'],\n ['goalBy', 'goal date'],\n ] as const) {\n const day = dateInput(input[key], key);\n if (day) {\n campaign[key] = day;\n changed.push(label);\n }\n }\n if (input.goalTarget !== undefined) {\n const target = wholeNumber(input.goalTarget);\n if (target === null) throw new Error('goalTarget must be a whole number, e.g. 600.');\n campaign.goalTarget = target;\n changed.push('goal number');\n }\n if (input.budget !== undefined) {\n const cents = toCents(input.budget);\n if (cents === null || cents < 0) throw new Error('budget must be an amount in dollars, e.g. 2400.');\n campaign.budgetCents = cents;\n changed.push('budget (' + money(cents) + ')');\n }\n if (input.budgetChange !== undefined) {\n const cents = toCents(input.budgetChange);\n if (cents === null || cents === 0) throw new Error('budgetChange must be dollars to add, e.g. 500 (or -200 to cut).');\n const before = campaign.budgetCents;\n campaign.budgetCents = Math.max(0, before + cents);\n changed.push('budget ' + (cents > 0 ? 'raised by ' + money(cents) : 'cut by ' + money(-cents)) + ' from ' + money(before) + ' to ' + money(campaign.budgetCents));\n }\n if (!changed.length) {\n throw new Error('set_campaign needs at least one of name, goal, audience, goalMetric, goalTarget, launchAt, startAt, endAt, goalBy, budget, or budgetChange.');\n }\n await saveCampaign(campaign);\n note = 'Campaign updated: ' + changed.join(', ') + '.';\n} else if (input.action === 'add_asset') {\n if (!input.title || !input.title.trim()) throw new Error(\"add_asset needs 'title'.\");\n const goesOutAt = dateInput(input.goesOutAt, 'goesOutAt');\n const channel = channelOf(input.channel);\n const kind = KINDS.includes(String(input.kind)) ? String(input.kind) : undefined;\n const status = input.status ? String(input.status).toLowerCase() : undefined;\n if (status && !STAGES.includes(status)) throw new Error(\"status must be one of idea, draft, approved, scheduled, live.\");\n const wanted = input.title.trim().toLowerCase();\n const existing = (await assets.list()).find((r) => String(r.fields.title ?? '').toLowerCase() === wanted);\n const fields: Record<string, unknown> = {\n ...(goesOutAt ? { goesOutAt } : {}),\n ...(channel ? { channel } : {}),\n ...(kind ? { kind } : {}),\n ...(input.owner ? { owner: input.owner.trim() } : {}),\n ...(input.note ? { notes: input.note.trim() } : {}),\n };\n if (existing) {\n await assets.update(existing.id, { fields });\n if (status && status !== existing.status) await assets.transition(existing.id, status, { note: 'Updated from the plan' });\n note = 'Updated ' + String(existing.fields.title) + ' (' + existing.id + ').';\n } else {\n const record = await assets.add({\n status: status ?? 'idea',\n fields: { title: input.title.trim(), channel: channel ?? 'other', kind: kind ?? 'post', ...fields },\n });\n note = 'Added ' + record.id + ' ' + String(record.fields.title) + (goesOutAt ? ' on ' + dayLabel(goesOutAt, now) : '') + '.';\n }\n} else if (input.action === 'move_asset') {\n const record = await resolve();\n const fields: Record<string, unknown> = {};\n const goesOutAt = dateInput(input.goesOutAt, 'goesOutAt');\n if (goesOutAt) fields.goesOutAt = goesOutAt;\n if (typeof input.shiftDays === 'number' && input.shiftDays !== 0) {\n const from = goesOutAt ?? (typeof record.fields.goesOutAt === 'string' ? record.fields.goesOutAt : null);\n if (!from) throw new Error(String(record.fields.title) + \" has no date yet; pass goesOutAt instead of shiftDays.\");\n fields.goesOutAt = addDays(from, Math.round(input.shiftDays));\n }\n if (input.owner) fields.owner = input.owner.trim();\n if (input.channel) fields.channel = channelOf(input.channel);\n const status = input.status ? String(input.status).toLowerCase() : undefined;\n if (status && !STAGES.includes(status)) throw new Error(\"status must be one of idea, draft, approved, scheduled, live.\");\n if (!Object.keys(fields).length && !status && !input.note) {\n throw new Error('move_asset needs status, goesOutAt, shiftDays, owner, channel, or note.');\n }\n if (Object.keys(fields).length) await assets.update(record.id, { fields });\n if (status && status !== record.status) await assets.transition(record.id, status, input.note ? { note: input.note } : {});\n else if (input.note) await assets.update(record.id, { note: input.note });\n note =\n String(record.fields.title) + ' (' + record.id + ')' +\n (status && status !== record.status ? ' moved from ' + record.status + ' to ' + status : ' updated') +\n (fields.goesOutAt ? ', now going out ' + dayLabel(String(fields.goesOutAt), now) : '') +\n (fields.owner ? ', owner ' + String(fields.owner) : '') + '.';\n} else if (input.action === 'log_result') {\n const record = await resolve();\n const day = dateInput(input.day, 'day') ?? today;\n const given: Record<string, number> = {};\n for (const key of ['reach', 'clicks', 'conversions'] as const) {\n if (input[key] === undefined) continue;\n const n = wholeNumber(input[key]);\n if (n === null) throw new Error(key + ' must be a whole number of 0 or more.');\n given[key] = n;\n }\n if (!Object.keys(given).length) throw new Error('log_result needs at least one of reach, clicks, or conversions.');\n const prior = latestResults(await results.list({ kind: 'result' })).find((e) => e.data.assetId === record.id && e.data.day === day);\n const data = { ...(prior ? prior.data : {}), assetId: record.id, day, channel: record.fields.channel ?? 'other', ...given };\n await results.append({ kind: 'result', note: input.note ?? 'Results for ' + String(record.fields.title) + '.', data });\n if (record.status !== 'live') await assets.transition(record.id, 'live', { note: 'Results logged' });\n const campaign = await loadCampaign();\n note =\n 'Logged ' + dayLabel(day, now) + ' for ' + String(record.fields.title) + ' (' + record.id + '): ' +\n figures({ reach: Number(data.reach) || 0, clicks: Number(data.clicks) || 0, conversions: Number(data.conversions) || 0 }, campaign.goalMetric || 'conversions') +\n (prior ? ', replacing the earlier figures for that day' : '') + '.';\n focusDay = day;\n} else if (input.action === 'log_spend') {\n const cents = toCents(input.amount);\n if (cents === null || cents <= 0) throw new Error('log_spend needs amount in dollars, e.g. 250.');\n const record = input.id || input.title ? await resolve() : null;\n const channel = channelOf(input.channel) ?? (record ? String(record.fields.channel ?? 'other') : 'other');\n const day = dateInput(input.day, 'day') ?? today;\n await results.append({\n kind: 'spend',\n note: input.note ?? 'Spent ' + money(cents) + ' on ' + channel + '.',\n data: { day, channel, amountCents: cents, ...(record ? { assetId: record.id } : {}) },\n });\n note = 'Logged ' + money(cents) + ' spent on ' + channel + (record ? ' for ' + String(record.fields.title) : '') + ' ' + dayLabel(day, now) + '.';\n} else if (input.action === 'status') {\n if (input.day) focusDay = dateInput(input.day, 'day');\n} else if (input.action !== 'list') {\n throw new Error(\n \"Unknown action '\" + input.action + \"'. Use status, set_campaign, add_asset, move_asset, log_result, log_spend, or list.\",\n );\n}\n\nconst campaign = await loadCampaign();\nconst records = await assets.list();\nconst events = await results.list();\nconst view = picture(campaign, records, events, now, withinDays, focusDay);\nconst latest = latestResults(events);\nconst metric = campaign.goalMetric || 'conversions';\n\ngezel.output({\n daysToLaunch: view.daysToLaunch,\n assets: records.length,\n ready: view.ready,\n budget: campaign.budgetCents / 100,\n spent: view.spentCents / 100,\n conversions: view.conversions,\n summary:\n input.action === 'list'\n ? records\n .slice()\n .sort((a, b) => String(a.fields.goesOutAt ?? '9999').localeCompare(String(b.fields.goesOutAt ?? '9999')))\n .map((r) => assetLine(r, latest, metric, now))\n .join('\\n') || 'No assets yet.'\n : (note ? note + ' ' : '') + view.summary,\n});\n"},"tools":[{"name":"campaign_status","description":"The whole campaign: the goal and the pace toward it, results by day for the last 8 days with each asset's numbers, the budget against spend by channel, and the calendar for the next 14 days (late items first) with ids, owners and stages. Call it first when asked how the campaign or a day is doing, what is going out, or what is left to spend.","script":"campaign-store","inputs":{"type":"object","properties":{"day":{"type":"string"},"withinDays":{"type":"number"}}},"bind":{"action":"status"},"state":true},{"name":"set_campaign","description":"Save the campaign itself: name, goal, audience, what the goal counts and the number to reach, launch, start and end dates (YYYY-MM-DD), and the budget in dollars. For more or less money pass budgetChange (500 adds $500) and the campaign does the sum; pass budget only to replace the whole budget. Call it as soon as any of these is mentioned, before you describe it.","script":"campaign-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"goal":{"type":"string"},"audience":{"type":"string"},"goalMetric":{"type":"string"},"goalTarget":{"type":"number"},"goalBy":{"type":"string"},"launchAt":{"type":"string"},"startAt":{"type":"string"},"endAt":{"type":"string"},"budget":{"type":"number"},"budgetChange":{"type":"number"}}},"bind":{"action":"set_campaign"}},{"name":"add_asset","description":"Put an asset on the campaign calendar: title, channel, the day it goes out (YYYY-MM-DD), owner and stage. An existing title is updated, never duplicated. When planning several, call it once per asset, as soon as each is decided and before you describe the plan.","script":"campaign-store","inputs":{"type":"object","properties":{"title":{"type":"string"},"channel":{"type":"string","enum":["email","instagram","facebook","linkedin","bluesky","x","tiktok","youtube","website","ads","print","press","event","other"]},"kind":{"type":"string","enum":["post","email","ad","landing-page","video","graphic","print","press-release","event","other"]},"goesOutAt":{"type":"string"},"owner":{"type":"string"},"status":{"type":"string","enum":["idea","draft","approved","scheduled","live"]},"note":{"type":"string"}},"required":["title"]},"bind":{"action":"add_asset"}},{"name":"move_asset","description":"Move an asset to another stage (idea, draft, approved, scheduled, live), or give it a new date or owner. To push it later or earlier pass shiftDays and the campaign does the date math. Call it the moment the person says an asset moved.","script":"campaign-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"status":{"type":"string","enum":["idea","draft","approved","scheduled","live"]},"goesOutAt":{"type":"string"},"shiftDays":{"type":"number"},"owner":{"type":"string"},"note":{"type":"string"}}},"bind":{"action":"move_asset"}},{"name":"log_result","description":"Record an asset's numbers for a day: reach (opens, views or impressions), clicks, and conversions (what the goal counts, such as preorders). day defaults to today. A second report for the same asset and day replaces the first. Call it as soon as the person shares numbers, before you comment on them.","script":"campaign-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"day":{"type":"string"},"reach":{"type":"number"},"clicks":{"type":"number"},"conversions":{"type":"number"},"note":{"type":"string"}}},"bind":{"action":"log_result"}},{"name":"log_spend","description":"Record money spent, in dollars, on a channel (and an asset when one is named). Each call adds to what was spent; never pass a running total. Call it as soon as the person mentions spending, before you comment on the budget.","script":"campaign-store","inputs":{"type":"object","properties":{"amount":{"type":"number"},"channel":{"type":"string","enum":["email","instagram","facebook","linkedin","bluesky","x","tiktok","youtube","website","ads","print","press","event","other"]},"id":{"type":"string"},"title":{"type":"string"},"day":{"type":"string"},"note":{"type":"string"}},"required":["amount"]},"bind":{"action":"log_spend"}},{"name":"list_assets","description":"Every asset with its channel, date, stage, owner and results.","script":"campaign-store","inputs":{"type":"object","properties":{}},"bind":{"action":"list"}},{"name":"page_set_campaign","description":"Save the campaign details.","script":"campaign-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"goal":{"type":"string"},"audience":{"type":"string"},"goalMetric":{"type":"string"},"goalTarget":{"type":"number"},"goalBy":{"type":"string"},"launchAt":{"type":"string"},"startAt":{"type":"string"},"endAt":{"type":"string"},"budget":{"type":"number"},"budgetChange":{"type":"number"}}},"bind":{"action":"set_campaign"}},{"name":"page_add_asset","description":"Add or update an asset.","script":"campaign-store","inputs":{"type":"object","properties":{"title":{"type":"string"},"channel":{"type":"string","enum":["email","instagram","facebook","linkedin","bluesky","x","tiktok","youtube","website","ads","print","press","event","other"]},"kind":{"type":"string","enum":["post","email","ad","landing-page","video","graphic","print","press-release","event","other"]},"goesOutAt":{"type":"string"},"owner":{"type":"string"},"status":{"type":"string","enum":["idea","draft","approved","scheduled","live"]},"note":{"type":"string"}},"required":["title"]},"bind":{"action":"add_asset"}},{"name":"page_move_asset","description":"Move an asset to another stage or date.","script":"campaign-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"status":{"type":"string","enum":["idea","draft","approved","scheduled","live"]},"goesOutAt":{"type":"string"},"shiftDays":{"type":"number"},"owner":{"type":"string"},"note":{"type":"string"}}},"bind":{"action":"move_asset"},"reaction":{"gezel":"campaign-manager","prompt":"The person just moved an asset on the campaign page. The campaign now reads (its first sentence is what changed):\n{{output.summary}}\nIn two short sentences, confirm the move and name the next asset on the calendar that still needs work, or anything that is late. Do not call tools.","hideSeed":true}},{"name":"page_log_result","description":"Record an asset's numbers for a day.","script":"campaign-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"day":{"type":"string"},"reach":{"type":"number"},"clicks":{"type":"number"},"conversions":{"type":"number"},"note":{"type":"string"}}},"bind":{"action":"log_result"}},{"name":"page_log_spend","description":"Record money spent.","script":"campaign-store","inputs":{"type":"object","properties":{"amount":{"type":"number"},"channel":{"type":"string","enum":["email","instagram","facebook","linkedin","bluesky","x","tiktok","youtube","website","ads","print","press","event","other"]},"id":{"type":"string"},"title":{"type":"string"},"day":{"type":"string"},"note":{"type":"string"}},"required":["amount"]},"bind":{"action":"log_spend"}}],"pages":{"entry":"campaign/index.html","api":1,"reads":[{"source":"workspace","path":"campaign.json"},{"source":"workspace","path":"assets.json"},{"source":"workspace","path":"results.json"}],"tools":["page_set_campaign","page_add_asset","page_move_asset","page_log_result","page_log_spend"]},"schedules":[],"workspaceSeed":["campaign.json","assets.json","results.json"],"artifactsSeed":[],"availableVersions":["1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"caregiving-binder","name":"Caregiving Binder","description":"Coordinate a loved one's care without losing the thread. A discreet care coordinator keeps meds, appointments, and the day-to-day journal — and preps every doctor visit from the record.","tags":["caregiving","health","family","medications","appointments"],"category":"home","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.1.4","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"person":{"type":"string","title":"Who is the care for?","description":"A first name is enough — e.g. 'Mom', 'Jan'.","default":"Mom"}},"required":["person"]},"nameTemplate":"Caregiving Binder","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"zorgcoordinator","voorman":true}],"toolsets":[],"craftbooks":["visit-prep"],"scripts":{"care-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { logStore, rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'care-store',\n description:\n \"Read and update the care record: medications (meds.json) and the care journal (care.json). Call action:'status' for active meds + upcoming appointments; 'add_med' / 'stop_med' on changes; 'log_entry' for journal notes and symptoms; 'log_appointment' with when (ISO); 'visit_prep' before a doctor visit.\",\n inputs: {\n action: {\n type: 'string',\n description:\n \"One of 'status', 'add_med', 'stop_med', 'log_entry', 'log_appointment', or 'visit_prep'.\",\n required: true,\n },\n name: { type: 'string', description: 'Medication name.' },\n dose: { type: 'string', description: \"Dose and schedule, e.g. '10mg mornings'.\" },\n prescriber: { type: 'string', description: 'Who prescribed it.' },\n id: { type: 'string', description: \"Medication id, e.g. 'med-2'.\" },\n kind: { type: 'string', description: \"Journal kind: 'note', 'symptom', or 'update'.\" },\n note: { type: 'string', description: 'The journal entry or appointment description.' },\n when: { type: 'string', description: 'Appointment time (ISO), e.g. 2026-08-02T14:00.' },\n },\n outputs: {\n meds: { type: 'number', description: 'Active medications.' },\n upcoming: { type: 'number', description: 'Upcoming appointments.' },\n summary: { type: 'string', description: 'The care picture (or the visit prep).' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── care-rules-start ──\n// Pure derivations: upcoming appointments (journal events kind\n// 'appointment' with data.whenAt in the future) and the since-last-visit\n// window for visit prep.\n\n// A date with no time (\"2026-11-14\") is an appointment some time that day, so\n// it stays upcoming until the day ends here; parsed as UTC midnight, it left\n// the list the evening before anywhere west of Greenwich.\nfunction appointmentEndMs(whenAt) {\n return /^\\d{4}-\\d{2}-\\d{2}$/.test(whenAt) ? Date.parse(whenAt + 'T23:59:59') : Date.parse(whenAt);\n}\n\nfunction upcomingAppointments(events, nowMs) {\n return events\n .filter(function (e) {\n var when = e.data && typeof e.data.whenAt === 'string' ? appointmentEndMs(e.data.whenAt) : NaN;\n return e.kind === 'appointment' && isFinite(when) && when >= nowMs;\n })\n .sort(function (a, b) {\n return Date.parse(a.data.whenAt) - Date.parse(b.data.whenAt);\n });\n}\n\nfunction lastVisitMs(events, nowMs) {\n var past = events.filter(function (e) {\n var when = e.data && typeof e.data.whenAt === 'string' ? appointmentEndMs(e.data.whenAt) : NaN;\n return e.kind === 'appointment' && isFinite(when) && when < nowMs;\n });\n if (past.length === 0) return null;\n return Math.max.apply(\n null,\n past.map(function (e) {\n return Date.parse(e.data.whenAt);\n }),\n );\n}\n\nfunction sinceWindow(events, nowMs) {\n var last = lastVisitMs(events, nowMs);\n return events.filter(function (e) {\n return e.kind !== 'appointment' && (last === null || Date.parse(e.at) > last);\n });\n}\n// ── care-rules-end ──\n\nconst meds = rosterStore(gezel.fs, 'meds.json', {\n stages: ['active', 'stopped'],\n idPrefix: 'med',\n});\nconst journal = logStore(gezel.fs, 'care.json');\n\nasync function resolveMed(): Promise<string> {\n if (input.id) return input.id;\n if (input.name) {\n const wanted = input.name.toLowerCase();\n const matches = (await meds.list({ status: 'active' })).filter(\n (r) => String(r.fields.name ?? '').toLowerCase() === wanted,\n );\n if (matches.length === 1) return matches[0]!.id;\n }\n throw new Error(\"Pass 'id' (e.g. 'med-2') or an exact active medication 'name'.\");\n}\n\nif (input.action === 'add_med') {\n if (!input.name || !input.dose) throw new Error(\"add_med needs 'name' and 'dose'.\");\n await meds.add({\n status: 'active',\n fields: {\n name: input.name,\n dose: input.dose,\n ...(input.prescriber ? { prescriber: input.prescriber } : {}),\n },\n });\n await journal.append({ kind: 'update', note: `Started ${input.name} (${input.dose}).` });\n} else if (input.action === 'stop_med') {\n const id = await resolveMed();\n const med = await meds.get(id);\n await meds.transition(id, 'stopped', input.note ? { note: input.note } : {});\n await journal.append({\n kind: 'update',\n note: `Stopped ${String(med?.fields.name ?? id)}${input.note ? ` — ${input.note}` : ''}.`,\n });\n} else if (input.action === 'log_entry') {\n if (!input.note) throw new Error(\"log_entry needs 'note'.\");\n const kind = input.kind === 'symptom' || input.kind === 'update' ? input.kind : 'note';\n await journal.append({ kind, note: input.note });\n} else if (input.action === 'log_appointment') {\n if (!input.note || !input.when) throw new Error(\"log_appointment needs 'note' and 'when' (ISO).\");\n await journal.append({ kind: 'appointment', note: input.note, data: { whenAt: input.when } });\n} else if (input.action !== 'status' && input.action !== 'visit_prep') {\n throw new Error(\n `Unknown action '${input.action}'. Use status, add_med, stop_med, log_entry, log_appointment, or visit_prep.`,\n );\n}\n\nconst activeMeds = await meds.list({ status: 'active' });\nconst events = await journal.list();\nconst nowMs = Date.now();\nconst upcoming = upcomingAppointments(events, nowMs);\n\nlet summary: string;\nif (input.action === 'visit_prep') {\n const since = sinceWindow(events, nowMs);\n const medLines = activeMeds\n .map((m) => `- ${String(m.fields.name)} ${String(m.fields.dose ?? '')}`.trim())\n .join('\\n');\n const noteLines = since\n .map((e) => `- [${e.kind}] ${String(e.at).slice(0, 10)}: ${e.note ?? ''}`)\n .join('\\n');\n summary = `VISIT PREP\\nActive medications:\\n${medLines || '- none recorded'}\\nSince the last visit:\\n${noteLines || '- quiet — nothing logged'}\\nUpcoming:\\n${upcoming.map((e) => `- ${String(e.data?.whenAt).slice(0, 16)} ${e.note ?? ''}`).join('\\n') || '- none scheduled'}`;\n} else {\n const next = upcoming[0];\n summary = `${activeMeds.length} active medication(s). ${upcoming.length} upcoming appointment(s)${\n next ? ` — next: ${String(next.data?.whenAt).slice(0, 16)} ${next.note ?? ''}` : ''\n }. ${events.filter((e) => e.kind !== 'appointment').length} journal entr(ies).`;\n}\n\ngezel.output({\n meds: activeMeds.length,\n upcoming: upcoming.length,\n summary,\n});\n"},"tools":[{"name":"add_med","description":"Record a medication (name, dose/schedule, prescriber).","script":"care-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"dose":{"type":"string"},"prescriber":{"type":"string"}},"required":["name","dose"]},"bind":{"action":"add_med"}},{"name":"stop_med","description":"Mark a medication stopped (with why, when known).","script":"care-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"note":{"type":"string"}}},"bind":{"action":"stop_med"}},{"name":"log_entry","description":"Add a journal entry — a note, a symptom observation, an update.","script":"care-store","inputs":{"type":"object","properties":{"kind":{"type":"string","enum":["note","symptom","update"]},"note":{"type":"string"}},"required":["note"]},"bind":{"action":"log_entry"}},{"name":"log_appointment","description":"Record an appointment (what and when, ISO).","script":"care-store","inputs":{"type":"object","properties":{"note":{"type":"string"},"when":{"type":"string"}},"required":["note","when"]},"bind":{"action":"log_appointment"}},{"name":"care_status","description":"Active meds, upcoming appointments, journal count.","script":"care-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"}},{"name":"visit_prep","description":"The one-page brief for the next doctor visit: meds + what happened since the last one.","script":"care-store","inputs":{"type":"object","properties":{}},"bind":{"action":"visit_prep"}},{"name":"page_log_entry","description":"Add a journal entry — a note, a symptom observation, an update.","script":"care-store","inputs":{"type":"object","properties":{"kind":{"type":"string","enum":["note","symptom","update"]},"note":{"type":"string"}},"required":["note"]},"bind":{"action":"log_entry"}},{"name":"page_log_appointment","description":"Record an appointment (what and when, ISO).","script":"care-store","inputs":{"type":"object","properties":{"note":{"type":"string"},"when":{"type":"string"}},"required":["note","when"]},"bind":{"action":"log_appointment"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"meds.json"},{"source":"workspace","path":"care.json"}],"tools":["page_log_entry","page_log_appointment"]},"schedules":[],"workspaceSeed":["meds.json","care.json"],"artifactsSeed":[],"availableVersions":["1.1.4","1.1.3","1.1.2","1.1.1","1.1.0","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"cash-flow-planner","name":"Cash Flow Planner","description":"See the cash coming in and going out, weeks ahead. A bookkeeper keeps a 13-week forecast from the invoices and bills you expect, warns you about the first week cash dips below your cushion, and tries what-ifs such as a late payer or a new hire without touching the plan.","tags":["cash-flow","forecast","runway","what-if","small-business"],"category":"money","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.0.0","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"business":{"type":"string","title":"What kind of business is this?","description":"e.g. 'a three-person electrical contractor', 'a design studio'.","default":"the business"},"currency":{"type":"string","title":"Which currency is the cash in?","description":"A three-letter code, e.g. USD, EUR or GBP.","default":"USD"}},"required":["business","currency"]},"nameTemplate":"Cash Flow Planner","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"bookkeeper","voorman":true}],"toolsets":[],"craftbooks":[],"scripts":{"cashflow-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'cashflow-store',\n description:\n \"Read and update the cash plan (cashflow.json): the bank balance, the money the business expects in and out, and what-if scenarios. action:'status' for the 13-week forecast and its warning week; 'set_balance' for the cash in the bank (and the cushion to keep); 'add' to save an expected invoice or bill (an existing name is updated, never duplicated); 'settle' when one arrived or was paid; 'remove' to take one out of the plan; 'what_if' to try a scenario without changing the plan; 'list' for every item.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'status', 'set_balance', 'add', 'settle', 'remove', 'what_if', or 'list'.\",\n required: true,\n },\n item: {\n type: 'string',\n description: \"An expected item's id (e.g. 'cf-3') or name, for settle, remove, and a what-if delay or drop.\",\n },\n name: { type: 'string', description: \"An item's name, e.g. 'Hollis Bakery invoice' or 'Payroll'.\" },\n direction: { type: 'string', description: 'in for money coming in, out for a bill or cost.' },\n amount: {\n type: 'number',\n description: 'Amount in ordinary units, e.g. 9600. For set_balance it may be 0 or negative.',\n },\n date: {\n type: 'string',\n description: 'YYYY-MM-DD: when it is expected (the first date, for a repeat); for set_balance, the day of the balance; for settle, the day it happened (default today).',\n },\n recurs: { type: 'string', description: 'none, weekly, biweekly, monthly, quarterly.' },\n until: { type: 'string', description: 'The last date a repeat runs, YYYY-MM-DD.' },\n cushion: { type: 'number', description: 'Cash to keep on hand, in ordinary units, e.g. 12000.' },\n scenario: { type: 'string', description: \"A what-if's name, e.g. 'Hire an apprentice'.\" },\n change: { type: 'string', description: 'For what_if: delay, drop, add, or clear.' },\n weeks: { type: 'number', description: 'For a what-if delay: how many weeks later (a month late is 4).' },\n note: { type: 'string', description: 'A short note, with any reference number exactly as written.' },\n },\n outputs: {\n balance: { type: 'number', description: 'Cash in the bank, in ordinary units like amount.' },\n lowestBalance: { type: 'number', description: 'The lowest week-end balance in the forecast, in ordinary units.' },\n lowWeek: { type: 'string', description: 'The Monday of the tightest week, YYYY-MM-DD.' },\n belowCushion: { type: 'number', description: 'Weeks that end below the cushion.' },\n endBalance: { type: 'number', description: 'The balance after 13 weeks, in ordinary units.' },\n summary: { type: 'string', description: 'What changed, then the forecast; or the listing.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── cashflow-rules-start ──\n// Pure derivations shared by the script, the page and the sample conversation:\n// integer-cent money, repeat dates, and the 13-week forecast with its tightest\n// week, for the plan and for each what-if. Kept self-contained between these\n// sentinels so unit tests execute the shipped bytes.\nvar DAY_MS = 86400000;\nvar WEEKS = 13;\nvar RECURS = ['none', 'weekly', 'biweekly', 'monthly', 'quarterly'];\nvar RECURS_TEXT = { none: 'once', weekly: 'every week', biweekly: 'every two weeks', monthly: 'every month', quarterly: 'every quarter' };\nvar SHORT_MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n\nfunction pad(n) {\n return n < 10 ? '0' + n : String(n);\n}\nfunction localDay(ms) {\n var d = new Date(ms);\n return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());\n}\nfunction normalizeDate(text) {\n var raw = String(text || '').trim();\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(raw)) return raw;\n var parsed = Date.parse(raw);\n return isFinite(parsed) ? localDay(parsed) : null;\n}\n// Local noon, so adding days never trips over a daylight-saving change.\nfunction dayMs(day) {\n return Date.parse(String(day).slice(0, 10) + 'T12:00:00');\n}\nfunction addDays(day, n) {\n var d = new Date(dayMs(day));\n d.setDate(d.getDate() + n);\n return localDay(d.getTime());\n}\n// The same day of the month `months` later; the 31st lands on a shorter month's last day.\nfunction addMonths(day, months, dom) {\n var d = new Date(dayMs(day));\n var date = dom || d.getDate();\n d.setDate(1);\n d.setMonth(d.getMonth() + months);\n d.setDate(Math.min(date, new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate()));\n return localDay(d.getTime());\n}\n// The k-th date of a series counted from its anchor, so a monthly 31st never drifts.\nfunction occurrence(anchor, recurs, k, dom) {\n if (recurs === 'weekly') return addDays(anchor, 7 * k);\n if (recurs === 'biweekly') return addDays(anchor, 14 * k);\n if (recurs === 'monthly') return addMonths(anchor, k, dom);\n if (recurs === 'quarterly') return addMonths(anchor, 3 * k, dom);\n return k === 0 ? anchor : null;\n}\nfunction daysBetween(from, to) {\n return Math.round((dayMs(to) - dayMs(from)) / DAY_MS);\n}\nfunction mondayOf(day) {\n return addDays(day, -((new Date(dayMs(day)).getDay() + 6) % 7));\n}\nfunction weekLabel(day) {\n return SHORT_MONTHS[Number(day.slice(5, 7)) - 1] + ' ' + Number(day.slice(8, 10));\n}\n// Integer cents from 9600, '9,600.00' or '-1240', with no float arithmetic.\nfunction parseCents(value) {\n var text = typeof value === 'number' ? (isFinite(value) ? String(value) : '') : String(value == null ? '' : value);\n var m = /^(-?)(\\d+)(?:\\.(\\d*))?$/.exec(text.replace(/[$,\\s]/g, ''));\n if (!m) return null;\n var frac = (m[3] || '') + '000';\n var cents = Number(m[2]) * 100 + Number(frac.slice(0, 2)) + (Number(frac.charAt(2)) >= 5 ? 1 : 0);\n return m[1] ? -cents : cents;\n}\nfunction toCents(value) {\n var cents = parseCents(value);\n return cents !== null && cents > 0 ? cents : null;\n}\nfunction money(cents) {\n var abs = Math.abs(Math.round(cents));\n var whole = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\n return (cents < 0 ? '-' : '') + whole + '.' + pad(abs % 100);\n}\nfunction normalizeRecurs(text) {\n var raw = String(text || '').trim().toLowerCase();\n if (RECURS.indexOf(raw) >= 0) return raw;\n if (/two weeks|fortnight|bi-?weekly/.test(raw)) return 'biweekly';\n if (/week/.test(raw)) return 'weekly';\n if (/quarter/.test(raw)) return 'quarterly';\n if (/month/.test(raw)) return 'monthly';\n if (/once|one-?off|single/.test(raw)) return 'none';\n return null;\n}\nfunction scenarioNames(records) {\n var names = [];\n records.forEach(function (r) {\n var s = r.status === 'whatif' && r.fields && r.fields.scenario;\n if (s && names.indexOf(s) < 0) names.push(s);\n });\n return names;\n}\n// The plan's expected items, or the plan with one what-if's changes applied.\nfunction planItems(records, scenario) {\n var changes = records.filter(function (r) {\n return scenario && r.status === 'whatif' && r.fields.scenario === scenario && r.fields.change !== 'add';\n });\n return records\n .filter(function (r) {\n return r.status === 'expected' || (scenario && r.status === 'whatif' && r.fields.scenario === scenario && r.fields.change === 'add');\n })\n .map(function (r) {\n var shift = 0;\n var dropped = false;\n changes.forEach(function (c) {\n if (c.fields.itemId !== r.id) return;\n if (c.fields.change === 'drop') dropped = true;\n if (c.fields.change === 'delay') shift += Math.round(Number(c.fields.weeks) || 0);\n });\n var f = r.fields;\n return dropped\n ? null\n : { id: r.id, name: f.name, direction: f.direction, amountCents: f.amountCents, date: f.date, recurs: f.recurs || 'none', until: f.until || '', dom: f.dom, shiftDays: 7 * shift, whatIf: r.status === 'whatif' };\n })\n .filter(Boolean);\n}\n// Thirteen weeks from this Monday. A repeat dated before the balance is already in it; a one-off\n// that never came stays expected and is counted (and flagged late) in the first week.\nfunction forecast(file, scenario, nowMs) {\n var today = localDay(nowMs);\n var balance = file && file.balance && typeof file.balance.amountCents === 'number' ? file.balance : null;\n var asOf = balance && balance.asOf ? balance.asOf : today;\n var start = mondayOf(today);\n var end = addDays(start, 7 * WEEKS - 1);\n var from = asOf < start ? asOf : start;\n var weeks = [];\n for (var w = 0; w < WEEKS; w++) weeks.push({ start: addDays(start, 7 * w), inCents: 0, outCents: 0, items: [] });\n var late = [];\n planItems((file && file.records) || [], scenario).forEach(function (item) {\n if (!item.date || !(item.amountCents > 0)) return;\n var k = 0;\n if (item.recurs !== 'none') {\n var gap = daysBetween(item.date, from) - item.shiftDays;\n var period = { weekly: 7, biweekly: 14, monthly: 31, quarterly: 92 }[item.recurs] || 7;\n if (gap > 0) k = Math.max(0, Math.floor(gap / period) - 1);\n }\n for (var guard = 0; guard < 600; guard++, k++) {\n var raw = occurrence(item.date, item.recurs, k, item.dom);\n if (!raw || (item.until && raw > item.until)) break;\n var day = item.shiftDays ? addDays(raw, item.shiftDays) : raw;\n if (day > end) break;\n if (item.recurs !== 'none' && day < asOf) continue;\n var isLate = item.recurs === 'none' && day < today;\n var hit = { id: item.id, name: item.name, direction: item.direction, amountCents: item.amountCents, day: day, late: isLate, whatIf: item.whatIf };\n var week = weeks[day < start ? 0 : Math.floor(daysBetween(start, day) / 7)];\n if (item.direction === 'in') week.inCents += item.amountCents;\n else week.outCents += item.amountCents;\n week.items.push(hit);\n if (isLate) late.push(hit);\n if (item.recurs === 'none') break;\n }\n });\n var running = balance ? balance.amountCents : 0;\n var totalIn = 0;\n var totalOut = 0;\n weeks.forEach(function (wk) {\n wk.openCents = running;\n running += wk.inCents - wk.outCents;\n wk.closeCents = running;\n totalIn += wk.inCents;\n totalOut += wk.outCents;\n });\n var cushion = file && typeof file.cushionCents === 'number' ? file.cushionCents : 0;\n var lowest = weeks[0];\n weeks.forEach(function (wk) {\n if (wk.closeCents < lowest.closeCents) lowest = wk;\n });\n return {\n today: today, start: start, asOf: asOf, hasBalance: !!balance, balanceCents: balance ? balance.amountCents : 0,\n cushionCents: cushion, weeks: weeks, lowest: lowest, late: late, inCents: totalIn, outCents: totalOut, endCents: running,\n firstLow: weeks.filter(function (wk) { return wk.closeCents < cushion; })[0] || null,\n firstNegative: weeks.filter(function (wk) { return wk.closeCents < 0; })[0] || null,\n belowCushion: weeks.filter(function (wk) { return wk.closeCents < cushion; }).length,\n };\n}\nfunction biggest(week) {\n return week.items\n .filter(function (i) { return i.direction === 'out'; })\n .sort(function (a, b) { return b.amountCents - a.amountCents; })\n .slice(0, 3)\n .map(function (i) { return i.name + ' ' + money(i.amountCents); })\n .reduce(function (text, part, i, all) { return text + (i === 0 ? '' : i === all.length - 1 ? ' and ' : '; ') + part; }, '');\n}\n// The answer to \"when does cash get tight?\": the warning week first, with what goes out in it.\nfunction tightLine(f) {\n var low = f.lowest;\n var warn = f.firstNegative || f.firstLow;\n var week = function (w) { return 'the week of ' + weekLabel(w.start) + ' (' + w.start + ')'; };\n var going = function (w) { var out = biggest(w); return out ? ', when ' + out + ' go out' : ''; };\n if (!warn) {\n return 'Cash stays above the ' + money(f.cushionCents) + ' cushion for all ' + WEEKS + ' weeks; the tightest is ' + week(low) + ', ending at ' + money(low.closeCents) + going(low) + '.';\n }\n return (\n (f.firstNegative ? 'Cash runs out in ' : 'Cash first drops below the ' + money(f.cushionCents) + ' cushion in ') + week(warn) +\n ', ending at ' + money(warn.closeCents) + going(warn) + '. ' +\n (low === warn ? 'That is the tightest week.' : 'The tightest is ' + week(low) + ', ending at ' + money(low.closeCents) + '.')\n );\n}\nfunction compareLine(name, plan, alt) {\n var low = alt.lowest;\n return (\n name + ': tightest week ' + weekLabel(low.start) + ' at ' + money(low.closeCents) +\n ' (plan: ' + weekLabel(plan.lowest.start) + ' at ' + money(plan.lowest.closeCents) + ')' +\n (alt.firstNegative\n ? '; runs out in the week of ' + weekLabel(alt.firstNegative.start)\n : alt.firstLow\n ? '; below the cushion from the week of ' + weekLabel(alt.firstLow.start)\n : '; never below the cushion') +\n '; ends the 13 weeks at ' + money(alt.endCents) + ' (plan ' + money(plan.endCents) + ')'\n );\n}\nfunction itemLine(r, records) {\n var f = r.fields || {};\n if (f.change === 'delay' || f.change === 'drop') {\n var target = records.filter(function (x) { return x.id === f.itemId; })[0];\n var what = target ? target.fields.name + ' (' + target.id + ')' : f.itemId;\n return r.id + ' [what-if ' + f.scenario + '] ' + (f.change === 'drop' ? 'drop ' + what : 'delay ' + what + ' by ' + f.weeks + (Number(f.weeks) === 1 ? ' week' : ' weeks'));\n }\n return (\n r.id + (r.status === 'whatif' ? ' [what-if ' + f.scenario + '] add ' : ' ') + f.name + ': ' + (f.direction === 'in' ? 'in ' : 'out ') +\n money(f.amountCents || 0) + ' ' + (f.recurs && f.recurs !== 'none' ? RECURS_TEXT[f.recurs] + ' from ' + f.date + (f.until ? ' until ' + f.until : '') : 'on ' + f.date) +\n (r.status === 'done' ? ' (done)' : '')\n );\n}\nfunction cashPicture(file, nowMs, scenario) {\n var records = (file && file.records) || [];\n var plan = forecast(file, null, nowMs);\n var view = scenario ? forecast(file, scenario, nowMs) : plan;\n var planned = records.filter(function (r) { return r.status === 'expected'; }).length;\n if (!plan.hasBalance && !planned) {\n return { plan: plan, view: view, summary: 'The plan is empty: no bank balance and no expected income or bills yet. Ask for today’s bank balance, the regular bills (payroll, rent, suppliers) and the invoices still to be paid.' };\n }\n var parts = [(scenario ? 'With the what-if ' + scenario + ': ' : '') + tightLine(view)];\n parts.push(\n plan.hasBalance\n ? 'Cash in the bank: ' + money(plan.balanceCents) + ' as of ' + plan.asOf + ' (cushion ' + money(plan.cushionCents) + ').' +\n (daysBetween(plan.asOf, plan.today) > 7 ? ' That balance is ' + daysBetween(plan.asOf, plan.today) + ' days old; a fresh one sharpens the forecast.' : '')\n : 'No bank balance yet, so the forecast starts from zero. Ask for today’s balance.',\n );\n if (view.late.length) {\n parts.push('Late, counted in this week until it arrives or is moved: ' + view.late.map(function (i) { return i.name + ' (' + i.id + ', ' + (i.direction === 'in' ? 'in ' : 'out ') + money(i.amountCents) + ', expected ' + i.day + ')'; }).join('; ') + '.');\n }\n parts.push(\n 'Week by week, ending balance: ' +\n view.weeks.map(function (wk) { return weekLabel(wk.start) + ' ' + money(wk.closeCents) + ' (in ' + money(wk.inCents) + ', out ' + money(wk.outCents) + ')'; }).join(' | ') + '.',\n );\n parts.push('Over 13 weeks: in ' + money(view.inCents) + ', out ' + money(view.outCents) + ', ending at ' + money(view.endCents) + '.');\n var names = scenarioNames(records);\n if (names.length) {\n parts.push('What-ifs: ' + names.map(function (n) { return compareLine(n, plan, forecast(file, n, nowMs)); }).join(' | ') + '.');\n }\n return { plan: plan, view: view, summary: parts.join(' ') };\n}\n// ── cashflow-rules-end ──\n\nconst STAGES: [string, ...string[]] = ['expected', 'whatif', 'done', 'removed'];\nconst plan = rosterStore(gezel.fs, 'cashflow.json', { stages: STAGES, idPrefix: 'cf' });\nconst now = Date.now();\nconst today = localDay(now);\n\ntype CashRecord = Awaited<ReturnType<typeof plan.list>>[number];\n\n// The balance and cushion sit beside the records in the same file; the roster store keeps them on every write.\nasync function loadFile(): Promise<Record<string, any>> {\n let raw: string;\n try {\n raw = await gezel.fs.read('cashflow.json');\n } catch {\n return { version: 1, stages: [...STAGES], records: [] };\n }\n return JSON.parse(raw);\n}\nasync function saveTop(patch: Record<string, unknown>): Promise<void> {\n const file = await loadFile();\n Object.assign(file, patch);\n await gezel.fs.write('cashflow.json', JSON.stringify(file, null, 2) + '\\n');\n}\n\nconst GENERIC = ['invoice', 'payment', 'bill', 'from', 'with', 'final'];\nfunction matches(records: CashRecord[], text: string, statuses: string[]): CashRecord[] {\n const wanted = text.trim().toLowerCase();\n const pool = records.filter((r) => statuses.includes(r.status) && (r.status === 'expected' || r.fields.change === 'add'));\n const byId = pool.filter((r) => r.id === wanted);\n if (byId.length) return byId;\n const nameOf = (r: CashRecord) => String(r.fields.name ?? '').toLowerCase();\n const exact = pool.filter((r) => nameOf(r) === wanted);\n if (exact.length) return exact;\n const partial = pool.filter((r) => nameOf(r).includes(wanted) || (!!nameOf(r) && wanted.includes(nameOf(r))));\n if (partial.length) return partial;\n // Fall back to distinctive shared words: 'Hollis invoice' finds 'Hollis Bakery lighting retrofit'.\n const words = (wanted.match(/[a-z]{4,}/g) ?? []).filter((w) => !GENERIC.includes(w));\n let best: CashRecord[] = [];\n let score = 0;\n for (const r of pool) {\n const hits = words.filter((w) => nameOf(r).includes(w)).length;\n if (hits > score) {\n best = [r];\n score = hits;\n } else if (hits && hits === score) best.push(r);\n }\n return best;\n}\nfunction resolveOne(records: CashRecord[], text: string, what: string): CashRecord {\n if (!text.trim()) throw new Error(\"Pass 'item': the id (e.g. 'cf-3') or the name of \" + what + \". Call action:'list' to see them.\");\n const hits = matches(records, text, ['expected']);\n if (hits.length === 1) return hits[0]!;\n if (!hits.length) throw new Error(\"Nothing expected in the plan matches '\" + text + \"'. Call action:'list' to see the items.\");\n throw new Error(\"More than one item matches '\" + text + \"': \" + hits.map((r) => itemLine(r, records)).join(' | ') + '. Pass the id.');\n}\nfunction directionOf(text: string | undefined): 'in' | 'out' | null {\n const d = String(text ?? '').trim().toLowerCase();\n if (/^(in|income|incoming|receivable|invoice)$/.test(d)) return 'in';\n if (/^(out|outgoing|expense|bill|cost|payable)$/.test(d)) return 'out';\n return null;\n}\nfunction itemFields(isNew: boolean): Record<string, unknown> {\n const fields: Record<string, unknown> = {};\n if (input.direction) {\n const d = directionOf(input.direction);\n if (!d) throw new Error(\"direction must be 'in' (money coming in) or 'out' (a bill).\");\n fields.direction = d;\n }\n if (input.amount !== undefined && input.amount !== null) {\n const cents = toCents(input.amount);\n if (cents === null) throw new Error(\"amount must be positive, in ordinary units, e.g. 9600.\");\n fields.amountCents = cents;\n }\n if (input.date) {\n const d = normalizeDate(input.date);\n if (!d) throw new Error(\"date must be a date, e.g. '\" + today + \"'.\");\n fields.date = d;\n fields.dom = Number(d.slice(8, 10));\n }\n if (input.recurs) {\n const r = normalizeRecurs(input.recurs);\n if (!r) throw new Error('recurs must be one of: ' + RECURS.join(', ') + '.');\n fields.recurs = r;\n }\n if (input.until) {\n const u = normalizeDate(input.until);\n if (!u) throw new Error('until must be a date, YYYY-MM-DD.');\n fields.until = u;\n }\n if (input.note) fields.note = input.note.trim();\n if (isNew) {\n if (!fields.direction) throw new Error(\"A new item needs 'direction': in for money coming in, out for a bill.\");\n if (!fields.amountCents) throw new Error(\"A new item needs a positive 'amount', e.g. 9600.\");\n if (!fields.date) throw new Error(\"A new item needs 'date', YYYY-MM-DD (the first date, for a repeat).\");\n if (!fields.recurs) fields.recurs = 'none';\n }\n return fields;\n}\n\nlet note = '';\nlet focus: string | null = null;\n\nif (input.action === 'set_balance') {\n const cents = parseCents(input.amount);\n if (cents === null) throw new Error(\"set_balance needs 'amount': the cash in the bank in ordinary units, e.g. 18420.\");\n const asOf = input.date ? normalizeDate(input.date) : today;\n if (!asOf) throw new Error(\"date must be a date, e.g. '\" + today + \"'.\");\n const patch: Record<string, unknown> = { balance: { amountCents: cents, asOf } };\n if (input.cushion !== undefined && input.cushion !== null) {\n const cushion = parseCents(input.cushion);\n if (cushion === null || cushion < 0) throw new Error('cushion must be zero or more, e.g. 12000.');\n patch.cushionCents = cushion;\n }\n await saveTop(patch);\n note = 'Bank balance set to ' + money(cents) + ' as of ' + asOf + (typeof patch.cushionCents === 'number' ? ', with a cushion of ' + money(patch.cushionCents) : '') + '.';\n} else if (input.action === 'add') {\n const name = (input.name ?? input.item ?? '').trim();\n if (!name) throw new Error(\"add needs 'name', e.g. 'Hollis Bakery invoice'.\");\n const records = await plan.list();\n const existing = records.find((r) => r.status === 'expected' && String(r.fields.name ?? '').toLowerCase() === name.toLowerCase());\n if (existing) {\n const updated = await plan.update(existing.id, { fields: itemFields(false), note: 'Updated' });\n note = 'Updated ' + itemLine(updated, records) + '.';\n } else {\n const added = await plan.add({ status: 'expected', fields: { name, ...itemFields(true) } });\n note = 'Added ' + itemLine(added, records) + '.';\n }\n} else if (input.action === 'settle') {\n const records = await plan.list();\n const rec = resolveOne(records, input.item ?? input.name ?? '', 'the item that came in or was paid');\n const f = rec.fields;\n const cents = input.amount !== undefined && input.amount !== null ? toCents(input.amount) : Number(f.amountCents);\n if (!cents) throw new Error('amount must be positive, in ordinary units.');\n const on = input.date ? normalizeDate(input.date) : today;\n if (!on) throw new Error(\"date must be a date, e.g. '\" + today + \"'.\");\n const file = await loadFile();\n const asOf = file.balance && typeof file.balance.amountCents === 'number' ? String(file.balance.asOf) : null;\n const recurs = String(f.recurs ?? 'none');\n let after = '';\n if (recurs !== 'none') {\n // The settled one is the first the forecast still counts: on or after the balance date.\n const from = asOf ?? today;\n let k = 0;\n let day = occurrence(String(f.date), recurs, 0, f.dom as number);\n while (day && day < from && k < 1000) day = occurrence(String(f.date), recurs, ++k, f.dom as number);\n const next = occurrence(String(f.date), recurs, k + 1, f.dom as number) as string;\n if (f.until && next > String(f.until)) {\n await plan.transition(rec.id, 'done', { note: 'Last one settled on ' + on });\n after = '; that was the last one';\n } else {\n await plan.update(rec.id, { fields: { date: next, lastSettled: on }, note: 'Settled ' + money(cents) + ' on ' + on });\n after = '; the next one is due ' + next;\n }\n } else {\n await plan.update(rec.id, { fields: { settledOn: on, settledCents: cents } });\n await plan.transition(rec.id, 'done', { note: (f.direction === 'in' ? 'Received ' : 'Paid ') + money(cents) + ' on ' + on });\n after = '; it leaves the forecast';\n }\n let moved = '';\n if (asOf && on >= asOf) {\n const balance = file.balance.amountCents + (f.direction === 'in' ? cents : -cents);\n await saveTop({ balance: { amountCents: balance, asOf } });\n moved = ' Cash in the bank is now ' + money(balance) + '.';\n }\n note = String(f.name) + (f.direction === 'in' ? ' came in: ' : ' was paid: ') + money(cents) + ' on ' + on + after + '.' + moved;\n} else if (input.action === 'remove') {\n const records = await plan.list();\n const rec = resolveOne(records, input.item ?? input.name ?? '', 'the item to take out');\n await plan.transition(rec.id, 'removed', { note: input.note ?? 'Taken out of the plan' });\n note = 'Took ' + String(rec.fields.name) + ' (' + rec.id + ') out of the plan.';\n} else if (input.action === 'what_if') {\n const records = await plan.list();\n const raw = (input.scenario ?? '').trim();\n if (!raw) throw new Error(\"what_if needs 'scenario': a short name, e.g. 'Hire an apprentice'.\");\n const scenario = scenarioNames(records).find((n) => n.toLowerCase() === raw.toLowerCase()) ?? raw;\n const change = String(input.change ?? '').trim().toLowerCase();\n if (change === 'delay' || change === 'drop') {\n const text = input.item ?? input.name ?? '';\n const targets = text.trim() ? matches(records, text, ['expected']) : [];\n if (!targets.length) throw new Error(\"A what-if \" + change + \" needs 'item': the id or name of something expected. Call action:'list' to see them.\");\n const weeks = Math.round(Number(input.weeks));\n if (change === 'delay' && (!isFinite(weeks) || weeks === 0)) throw new Error(\"A delay needs 'weeks', e.g. 4 for a month late.\");\n for (const t of targets) {\n const existing = records.find((r) => r.status === 'whatif' && r.fields.scenario === scenario && r.fields.change === change && r.fields.itemId === t.id);\n if (existing) await plan.update(existing.id, { fields: change === 'delay' ? { weeks } : {} });\n else await plan.add({ status: 'whatif', fields: { scenario, change, itemId: t.id, ...(change === 'delay' ? { weeks } : {}) } });\n }\n note = 'What-if ' + scenario + ': ' + change + ' ' + targets.map((t) => String(t.fields.name) + ' (' + t.id + ')').join(' and ') +\n (change === 'delay' ? ' by ' + weeks + (weeks === 1 ? ' week' : ' weeks') : '') + '. The plan itself is unchanged.';\n } else if (change === 'add') {\n const name = (input.name ?? '').trim();\n if (!name) throw new Error(\"A what-if add needs 'name', e.g. 'Apprentice wages'.\");\n const existing = records.find((r) => r.status === 'whatif' && r.fields.scenario === scenario && r.fields.change === 'add' && String(r.fields.name).toLowerCase() === name.toLowerCase());\n if (existing) await plan.update(existing.id, { fields: itemFields(false) });\n else await plan.add({ status: 'whatif', fields: { scenario, change: 'add', name, ...itemFields(true) } });\n note = 'What-if ' + scenario + ': add ' + name + '. The plan itself is unchanged.';\n } else if (change === 'clear') {\n const mine = records.filter((r) => r.status === 'whatif' && r.fields.scenario === scenario);\n if (!mine.length) throw new Error(\"No what-if is named '\" + raw + \"'. What-ifs: \" + (scenarioNames(records).join(', ') || 'none') + '.');\n for (const r of mine) await plan.transition(r.id, 'removed', { note: 'What-if cleared' });\n note = 'Cleared the what-if ' + scenario + '.';\n } else {\n throw new Error(\"what_if needs 'change': delay, drop, add, or clear.\");\n }\n if (change !== 'clear') focus = scenario;\n} else if (input.action === 'status') {\n if (input.scenario) {\n const names = scenarioNames(await plan.list());\n focus = names.find((n) => n.toLowerCase() === input.scenario!.trim().toLowerCase()) ?? null;\n if (!focus) note = \"No what-if is named '\" + input.scenario + \"'; showing the plan. What-ifs: \" + (names.join(', ') || 'none') + '.';\n }\n} else if (input.action !== 'list') {\n throw new Error(\"Unknown action '\" + input.action + \"'. Use status, set_balance, add, settle, remove, what_if, or list.\");\n}\n\nconst file = await loadFile();\nconst view = cashPicture(file, now, focus);\nconst records = (file.records ?? []) as CashRecord[];\nconst listing =\n input.action === 'list'\n ? (file.balance ? 'Cash in the bank: ' + money(file.balance.amountCents) + ' as of ' + file.balance.asOf + '. Cushion: ' + money(file.cushionCents ?? 0) + '.\\n' : 'No bank balance yet.\\n') +\n (records.filter((r) => r.status === 'expected' || r.status === 'whatif').map((r) => itemLine(r, records)).join('\\n') || 'Nothing is expected yet.')\n : '';\n\ngezel.output({\n balance: view.plan.balanceCents / 100,\n lowestBalance: view.view.lowest.closeCents / 100,\n lowWeek: view.view.lowest.start,\n belowCushion: view.view.belowCushion,\n endBalance: view.view.endCents / 100,\n summary: listing || (note ? note + ' ' : '') + view.summary,\n});\n"},"tools":[{"name":"cash_forecast","description":"The 13-week cash forecast: the first week cash drops below the cushion (the warning week) and what goes out then, the tightest week, cash in the bank, late items, every week-end balance, and each what-if compared with the plan. Call it first for any question about cash.","script":"cashflow-store","inputs":{"type":"object","properties":{"scenario":{"type":"string"}}},"bind":{"action":"status"},"state":true},{"name":"set_balance","description":"Save the cash in the bank (amount in ordinary units, as of a date, default today) and, if given, the cushion to keep on hand. Call it as soon as the person says what is in the bank.","script":"cashflow-store","inputs":{"type":"object","properties":{"amount":{"type":"number"},"date":{"type":"string"},"cushion":{"type":"number"}},"required":["amount"]},"bind":{"action":"set_balance"}},{"name":"add_cash_item","description":"Save money the business expects: an invoice coming in or a bill going out, once or repeating (weekly, biweekly, monthly, quarterly). An existing name is updated, never duplicated, so use it to move a date or change an amount for real. Call it as soon as one is mentioned, before you describe it. For a 'what if', use what_if instead.","script":"cashflow-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"direction":{"type":"string","enum":["in","out"]},"amount":{"type":"number"},"date":{"type":"string"},"recurs":{"type":"string","enum":["none","weekly","biweekly","monthly","quarterly"]},"until":{"type":"string"},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"add"}},{"name":"settle_cash_item","description":"Record that expected money came in or a bill was paid: a one-off leaves the forecast, a repeating one moves to its next date, and the bank balance moves by the amount. Call it the moment the person says it arrived or went out.","script":"cashflow-store","inputs":{"type":"object","properties":{"item":{"type":"string"},"amount":{"type":"number"},"date":{"type":"string"}},"required":["item"]},"bind":{"action":"settle"}},{"name":"remove_cash_item","description":"Take an expected item out of the plan for good, such as a cancelled job or a bill that ended.","script":"cashflow-store","inputs":{"type":"object","properties":{"item":{"type":"string"},"note":{"type":"string"}},"required":["item"]},"bind":{"action":"remove"}},{"name":"what_if","description":"Try a what-if without changing the plan, under a short scenario name: delay an expected item by some weeks (a month late is 4), drop one, or add a new cost or income such as a hire; 'clear' removes the scenario. The reply compares its warning week with the plan. Call it whenever the person asks 'what if'.","script":"cashflow-store","inputs":{"type":"object","properties":{"scenario":{"type":"string"},"change":{"type":"string","enum":["delay","drop","add","clear"]},"item":{"type":"string"},"weeks":{"type":"number"},"name":{"type":"string"},"direction":{"type":"string","enum":["in","out"]},"amount":{"type":"number"},"date":{"type":"string"},"recurs":{"type":"string","enum":["none","weekly","biweekly","monthly","quarterly"]},"until":{"type":"string"}},"required":["scenario","change"]},"bind":{"action":"what_if"}},{"name":"list_cash_items","description":"Every expected item and what-if change, with ids, amounts, dates and repeats.","script":"cashflow-store","inputs":{"type":"object","properties":{}},"bind":{"action":"list"}},{"name":"page_set_balance","description":"Save the cash in the bank and the cushion.","script":"cashflow-store","inputs":{"type":"object","properties":{"amount":{"type":"number"},"date":{"type":"string"},"cushion":{"type":"number"}},"required":["amount"]},"bind":{"action":"set_balance"}},{"name":"page_add_cash_item","description":"Save an expected invoice or bill.","script":"cashflow-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"direction":{"type":"string","enum":["in","out"]},"amount":{"type":"number"},"date":{"type":"string"},"recurs":{"type":"string","enum":["none","weekly","biweekly","monthly","quarterly"]},"until":{"type":"string"},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"add"}},{"name":"page_settle_cash_item","description":"Record that expected money came in or a bill was paid.","script":"cashflow-store","inputs":{"type":"object","properties":{"item":{"type":"string"},"amount":{"type":"number"},"date":{"type":"string"}},"required":["item"]},"bind":{"action":"settle"}},{"name":"page_what_if","description":"Try a what-if without changing the plan.","script":"cashflow-store","inputs":{"type":"object","properties":{"scenario":{"type":"string"},"change":{"type":"string","enum":["delay","drop","add","clear"]},"item":{"type":"string"},"weeks":{"type":"number"},"name":{"type":"string"},"direction":{"type":"string","enum":["in","out"]},"amount":{"type":"number"},"date":{"type":"string"},"recurs":{"type":"string","enum":["none","weekly","biweekly","monthly","quarterly"]},"until":{"type":"string"}},"required":["scenario","change"]},"bind":{"action":"what_if"},"reaction":{"gezel":"bookkeeper","prompt":"The person just tried a what-if on the cash flow page. The forecast now reads (the first sentence is what changed, the next is the scenario):\n{{output.summary}}\nIn two short sentences, say how the what-if moves the warning week or the tightest week compared with the plan, and whether cash stays above the cushion. Do not call tools.","hideSeed":true}}],"pages":{"entry":"forecast/index.html","api":1,"reads":[{"source":"workspace","path":"cashflow.json"}],"tools":["page_set_balance","page_add_cash_item","page_settle_cash_item","page_what_if"]},"schedules":[],"workspaceSeed":["cashflow.json"],"artifactsSeed":[],"availableVersions":["1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"just-chat","name":"Chat","description":"A quiet room for talking — no tasks, no workspace, no deliverables. Just an open thread with a gezel of your choosing: brainstorming, writing back and forth, asking questions, thinking out loud. Ideal for a warm companion gezel or a small on-device model that's happiest simply conversing.","tags":["chat","conversation","companion","casual","writing"],"category":"general","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26279","version":"1.0.2","releasedAt":"2026-10-05T00:00:00Z","meesterManaged":false,"tabVisibility":{"overview":false,"tasks":false,"approvals":false,"workspace":false,"artifacts":false,"map":false},"nameTemplate":"Chat","aboutTemplate":"about.md","gezels":[{"templateId":"conversationalist","voorman":false}],"toolsets":[],"craftbooks":[],"tools":[],"schedules":[],"workspaceSeed":[],"artifactsSeed":[],"availableVersions":["1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"checkers","name":"Checkers","description":"Play checkers against a gezel opponent on a live board. You move on the board; the checkers player sees the position, plays back, and keeps the table talk going.","tags":["checkers","game","board-game","play"],"category":"game","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.2.7","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"tabVisibility":{"overview":false,"tasks":false,"approvals":false,"workspace":false,"artifacts":false,"map":false},"mode":"solo","leadLabel":"Opponent","leanProfile":true,"params":{"type":"object","properties":{"personality":{"type":"string","title":"Table-talk style","description":"How your opponent talks between moves. In-character follows the gezel's own character when social mode is on.","enum":["in-character","peppy","cheeky","zen","gracious"],"default":"in-character"},"playStyle":{"type":"string","title":"How should the checkers player play?","description":"An opponent keeps their strategy to themselves; an instructor offers light teaching notes.","enum":["Opponent","Instructor"],"default":"Opponent"}},"required":["personality","playStyle"]},"nameTemplate":"Checkers Table","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"checkers-player","voorman":true}],"toolsets":[],"craftbooks":[],"scripts":{"game-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\n\nexport const meta = defineScript({\n name: 'game-store',\n description:\n \"Read and update the checkers game (game.json). Call action:'board' to see the position, the side to move, and every legal move; action:'ai_move' to play your move (from/to, optional moveThought); action:'state' for a light summary; action:'new_game' to reset, optionally with forceCaptures:false. An illegal ai_move fails with the full legal-move list — pick one of those and call again.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'state', 'board', 'user_move', 'ai_move', or 'new_game'.\",\n required: true,\n },\n from: { type: 'string', description: \"Origin square, e.g. 'c3'.\" },\n to: { type: 'string', description: \"Destination square (a jump sequence's final square).\" },\n moveThought: { type: 'string', description: 'A short line of table talk to show on the board (max 140 chars).' },\n forceCaptures: {\n type: 'boolean',\n description: \"For new_game: true for standard forced captures; false to keep ordinary moves legal when a capture is available.\",\n },\n },\n outputs: {\n board: { type: 'string', description: 'Legacy human-readable ASCII board with coordinates.' },\n modelState: {\n type: 'object',\n description:\n 'Authoritative model-facing state: orientation, square lists, capture availability, and structured legal moves.',\n },\n turn: { type: 'string', description: \"Whose move: 'user' or 'ai'.\" },\n status: { type: 'string', description: 'playing, user_won, or ai_won.' },\n lastMove: { type: 'string', description: \"The move just played, e.g. 'c3-d4' or 'b6xd4'.\" },\n legalMoves: { type: 'string', description: 'Rendered legal moves for the side to move.' },\n captureRule: { type: 'string', description: \"Either 'forced' or 'optional'.\" },\n summary: { type: 'string', description: 'Human-readable game summary.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── checkers-rules-start ──\n// Pure, annotation-free rules engine (American/English draughts, 8x8).\n// Squares: 64-char row-major string, index = y*8+x, y0 = rank 8, x0 = file a.\n// 'r'/'R' = red (the user, moving toward rank 8 / decreasing y);\n// 'b'/'B' = black (the AI, moving toward rank 1 / increasing y); '.' empty.\n// Kept self-contained between these sentinels so unit tests execute the\n// shipped bytes directly (new Function) on every platform.\n\nvar FILES = 'abcdefgh';\n\nfunction sqName(x, y) {\n return FILES[x] + String(8 - y);\n}\n\nfunction parseSq(name) {\n if (typeof name !== 'string' || name.length !== 2) return null;\n var x = FILES.indexOf(name[0].toLowerCase());\n var rank = Number(name[1]);\n if (x < 0 || !(rank >= 1 && rank <= 8)) return null;\n return { x: x, y: 8 - rank };\n}\n\nfunction pieceAt(squares, x, y) {\n return squares[y * 8 + x];\n}\n\nfunction withPiece(squares, x, y, ch) {\n var i = y * 8 + x;\n return squares.slice(0, i) + ch + squares.slice(i + 1);\n}\n\nfunction sideOf(ch) {\n if (ch === 'r' || ch === 'R') return 'user';\n if (ch === 'b' || ch === 'B') return 'ai';\n return null;\n}\n\nfunction isKing(ch) {\n return ch === 'R' || ch === 'B';\n}\n\nfunction kingRowY(side) {\n return side === 'user' ? 0 : 7;\n}\n\nfunction dirsFor(ch) {\n if (isKing(ch)) {\n return [\n { dx: -1, dy: -1 },\n { dx: 1, dy: -1 },\n { dx: -1, dy: 1 },\n { dx: 1, dy: 1 },\n ];\n }\n var dy = ch === 'r' ? -1 : 1;\n return [\n { dx: -1, dy: dy },\n { dx: 1, dy: dy },\n ];\n}\n\nfunction inBounds(x, y) {\n return x >= 0 && x < 8 && y >= 0 && y < 8;\n}\n\nfunction buildInitial() {\n var out = '';\n for (var y = 0; y < 8; y += 1) {\n for (var x = 0; x < 8; x += 1) {\n var dark = (x + y) % 2 === 1;\n if (dark && y <= 2) out += 'b';\n else if (dark && y >= 5) out += 'r';\n else out += '.';\n }\n }\n return out;\n}\n\n// All complete jump sequences for the piece at (x, y). A sequence keeps\n// jumping with the same piece while another capture is available; a man\n// that reaches the king row STOPS there (standard rule — the move ends on\n// crowning). Each result: { from, to, path, captures } (square names).\nfunction jumpSequencesFrom(squares, x, y, ch) {\n var side = sideOf(ch);\n var results = [];\n\n function explore(sq, cx, cy, curCh, path, captures) {\n var extended = false;\n var dirs = dirsFor(curCh);\n for (var i = 0; i < dirs.length; i += 1) {\n var mx = cx + dirs[i].dx;\n var my = cy + dirs[i].dy;\n var lx = cx + dirs[i].dx * 2;\n var ly = cy + dirs[i].dy * 2;\n if (!inBounds(lx, ly)) continue;\n var mid = pieceAt(sq, mx, my);\n if (sideOf(mid) === null || sideOf(mid) === side) continue;\n if (pieceAt(sq, lx, ly) !== '.') continue;\n\n var nextCh = curCh;\n var crowned = false;\n if (!isKing(curCh) && ly === kingRowY(side)) {\n nextCh = side === 'user' ? 'R' : 'B';\n crowned = true;\n }\n var nextSq = withPiece(withPiece(withPiece(sq, cx, cy, '.'), mx, my, '.'), lx, ly, nextCh);\n var nextPath = path.concat([sqName(lx, ly)]);\n var nextCaptures = captures.concat([sqName(mx, my)]);\n extended = true;\n if (crowned) {\n results.push({\n from: path[0],\n to: sqName(lx, ly),\n path: nextPath,\n captures: nextCaptures,\n });\n } else {\n explore(nextSq, lx, ly, nextCh, nextPath, nextCaptures);\n }\n }\n if (!extended && captures.length > 0) {\n results.push({ from: path[0], to: path[path.length - 1], path: path, captures: captures });\n }\n }\n\n explore(squares, x, y, ch, [sqName(x, y)], []);\n return results;\n}\n\n// Every legal move for `side`. With standard forced captures, any jump\n// masks quiet moves. In the optional-capture variant, both remain legal.\n// Simple moves are single diagonal steps.\nfunction legalMovesFor(squares, side, forceCaptures) {\n var jumps = [];\n var steps = [];\n for (var y = 0; y < 8; y += 1) {\n for (var x = 0; x < 8; x += 1) {\n var ch = pieceAt(squares, x, y);\n if (sideOf(ch) !== side) continue;\n var seqs = jumpSequencesFrom(squares, x, y, ch);\n for (var j = 0; j < seqs.length; j += 1) jumps.push(seqs[j]);\n var dirs = dirsFor(ch);\n for (var i = 0; i < dirs.length; i += 1) {\n var nx = x + dirs[i].dx;\n var ny = y + dirs[i].dy;\n if (!inBounds(nx, ny) || pieceAt(squares, nx, ny) !== '.') continue;\n steps.push({\n from: sqName(x, y),\n to: sqName(nx, ny),\n path: [sqName(x, y), sqName(nx, ny)],\n captures: [],\n });\n }\n }\n }\n return forceCaptures !== false && jumps.length > 0 ? jumps : jumps.concat(steps);\n}\n\n// Apply a legal sequence, returning the new squares string. Crowns a man\n// that ends on the king row (mid-sequence crowning already ended the\n// sequence in jumpSequencesFrom, so end-of-path crowning is complete).\nfunction applySequence(squares, seq) {\n var start = parseSq(seq.from);\n var end = parseSq(seq.to);\n var ch = pieceAt(squares, start.x, start.y);\n var side = sideOf(ch);\n var next = withPiece(squares, start.x, start.y, '.');\n for (var i = 0; i < seq.captures.length; i += 1) {\n var cap = parseSq(seq.captures[i]);\n next = withPiece(next, cap.x, cap.y, '.');\n }\n var finalCh = ch;\n if (!isKing(ch) && end.y === kingRowY(side)) finalCh = side === 'user' ? 'R' : 'B';\n return withPiece(next, end.x, end.y, finalCh);\n}\n\n// The side to move with no legal move has lost (covers zero pieces too).\nfunction statusAfter(squares, sideToMove, forceCaptures) {\n if (legalMovesFor(squares, sideToMove, forceCaptures).length > 0) return 'playing';\n return sideToMove === 'user' ? 'ai_won' : 'user_won';\n}\n\nfunction describeMove(seq) {\n var joiner = seq.captures.length > 0 ? 'x' : '-';\n var text = seq.path.join(joiner);\n if (seq.captures.length > 0) text += ' (captures ' + seq.captures.join(', ') + ')';\n return text;\n}\n\nfunction renderAscii(squares) {\n var lines = [' a b c d e f g h'];\n for (var y = 0; y < 8; y += 1) {\n var row = String(8 - y);\n for (var x = 0; x < 8; x += 1) {\n row += ' ' + pieceAt(squares, x, y);\n }\n lines.push(row);\n }\n lines.push('r/R = red (your opponent, moving up). b/B = black (you, moving down). Capitals are kings.');\n return lines.join('\\n');\n}\n\nfunction renderPieces(squares) {\n var redMen = [];\n var redKings = [];\n var blackMen = [];\n var blackKings = [];\n for (var y = 0; y < 8; y += 1) {\n for (var x = 0; x < 8; x += 1) {\n var ch = pieceAt(squares, x, y);\n var name = sqName(x, y);\n if (ch === 'r') redMen.push(name);\n else if (ch === 'R') redKings.push(name);\n else if (ch === 'b') blackMen.push(name);\n else if (ch === 'B') blackKings.push(name);\n }\n }\n return { redMen: redMen, redKings: redKings, blackMen: blackMen, blackKings: blackKings };\n}\n// ── checkers-rules-end ──\n\nconst STATE_FILE = 'game.json';\nconst STAGE_SIDES = { user: 'red', ai: 'black' };\n\ninterface GameState {\n version: number;\n squares: string;\n turn: 'user' | 'ai';\n status: 'playing' | 'user_won' | 'ai_won' | 'draw';\n userColor: string;\n forceCaptures: boolean;\n legalMoves: Array<{ from: string; to: string; path: string[]; captures: string[] }>;\n moveLog: Array<{\n by: 'user' | 'ai';\n from: string;\n to: string;\n captures: string[];\n at: string;\n moveThought?: string;\n }>;\n lastMove: { by: 'user' | 'ai'; from: string; to: string; captures: string[] } | null;\n lastMoveThought: string;\n updatedAt: string;\n}\n\nfunction freshState(forceCaptures = true): GameState {\n const squares = buildInitial();\n return {\n version: 1,\n squares,\n turn: 'user',\n status: 'playing',\n userColor: 'red',\n forceCaptures,\n legalMoves: legalMovesFor(squares, 'user', forceCaptures),\n moveLog: [],\n lastMove: null,\n lastMoveThought: '',\n updatedAt: new Date().toISOString(),\n };\n}\n\nasync function load(): Promise<GameState> {\n let raw: string;\n try {\n raw = await gezel.fs.read(STATE_FILE);\n } catch {\n return freshState();\n }\n const parsed = JSON.parse(raw) as Partial<GameState>;\n if (typeof parsed.squares !== 'string' || parsed.squares.length !== 64) {\n throw new Error(`${STATE_FILE} is corrupt (squares missing); call action:'new_game' to reset.`);\n }\n return { ...freshState(parsed.forceCaptures !== false), ...parsed, forceCaptures: parsed.forceCaptures !== false } as GameState;\n}\n\nasync function persist(state: GameState): Promise<GameState> {\n state.legalMoves = state.status === 'playing' ? legalMovesFor(state.squares, state.turn, state.forceCaptures) : [];\n state.updatedAt = new Date().toISOString();\n await gezel.fs.write(STATE_FILE, `${JSON.stringify(state, null, 2)}\\n`);\n return state;\n}\n\nfunction summarize(state: GameState): string {\n const counts = { r: 0, b: 0 };\n for (const ch of state.squares) {\n if (ch === 'r' || ch === 'R') counts.r += 1;\n if (ch === 'b' || ch === 'B') counts.b += 1;\n }\n if (state.status === 'user_won') return `Game over — the user (red) won. Red ${counts.r} pieces, black ${counts.b}.`;\n if (state.status === 'ai_won') return `Game over — you (black) won. Red ${counts.r} pieces, black ${counts.b}.`;\n return `Move ${state.moveLog.length + 1}: ${STAGE_SIDES[state.turn]} (${state.turn}) to move. Red ${counts.r} pieces, black ${counts.b}. Captures are ${state.forceCaptures ? 'forced' : 'optional'}.`;\n}\n\nfunction renderLegal(state: GameState): string {\n if (state.status !== 'playing') return '(game over)';\n return state.legalMoves.map(describeMove).join(', ') || '(none)';\n}\n\nfunction renderModelState(state: GameState) {\n return {\n status: state.status,\n sideToMove: STAGE_SIDES[state.turn],\n coordinateFormat: 'file-rank (for example e3)',\n orientation: { redForwardRankDelta: 1, blackForwardRankDelta: -1 },\n pieces: renderPieces(state.squares),\n capturePolicy: state.forceCaptures ? 'mandatory-if-available' : 'optional',\n capturesAvailable: state.legalMoves.some((move) => move.captures.length > 0),\n legalMoves: state.legalMoves.map((move) => ({\n from: move.from,\n to: move.to,\n path: move.path,\n captures: move.captures,\n type: move.captures.length > 0 ? 'capture' : 'step',\n })),\n };\n}\n\nfunction applyTurn(state: GameState, by: 'user' | 'ai', moveThought?: string): GameState {\n if (state.status !== 'playing') {\n throw new Error(`The game is over (${state.status}). Call action:'new_game' to start another.`);\n }\n if (state.turn !== by) {\n throw new Error(\n by === 'ai'\n ? \"It's not your turn — the user has not moved yet.\"\n : \"It's not your turn — the AI is still to move.\",\n );\n }\n if (!input.from || !input.to) throw new Error(\"Pass 'from' and 'to' squares, e.g. from:'c3' to:'d4'.\");\n const seq = state.legalMoves.find(\n (m) => m.from === input.from!.toLowerCase() && m.to === input.to!.toLowerCase(),\n );\n if (!seq) {\n throw new Error(\n `Illegal move ${input.from}-${input.to}. Legal moves for ${STAGE_SIDES[by]}: ${renderLegal(state)}`,\n );\n }\n state.squares = applySequence(state.squares, seq);\n const nextTurn = by === 'user' ? 'ai' : 'user';\n state.status = statusAfter(state.squares, nextTurn, state.forceCaptures) as GameState['status'];\n state.turn = nextTurn;\n const entry = {\n by,\n from: seq.from,\n to: seq.to,\n captures: seq.captures,\n at: new Date().toISOString(),\n ...(moveThought ? { moveThought } : {}),\n };\n state.moveLog.push(entry);\n state.lastMove = { by, from: seq.from, to: seq.to, captures: seq.captures };\n if (by === 'ai' && moveThought) state.lastMoveThought = moveThought;\n return state;\n}\n\nlet state = await load();\nlet lastMoveText = state.lastMove\n ? describeMove({ ...state.lastMove, path: [state.lastMove.from, state.lastMove.to] })\n : '(none)';\n\nif (input.action === 'new_game') {\n state = await persist(freshState(input.forceCaptures !== false));\n lastMoveText = '(none)';\n} else if (input.action === 'user_move' || input.action === 'ai_move') {\n const by = input.action === 'user_move' ? 'user' : 'ai';\n const moveThought = input.moveThought ? input.moveThought.trim().slice(0, 140) : undefined;\n const before = state.legalMoves.find(\n (m) => m.from === (input.from ?? '').toLowerCase() && m.to === (input.to ?? '').toLowerCase(),\n );\n applyTurn(state, by, moveThought);\n state = await persist(state);\n lastMoveText = before ? describeMove(before) : `${input.from}-${input.to}`;\n} else if (input.action !== 'state' && input.action !== 'board') {\n throw new Error(`Unknown action '${input.action}'. Use state, board, user_move, ai_move, or new_game.`);\n}\n\ngezel.output({\n board:\n input.action === 'state'\n ? `${renderAscii(state.squares).split('\\n').slice(0, 9).join('\\n')}`\n : `${renderAscii(state.squares)}\\nCapture rule: ${state.forceCaptures ? 'forced' : 'optional'}.\\nTurn: ${STAGE_SIDES[state.turn]} (${state.turn}). Legal moves: ${renderLegal(state)}`,\n modelState: renderModelState(state),\n turn: state.turn,\n status: state.status,\n lastMove: lastMoveText,\n legalMoves: renderLegal(state),\n captureRule: state.forceCaptures ? 'forced' : 'optional',\n summary: summarize(state),\n});\n"},"tools":[{"name":"get_board","description":"See the authoritative structured checkers position, whose turn it is, capture availability, and every legal move. A legacy ASCII board is included for human readability.","script":"game-store","inputs":{"type":"object","properties":{}},"bind":{"action":"board"},"state":true},{"name":"make_move","description":"Play your (black's) move. Pass the from/to squares of a legal move; include a short moveThought to show on the board.","script":"game-store","inputs":{"type":"object","properties":{"from":{"type":"string","description":"Origin square, e.g. 'b6'."},"to":{"type":"string","description":"Destination square (a jump's final landing square)."},"moveThought":{"type":"string","description":"A short line of table talk (max 140 chars)."}},"required":["from","to"]},"bind":{"action":"ai_move"},"turn":{"say":"moveThought","fallback":"Move made — your turn."}},{"name":"user_move","description":"The user's move, played from the board page.","script":"game-store","inputs":{"type":"object","properties":{"from":{"type":"string"},"to":{"type":"string"}},"required":["from","to"]},"bind":{"action":"user_move"},"reaction":{"gezel":"checkers-player","prompt":"Your opponent played {{output.lastMove}}. The game engine returned this authoritative state:\n```json\n{{output.modelState}}\n```\nEvery `legalMoves` entry is legal. Its `type` and `captures` fields explicitly say whether it is a jump. Do not redraw the position as a grid, re-derive legality, recalculate capture availability, recount pieces, or question the stated orientation. Spend any thinking only on which listed move is strongest.\nStyle: {{playStyle}}. In Opponent style, do not volunteer advice or reveal the user's available moves, captures, threats, or tactics; comment only about your own move or the atmosphere. In Instructor style, offer at most one brief teaching observation without choosing the user's move. Answer strategy questions when asked.\nAct on the state above. If the game is over, do not move — one gracious line and offer new_game. Otherwise it is your turn: choose one listed move and call make_move with its `from` and `to` strings, including a short {{personality}} moveThought that follows the selected style. If make_move rejects it, choose one move from the legal list in the error and try again. After moving, reply with ONE short line of table talk that follows the selected style.","hideSeed":true,"standalone":true,"turn":{"tool":"make_move","when":{"op":"equals","field":"status","value":"playing"}}}},{"name":"new_game","description":"Reset the board to the opening position (user moves first).","script":"game-store","inputs":{"type":"object","properties":{"forceCaptures":{"type":"boolean","description":"Whether captures are required when available. Defaults to true."}}},"bind":{"action":"new_game"}}],"pages":{"entry":"board/index.html","api":1,"reads":[{"source":"workspace","path":"game.json"}],"tools":["user_move","new_game"]},"schedules":[],"workspaceSeed":["game.json"],"artifactsSeed":[],"availableVersions":["1.2.7","1.2.6","1.2.5","1.2.4","1.2.3","1.2.2","1.2.1","1.2.0","1.1.2","1.1.1","1.1.0","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"chess","name":"Chess","description":"Play a complete game of chess against a gezel opponent on a live board. You move white; the chess player sees the exact position, replies with a legal move, and shares the table without spoiling your plans.","tags":["chess","game","board-game","strategy","play"],"category":"game","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.9","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"tabVisibility":{"overview":false,"tasks":false,"approvals":false,"workspace":false,"artifacts":false,"map":false},"mode":"solo","leadLabel":"Opponent","leanProfile":true,"params":{"type":"object","properties":{"personality":{"type":"string","title":"Table-talk style","description":"How your opponent talks between moves. In-character follows the gezel's own character when social mode is on.","enum":["in-character","peppy","cheeky","zen","gracious"],"default":"in-character"},"playStyle":{"type":"string","title":"How should the chess player play?","description":"An opponent keeps their strategy to themselves; an instructor offers light teaching notes.","enum":["Opponent","Instructor"],"default":"Opponent"}},"required":["personality","playStyle"]},"nameTemplate":"Chess Table","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"chess-player","voorman":true}],"toolsets":[],"craftbooks":[],"scripts":{"game-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\n\nexport const meta = defineScript({\n name: 'game-store',\n description:\n \"Read and update the chess game (game.json). Call action:'board' to see the position and every legal move; action:'ai_move' to play your move (from/to, optional promotion and moveThought); action:'state' for a light summary; action:'new_game' to reset. Illegal moves fail with the engine's legal-move list.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'state', 'board', 'user_move', 'ai_move', or 'new_game'.\",\n required: true,\n },\n from: { type: 'string', description: \"Origin square, e.g. 'e7'.\" },\n to: { type: 'string', description: \"Destination square, e.g. 'e5'.\" },\n promotion: {\n type: 'string',\n description: \"Promotion piece: 'q', 'r', 'b', or 'n'. Defaults to queen.\",\n },\n moveThought: {\n type: 'string',\n description: 'A short line of table talk to show on the board (max 140 chars).',\n },\n },\n outputs: {\n board: { type: 'string', description: 'ASCII board with coordinates.' },\n turn: { type: 'string', description: \"Whose move: 'user' (white) or 'ai' (black).\" },\n status: {\n type: 'string',\n description: 'playing, user_won, ai_won, or draw.',\n },\n lastMove: { type: 'string', description: \"The move just played, e.g. 'e2-e4'.\" },\n legalMoves: { type: 'string', description: 'Rendered legal moves for the side to move.' },\n summary: { type: 'string', description: 'Human-readable game summary.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── chess-rules-start ──\n// Pure, annotation-free chess engine. Squares are a 64-character row-major\n// string: y0 is rank 8, x0 is file a. Uppercase pieces are white (the user);\n// lowercase pieces are black (the AI).\n\nvar FILES = 'abcdefgh';\nvar PROMOTIONS = ['q', 'r', 'b', 'n'];\n\nfunction sqName(x, y) {\n return FILES[x] + String(8 - y);\n}\n\nfunction parseSq(name) {\n if (typeof name !== 'string' || name.length !== 2) return null;\n var x = FILES.indexOf(name[0].toLowerCase());\n var rank = Number(name[1]);\n if (x < 0 || !(rank >= 1 && rank <= 8)) return null;\n return { x: x, y: 8 - rank };\n}\n\nfunction inBounds(x, y) {\n return x >= 0 && x < 8 && y >= 0 && y < 8;\n}\n\nfunction pieceAt(squares, x, y) {\n return squares[y * 8 + x];\n}\n\nfunction withPiece(squares, x, y, ch) {\n var i = y * 8 + x;\n return squares.slice(0, i) + ch + squares.slice(i + 1);\n}\n\nfunction sideOf(ch) {\n if (!ch || ch === '.') return null;\n return ch === ch.toUpperCase() ? 'user' : 'ai';\n}\n\nfunction otherSide(side) {\n return side === 'user' ? 'ai' : 'user';\n}\n\nfunction kindOf(ch) {\n return ch && ch !== '.' ? ch.toLowerCase() : '';\n}\n\nfunction buildInitial() {\n return 'rnbqkbnr' + 'pppppppp' + '.'.repeat(32) + 'PPPPPPPP' + 'RNBQKBNR';\n}\n\nfunction findKing(squares, side) {\n var needle = side === 'user' ? 'K' : 'k';\n var i = squares.indexOf(needle);\n return i < 0 ? null : { x: i % 8, y: Math.floor(i / 8) };\n}\n\nfunction isAttacked(squares, x, y, bySide) {\n var pawn = bySide === 'user' ? 'P' : 'p';\n var pawnY = y - (bySide === 'user' ? -1 : 1);\n for (var pdx of [-1, 1]) {\n var px = x - pdx;\n if (inBounds(px, pawnY) && pieceAt(squares, px, pawnY) === pawn) return true;\n }\n\n var knight = bySide === 'user' ? 'N' : 'n';\n var knightSteps = [\n [-2, -1],\n [-2, 1],\n [-1, -2],\n [-1, 2],\n [1, -2],\n [1, 2],\n [2, -1],\n [2, 1],\n ];\n for (var n of knightSteps) {\n if (inBounds(x + n[0], y + n[1]) && pieceAt(squares, x + n[0], y + n[1]) === knight) {\n return true;\n }\n }\n\n var rays = [\n [-1, 0, 'rq'],\n [1, 0, 'rq'],\n [0, -1, 'rq'],\n [0, 1, 'rq'],\n [-1, -1, 'bq'],\n [-1, 1, 'bq'],\n [1, -1, 'bq'],\n [1, 1, 'bq'],\n ];\n for (var ray of rays) {\n var rx = x + ray[0];\n var ry = y + ray[1];\n while (inBounds(rx, ry)) {\n var seen = pieceAt(squares, rx, ry);\n if (seen !== '.') {\n if (sideOf(seen) === bySide && ray[2].indexOf(kindOf(seen)) >= 0) return true;\n break;\n }\n rx += ray[0];\n ry += ray[1];\n }\n }\n\n var king = bySide === 'user' ? 'K' : 'k';\n for (var ky = -1; ky <= 1; ky += 1) {\n for (var kx = -1; kx <= 1; kx += 1) {\n if (\n (kx !== 0 || ky !== 0) &&\n inBounds(x + kx, y + ky) &&\n pieceAt(squares, x + kx, y + ky) === king\n ) {\n return true;\n }\n }\n }\n return false;\n}\n\nfunction inCheck(squares, side) {\n var king = findKing(squares, side);\n return !king || isAttacked(squares, king.x, king.y, otherSide(side));\n}\n\nfunction pushMove(out, fromX, fromY, toX, toY, extra) {\n out.push(\n Object.assign(\n {\n from: sqName(fromX, fromY),\n to: sqName(toX, toY),\n capture: false,\n },\n extra || {},\n ),\n );\n}\n\nfunction pseudoMovesFor(squares, side, castling, enPassant) {\n var out = [];\n for (var y = 0; y < 8; y += 1) {\n for (var x = 0; x < 8; x += 1) {\n var ch = pieceAt(squares, x, y);\n if (sideOf(ch) !== side) continue;\n var kind = kindOf(ch);\n\n if (kind === 'p') {\n var dir = side === 'user' ? -1 : 1;\n var startY = side === 'user' ? 6 : 1;\n var promotionY = side === 'user' ? 0 : 7;\n var oneY = y + dir;\n if (inBounds(x, oneY) && pieceAt(squares, x, oneY) === '.') {\n if (oneY === promotionY) {\n for (var promotion of PROMOTIONS) {\n pushMove(out, x, y, x, oneY, { promotion: promotion });\n }\n } else {\n pushMove(out, x, y, x, oneY);\n var twoY = y + dir * 2;\n if (y === startY && pieceAt(squares, x, twoY) === '.') {\n pushMove(out, x, y, x, twoY, { doublePawn: true });\n }\n }\n }\n for (var dx of [-1, 1]) {\n var cx = x + dx;\n var cy = y + dir;\n if (!inBounds(cx, cy)) continue;\n var target = pieceAt(squares, cx, cy);\n var targetName = sqName(cx, cy);\n var isEp = targetName === enPassant && target === '.';\n if ((target !== '.' && sideOf(target) === otherSide(side)) || isEp) {\n if (cy === promotionY) {\n for (var capturePromotion of PROMOTIONS) {\n pushMove(out, x, y, cx, cy, {\n capture: true,\n promotion: capturePromotion,\n enPassant: isEp,\n });\n }\n } else {\n pushMove(out, x, y, cx, cy, { capture: true, enPassant: isEp });\n }\n }\n }\n continue;\n }\n\n if (kind === 'n') {\n var jumps = [\n [-2, -1],\n [-2, 1],\n [-1, -2],\n [-1, 2],\n [1, -2],\n [1, 2],\n [2, -1],\n [2, 1],\n ];\n for (var jump of jumps) {\n var nx = x + jump[0];\n var ny = y + jump[1];\n if (!inBounds(nx, ny) || sideOf(pieceAt(squares, nx, ny)) === side) continue;\n pushMove(out, x, y, nx, ny, { capture: pieceAt(squares, nx, ny) !== '.' });\n }\n continue;\n }\n\n if (kind === 'b' || kind === 'r' || kind === 'q') {\n var dirs = [];\n if (kind === 'b' || kind === 'q') dirs.push([-1, -1], [-1, 1], [1, -1], [1, 1]);\n if (kind === 'r' || kind === 'q') dirs.push([-1, 0], [1, 0], [0, -1], [0, 1]);\n for (var d of dirs) {\n var sx = x + d[0];\n var sy = y + d[1];\n while (inBounds(sx, sy)) {\n var occupant = pieceAt(squares, sx, sy);\n if (sideOf(occupant) === side) break;\n pushMove(out, x, y, sx, sy, { capture: occupant !== '.' });\n if (occupant !== '.') break;\n sx += d[0];\n sy += d[1];\n }\n }\n continue;\n }\n\n if (kind === 'k') {\n for (var kdy = -1; kdy <= 1; kdy += 1) {\n for (var kdx = -1; kdx <= 1; kdx += 1) {\n if (kdx === 0 && kdy === 0) continue;\n var ktx = x + kdx;\n var kty = y + kdy;\n if (!inBounds(ktx, kty) || sideOf(pieceAt(squares, ktx, kty)) === side) continue;\n pushMove(out, x, y, ktx, kty, { capture: pieceAt(squares, ktx, kty) !== '.' });\n }\n }\n\n var homeY = side === 'user' ? 7 : 0;\n var kingChar = side === 'user' ? 'K' : 'k';\n var rookChar = side === 'user' ? 'R' : 'r';\n var enemy = otherSide(side);\n if (x === 4 && y === homeY && ch === kingChar && !isAttacked(squares, 4, homeY, enemy)) {\n var kingRight = side === 'user' ? castling.indexOf('K') >= 0 : castling.indexOf('k') >= 0;\n if (\n kingRight &&\n pieceAt(squares, 7, homeY) === rookChar &&\n pieceAt(squares, 5, homeY) === '.' &&\n pieceAt(squares, 6, homeY) === '.' &&\n !isAttacked(squares, 5, homeY, enemy) &&\n !isAttacked(squares, 6, homeY, enemy)\n ) {\n pushMove(out, x, y, 6, homeY, { castle: 'king' });\n }\n var queenRight = side === 'user' ? castling.indexOf('Q') >= 0 : castling.indexOf('q') >= 0;\n if (\n queenRight &&\n pieceAt(squares, 0, homeY) === rookChar &&\n pieceAt(squares, 1, homeY) === '.' &&\n pieceAt(squares, 2, homeY) === '.' &&\n pieceAt(squares, 3, homeY) === '.' &&\n !isAttacked(squares, 3, homeY, enemy) &&\n !isAttacked(squares, 2, homeY, enemy)\n ) {\n pushMove(out, x, y, 2, homeY, { castle: 'queen' });\n }\n }\n }\n }\n }\n return out;\n}\n\nfunction applyUnchecked(squares, move, side) {\n var from = parseSq(move.from);\n var to = parseSq(move.to);\n var ch = pieceAt(squares, from.x, from.y);\n var next = withPiece(squares, from.x, from.y, '.');\n if (move.enPassant) {\n next = withPiece(next, to.x, from.y, '.');\n }\n if (move.castle === 'king') {\n next = withPiece(next, 7, from.y, '.');\n next = withPiece(next, 5, from.y, side === 'user' ? 'R' : 'r');\n } else if (move.castle === 'queen') {\n next = withPiece(next, 0, from.y, '.');\n next = withPiece(next, 3, from.y, side === 'user' ? 'R' : 'r');\n }\n if (move.promotion) ch = side === 'user' ? move.promotion.toUpperCase() : move.promotion;\n return withPiece(next, to.x, to.y, ch);\n}\n\nfunction legalMovesFor(squares, side, castling, enPassant) {\n return pseudoMovesFor(squares, side, castling || '', enPassant || null).filter(function (move) {\n return !inCheck(applyUnchecked(squares, move, side), side);\n });\n}\n\nfunction nextCastling(castling, squares, move) {\n var rights = castling || '';\n var ch = pieceAt(squares, parseSq(move.from).x, parseSq(move.from).y);\n if (ch === 'K') rights = rights.replace(/K|Q/g, '');\n if (ch === 'k') rights = rights.replace(/k|q/g, '');\n if (move.from === 'a1' || move.to === 'a1') rights = rights.replace('Q', '');\n if (move.from === 'h1' || move.to === 'h1') rights = rights.replace('K', '');\n if (move.from === 'a8' || move.to === 'a8') rights = rights.replace('q', '');\n if (move.from === 'h8' || move.to === 'h8') rights = rights.replace('k', '');\n return rights;\n}\n\nfunction nextEnPassant(move, side) {\n if (!move.doublePawn) return null;\n var from = parseSq(move.from);\n var to = parseSq(move.to);\n return sqName(from.x, (from.y + to.y) / 2);\n}\n\nfunction isInsufficientMaterial(squares) {\n var pieces = [];\n for (var i = 0; i < squares.length; i += 1) {\n var ch = squares[i];\n if (ch !== '.' && kindOf(ch) !== 'k') pieces.push({ ch: ch, x: i % 8, y: Math.floor(i / 8) });\n }\n if (pieces.length === 0) return true;\n if (pieces.length === 1 && (kindOf(pieces[0].ch) === 'b' || kindOf(pieces[0].ch) === 'n')) {\n return true;\n }\n if (\n pieces.length > 0 &&\n pieces.every(function (p) {\n return kindOf(p.ch) === 'b';\n })\n ) {\n var color = (pieces[0].x + pieces[0].y) % 2;\n return pieces.every(function (p) {\n return (p.x + p.y) % 2 === color;\n });\n }\n return false;\n}\n\nfunction positionKey(squares, side, castling, enPassant) {\n var effectiveEnPassant =\n enPassant &&\n legalMovesFor(squares, side, castling, enPassant).some(function (move) {\n return move.enPassant;\n })\n ? enPassant\n : '-';\n return [squares, side, castling || '-', effectiveEnPassant].join('|');\n}\n\nfunction statusAfter(squares, sideToMove, castling, enPassant) {\n if (isInsufficientMaterial(squares)) return 'draw';\n var moves = legalMovesFor(squares, sideToMove, castling, enPassant);\n if (moves.length > 0) return 'playing';\n if (!inCheck(squares, sideToMove)) return 'draw';\n return sideToMove === 'user' ? 'ai_won' : 'user_won';\n}\n\nfunction describeMove(move) {\n if (move.castle === 'king') return move.from + '-' + move.to + ' (O-O)';\n if (move.castle === 'queen') return move.from + '-' + move.to + ' (O-O-O)';\n var text = move.from + (move.capture ? 'x' : '-') + move.to;\n if (move.promotion) text += '=' + move.promotion.toUpperCase();\n if (move.enPassant) text += ' e.p.';\n return text;\n}\n\nfunction renderAscii(squares) {\n var lines = [' a b c d e f g h'];\n for (var y = 0; y < 8; y += 1) {\n var row = String(8 - y);\n for (var x = 0; x < 8; x += 1) row += ' ' + pieceAt(squares, x, y);\n lines.push(row + ' ' + String(8 - y));\n }\n lines.push(' a b c d e f g h');\n lines.push('Uppercase = white (user). Lowercase = black (you).');\n return lines.join('\\n');\n}\n// ── chess-rules-end ──\n\nconst STATE_FILE = 'game.json';\nconst SIDE_NAMES = { user: 'white', ai: 'black' };\n\ninterface ChessMove {\n from: string;\n to: string;\n capture: boolean;\n promotion?: string;\n doublePawn?: boolean;\n enPassant?: boolean;\n castle?: string;\n}\n\ninterface GameState {\n version: number;\n squares: string;\n turn: 'user' | 'ai';\n status: 'playing' | 'user_won' | 'ai_won' | 'draw';\n castling: string;\n enPassant: string | null;\n halfmoveClock: number;\n fullmoveNumber: number;\n positionHistory: string[];\n legalMoves: ChessMove[];\n moveLog: Array<{\n by: 'user' | 'ai';\n from: string;\n to: string;\n promotion?: string;\n notation: string;\n at: string;\n moveThought?: string;\n }>;\n lastMove: {\n by: 'user' | 'ai';\n from: string;\n to: string;\n promotion?: string;\n notation: string;\n } | null;\n lastMoveThought: string;\n updatedAt: string;\n}\n\nfunction freshState(): GameState {\n const squares = buildInitial();\n const castling = 'KQkq';\n return {\n version: 1,\n squares,\n turn: 'user',\n status: 'playing',\n castling,\n enPassant: null,\n halfmoveClock: 0,\n fullmoveNumber: 1,\n positionHistory: [positionKey(squares, 'user', castling, null)],\n legalMoves: legalMovesFor(squares, 'user', castling, null),\n moveLog: [],\n lastMove: null,\n lastMoveThought: '',\n updatedAt: new Date().toISOString(),\n };\n}\n\nasync function load(): Promise<GameState> {\n let raw: string;\n try {\n raw = await gezel.fs.read(STATE_FILE);\n } catch {\n return freshState();\n }\n const parsed = JSON.parse(raw) as Partial<GameState>;\n if (typeof parsed.squares !== 'string' || parsed.squares.length !== 64) {\n throw new Error(`${STATE_FILE} is corrupt; call action:'new_game' to reset.`);\n }\n return {\n ...freshState(),\n ...parsed,\n castling: typeof parsed.castling === 'string' ? parsed.castling : '',\n enPassant: parsed.enPassant ?? null,\n } as GameState;\n}\n\nasync function persist(state: GameState): Promise<GameState> {\n state.legalMoves =\n state.status === 'playing'\n ? legalMovesFor(state.squares, state.turn, state.castling, state.enPassant)\n : [];\n state.updatedAt = new Date().toISOString();\n await gezel.fs.write(STATE_FILE, `${JSON.stringify(state, null, 2)}\\n`);\n return state;\n}\n\nfunction renderLegal(state: GameState): string {\n if (state.status !== 'playing') return '(game over)';\n return state.legalMoves.map(describeMove).join(', ') || '(none)';\n}\n\nfunction summarize(state: GameState): string {\n if (state.status === 'user_won') return 'Checkmate — the user (white) won.';\n if (state.status === 'ai_won') return 'Checkmate — you (black) won.';\n if (state.status === 'draw') return 'Game over — draw.';\n const check = inCheck(state.squares, state.turn) ? ' The king is in check.' : '';\n return `Move ${state.fullmoveNumber}: ${SIDE_NAMES[state.turn]} (${state.turn}) to move.${check}`;\n}\n\nfunction applyTurn(\n state: GameState,\n by: 'user' | 'ai',\n moveThought?: string,\n): { state: GameState; move: ChessMove } {\n if (state.status !== 'playing') {\n throw new Error(`The game is over (${state.status}). Call action:'new_game' to start another.`);\n }\n if (state.turn !== by) {\n throw new Error(by === 'ai' ? \"It's not your turn yet.\" : 'The opponent is still to move.');\n }\n if (!input.from || !input.to) throw new Error(\"Pass 'from' and 'to' squares.\");\n const wantedPromotion = (input.promotion || 'q').toLowerCase();\n const candidates = state.legalMoves.filter(\n (move) =>\n move.from === input.from!.toLowerCase() &&\n move.to === input.to!.toLowerCase(),\n );\n const move =\n candidates.find((candidate) => (candidate.promotion || 'q') === wantedPromotion) ??\n candidates.find((candidate) => !candidate.promotion);\n if (!move) {\n throw new Error(\n `Illegal move ${input.from}-${input.to}. Legal moves for ${SIDE_NAMES[by]}: ${renderLegal(state)}`,\n );\n }\n\n const movingPiece = pieceAt(\n state.squares,\n parseSq(move.from)!.x,\n parseSq(move.from)!.y,\n );\n const oldSquares = state.squares;\n state.castling = nextCastling(state.castling, oldSquares, move);\n state.squares = applyUnchecked(oldSquares, move, by);\n state.enPassant = nextEnPassant(move, by);\n state.halfmoveClock =\n kindOf(movingPiece) === 'p' || move.capture ? 0 : state.halfmoveClock + 1;\n if (by === 'ai') state.fullmoveNumber += 1;\n state.turn = otherSide(by) as 'user' | 'ai';\n const key = positionKey(state.squares, state.turn, state.castling, state.enPassant);\n state.positionHistory.push(key);\n state.status = statusAfter(\n state.squares,\n state.turn,\n state.castling,\n state.enPassant,\n ) as GameState['status'];\n if (\n state.status === 'playing' &&\n (state.halfmoveClock >= 100 ||\n state.positionHistory.filter((candidate) => candidate === key).length >= 3)\n ) {\n state.status = 'draw';\n }\n\n const notation = describeMove(move);\n const entry = {\n by,\n from: move.from,\n to: move.to,\n ...(move.promotion ? { promotion: move.promotion } : {}),\n notation,\n at: new Date().toISOString(),\n ...(moveThought ? { moveThought } : {}),\n };\n state.moveLog.push(entry);\n state.lastMove = {\n by,\n from: move.from,\n to: move.to,\n ...(move.promotion ? { promotion: move.promotion } : {}),\n notation,\n };\n if (by === 'ai' && moveThought) state.lastMoveThought = moveThought;\n return { state, move };\n}\n\nlet state = await load();\nlet lastMoveText = state.lastMove?.notation ?? '(none)';\n\nif (input.action === 'new_game') {\n state = await persist(freshState());\n lastMoveText = '(none)';\n} else if (input.action === 'user_move' || input.action === 'ai_move') {\n const by = input.action === 'user_move' ? 'user' : 'ai';\n const moveThought = input.moveThought?.trim().slice(0, 140);\n const applied = applyTurn(state, by, moveThought);\n state = await persist(applied.state);\n lastMoveText = describeMove(applied.move);\n} else if (input.action !== 'state' && input.action !== 'board') {\n throw new Error(`Unknown action '${input.action}'. Use state, board, user_move, ai_move, or new_game.`);\n}\n\ngezel.output({\n board:\n `${renderAscii(state.squares)}\\nTurn: ${SIDE_NAMES[state.turn]} (${state.turn}).` +\n `${inCheck(state.squares, state.turn) && state.status === 'playing' ? ' CHECK.' : ''}\\n` +\n `Legal moves: ${renderLegal(state)}`,\n turn: state.turn,\n status: state.status,\n lastMove: lastMoveText,\n legalMoves: renderLegal(state),\n summary: summarize(state),\n});\n"},"tools":[{"name":"get_board","description":"See the authoritative chess position, whose turn it is, and every legal move.","script":"game-store","inputs":{"type":"object","properties":{}},"bind":{"action":"board"},"state":true},{"name":"make_move","description":"Play your black move. Pass from/to; for promotion optionally choose 'q', 'r', 'b', or 'n'. Include a short moveThought for the board.","script":"game-store","inputs":{"type":"object","properties":{"from":{"type":"string","description":"Origin square, e.g. 'e7'."},"to":{"type":"string","description":"Destination square, e.g. 'e5'."},"promotion":{"type":"string","enum":["q","r","b","n"],"description":"Promotion piece. Defaults to queen."},"moveThought":{"type":"string","description":"A short line of table talk (max 140 chars)."}},"required":["from","to"]},"bind":{"action":"ai_move"},"turn":{"say":"moveThought","fallback":"Move made — your turn."}},{"name":"user_move","description":"The user's white move, played from the chess board.","script":"game-store","inputs":{"type":"object","properties":{"from":{"type":"string"},"to":{"type":"string"},"promotion":{"type":"string","enum":["q","r","b","n"]}},"required":["from","to"]},"bind":{"action":"user_move"},"reaction":{"gezel":"chess-player","prompt":"Your opponent played {{output.lastMove}}. Status: {{output.status}}. Board now:\n{{output.board}}\nThe board and Legal moves line come directly from the chess engine and are always correct. Do not re-derive the position, dispute a listed move, or invent a move outside that list. Spend your thought on choosing among the listed legal moves.\nStyle: {{playStyle}}. In Opponent style, do not volunteer advice or reveal the user’s available moves, threats, tactics, or your plan; comment only about your own move or the atmosphere. In Instructor style, offer at most one brief teaching observation without choosing the user’s move. Answer strategy questions when asked.\nAct on this latest position. If the game is over, do not move — give one gracious line and offer a new game. Otherwise choose a strong legal move and play it with make_move, including a short {{personality}} moveThought that follows the selected style. If make_move rejects it, choose one move verbatim from the legal list in the error and retry. After moving, reply with ONE short line of table talk.","hideSeed":true,"standalone":true,"turn":{"tool":"make_move","when":{"op":"equals","field":"status","value":"playing"}}}},{"name":"new_game","description":"Reset the chess board to the standard opening position.","script":"game-store","inputs":{"type":"object","properties":{}},"bind":{"action":"new_game"}}],"pages":{"entry":"board/index.html","api":1,"reads":[{"source":"workspace","path":"game.json"}],"tools":["user_move","new_game"]},"schedules":[],"workspaceSeed":["game.json"],"artifactsSeed":[],"availableVersions":["1.0.9","1.0.8","1.0.7","1.0.6","1.0.5","1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"client-delivery","name":"Client Delivery","description":"Deliver client work on time, with every handoff tracked. A planner keeps each client project with its milestones, counts how long every approval has waited on the client, names what is late, and drafts the weekly status each client gets.","tags":["agency","consulting","deliverables","milestones","approvals","status-report","small-business"],"category":"business","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.0.0","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"studio":{"type":"string","title":"Who delivers the work?","description":"e.g. 'Fernwood Studio, a six-person design agency', 'a solo brand consultant'.","default":"the studio"}},"required":["studio"]},"nameTemplate":"Client Delivery","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"planner","voorman":true},{"templateId":"copywriter","voorman":false}],"toolsets":[],"craftbooks":["status-report","meeting-notes-to-actions","proposal-sow","case-study"],"scripts":{"delivery-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { type RosterRecord, rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'delivery-store',\n description:\n \"Read and update client delivery: projects.json and milestones.json (rosters). action:'status' for what is waiting on clients, late and due soon; 'report' for a project's weekly status; 'add_project' and 'add_milestone' to save one (an existing title is updated, never duplicated; shiftDays moves dates by a number of days); 'set_status' to move a milestone between planned, in-progress, waiting (sent to the client for approval) and approved; 'list' for every project and milestone.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'status', 'report', 'add_project', 'add_milestone', 'set_status', or 'list'.\",\n required: true,\n },\n id: {\n type: 'string',\n description: \"A milestone id like 'ms-4' (for add_project, a project id like 'pr-2').\",\n },\n title: {\n type: 'string',\n description: \"The milestone's (or for add_project, the project's) title. Also finds it when no id is given.\",\n },\n project: { type: 'string', description: \"The project's id or name, e.g. 'pr-1' or 'Juniper website'.\" },\n client: { type: 'string', description: 'The client, e.g. Juniper Press.' },\n contact: { type: 'string', description: 'Who approves on the client side.' },\n lead: { type: 'string', description: \"Who leads the project on the studio's side.\" },\n owner: { type: 'string', description: 'Who owns the milestone.' },\n dueAt: { type: 'string', description: 'The due date, YYYY-MM-DD.' },\n shiftDays: {\n type: 'number',\n description:\n \"Move the due date by this many days (negative pulls it in). On a project, moves the project's date and every milestone not yet approved.\",\n },\n status: { type: 'string', description: 'A project: proposed, active, on-hold, or done. A milestone: planned, in-progress, waiting, or approved.' },\n note: { type: 'string', description: 'What happened, with the client’s feedback in their words.' },\n withinDays: { type: 'number', description: 'How many days ahead counts as due soon (default 14).' },\n },\n outputs: {\n active: { type: 'number', description: 'Active projects.' },\n waiting: { type: 'number', description: 'Milestones waiting on a client.' },\n late: { type: 'number', description: 'Milestones past due and not with the client.' },\n dueSoon: { type: 'number', description: 'Open milestones due within the window.' },\n summary: { type: 'string', description: 'What changed first, then the delivery picture (or the report or listing).' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── delivery-rules-start ──\n// Pure derivations: local calendar days, date shifts, milestone and project\n// health, and the lines the crew reads. Kept self-contained between these\n// sentinels so tests (and the page's demo) execute the shipped bytes.\nvar DAY_MS = 86400000;\nvar PROJECT_STAGES = ['proposed', 'active', 'on-hold', 'done'];\nvar MILESTONE_STAGES = ['planned', 'in-progress', 'waiting', 'approved'];\n\nfunction pad(n) {\n return n < 10 ? '0' + n : String(n);\n}\nfunction localDay(ms) {\n var d = new Date(ms);\n return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());\n}\nfunction isDay(text) {\n return /^\\d{4}-\\d{2}-\\d{2}$/.test(String(text || ''));\n}\nfunction normalizeDate(text, nowMs) {\n var raw = String(text || '').trim();\n if (isDay(raw)) return raw;\n // Only something that reads as a date: a month name with a day, or numbers like 12/10.\n if (!/\\b(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\\.?\\s+\\d|\\d\\s+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)|\\d{1,4}[/.-]\\d{1,2}[/.-]\\d{1,4}/i.test(raw)) return null;\n if (/\\d{4}/.test(raw)) {\n var full = Date.parse(raw);\n return isFinite(full) ? localDay(full) : null;\n }\n // 'December 10' names the next December 10, not one in 2001.\n var now = new Date(nowMs || Date.now());\n var parsed = Date.parse(raw + ' ' + now.getFullYear());\n if (!isFinite(parsed)) return null;\n if (parsed < now.getTime() - 31 * DAY_MS) parsed = Date.parse(raw + ' ' + (now.getFullYear() + 1));\n return localDay(parsed);\n}\nfunction daysLeft(day, nowMs) {\n var due = Date.parse(String(day).slice(0, 10) + 'T00:00:00');\n var today = Date.parse(localDay(nowMs) + 'T00:00:00');\n return Math.round((due - today) / DAY_MS);\n}\nfunction shiftDay(day, days) {\n var d = new Date(String(day).slice(0, 10) + 'T12:00:00');\n d.setDate(d.getDate() + Math.round(days));\n return localDay(d.getTime());\n}\nfunction when(days) {\n if (days < 0) return -days + (days === -1 ? ' day late' : ' days late');\n if (days === 0) return 'due today';\n return 'due in ' + days + (days === 1 ? ' day' : ' days');\n}\nfunction key(text) {\n return String(text || '')\n .normalize('NFD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9&]+/g, ' ')\n .trim();\n}\n// 'exact', 'partial' (the title starts with the words given, contains them whole, or holds every word given), or ''.\nfunction titleMatch(title, wanted) {\n var have = key(title);\n var want = key(wanted);\n if (!have || !want) return '';\n if (have === want) return 'exact';\n if ((' ' + have).indexOf(' ' + want) >= 0 || (' ' + want + ' ').indexOf(' ' + have + ' ') >= 0) return 'partial';\n var words = want.split(' ').filter(function (w) {\n return w.length > 2 && ['the', 'and', 'for'].indexOf(w) < 0;\n });\n return words.length && words.every(function (w) { return (' ' + have).indexOf(' ' + w) >= 0; }) ? 'partial' : '';\n}\nfunction waitedDays(m, nowMs) {\n return m.fields && isDay(m.fields.sentAt) ? Math.max(0, -daysLeft(m.fields.sentAt, nowMs)) : 0;\n}\nfunction isLate(m, nowMs) {\n return m.status !== 'approved' && m.status !== 'waiting' && isDay(m.fields && m.fields.dueAt) && daysLeft(m.fields.dueAt, nowMs) < 0;\n}\nfunction milestonesOf(projectId, milestones) {\n return milestones\n .filter(function (m) { return m.fields && m.fields.projectId === projectId; })\n .sort(function (a, b) { return String(a.fields.dueAt || '9999').localeCompare(String(b.fields.dueAt || '9999')); });\n}\nfunction health(project, milestones, nowMs) {\n if (project.status === 'done') return 'done';\n var mine = milestonesOf(project.id, milestones);\n if (mine.some(function (m) { return isLate(m, nowMs); })) return 'late';\n if (\n mine.some(function (m) {\n return m.status === 'waiting' && (waitedDays(m, nowMs) >= 5 || (isDay(m.fields.dueAt) && daysLeft(m.fields.dueAt, nowMs) < 0));\n })\n ) return 'at risk';\n return 'on track';\n}\nfunction milestoneLine(m, project, nowMs) {\n var f = m.fields || {};\n var head = f.title + ' (' + m.id + ', ' + (project ? project.fields.title : 'no project') + ')';\n if (m.status === 'approved') return head + ' approved' + (f.approvedAt ? ' ' + f.approvedAt : '');\n if (m.status === 'waiting') {\n var waited = waitedDays(m, nowMs);\n return (\n head + ' with ' + (f.approver || (project && project.fields.contact) || 'the client') + ' for approval ' +\n (waited === 0 ? 'since today' : 'for ' + waited + (waited === 1 ? ' day' : ' days')) +\n ', round ' + (f.rounds || 1) + (isDay(f.dueAt) ? ', ' + when(daysLeft(f.dueAt, nowMs)) : '')\n );\n }\n return head + ' ' + m.status + (isDay(f.dueAt) ? ', ' + when(daysLeft(f.dueAt, nowMs)) + ' (' + f.dueAt + ')' : ', no date') + (f.owner ? ', owner ' + f.owner : '');\n}\nfunction deliveryPicture(projects, milestones, nowMs, withinDays) {\n var byId = {};\n projects.forEach(function (p) { byId[p.id] = p; });\n var active = projects.filter(function (p) { return p.status === 'active'; });\n var live = milestones.filter(function (m) {\n var p = byId[m.fields && m.fields.projectId];\n return p && p.status === 'active' && m.status !== 'approved';\n });\n var waiting = live\n .filter(function (m) { return m.status === 'waiting'; })\n .sort(function (a, b) { return waitedDays(b, nowMs) - waitedDays(a, nowMs); });\n var late = live.filter(function (m) { return isLate(m, nowMs); });\n // One list, late first: asked what's due, a model read a separate late list as out of scope.\n var due = live\n .filter(function (m) { return isDay(m.fields.dueAt) && daysLeft(m.fields.dueAt, nowMs) <= withinDays; })\n .sort(function (a, b) { return String(a.fields.dueAt).localeCompare(String(b.fields.dueAt)); });\n var line = function (m) { return milestoneLine(m, byId[m.fields.projectId], nowMs); };\n var parts = [\n active.length + (active.length === 1 ? ' active project' : ' active projects') + ', ' + waiting.length + ' waiting on clients, ' + late.length + ' late on our side.',\n ];\n parts.push(waiting.length ? 'Waiting on clients, longest first: ' + waiting.map(line).join(' | ') + '.' : 'Nothing is waiting on a client.');\n parts.push(\n due.length\n ? 'Due within ' + withinDays + ' days, late first: ' + due.map(line).join(' | ') + '.'\n : 'Nothing due in the next ' + withinDays + ' days.',\n );\n parts.push(\n active.length\n ? 'Projects: ' + active.map(function (p) {\n var next = milestonesOf(p.id, milestones).filter(function (m) { return m.status !== 'approved'; })[0];\n return p.fields.title + ' (' + p.id + ', ' + (p.fields.client || 'no client') + (p.fields.lead ? ', lead ' + p.fields.lead : '') + (isDay(p.fields.dueAt) ? ', due ' + p.fields.dueAt : '') + ') ' + health(p, milestones, nowMs) + (next ? '; next: ' + next.fields.title + ' (' + next.status + ')' : '; every milestone approved');\n }).join(' | ') + '.'\n : 'No active projects.',\n );\n var other = projects.filter(function (p) { return p.status !== 'active'; });\n if (other.length) parts.push('Also: ' + other.map(function (p) { return p.fields.title + ' (' + p.id + ', ' + p.status + ')'; }).join(', ') + '.');\n return { active: active.length, waiting: waiting.length, late: late.length, dueSoon: due.length, summary: parts.join(' ') };\n}\nfunction weeklyReport(project, milestones, nowMs) {\n var mine = milestonesOf(project.id, milestones);\n var weekAgo = localDay(nowMs - 7 * DAY_MS);\n var done = mine.filter(function (m) { return m.status === 'approved' && String(m.fields.approvedAt || '') >= weekAgo; });\n var waiting = mine.filter(function (m) { return m.status === 'waiting'; });\n var working = mine.filter(function (m) { return m.status === 'in-progress'; });\n var next = mine.filter(function (m) { return m.status === 'planned'; }).slice(0, 2);\n var client = project.fields.client || 'the client';\n var list = function (items, fn) { return items.length ? items.map(fn).join('; ') : 'nothing'; };\n return (\n project.fields.title + ' (' + project.id + ') for ' + client + ', week of ' + localDay(nowMs) + ', ' + health(project, milestones, nowMs) + '. ' +\n 'Approved in the last 7 days: ' + list(done, function (m) { return m.fields.title + ' (' + m.fields.approvedAt + ')'; }) + '. ' +\n 'Waiting on ' + client + ': ' + list(waiting, function (m) { return m.fields.title + ', sent ' + (m.fields.sentAt || 'recently') + ', round ' + (m.fields.rounds || 1); }) + '. ' +\n 'In progress: ' + list(working, function (m) { return m.fields.title + (isDay(m.fields.dueAt) ? ', ' + when(daysLeft(m.fields.dueAt, nowMs)) + ' (' + m.fields.dueAt + ')' : '') + (m.fields.owner ? ', ' + m.fields.owner : ''); }) + '. ' +\n 'Next up: ' + list(next, function (m) { return m.fields.title + (isDay(m.fields.dueAt) ? ', due ' + m.fields.dueAt : ''); }) + '.' +\n (isDay(project.fields.dueAt) ? ' Project due ' + project.fields.dueAt + '.' : '')\n );\n}\n// ── delivery-rules-end ──\n\nconst projects = rosterStore(gezel.fs, 'projects.json', { stages: ['proposed', 'active', 'on-hold', 'done'], idPrefix: 'pr' });\nconst milestones = rosterStore(gezel.fs, 'milestones.json', {\n stages: ['planned', 'in-progress', 'waiting', 'approved'],\n idPrefix: 'ms',\n});\n\nfunction choose(all: RosterRecord[], wanted: string, what: string, label: (r: RosterRecord) => string): RosterRecord | null {\n const exact = all.filter((r) => titleMatch(r.fields.title, wanted) === 'exact');\n if (exact.length === 1) return exact[0]!;\n const partial = exact.length > 1 ? exact : all.filter((r) => titleMatch(r.fields.title, wanted) === 'partial' || titleMatch(r.fields.client, wanted) === 'exact');\n if (partial.length === 1) return partial[0]!;\n if (partial.length > 1) throw new Error('More than one ' + what + \" matches '\" + wanted + \"': \" + partial.map(label).join(', ') + '. Pass id.');\n return null;\n}\nasync function resolveProject(text: string | undefined): Promise<RosterRecord> {\n const all = await projects.list();\n if (!text) throw new Error(\"Pass 'project' (an id like 'pr-1' or its name). Projects: \" + (all.map((p) => p.id + ' ' + String(p.fields.title)).join(', ') || 'none') + '.');\n const byId = all.find((p) => p.id === text.trim());\n if (byId) return byId;\n // 'Juniper' means the client's active project before its proposed or finished ones.\n const label = (p: RosterRecord) => p.id + ' ' + String(p.fields.title);\n const found = choose(all.filter((p) => p.status === 'active'), text, 'project', label) ?? choose(all, text, 'project', label);\n if (found) return found;\n throw new Error(\"No project matches '\" + text + \"'. Projects: \" + (all.map((p) => p.id + ' ' + String(p.fields.title)).join(', ') || 'none') + '.');\n}\nasync function resolveMilestone(): Promise<RosterRecord> {\n const all = await milestones.list();\n if (input.id) {\n const byId = all.find((m) => m.id === input.id);\n if (byId) return byId;\n throw new Error(\"No milestone with id '\" + input.id + \"'.\");\n }\n if (!input.title) throw new Error(\"Pass the milestone's 'id' (e.g. 'ms-4') or 'title'.\");\n const scoped = input.project ? milestonesOf((await resolveProject(input.project)).id, all) : all;\n const names: Record<string, string> = {};\n (await projects.list()).forEach((p) => (names[p.id] = String(p.fields.title)));\n const found = choose(scoped, input.title, 'milestone', (m) => m.id + ' ' + String(m.fields.title) + ' (' + names[String(m.fields.projectId)] + ')');\n if (found) return found;\n throw new Error(\"No milestone matches '\" + input.title + \"'. Call list_client_projects to see them, or add it with add_milestone.\");\n}\nfunction checkDate(text: string | undefined, label: string): string | null {\n if (!text) return null;\n const day = normalizeDate(text);\n if (!day) throw new Error(label + \" must be a date, e.g. '2026-12-01'.\");\n return day;\n}\nfunction shift(input: { shiftDays?: number }): number {\n return typeof input.shiftDays === 'number' && isFinite(input.shiftDays) ? Math.round(input.shiftDays) : 0;\n}\n\nconst today = localDay(Date.now());\nconst withinDays = typeof input.withinDays === 'number' && input.withinDays > 0 ? Math.round(input.withinDays) : 14;\nlet note = '';\nlet reply = '';\n\nif (input.action === 'add_project') {\n if (!input.title && !input.id) throw new Error(\"add_project needs 'title'.\");\n if (input.status && !PROJECT_STAGES.includes(input.status)) throw new Error('A project is proposed, active, on-hold, or done.');\n const all = await projects.list();\n const existing = input.id ? all.find((p) => p.id === input.id) : all.find((p) => titleMatch(p.fields.title, input.title) === 'exact');\n if (input.id && !existing) throw new Error(\"No project with id '\" + input.id + \"'.\");\n const dueAt = checkDate(input.dueAt, 'dueAt');\n const fields: Record<string, unknown> = {\n ...(input.id && input.title ? { title: input.title.trim() } : {}),\n ...(input.client ? { client: input.client.trim() } : {}),\n ...(input.contact ? { contact: input.contact.trim() } : {}),\n ...(input.lead ? { lead: input.lead.trim() } : {}),\n ...(dueAt ? { dueAt } : {}),\n ...(input.note ? { notes: input.note.trim() } : {}),\n };\n const days = shift(input);\n if (existing) {\n if (days && !dueAt && isDay(existing.fields.dueAt)) fields.dueAt = shiftDay(String(existing.fields.dueAt), days);\n await projects.update(existing.id, { fields });\n if (input.status && input.status !== existing.status) await projects.transition(existing.id, input.status, input.note ? { note: input.note } : {});\n let moved = 0;\n if (days) {\n for (const m of milestonesOf(existing.id, await milestones.list())) {\n if (m.status === 'approved' || !isDay(m.fields.dueAt)) continue;\n await milestones.update(m.id, { fields: { dueAt: shiftDay(String(m.fields.dueAt), days) }, note: 'Moved ' + days + ' days with the project' });\n moved++;\n }\n }\n note =\n 'Updated ' + String(fields.title ?? existing.fields.title) + '.' +\n (days ? ' Moved ' + (days > 0 ? 'out' : 'in') + ' by ' + Math.abs(days) + (Math.abs(days) === 1 ? ' day' : ' days') + (isDay(fields.dueAt) ? ', now due ' + String(fields.dueAt) : '') + ', with ' + moved + (moved === 1 ? ' open milestone.' : ' open milestones.') : '');\n } else {\n if (!input.client) {\n const near = all.filter((p) => titleMatch(p.fields.title, input.title) === 'partial');\n throw new Error(\n (near.length ? \"No project is titled exactly '\" + input.title + \"'. Did you mean \" + near.map((p) => p.id + ' ' + String(p.fields.title)).join(' or ') + '? Pass its id to change it, or ' : 'A new project needs ') +\n \"'client' to add a new one.\",\n );\n }\n const record = await projects.add({ status: input.status ?? 'active', fields: { title: String(input.title).trim(), ...fields } });\n note = 'Added ' + record.id + ', ' + String(input.title).trim() + ' for ' + input.client.trim() + '.';\n }\n} else if (input.action === 'add_milestone') {\n if (!input.title && !input.id) throw new Error(\"add_milestone needs 'title'.\");\n if (input.status && !MILESTONE_STAGES.includes(input.status)) throw new Error('A milestone is planned, in-progress, waiting, or approved.');\n const all = await milestones.list();\n let existing: RosterRecord | undefined;\n let project: RosterRecord | null = null;\n if (input.id) {\n existing = all.find((m) => m.id === input.id);\n if (!existing) throw new Error(\"No milestone with id '\" + input.id + \"'.\");\n } else {\n project = input.project ? await resolveProject(input.project) : null;\n const pool = project ? milestonesOf(project.id, all) : all;\n const same = pool.filter((m) => titleMatch(m.fields.title, input.title) === 'exact');\n if (same.length > 1) throw new Error(\"More than one milestone is titled '\" + input.title + \"'. Pass project or id.\");\n existing = same[0];\n }\n const dueAt = checkDate(input.dueAt, 'dueAt');\n const days = shift(input);\n const fields: Record<string, unknown> = {\n ...(input.id && input.title ? { title: input.title.trim() } : {}),\n ...(dueAt ? { dueAt } : {}),\n ...(input.owner ? { owner: input.owner.trim() } : {}),\n ...(input.note ? { notes: input.note.trim() } : {}),\n };\n if (existing) {\n if (days && !dueAt) {\n if (!isDay(existing.fields.dueAt)) throw new Error(String(existing.fields.title) + \" has no due date to move; pass 'dueAt'.\");\n fields.dueAt = shiftDay(String(existing.fields.dueAt), days);\n }\n await milestones.update(existing.id, { fields, ...(days ? { note: 'Moved ' + days + ' days' } : {}) });\n if (input.status && input.status !== existing.status) await milestones.transition(existing.id, input.status, input.note ? { note: input.note } : {});\n note =\n 'Updated ' + String(fields.title ?? existing.fields.title) + (isDay(fields.dueAt) ? ', now due ' + String(fields.dueAt) : '') +\n (days ? ' (' + (days > 0 ? 'moved out ' : 'pulled in ') + Math.abs(days) + (Math.abs(days) === 1 ? ' day' : ' days') + ')' : '') + '.';\n } else {\n if (!project) throw new Error(\"A new milestone needs 'project' (its id or name).\");\n if (!dueAt) throw new Error(\"A new milestone needs 'dueAt' (YYYY-MM-DD).\");\n const record = await milestones.add({\n status: input.status ?? 'planned',\n fields: { projectId: project.id, title: String(input.title).trim(), rounds: 0, ...fields },\n });\n note = 'Added ' + record.id + ', ' + String(input.title).trim() + ' on ' + String(project.fields.title) + ', due ' + dueAt + '.';\n }\n} else if (input.action === 'set_status') {\n if (!input.status || !MILESTONE_STAGES.includes(input.status)) throw new Error(\"set_status needs status 'planned', 'in-progress', 'waiting', or 'approved'.\");\n const m = await resolveMilestone();\n const project = (await projects.get(String(m.fields.projectId))) ?? null;\n const fields: Record<string, unknown> = {};\n if (input.status === 'waiting' && m.status !== 'waiting') {\n fields.sentAt = today;\n fields.rounds = (Number(m.fields.rounds) || 0) + 1;\n fields.approver = input.contact ? input.contact.trim() : String(project?.fields.contact ?? m.fields.approver ?? '') || undefined;\n }\n if (input.status === 'approved' && m.status !== 'approved') fields.approvedAt = today;\n if (m.status === 'waiting' && input.status === 'in-progress' && input.note) fields.feedback = input.note.trim();\n if (Object.keys(fields).length) await milestones.update(m.id, { fields });\n if (input.status !== m.status) await milestones.transition(m.id, input.status, input.note ? { note: input.note } : {});\n const title = String(m.fields.title);\n const on = project ? ' (' + String(project.fields.title) + ')' : '';\n note =\n m.status === input.status\n ? title + on + ' was already ' + input.status + '.'\n : input.status === 'approved'\n ? title + on + ' is approved.'\n : input.status === 'waiting'\n ? title + on + ' went to ' + String(fields.approver || 'the client') + ' for approval, round ' + String(fields.rounds) + '.'\n : m.status === 'waiting' && input.status === 'in-progress'\n ? title + on + ' came back with changes and is in progress again' + (input.note ? ': ' + input.note.trim() : '') + '.'\n : title + on + ' is now ' + input.status + '.';\n} else if (input.action === 'report') {\n const all = await projects.list();\n const ms = await milestones.list();\n const chosen = input.project ? [await resolveProject(input.project)] : all.filter((p) => p.status === 'active');\n reply = chosen.map((p) => weeklyReport(p, ms, Date.now())).join('\\n\\n') || 'No active projects to report on.';\n} else if (input.action === 'list') {\n const ms = await milestones.list();\n reply =\n (await projects.list())\n .map(\n (p) =>\n '[' + p.status + '] ' + String(p.fields.title) + ' (' + p.id + ', ' + String(p.fields.client ?? 'no client') + (p.fields.lead ? ', lead ' + String(p.fields.lead) : '') + (isDay(p.fields.dueAt) ? ', due ' + String(p.fields.dueAt) : '') + '): ' +\n (milestonesOf(p.id, ms).map((m) => milestoneLine(m, p, Date.now())).join(' | ') || 'no milestones yet'),\n )\n .join('\\n') || 'No projects yet.';\n} else if (input.action !== 'status') {\n throw new Error(\"Unknown action '\" + input.action + \"'. Use status, report, add_project, add_milestone, set_status, or list.\");\n}\n\nconst view = deliveryPicture(await projects.list(), await milestones.list(), Date.now(), withinDays);\ngezel.output({\n active: view.active,\n waiting: view.waiting,\n late: view.late,\n dueSoon: view.dueSoon,\n summary: reply || (note ? note + ' ' : '') + view.summary,\n});\n"},"tools":[{"name":"delivery_status","description":"The delivery picture in one read, with ids: every approval waiting on a client and for how long, everything due in the next 14 days with late items first, and each active project's health and next milestone. Call it first when asked what's waiting, late or due.","script":"delivery-store","inputs":{"type":"object","properties":{"withinDays":{"type":"number"}}},"bind":{"action":"status"},"state":true},{"name":"weekly_report","description":"This week's status for one client project, or every active one: what was approved, what waits on the client, what is in progress, and what comes next. Call it before drafting a status update and write only from it.","script":"delivery-store","inputs":{"type":"object","properties":{"project":{"type":"string"}}},"bind":{"action":"report"}},{"name":"add_project","description":"Save a client project: title, client, the client's approver, the studio lead, and the due date (YYYY-MM-DD). An existing title is updated, never duplicated. When the whole project slips, pass shiftDays (days later; negative for earlier) and the board moves its date and every milestone not yet approved. Call it as soon as a project is mentioned, before you describe it.","script":"delivery-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"client":{"type":"string"},"contact":{"type":"string"},"lead":{"type":"string"},"dueAt":{"type":"string"},"status":{"type":"string","enum":["proposed","active","on-hold","done"]},"shiftDays":{"type":"number"},"note":{"type":"string"}}},"bind":{"action":"add_project"}},{"name":"add_milestone","description":"Save a milestone on a project: title, due date (YYYY-MM-DD) and owner. An existing title on that project is updated, never duplicated. When a date slips, pass shiftDays (how many days later; negative for earlier) and the board moves it; never work out the new date yourself. Call it as soon as a milestone or a slip is mentioned.","script":"delivery-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"project":{"type":"string"},"title":{"type":"string"},"dueAt":{"type":"string"},"owner":{"type":"string"},"status":{"type":"string","enum":["planned","in-progress","waiting","approved"]},"shiftDays":{"type":"number"},"note":{"type":"string"}}},"bind":{"action":"add_milestone"}},{"name":"set_milestone_status","description":"Move a milestone: in-progress when work starts; waiting when it goes to the client for approval (the board starts counting the wait and the round); approved when the client signs off; back to in-progress, with their feedback as note, when they ask for changes. Call it the moment the person says it.","script":"delivery-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"project":{"type":"string"},"status":{"type":"string","enum":["planned","in-progress","waiting","approved"]},"contact":{"type":"string"},"note":{"type":"string"}},"required":["status"]},"bind":{"action":"set_status"}},{"name":"list_client_projects","description":"Every client project with all of its milestones, statuses and dates.","script":"delivery-store","inputs":{"type":"object","properties":{}},"bind":{"action":"list"}},{"name":"page_add_project","description":"Add or update a client project.","script":"delivery-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"client":{"type":"string"},"contact":{"type":"string"},"lead":{"type":"string"},"dueAt":{"type":"string"},"status":{"type":"string","enum":["proposed","active","on-hold","done"]},"shiftDays":{"type":"number"},"note":{"type":"string"}}},"bind":{"action":"add_project"}},{"name":"page_add_milestone","description":"Add or update a milestone.","script":"delivery-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"project":{"type":"string"},"title":{"type":"string"},"dueAt":{"type":"string"},"owner":{"type":"string"},"status":{"type":"string","enum":["planned","in-progress","waiting","approved"]},"shiftDays":{"type":"number"},"note":{"type":"string"}}},"bind":{"action":"add_milestone"}},{"name":"page_set_milestone_status","description":"Move a milestone.","script":"delivery-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"project":{"type":"string"},"status":{"type":"string","enum":["planned","in-progress","waiting","approved"]},"contact":{"type":"string"},"note":{"type":"string"}},"required":["status"]},"bind":{"action":"set_status"},"reaction":{"gezel":"planner","prompt":"The person just moved a milestone on the delivery board. The board now reads (its first sentence is what changed):\n{{output.summary}}\nIn two short sentences, confirm what changed and name the one thing to chase next: the longest wait on a client, or the next milestone due. Do not call tools.","hideSeed":true}}],"pages":{"entry":"delivery/index.html","api":1,"reads":[{"source":"workspace","path":"projects.json"},{"source":"workspace","path":"milestones.json"}],"tools":["page_add_project","page_add_milestone","page_set_milestone_status"]},"schedules":[],"workspaceSeed":["projects.json","milestones.json"],"artifactsSeed":[],"availableVersions":["1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"compliance-register","name":"Compliance Register","description":"Keep a small business in good standing. A compliance officer tracks every license, permit, filing, policy and certificate with an owner, a due date and the proof it was done, and reminds you before anything lapses.","tags":["compliance","permits","licenses","regulations","renewals","audit","small-business"],"category":"business","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.0.0","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"business":{"type":"string","title":"What kind of business is this?","description":"e.g. 'a café in Portland', 'a two-person electrical contractor'.","default":"the business"}},"required":["business"]},"nameTemplate":"Compliance Register","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"compliance-officer","voorman":true},{"templateId":"archivaris","voorman":false}],"toolsets":[],"craftbooks":["audit-evidence-pack"],"scripts":{"compliance-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { logStore, rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'compliance-store',\n description:\n \"Read and update the compliance register (obligations.json) and its evidence log (evidence.json). action:'status' for what is overdue and due soon; 'add' to record an obligation (an existing title is updated, never duplicated); 'complete' when one is done (a recurring one rolls to its next due date); 'set_status' to mark one in progress; 'log_evidence' to file proof; 'list' for the whole register.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'status', 'add', 'complete', 'set_status', 'log_evidence', or 'list'.\",\n required: true,\n },\n id: { type: 'string', description: \"Obligation id, e.g. 'ob-3'.\" },\n title: {\n type: 'string',\n description: \"The obligation's name, e.g. 'Food service permit'. Also finds it when no id is given.\",\n },\n category: {\n type: 'string',\n description: 'license, permit, filing, insurance, certification, inspection, policy, or other.',\n },\n dueAt: { type: 'string', description: 'The next due date, YYYY-MM-DD.' },\n recurs: { type: 'string', description: 'none, monthly, quarterly, or yearly.' },\n owner: { type: 'string', description: 'Who is responsible.' },\n authority: { type: 'string', description: 'Who issues or checks it, e.g. County Health Department.' },\n status: { type: 'string', description: 'For set_status: open or in-progress.' },\n note: { type: 'string', description: 'What happened, with any reference number exactly as written.' },\n file: { type: 'string', description: \"Workspace path of an evidence file, e.g. 'evidence/permit-2026.pdf'.\" },\n withinDays: { type: 'number', description: 'How many days ahead counts as due soon (default 60).' },\n },\n outputs: {\n overdue: { type: 'number', description: 'Open obligations past their due date.' },\n dueSoon: { type: 'number', description: 'Open obligations due within the window.' },\n tracked: { type: 'number', description: 'Obligations on the register.' },\n summary: { type: 'string', description: 'The register picture, or the listing.' },\n },\n requires: ['workspace.read', 'workspace.write', 'reminders'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── compliance-rules-start ──\n// Pure derivations: days left in local calendar days, the next due date of a\n// recurring obligation, and the register line the crew reads. Kept\n// self-contained between these sentinels so unit tests execute the shipped\n// bytes.\nvar DAY_MS = 86400000;\nvar CATEGORIES = ['license', 'permit', 'filing', 'insurance', 'certification', 'inspection', 'policy', 'other'];\nvar RECURS = ['none', 'monthly', 'quarterly', 'yearly'];\n\nfunction pad(n) {\n return n < 10 ? '0' + n : String(n);\n}\nfunction localDay(ms) {\n var d = new Date(ms);\n return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());\n}\nfunction normalizeDate(text) {\n var raw = String(text || '').trim();\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(raw)) return raw;\n var parsed = Date.parse(raw);\n return isFinite(parsed) ? localDay(parsed) : null;\n}\nfunction daysLeft(dueAt, nowMs) {\n var due = Date.parse(String(dueAt).slice(0, 10) + 'T00:00:00');\n var today = Date.parse(localDay(nowMs) + 'T00:00:00');\n return Math.round((due - today) / DAY_MS);\n}\nfunction rollForward(dueAt, recurs) {\n var months = recurs === 'monthly' ? 1 : recurs === 'quarterly' ? 3 : recurs === 'yearly' ? 12 : 0;\n if (!months) return null;\n var d = new Date(String(dueAt).slice(0, 10) + 'T12:00:00');\n var day = d.getDate();\n d.setDate(1);\n d.setMonth(d.getMonth() + months);\n // The 31st of a month rolls to the last day of a shorter one, not into the next.\n var last = new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate();\n d.setDate(Math.min(day, last));\n return localDay(d.getTime());\n}\nfunction when(days) {\n if (days < 0) return -days + (days === -1 ? ' day late' : ' days late');\n if (days === 0) return 'due today';\n return 'in ' + days + (days === 1 ? ' day' : ' days');\n}\nfunction proofOf(record, events) {\n return events.filter(function (e) {\n return e.data && e.data.obligationId === record.id;\n });\n}\nfunction line(record, events, nowMs) {\n var f = record.fields || {};\n var proof = proofOf(record, events);\n var last = proof.length ? proof[proof.length - 1] : null;\n return (\n f.title +\n ' (' + record.id + ', ' + (f.category || 'other') + ', owner ' + (f.owner || 'unassigned') + ') ' +\n when(daysLeft(f.dueAt, nowMs)) + ', due ' + f.dueAt +\n (record.status === 'in-progress' ? ', in progress' : '') +\n (f.recurs && f.recurs !== 'none' ? ', ' + f.recurs : '') +\n '; ' + (last ? 'last proof ' + String(last.at).slice(0, 10) + ': ' + (last.note || last.data.file) : 'no proof on file')\n );\n}\nfunction picture(records, events, nowMs, withinDays) {\n var open = records.filter(function (r) {\n return r.status !== 'done' && r.fields && r.fields.dueAt;\n });\n var byDue = function (a, b) {\n return String(a.fields.dueAt).localeCompare(String(b.fields.dueAt));\n };\n var overdue = open.filter(function (r) { return daysLeft(r.fields.dueAt, nowMs) < 0; }).sort(byDue);\n var soon = open\n .filter(function (r) {\n var d = daysLeft(r.fields.dueAt, nowMs);\n return d >= 0 && d <= withinDays;\n })\n .sort(byDue);\n var later = open.filter(function (r) { return daysLeft(r.fields.dueAt, nowMs) > withinDays; }).sort(byDue);\n var parts = [records.length + (records.length === 1 ? ' obligation' : ' obligations') + ' on the register, ' + overdue.length + ' overdue.'];\n // One list, overdue first: asked \"what's due in 60 days\", a model read a separate overdue list as out of scope.\n var due = overdue.concat(soon);\n parts.push(\n due.length\n ? 'Due within ' + withinDays + ' days, overdue first: ' + due.map(function (r) { return line(r, events, nowMs); }).join(' | ') + '.'\n : 'Nothing due in the next ' + withinDays + ' days.',\n );\n if (later.length) parts.push('Next after that: ' + later[0].fields.title + ', due ' + later[0].fields.dueAt + '.');\n return { overdue: overdue.length, dueSoon: soon.length, summary: parts.join(' ') };\n}\n// ── compliance-rules-end ──\n\nconst obligations = rosterStore(gezel.fs, 'obligations.json', {\n stages: ['open', 'in-progress', 'done'],\n idPrefix: 'ob',\n});\nconst evidence = logStore(gezel.fs, 'evidence.json');\n\nasync function resolve(): Promise<string> {\n if (input.id) return input.id;\n if (input.title) {\n const wanted = input.title.trim().toLowerCase();\n const all = await obligations.list();\n const exact = all.filter((r) => String(r.fields.title ?? '').toLowerCase() === wanted);\n if (exact.length === 1) return exact[0]!.id;\n const partial = all.filter((r) => String(r.fields.title ?? '').toLowerCase().includes(wanted));\n if (partial.length === 1) return partial[0]!.id;\n if (partial.length > 1) {\n throw new Error(\"More than one obligation matches '\" + input.title + \"': \" + partial.map((r) => r.id + ' ' + String(r.fields.title)).join(', ') + '. Pass id.');\n }\n }\n throw new Error(\"Pass 'id' (e.g. 'ob-3') or the obligation's 'title'. Call action:'list' to see them.\");\n}\n\n// The register's one reminder sits on the soonest open obligation, 14 days ahead of it.\nasync function remindNextDue(): Promise<void> {\n const now = Date.now();\n const lead = 14 * DAY_MS;\n const next = (await obligations.list())\n .filter((r) => r.status !== 'done' && typeof r.fields.dueAt === 'string')\n .map((r) => ({ title: String(r.fields.title), dueAt: String(r.fields.dueAt), at: Date.parse(String(r.fields.dueAt) + 'T09:00:00') - lead }))\n .filter((r) => r.at > now)\n .sort((a, b) => a.at - b.at)[0];\n try {\n if (!next || next.at - now > 30 * DAY_MS) await gezel.reminder.clear();\n else await gezel.reminder.set({ at: new Date(next.at).toISOString(), title: next.title + ' is due in two weeks', body: 'Due ' + next.dueAt + '. Open the register to plan it.' });\n } catch {\n // Reminders are a convenience; the register is the record.\n }\n}\n\nconst withinDays = typeof input.withinDays === 'number' && input.withinDays > 0 ? Math.round(input.withinDays) : 60;\nlet note = '';\n\nif (input.action === 'add') {\n if (!input.title) throw new Error(\"add needs 'title'.\");\n const dueAt = input.dueAt ? normalizeDate(input.dueAt) : null;\n if (input.dueAt && !dueAt) throw new Error(\"dueAt must be a date, e.g. '2026-12-01'.\");\n const category = CATEGORIES.includes(String(input.category)) ? String(input.category) : undefined;\n const recurs = RECURS.includes(String(input.recurs)) ? String(input.recurs) : undefined;\n const wanted = input.title.trim().toLowerCase();\n const existing = (await obligations.list()).find((r) => String(r.fields.title ?? '').toLowerCase() === wanted);\n const fields: Record<string, unknown> = {\n ...(dueAt ? { dueAt } : {}),\n ...(category ? { category } : {}),\n ...(recurs ? { recurs } : {}),\n ...(input.owner ? { owner: input.owner.trim() } : {}),\n ...(input.authority ? { authority: input.authority.trim() } : {}),\n ...(input.note ? { notes: input.note.trim() } : {}),\n };\n if (existing) {\n await obligations.update(existing.id, { fields });\n note = 'Updated ' + String(existing.fields.title) + '.';\n } else {\n if (!dueAt) throw new Error(\"A new obligation needs 'dueAt' (YYYY-MM-DD).\");\n const record = await obligations.add({\n status: 'open',\n fields: { title: input.title.trim(), category: category ?? 'other', recurs: recurs ?? 'none', ...fields },\n });\n note = 'Added ' + record.id + '.';\n }\n} else if (input.action === 'complete') {\n const id = await resolve();\n const record = await obligations.get(id);\n if (!record) throw new Error('No obligation ' + id + '.');\n await evidence.append({\n kind: 'completed',\n note: input.note ?? 'Completed.',\n data: { obligationId: id, ...(input.file ? { file: input.file } : {}) },\n });\n const next = rollForward(String(record.fields.dueAt ?? ''), String(record.fields.recurs ?? 'none'));\n if (next) {\n await obligations.update(id, { fields: { dueAt: next, lastCompletedAt: localDay(Date.now()) } });\n if (record.status !== 'open') await obligations.transition(id, 'open', { note: 'Completed; next due ' + next });\n note = String(record.fields.title) + ' completed; next due ' + next + '.';\n } else {\n await obligations.transition(id, 'done', { note: input.note ?? 'Completed' });\n note = String(record.fields.title) + ' completed.';\n }\n} else if (input.action === 'set_status') {\n if (input.status !== 'open' && input.status !== 'in-progress') throw new Error(\"set_status needs status 'open' or 'in-progress'.\");\n const id = await resolve();\n await obligations.transition(id, input.status, input.note ? { note: input.note } : {});\n} else if (input.action === 'log_evidence') {\n if (!input.note && !input.file) throw new Error(\"log_evidence needs 'note' or 'file'.\");\n const id = await resolve();\n await evidence.append({\n kind: 'evidence',\n note: input.note ?? 'Filed ' + input.file + '.',\n data: { obligationId: id, ...(input.file ? { file: input.file } : {}) },\n });\n} else if (input.action !== 'status' && input.action !== 'list') {\n throw new Error(\"Unknown action '\" + input.action + \"'. Use status, add, complete, set_status, log_evidence, or list.\");\n}\n\nconst records = await obligations.list();\nconst events = await evidence.list();\nconst now = Date.now();\nconst view = picture(records, events, now, withinDays);\nawait remindNextDue();\n\ngezel.output({\n overdue: view.overdue,\n dueSoon: view.dueSoon,\n tracked: records.length,\n summary:\n input.action === 'list'\n ? records.map((r) => '[' + r.status + '] ' + line(r, events, now)).join('\\n') || 'The register is empty.'\n : (note ? note + ' ' : '') + view.summary,\n});\n"},"tools":[{"name":"register_status","description":"What is overdue and due soon on the register, each with its owner, days left and the last proof on file. Call it first when asked what's due.","script":"compliance-store","inputs":{"type":"object","properties":{"withinDays":{"type":"number"}}},"bind":{"action":"status"},"state":true},{"name":"add_obligation","description":"Save an obligation to the register: title, category, next due date (YYYY-MM-DD), how it recurs, owner and authority. An existing title is updated, never duplicated. Call it as soon as one is mentioned, before you describe it.","script":"compliance-store","inputs":{"type":"object","properties":{"title":{"type":"string"},"category":{"type":"string","enum":["license","permit","filing","insurance","certification","inspection","policy","other"]},"dueAt":{"type":"string"},"recurs":{"type":"string","enum":["none","monthly","quarterly","yearly"]},"owner":{"type":"string"},"authority":{"type":"string"},"note":{"type":"string"}},"required":["title"]},"bind":{"action":"add"}},{"name":"complete_obligation","description":"Record that an obligation was done, with the reference number or certificate exactly as given. A recurring one rolls to its next due date. Call it the moment the person says it's done.","script":"compliance-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"note":{"type":"string"},"file":{"type":"string"}}},"bind":{"action":"complete"}},{"name":"set_obligation_status","description":"Mark an obligation in progress (or back to open).","script":"compliance-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"status":{"type":"string","enum":["open","in-progress"]},"note":{"type":"string"}},"required":["status"]},"bind":{"action":"set_status"}},{"name":"log_evidence","description":"File proof against an obligation: a note with the reference number, or the path of an uploaded file under evidence/.","script":"compliance-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"note":{"type":"string"},"file":{"type":"string"}}},"bind":{"action":"log_evidence"}},{"name":"list_obligations","description":"Every obligation on the register with its status, due date and proof.","script":"compliance-store","inputs":{"type":"object","properties":{}},"bind":{"action":"list"}},{"name":"page_add_obligation","description":"Add or update an obligation.","script":"compliance-store","inputs":{"type":"object","properties":{"title":{"type":"string"},"category":{"type":"string","enum":["license","permit","filing","insurance","certification","inspection","policy","other"]},"dueAt":{"type":"string"},"recurs":{"type":"string","enum":["none","monthly","quarterly","yearly"]},"owner":{"type":"string"},"authority":{"type":"string"},"note":{"type":"string"}},"required":["title"]},"bind":{"action":"add"}},{"name":"page_complete_obligation","description":"Record that an obligation was done.","script":"compliance-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"note":{"type":"string"},"file":{"type":"string"}}},"bind":{"action":"complete"},"reaction":{"gezel":"compliance-officer","prompt":"The person just recorded a completion on the register page. The register now reads (its first sentence is what changed):\n{{output.summary}}\nIn two short sentences, confirm what changed, including the next due date if it recurs, and name the next item to plan. Do not call tools.","hideSeed":true}},{"name":"page_log_evidence","description":"File proof against an obligation.","script":"compliance-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"note":{"type":"string"},"file":{"type":"string"}}},"bind":{"action":"log_evidence"}}],"pages":{"imports":[{"id":"evidence","source":"workspace","path":"evidence","accept":[".pdf",".png",".jpg",".jpeg",".webp",".heic",".docx",".txt",".md"],"maxFileBytes":26214400}],"entry":"register/index.html","api":1,"reads":[{"source":"workspace","path":"obligations.json"},{"source":"workspace","path":"evidence.json"},{"source":"workspace","path":"evidence","subtree":true}],"tools":["page_add_obligation","page_complete_obligation","page_log_evidence"]},"schedules":[],"workspaceSeed":["obligations.json","evidence.json"],"artifactsSeed":[],"availableVersions":["1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"content-studio","name":"Content Studio","description":"Keep long-form content moving from idea to published, then make each piece work twice. A managing editor runs the pipeline, the editorial calendar and who is writing what, and plans the newsletter, social posts and video chapters every piece spins off.","tags":["content","editorial","blog","newsletter","repurposing","content-calendar","small-business"],"category":"business","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.0.0","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"business":{"type":"string","title":"What business is the content for?","description":"e.g. 'a six-person design studio', 'a small publisher'.","default":"the business"},"audience":{"type":"string","title":"Who do you write for?","description":"e.g. 'small business owners planning a rebrand'.","default":"your readers"}},"required":["business"]},"nameTemplate":"Content Studio","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"managing-editor","voorman":true},{"templateId":"copywriter","voorman":false},{"templateId":"reviewer","voorman":false},{"templateId":"illustrator","voorman":false}],"toolsets":[],"craftbooks":["blog-post","newsletter-issue","case-study","seo-meta-pack","copy-review","social-thread"],"scripts":{"content-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'content-store',\n description:\n \"Read and update the content studio: the long-form pieces (pieces.json) and the editorial calendar of what each piece spins off (calendar.json). action:'status' for the whole picture; 'add_piece' to save a piece (an existing title is updated, never duplicated); 'update_piece' to move a piece to another stage, reassign it or change its publish date; 'repurpose_piece' to plan a piece's newsletter, social posts or video chapters (count is how many of that format in all; only the missing ones are added, each dated after the piece); 'update_spinoff' to move or reschedule one of those; 'list' for everything.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'status', 'add_piece', 'update_piece', 'repurpose_piece', 'update_spinoff', or 'list'.\",\n required: true,\n },\n id: { type: 'string', description: \"A piece id ('pc-3'), or for update_spinoff a spin-off id ('so-2').\" },\n title: {\n type: 'string',\n description: \"The piece's title, e.g. 'How we price brand projects'. Also finds a piece (or a spin-off) when no id is given.\",\n },\n format: {\n type: 'string',\n description:\n 'For a piece: article, guide, case-study, interview, essay, video, podcast, or other. For repurpose_piece: newsletter, social-post, video-chapters, short-video, quote-card, or other.',\n },\n status: {\n type: 'string',\n description:\n 'A piece stage (idea, brief, draft, edit, design, published), or for a spin-off: planned, drafted, scheduled, published.',\n },\n assignee: { type: 'string', description: 'Who is writing or making it.' },\n publishAt: { type: 'string', description: 'The day it publishes or goes out, YYYY-MM-DD.' },\n shiftDays: {\n type: 'number',\n description: 'Move the date by this many days (7 = a week later, -2 = two days earlier). The studio does the date math.',\n },\n keyword: { type: 'string', description: 'The search phrase the piece targets.' },\n angle: {\n type: 'string',\n description: \"One line on what it says. For several spin-offs at once, separate one line each with ' | '.\",\n },\n words: { type: 'number', description: 'Target length in words.' },\n link: { type: 'string', description: 'Where it was published.' },\n note: { type: 'string', description: 'What happened, in the person’s words.' },\n count: {\n type: 'number',\n description: 'For repurpose_piece: how many of this format the piece should have in all (three posts = 3). Only the missing ones are added.',\n },\n startAt: { type: 'string', description: 'For repurpose_piece: the day the first new one goes out, YYYY-MM-DD (default: after the piece publishes).' },\n channel: { type: 'string', description: \"Where a spin-off goes out, e.g. 'LinkedIn', 'Instagram', 'YouTube', 'the newsletter'.\" },\n withinDays: { type: 'number', description: 'How many days ahead counts as publishing soon (default 14).' },\n },\n outputs: {\n inPipeline: { type: 'number', description: 'Pieces not yet published.' },\n dueSoon: { type: 'number', description: 'Pieces and spin-offs going out within the window.' },\n late: { type: 'number', description: 'Pieces and spin-offs past their date and not published.' },\n repurposed: { type: 'number', description: 'Published pieces with at least one spin-off.' },\n summary: { type: 'string', description: 'What changed, then the studio picture; or the listing.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── content-rules-start ──\n// Pure derivations: local calendar days, spin-off dates after a piece\n// publishes, record lookup by id or name, and the studio picture the crew\n// reads. Kept self-contained between these sentinels so tests execute the\n// shipped bytes.\nvar DAY_MS = 86400000;\nvar STAGES = ['idea', 'brief', 'draft', 'edit', 'design', 'published'];\nvar FORMATS = ['article', 'guide', 'case-study', 'interview', 'essay', 'video', 'podcast', 'other'];\nvar SPIN_FORMATS = ['newsletter', 'social-post', 'video-chapters', 'short-video', 'quote-card', 'other'];\nvar SPIN_STAGES = ['planned', 'drafted', 'scheduled', 'published'];\nvar SPIN_ALIASES = {\n post: 'social-post', posts: 'social-post', social: 'social-post', 'social post': 'social-post', 'social posts': 'social-post',\n 'social-posts': 'social-post', 'linkedin post': 'social-post', thread: 'social-post', email: 'newsletter', newsletters: 'newsletter',\n 'newsletter issue': 'newsletter', chapters: 'video-chapters', 'video chapters': 'video-chapters', 'youtube chapters': 'video-chapters',\n reel: 'short-video', reels: 'short-video', short: 'short-video', shorts: 'short-video', clip: 'short-video', 'short video': 'short-video',\n quote: 'quote-card', quotes: 'quote-card', 'quote card': 'quote-card', 'quote cards': 'quote-card',\n};\nvar SPIN_NOUN = {\n newsletter: ['newsletter', 'newsletters'],\n 'social-post': ['social post', 'social posts'],\n 'video-chapters': ['set of video chapters', 'sets of video chapters'],\n 'short-video': ['short video', 'short videos'],\n 'quote-card': ['quote card', 'quote cards'],\n other: ['spin-off', 'spin-offs'],\n};\nvar SPIN_LABEL = {\n newsletter: 'Newsletter', 'social-post': 'Social post', 'video-chapters': 'Video chapters', 'short-video': 'Short video',\n 'quote-card': 'Quote card', other: 'Spin-off',\n};\n// Days after the piece publishes that the first of each format goes out; later ones follow every SPACING days.\nvar OFFSET = { newsletter: 3, 'social-post': 1, 'video-chapters': 7, 'short-video': 4, 'quote-card': 2, other: 7 };\nvar SPACING = 2;\nvar WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\nvar MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\nvar STOP = ['the', 'and', 'our', 'for', 'with', 'from', 'this', 'that', 'post', 'piece', 'article'];\n\nfunction pad(n) {\n return n < 10 ? '0' + n : String(n);\n}\nfunction localDay(ms) {\n var d = new Date(ms);\n return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());\n}\nfunction addDays(day, n) {\n var d = new Date(String(day).slice(0, 10) + 'T12:00:00');\n d.setDate(d.getDate() + n);\n return localDay(d.getTime());\n}\nfunction daysLeft(day, nowMs) {\n var due = Date.parse(String(day).slice(0, 10) + 'T00:00:00');\n var today = Date.parse(localDay(nowMs) + 'T00:00:00');\n return Math.round((due - today) / DAY_MS);\n}\n// YYYY-MM-DD, or today/tomorrow, or a weekday ('friday' is the next one).\nfunction normalizeDate(text, nowMs) {\n var raw = String(text || '').trim();\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(raw)) return raw;\n var lower = raw.toLowerCase();\n var today = localDay(nowMs);\n if (lower === 'today') return today;\n if (lower === 'tomorrow') return addDays(today, 1);\n var m = lower.match(/^(next |this )?(sunday|monday|tuesday|wednesday|thursday|friday|saturday)$/);\n if (m) {\n var target = WEEKDAYS.map(function (w) { return w.toLowerCase(); }).indexOf(m[2]);\n var dow = new Date(today + 'T12:00:00').getDay();\n return addDays(today, ((target - dow + 6) % 7) + 1);\n }\n var parsed = Date.parse(raw);\n if (!isFinite(parsed)) return null;\n if (/\\d{4}/.test(raw)) return localDay(parsed);\n // 'Nov 20' parses into some default year: take this year's, or next year's once it is well past.\n var d = new Date(parsed);\n var year = new Date(nowMs).getFullYear();\n var guess = year + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());\n return daysLeft(guess, nowMs) < -60 ? year + 1 + guess.slice(4) : guess;\n}\nfunction niceDay(day) {\n var d = new Date(String(day).slice(0, 10) + 'T12:00:00');\n return WEEKDAYS[d.getDay()].slice(0, 3) + ' ' + MONTHS[d.getMonth()] + ' ' + d.getDate();\n}\nfunction when(days) {\n if (days < 0) return -days + (days === -1 ? ' day late' : ' days late');\n if (days === 0) return 'today';\n return 'in ' + days + (days === 1 ? ' day' : ' days');\n}\nfunction wholeNumber(value) {\n var n = typeof value === 'string' ? Number(String(value).replace(/,/g, '')) : value;\n return typeof n === 'number' && isFinite(n) && n >= 0 ? Math.round(n) : null;\n}\nfunction spinFormat(text) {\n var key = String(text || '').trim().toLowerCase();\n if (!key) return null;\n if (SPIN_FORMATS.indexOf(key) >= 0) return key;\n return SPIN_ALIASES[key] || null;\n}\nfunction stem(word) {\n return word.replace(/(ing|ed|es|s|e)$/, '');\n}\nfunction words(text) {\n return (String(text || '').toLowerCase().match(/[a-z0-9]+/g) || []).map(stem).filter(function (w) {\n return w.length > 2 && STOP.indexOf(w) < 0;\n });\n}\n// The record a person means: its id, its exact title, a unique part of its\n// title, or the title sharing the most words with what they wrote.\nfunction findRecord(records, key) {\n var text = String(key || '').trim();\n if (!text) return { record: null, matches: [] };\n var lower = text.toLowerCase();\n var titleOf = function (r) { return String((r.fields && r.fields.title) || '').toLowerCase(); };\n var byId = records.filter(function (r) { return String(r.id).toLowerCase() === lower; });\n if (byId.length) return { record: byId[0], matches: byId };\n var exact = records.filter(function (r) { return titleOf(r) === lower; });\n if (exact.length === 1) return { record: exact[0], matches: exact };\n var partial = records.filter(function (r) { return titleOf(r).indexOf(lower) >= 0; });\n if (partial.length === 1) return { record: partial[0], matches: partial };\n if (partial.length > 1) return { record: null, matches: partial };\n var want = words(text);\n var best = 0;\n var hits = [];\n records.forEach(function (r) {\n var have = words(titleOf(r));\n var score = want.filter(function (w) { return have.indexOf(w) >= 0; }).length;\n if (score > best) { best = score; hits = [r]; } else if (score === best && score > 0) hits.push(r);\n });\n return { record: hits.length === 1 ? hits[0] : null, matches: hits };\n}\n// The dates for the spin-offs a piece still needs: after it publishes (or from today), one every SPACING days.\nfunction spinoffDates(piece, format, already, missing, startAt, nowMs) {\n var today = localDay(nowMs);\n var f = piece.fields || {};\n var published = piece.status === 'published';\n var base = f.publishAt && !published && f.publishAt >= today ? f.publishAt : today;\n var first = startAt || addDays(base, (OFFSET[format] || 7) + already * SPACING);\n var out = [];\n for (var i = 0; i < missing; i++) out.push(addDays(first, i * SPACING));\n return out;\n}\nfunction spinoffTitle(format, index, total, pieceTitle) {\n return SPIN_LABEL[format] + (total > 1 || index > 0 ? ' ' + (index + 1) : '') + ': ' + pieceTitle;\n}\nfunction dateOf(r) {\n var f = r.fields || {};\n return r.status === 'published' ? f.publishedAt || f.publishAt || '' : f.publishAt || '';\n}\nfunction pieceLine(r, nowMs) {\n var f = r.fields || {};\n var d = dateOf(r);\n return (\n f.title + ' (' + r.id + ', ' + (f.format || 'article') + ', ' + (r.status === 'published' ? 'published' : 'in ' + r.status) +\n ', ' + (f.assignee || 'unassigned') + ')' + (d ? ' ' + niceDay(d) + (r.status === 'published' ? '' : ', ' + when(daysLeft(d, nowMs))) : ', no date yet')\n );\n}\nfunction spinoffLine(s, pieces, nowMs) {\n var f = s.fields || {};\n var piece = pieces.find(function (p) { return p.id === f.pieceId; });\n return (\n f.title + ' (' + s.id + ', ' + f.format + ' for ' + (piece ? piece.id : 'a removed piece') + ', ' + s.status +\n (f.channel ? ', ' + f.channel : '') + (f.assignee ? ', ' + f.assignee : '') + ')' +\n (f.publishAt ? ' ' + niceDay(f.publishAt) + (s.status === 'published' ? '' : ', ' + when(daysLeft(f.publishAt, nowMs))) : ', no date yet')\n );\n}\nfunction spinoffSummary(list) {\n return SPIN_FORMATS.map(function (format) {\n var mine = list.filter(function (s) { return s.fields.format === format; });\n if (!mine.length) return '';\n var byStage = SPIN_STAGES.map(function (st) {\n var n = mine.filter(function (s) { return s.status === st; }).length;\n return n ? (mine.length === 1 ? st : n + ' ' + st) : '';\n }).filter(Boolean).join(', ');\n return mine.length === 1 ? SPIN_NOUN[format][0] + ' ' + byStage : mine.length + ' ' + SPIN_NOUN[format][1] + ' (' + byStage + ')';\n }).filter(Boolean).join(', ');\n}\nfunction studioPicture(pieces, spinoffs, nowMs, withinDays) {\n var parts = [];\n var open = pieces.filter(function (p) { return p.status !== 'published'; });\n var stageCounts = STAGES.map(function (s) {\n var n = pieces.filter(function (p) { return p.status === s; }).length;\n return n ? n + ' ' + s : '';\n }).filter(Boolean);\n parts.push(pieces.length ? 'Pipeline: ' + pieces.length + (pieces.length === 1 ? ' piece' : ' pieces') + ' (' + stageCounts.join(', ') + ').' : 'No pieces yet.');\n var items = [];\n open.forEach(function (p) { if (p.fields.publishAt) items.push({ day: p.fields.publishAt, line: pieceLine(p, nowMs) }); });\n spinoffs.forEach(function (s) {\n if (s.status !== 'published' && s.fields.publishAt) items.push({ day: s.fields.publishAt, line: spinoffLine(s, pieces, nowMs) });\n });\n items.sort(function (a, b) { return a.day.localeCompare(b.day); });\n var late = items.filter(function (i) { return daysLeft(i.day, nowMs) < 0; });\n var soon = items.filter(function (i) { var d = daysLeft(i.day, nowMs); return d >= 0 && d <= withinDays; });\n var later = items.filter(function (i) { return daysLeft(i.day, nowMs) > withinDays; });\n // One list, late items first: asked what is publishing soon, a model must see what slipped.\n var due = late.concat(soon);\n parts.push(\n due.length\n ? 'Publishing in the next ' + withinDays + ' days, late items first: ' + due.map(function (i) { return i.line; }).join(' | ') + '.'\n : 'Nothing publishing in the next ' + withinDays + ' days.',\n );\n if (later.length) parts.push('Next after that: ' + later[0].line + '.');\n var undated = open.filter(function (p) { return !p.fields.publishAt; });\n if (undated.length) parts.push('No publish date yet: ' + undated.map(function (p) { return p.fields.title + ' (' + p.id + ', ' + p.status + ')'; }).join(', ') + '.');\n var people = {};\n var unassigned = [];\n open.forEach(function (p) {\n var who = p.fields.assignee;\n var entry = p.fields.title + ' (' + p.id + ', ' + p.status + (p.fields.publishAt ? ', ' + niceDay(p.fields.publishAt) : '') + ')';\n if (!who) unassigned.push(entry);\n else (people[who] = people[who] || []).push(entry);\n });\n spinoffs.forEach(function (s) {\n if (s.status === 'published' || !s.fields.assignee) return;\n (people[s.fields.assignee] = people[s.fields.assignee] || []).push(s.fields.title + ' (' + s.id + ', ' + s.status + (s.fields.publishAt ? ', ' + niceDay(s.fields.publishAt) : '') + ')');\n });\n var names = Object.keys(people).sort(function (a, b) { return people[b].length - people[a].length || a.localeCompare(b); });\n parts.push(\n names.length || unassigned.length\n ? 'Who has what, most first: ' + names.map(function (n) { return n + ' ' + people[n].length + ': ' + people[n].join(', '); }).join(' | ') +\n (unassigned.length ? (names.length ? ' | ' : '') + 'unassigned ' + unassigned.length + ': ' + unassigned.join(', ') : '') + '.'\n : 'Nobody has open work.',\n );\n var shown = pieces\n .filter(function (p) {\n return p.status === 'published' || spinoffs.some(function (s) { return s.fields.pieceId === p.id; });\n })\n .sort(function (a, b) { return String(dateOf(b)).localeCompare(String(dateOf(a))); })\n .slice(0, 8);\n parts.push(\n shown.length\n ? 'Repurposing, newest first: ' + shown.map(function (p) {\n var mine = spinoffs.filter(function (s) { return s.fields.pieceId === p.id; });\n return p.fields.title + ' (' + p.id + ', ' + (p.status === 'published' ? 'published ' + (dateOf(p) ? niceDay(dateOf(p)) : '') : 'in ' + p.status) + '): ' +\n (mine.length ? spinoffSummary(mine) : 'nothing repurposed yet');\n }).join(' | ') + '.'\n : 'Nothing published or repurposed yet.',\n );\n var published = pieces.filter(function (p) { return p.status === 'published'; });\n return {\n inPipeline: open.length,\n dueSoon: soon.length,\n late: late.length,\n repurposed: published.filter(function (p) { return spinoffs.some(function (s) { return s.fields.pieceId === p.id; }); }).length,\n summary: parts.join(' '),\n };\n}\n// ── content-rules-end ──\n\nconst pieces = rosterStore(gezel.fs, 'pieces.json', {\n stages: ['idea', 'brief', 'draft', 'edit', 'design', 'published'],\n idPrefix: 'pc',\n});\nconst calendar = rosterStore(gezel.fs, 'calendar.json', {\n stages: ['planned', 'drafted', 'scheduled', 'published'],\n idPrefix: 'so',\n});\n\nasync function resolveIn(store: typeof pieces, noun: string, example: string) {\n const all = await store.list();\n const keys = [input.id, input.title].filter((k): k is string => typeof k === 'string' && k.trim() !== '');\n for (const key of keys) {\n const found = findRecord(all, key);\n if (found.record) return found.record;\n if (found.matches.length > 1) {\n throw new Error(\n 'More than one ' + noun + \" matches '\" + key + \"': \" + found.matches.map((r) => r.id + ' ' + String(r.fields.title)).join(', ') + '. Pass id.',\n );\n }\n }\n const known = all.map((r) => r.id + ' ' + String(r.fields.title)).join(', ') || 'none yet';\n throw new Error(\n (keys.length ? 'No ' + noun + \" matches '\" + keys.join(\"' or '\") + \"'. \" : \"Pass 'id' (e.g. '\" + example + \"') or the \" + noun + \"'s 'title'. \") + 'Known: ' + known + '.',\n );\n}\n\nconst now = Date.now();\nconst today = localDay(now);\nconst withinDays = typeof input.withinDays === 'number' && input.withinDays > 0 ? Math.round(input.withinDays) : 14;\n\nfunction dateInput(value: string | undefined, label: string): string | null {\n if (value === undefined || String(value).trim() === '') return null;\n const day = normalizeDate(value, now);\n if (!day) throw new Error(label + \" must be a date, e.g. '2026-12-01'.\");\n return day;\n}\nfunction shifted(from: unknown, title: unknown): string | null {\n if (typeof input.shiftDays !== 'number' || input.shiftDays === 0) return null;\n if (typeof from !== 'string' || !from) throw new Error(String(title) + ' has no date yet; pass publishAt instead of shiftDays.');\n return addDays(from, Math.round(input.shiftDays));\n}\n\nlet note = '';\n\nif (input.action === 'add_piece') {\n if (!input.title || !input.title.trim()) throw new Error(\"add_piece needs 'title'.\");\n const publishAt = dateInput(input.publishAt, 'publishAt');\n const format = input.format ? String(input.format).toLowerCase() : undefined;\n if (format && !FORMATS.includes(format)) throw new Error('format must be one of ' + FORMATS.join(', ') + '.');\n const status = input.status ? String(input.status).toLowerCase() : undefined;\n if (status && !STAGES.includes(status)) throw new Error('status must be one of ' + STAGES.join(', ') + '.');\n const wanted = input.title.trim().toLowerCase();\n const existing = (await pieces.list()).find((r) => String(r.fields.title ?? '').toLowerCase() === wanted);\n const wordTarget = wholeNumber(input.words);\n const fields: Record<string, unknown> = {\n ...(format ? { format } : {}),\n ...(publishAt ? { publishAt } : {}),\n ...(input.assignee ? { assignee: input.assignee.trim() } : {}),\n ...(input.keyword ? { keyword: input.keyword.trim() } : {}),\n ...(input.angle ? { angle: input.angle.trim() } : {}),\n ...(wordTarget ? { words: wordTarget } : {}),\n ...(input.link ? { link: input.link.trim() } : {}),\n ...(input.note ? { notes: input.note.trim() } : {}),\n ...(status === 'published' ? { publishedAt: publishAt ?? today } : {}),\n };\n if (existing) {\n await pieces.update(existing.id, { fields });\n if (status && status !== existing.status) await pieces.transition(existing.id, status, { note: 'Updated from the plan' });\n note = 'Updated ' + String(existing.fields.title) + ' (' + existing.id + ').';\n } else {\n const record = await pieces.add({\n status: status ?? 'idea',\n fields: { title: input.title.trim(), format: format ?? 'article', ...fields },\n });\n note = 'Added ' + record.id + ' ' + String(record.fields.title) + ' as ' + record.status + (publishAt ? ', publishing ' + niceDay(publishAt) : '') + '.';\n }\n} else if (input.action === 'update_piece') {\n const record = await resolveIn(pieces, 'piece', 'pc-3');\n const fields: Record<string, unknown> = {};\n const publishAt = dateInput(input.publishAt, 'publishAt') ?? shifted(record.fields.publishAt, record.fields.title);\n if (publishAt) fields.publishAt = publishAt;\n if (input.assignee) fields.assignee = input.assignee.trim();\n if (input.keyword) fields.keyword = input.keyword.trim();\n if (input.angle) fields.angle = input.angle.trim();\n if (input.link) fields.link = input.link.trim();\n const wordTarget = wholeNumber(input.words);\n if (wordTarget) fields.words = wordTarget;\n const format = input.format ? String(input.format).toLowerCase() : undefined;\n if (format) {\n if (!FORMATS.includes(format)) throw new Error('format must be one of ' + FORMATS.join(', ') + '.');\n fields.format = format;\n }\n const status = input.status ? String(input.status).toLowerCase() : undefined;\n if (status && !STAGES.includes(status)) throw new Error('status must be one of ' + STAGES.join(', ') + '.');\n if (status === 'published' && record.status !== 'published') fields.publishedAt = today;\n if (!Object.keys(fields).length && !status && !input.note) {\n throw new Error('update_piece needs status, assignee, publishAt, shiftDays, keyword, angle, link, words, format, or note.');\n }\n if (Object.keys(fields).length) await pieces.update(record.id, { fields });\n if (status && status !== record.status) await pieces.transition(record.id, status, input.note ? { note: input.note } : {});\n else if (input.note) await pieces.update(record.id, { note: input.note });\n note =\n String(record.fields.title) + ' (' + record.id + ')' +\n (status && status !== record.status ? ' moved from ' + record.status + ' to ' + status : ' updated') +\n (fields.publishAt ? ', publishing ' + niceDay(String(fields.publishAt)) : '') +\n (fields.assignee ? ', now with ' + String(fields.assignee) : '') + '.';\n} else if (input.action === 'repurpose_piece') {\n const piece = await resolveIn(pieces, 'piece', 'pc-3');\n const format = spinFormat(input.format);\n if (!format) throw new Error('repurpose_piece needs format: ' + SPIN_FORMATS.join(', ') + '.');\n const want = Math.min(10, wholeNumber(input.count) || 1);\n const already = (await calendar.list()).filter((s) => s.fields.pieceId === piece.id && s.fields.format === format);\n const missing = want - already.length;\n const nouns = SPIN_NOUN[format] as string[];\n if (missing <= 0) {\n note =\n String(piece.fields.title) + ' (' + piece.id + ') already has ' + already.length + ' ' + (already.length === 1 ? nouns[0] : nouns[1]) +\n '; nothing added. Pass a higher count for more.';\n } else {\n const startAt = dateInput(input.startAt, 'startAt');\n const dates = spinoffDates(piece, format, already.length, missing, startAt, now) as string[];\n const angles = String(input.angle ?? '').split(/\\s*\\|\\s*|\\n+/).map((a) => a.trim()).filter(Boolean);\n const added: string[] = [];\n for (let i = 0; i < missing; i++) {\n const index = already.length + i;\n const record = await calendar.add({\n status: 'planned',\n fields: {\n title: spinoffTitle(format, index, Math.max(want, index + 1), String(piece.fields.title)),\n pieceId: piece.id,\n format,\n publishAt: dates[i],\n ...(input.channel ? { channel: input.channel.trim() } : {}),\n ...(input.assignee || piece.fields.assignee ? { assignee: (input.assignee ?? String(piece.fields.assignee)).trim() } : {}),\n ...(angles[i] ? { angle: angles[i] } : {}),\n },\n });\n added.push(record.id + ' ' + niceDay(dates[i]!));\n }\n note =\n 'Planned ' + missing + ' ' + (missing === 1 ? nouns[0] : nouns[1]) + ' for ' + String(piece.fields.title) + ' (' + piece.id + '): ' + added.join(', ') + '.';\n }\n} else if (input.action === 'update_spinoff') {\n const record = await resolveIn(calendar, 'spin-off', 'so-2');\n const fields: Record<string, unknown> = {};\n const publishAt = dateInput(input.publishAt, 'publishAt') ?? shifted(record.fields.publishAt, record.fields.title);\n if (publishAt) fields.publishAt = publishAt;\n if (input.channel) fields.channel = input.channel.trim();\n if (input.assignee) fields.assignee = input.assignee.trim();\n if (input.angle) fields.angle = input.angle.trim();\n if (input.link) fields.link = input.link.trim();\n const status = input.status ? String(input.status).toLowerCase() : undefined;\n if (status && !SPIN_STAGES.includes(status)) throw new Error('status must be one of ' + SPIN_STAGES.join(', ') + '.');\n if (!Object.keys(fields).length && !status && !input.note) {\n throw new Error('update_spinoff needs status, publishAt, shiftDays, channel, assignee, angle, link, or note.');\n }\n if (Object.keys(fields).length) await calendar.update(record.id, { fields });\n if (status && status !== record.status) await calendar.transition(record.id, status, input.note ? { note: input.note } : {});\n else if (input.note) await calendar.update(record.id, { note: input.note });\n note =\n String(record.fields.title) + ' (' + record.id + ')' +\n (status && status !== record.status ? ' moved from ' + record.status + ' to ' + status : ' updated') +\n (fields.publishAt ? ', going out ' + niceDay(String(fields.publishAt)) : '') + '.';\n} else if (input.action !== 'status' && input.action !== 'list') {\n throw new Error(\n \"Unknown action '\" + input.action + \"'. Use status, add_piece, update_piece, repurpose_piece, update_spinoff, or list.\",\n );\n}\n\nconst allPieces = await pieces.list();\nconst allSpinoffs = await calendar.list();\nconst view = studioPicture(allPieces, allSpinoffs, now, withinDays);\n\ngezel.output({\n inPipeline: view.inPipeline,\n dueSoon: view.dueSoon,\n late: view.late,\n repurposed: view.repurposed,\n summary:\n input.action === 'list'\n ? [\n ...allPieces.map((p) => '[' + p.status + '] ' + pieceLine(p, now)),\n ...allSpinoffs.map((s) => ' [' + s.status + '] ' + spinoffLine(s, allPieces, now)),\n ].join('\\n') || 'The studio is empty.'\n : (note ? note + ' ' : '') + view.summary,\n});\n"},"tools":[{"name":"studio_status","description":"The whole studio: the pipeline by stage, everything publishing in the next 14 days (late items first) with ids, stages and owners, who has what, and what each published piece has been repurposed into. Call it first when asked what is coming, who is on what, or what a piece still needs.","script":"content-store","inputs":{"type":"object","properties":{"withinDays":{"type":"number"}}},"bind":{"action":"status"},"state":true},{"name":"add_piece","description":"Save a long-form piece: title, format, stage, who writes it, publish date (YYYY-MM-DD), the search keyword and one line on its angle. An existing title is updated, never duplicated. Call it as soon as a piece is pitched or mentioned, before you describe it.","script":"content-store","inputs":{"type":"object","properties":{"title":{"type":"string"},"format":{"type":"string","enum":["article","guide","case-study","interview","essay","video","podcast","other"]},"status":{"type":"string","enum":["idea","brief","draft","edit","design","published"]},"assignee":{"type":"string"},"publishAt":{"type":"string"},"keyword":{"type":"string"},"angle":{"type":"string"},"words":{"type":"number"},"link":{"type":"string"},"note":{"type":"string"}},"required":["title"]},"bind":{"action":"add_piece"}},{"name":"update_piece","description":"Move a piece to another stage (idea, brief, draft, edit, design, published), hand it to someone else, or change its publish date. To push it later or earlier pass shiftDays and the studio does the date math. Call it the moment the person says a piece moved.","script":"content-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"status":{"type":"string","enum":["idea","brief","draft","edit","design","published"]},"assignee":{"type":"string"},"publishAt":{"type":"string"},"shiftDays":{"type":"number"},"keyword":{"type":"string"},"angle":{"type":"string"},"link":{"type":"string"},"note":{"type":"string"}}},"bind":{"action":"update_piece"}},{"name":"repurpose_piece","description":"Plan what a piece spins off: a newsletter, social posts, video chapters, short videos or quote cards. One call per format; count is how many of that format the piece should have in all (three posts = count 3), and the studio dates each one after the piece publishes. Call it as soon as repurposing is asked for, before you write any of it.","script":"content-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"format":{"type":"string","enum":["newsletter","social-post","video-chapters","short-video","quote-card","other"]},"count":{"type":"number"},"startAt":{"type":"string"},"channel":{"type":"string"},"assignee":{"type":"string"},"angle":{"type":"string"}},"required":["format"]},"bind":{"action":"repurpose_piece"}},{"name":"update_spinoff","description":"Move one of a piece's spin-offs (planned, drafted, scheduled, published), or change its date, channel or owner. To push it later or earlier pass shiftDays.","script":"content-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"status":{"type":"string","enum":["planned","drafted","scheduled","published"]},"publishAt":{"type":"string"},"shiftDays":{"type":"number"},"channel":{"type":"string"},"assignee":{"type":"string"},"angle":{"type":"string"},"link":{"type":"string"},"note":{"type":"string"}}},"bind":{"action":"update_spinoff"}},{"name":"list_pieces","description":"Every piece and spin-off with its stage, date and owner.","script":"content-store","inputs":{"type":"object","properties":{}},"bind":{"action":"list"}},{"name":"page_add_piece","description":"Add or update a piece.","script":"content-store","inputs":{"type":"object","properties":{"title":{"type":"string"},"format":{"type":"string","enum":["article","guide","case-study","interview","essay","video","podcast","other"]},"status":{"type":"string","enum":["idea","brief","draft","edit","design","published"]},"assignee":{"type":"string"},"publishAt":{"type":"string"},"keyword":{"type":"string"},"angle":{"type":"string"},"words":{"type":"number"},"link":{"type":"string"},"note":{"type":"string"}},"required":["title"]},"bind":{"action":"add_piece"}},{"name":"page_update_piece","description":"Move a piece to another stage.","script":"content-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"status":{"type":"string","enum":["idea","brief","draft","edit","design","published"]},"assignee":{"type":"string"},"publishAt":{"type":"string"},"shiftDays":{"type":"number"},"keyword":{"type":"string"},"angle":{"type":"string"},"link":{"type":"string"},"note":{"type":"string"}}},"bind":{"action":"update_piece"},"reaction":{"gezel":"managing-editor","prompt":"The person just moved a piece on the studio board. The studio now reads (its first sentence is what changed):\n{{output.summary}}\nIn two short sentences, confirm the move and name the next step for that piece; if it was just published, name the repurposing it has not had yet. Do not call tools.","hideSeed":true}},{"name":"page_repurpose_piece","description":"Plan what a piece spins off.","script":"content-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"format":{"type":"string","enum":["newsletter","social-post","video-chapters","short-video","quote-card","other"]},"count":{"type":"number"},"startAt":{"type":"string"},"channel":{"type":"string"},"assignee":{"type":"string"},"angle":{"type":"string"}},"required":["format"]},"bind":{"action":"repurpose_piece"}},{"name":"page_update_spinoff","description":"Move a spin-off to another stage.","script":"content-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"status":{"type":"string","enum":["planned","drafted","scheduled","published"]},"publishAt":{"type":"string"},"shiftDays":{"type":"number"},"channel":{"type":"string"},"assignee":{"type":"string"},"angle":{"type":"string"},"link":{"type":"string"},"note":{"type":"string"}}},"bind":{"action":"update_spinoff"}}],"pages":{"entry":"studio/index.html","api":1,"reads":[{"source":"workspace","path":"pieces.json"},{"source":"workspace","path":"calendar.json"}],"tools":["page_add_piece","page_update_piece","page_repurpose_piece","page_update_spinoff"]},"schedules":[],"workspaceSeed":["pieces.json","calendar.json"],"artifactsSeed":[],"availableVersions":["1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"customer-voice","name":"Customer Voice","description":"Gather what customers say and turn it into what to fix next. A researcher sorts reviews and survey answers into themes with counts and trends, flags the reviews that need a reply, and keeps an action list for what the business will change.","tags":["customer-feedback","surveys","ratings","reputation","small-business"],"category":"business","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.0.0","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"business":{"type":"string","title":"What kind of business is this?","description":"e.g. 'a café in Portland', 'a small publisher'.","default":"the business"},"sources":{"type":"string","title":"Where do customers leave feedback?","description":"e.g. 'Google and Yelp reviews and a receipt survey'.","default":"online reviews and a customer survey"}},"required":["business"]},"nameTemplate":"Customer Voice","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"researcher","voorman":true},{"templateId":"copywriter","voorman":false}],"toolsets":[],"craftbooks":["survey-analysis","review-reply-batch"],"scripts":{"voice-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { logStore, rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'voice-store',\n description:\n \"Read and update Customer Voice: the feedback log (feedback.json), its themes (themes.json) and the action list (actions.json). action:'status' for each theme's count and trend, what is not sorted yet, the replies owed and the open actions; 'log' to save a review or survey answer (the same words from the same author are never duplicated); 'tag' to sort feedback into themes; 'reply' to save a reply; 'mark_replied' once a reply is posted; 'add_action' (an existing title is updated); 'set_action' to move an action; 'import' to read a CSV of reviews under imports/; 'list' for every entry.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'status', 'log', 'tag', 'reply', 'mark_replied', 'add_action', 'set_action', 'import', or 'list'.\",\n required: true,\n },\n id: {\n type: 'string',\n description: \"Feedback id, e.g. 'fb-12' (for tag, several comma-separated: 'fb-12, fb-13'); for set_action an action id like 'ac-2'.\",\n },\n text: { type: 'string', description: \"The customer's words, exactly as written.\" },\n source: { type: 'string', description: 'google, yelp, tripadvisor, survey, email, social, in-person, or other.' },\n rating: { type: 'number', description: 'Stars, 1 to 5.' },\n stars: { type: 'string', description: \"Stars as text from the page, '1' to '5'.\" },\n author: { type: 'string', description: 'Who wrote it, as it appears.' },\n receivedAt: { type: 'string', description: 'The day it was written, YYYY-MM-DD (default today).' },\n themes: { type: 'string', description: \"Theme names, comma-separated, e.g. 'Slow weekend service, Friendly staff'.\" },\n kind: { type: 'string', description: 'For a new theme: praise, problem, or request.' },\n replyNeeded: { type: 'boolean', description: 'Whether it needs a reply (default: public reviews of 3 stars or fewer).' },\n reply: { type: 'string', description: 'The reply text, ready to post.' },\n posted: { type: 'boolean', description: 'True once the reply is live.' },\n title: { type: 'string', description: \"For actions: the action's title. Also finds it when no id is given.\" },\n theme: { type: 'string', description: 'For actions: the theme it answers, by name or id. For list: only that theme.' },\n owner: { type: 'string', description: 'Who takes the action.' },\n dueAt: { type: 'string', description: 'When the action is due, YYYY-MM-DD.' },\n status: { type: 'string', description: 'For set_action: todo, doing, or done.' },\n note: { type: 'string', description: 'What happened.' },\n file: { type: 'string', description: \"For import: the CSV's workspace path, e.g. 'imports/google-reviews.csv'.\" },\n },\n outputs: {\n themes: { type: 'number', description: 'Themes being tracked.' },\n repliesNeeded: { type: 'number', description: 'Feedback that still needs a reply posted.' },\n unsorted: { type: 'number', description: 'Feedback not sorted into a theme.' },\n openActions: { type: 'number', description: 'Actions not done.' },\n summary: { type: 'string', description: 'The picture, or the listing.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── voice-rules-start ──\n// Pure derivations: the feedback log folded into entries (with their themes,\n// replies and edits), theme counts over the last 30 days against the 30\n// before, the replies still owed, the CSV reader for imports, and the picture\n// the crew reads. Kept self-contained between these sentinels so unit tests\n// execute the shipped bytes.\nvar DAY_MS = 86400000;\nvar SOURCES = ['google', 'yelp', 'tripadvisor', 'survey', 'email', 'social', 'in-person', 'other'];\nvar PUBLIC_SOURCES = ['google', 'yelp', 'tripadvisor', 'social'];\nvar THEME_KINDS = ['praise', 'problem', 'request'];\nvar FEEDBACK_KINDS = ['review', 'survey', 'comment'];\nvar ACTION_STAGES = ['todo', 'doing', 'done'];\n\nfunction pad(n) {\n return n < 10 ? '0' + n : String(n);\n}\nfunction localDay(ms) {\n var d = new Date(ms);\n return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());\n}\nfunction normalizeDate(text) {\n var raw = String(text || '').trim();\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(raw)) return raw;\n if (/^\\d{4}-\\d{2}-\\d{2}[T ]/.test(raw)) return raw.slice(0, 10);\n var parsed = Date.parse(raw);\n return raw && isFinite(parsed) ? localDay(parsed) : null;\n}\nfunction daysAgo(day, nowMs) {\n var then = Date.parse(String(day || '').slice(0, 10) + 'T00:00:00');\n var today = Date.parse(localDay(nowMs) + 'T00:00:00');\n return isFinite(then) ? Math.round((today - then) / DAY_MS) : 0;\n}\nfunction nameKey(text) {\n return String(text || '').trim().toLowerCase().replace(/\\s+/g, ' ');\n}\nfunction textKey(text, author) {\n return nameKey(author) + '|' + nameKey(text).slice(0, 160);\n}\nfunction sourceOf(text) {\n var s = nameKey(text);\n if (SOURCES.indexOf(s) >= 0) return s;\n if (/google/.test(s)) return 'google';\n if (/yelp/.test(s)) return 'yelp';\n if (/trip ?advisor/.test(s)) return 'tripadvisor';\n if (/survey|questionnaire|form|typeform|nps|poll/.test(s)) return 'survey';\n if (/e-?mail|inbox/.test(s)) return 'email';\n if (/facebook|instagram|twitter|bluesky|tiktok|social|linkedin|\\bx\\b/.test(s)) return 'social';\n if (/in person|in-person|counter|store|shop floor|phone|call/.test(s)) return 'in-person';\n return 'other';\n}\nfunction feedbackKind(source) {\n return source === 'survey' ? 'survey' : PUBLIC_SOURCES.indexOf(source) >= 0 ? 'review' : 'comment';\n}\n// Stars from a number, '4/5', '4 stars' or a row of star characters; null when absent.\nfunction ratingOf(value, scale) {\n if (value === undefined || value === null || value === '') return null;\n var n = typeof value === 'number' ? value : NaN;\n if (typeof value === 'string') {\n var starCount = (value.match(/★/g) || []).length;\n n = starCount ? starCount : parseFloat(value.replace(',', '.'));\n }\n if (!isFinite(n)) return null;\n if (scale === 10) n = n / 2;\n return Math.min(5, Math.max(1, Math.round(n)));\n}\nfunction needsReply(source, rating, explicit) {\n if (explicit === true || explicit === false) return explicit;\n return PUBLIC_SOURCES.indexOf(source) >= 0 && typeof rating === 'number' && rating <= 3;\n}\nfunction guessKind(items) {\n var rated = items.filter(function (e) { return typeof e.rating === 'number'; });\n var avg = rated.length ? rated.reduce(function (s, e) { return s + e.rating; }, 0) / rated.length : null;\n var asks = items.some(function (e) { return /\\b(wish|please|would love|could you|should|add|bring back|more)\\b/i.test(e.text || ''); });\n if (avg !== null && avg >= 4 && !asks) return 'praise';\n if (asks && (avg === null || avg >= 3)) return 'request';\n return avg !== null && avg >= 4 ? 'praise' : 'problem';\n}\n// The log, folded: each feedback event becomes an entry; later events tag it, edit it, reply to it.\nfunction entries(events) {\n var list = [], byId = {};\n (events || []).forEach(function (e) {\n var d = e.data || {};\n if (FEEDBACK_KINDS.indexOf(e.kind) >= 0 && d.id && !byId[d.id]) {\n var entry = {\n id: d.id, kind: e.kind, text: e.note || '', source: d.source || 'other',\n rating: typeof d.rating === 'number' ? d.rating : null, author: d.author || '',\n day: d.day || String(e.at || '').slice(0, 10), themes: Array.isArray(d.themes) ? d.themes.slice() : [],\n replyNeeded: !!d.replyNeeded, reply: '', posted: false,\n };\n list.push(entry);\n byId[d.id] = entry;\n return;\n }\n var target = byId[d.feedbackId];\n if (!target) return;\n if (e.kind === 'tagged') target.themes = Array.isArray(d.themes) ? d.themes.slice() : [];\n else if (e.kind === 'edited') {\n if (typeof d.rating === 'number') target.rating = d.rating;\n if (d.source) target.source = d.source;\n if (typeof d.replyNeeded === 'boolean') target.replyNeeded = d.replyNeeded;\n if (Array.isArray(d.themes)) target.themes = d.themes.slice();\n } else if (e.kind === 'reply') {\n if (e.note) target.reply = e.note;\n if (d.posted) target.posted = true;\n } else if (e.kind === 'replied') target.posted = true;\n });\n return list;\n}\nfunction nextFeedbackNumber(events) {\n var max = 0;\n (events || []).forEach(function (e) {\n var m = /^fb-(\\d+)$/.exec(String((e.data && e.data.id) || ''));\n if (m) max = Math.max(max, Number(m[1]));\n });\n return max + 1;\n}\nfunction themeStats(themes, list, nowMs) {\n return themes\n .filter(function (t) { return t.status !== 'retired'; })\n .map(function (t) {\n var hits = list.filter(function (e) { return e.themes.indexOf(t.id) >= 0; });\n var recent = hits.filter(function (e) { var d = daysAgo(e.day, nowMs); return d >= 0 && d < 30; }).length;\n var before = hits.filter(function (e) { var d = daysAgo(e.day, nowMs); return d >= 30 && d < 60; }).length;\n var trend = !recent && !before ? 'quiet' : !before ? 'new this month' : recent > before ? 'rising' : recent < before ? 'falling' : 'steady';\n var latest = hits.slice().sort(function (a, b) { return String(b.day).localeCompare(String(a.day)); })[0] || null;\n return { id: t.id, name: String(t.fields.name), kind: t.fields.kind || 'problem', total: hits.length, recent: recent, before: before, trend: trend, latest: latest };\n })\n .sort(function (a, b) { return b.recent - a.recent || b.total - a.total || a.name.localeCompare(b.name); });\n}\nfunction repliesOwed(list) {\n return list\n .filter(function (e) { return e.replyNeeded && !e.posted; })\n .sort(function (a, b) { return String(a.day).localeCompare(String(b.day)) || a.id.localeCompare(b.id, undefined, { numeric: true }); });\n}\nfunction quote(text, length) {\n var t = String(text || '').replace(/\\s+/g, ' ').trim();\n return t.length > length ? t.slice(0, length - 1).trim() + '…' : t;\n}\nfunction feedbackLine(e, names) {\n var themeNames = e.themes.map(function (id) { return names[id] || id; });\n return (\n e.id + ' ' + e.source + (e.rating ? ' ' + e.rating + '/5' : '') + (e.author ? ' by ' + e.author : '') + ', ' + e.day + ': \"' + quote(e.text, 110) + '\"' +\n (themeNames.length ? ' [' + themeNames.join(', ') + ']' : ' [not sorted]') +\n (e.replyNeeded && !e.posted ? (e.reply ? ', reply drafted, not posted yet' : ', needs a reply') : e.posted ? ', replied' : '')\n );\n}\nfunction capped(items, max, render) {\n var shown = items.slice(0, max).map(render).join(' | ');\n return items.length > max ? shown + ' | and ' + (items.length - max) + ' more' : shown;\n}\nfunction picture(themes, list, actions, nowMs) {\n var names = {};\n themes.forEach(function (t) { names[t.id] = String(t.fields.name); });\n var stats = themeStats(themes, list, nowMs);\n var month = list.filter(function (e) { var d = daysAgo(e.day, nowMs); return d >= 0 && d < 30; });\n var rated = month.filter(function (e) { return typeof e.rating === 'number'; });\n var avg = rated.length ? Math.round((rated.reduce(function (s, e) { return s + e.rating; }, 0) / rated.length) * 10) / 10 : null;\n var unsorted = list.filter(function (e) { return !e.themes.length; });\n var owed = repliesOwed(list);\n var open = actions.filter(function (a) { return a.status !== 'done'; });\n var parts = [\n list.length + (list.length === 1 ? ' piece of feedback' : ' pieces of feedback') + ' logged, ' + month.length + ' in the last 30 days' +\n (avg !== null ? ', averaging ' + avg + ' of 5 stars' : '') + '.',\n ];\n parts.push(\n stats.length\n ? 'Themes, most mentioned in the last 30 days first: ' +\n stats.map(function (s) {\n return s.name + ' (' + s.id + ', ' + s.kind + '): ' + s.recent + ' in the last 30 days, ' + s.before + ' in the 30 before, ' + s.trend +\n (s.latest ? '; latest: \"' + quote(s.latest.text, 80) + '\"' : '');\n }).join(' | ') + '.'\n : 'No themes yet.',\n );\n parts.push(unsorted.length ? 'Not sorted into a theme yet: ' + capped(unsorted, 12, function (e) { return feedbackLine(e, names); }) + '.' : 'Everything is sorted into themes.');\n parts.push(owed.length ? 'Needs a reply, oldest first: ' + capped(owed, 10, function (e) { return feedbackLine(e, names); }) + '.' : 'No replies owed.');\n parts.push(\n open.length\n ? 'Open actions: ' +\n open.map(function (a) {\n var f = a.fields || {};\n return f.title + ' (' + a.id + ', ' + a.status + (f.theme && names[f.theme] ? ', for ' + names[f.theme] : '') + (f.owner ? ', owner ' + f.owner : '') + (f.dueAt ? ', due ' + f.dueAt : '') + ')';\n }).join(' | ') + '.'\n : 'No open actions.',\n );\n return { themes: stats.length, repliesNeeded: owed.length, unsorted: unsorted.length, openActions: open.length, summary: parts.join(' ') };\n}\n// ── CSV import: a header row names the columns; anything unrecognized is ignored. ──\nfunction parseCsv(text) {\n var src = String(text || '').replace(/^/, '');\n var first = src.split(/\\r?\\n/, 1)[0] || '';\n var delim = [',', ';', '\\t'].map(function (d) { return [d, first.split(d).length]; }).sort(function (a, b) { return b[1] - a[1]; })[0][0];\n var rows = [], row = [], cell = '', quoted = false;\n for (var i = 0; i < src.length; i++) {\n var c = src[i];\n if (quoted) {\n if (c === '\"') {\n if (src[i + 1] === '\"') { cell += '\"'; i++; } else quoted = false;\n } else cell += c;\n } else if (c === '\"' && cell === '') quoted = true;\n else if (c === delim) { row.push(cell); cell = ''; }\n else if (c === '\\n' || c === '\\r') {\n if (c === '\\r' && src[i + 1] === '\\n') i++;\n row.push(cell); rows.push(row); row = []; cell = '';\n } else cell += c;\n }\n if (cell !== '' || row.length) { row.push(cell); rows.push(row); }\n return rows.filter(function (r) { return r.some(function (v) { return String(v).trim() !== ''; }); });\n}\nfunction columnOf(header) {\n var h = nameKey(header);\n if (/(date|created|submitted|posted|timestamp|time|when)/.test(h)) return 'day';\n if (/(rating|stars?|score|nps)/.test(h)) return 'rating';\n if (/(author|reviewer|name|respondent)/.test(h)) return 'author';\n if (/(source|platform|site|channel)/.test(h)) return 'source';\n if (/(review|text|comment|feedback|body|message|answer|response|content|said|why)/.test(h)) return 'text';\n if (/(customer|user|who)/.test(h)) return 'author';\n return null;\n}\nfunction csvFeedback(text, defaultSource) {\n var rows = parseCsv(text);\n if (!rows.length) return { items: [], blank: 0, columns: {} };\n var at = {};\n rows[0].forEach(function (h, i) { var col = columnOf(h); if (col && at[col] === undefined) at[col] = i; });\n var hasHeader = Object.keys(at).length > 0;\n var body = hasHeader ? rows.slice(1) : rows;\n if (at.text === undefined) {\n // No column says it holds the words: take the one with the longest cells.\n var widths = (rows[0] || []).map(function (_, i) {\n if (Object.keys(at).some(function (k) { return at[k] === i; })) return -1;\n return body.reduce(function (s, r) { return s + String(r[i] || '').length; }, 0);\n });\n var widest = widths.indexOf(Math.max.apply(null, widths.concat([-1])));\n if (widest >= 0) at.text = widest;\n }\n var scale = at.rating !== undefined && body.some(function (r) { var v = parseFloat(r[at.rating]); return isFinite(v) && v > 5; }) ? 10 : 5;\n var items = [], blank = 0;\n body.forEach(function (r) {\n var words = at.text === undefined ? '' : String(r[at.text] || '').trim();\n if (!words) { blank += 1; return; }\n items.push({\n text: words,\n rating: at.rating === undefined ? null : ratingOf(String(r[at.rating] || '').trim(), scale),\n day: at.day === undefined ? null : normalizeDate(r[at.day]),\n author: at.author === undefined ? '' : String(r[at.author] || '').trim(),\n source: at.source !== undefined && String(r[at.source] || '').trim() ? sourceOf(r[at.source]) : defaultSource,\n });\n });\n return { items: items, blank: blank, columns: at };\n}\n// ── voice-rules-end ──\n\nconst FEEDBACK = 'feedback.json';\nconst feedback = logStore(gezel.fs, FEEDBACK);\nconst themes = rosterStore(gezel.fs, 'themes.json', { stages: ['active', 'retired'], idPrefix: 'th' });\nconst actions = rosterStore(gezel.fs, 'actions.json', { stages: ['todo', 'doing', 'done'], idPrefix: 'ac' });\n\nfunction upperFirst(text: string): string {\n return text.charAt(0).toUpperCase() + text.slice(1);\n}\n\n// Theme names to ids, reusing a theme whose name matches (or one the name clearly means);\n// a new name starts a new theme.\nasync function ensureThemes(text: string, kind: string): Promise<{ ids: string[]; created: string[] }> {\n const all = await themes.list();\n const ids: string[] = [];\n const created: string[] = [];\n for (const raw of String(text).split(/[,;\\n]+/)) {\n const name = raw.trim().replace(/^[\"']|[\"']$/g, '');\n if (!name) continue;\n let theme = all.find((t) => t.id === name.toLowerCase() || nameKey(t.fields.name) === nameKey(name));\n if (!theme) {\n const near = all.filter((t) => t.status !== 'retired' && (nameKey(t.fields.name).includes(nameKey(name)) || nameKey(name).includes(nameKey(t.fields.name))));\n if (near.length === 1) theme = near[0];\n }\n if (!theme) {\n theme = await themes.add({ status: 'active', fields: { name: upperFirst(name), kind } });\n all.push(theme);\n created.push(String(theme.fields.name));\n }\n if (!ids.includes(theme.id)) ids.push(theme.id);\n }\n return { ids, created };\n}\n\nasync function themeNames(ids: string[]): Promise<string> {\n const all = await themes.list();\n return ids.map((id) => String(all.find((t) => t.id === id)?.fields.name ?? id)).join(', ');\n}\n\nfunction feedbackIds(list: ReturnType<typeof entries>): string[] {\n const ids = String(input.id ?? '').split(/[\\s,;]+/).map((s) => s.trim().toLowerCase()).filter(Boolean);\n if (!ids.length) throw new Error(\"Pass 'id', e.g. 'fb-12'. Call action:'status' to see the ids.\");\n const unknown = ids.filter((id) => !list.some((e) => e.id === id));\n if (unknown.length) {\n throw new Error('No feedback ' + unknown.join(', ') + '. Known ids run from ' + (list[0]?.id ?? 'none') + ' to ' + (list[list.length - 1]?.id ?? 'none') + '.');\n }\n return ids;\n}\n\nasync function resolveAction(): Promise<string> {\n const all = await actions.list();\n const byId = input.id ? all.find((a) => a.id === input.id!.trim().toLowerCase()) : undefined;\n if (byId) return byId.id;\n const text = input.title ?? input.id;\n if (text) {\n const wanted = nameKey(text);\n const exact = all.filter((a) => nameKey(a.fields.title) === wanted);\n if (exact.length === 1) return exact[0]!.id;\n const partial = all.filter((a) => nameKey(a.fields.title).includes(wanted));\n if (partial.length === 1) return partial[0]!.id;\n if (partial.length > 1) throw new Error(\"More than one action matches '\" + text + \"': \" + partial.map((a) => a.id + ' ' + String(a.fields.title)).join(', ') + '. Pass id.');\n }\n throw new Error(\"Pass 'id' (e.g. 'ac-2') or the action's 'title'. Actions: \" + (all.map((a) => a.id + ' ' + String(a.fields.title)).join(', ') || 'none yet') + '.');\n}\n\n// Many rows at once: one read and one write of the log, in the store's own format.\nasync function appendMany(events: Array<{ at: string; kind: string; note: string; data: Record<string, unknown> }>): Promise<void> {\n let doc: { version: number; events: unknown[] };\n let raw: string | null = null;\n try {\n raw = await gezel.fs.read(FEEDBACK);\n } catch {\n raw = null;\n }\n if (raw === null) doc = { version: 1, events: [] };\n else {\n doc = JSON.parse(raw);\n if (doc.version !== 1 || !Array.isArray(doc.events)) throw new Error(FEEDBACK + ' is not a version 1 log; it was left untouched.');\n }\n doc.events.push(...events);\n await gezel.fs.write(FEEDBACK, JSON.stringify(doc, null, 2) + '\\n');\n}\n\nlet note = '';\nconst today = localDay(Date.now());\n\nif (input.action === 'log') {\n const text = (input.text ?? '').trim();\n if (!text) throw new Error(\"log needs 'text' (the customer's words).\");\n const day = input.receivedAt ? normalizeDate(input.receivedAt) : today;\n if (!day) throw new Error(\"receivedAt must be a date, e.g. '2026-11-02'.\");\n const source = sourceOf(input.source ?? 'other');\n const rating = ratingOf(input.rating ?? input.stars, 5);\n const events = await feedback.list();\n const list = entries(events);\n const existing = list.find((e) => textKey(e.text, e.author) === textKey(text, input.author));\n const tagged = input.themes?.trim()\n ? await ensureThemes(input.themes, THEME_KINDS.includes(String(input.kind)) ? String(input.kind) : guessKind([{ rating, text }]))\n : { ids: [], created: [] };\n if (existing) {\n await feedback.append({\n kind: 'edited',\n note: 'Logged again.',\n data: {\n feedbackId: existing.id,\n ...(rating !== null ? { rating } : {}),\n ...(input.source ? { source } : {}),\n ...(typeof input.replyNeeded === 'boolean' ? { replyNeeded: input.replyNeeded } : {}),\n ...(tagged.ids.length ? { themes: tagged.ids } : {}),\n },\n });\n note = 'Already in the log as ' + existing.id + '; updated it.';\n } else {\n const id = 'fb-' + nextFeedbackNumber(events);\n const owed = needsReply(source, rating, input.replyNeeded);\n await feedback.append({\n kind: feedbackKind(source),\n note: text,\n data: {\n id,\n source,\n ...(rating !== null ? { rating } : {}),\n ...(input.author?.trim() ? { author: input.author.trim() } : {}),\n day,\n themes: tagged.ids,\n replyNeeded: owed,\n },\n });\n note =\n 'Logged ' + id + (tagged.ids.length ? ' under ' + (await themeNames(tagged.ids)) : ', not sorted into a theme yet') +\n (tagged.created.length ? ' (new theme: ' + tagged.created.join(', ') + ')' : '') + (owed ? '; it needs a reply' : '') + '.';\n }\n} else if (input.action === 'tag') {\n if (!input.themes?.trim()) throw new Error(\"tag needs 'themes' (names, comma-separated).\");\n const list = entries(await feedback.list());\n const ids = feedbackIds(list);\n const chosen = list.filter((e) => ids.includes(e.id));\n const tagged = await ensureThemes(input.themes, THEME_KINDS.includes(String(input.kind)) ? String(input.kind) : guessKind(chosen));\n for (const id of ids) {\n await feedback.append({ kind: 'tagged', note: 'Sorted into themes.', data: { feedbackId: id, themes: tagged.ids } });\n }\n note =\n 'Sorted ' + ids.join(', ') + ' under ' + (await themeNames(tagged.ids)) +\n (tagged.created.length ? ' (new theme: ' + tagged.created.join(', ') + ')' : '') + '.';\n} else if (input.action === 'reply') {\n const list = entries(await feedback.list());\n const [id] = feedbackIds(list);\n const text = (input.reply ?? '').trim();\n if (!text && input.posted !== true) throw new Error(\"reply needs 'reply' (the text to post).\");\n if (text) {\n await feedback.append({ kind: 'reply', note: text, data: { feedbackId: id, posted: input.posted === true } });\n } else {\n await feedback.append({ kind: 'replied', note: 'Reply posted.', data: { feedbackId: id } });\n }\n note = input.posted === true ? 'Marked ' + id + ' replied.' : 'Saved a reply to ' + id + '; it is not posted yet.';\n} else if (input.action === 'mark_replied') {\n const list = entries(await feedback.list());\n const [id] = feedbackIds(list);\n await feedback.append({ kind: 'replied', note: input.note ?? 'Reply posted.', data: { feedbackId: id } });\n note = 'Marked ' + id + ' replied.';\n} else if (input.action === 'add_action') {\n const title = (input.title ?? '').trim();\n if (!title) throw new Error(\"add_action needs 'title'.\");\n const dueAt = input.dueAt ? normalizeDate(input.dueAt) : null;\n if (input.dueAt && !dueAt) throw new Error(\"dueAt must be a date, e.g. '2026-12-01'.\");\n const theme = input.theme?.trim() ? (await ensureThemes(input.theme, 'problem')).ids[0] : undefined;\n const fields: Record<string, unknown> = {\n ...(theme ? { theme } : {}),\n ...(input.owner?.trim() ? { owner: input.owner.trim() } : {}),\n ...(dueAt ? { dueAt } : {}),\n ...(input.note?.trim() ? { notes: input.note.trim() } : {}),\n };\n const existing = (await actions.list()).find((a) => nameKey(a.fields.title) === nameKey(title));\n if (existing) {\n await actions.update(existing.id, { fields });\n note = 'Updated the action ' + String(existing.fields.title) + '.';\n } else {\n const record = await actions.add({ status: 'todo', fields: { title, ...fields } });\n note = 'Added ' + record.id + ': ' + title + '.';\n }\n} else if (input.action === 'set_action') {\n const status = String(input.status ?? '').trim().toLowerCase();\n if (!ACTION_STAGES.includes(status)) throw new Error(\"set_action needs status 'todo', 'doing' or 'done'.\");\n const id = await resolveAction();\n const record = (await actions.get(id))!;\n await actions.transition(id, status, input.note ? { note: input.note } : {});\n if (status === 'done') await actions.update(id, { fields: { doneAt: today } });\n note = String(record.fields.title) + ' (' + id + ') is ' + (status === 'todo' ? 'to do' : status === 'doing' ? 'under way' : 'done') + '.';\n} else if (input.action === 'import') {\n const file = String(input.file ?? '').trim().replace(/\\\\/g, '/').replace(/^\\.?\\/+/, '');\n if (!file) throw new Error(\"import needs 'file', e.g. 'imports/reviews.csv'.\");\n if (!/\\.(csv|tsv|txt)$/i.test(file) || file.split('/').includes('..')) {\n throw new Error('import reads a .csv, .tsv or .txt file in the workspace, e.g. imports/reviews.csv.');\n }\n let text: string;\n try {\n text = await gezel.fs.read(file);\n } catch {\n throw new Error(\"Could not read '\" + file + \"'. Add the file on the Customer Voice page first; it lands under imports/.\");\n }\n const parsed = csvFeedback(text, sourceOf(input.source ?? file));\n if (parsed.columns.text === undefined) throw new Error('No column of customer comments found in ' + file + '. Name one review, comment, feedback or text.');\n const events = await feedback.list();\n const seen = new Set(entries(events).map((e) => textKey(e.text, e.author)));\n let next = nextFeedbackNumber(events);\n let repeats = 0;\n const rows = parsed.items.slice(0, 2000);\n const fresh: Array<{ at: string; kind: string; note: string; data: Record<string, unknown> }> = [];\n for (const item of rows) {\n const key = textKey(item.text, item.author);\n if (seen.has(key)) {\n repeats += 1;\n continue;\n }\n seen.add(key);\n fresh.push({\n at: new Date().toISOString(),\n kind: feedbackKind(item.source),\n note: item.text,\n data: {\n id: 'fb-' + next++,\n source: item.source,\n ...(item.rating !== null ? { rating: item.rating } : {}),\n ...(item.author ? { author: item.author } : {}),\n day: item.day ?? today,\n themes: [],\n replyNeeded: needsReply(item.source, item.rating, undefined),\n imported: file,\n },\n });\n }\n if (fresh.length) await appendMany(fresh);\n note =\n 'Imported ' + fresh.length + (fresh.length === 1 ? ' entry' : ' entries') + ' from ' + file +\n (repeats ? ' (' + repeats + ' already in the log)' : '') + (parsed.blank ? ', skipped ' + parsed.blank + (parsed.blank === 1 ? ' blank row' : ' blank rows') : '') +\n (parsed.items.length > rows.length ? ', stopped at 2000 rows' : '') +\n (fresh.length ? '; ' + fresh.length + ' new ' + (fresh.length === 1 ? 'entry is' : 'entries are') + ' not sorted into themes yet' : '') + '.';\n} else if (input.action !== 'status' && input.action !== 'list') {\n throw new Error(\"Unknown action '\" + input.action + \"'. Use status, log, tag, reply, mark_replied, add_action, set_action, import, or list.\");\n}\n\nconst list = entries(await feedback.list());\nconst themeRecords = await themes.list();\nconst actionRecords = await actions.list();\nconst view = picture(themeRecords, list, actionRecords, Date.now());\n\nlet listing = '';\nif (input.action === 'list') {\n const names: Record<string, string> = {};\n themeRecords.forEach((t) => { names[t.id] = String(t.fields.name); });\n const themeId = input.theme ? themeRecords.find((t) => t.id === input.theme!.trim().toLowerCase() || nameKey(t.fields.name) === nameKey(input.theme))?.id : undefined;\n if (input.theme && !themeId) throw new Error(\"No theme '\" + input.theme + \"'. Themes: \" + themeRecords.map((t) => t.id + ' ' + String(t.fields.name)).join(', ') + '.');\n const shown = themeId ? list.filter((e) => e.themes.includes(themeId)) : list;\n listing =\n shown.map((e) => feedbackLine(e, names) + (e.reply ? '; reply: \"' + quote(e.reply, 160) + '\"' : '')).join('\\n') || 'No feedback logged yet.';\n if (!themeId && actionRecords.length) {\n listing += '\\nActions: ' + actionRecords.map((a) => '[' + a.status + '] ' + String(a.fields.title) + ' (' + a.id + ')').join(' | ');\n }\n}\n\ngezel.output({\n themes: view.themes,\n repliesNeeded: view.repliesNeeded,\n unsorted: view.unsorted,\n openActions: view.openActions,\n summary: input.action === 'list' ? listing : (note ? note + ' ' : '') + view.summary,\n});\n"},"tools":[{"name":"voice_status","description":"What customers are saying now: each theme with its count over the last 30 days, the 30 before and the trend, the feedback not yet sorted into a theme, the reviews that still need a reply (oldest first), and the open actions. Every entry has its id. Call it first when asked what customers say.","script":"voice-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"},"state":true},{"name":"log_feedback","description":"Save a review, survey answer or comment exactly as the customer wrote it: text, source, rating (1 to 5 stars), author, the day it was written (YYYY-MM-DD), and its themes by name (comma-separated; reuse names from the status, a new name starts a theme). Public reviews of 3 stars or fewer are marked as needing a reply. The same words from the same author update the entry, never duplicate it. Call it as soon as feedback is shared, before you discuss it.","script":"voice-store","inputs":{"type":"object","properties":{"text":{"type":"string"},"source":{"type":"string","enum":["google","yelp","tripadvisor","survey","email","social","in-person","other"]},"rating":{"type":"number"},"author":{"type":"string"},"receivedAt":{"type":"string"},"themes":{"type":"string"},"kind":{"type":"string","enum":["praise","problem","request"]},"replyNeeded":{"type":"boolean"}},"required":["text"]},"bind":{"action":"log"}},{"name":"tag_feedback","description":"Sort feedback into themes: one id or several comma-separated ('fb-12, fb-13') and the theme names, reusing names from the status; a new name starts a new theme (kind: praise, problem or request). Call it as soon as you have decided, before you report it.","script":"voice-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"themes":{"type":"string"},"kind":{"type":"string","enum":["praise","problem","request"]}},"required":["id","themes"]},"bind":{"action":"tag"}},{"name":"save_reply","description":"Save a reply to a review, ready for the person to post where the review lives. Mention a fix only when an open action covers it, and never offer a refund, discount or free item the business has not agreed. Pass posted: true once the person says it is live. Call it as soon as the reply is drafted, before you show it.","script":"voice-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"reply":{"type":"string"},"posted":{"type":"boolean"}},"required":["id"]},"bind":{"action":"reply"}},{"name":"add_action","description":"Add an action the business agreed to take: title, the theme it answers (by name), owner and due date (YYYY-MM-DD). An existing title is updated, never duplicated. Call it as soon as an action is agreed, before you describe it.","script":"voice-store","inputs":{"type":"object","properties":{"title":{"type":"string"},"theme":{"type":"string"},"owner":{"type":"string"},"dueAt":{"type":"string"},"note":{"type":"string"}},"required":["title"]},"bind":{"action":"add_action"}},{"name":"set_action_status","description":"Move an action to todo, doing or done, by id or title. Call it the moment the person says it moved.","script":"voice-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"status":{"type":"string","enum":["todo","doing","done"]},"note":{"type":"string"}},"required":["status"]},"bind":{"action":"set_action"}},{"name":"import_reviews","description":"Read a CSV of reviews or survey answers the person added under imports/ (e.g. 'imports/google-reviews.csv') into the log. Rows already in the log are skipped; new rows arrive unsorted.","script":"voice-store","inputs":{"type":"object","properties":{"file":{"type":"string"},"source":{"type":"string","enum":["google","yelp","tripadvisor","survey","email","social","in-person","other"]}},"required":["file"]},"bind":{"action":"import"}},{"name":"list_feedback","description":"Every piece of feedback with its themes and replies, or only one theme (by name), plus the actions.","script":"voice-store","inputs":{"type":"object","properties":{"theme":{"type":"string"}}},"bind":{"action":"list"}},{"name":"page_log_feedback","description":"Log a review or survey answer.","script":"voice-store","inputs":{"type":"object","properties":{"text":{"type":"string"},"source":{"type":"string","enum":["google","yelp","tripadvisor","survey","email","social","in-person","other"]},"stars":{"type":"string","enum":["1","2","3","4","5"]},"author":{"type":"string"},"receivedAt":{"type":"string"},"themes":{"type":"string"}},"required":["text"]},"bind":{"action":"log"}},{"name":"page_add_action","description":"Add an action.","script":"voice-store","inputs":{"type":"object","properties":{"title":{"type":"string"},"theme":{"type":"string"},"owner":{"type":"string"},"dueAt":{"type":"string"},"note":{"type":"string"}},"required":["title"]},"bind":{"action":"add_action"}},{"name":"page_set_action_status","description":"Move an action.","script":"voice-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"status":{"type":"string","enum":["todo","doing","done"]},"note":{"type":"string"}},"required":["status"]},"bind":{"action":"set_action"},"reaction":{"gezel":"researcher","prompt":"The person just updated an action on the Customer Voice page. The board now reads (its first sentence is what changed):\n{{output.summary}}\nIn two short sentences, confirm what changed and say how the theme it answers is trending this month. Do not call tools.","hideSeed":true}},{"name":"page_import_reviews","description":"Read an added CSV of reviews into the log.","script":"voice-store","inputs":{"type":"object","properties":{"file":{"type":"string"},"source":{"type":"string","enum":["google","yelp","tripadvisor","survey","email","social","in-person","other"]}},"required":["file"]},"bind":{"action":"import"},"reaction":{"gezel":"researcher","prompt":"The person just added a file of reviews or survey answers on the Customer Voice page. The board now reads (its first sentence is what changed):\n{{output.summary}}\nIn two short sentences, say how many entries arrived and offer to sort the new ones into themes. Do not call tools.","hideSeed":true}},{"name":"page_mark_replied","description":"Mark a review replied.","script":"voice-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"note":{"type":"string"}},"required":["id"]},"bind":{"action":"mark_replied"}}],"pages":{"imports":[{"id":"reviews","source":"workspace","path":"imports","accept":[".csv",".tsv",".txt"],"maxFileBytes":10485760}],"entry":"voice/index.html","api":1,"reads":[{"source":"workspace","path":"feedback.json"},{"source":"workspace","path":"themes.json"},{"source":"workspace","path":"actions.json"},{"source":"workspace","path":"imports","subtree":true}],"tools":["page_log_feedback","page_add_action","page_set_action_status","page_import_reviews","page_mark_replied"]},"schedules":[],"workspaceSeed":["feedback.json","themes.json","actions.json"],"artifactsSeed":[],"availableVersions":["1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"data-analysis","name":"Data Analysis","description":"Explore the datasets in a project folder. A live dashboard finds spreadsheets and data files and opens them in Gezel's file viewers.","tags":["data","analysis","spreadsheets","csv","dashboard","reports"],"category":"data","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.2","releasedAt":"2026-11-02T18:00:00.000Z","extends":"data-analysis","nameTemplate":"Data Analysis","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"researcher","voorman":true}],"toolsets":[],"craftbooks":[],"tools":[],"pages":{"imports":[{"id":"data","source":"workspace","path":".","accept":[".csv",".tsv",".tab",".xlsx",".xls",".xlsm",".xlsb",".ods",".numbers",".json",".jsonl",".ndjson",".parquet",".arrow",".feather",".sqlite",".sqlite3",".db",".duckdb",".h5",".hdf5",".rds",".rdata",".sav",".dta",".sas7bdat",".xml",".html",".htm",".pdf",".md",".docx",".pptx",".ipynb"],"maxFileBytes":268435456}],"entry":"index.html","api":1,"reads":[{"source":"workspace","path":".","subtree":true}]},"schedules":[],"workspaceSeed":[],"artifactsSeed":[],"availableVersions":["1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"design-scheme","name":"Design Scheme","description":"Explore color schemes and design directions with a designer. Palettes are saved as artifacts and shown on a live gallery.","tags":["design","color","palette","branding","prototype"],"category":"creative","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.4","releasedAt":"2026-11-02T18:00:00.000Z","extends":"design-prototype","params":{"type":"object","properties":{"brief":{"type":"string","title":"What are you designing?","description":"A short brief — e.g. \"a calm meditation app\", \"a bold sports brand\".","default":"a new brand"}},"required":["brief"]},"nameTemplate":"Design Scheme: {{brief}}","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"designer","voorman":true}],"toolsets":[],"craftbooks":[],"scripts":{"scheme-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\n\nexport const meta = defineScript({\n name: 'scheme-store',\n description:\n \"Save and list the project's design color schemes. Call action:'save' with a name and an array of hex colors to add a scheme (it lands in artifacts/schemes/ and shows on the project's gallery). Call action:'list' to see what's saved.\",\n inputs: {\n action: { type: 'string', description: \"'save' or 'list'.\", required: true },\n name: { type: 'string', description: \"Scheme name (required for 'save'), e.g. 'Dusk'.\" },\n colors: {\n type: 'json',\n description: \"Array of hex colors for 'save', e.g. [\\\"#1b1a2e\\\", \\\"#e0894a\\\", \\\"#f5f0e8\\\"].\",\n },\n },\n outputs: {\n count: { type: 'number', description: 'How many schemes are saved.' },\n message: { type: 'string', description: 'Human-readable summary.' },\n },\n requires: ['artifacts.read', 'artifacts.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\ninterface Scheme {\n name: string;\n file: string;\n colors: string[];\n}\n\nconst INDEX = 'schemes/index.json';\n\nasync function loadIndex(): Promise<Scheme[]> {\n try {\n const raw = await gezel.artifacts.read(INDEX);\n const parsed = JSON.parse(raw) as { schemes?: Scheme[] };\n return Array.isArray(parsed.schemes) ? parsed.schemes : [];\n } catch {\n return [];\n }\n}\n\nfunction slugify(s: string): string {\n return (\n s\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '') || 'scheme'\n );\n}\n\nconst schemes = await loadIndex();\n\nif (input.action === 'save') {\n const name = (input.name ?? '').trim();\n const colors = Array.isArray(input.colors) ? input.colors.map(String) : [];\n if (!name || colors.length === 0) {\n gezel.output({ count: schemes.length, message: 'save needs a name and a non-empty colors array.' });\n } else {\n const file = `schemes/${slugify(name)}.json`;\n await gezel.artifacts.write(file, `${JSON.stringify({ name, colors }, null, 2)}\\n`);\n const next = [...schemes.filter((s) => s.file !== file), { name, file, colors }];\n await gezel.artifacts.write(INDEX, `${JSON.stringify({ schemes: next }, null, 2)}\\n`);\n gezel.output({ count: next.length, message: `Saved \"${name}\" (${colors.length} colors). ${next.length} scheme(s) total.` });\n }\n} else {\n gezel.output({\n count: schemes.length,\n message: schemes.length\n ? `${schemes.length} scheme(s): ${schemes.map((s) => s.name).join(', ')}.`\n : 'No schemes saved yet.',\n });\n}\n"},"tools":[{"name":"save_scheme","description":"Save a named color scheme so it shows on the gallery.","script":"scheme-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"colors":{"type":"array","items":{"type":"string"}}}},"bind":{"action":"save"}},{"name":"page_save_scheme","description":"Save a named color scheme so it shows on the gallery.","script":"scheme-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"colors":{"type":"array","items":{"type":"string"}}}},"bind":{"action":"save"}}],"pages":{"entry":"gallery/index.html","api":1,"reads":[{"source":"artifacts","path":"schemes/index.json"}],"tools":["page_save_scheme"]},"schedules":[],"workspaceSeed":[],"artifactsSeed":["schemes/index.json","schemes/warm-dusk.json"],"availableVersions":["1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"email","name":"Email / Inbox","description":"Sync an email account into a project as canonical markdown, then triage, draft, and summarize correspondence with a gezel.","tags":["email","inbox","triage","correspondence","builtin"],"category":"communication","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.0","releasedAt":"2026-07-06T00:00:00Z","extends":"email","aboutTemplate":"about.md","gezels":[],"toolsets":[],"craftbooks":[],"tools":[],"schedules":[],"workspaceSeed":[],"artifactsSeed":[],"notes":"Wraps the native mail pipeline (packages/service/src/mail) as a catalog entry so it appears in the New Project gallery alongside custom project types. Mailbox linking (IMAP / OAuth) remains a native creation step; this manifest carries no toolsets or scripts.","availableVersions":["1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"event-desk","name":"Event Desk","description":"Run a business event, from a client summit to a team offsite or a launch party. An event planner compares the venues, keeps every vendor with its contract and deposits, tracks RSVPs and dietary needs, holds the run of show, and shows the budget against what is signed.","tags":["conference","summit","client-summit","offsite","run-of-show","vendors","small-business"],"category":"business","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.0.0","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"event":{"type":"string","title":"What's the event?","description":"e.g. 'our client summit', 'the team offsite in March', 'the spring launch party'.","default":"our client summit"},"date":{"type":"string","title":"When is it?","description":"The date, e.g. 2026-12-10. Leave it empty if it is not set yet; change it any time.","default":""}},"required":["event"]},"nameTemplate":"Event Desk","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"ceremoniemeester","voorman":true},{"templateId":"kantoormeester","voorman":false},{"templateId":"copywriter","voorman":false}],"toolsets":[],"craftbooks":["run-of-show","invitation-design","comparison-matrix"],"scripts":{"event-desk-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { type RosterRecord, ledgerStore, rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'event-desk-store',\n description:\n \"Read and update the event desk: event.json (the event's details and run of show), venues.json, vendors.json and guests.json (rosters), and budget.json (payments in integer cents). action:'status' for the whole picture; 'compare' to compare the venues for a headcount; 'add_venue', 'book_venue', 'add_vendor', 'pay', 'add_guest', 'rsvp', 'set_event' and 'program' to change it; 'guests' for the whole guest list. An add with an existing name updates that record, never duplicates it. Amounts are in dollars.\",\n inputs: {\n action: {\n type: 'string',\n description:\n \"One of 'status', 'compare', 'add_venue', 'book_venue', 'add_vendor', 'pay', 'add_guest', 'rsvp', 'set_event', 'program', or 'guests'.\",\n required: true,\n },\n id: { type: 'string', description: \"A record id: a venue 've-2', a vendor 'vn-3' or a guest 'gu-12'.\" },\n name: {\n type: 'string',\n description: \"The venue's, vendor's or guest's name. Also finds the record when no id is given.\",\n },\n occasion: { type: 'string', description: \"The event's name, e.g. 'Fernwood Client Summit'.\" },\n date: { type: 'string', description: 'The event date, YYYY-MM-DD.' },\n time: {\n type: 'string',\n description:\n \"For set_event, the event's hours as they should be printed ('3:00 to 8:30 pm'). For program, the item's start time ('4:30 pm' or '16:30').\",\n },\n host: { type: 'string', description: 'Who hosts the event.' },\n rsvp: { type: 'string', description: 'How and by when guests reply, exactly as it should be printed.' },\n headcount: { type: 'number', description: 'How many guests the event plans for.' },\n budget: { type: 'number', description: 'The whole budget in dollars (replaces it).' },\n budgetChange: { type: 'number', description: 'Dollars to add to the budget (negative to cut it).' },\n capacity: { type: 'number', description: 'How many guests the venue holds.' },\n fee: { type: 'number', description: \"The venue's hire fee in dollars.\" },\n cateringPerHead: {\n type: 'number',\n description: 'In-house catering per guest in dollars; leave it out when you bring your own caterer.',\n },\n av: { type: 'string', description: \"Whether sound and screens come with the venue: 'included' or 'extra'.\" },\n location: { type: 'string', description: 'Where the venue is.' },\n category: {\n type: 'string',\n description: 'venue, catering, av, entertainment, photography, rentals, decor, transport, or other.',\n },\n contract: { type: 'number', description: \"The vendor's agreed or quoted total in dollars (replaces it).\" },\n contractChange: {\n type: 'number',\n description: \"Dollars to add to the vendor's total (negative when it drops).\",\n },\n deposit: { type: 'number', description: 'The deposit in dollars.' },\n depositDueAt: { type: 'string', description: 'When the deposit is due, YYYY-MM-DD.' },\n contact: { type: 'string', description: 'Who to call at the vendor, with a number.' },\n arrival: { type: 'string', description: \"When the vendor arrives on the day ('2 pm' or '14:00').\" },\n amount: { type: 'number', description: 'A payment in dollars.' },\n kind: { type: 'string', description: 'For pay: deposit, balance, or other.' },\n company: { type: 'string', description: \"The guest's company.\" },\n response: { type: 'string', description: 'invited, yes, or no.' },\n dietary: {\n type: 'string',\n description: \"What the guest can't eat, as they said it ('vegetarian', 'nut allergy'), or 'none'.\",\n },\n partySize: {\n type: 'number',\n description: 'How many people the invitation covers, the guest included (replaces it).',\n },\n joining: { type: 'number', description: 'How many extra people come with this guest (added to their party).' },\n item: { type: 'string', description: \"A run-of-show item, e.g. 'Welcome from Fernwood'.\" },\n owner: { type: 'string', description: \"Who's on point for the item.\" },\n remove: { type: 'boolean', description: 'For program: take the item off the run of show.' },\n status: {\n type: 'string',\n description: 'A venue: shortlisted, visited, held, or declined. A vendor: quoted, booked, or dropped.',\n },\n note: { type: 'string', description: 'Anything to keep with it, with reference numbers exactly as written.' },\n guests: {\n type: 'number',\n description: 'For compare: the headcount to compare for (default: the planned headcount).',\n },\n },\n outputs: {\n attending: { type: 'number', description: 'People coming: yes answers with the guests they bring.' },\n noDietaryAnswer: { type: 'array', itemType: 'string', description: 'Every attending guest with no dietary answer yet, by name.' },\n budgetLeft: { type: 'number', description: 'Budget not yet committed to booked vendors, in dollars.' },\n summary: {\n type: 'string',\n description: 'What changed first, then the whole picture (or the venue comparison, or the guest list).',\n },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── event-desk-rules-start ──\n// Pure derivations: money in integer cents, local calendar days, clock times,\n// dietary answers, the venue comparison and the desk picture the crew reads.\n// Kept self-contained between these sentinels so tests (and the page's demo)\n// execute the shipped bytes.\nvar DAY_MS = 86400000;\nvar VENUE_STAGES = ['shortlisted', 'visited', 'held', 'booked', 'declined'];\nvar VENDOR_STAGES = ['quoted', 'booked', 'paid', 'dropped'];\nvar GUEST_STAGES = ['invited', 'yes', 'no'];\nvar VENDOR_KINDS = ['venue', 'catering', 'av', 'entertainment', 'photography', 'rentals', 'decor', 'transport', 'other'];\n\nfunction pad(n) {\n return n < 10 ? '0' + n : String(n);\n}\nfunction localDay(ms) {\n var d = new Date(ms);\n return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());\n}\nfunction isDay(text) {\n return /^\\d{4}-\\d{2}-\\d{2}$/.test(String(text || ''));\n}\nfunction normalizeDate(text, nowMs) {\n var raw = String(text || '').trim();\n if (isDay(raw)) return raw;\n // Only something that reads as a date: a month name with a day, or numbers like 12/10.\n if (!/\\b(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\\.?\\s+\\d|\\d\\s+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)|\\d{1,4}[/.-]\\d{1,2}[/.-]\\d{1,4}/i.test(raw)) return null;\n if (/\\d{4}/.test(raw)) {\n var full = Date.parse(raw);\n return isFinite(full) ? localDay(full) : null;\n }\n // 'December 10' names the next December 10, not one in 2001.\n var now = new Date(nowMs || Date.now());\n var parsed = Date.parse(raw + ' ' + now.getFullYear());\n if (!isFinite(parsed)) return null;\n if (parsed < now.getTime() - 31 * DAY_MS) parsed = Date.parse(raw + ' ' + (now.getFullYear() + 1));\n return localDay(parsed);\n}\nfunction daysLeft(day, nowMs) {\n var due = Date.parse(String(day).slice(0, 10) + 'T00:00:00');\n var today = Date.parse(localDay(nowMs) + 'T00:00:00');\n return Math.round((due - today) / DAY_MS);\n}\nfunction when(days) {\n if (days < 0) return -days + (days === -1 ? ' day late' : ' days late');\n if (days === 0) return 'due today';\n return 'in ' + days + (days === 1 ? ' day' : ' days');\n}\nfunction key(text) {\n return String(text || '')\n .normalize('NFD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9&]+/g, ' ')\n .trim();\n}\n// 'exact', 'partial' (the name starts with the words given, or contains them whole), or ''.\nfunction nameMatch(name, wanted) {\n var have = key(name);\n var want = key(wanted);\n if (!have || !want) return '';\n if (have === want) return 'exact';\n return (' ' + have).indexOf(' ' + want) >= 0 || (' ' + want + ' ').indexOf(' ' + have + ' ') >= 0 ? 'partial' : '';\n}\nfunction toCents(amount) {\n var n = typeof amount === 'string' ? Number(String(amount).replace(/[$,\\s]/g, '')) : amount;\n return typeof n === 'number' && isFinite(n) ? Math.round(n * 100) : null;\n}\nfunction money(cents) {\n var c = Math.round(Number(cents) || 0);\n var sign = c < 0 ? '-' : '';\n c = Math.abs(c);\n var whole = String(Math.floor(c / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\n return sign + '$' + whole + (c % 100 ? '.' + pad(c % 100) : '');\n}\nfunction normalizeTime(text) {\n var m = String(text || '')\n .trim()\n .toLowerCase()\n .replace(/\\s+/g, '')\n .match(/^(\\d{1,2})(?:[:.h](\\d{2}))?(a\\.?m\\.?|p\\.?m\\.?)?$/);\n if (!m) return null;\n var h = Number(m[1]);\n var min = m[2] ? Number(m[2]) : 0;\n if (m[3]) {\n if (h < 1 || h > 12) return null;\n if (m[3].charAt(0) === 'p' && h !== 12) h += 12;\n if (m[3].charAt(0) === 'a' && h === 12) h = 0;\n }\n if (h > 23 || min > 59) return null;\n return pad(h) + ':' + pad(min);\n}\nfunction clock(hhmm) {\n var parts = String(hhmm || '').split(':');\n var h = Number(parts[0]);\n if (!isFinite(h) || parts.length !== 2) return String(hhmm || '');\n return ((h % 12) || 12) + (parts[1] === '00' ? '' : ':' + parts[1]) + (h < 12 ? ' am' : ' pm');\n}\nfunction normalizeDietary(text) {\n var t = String(text || '').trim().toLowerCase().replace(/\\s+/g, ' ').replace(/[.!]+$/, '');\n if (!t) return '';\n if (/^(none|no|nothing|n\\/?a|no restrictions?|no needs|no dietary needs|nothing special|eats anything|anything)$/.test(t)) return 'none';\n var aliases = {\n veg: 'vegetarian',\n veggie: 'vegetarian',\n gf: 'gluten-free',\n 'gluten free': 'gluten-free',\n 'no gluten': 'gluten-free',\n 'dairy free': 'dairy-free',\n 'no dairy': 'dairy-free',\n nuts: 'nut allergy',\n 'no nuts': 'nut allergy',\n 'nut free': 'nut allergy',\n };\n return aliases[t] || t;\n}\nfunction people(guest) {\n var n = Number(guest && guest.fields && guest.fields.partySize);\n return n >= 1 ? Math.round(n) : 1;\n}\nfunction paidFor(vendorId, entries) {\n return entries\n .filter(function (e) {\n return e.kind === 'out' && e.data && e.data.vendorId === vendorId;\n })\n .reduce(function (sum, e) {\n return sum + (Number(e.amountCents) || 0);\n }, 0);\n}\nfunction blankEvent() {\n return { version: 1, occasion: '', date: '', time: '', venue: '', host: '', rsvp: '', headcount: 0, budgetCents: 0, program: [] };\n}\nfunction guestTag(g, extra) {\n var f = g.fields || {};\n return f.name + ' (' + g.id + (f.company ? ', ' + f.company : '') + (extra ? ', ' + extra : '') + (people(g) > 1 ? ', party of ' + people(g) : '') + ')';\n}\nfunction venueCost(venue, guests) {\n var f = venue.fields || {};\n var fee = Number(f.feeCents) || 0;\n var perHead = Number(f.cateringPerHeadCents) || 0;\n var total = fee + perHead * guests;\n return { fee: fee, perHead: perHead, total: total, each: guests > 0 ? Math.round(total / guests) : 0 };\n}\nfunction compareVenues(venues, guests) {\n var live = venues.filter(function (v) {\n return v.status !== 'declined';\n });\n if (!live.length) return { fits: 0, summary: 'No venues on the shortlist yet.' };\n var rows = live.map(function (v) {\n var f = v.fields || {};\n var cap = Number(f.capacity) || 0;\n var cost = venueCost(v, guests);\n return { v: v, cap: cap, fits: cap >= guests, cost: cost };\n });\n rows.sort(function (a, b) {\n return (b.fits ? 1 : 0) - (a.fits ? 1 : 0) || a.cost.each - b.cost.each;\n });\n var lines = rows.map(function (r) {\n var f = r.v.fields || {};\n return (\n f.name + ' (' + r.v.id + ', ' + r.v.status + '): ' +\n (r.cap ? 'holds ' + r.cap + (r.fits ? ', fits ' + guests : ', ' + (guests - r.cap) + ' short for ' + guests) : 'capacity unknown') +\n '; hire ' + money(r.cost.fee) +\n (r.cost.perHead\n ? ' plus in-house catering at ' + money(r.cost.perHead) + ' a guest = ' + money(r.cost.total) + ' for ' + guests + ' (' + money(r.cost.each) + ' a guest)'\n : ', bring your own caterer') +\n '; sound and screens ' + (f.av === 'included' ? 'included' : 'extra') +\n (f.location ? '; ' + f.location : '') +\n (f.notes ? '; ' + f.notes : '')\n );\n });\n var fit = rows.filter(function (r) { return r.fits; });\n var small = rows.filter(function (r) { return r.cap && !r.fits; });\n return {\n fits: fit.length,\n summary:\n 'Venues for ' + guests + ' guests, those that fit first: ' + lines.join(' | ') + '. ' +\n (fit.length ? 'Fits ' + guests + ': ' + fit.map(function (r) { return r.v.fields.name; }).join(', ') + '.' : 'None of them holds ' + guests + '.') +\n (small.length ? ' Too small: ' + small.map(function (r) { return r.v.fields.name; }).join(', ') + '.' : ''),\n };\n}\nfunction deskPicture(event, venues, vendors, guests, entries, nowMs) {\n var ev = event || blankEvent();\n var parts = [];\n var days = isDay(ev.date) ? daysLeft(ev.date, nowMs) : null;\n parts.push(\n (ev.occasion || 'The event') +\n (days === null ? (ev.date ? ', date to confirm (' + ev.date + ')' : ', date not set') : ' on ' + ev.date + (days > 0 ? ' (' + days + (days === 1 ? ' day' : ' days') + ' to go)' : days === 0 ? ' (today)' : ' (' + -days + ' days ago)')) +\n (ev.time ? ', ' + ev.time : '') +\n (ev.venue ? ', at ' + ev.venue : ', venue not booked yet') +\n (ev.host ? ', hosted by ' + ev.host : '') +\n '.',\n );\n var yes = guests.filter(function (g) { return g.status === 'yes'; });\n var no = guests.filter(function (g) { return g.status === 'no'; });\n var waiting = guests.filter(function (g) { return g.status === 'invited'; });\n var attending = yes.reduce(function (sum, g) { return sum + people(g); }, 0);\n parts.push(\n 'RSVPs: ' + yes.length + ' yes (' + attending + (attending === 1 ? ' person' : ' people') + ' with the guests they bring), ' + no.length + ' no, ' + waiting.length + ' not replied yet' +\n (ev.headcount ? '; planning for ' + ev.headcount : '') + '.',\n );\n // One list a dietary question selects: attending guests first, then those who have not replied.\n var noAnswer = yes.filter(function (g) { return !g.fields.dietary; });\n var pending = noAnswer.map(function (g) { return guestTag(g, 'attending'); }).concat(\n waiting.filter(function (g) { return !g.fields.dietary; }).map(function (g) { return guestTag(g, 'not replied'); }),\n );\n parts.push(\n !guests.length ? 'No guests on the list yet.' : pending.length ? 'No dietary answer yet, attending first: ' + pending.join(' | ') + '.' : 'Every guest has a dietary answer.',\n );\n var tally = {};\n yes.forEach(function (g) {\n var d = g.fields.dietary;\n if (d && d !== 'none') tally[d] = (tally[d] || 0) + 1;\n });\n var needs = Object.keys(tally).sort().map(function (d) { return d + ' ' + tally[d]; });\n parts.push(needs.length ? 'Dietary needs among those attending: ' + needs.join(', ') + '.' : 'No dietary needs among those attending so far.');\n if (waiting.length) parts.push('Not replied yet: ' + waiting.map(function (g) { return guestTag(g, ''); }).join(', ') + '.');\n\n var live = vendors.filter(function (v) { return v.status !== 'dropped'; });\n var due = [];\n live.forEach(function (v) {\n var f = v.fields || {};\n var paid = paidFor(v.id, entries);\n var deposit = Number(f.depositCents) || 0;\n if (v.status !== 'quoted' && deposit > paid) {\n due.push({ at: f.depositDueAt || '9999-12-31', text: f.name + ' (' + v.id + ') deposit ' + money(deposit - paid) + (isDay(f.depositDueAt) ? ', due ' + f.depositDueAt + ' (' + when(daysLeft(f.depositDueAt, nowMs)) + ')' : ', no due date') });\n }\n });\n due.sort(function (a, b) { return a.at.localeCompare(b.at); });\n parts.push(due.length ? 'Deposits still to pay, soonest first: ' + due.map(function (d) { return d.text; }).join(' | ') + '.' : 'No deposits outstanding.');\n\n var signed = live.filter(function (v) { return v.status === 'booked' || v.status === 'paid'; });\n var contracted = signed.reduce(function (sum, v) { return sum + (Number(v.fields.contractCents) || 0); }, 0);\n var paidTotal = entries.filter(function (e) { return e.kind === 'out'; }).reduce(function (sum, e) { return sum + (Number(e.amountCents) || 0); }, 0);\n var budget = Number(ev.budgetCents) || 0;\n var left = budget - contracted;\n parts.push(\n (budget ? 'Budget ' + money(budget) + ': ' : 'No budget set: ') +\n money(contracted) + ' signed with booked vendors, ' + money(paidTotal) + ' paid, ' + money(contracted - paidTotal) + ' still owed on signed contracts' +\n (budget ? ', ' + (left >= 0 ? money(left) + ' left to commit' : money(-left) + ' over budget') : '') + '.',\n );\n parts.push(\n live.length\n ? 'Vendors: ' + live.map(function (v) {\n var f = v.fields || {};\n return f.name + ' (' + v.id + ', ' + (f.category || 'other') + ', ' + v.status + (f.contractCents ? ', ' + money(f.contractCents) : '') + ', paid ' + money(paidFor(v.id, entries)) + (f.arrival ? ', arrives ' + clock(f.arrival) : '') + ')';\n }).join(' | ') + '.'\n : 'No vendors yet.',\n );\n parts.push(\n venues.length\n ? 'Venues: ' + venues.map(function (v) { return v.fields.name + ' (' + v.id + ', ' + v.status + (v.fields.capacity ? ', holds ' + v.fields.capacity : '') + ')'; }).join(', ') + '.'\n : 'No venues on the shortlist yet.',\n );\n var program = (ev.program || []).slice().sort(function (a, b) { return String(a.time).localeCompare(String(b.time)); });\n parts.push(\n program.length\n ? 'Run of show: ' + program.map(function (p) { return clock(p.time) + ' ' + p.item + (p.owner ? ' (' + p.owner + ')' : ''); }).join(' | ') + '.'\n : 'The run of show is empty.',\n );\n return { attending: attending, noDietaryAnswer: noAnswer.map(function (g) { return String(g.fields.name); }), budgetLeftCents: left, summary: parts.join(' ') };\n}\n// ── event-desk-rules-end ──\n\nconst venues = rosterStore(gezel.fs, 'venues.json', {\n stages: ['shortlisted', 'visited', 'held', 'booked', 'declined'],\n idPrefix: 've',\n});\nconst vendors = rosterStore(gezel.fs, 'vendors.json', {\n stages: ['quoted', 'booked', 'paid', 'dropped'],\n idPrefix: 'vn',\n});\nconst guests = rosterStore(gezel.fs, 'guests.json', { stages: ['invited', 'yes', 'no'], idPrefix: 'gu' });\nconst budget = ledgerStore(gezel.fs, 'budget.json');\n\ninterface ProgramItem {\n id: string;\n time: string;\n item: string;\n owner?: string;\n note?: string;\n}\ninterface EventDoc {\n version: 1;\n occasion: string;\n date: string;\n time: string;\n venue: string;\n venueId?: string;\n host: string;\n rsvp: string;\n headcount: number;\n budgetCents: number;\n program: ProgramItem[];\n}\n\nasync function readEvent(): Promise<EventDoc> {\n let raw: string;\n try {\n raw = await gezel.fs.read('event.json');\n } catch {\n return blankEvent() as EventDoc;\n }\n let doc: Partial<EventDoc>;\n try {\n doc = JSON.parse(raw);\n } catch {\n throw new Error('event.json is not valid JSON. Fix or remove it; it will not be overwritten automatically.');\n }\n if (doc.version !== 1) throw new Error('event.json has unsupported version ' + String(doc.version) + ' (expected 1).');\n return { ...(blankEvent() as EventDoc), ...doc, program: Array.isArray(doc.program) ? doc.program : [] };\n}\n\n// A record by id or by (partial) name; a clear error names the matches.\nfunction pick(all: RosterRecord[], what: string, example: string): RosterRecord | null {\n if (input.id) {\n const byId = all.find((r) => r.id === input.id);\n if (byId) return byId;\n throw new Error('No ' + what + \" with id '\" + input.id + \"'. Known: \" + (all.map((r) => r.id + ' ' + String(r.fields.name)).join(', ') || 'none') + '.');\n }\n if (!input.name) throw new Error(\"Pass 'id' (e.g. '\" + example + \"') or the \" + what + \"'s 'name'.\");\n const exact = all.filter((r) => nameMatch(r.fields.name, input.name) === 'exact');\n if (exact.length === 1) return exact[0]!;\n const partial = all.filter((r) => nameMatch(r.fields.name, input.name) === 'partial');\n if (partial.length === 1) return partial[0]!;\n if (partial.length > 1) {\n throw new Error('More than one ' + what + \" matches '\" + input.name + \"': \" + partial.map((r) => r.id + ' ' + String(r.fields.name)).join(', ') + '. Pass id.');\n }\n return null;\n}\nfunction mustPick(all: RosterRecord[], what: string, example: string): RosterRecord {\n const found = pick(all, what, example);\n if (found) return found;\n throw new Error('No ' + what + \" named '\" + input.name + \"'. Known: \" + (all.map((r) => r.id + ' ' + String(r.fields.name)).join(', ') || 'none') + '.');\n}\nfunction dollars(value: unknown, label: string, allowNegative = false): number | null {\n if (value === undefined || value === null || value === '') return null;\n const cents = toCents(value);\n if (cents === null || (!allowNegative && cents < 0)) throw new Error(label + ' must be an amount in dollars, e.g. 1800.');\n return cents;\n}\n\nconst event = await readEvent();\nlet eventChanged = false;\nlet note = '';\nlet reply = '';\n\nif (input.action === 'set_event') {\n const given = ['occasion', 'date', 'time', 'host', 'rsvp', 'headcount', 'budget', 'budgetChange'].filter(\n (k) => (input as Record<string, unknown>)[k] !== undefined && (input as Record<string, unknown>)[k] !== '',\n );\n if (!given.length) throw new Error('set_event needs at least one of occasion, date, time, host, rsvp, headcount, budget or budgetChange.');\n if (input.occasion) event.occasion = input.occasion.trim();\n if (input.date) {\n const day = normalizeDate(input.date);\n if (!day) throw new Error(\"date must be a date, e.g. '2026-12-10'.\");\n event.date = day;\n }\n if (input.time) event.time = input.time.trim();\n if (input.host) event.host = input.host.trim();\n if (input.rsvp) event.rsvp = input.rsvp.trim();\n if (typeof input.headcount === 'number') {\n if (!(input.headcount >= 1)) throw new Error('headcount must be at least 1.');\n event.headcount = Math.round(input.headcount);\n }\n const whole = dollars(input.budget, 'budget');\n if (whole !== null) event.budgetCents = whole;\n const change = dollars(input.budgetChange, 'budgetChange', true);\n if (change !== null) event.budgetCents = Math.max(0, (Number(event.budgetCents) || 0) + change);\n eventChanged = true;\n note = 'Saved the event details' + (whole !== null || change !== null ? '; the budget is now ' + money(event.budgetCents) : '') + '.';\n} else if (input.action === 'add_venue') {\n if (!input.name) throw new Error(\"add_venue needs 'name'.\");\n if (input.status && !VENUE_STAGES.includes(input.status)) throw new Error(\"A venue's status is shortlisted, visited, held, or declined.\");\n const fee = dollars(input.fee, 'fee');\n const catering = dollars(input.cateringPerHead, 'cateringPerHead');\n const fields: Record<string, unknown> = {\n ...(typeof input.capacity === 'number' && input.capacity > 0 ? { capacity: Math.round(input.capacity) } : {}),\n ...(fee !== null ? { feeCents: fee } : {}),\n ...(catering !== null ? { cateringPerHeadCents: catering } : {}),\n ...(input.av === 'included' || input.av === 'extra' ? { av: input.av } : {}),\n ...(input.location ? { location: input.location.trim() } : {}),\n ...(input.note ? { notes: input.note.trim() } : {}),\n };\n const existing = (await venues.list()).find((r) => key(r.fields.name) === key(input.name));\n let record: RosterRecord;\n if (existing) {\n record = await venues.update(existing.id, { fields });\n note = 'Updated ' + String(existing.fields.name) + '.';\n } else {\n record = await venues.add({ status: 'shortlisted', fields: { name: input.name.trim(), av: 'extra', ...fields } });\n note = 'Added ' + input.name.trim() + ' (' + record.id + ') to the shortlist.';\n }\n if (input.status === 'booked') await bookVenue(record);\n else if (input.status && input.status !== record.status) await venues.transition(record.id, input.status, input.note ? { note: input.note } : {});\n} else if (input.action === 'book_venue') {\n await bookVenue(mustPick(await venues.list(), 'venue', 've-2'));\n} else if (input.action === 'add_vendor') {\n if (!input.name) throw new Error(\"add_vendor needs 'name'.\");\n if (input.status && !['quoted', 'booked', 'dropped'].includes(input.status)) throw new Error(\"A vendor's status is quoted, booked, or dropped.\");\n const existing = (await vendors.list()).find((r) => key(r.fields.name) === key(input.name));\n const contract = dollars(input.contract, 'contract');\n const change = dollars(input.contractChange, 'contractChange', true);\n const deposit = dollars(input.deposit, 'deposit');\n const dueAt = input.depositDueAt ? normalizeDate(input.depositDueAt) : null;\n if (input.depositDueAt && !dueAt) throw new Error(\"depositDueAt must be a date, e.g. '2026-11-12'.\");\n const arrival = input.arrival ? normalizeTime(input.arrival) : null;\n if (input.arrival && !arrival) throw new Error(\"arrival must be a time, e.g. '2 pm' or '14:00'.\");\n let total = contract;\n if (change !== null) total = Math.max(0, (total ?? (Number(existing?.fields.contractCents) || 0)) + change);\n const fields: Record<string, unknown> = {\n ...(input.category && VENDOR_KINDS.includes(input.category) ? { category: input.category } : {}),\n ...(total !== null ? { contractCents: total } : {}),\n ...(deposit !== null ? { depositCents: deposit } : {}),\n ...(dueAt ? { depositDueAt: dueAt } : {}),\n ...(input.contact ? { contact: input.contact.trim() } : {}),\n ...(arrival ? { arrival } : {}),\n ...(input.note ? { notes: input.note.trim() } : {}),\n };\n if (existing) {\n await vendors.update(existing.id, { fields });\n if (input.status && input.status !== existing.status) await vendors.transition(existing.id, input.status, input.note ? { note: input.note } : {});\n note = 'Updated ' + String(existing.fields.name) + (total !== null ? '; total now ' + money(total) : '') + '.';\n } else {\n const record = await vendors.add({\n status: input.status ?? 'quoted',\n fields: { name: input.name.trim(), category: 'other', contractCents: 0, depositCents: 0, ...fields },\n });\n note = 'Added ' + input.name.trim() + ' (' + record.id + ', ' + record.status + ').';\n }\n} else if (input.action === 'pay') {\n const cents = dollars(input.amount, 'amount');\n if (!cents || cents <= 0) throw new Error(\"pay needs a positive 'amount' in dollars.\");\n const vendor = mustPick(await vendors.list(), 'vendor', 'vn-2');\n const entries = await budget.list();\n const before = paidFor(vendor.id, entries);\n const deposit = Number(vendor.fields.depositCents) || 0;\n const kind = ['deposit', 'balance', 'other'].includes(String(input.kind)) ? String(input.kind) : before < deposit ? 'deposit' : 'balance';\n const today = localDay(Date.now());\n const repeat = entries.find(\n (e) => e.data && e.data.vendorId === vendor.id && e.amountCents === cents && e.data.payment === kind && localDay(Date.parse(e.at)) === today,\n );\n const name = String(vendor.fields.name);\n if (repeat) {\n note = 'Already recorded: ' + money(cents) + ' ' + kind + ' to ' + name + ' today.';\n } else {\n await budget.add({\n amountCents: cents,\n kind: 'out',\n category: String(vendor.fields.category ?? 'other'),\n note: input.note ? input.note.trim() : kind.charAt(0).toUpperCase() + kind.slice(1) + ' to ' + name,\n data: { vendorId: vendor.id, vendor: name, payment: kind },\n });\n const paid = before + cents;\n const contract = Number(vendor.fields.contractCents) || 0;\n if (contract > 0 && paid >= contract && vendor.status !== 'paid') await vendors.transition(vendor.id, 'paid', { note: 'Paid in full' });\n else if (vendor.status === 'quoted' || vendor.status === 'dropped') await vendors.transition(vendor.id, 'booked', { note: 'Booked with a payment' });\n note =\n 'Paid ' + money(cents) + ' ' + kind + ' to ' + name + '; ' +\n (contract ? money(paid) + ' of ' + money(contract) + ' paid' + (paid >= contract ? ', paid in full' : ', ' + money(contract - paid) + ' to go') : money(paid) + ' paid so far') + '.';\n }\n} else if (input.action === 'add_guest' || input.action === 'rsvp') {\n if (input.response && !GUEST_STAGES.includes(input.response)) throw new Error(\"response is invited, yes, or no.\");\n const all = await guests.list();\n let guest: RosterRecord | null;\n if (input.action === 'add_guest') {\n if (!input.name) throw new Error(\"add_guest needs 'name'.\");\n guest = all.find((r) => key(r.fields.name) === key(input.name)) ?? null;\n } else {\n if (!input.response && !input.dietary && typeof input.joining !== 'number' && typeof input.partySize !== 'number') {\n throw new Error(\"rsvp needs 'response' (yes or no), 'dietary', or 'joining'.\");\n }\n guest = pick(all, 'guest', 'gu-4');\n }\n const dietary = input.dietary ? normalizeDietary(input.dietary) : '';\n const party =\n typeof input.partySize === 'number' && input.partySize >= 1\n ? Math.round(input.partySize)\n : typeof input.joining === 'number' && input.joining > 0\n ? (guest ? people(guest) : 1) + Math.round(input.joining)\n : null;\n const fields: Record<string, unknown> = {\n ...(input.company ? { company: input.company.trim() } : {}),\n ...(dietary ? { dietary } : {}),\n ...(party !== null ? { partySize: party } : {}),\n ...(input.note ? { notes: input.note.trim() } : {}),\n };\n if (guest) {\n await guests.update(guest.id, { fields });\n if (input.response && input.response !== guest.status) await guests.transition(guest.id, input.response, input.note ? { note: input.note } : {});\n } else {\n if (!input.name) throw new Error(\"Pass the guest's 'name'.\");\n guest = await guests.add({ status: input.response ?? 'invited', fields: { name: input.name.trim(), partySize: 1, ...fields } });\n }\n const now = (await guests.get(guest.id))!;\n const label = String(now.fields.name);\n note =\n (all.some((r) => r.id === now.id) ? '' : 'Added ' + label + ' (' + now.id + ') to the list. ') +\n label + (now.status === 'yes' ? ' is coming' : now.status === 'no' ? \" can't come\" : ' is invited') +\n (people(now) > 1 ? ' with ' + (people(now) - 1) + ' more (party of ' + people(now) + ')' : '') +\n (now.fields.dietary ? '; dietary: ' + String(now.fields.dietary) : now.status === 'yes' ? '; no dietary answer yet' : '') + '.';\n} else if (input.action === 'program') {\n if (!input.item) throw new Error(\"program needs 'item'.\");\n const wanted = key(input.item);\n const list = event.program;\n let hits = list.filter((p) => key(p.item) === wanted);\n if (!hits.length) hits = list.filter((p) => key(p.item).includes(wanted));\n if (input.remove) {\n if (hits.length !== 1) throw new Error(hits.length ? 'More than one item matches: ' + hits.map((p) => clock(p.time) + ' ' + p.item).join(', ') + '.' : \"No run-of-show item matches '\" + input.item + \"'.\");\n event.program = list.filter((p) => p !== hits[0]);\n note = 'Took ' + hits[0]!.item + ' off the run of show.';\n } else {\n const time = input.time ? normalizeTime(input.time) : null;\n if (input.time && !time) throw new Error(\"time must be a clock time, e.g. '4:30 pm' or '16:30'.\");\n const same = list.find((p) => key(p.item) === wanted);\n if (same) {\n if (time) same.time = time;\n if (input.owner) same.owner = input.owner.trim();\n if (input.note) same.note = input.note.trim();\n note = 'Run of show: ' + clock(same.time) + ' ' + same.item + (same.owner ? ' (' + same.owner + ')' : '') + '.';\n } else {\n if (!time) throw new Error(\"A new run-of-show item needs 'time', e.g. '4:30 pm'.\");\n const next = list.reduce((max, p) => Math.max(max, Number(String(p.id).split('-')[1]) || 0), 0) + 1;\n list.push({ id: 'rs-' + next, time, item: input.item.trim(), ...(input.owner ? { owner: input.owner.trim() } : {}), ...(input.note ? { note: input.note.trim() } : {}) });\n note = 'Added to the run of show: ' + clock(time) + ' ' + input.item.trim() + (input.owner ? ' (' + input.owner.trim() + ')' : '') + '.';\n }\n event.program.sort((a, b) => String(a.time).localeCompare(String(b.time)));\n }\n eventChanged = true;\n} else if (input.action === 'compare') {\n const yes = (await guests.list()).filter((g) => g.status === 'yes').reduce((sum, g) => sum + people(g), 0);\n const count = typeof input.guests === 'number' && input.guests > 0 ? Math.round(input.guests) : Number(event.headcount) || yes;\n if (!count) throw new Error(\"Pass 'guests', the headcount to compare for.\");\n reply = compareVenues(await venues.list(), count).summary;\n} else if (input.action === 'guests') {\n const order = { yes: 0, invited: 1, no: 2 } as Record<string, number>;\n reply =\n (await guests.list())\n .slice()\n .sort((a, b) => (order[a.status] ?? 3) - (order[b.status] ?? 3) || String(a.fields.name).localeCompare(String(b.fields.name)))\n .map((g) => '[' + g.status + '] ' + guestTag(g, '') + ': ' + (g.fields.dietary ? String(g.fields.dietary) : 'no dietary answer'))\n .join('\\n') || 'The guest list is empty.';\n} else if (input.action !== 'status') {\n throw new Error(\"Unknown action '\" + input.action + \"'. Use status, compare, add_venue, book_venue, add_vendor, pay, add_guest, rsvp, set_event, program, or guests.\");\n}\n\n// Booking a venue makes it the event's venue and puts its hire fee in the contracts.\nasync function bookVenue(record: RosterRecord): Promise<void> {\n const released: string[] = [];\n const entries = await budget.list();\n for (const other of await venues.list()) {\n if (other.id === record.id || other.status !== 'booked') continue;\n await venues.transition(other.id, 'declined', { note: 'Released when ' + String(record.fields.name) + ' was booked' });\n const line = (await vendors.list()).find((v) => v.fields.venueId === other.id);\n if (line && line.status !== 'dropped' && paidFor(line.id, entries) === 0) await vendors.transition(line.id, 'dropped', { note: 'Venue released' });\n released.push(String(other.fields.name));\n }\n if (record.status !== 'booked') await venues.transition(record.id, 'booked', input.note ? { note: input.note } : {});\n const fee = Number(record.fields.feeCents) || 0;\n const all = await vendors.list();\n const line = all.find((v) => v.fields.venueId === record.id) ?? all.find((v) => key(v.fields.name) === key(record.fields.name));\n if (line) {\n await vendors.update(line.id, { fields: { category: 'venue', venueId: record.id, contractCents: fee } });\n if (line.status === 'quoted' || line.status === 'dropped') await vendors.transition(line.id, 'booked', { note: 'Venue booked' });\n } else {\n await vendors.add({\n status: 'booked',\n fields: { name: String(record.fields.name), category: 'venue', venueId: record.id, contractCents: fee, depositCents: 0, notes: 'Venue hire' },\n });\n }\n event.venue = String(record.fields.name);\n event.venueId = record.id;\n eventChanged = true;\n const perHead = Number(record.fields.cateringPerHeadCents) || 0;\n note =\n 'Booked ' + String(record.fields.name) + ' (' + record.id + '); its ' + money(fee) + ' hire fee is now with the signed contracts' +\n (perHead ? ', and its in-house catering at ' + money(perHead) + ' a guest goes in as a vendor once the count is final' : '') +\n (released.length ? '. Released ' + released.join(', ') : '') + '.';\n}\n\nif (eventChanged) await gezel.fs.write('event.json', JSON.stringify(event, null, 2) + '\\n');\n\nconst view = deskPicture(event, await venues.list(), await vendors.list(), await guests.list(), await budget.list(), Date.now());\n\ngezel.output({\n attending: view.attending,\n noDietaryAnswer: view.noDietaryAnswer,\n budgetLeft: view.budgetLeftCents / 100,\n summary: reply || (note ? note + ' ' : '') + view.summary,\n});\n"},"tools":[{"name":"event_status","description":"The whole event in one read, with ids: date and days to go, RSVPs, every guest still owing a dietary answer, deposits still to pay, the budget against signed contracts, vendors, venues and the run of show. Call it first when asked how things stand.","script":"event-desk-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"},"state":true},{"name":"compare_venues","description":"Compare the shortlisted venues for a headcount: which hold it, the hire fee, catering, sound and screens, and the cost per guest. Call it when asked to compare venues and answer from it.","script":"event-desk-store","inputs":{"type":"object","properties":{"guests":{"type":"number"}}},"bind":{"action":"compare"}},{"name":"add_venue","description":"Save a venue to the shortlist: name, how many it holds, the hire fee in dollars, in-house catering per guest (leave it out when you bring your own caterer), whether sound and screens are included, and where it is. An existing name is updated, never duplicated. Call it as soon as a venue or its quote is mentioned, before you describe it.","script":"event-desk-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"capacity":{"type":"number"},"fee":{"type":"number"},"cateringPerHead":{"type":"number"},"av":{"type":"string","enum":["included","extra"]},"location":{"type":"string"},"status":{"type":"string","enum":["shortlisted","visited","held","declined"]},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"add_venue"}},{"name":"book_venue","description":"Book a venue: it becomes the event's venue, its hire fee joins the signed contracts, and a venue booked before is released. Call it the moment the person chooses one.","script":"event-desk-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"note":{"type":"string"}}},"bind":{"action":"book_venue"}},{"name":"add_vendor","description":"Save a vendor (caterer, sound and screens, entertainment, photographer, rentals): its total in dollars, deposit and when it is due, the contact and when they arrive on the day. Pass status booked once it is signed. Pass contract for a new total, or contractChange when it goes up or down by an amount. An existing name is updated, never duplicated. Call it as soon as a vendor is mentioned, before you describe it.","script":"event-desk-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"category":{"type":"string","enum":["venue","catering","av","entertainment","photography","rentals","decor","transport","other"]},"status":{"type":"string","enum":["quoted","booked","dropped"]},"contract":{"type":"number"},"contractChange":{"type":"number"},"deposit":{"type":"number"},"depositDueAt":{"type":"string"},"contact":{"type":"string"},"arrival":{"type":"string"},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"add_vendor"}},{"name":"record_payment","description":"Record money paid to a vendor, in dollars, as a deposit or the balance, with any reference exactly as given. Call it the moment the person says they paid.","script":"event-desk-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"amount":{"type":"number"},"kind":{"type":"string","enum":["deposit","balance","other"]},"note":{"type":"string"}},"required":["amount"]},"bind":{"action":"pay"}},{"name":"add_guest","description":"Add a guest to the invite list: name, company, RSVP and dietary needs. An existing name is updated, never duplicated. Call it as soon as a guest is mentioned, before you describe it.","script":"event-desk-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"company":{"type":"string"},"response":{"type":"string","enum":["invited","yes","no"]},"dietary":{"type":"string"},"partySize":{"type":"number"},"joining":{"type":"number"},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"add_guest"}},{"name":"record_rsvp","description":"Record a guest's answer: yes or no, and what they can't eat (or 'none'). When they bring someone, pass joining with how many extra people and the desk adds them to the guest's party. A name not on the list is added. Call it the moment an answer comes in.","script":"event-desk-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"response":{"type":"string","enum":["yes","no","invited"]},"dietary":{"type":"string"},"joining":{"type":"number"},"partySize":{"type":"number"},"note":{"type":"string"}}},"bind":{"action":"rsvp"}},{"name":"set_event","description":"Change the event's details: its name, date (YYYY-MM-DD), hours, host, the RSVP line exactly as it should be printed, the headcount to plan for, or the budget. Pass budget for the whole new budget, or budgetChange to add or cut an amount. Record their words; never choose a date for them.","script":"event-desk-store","inputs":{"type":"object","properties":{"occasion":{"type":"string"},"date":{"type":"string"},"time":{"type":"string"},"host":{"type":"string"},"rsvp":{"type":"string"},"headcount":{"type":"number"},"budget":{"type":"number"},"budgetChange":{"type":"number"}}},"bind":{"action":"set_event"}},{"name":"set_program_item","description":"Put an item on the run of show at a start time ('4:30 pm'), with who's on point. The same item name is moved, never duplicated; pass remove to take it off.","script":"event-desk-store","inputs":{"type":"object","properties":{"time":{"type":"string"},"item":{"type":"string"},"owner":{"type":"string"},"note":{"type":"string"},"remove":{"type":"boolean"}},"required":["item"]},"bind":{"action":"program"}},{"name":"guest_list","description":"The whole invite list with each RSVP, company, party size and dietary answer.","script":"event-desk-store","inputs":{"type":"object","properties":{}},"bind":{"action":"guests"}},{"name":"page_set_event","description":"Change the event's details.","script":"event-desk-store","inputs":{"type":"object","properties":{"occasion":{"type":"string"},"date":{"type":"string"},"time":{"type":"string"},"host":{"type":"string"},"rsvp":{"type":"string"},"headcount":{"type":"number"},"budget":{"type":"number"},"budgetChange":{"type":"number"}}},"bind":{"action":"set_event"}},{"name":"page_add_venue","description":"Add or update a venue.","script":"event-desk-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"capacity":{"type":"number"},"fee":{"type":"number"},"cateringPerHead":{"type":"number"},"av":{"type":"string","enum":["included","extra"]},"location":{"type":"string"},"status":{"type":"string","enum":["shortlisted","visited","held","declined"]},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"add_venue"}},{"name":"page_book_venue","description":"Book a venue.","script":"event-desk-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"note":{"type":"string"}}},"bind":{"action":"book_venue"},"reaction":{"gezel":"ceremoniemeester","prompt":"The person just booked a venue on the event desk page. The desk now reads (its first sentence is what changed):\n{{output.summary}}\nIn two short sentences, confirm the booking and what it adds to the signed contracts, and name the next thing to lock. Do not call tools.","hideSeed":true}},{"name":"page_add_vendor","description":"Add or update a vendor.","script":"event-desk-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"category":{"type":"string","enum":["venue","catering","av","entertainment","photography","rentals","decor","transport","other"]},"status":{"type":"string","enum":["quoted","booked","dropped"]},"contract":{"type":"number"},"contractChange":{"type":"number"},"deposit":{"type":"number"},"depositDueAt":{"type":"string"},"contact":{"type":"string"},"arrival":{"type":"string"},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"add_vendor"}},{"name":"page_record_payment","description":"Record a payment to a vendor.","script":"event-desk-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"amount":{"type":"number"},"kind":{"type":"string","enum":["deposit","balance","other"]},"note":{"type":"string"}},"required":["amount"]},"bind":{"action":"pay"},"reaction":{"gezel":"ceremoniemeester","prompt":"The person just recorded a payment on the event desk page. The desk now reads (its first sentence is what changed):\n{{output.summary}}\nIn two short sentences, confirm the payment and what is still owed to that vendor, and name the next deposit due. Do not call tools.","hideSeed":true}},{"name":"page_add_guest","description":"Add or update a guest.","script":"event-desk-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"company":{"type":"string"},"response":{"type":"string","enum":["invited","yes","no"]},"dietary":{"type":"string"},"partySize":{"type":"number"},"joining":{"type":"number"},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"add_guest"}},{"name":"page_record_rsvp","description":"Record a guest's answer.","script":"event-desk-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"response":{"type":"string","enum":["yes","no","invited"]},"dietary":{"type":"string"},"joining":{"type":"number"},"partySize":{"type":"number"},"note":{"type":"string"}}},"bind":{"action":"rsvp"}},{"name":"page_set_program_item","description":"Put an item on the run of show.","script":"event-desk-store","inputs":{"type":"object","properties":{"time":{"type":"string"},"item":{"type":"string"},"owner":{"type":"string"},"note":{"type":"string"},"remove":{"type":"boolean"}},"required":["item"]},"bind":{"action":"program"}}],"pages":{"entry":"desk/index.html","api":1,"reads":[{"source":"workspace","path":"event.json"},{"source":"workspace","path":"venues.json"},{"source":"workspace","path":"vendors.json"},{"source":"workspace","path":"guests.json"},{"source":"workspace","path":"budget.json"}],"tools":["page_set_event","page_add_venue","page_book_venue","page_add_vendor","page_record_payment","page_add_guest","page_record_rsvp","page_set_program_item"]},"schedules":[],"workspaceSeed":["event.json","venues.json","vendors.json","guests.json","budget.json"],"artifactsSeed":[],"availableVersions":["1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"event-planner","name":"Event Planner","description":"Plan the wedding, the milestone birthday, the reunion. A composed event planner keeps the guest list sacred, the budget honest, and the day-of runbook ready — with a live countdown board.","tags":["event","wedding","party","guests","planning"],"category":"events","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.5","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"occasion":{"type":"string","title":"What are we celebrating?","description":"e.g. 'our wedding', 'Dad's 70th', 'the class reunion'.","default":"a big celebration"},"date":{"type":"string","title":"When is it?","description":"The date, e.g. 2026-09-12. A rough date is fine — change it later.","default":"2026-12-31"}},"required":["occasion","date"]},"nameTemplate":"Event: {{occasion}}","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"ceremoniemeester","voorman":true}],"toolsets":[],"craftbooks":["runbook"],"scripts":{"event-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { ledgerStore, rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'event-store',\n description:\n \"Read and update the event: guests (guests.json) and spending (budget.json). Call action:'status' for headcount + budget + countdown; 'add_guest' as invitations go out; 'guest_status' as RSVPs land (invited/yes/no); 'record_spend' when money is committed (ordinary units); 'guest_list' to read everyone.\",\n inputs: {\n action: {\n type: 'string',\n description:\n \"One of 'status', 'add_guest', 'guest_status', 'record_spend', or 'guest_list'.\",\n required: true,\n },\n name: { type: 'string', description: 'Guest name (party name is fine).' },\n party: { type: 'number', description: 'How many people this entry covers (default 1).' },\n status: { type: 'string', description: \"RSVP status: 'invited', 'yes', or 'no'.\" },\n id: { type: 'string', description: \"Guest id, e.g. 'guest-4'.\" },\n amount: { type: 'number', description: 'Spend amount in ordinary units.' },\n category: { type: 'string', description: \"Spend category, e.g. 'venue', 'catering'.\" },\n note: { type: 'string', description: 'Short note.' },\n },\n outputs: {\n invited: { type: 'number', description: 'People invited (sum of parties).' },\n coming: { type: 'number', description: \"People who said yes.\" },\n spentCents: { type: 'number', description: 'Total committed spend, in cents.' },\n summary: { type: 'string', description: 'The event picture.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── event-rules-start ──\n// Pure derivations: headcounts weighted by party size, and the countdown.\n\nfunction toCents(amount) {\n if (typeof amount !== 'number' || !isFinite(amount) || amount <= 0) return null;\n return Math.round(amount * 100);\n}\n\nfunction fmtCents(cents) {\n var abs = Math.abs(cents);\n return (cents < 0 ? '-' : '') + Math.floor(abs / 100) + '.' + String(abs % 100).padStart(2, '0');\n}\n\nfunction partyOf(record) {\n var p = record.fields && record.fields.party;\n return typeof p === 'number' && p >= 1 ? Math.floor(p) : 1;\n}\n\nfunction headcounts(records) {\n var invited = 0;\n var coming = 0;\n var awaiting = 0;\n records.forEach(function (r) {\n var size = partyOf(r);\n invited += size;\n if (r.status === 'yes') coming += size;\n if (r.status === 'invited') awaiting += size;\n });\n return { invited: invited, coming: coming, awaiting: awaiting };\n}\n\nfunction daysUntil(dateStr, nowMs) {\n var when = Date.parse(dateStr);\n if (!isFinite(when)) return null;\n return Math.ceil((when - nowMs) / (24 * 60 * 60 * 1000));\n}\n\nfunction eventLine(records, spentCents, eventDate, nowMs) {\n var heads = headcounts(records);\n var days = daysUntil(eventDate, nowMs);\n return (\n (days === null ? '' : days >= 0 ? days + ' day(s) to go. ' : 'The day has passed. ') +\n heads.coming +\n ' coming, ' +\n heads.awaiting +\n ' awaiting reply (' +\n heads.invited +\n ' invited). Spent ' +\n fmtCents(spentCents) +\n '.'\n );\n}\n// ── event-rules-end ──\n\nconst guests = rosterStore(gezel.fs, 'guests.json', {\n stages: ['invited', 'yes', 'no'],\n idPrefix: 'guest',\n});\nconst budget = ledgerStore(gezel.fs, 'budget.json');\n\nasync function readEventDate(): Promise<string> {\n try {\n const parsed = JSON.parse(await gezel.fs.read('guests.json')) as { eventDate?: string };\n return typeof parsed.eventDate === 'string' ? parsed.eventDate : '';\n } catch {\n return '';\n }\n}\n\nasync function resolveGuest(): Promise<string> {\n if (input.id) return input.id;\n if (input.name) {\n const wanted = input.name.toLowerCase();\n const matches = (await guests.list()).filter(\n (r) => String(r.fields.name ?? '').toLowerCase() === wanted,\n );\n if (matches.length === 1) return matches[0]!.id;\n }\n throw new Error(\"Pass 'id' (e.g. 'guest-4') or an exact guest 'name'.\");\n}\n\nif (input.action === 'add_guest') {\n if (!input.name) throw new Error(\"add_guest needs 'name'.\");\n await guests.add({\n status: 'invited',\n fields: {\n name: input.name,\n ...(typeof input.party === 'number' && input.party >= 1 ? { party: Math.floor(input.party) } : {}),\n ...(input.note ? { note: input.note } : {}),\n },\n });\n} else if (input.action === 'guest_status') {\n if (!input.status || !['invited', 'yes', 'no'].includes(input.status)) {\n throw new Error(\"guest_status needs status 'invited', 'yes', or 'no'.\");\n }\n await guests.transition(await resolveGuest(), input.status, input.note ? { note: input.note } : {});\n} else if (input.action === 'record_spend') {\n const cents = toCents(input.amount);\n if (cents === null || !input.category) {\n throw new Error(\"record_spend needs a positive 'amount' and a 'category' (e.g. 'venue').\");\n }\n await budget.add({\n amountCents: cents,\n kind: 'out',\n category: input.category.toLowerCase(),\n ...(input.note ? { note: input.note } : {}),\n });\n} else if (input.action !== 'status' && input.action !== 'guest_list') {\n throw new Error(\n `Unknown action '${input.action}'. Use status, add_guest, guest_status, record_spend, or guest_list.`,\n );\n}\n\nconst records = await guests.list();\nconst totals = await budget.totals();\nconst heads = headcounts(records);\nconst eventDate = await readEventDate();\nconst listing =\n input.action === 'guest_list'\n ? records\n .map(\n (r) =>\n `${r.id} [${r.status}] ${String(r.fields.name ?? '?')}${partyOf(r) > 1 ? ` (party of ${partyOf(r)})` : ''}`,\n )\n .join('\\n') || 'The guest list is empty.'\n : '';\n\ngezel.output({\n invited: heads.invited,\n coming: heads.coming,\n spentCents: totals.outCents,\n summary: listing || eventLine(records, totals.outCents, eventDate, Date.now()),\n});\n"},"tools":[{"name":"add_guest","description":"Add a guest or party to the list (status starts at invited).","script":"event-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"party":{"type":"number"},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"add_guest"}},{"name":"guest_status","description":"Record an RSVP: 'yes', 'no', or back to 'invited'.","script":"event-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"status":{"type":"string","enum":["invited","yes","no"]},"note":{"type":"string"}},"required":["status"]},"bind":{"action":"guest_status"}},{"name":"record_spend","description":"Record committed spending (deposit, balance, purchase) in ordinary units.","script":"event-store","inputs":{"type":"object","properties":{"amount":{"type":"number"},"category":{"type":"string"},"note":{"type":"string"}},"required":["amount","category"]},"bind":{"action":"record_spend"}},{"name":"event_status","description":"Countdown, headcount, and budget in one line.","script":"event-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"}},{"name":"guest_list","description":"Read the whole guest list with statuses.","script":"event-store","inputs":{"type":"object","properties":{}},"bind":{"action":"guest_list"}},{"name":"page_add_guest","description":"Add a guest or party to the list (status starts at invited).","script":"event-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"party":{"type":"number"},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"add_guest"}},{"name":"page_guest_status","description":"Record an RSVP: 'yes', 'no', or back to 'invited'.","script":"event-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"status":{"type":"string","enum":["invited","yes","no"]},"note":{"type":"string"}},"required":["status"]},"bind":{"action":"guest_status"}},{"name":"page_record_spend","description":"Record committed spending (deposit, balance, purchase) in ordinary units.","script":"event-store","inputs":{"type":"object","properties":{"amount":{"type":"number"},"category":{"type":"string"},"note":{"type":"string"}},"required":["amount","category"]},"bind":{"action":"record_spend"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"guests.json"},{"source":"workspace","path":"budget.json"}],"tools":["page_add_guest","page_guest_status","page_record_spend"]},"schedules":[],"workspaceSeed":["guests.json","budget.json"],"artifactsSeed":[],"availableVersions":["1.0.5","1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"fitness-coach","name":"Fitness Coach","description":"A training habit that survives real life. A steady Coach logs every session, guards the streak, and adjusts the weekly plan to fit your schedule — with a live board showing the week and the streak.","tags":["fitness","training","habits","streak","health"],"category":"growth","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.1.2","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"leanProfile":true,"params":{"type":"object","properties":{"goal":{"type":"string","title":"What are you training toward?","description":"e.g. 'feel strong again', 'a 10k in October'.","default":"feeling strong and consistent"},"weeklyTarget":{"type":"number","title":"Sessions per week","description":"How many training sessions a week to aim for.","default":3}},"required":["goal","weeklyTarget"]},"nameTemplate":"Fitness: {{goal}}","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"coach","voorman":true}],"toolsets":[],"craftbooks":["training-recap"],"scripts":{"training-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { logStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'training-store',\n description:\n \"Read and update the training log (training.json). Call action:'status' for streak + this week vs the target; 'log_workout' the moment a session is reported (activity + minutes); 'set_target' to change the weekly session target; 'history' for the recent sessions; 'recap_numbers' for this week against last; 'save_recap' to write the weekly recap with one suggestion.\",\n inputs: {\n action: {\n type: 'string',\n description:\n \"One of 'status', 'log_workout', 'set_target', 'history', 'recap_numbers', 'request_recap', or 'save_recap'.\",\n required: true,\n },\n activity: { type: 'string', description: \"What they did, e.g. 'run', 'gym', 'long walk'.\" },\n minutes: { type: 'number', description: 'How long the session ran, in minutes.' },\n note: { type: 'string', description: 'Anything worth remembering about the session.' },\n weeklyTarget: { type: 'number', description: 'Sessions per week to aim for (set_target).' },\n suggestion: { type: 'string', description: 'For save_recap: one concrete suggestion for next week.' },\n },\n outputs: {\n streakDays: { type: 'number', description: 'Consecutive days with a session, ending at the latest.' },\n thisWeek: { type: 'number', description: 'Sessions logged this week (Monday UTC start).' },\n weeklyTarget: { type: 'number', description: 'The current weekly session target.' },\n summary: { type: 'string', description: 'The training picture.' },\n personalBest: { type: 'boolean', description: 'For log_workout: the longest session on record.' },\n recap: { type: 'json', description: 'This week against last: sessions, minutes, longest session.' },\n display: { type: 'string', description: 'For save_recap: the recap as shown.' },\n status: { type: 'string', description: \"'recap_wanted' after request_recap, else 'ok'.\" },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── fitness-rules-start ──\n// Pure derivations over logStore-shaped workout events: kind 'workout',\n// data {activity, minutes}. Weeks start Monday 00:00 UTC; nowIso is a\n// parameter so the rules stay clock-independent and testable.\n\nfunction weekStartMs(nowIso) {\n var day = new Date(nowIso.slice(0, 10) + 'T00:00:00Z');\n var sinceMonday = (day.getUTCDay() + 6) % 7;\n return day.getTime() - sinceMonday * 86400000;\n}\n\nfunction thisWeekCount(events, nowIso) {\n var start = weekStartMs(nowIso);\n return events.filter(function (e) {\n return Date.parse(e.at) >= start;\n }).length;\n}\n\nfunction trainingLine(stats, weekCount, weeklyTarget) {\n var target = weeklyTarget > 0 ? weeklyTarget : 0;\n var weekPart =\n 'This week: ' +\n weekCount +\n (target > 0 ? ' of ' + target + ' session(s)' : ' session(s)') +\n (target > 0 && weekCount >= target ? ' — target met.' : '.');\n var streakPart =\n stats.total === 0\n ? 'No sessions logged yet.'\n : 'Streak: ' + stats.streakDays + ' day(s); ' + stats.total + ' session(s) all time.';\n return weekPart + ' ' + streakPart;\n}\n\n// The week's numbers against the week before: what a recap reports, so the\n// coach only adds a suggestion. Weeks start Monday UTC, as above.\nfunction weekRecap(events, nowIso, weeklyTarget) {\n var start = weekStartMs(nowIso);\n var prevStart = start - 7 * 86400000;\n function minutesOf(e) {\n var m = e.data && Number(e.data.minutes);\n return isFinite(m) && m > 0 ? m : 0;\n }\n var week = events.filter(function (e) { return Date.parse(e.at) >= start; });\n var prev = events.filter(function (e) {\n var t = Date.parse(e.at);\n return t >= prevStart && t < start;\n });\n var minutes = week.reduce(function (n, e) { return n + minutesOf(e); }, 0);\n var prevMinutes = prev.reduce(function (n, e) { return n + minutesOf(e); }, 0);\n var longest = week.reduce(function (best, e) {\n return !best || minutesOf(e) > minutesOf(best) ? e : best;\n }, null);\n return {\n weekOf: new Date(start).toISOString().slice(0, 10),\n sessions: week.length,\n target: weeklyTarget,\n minutes: minutes,\n sessionsChange: week.length - prev.length,\n minutesChange: minutes - prevMinutes,\n longest: longest\n ? { activity: String((longest.data && longest.data.activity) || 'session'), minutes: minutesOf(longest) }\n : null,\n };\n}\n\nfunction recapLine(recap, suggestion) {\n var change = recap.minutesChange === 0 ? 'same as last week' : (recap.minutesChange > 0 ? '+' : '') + recap.minutesChange + ' min vs last week';\n return (\n 'Week of ' + recap.weekOf + ': ' + recap.sessions + (recap.target > 0 ? ' of ' + recap.target : '') +\n ' session(s), ' + recap.minutes + ' min (' + change + ').' +\n (suggestion ? ' Next week: ' + suggestion : '')\n );\n}\n// ── fitness-rules-end ──\n\nconst training = logStore(gezel.fs, 'training.json');\n\nasync function readWeeklyTarget(): Promise<number> {\n try {\n const parsed = JSON.parse(await gezel.fs.read('training.json')) as { weeklyTarget?: unknown };\n const target = Number(parsed.weeklyTarget);\n return Number.isFinite(target) && target > 0 ? Math.round(target) : 0;\n } catch {\n return 0;\n }\n}\n\nlet personalBest = false;\nlet display = '';\nlet status = 'ok';\nif (input.action === 'log_workout') {\n if (!input.activity) throw new Error(\"log_workout needs 'activity' (what they did).\");\n const minutes = typeof input.minutes === 'number' && input.minutes > 0 ? Math.round(input.minutes) : 0;\n const before = await training.list();\n const longestBefore = before.reduce((n, e) => Math.max(n, Number(e.data?.minutes) || 0), 0);\n personalBest = minutes > 0 && before.length > 0 && minutes > longestBefore;\n await training.append({\n kind: 'workout',\n ...(input.note ? { note: input.note } : {}),\n data: {\n activity: input.activity,\n ...(typeof input.minutes === 'number' && input.minutes > 0\n ? { minutes: Math.round(input.minutes) }\n : {}),\n },\n });\n} else if (input.action === 'set_target') {\n const target = Number(input.weeklyTarget);\n if (!Number.isFinite(target) || target <= 0) {\n throw new Error(\"set_target needs a positive 'weeklyTarget' (sessions per week).\");\n }\n // logStore has no field API; the passenger key flips via a targeted\n // read-modify-write that preserves the rest of the file.\n const raw = JSON.parse(await gezel.fs.read('training.json')) as Record<string, unknown>;\n raw.weeklyTarget = Math.round(target);\n await gezel.fs.write('training.json', `${JSON.stringify(raw, null, 2)}\\n`);\n} else if (input.action === 'request_recap') {\n status = 'recap_wanted';\n} else if (input.action === 'save_recap') {\n const suggestion = String(input.suggestion ?? '').replace(/\\s+/g, ' ').trim().slice(0, 240);\n if (suggestion.length < 10) throw new Error(\"save_recap needs a one-sentence 'suggestion' for next week.\");\n const recap = weekRecap(await training.list(), new Date().toISOString(), await readWeeklyTarget());\n const doc = { ...recap, suggestion, writtenAt: new Date().toISOString() };\n const body = `${JSON.stringify(doc, null, 2)}\\n`;\n await gezel.fs.write(`recaps/${recap.weekOf}.json`, body);\n await gezel.fs.write('recaps/latest.json', body);\n display = recapLine(recap, suggestion);\n} else if (!['status', 'history', 'recap_numbers'].includes(String(input.action))) {\n throw new Error(\n `Unknown action '${input.action}'. Use status, log_workout, set_target, history, recap_numbers, or save_recap.`,\n );\n}\n\nconst events = await training.list();\nconst stats = await training.stats();\nconst weeklyTarget = await readWeeklyTarget();\nconst nowIso = new Date().toISOString();\nconst weekCount = thisWeekCount(events, nowIso);\nconst listing =\n input.action === 'history'\n ? events\n .slice(-12)\n .map(\n (e) =>\n `${e.at.slice(0, 10)} ${String(e.data?.activity ?? 'session')}${typeof e.data?.minutes === 'number' ? ` (${e.data.minutes} min)` : ''}${e.note ? ` — ${e.note}` : ''}`,\n )\n .join('\\n') || 'No sessions yet.'\n : '';\n\nconst recap = weekRecap(events, nowIso, weeklyTarget);\ngezel.output({\n streakDays: stats.streakDays,\n thisWeek: weekCount,\n weeklyTarget,\n summary:\n listing ||\n (input.action === 'recap_numbers' || input.action === 'request_recap'\n ? recapLine(recap, '')\n : trainingLine(stats, weekCount, weeklyTarget)),\n personalBest,\n recap,\n display,\n status,\n});\n"},"tools":[{"name":"log_workout","description":"Log a training session the moment it is reported (activity + minutes).","script":"training-store","inputs":{"type":"object","properties":{"activity":{"type":"string"},"minutes":{"type":"number"},"note":{"type":"string"}},"required":["activity"]},"bind":{"action":"log_workout"}},{"name":"set_target","description":"Change the weekly session target.","script":"training-store","inputs":{"type":"object","properties":{"weeklyTarget":{"type":"number"}},"required":["weeklyTarget"]},"bind":{"action":"set_target"}},{"name":"training_status","description":"Streak, this week against the target, all-time count.","script":"training-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"}},{"name":"workout_history","description":"The recent sessions, most recent last.","script":"training-store","inputs":{"type":"object","properties":{}},"bind":{"action":"history"}},{"name":"training_recap","description":"This week's training against last week: sessions, minutes, and the longest session.","script":"training-store","inputs":{"type":"object","properties":{}},"bind":{"action":"recap_numbers"}},{"name":"save_recap","description":"Save the weekly recap with ONE concrete suggestion for next week, in one sentence, grounded in this week's numbers. The app adds the numbers.","script":"training-store","inputs":{"type":"object","properties":{"suggestion":{"type":"string","description":"One sentence for next week."}},"required":["suggestion"]},"bind":{"action":"save_recap"},"turn":{"fallback":"Recap saved.","show":"display"}},{"name":"page_log_workout","description":"Log a session from the dashboard.","script":"training-store","inputs":{"type":"object","properties":{"activity":{"type":"string"},"minutes":{"type":"number"},"note":{"type":"string"}},"required":["activity"]},"bind":{"action":"log_workout"}},{"name":"request_recap","description":"Ask the coach for this week's recap from the dashboard.","script":"training-store","inputs":{"type":"object","properties":{}},"bind":{"action":"request_recap"},"reaction":{"gezel":"coach","prompt":"The person asked for this week's training recap. The numbers, from their log:\n```json\n{{output.recap}}\n```\nCall save_recap once with ONE concrete suggestion for next week, in one sentence, grounded in these numbers. Their goal: {{goal}}.","hideSeed":true,"standalone":true,"turn":{"tool":"save_recap","when":{"op":"equals","field":"status","value":"recap_wanted"}}}},{"name":"page_set_target","description":"Change the weekly session target.","script":"training-store","inputs":{"type":"object","properties":{"weeklyTarget":{"type":"number"}},"required":["weeklyTarget"]},"bind":{"action":"set_target"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"training.json"},{"source":"workspace","path":"recaps/latest.json"}],"tools":["page_log_workout","request_recap","page_set_target"]},"schedules":[{"runMode":"scheduled","cron":"0 18 * * 0","craftbook":"training-recap","consent":"ask"}],"workspaceSeed":["training.json"],"artifactsSeed":[],"availableVersions":["1.1.2","1.1.1","1.1.0","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"flashcards","name":"Flashcards","description":"Learn anything with spaced-repetition flashcards. Your study partner writes the cards in chat; you review them on a live card-flip page that schedules what comes back and when.","tags":["flashcards","study","learning","spaced-repetition"],"category":"growth","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.2.4","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"subject":{"type":"string","title":"What are you learning?","description":"The deck's subject — e.g. Spanish vocabulary, AWS certification, organic chemistry.","default":"Spanish vocabulary"}},"required":["subject"]},"nameTemplate":"{{subject}} Flashcards","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"study-buddy","voorman":true}],"toolsets":[],"craftbooks":[],"scripts":{"deck-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\n\nexport const meta = defineScript({\n name: 'deck-store',\n description:\n \"Read and update the flashcard deck (deck.json). Call action:'add_cards' with a cards array ([{front, back}, ...]) to add practice cards; action:'state' to see due counts and box distribution; action:'list_deck' to read every card. The review page drives 'record_review', 'finish_session' and 'stage_notes' itself.\",\n inputs: {\n action: {\n type: 'string',\n description:\n \"One of 'state', 'list_deck', 'add_cards', 'record_review', 'finish_session', or 'stage_notes'.\",\n required: true,\n },\n cards: {\n type: 'json',\n description: 'For add_cards: an array of {front, back} objects.',\n },\n cardId: { type: 'string', description: \"For record_review: the card id, e.g. 'card-3'.\" },\n verdict: { type: 'string', description: \"For record_review: 'got-it' or 'missed'.\" },\n reviewed: { type: 'number', description: 'For finish_session: how many cards were reviewed.' },\n missedIds: { type: 'json', description: 'For finish_session: array of card ids that were missed.' },\n notes: { type: 'string', description: 'For stage_notes: notes the student pasted to turn into cards.' },\n },\n outputs: {\n total: { type: 'number', description: 'Cards in the deck.' },\n due: { type: 'number', description: 'Cards due for review now.' },\n summary: { type: 'string', description: 'Human-readable deck or session summary.' },\n missedList: { type: 'string', description: 'Fronts of the cards missed this session (finish_session).' },\n status: { type: 'string', description: \"'forging' after stage_notes, else 'idle'.\" },\n notes: { type: 'string', description: 'The staged notes (stage_notes), clipped to 3000 characters.' },\n },\n requires: ['workspace.read', 'workspace.write', 'reminders'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── leitner-rules-start ──\n// Pure Leitner-box scheduling (3 boxes). Box 1 reviews daily, box 2 every\n// 3 days, box 3 weekly. A got-it promotes (capped at 3); a miss goes back\n// to box 1. Never-reviewed cards are always due. Kept self-contained\n// between these sentinels so unit tests execute the shipped bytes.\n\nvar BOX_INTERVAL_DAYS = { 1: 1, 2: 3, 3: 7 };\nvar DAY_MS = 24 * 60 * 60 * 1000;\n\nfunction isDue(card, nowMs) {\n if (!card.lastReviewedAt) return true;\n var interval = BOX_INTERVAL_DAYS[card.box] || 1;\n return nowMs - Date.parse(card.lastReviewedAt) >= interval * DAY_MS;\n}\n\nfunction computeDueIds(cards, nowMs) {\n return cards\n .filter(function (c) {\n return isDue(c, nowMs);\n })\n .sort(function (a, b) {\n if (a.box !== b.box) return a.box - b.box;\n return a.createdAt < b.createdAt ? -1 : a.createdAt > b.createdAt ? 1 : 0;\n })\n .map(function (c) {\n return c.id;\n });\n}\n\nfunction applyReview(card, verdict, nowIso) {\n if (verdict === 'got-it') card.box = Math.min(3, card.box + 1);\n else card.box = 1;\n card.lastReviewedAt = nowIso;\n card.stats = card.stats || { gotIt: 0, missed: 0 };\n if (verdict === 'got-it') card.stats.gotIt += 1;\n else card.stats.missed += 1;\n return card;\n}\n\nfunction nextCardId(cards) {\n var max = 0;\n for (var i = 0; i < cards.length; i += 1) {\n var m = /^card-(\\d+)$/.exec(cards[i].id);\n if (m) max = Math.max(max, Number(m[1]));\n }\n return 'card-' + (max + 1);\n}\n// ── leitner-rules-end ──\n\nconst DECK_FILE = 'deck.json';\n\ninterface Card {\n id: string;\n front: string;\n back: string;\n box: number;\n lastReviewedAt: string | null;\n createdAt: string;\n stats: { gotIt: number; missed: number };\n}\n\ninterface Deck {\n version: number;\n subject: string;\n cards: Card[];\n dueCardIds: string[];\n updatedAt: string;\n}\n\nasync function load(): Promise<Deck> {\n let raw: string;\n try {\n raw = await gezel.fs.read(DECK_FILE);\n } catch {\n return { version: 1, subject: 'your subject', cards: [], dueCardIds: [], updatedAt: new Date().toISOString() };\n }\n const parsed = JSON.parse(raw) as Partial<Deck>;\n return {\n version: 1,\n subject: typeof parsed.subject === 'string' ? parsed.subject : 'your subject',\n cards: Array.isArray(parsed.cards) ? (parsed.cards as Card[]) : [],\n dueCardIds: [],\n updatedAt: new Date().toISOString(),\n };\n}\n\n// ── reminder-start ──\n// The next time a reviewed card comes due, worked out from the deck itself:\n// the one moment a reminder is earned. Nothing left to come due clears it.\n// Kept self-contained between these sentinels so unit tests execute the\n// shipped bytes.\nasync function remind(deck, nowMs) {\n var next = Infinity;\n for (var i = 0; i < deck.cards.length; i += 1) {\n var card = deck.cards[i];\n if (!card.lastReviewedAt) continue;\n var dueAt = Date.parse(card.lastReviewedAt) + (BOX_INTERVAL_DAYS[card.box] || 1) * DAY_MS;\n if (dueAt > nowMs && dueAt < next) next = dueAt;\n }\n try {\n if (!isFinite(next)) {\n await gezel.reminder.clear();\n return;\n }\n var count = computeDueIds(deck.cards, next).length;\n await gezel.reminder.set({\n at: new Date(next).toISOString(),\n title: 'Flashcards are due',\n body: count + (count === 1 ? ' card' : ' cards') + ' on \"' + deck.subject + '\" ready to review.',\n });\n } catch (err) {\n // A host without reminders still keeps the deck.\n }\n}\n// ── reminder-end ──\n\nasync function persist(deck: Deck): Promise<Deck> {\n const nowMs = Date.now();\n deck.dueCardIds = computeDueIds(deck.cards, nowMs);\n deck.updatedAt = new Date(nowMs).toISOString();\n await gezel.fs.write(DECK_FILE, `${JSON.stringify(deck, null, 2)}\\n`);\n await remind(deck, nowMs);\n return deck;\n}\n\nconst deck = await load();\ndeck.dueCardIds = computeDueIds(deck.cards, Date.now());\nlet summary = '';\nlet missedList = '';\nlet status = 'idle';\nlet notes = '';\n// Cards from one call: enough for a set of notes, short enough that a small\n// model writes them in one turn.\nconst MAX_NEW_CARDS = 8;\n\nif (input.action === 'add_cards') {\n const raw = Array.isArray(input.cards) ? input.cards : [];\n const added: string[] = [];\n for (const entry of raw.slice(0, MAX_NEW_CARDS)) {\n const front = typeof (entry as { front?: unknown }).front === 'string' ? (entry as { front: string }).front.trim() : '';\n const back = typeof (entry as { back?: unknown }).back === 'string' ? (entry as { back: string }).back.trim() : '';\n if (!front || !back) continue;\n const card: Card = {\n id: nextCardId(deck.cards),\n front: front.slice(0, 300),\n back: back.slice(0, 500),\n box: 1,\n lastReviewedAt: null,\n createdAt: new Date().toISOString(),\n stats: { gotIt: 0, missed: 0 },\n };\n deck.cards.push(card);\n added.push(card.id);\n }\n if (added.length === 0) {\n throw new Error(\"add_cards needs a non-empty 'cards' array of {front, back} objects.\");\n }\n await persist(deck);\n summary = `Added ${added.length} card(s). ${deck.cards.length} in the deck, ${deck.dueCardIds.length} due now.`;\n} else if (input.action === 'record_review') {\n if (!input.cardId || (input.verdict !== 'got-it' && input.verdict !== 'missed')) {\n throw new Error(\"record_review needs 'cardId' and verdict 'got-it' or 'missed'.\");\n }\n const card = deck.cards.find((c) => c.id === input.cardId);\n if (!card) throw new Error(`No card '${input.cardId}' in the deck.`);\n applyReview(card, input.verdict, new Date().toISOString());\n await persist(deck);\n summary = `${card.id} marked ${input.verdict} (now box ${card.box}). ${deck.dueCardIds.length} still due.`;\n} else if (input.action === 'finish_session') {\n const reviewed = typeof input.reviewed === 'number' ? input.reviewed : 0;\n const missedIds = Array.isArray(input.missedIds) ? input.missedIds.map(String) : [];\n const missedFronts = missedIds\n .map((id) => deck.cards.find((c) => c.id === id)?.front)\n .filter((f): f is string => typeof f === 'string');\n missedList = missedFronts.length ? missedFronts.join(' | ') : '(none)';\n summary = `Reviewed ${reviewed} card(s): ${reviewed - missedIds.length} got it, ${missedIds.length} missed. ${deck.dueCardIds.length} due next.`;\n} else if (input.action === 'list_deck') {\n summary = deck.cards.length\n ? deck.cards\n .map((c) => `${c.id} [box ${c.box}] ${c.front} -> ${c.back}`)\n .join('\\n')\n : 'The deck is empty — add cards with add_cards.';\n} else if (input.action === 'state') {\n const boxes = { 1: 0, 2: 0, 3: 0 } as Record<number, number>;\n for (const c of deck.cards) boxes[c.box] = (boxes[c.box] ?? 0) + 1;\n summary = deck.cards.length\n ? `${deck.cards.length} card(s) on \"${deck.subject}\": ${deck.dueCardIds.length} due now. Boxes: ${boxes[1]} daily, ${boxes[2]} every-3-days, ${boxes[3]} weekly.`\n : `The deck for \"${deck.subject}\" is empty — offer to write the first cards.`;\n} else if (input.action === 'stage_notes') {\n notes = String(input.notes ?? '').trim().slice(0, 3000);\n if (notes.length < 20) throw new Error('Paste a few sentences of notes to make cards from.');\n status = 'forging';\n summary = `Notes staged for \"${deck.subject}\". ${deck.cards.length} card(s) in the deck so far.`;\n} else {\n throw new Error(\n `Unknown action '${input.action}'. Use state, list_deck, add_cards, record_review, finish_session, or stage_notes.`,\n );\n}\n\ngezel.output({\n total: deck.cards.length,\n due: deck.dueCardIds.length,\n summary,\n missedList,\n status,\n notes,\n});\n"},"tools":[{"name":"add_cards","description":"Add flashcards to the deck: a cards array of {front, back} objects, one fact per card, at most 8 at a time. The deck's summary becomes your reply.","script":"deck-store","inputs":{"type":"object","properties":{"cards":{"type":"array","items":{"type":"object","properties":{"front":{"type":"string"},"back":{"type":"string"}},"required":["front","back"]},"description":"The cards to add."}},"required":["cards"]},"bind":{"action":"add_cards"},"turn":{"fallback":"Cards added to the deck.","show":"summary"}},{"name":"deck_status","description":"See the deck: how many cards, how many due, and the box distribution.","script":"deck-store","inputs":{"type":"object","properties":{}},"bind":{"action":"state"}},{"name":"list_deck","description":"Read every card in the deck (id, box, front, back).","script":"deck-store","inputs":{"type":"object","properties":{}},"bind":{"action":"list_deck"}},{"name":"record_review","description":"The review page's per-card verdict.","script":"deck-store","inputs":{"type":"object","properties":{"cardId":{"type":"string"},"verdict":{"type":"string","enum":["got-it","missed"]}},"required":["cardId","verdict"]},"bind":{"action":"record_review"}},{"name":"finish_session","description":"The review page's end-of-session summary.","script":"deck-store","inputs":{"type":"object","properties":{"reviewed":{"type":"number"},"missedIds":{"type":"array","items":{"type":"string"}}},"required":["reviewed"]},"bind":{"action":"finish_session"},"reaction":{"gezel":"study-buddy","prompt":"The user finished a flashcard review session. {{output.summary}}\nMissed cards: {{output.missedList}}\nReply with ONE short encouraging line — specific beats generic. If any cards were missed, offer to add fresh practice cards that come at those same ideas from a new angle (add them with your deck capabilities if the user agrees)."}},{"name":"forge_from_notes","description":"The review page's notes-to-cards request.","script":"deck-store","inputs":{"type":"object","properties":{"notes":{"type":"string"}},"required":["notes"]},"bind":{"action":"stage_notes"},"reaction":{"gezel":"study-buddy","prompt":"The student pasted notes to turn into flashcards for \"{{subject}}\":\n<<<\n{{output.notes}}\n>>>\nMake 4 to 8 cards that test the key facts in these notes, one fact per card: the front a short question, the back its answer (a name, number or short fact from the notes), for example front \"What produces ATP?\", back \"Mitochondria\". Save them with add_cards.","hideSeed":true,"standalone":true,"turn":{"tool":"add_cards","when":{"op":"equals","field":"status","value":"forging"}}}},{"name":"page_add_cards","description":"Add flashcards to the deck: a cards array of {front, back} objects, one fact per card, at most 8 at a time.","script":"deck-store","inputs":{"type":"object","properties":{"cards":{"type":"array","items":{"type":"object","properties":{"front":{"type":"string"},"back":{"type":"string"}},"required":["front","back"]},"description":"The cards to add."}},"required":["cards"]},"bind":{"action":"add_cards"}}],"pages":{"entry":"review/index.html","api":1,"reads":[{"source":"workspace","path":"deck.json"}],"tools":["record_review","finish_session","forge_from_notes","page_add_cards"]},"schedules":[],"workspaceSeed":["deck.json"],"artifactsSeed":[],"availableVersions":["1.2.4","1.2.3","1.2.1","1.2.0","1.1.2","1.1.1","1.1.0","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"freelance-office","name":"Freelance Office","description":"Run a one-person business without dropping anything. Your office administrator tracks every invoice to paid, drafts the polite chase, and keeps the income picture one question away.","tags":["freelance","invoices","clients","business","income"],"category":"money","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.5","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"business":{"type":"string","title":"What do you do?","description":"One line about the business — e.g. 'freelance brand design'.","default":"freelance work"}},"required":["business"]},"nameTemplate":"Freelance Office","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"kantoormeester","voorman":true}],"toolsets":[],"craftbooks":["proposal-sow","weekly-review"],"scripts":{"office-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'office-store',\n description:\n \"Read and update the invoice book (invoices.json). Call action:'status' for outstanding/overdue/paid-this-month; 'record_invoice' when work is billed (amount in ordinary units, e.g. 1200.00); 'invoice_sent' / 'invoice_paid' as reality moves; 'list_invoices' to read the book.\",\n inputs: {\n action: {\n type: 'string',\n description:\n \"One of 'status', 'record_invoice', 'invoice_sent', 'invoice_paid', or 'list_invoices'.\",\n required: true,\n },\n client: { type: 'string', description: 'Client name.' },\n amount: { type: 'number', description: 'Invoice amount in ordinary units, e.g. 1200.00.' },\n due: { type: 'string', description: 'Due date (ISO), e.g. 2026-08-15.' },\n note: { type: 'string', description: 'Short note (what the invoice covers).' },\n id: { type: 'string', description: \"Invoice id, e.g. 'inv-3'.\" },\n },\n outputs: {\n invoices: { type: 'number', description: 'Invoices in the book.' },\n outstandingCents: { type: 'number', description: 'Total sent-but-unpaid, in cents.' },\n overdue: { type: 'number', description: 'Count of overdue invoices.' },\n summary: { type: 'string', description: 'Human-readable office summary.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── office-rules-start ──\n// Pure derivations over rosterStore-shaped invoice records: statuses are\n// draft -> sent -> paid; fields carry {client, amountCents, dueAt, note}.\n\nfunction toCents(amount) {\n if (typeof amount !== 'number' || !isFinite(amount) || amount <= 0) return null;\n return Math.round(amount * 100);\n}\n\nfunction fmtCents(cents) {\n var sign = cents < 0 ? '-' : '';\n var abs = Math.abs(cents);\n return sign + Math.floor(abs / 100) + '.' + String(abs % 100).padStart(2, '0');\n}\n\nfunction officeShape(records, nowMs) {\n var outstanding = 0;\n var overdue = [];\n var paidMonth = 0;\n var month = new Date(nowMs).toISOString().slice(0, 7);\n records.forEach(function (r) {\n var cents = typeof r.fields.amountCents === 'number' ? r.fields.amountCents : 0;\n if (r.status === 'sent') {\n outstanding += cents;\n var due = typeof r.fields.dueAt === 'string' ? Date.parse(r.fields.dueAt) : NaN;\n if (isFinite(due) && due < nowMs) overdue.push(r);\n }\n if (r.status === 'paid' && r.updatedAt.slice(0, 7) === month) paidMonth += cents;\n });\n return { outstanding: outstanding, overdue: overdue, paidMonth: paidMonth, month: month };\n}\n\nfunction officeLine(records, nowMs) {\n var shape = officeShape(records, nowMs);\n var chase = shape.overdue\n .map(function (r) {\n return r.fields.client + ' (' + r.id + ', ' + fmtCents(r.fields.amountCents || 0) + ')';\n })\n .join(', ');\n return (\n 'Outstanding ' +\n fmtCents(shape.outstanding) +\n ' across ' +\n records.filter(function (r) {\n return r.status === 'sent';\n }).length +\n ' sent invoice(s); ' +\n shape.overdue.length +\n ' overdue' +\n (chase ? ' (' + chase + ')' : '') +\n '. Paid this month: ' +\n fmtCents(shape.paidMonth) +\n '.'\n );\n}\n// ── office-rules-end ──\n\nconst invoices = rosterStore(gezel.fs, 'invoices.json', {\n stages: ['draft', 'sent', 'paid'],\n idPrefix: 'inv',\n});\n\nif (input.action === 'record_invoice') {\n const cents = toCents(input.amount);\n if (!input.client || cents === null) {\n throw new Error(\"record_invoice needs 'client' and a positive 'amount' (ordinary units).\");\n }\n await invoices.add({\n fields: {\n client: input.client,\n amountCents: cents,\n ...(input.due ? { dueAt: input.due } : {}),\n ...(input.note ? { note: input.note } : {}),\n },\n });\n} else if (input.action === 'invoice_sent' || input.action === 'invoice_paid') {\n if (!input.id) throw new Error(\"Pass the invoice 'id', e.g. 'inv-3'.\");\n await invoices.transition(input.id, input.action === 'invoice_sent' ? 'sent' : 'paid');\n} else if (input.action !== 'status' && input.action !== 'list_invoices') {\n throw new Error(\n `Unknown action '${input.action}'. Use status, record_invoice, invoice_sent, invoice_paid, or list_invoices.`,\n );\n}\n\nconst records = await invoices.list();\nconst shape = officeShape(records, Date.now());\nconst listing =\n input.action === 'list_invoices'\n ? records\n .map(\n (r) =>\n `${r.id} [${r.status}] ${String(r.fields.client ?? '?')} ${fmtCents(Number(r.fields.amountCents ?? 0))}${r.fields.dueAt ? ` due ${String(r.fields.dueAt).slice(0, 10)}` : ''}`,\n )\n .join('\\n') || 'The invoice book is empty.'\n : '';\n\ngezel.output({\n invoices: records.length,\n outstandingCents: shape.outstanding,\n overdue: shape.overdue.length,\n summary: listing || officeLine(records, Date.now()),\n});\n"},"tools":[{"name":"record_invoice","description":"Add an invoice to the book (amount in ordinary units).","script":"office-store","inputs":{"type":"object","properties":{"client":{"type":"string"},"amount":{"type":"number"},"due":{"type":"string"},"note":{"type":"string"}},"required":["client","amount"]},"bind":{"action":"record_invoice"}},{"name":"invoice_sent","description":"Mark an invoice sent to the client.","script":"office-store","inputs":{"type":"object","properties":{"id":{"type":"string"}},"required":["id"]},"bind":{"action":"invoice_sent"}},{"name":"invoice_paid","description":"Mark an invoice paid.","script":"office-store","inputs":{"type":"object","properties":{"id":{"type":"string"}},"required":["id"]},"bind":{"action":"invoice_paid"}},{"name":"office_status","description":"The money picture: outstanding, overdue, paid this month.","script":"office-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"}},{"name":"list_invoices","description":"Read the whole invoice book.","script":"office-store","inputs":{"type":"object","properties":{}},"bind":{"action":"list_invoices"}},{"name":"page_record_invoice","description":"Add an invoice to the book (amount in ordinary units).","script":"office-store","inputs":{"type":"object","properties":{"client":{"type":"string"},"amount":{"type":"number"},"due":{"type":"string"},"note":{"type":"string"}},"required":["client","amount"]},"bind":{"action":"record_invoice"}},{"name":"page_invoice_sent","description":"Mark an invoice sent to the client.","script":"office-store","inputs":{"type":"object","properties":{"id":{"type":"string"}},"required":["id"]},"bind":{"action":"invoice_sent"}},{"name":"page_invoice_paid","description":"Mark an invoice paid.","script":"office-store","inputs":{"type":"object","properties":{"id":{"type":"string"}},"required":["id"]},"bind":{"action":"invoice_paid"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"invoices.json"}],"tools":["page_record_invoice","page_invoice_sent","page_invoice_paid"]},"schedules":[],"workspaceSeed":["invoices.json"],"artifactsSeed":[],"availableVersions":["1.0.5","1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"fundraiser-hq","name":"Fundraiser HQ","description":"Rally a community drive. An infectious fundraiser keeps the thermometer honest, drafts warm sponsor outreach and progress posts, and makes sure every single donor gets thanked.","tags":["fundraiser","donations","community","charity","drive"],"category":"events","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.5","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"cause":{"type":"string","title":"What are you raising for?","description":"e.g. 'new jerseys for the team', 'the library roof'.","default":"a good cause"},"goalCents":{"type":"number","title":"Goal (in cents)","description":"The target, in cents — e.g. 500000 for 5,000.00.","default":100000}},"required":["cause","goalCents"]},"nameTemplate":"Fundraiser: {{cause}}","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"aanjager","voorman":true}],"toolsets":[],"craftbooks":["social-thread","drive-wrap-up"],"scripts":{"drive-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { ledgerStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'drive-store',\n description:\n \"Read and update the fundraising drive (donations.json). Call action:'status' for the thermometer + unthanked list; 'record_donation' the moment a gift lands (ordinary units, donor name); 'mark_thanked' once the thank-you goes out.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'status', 'record_donation', 'mark_thanked', or 'donor_list'.\",\n required: true,\n },\n donor: { type: 'string', description: \"Donor name ('anonymous' is fine).\" },\n amount: { type: 'number', description: 'Gift amount in ordinary units.' },\n note: { type: 'string', description: 'Anything worth remembering about the gift.' },\n id: { type: 'string', description: \"Donation id, e.g. 'ledger-4'.\" },\n },\n outputs: {\n raisedCents: { type: 'number', description: 'Total raised, in cents.' },\n donors: { type: 'number', description: 'Number of gifts.' },\n unthanked: { type: 'number', description: 'Gifts still awaiting a thank-you.' },\n summary: { type: 'string', description: 'The drive picture.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── drive-rules-start ──\n// Pure derivations over ledgerStore-shaped donation entries: entries are\n// kind 'in', category 'donation', data {donor, thanked}.\n\nfunction toCents(amount) {\n if (typeof amount !== 'number' || !isFinite(amount) || amount <= 0) return null;\n return Math.round(amount * 100);\n}\n\nfunction fmtCents(cents) {\n var abs = Math.abs(cents);\n return (cents < 0 ? '-' : '') + Math.floor(abs / 100) + '.' + String(abs % 100).padStart(2, '0');\n}\n\nfunction driveShape(entries) {\n var raised = 0;\n var unthanked = [];\n entries.forEach(function (e) {\n raised += e.amountCents;\n if (!e.data || e.data.thanked !== true) unthanked.push(e);\n });\n return { raised: raised, unthanked: unthanked };\n}\n\nfunction driveLine(entries, goalCents) {\n var shape = driveShape(entries);\n var pct = goalCents > 0 ? Math.min(100, Math.round((shape.raised / goalCents) * 100)) : null;\n return (\n 'Raised ' +\n fmtCents(shape.raised) +\n (goalCents > 0 ? ' of ' + fmtCents(goalCents) + ' (' + pct + ' percent)' : '') +\n ' across ' +\n entries.length +\n ' gift(s). ' +\n (shape.unthanked.length === 0\n ? 'Everyone thanked.'\n : shape.unthanked.length + ' thank-you(s) still owed.')\n );\n}\n// ── drive-rules-end ──\n\nconst donations = ledgerStore(gezel.fs, 'donations.json');\n\nasync function readGoalCents(): Promise<number> {\n try {\n const parsed = JSON.parse(await gezel.fs.read('donations.json')) as { goalCents?: unknown };\n const goal = Number(parsed.goalCents);\n return Number.isFinite(goal) && goal > 0 ? Math.round(goal) : 0;\n } catch {\n return 0;\n }\n}\n\nif (input.action === 'record_donation') {\n const cents = toCents(input.amount);\n if (cents === null) throw new Error(\"record_donation needs a positive 'amount' (ordinary units).\");\n await donations.add({\n amountCents: cents,\n kind: 'in',\n category: 'donation',\n ...(input.note ? { note: input.note } : {}),\n data: { donor: input.donor || 'anonymous', thanked: false },\n });\n} else if (input.action === 'mark_thanked') {\n if (!input.id && !input.donor) throw new Error(\"Pass 'id' (e.g. 'ledger-4') or a unique 'donor'.\");\n // ledgerStore is append-only by design; thanked flips via a targeted\n // read-modify-write on the entry's data (the one mutation this drive needs).\n const raw = JSON.parse(await gezel.fs.read('donations.json')) as {\n entries: Array<{ id: string; data?: { donor?: string; thanked?: boolean } }>;\n };\n const matches = raw.entries.filter((e) =>\n input.id\n ? e.id === input.id\n : String(e.data?.donor ?? '').toLowerCase() === String(input.donor).toLowerCase() &&\n e.data?.thanked !== true,\n );\n if (matches.length === 0) throw new Error('No matching unthanked donation found.');\n if (matches.length > 1 && !input.id) {\n throw new Error(\n `Multiple unthanked gifts from '${input.donor}': ${matches.map((m) => m.id).join(', ')}. Pass id.`,\n );\n }\n matches[0]!.data = { ...(matches[0]!.data ?? {}), thanked: true };\n await gezel.fs.write('donations.json', `${JSON.stringify(raw, null, 2)}\\n`);\n} else if (input.action !== 'status' && input.action !== 'donor_list') {\n throw new Error(\n `Unknown action '${input.action}'. Use status, record_donation, mark_thanked, or donor_list.`,\n );\n}\n\nconst entries = await donations.list();\nconst goalCents = await readGoalCents();\nconst shape = driveShape(entries);\nconst listing =\n input.action === 'donor_list'\n ? entries\n .map(\n (e) =>\n `${e.id} ${fmtCents(e.amountCents)} from ${String(e.data?.donor ?? 'anonymous')}${e.data?.thanked === true ? '' : ' (thank-you owed)'}`,\n )\n .join('\\n') || 'No gifts yet.'\n : '';\n\ngezel.output({\n raisedCents: shape.raised,\n donors: entries.length,\n unthanked: shape.unthanked.length,\n summary: listing || driveLine(entries, goalCents),\n});\n"},"tools":[{"name":"record_donation","description":"Record a gift the moment it lands (ordinary units, donor name).","script":"drive-store","inputs":{"type":"object","properties":{"donor":{"type":"string"},"amount":{"type":"number"},"note":{"type":"string"}},"required":["amount"]},"bind":{"action":"record_donation"}},{"name":"mark_thanked","description":"Record that a thank-you went out for a gift.","script":"drive-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"donor":{"type":"string"}}},"bind":{"action":"mark_thanked"}},{"name":"drive_status","description":"The thermometer and the thank-you debt.","script":"drive-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"}},{"name":"donor_list","description":"Every gift, with thank-you state.","script":"drive-store","inputs":{"type":"object","properties":{}},"bind":{"action":"donor_list"}},{"name":"page_record_donation","description":"Record a gift the moment it lands (ordinary units, donor name).","script":"drive-store","inputs":{"type":"object","properties":{"donor":{"type":"string"},"amount":{"type":"number"},"note":{"type":"string"}},"required":["amount"]},"bind":{"action":"record_donation"}},{"name":"page_mark_thanked","description":"Record that a thank-you went out for a gift.","script":"drive-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"donor":{"type":"string"}}},"bind":{"action":"mark_thanked"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"donations.json"}],"tools":["page_record_donation","page_mark_thanked"]},"schedules":[],"workspaceSeed":["donations.json"],"artifactsSeed":[],"availableVersions":["1.0.5","1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"go","name":"Go","description":"Play Go against a gezel opponent on a live 9×9, 13×13, or 19×19 board. Place black stones; the Go player reads the exact position, replies in white, and keeps the conversation calm and sporting.","tags":["go","baduk","weiqi","game","board-game","strategy","play"],"category":"game","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.7","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"tabVisibility":{"overview":false,"tasks":false,"approvals":false,"workspace":false,"artifacts":false,"map":false},"mode":"solo","leadLabel":"Opponent","leanProfile":true,"params":{"type":"object","properties":{"personality":{"type":"string","title":"Table-talk style","description":"How your opponent talks between moves. In-character follows the gezel's own character when social mode is on.","enum":["in-character","peppy","cheeky","zen","gracious"],"default":"in-character"},"playStyle":{"type":"string","title":"How should the Go player play?","description":"An opponent keeps their strategy to themselves; an instructor offers light teaching notes.","enum":["Opponent","Instructor"],"default":"Opponent"}},"required":["personality","playStyle"]},"nameTemplate":"Go Table","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"go-player","voorman":true}],"toolsets":[],"craftbooks":[],"scripts":{"game-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\n\nexport const meta = defineScript({\n name: 'game-store',\n description:\n \"Read and update the Go game (game.json). Call action:'board' to see the position and every legal move; action:'ai_move' to play a coordinate such as D4 or 'pass' (optional moveThought); action:'state' for a light summary; action:'new_game' to reset with boardSize 9, 13, or 19 and optional komi. The engine enforces captures, suicide, simple ko, passing, and area scoring.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'state', 'board', 'user_move', 'ai_move', or 'new_game'.\",\n required: true,\n },\n move: {\n type: 'string',\n description: \"A board coordinate such as 'D4', or 'pass'.\",\n },\n boardSize: {\n type: 'number',\n description: 'For new_game: 9, 13, or 19. Defaults to 9.',\n },\n komi: {\n type: 'number',\n description: 'For new_game: points added to white. Defaults to 6.5.',\n },\n moveThought: {\n type: 'string',\n description: 'A short line of table talk to show on the board (max 140 chars).',\n },\n },\n outputs: {\n board: { type: 'string', description: 'ASCII board with coordinates.' },\n turn: { type: 'string', description: \"Whose move: 'user' (black) or 'ai' (white).\" },\n status: {\n type: 'string',\n description: 'playing, user_won, ai_won, or draw.',\n },\n lastMove: { type: 'string', description: \"The move just played, e.g. 'D4' or 'pass'.\" },\n legalMoves: { type: 'string', description: 'Legal placements plus pass.' },\n score: { type: 'string', description: 'Area score when the game has ended.' },\n summary: { type: 'string', description: 'Human-readable game summary.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── go-rules-start ──\n// Pure, annotation-free Go engine. Supports 9x9, 13x13, and 19x19.\n// Squares are row-major, y0 at the top. X = black/user; O = white/AI.\n// Coordinates follow Go convention and skip the letter I.\n\nvar GO_FILES = 'ABCDEFGHJKLMNOPQRST';\n\nfunction buildInitial(size) {\n return '.'.repeat(size * size);\n}\n\nfunction inBounds(x, y, size) {\n return x >= 0 && x < size && y >= 0 && y < size;\n}\n\nfunction pointName(x, y, size) {\n return GO_FILES[x] + String(size - y);\n}\n\nfunction parsePoint(name, size) {\n if (typeof name !== 'string') return null;\n var text = name.trim().toUpperCase();\n var match = /^([A-HJ-T])(\\d{1,2})$/.exec(text);\n if (!match) return null;\n var x = GO_FILES.indexOf(match[1]);\n var rank = Number(match[2]);\n if (x < 0 || x >= size || rank < 1 || rank > size) return null;\n return { x: x, y: size - rank, index: (size - rank) * size + x };\n}\n\nfunction neighbors(index, size) {\n var x = index % size;\n var y = Math.floor(index / size);\n var out = [];\n if (x > 0) out.push(index - 1);\n if (x + 1 < size) out.push(index + 1);\n if (y > 0) out.push(index - size);\n if (y + 1 < size) out.push(index + size);\n return out;\n}\n\nfunction groupAt(squares, index, size) {\n var color = squares[index];\n var stones = [];\n var liberties = {};\n var seen = {};\n var queue = [index];\n seen[index] = true;\n while (queue.length) {\n var current = queue.pop();\n stones.push(current);\n for (var next of neighbors(current, size)) {\n if (squares[next] === '.') liberties[next] = true;\n else if (squares[next] === color && !seen[next]) {\n seen[next] = true;\n queue.push(next);\n }\n }\n }\n return { stones: stones, liberties: Object.keys(liberties).map(Number) };\n}\n\nfunction replaceAt(squares, index, ch) {\n return squares.slice(0, index) + ch + squares.slice(index + 1);\n}\n\nfunction applyPlacement(squares, size, side, name, previousPosition) {\n var point = parsePoint(name, size);\n if (!point) return { error: 'bad-coordinate' };\n if (squares[point.index] !== '.') return { error: 'occupied' };\n var stone = side === 'user' ? 'X' : 'O';\n var enemy = side === 'user' ? 'O' : 'X';\n var next = replaceAt(squares, point.index, stone);\n var captures = [];\n var checked = {};\n for (var adjacent of neighbors(point.index, size)) {\n if (next[adjacent] !== enemy || checked[adjacent]) continue;\n var enemyGroup = groupAt(next, adjacent, size);\n for (var member of enemyGroup.stones) checked[member] = true;\n if (enemyGroup.liberties.length === 0) {\n for (var captured of enemyGroup.stones) {\n next = replaceAt(next, captured, '.');\n captures.push(pointName(captured % size, Math.floor(captured / size), size));\n }\n }\n }\n if (groupAt(next, point.index, size).liberties.length === 0) return { error: 'suicide' };\n if (previousPosition && next === previousPosition) return { error: 'ko' };\n return { squares: next, captures: captures };\n}\n\nfunction legalMovesFor(squares, size, side, previousPosition) {\n var moves = [];\n for (var y = 0; y < size; y += 1) {\n for (var x = 0; x < size; x += 1) {\n if (squares[y * size + x] !== '.') continue;\n var name = pointName(x, y, size);\n var result = applyPlacement(squares, size, side, name, previousPosition);\n if (!result.error) moves.push(name);\n }\n }\n moves.push('pass');\n return moves;\n}\n\nfunction scoreArea(squares, size, komi) {\n var blackStones = 0;\n var whiteStones = 0;\n var blackTerritory = 0;\n var whiteTerritory = 0;\n var seen = {};\n for (var i = 0; i < squares.length; i += 1) {\n if (squares[i] === 'X') {\n blackStones += 1;\n continue;\n }\n if (squares[i] === 'O') {\n whiteStones += 1;\n continue;\n }\n if (seen[i]) continue;\n var region = [];\n var borders = {};\n var queue = [i];\n seen[i] = true;\n while (queue.length) {\n var current = queue.pop();\n region.push(current);\n for (var next of neighbors(current, size)) {\n if (squares[next] === '.' && !seen[next]) {\n seen[next] = true;\n queue.push(next);\n } else if (squares[next] === 'X' || squares[next] === 'O') {\n borders[squares[next]] = true;\n }\n }\n }\n if (borders.X && !borders.O) blackTerritory += region.length;\n if (borders.O && !borders.X) whiteTerritory += region.length;\n }\n var black = blackStones + blackTerritory;\n var white = whiteStones + whiteTerritory + komi;\n return {\n black: black,\n white: white,\n blackStones: blackStones,\n whiteStones: whiteStones,\n blackTerritory: blackTerritory,\n whiteTerritory: whiteTerritory,\n winner: black === white ? 'draw' : black > white ? 'user' : 'ai',\n margin: Math.abs(black - white),\n };\n}\n\nfunction statusAfter(squares, size, komi, consecutivePasses) {\n if (consecutivePasses < 2) return 'playing';\n var score = scoreArea(squares, size, komi);\n return score.winner === 'draw' ? 'draw' : score.winner === 'user' ? 'user_won' : 'ai_won';\n}\n\nfunction renderAscii(squares, size) {\n var labels = [];\n for (var x = 0; x < size; x += 1) labels.push(GO_FILES[x]);\n var pad = size >= 10 ? ' ' : ' ';\n var lines = [pad + labels.join(' ')];\n for (var y = 0; y < size; y += 1) {\n var rank = String(size - y).padStart(size >= 10 ? 2 : 1, ' ');\n var row = [];\n for (var x = 0; x < size; x += 1) row.push(squares[y * size + x]);\n lines.push(rank + ' ' + row.join(' ') + ' ' + rank);\n }\n lines.push(pad + labels.join(' '));\n lines.push('X = black (user). O = white (you).');\n return lines.join('\\n');\n}\n// ── go-rules-end ──\n\nconst STATE_FILE = 'game.json';\nconst SIDE_NAMES = { user: 'black', ai: 'white' };\n\ninterface GameState {\n version: number;\n boardSize: number;\n squares: string;\n turn: 'user' | 'ai';\n status: 'playing' | 'user_won' | 'ai_won' | 'draw';\n komi: number;\n consecutivePasses: number;\n previousPosition: string | null;\n legalMoves: string[];\n captures: { user: number; ai: number };\n score: ReturnType<typeof scoreArea> | null;\n moveLog: Array<{\n by: 'user' | 'ai';\n move: string;\n captures: string[];\n at: string;\n moveThought?: string;\n }>;\n lastMove: { by: 'user' | 'ai'; move: string; captures: string[] } | null;\n lastMoveThought: string;\n updatedAt: string;\n}\n\nfunction validSize(value: unknown): number {\n const size = Number(value);\n return size === 13 || size === 19 ? size : 9;\n}\n\nfunction validKomi(value: unknown): number {\n const komi = Number(value);\n return Number.isFinite(komi) && komi >= 0 && komi <= 20 ? komi : 6.5;\n}\n\nfunction freshState(boardSize = 9, komi = 6.5): GameState {\n const size = validSize(boardSize);\n const nextKomi = validKomi(komi);\n const squares = buildInitial(size);\n return {\n version: 1,\n boardSize: size,\n squares,\n turn: 'user',\n status: 'playing',\n komi: nextKomi,\n consecutivePasses: 0,\n previousPosition: null,\n legalMoves: legalMovesFor(squares, size, 'user', null),\n captures: { user: 0, ai: 0 },\n score: null,\n moveLog: [],\n lastMove: null,\n lastMoveThought: '',\n updatedAt: new Date().toISOString(),\n };\n}\n\nasync function load(): Promise<GameState> {\n let raw: string;\n try {\n raw = await gezel.fs.read(STATE_FILE);\n } catch {\n return freshState();\n }\n const parsed = JSON.parse(raw) as Partial<GameState>;\n const size = validSize(parsed.boardSize);\n if (typeof parsed.squares !== 'string' || parsed.squares.length !== size * size) {\n throw new Error(`${STATE_FILE} is corrupt; call action:'new_game' to reset.`);\n }\n return {\n ...freshState(size, parsed.komi),\n ...parsed,\n boardSize: size,\n komi: validKomi(parsed.komi),\n } as GameState;\n}\n\nasync function persist(state: GameState): Promise<GameState> {\n state.legalMoves =\n state.status === 'playing'\n ? legalMovesFor(\n state.squares,\n state.boardSize,\n state.turn,\n state.previousPosition,\n )\n : [];\n state.updatedAt = new Date().toISOString();\n await gezel.fs.write(STATE_FILE, `${JSON.stringify(state, null, 2)}\\n`);\n return state;\n}\n\nfunction renderLegal(state: GameState): string {\n if (state.status !== 'playing') return '(game over)';\n return state.legalMoves.join(', ');\n}\n\nfunction renderScore(state: GameState): string {\n if (!state.score) return '(not scored — play continues)';\n const result =\n state.score.winner === 'draw'\n ? 'draw'\n : `${SIDE_NAMES[state.score.winner]} wins by ${state.score.margin}`;\n return `Black ${state.score.black}; white ${state.score.white} (includes ${state.komi} komi): ${result}.`;\n}\n\nfunction summarize(state: GameState): string {\n if (state.status !== 'playing') return `Game over. ${renderScore(state)}`;\n return `Move ${state.moveLog.length + 1}: ${SIDE_NAMES[state.turn]} (${state.turn}) to move on ${state.boardSize}x${state.boardSize}. Captures — black ${state.captures.user}, white ${state.captures.ai}.`;\n}\n\nfunction applyTurn(\n state: GameState,\n by: 'user' | 'ai',\n moveThought?: string,\n): GameState {\n if (state.status !== 'playing') {\n throw new Error(`The game is over (${state.status}). Call action:'new_game' to start another.`);\n }\n if (state.turn !== by) {\n throw new Error(by === 'ai' ? \"It's not your turn yet.\" : 'The opponent is still to move.');\n }\n const move = input.move?.trim() || '';\n const normalized = move.toLowerCase() === 'pass' ? 'pass' : move.toUpperCase();\n if (!state.legalMoves.includes(normalized)) {\n throw new Error(\n `Illegal move '${move}'. Legal moves for ${SIDE_NAMES[by]}: ${renderLegal(state)}`,\n );\n }\n\n let captured: string[] = [];\n const before = state.squares;\n if (normalized === 'pass') {\n state.consecutivePasses += 1;\n } else {\n const applied = applyPlacement(\n state.squares,\n state.boardSize,\n by,\n normalized,\n state.previousPosition,\n );\n if (applied.error || !applied.squares) {\n throw new Error(`Illegal move '${move}' (${applied.error || 'unknown'}).`);\n }\n state.squares = applied.squares;\n captured = applied.captures || [];\n state.captures[by] += captured.length;\n state.consecutivePasses = 0;\n }\n state.previousPosition = before;\n state.turn = (by === 'user' ? 'ai' : 'user') as 'user' | 'ai';\n state.status = statusAfter(\n state.squares,\n state.boardSize,\n state.komi,\n state.consecutivePasses,\n ) as GameState['status'];\n if (state.status !== 'playing') {\n state.score = scoreArea(state.squares, state.boardSize, state.komi);\n }\n const entry = {\n by,\n move: normalized,\n captures: captured,\n at: new Date().toISOString(),\n ...(moveThought ? { moveThought } : {}),\n };\n state.moveLog.push(entry);\n state.lastMove = { by, move: normalized, captures: captured };\n if (by === 'ai' && moveThought) state.lastMoveThought = moveThought;\n return state;\n}\n\nlet state = await load();\nlet lastMoveText = state.lastMove?.move ?? '(none)';\n\nif (input.action === 'new_game') {\n state = await persist(freshState(input.boardSize, input.komi));\n lastMoveText = '(none)';\n} else if (input.action === 'user_move' || input.action === 'ai_move') {\n const by = input.action === 'user_move' ? 'user' : 'ai';\n const moveThought = input.moveThought?.trim().slice(0, 140);\n state = await persist(applyTurn(state, by, moveThought));\n lastMoveText = state.lastMove?.move ?? '(none)';\n} else if (input.action !== 'state' && input.action !== 'board') {\n throw new Error(`Unknown action '${input.action}'. Use state, board, user_move, ai_move, or new_game.`);\n}\n\ngezel.output({\n board:\n `${renderAscii(state.squares, state.boardSize)}\\nTurn: ${SIDE_NAMES[state.turn]} (${state.turn}).\\n` +\n `Komi: ${state.komi}. Consecutive passes: ${state.consecutivePasses}.\\n` +\n `Legal moves: ${renderLegal(state)}`,\n turn: state.turn,\n status: state.status,\n lastMove: lastMoveText,\n legalMoves: renderLegal(state),\n score: renderScore(state),\n summary: summarize(state),\n});\n"},"tools":[{"name":"get_board","description":"See the authoritative Go position, board size, captures, whose turn it is, and every legal move.","script":"game-store","inputs":{"type":"object","properties":{}},"bind":{"action":"board"},"state":true},{"name":"make_move","description":"Play your white move. Pass a coordinate such as 'D4', or 'pass', plus optional moveThought.","script":"game-store","inputs":{"type":"object","properties":{"move":{"type":"string","description":"A legal coordinate such as 'D4', or 'pass'."},"moveThought":{"type":"string","description":"A short line of table talk (max 140 chars)."}},"required":["move"]},"bind":{"action":"ai_move"},"turn":{"say":"moveThought","fallback":"Move made — your turn."}},{"name":"user_move","description":"The user's black move or pass, played from the Go board.","script":"game-store","inputs":{"type":"object","properties":{"move":{"type":"string"}},"required":["move"]},"bind":{"action":"user_move"},"reaction":{"gezel":"go-player","prompt":"Your opponent played {{output.lastMove}}. Status: {{output.status}}. Board now:\n{{output.board}}\nThe board and Legal moves line come directly from the Go engine and are always correct. Do not re-derive captures, liberties, ko, scoring, or legality, and do not invent a coordinate outside the legal list. Spend your thought on choosing among the listed moves.\nStyle: {{playStyle}}. In Opponent style, do not volunteer advice or reveal the user’s available moves, weak groups, threats, or your plan; comment only about your own move or the atmosphere. In Instructor style, offer at most one brief teaching observation without choosing the user’s move. Answer strategy questions when asked.\nAct on this latest position. If the game is over, do not move — give one gracious line about the result and offer a new game. Otherwise choose a strong legal move (or pass when strategically sound) and play it with make_move, including a short {{personality}} moveThought. If make_move rejects it, choose one move verbatim from the legal list in the error and retry. After moving, reply with ONE short line of table talk.","hideSeed":true,"standalone":true,"turn":{"tool":"make_move","when":{"op":"equals","field":"status","value":"playing"}}}},{"name":"new_game","description":"Reset the Go board. Choose 9, 13, or 19 lines and optional komi; defaults to 9×9 with 6.5 komi.","script":"game-store","inputs":{"type":"object","properties":{"boardSize":{"type":"number","enum":[9,13,19]},"komi":{"type":"number","minimum":0,"maximum":20}}},"bind":{"action":"new_game"}}],"pages":{"entry":"board/index.html","api":1,"reads":[{"source":"workspace","path":"game.json"}],"tools":["user_move","new_game"]},"schedules":[],"workspaceSeed":["game.json"],"artifactsSeed":[],"availableVersions":["1.0.7","1.0.6","1.0.5","1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"grants-and-proposals","name":"Grants & Proposals","description":"Find grants, write proposals and meet every deadline. A fundraiser tracks each funding opportunity and request for proposals with its deadline, fit and ask, keeps a requirements checklist for every submission, records what was awarded, and reminds you two weeks before the next deadline.","tags":["grants","rfp","funding","funders"],"category":"money","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.0.0","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"organization":{"type":"string","title":"Who is applying?","description":"e.g. 'a small literary press', 'a community theater in Tacoma'.","default":"the organization"},"focus":{"type":"string","title":"What will the funding support?","description":"e.g. 'new translations and author readings'.","default":"its work"}},"required":["organization","focus"]},"nameTemplate":"Grants & Proposals","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"aanjager","voorman":true},{"templateId":"researcher","voorman":false},{"templateId":"copywriter","voorman":false}],"toolsets":[],"craftbooks":["research-report","proposal-sow","evidence-brief"],"scripts":{"grants-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'grants-store',\n description:\n \"Read and update the funding pipeline (opportunities.json) and each submission's requirements checklist (requirements.json). action:'status' for the open opportunities by deadline with what each still needs, what awaits a decision, and the outcomes; 'add' saves an opportunity (an existing title is updated, never duplicated); 'update' changes one (extendDays moves its deadline later); 'stage' moves one to prospect, drafting, submitted or passed; 'outcome' records awarded, declined or passed; 'add_requirement' and 'check_requirement' keep the checklist.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'status', 'add', 'update', 'stage', 'outcome', 'add_requirement', or 'check_requirement'.\",\n required: true,\n },\n opportunity: { type: 'string', description: \"An opportunity's id ('op-2') or (part of) its title.\" },\n title: { type: 'string', description: \"The opportunity's or requirement's title, e.g. 'Small Press Grant' or 'Budget narrative'.\" },\n titles: { type: 'json', description: 'Several requirement titles at once, as a list.' },\n requirement: { type: 'string', description: \"A requirement's id ('req-4') or (part of) its title.\" },\n funder: { type: 'string', description: 'Who gives the money, e.g. Oregon Literary Arts.' },\n kind: { type: 'string', description: 'grant, rfp, fellowship, sponsorship, or other.' },\n deadline: { type: 'string', description: 'The submission deadline, YYYY-MM-DD.' },\n extendDays: { type: 'number', description: 'How many days later the deadline moved, e.g. 14.' },\n ask: { type: 'number', description: 'The amount requested, in dollars, e.g. 8000.' },\n award: { type: 'number', description: 'The amount awarded, in dollars.' },\n fit: { type: 'string', description: 'strong, good, or long shot.' },\n url: { type: 'string', description: 'Where the guidelines live.' },\n stage: { type: 'string', description: 'prospect, drafting, submitted, or passed.' },\n outcome: { type: 'string', description: 'awarded, declined, or passed.' },\n owner: { type: 'string', description: 'Who is preparing a requirement.' },\n done: { type: 'boolean', description: 'For check_requirement: false reopens it (default true).' },\n withinDays: { type: 'number', description: 'How many days ahead counts as due soon (default 30).' },\n note: { type: 'string', description: 'What happened, with any reference number exactly as written.' },\n },\n outputs: {\n open: { type: 'number', description: 'Opportunities still being considered or drafted.' },\n dueSoon: { type: 'number', description: 'Open opportunities due within the window, missed deadlines included.' },\n awaiting: { type: 'number', description: 'Submissions awaiting a decision.' },\n awarded: { type: 'number', description: 'Total awarded, in dollars.' },\n summary: {\n type: 'string',\n description: 'What changed first, then the open opportunities by deadline with what each still needs, the submissions awaiting a decision, and the outcomes.',\n },\n },\n requires: ['workspace.read', 'workspace.write', 'reminders'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── grants-rules-start ──\n// Pure derivations: days to a deadline in local calendar days, a moved\n// deadline, money in integer cents, each submission's readiness, and the\n// pipeline lines the crew reads. Kept self-contained between these sentinels\n// so unit tests execute the shipped bytes.\nvar DAY_MS = 86400000;\nvar OPEN_STAGES = ['prospect', 'drafting'];\nvar STOP_WORDS = ['the', 'and', 'for', 'our', 'with', 'from', 'that', 'this', 'into', 'grant', 'fund'];\n\nfunction pad(n) {\n return n < 10 ? '0' + n : String(n);\n}\nfunction localDay(ms) {\n var d = new Date(ms);\n return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());\n}\nfunction normalizeDate(text) {\n var raw = String(text || '').trim();\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(raw)) return raw;\n var parsed = Date.parse(raw);\n return isFinite(parsed) ? localDay(parsed) : null;\n}\nfunction dayMs(day) {\n return Date.parse(String(day).slice(0, 10) + 'T00:00:00');\n}\nfunction daysLeft(day, nowMs) {\n return Math.round((dayMs(day) - dayMs(localDay(nowMs))) / DAY_MS);\n}\nfunction addDays(day, days) {\n var d = new Date(String(day).slice(0, 10) + 'T12:00:00');\n d.setDate(d.getDate() + Math.round(days));\n return localDay(d.getTime());\n}\nfunction when(days) {\n if (days < 0) return -days + (days === -1 ? ' day late' : ' days late');\n if (days === 0) return 'due today';\n return 'in ' + days + (days === 1 ? ' day' : ' days');\n}\nfunction toCents(amount) {\n if (typeof amount !== 'number' || !isFinite(amount) || amount < 0) return null;\n return Math.round(amount * 100);\n}\nfunction money(cents) {\n var c = Math.round(Number(cents) || 0);\n var whole = Math.floor(Math.abs(c) / 100);\n var rest = Math.abs(c) % 100;\n return (c < 0 ? '-' : '') + '$' + String(whole).replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',') + (rest ? '.' + pad(rest) : '');\n}\nfunction normalizeFit(text) {\n var t = String(text || '').trim().toLowerCase();\n if (!t) return null;\n if (/long|weak|low|poor|stretch|unlikely|reach/.test(t)) return 'long shot';\n if (/strong|great|excellent|perfect|high|ideal/.test(t)) return 'strong';\n if (/good|ok|fair|decent|medium|possible|moderate|solid/.test(t)) return 'good';\n return null;\n}\nfunction normalizeKind(text) {\n var t = String(text || '').trim().toLowerCase();\n if (!t) return null;\n if (/rfp|request for proposal|proposal|tender|bid|contract/.test(t)) return 'rfp';\n if (/fellow|residen/.test(t)) return 'fellowship';\n if (/sponsor/.test(t)) return 'sponsorship';\n if (/grant|award|fund/.test(t)) return 'grant';\n return 'other';\n}\nfunction normalizeStage(text) {\n var t = String(text || '').trim().toLowerCase();\n if (/^(prospect|research|consider|maybe|watch|idea)/.test(t)) return 'prospect';\n if (/^(draft|writ|work|start|in.progress|prepar)/.test(t)) return 'drafting';\n if (/^(submit|sent|applied|filed|delivered)/.test(t)) return 'submitted';\n if (/^(pass|skip|not.apply|withdr|drop)/.test(t)) return 'passed';\n return null;\n}\nfunction normalizeOutcome(text) {\n var t = String(text || '').trim().toLowerCase();\n if (/^(award|won|win|funded|granted|approved|accepted|yes)/.test(t)) return 'awarded';\n if (/^(declin|reject|denied|turned|unsuccess|lost|no\\b)/.test(t)) return 'declined';\n if (/^(pass|withdr|skip|drop)/.test(t)) return 'passed';\n return null;\n}\nfunction titleOf(record) {\n return String((record && record.fields && record.fields.title) || '');\n}\nfunction requirementsFor(op, reqs) {\n return reqs.filter(function (r) {\n return r.fields && r.fields.opportunityId === op.id;\n });\n}\nfunction readiness(op, reqs) {\n var mine = requirementsFor(op, reqs);\n var open = mine.filter(function (r) { return r.status !== 'done'; });\n return { done: mine.length - open.length, total: mine.length, open: open };\n}\nfunction opLine(op, reqs, nowMs) {\n var f = op.fields || {};\n var r = readiness(op, reqs);\n var facts = [f.funder, f.kind, f.fit ? f.fit + ' fit' : '', typeof f.askCents === 'number' ? 'ask ' + money(f.askCents) : '', op.status].filter(Boolean);\n return (\n op.id + ' ' + f.title + ' (' + facts.join(', ') + ')' +\n (f.deadline ? ' due ' + f.deadline + ', ' + when(daysLeft(f.deadline, nowMs)) : ', no deadline yet') +\n '; requirements ' +\n (r.total\n ? r.done + ' of ' + r.total + ' done' + (r.open.length ? ', still to do: ' + r.open.map(function (x) { return x.id + ' ' + titleOf(x); }).join(', ') : ', ready to submit')\n : 'not listed yet')\n );\n}\nfunction picture(ops, reqs, nowMs, withinDays) {\n var byDeadline = function (a, b) { return String(a.fields.deadline).localeCompare(String(b.fields.deadline)); };\n var open = ops.filter(function (o) { return OPEN_STAGES.indexOf(o.status) >= 0; });\n // One list, missed deadlines first: asked \"what's due\", a model reads a side list as out of scope.\n var dated = open.filter(function (o) { return o.fields && o.fields.deadline; }).sort(byDeadline);\n var undated = open.filter(function (o) { return !(o.fields && o.fields.deadline); });\n var soon = dated.filter(function (o) { return daysLeft(o.fields.deadline, nowMs) <= withinDays; });\n var awaiting = ops.filter(function (o) { return o.status === 'submitted'; });\n var awarded = ops.filter(function (o) { return o.status === 'awarded'; });\n var declined = ops.filter(function (o) { return o.status === 'declined'; });\n var passed = ops.filter(function (o) { return o.status === 'passed'; });\n var askCents = open.reduce(function (sum, o) { return sum + (typeof o.fields.askCents === 'number' ? o.fields.askCents : 0); }, 0);\n var awardedCents = awarded.reduce(function (sum, o) { return sum + (typeof o.fields.awardCents === 'number' ? o.fields.awardCents : 0); }, 0);\n var parts = [];\n parts.push(\n open.length\n ? open.length + (open.length === 1 ? ' open opportunity' : ' open opportunities') + (askCents ? ', asking ' + money(askCents) + ' in all' : '') + ', ' + soon.length + ' due within ' + withinDays + ' days.'\n : ops.length ? 'No open opportunities.' : 'No open opportunities yet.',\n );\n if (dated.length) parts.push('Open opportunities by deadline, soonest first: ' + dated.map(function (o) { return opLine(o, reqs, nowMs); }).join(' | ') + '.');\n if (undated.length) parts.push('No deadline yet: ' + undated.map(function (o) { return opLine(o, reqs, nowMs); }).join(' | ') + '.');\n parts.push(\n awaiting.length\n ? 'Submitted, awaiting a decision: ' +\n awaiting.map(function (o) {\n var f = o.fields;\n return o.id + ' ' + f.title + ' (' + [f.funder, typeof f.askCents === 'number' ? 'ask ' + money(f.askCents) : '', f.submittedAt ? 'submitted ' + f.submittedAt : ''].filter(Boolean).join(', ') + ')';\n }).join('; ') + '.'\n : 'Nothing awaiting a decision.',\n );\n if (awarded.length || declined.length || passed.length) {\n parts.push(\n 'Outcomes: ' + awarded.length + ' awarded' +\n (awarded.length ? ' (' + money(awardedCents) + ': ' + awarded.map(function (o) { return titleOf(o) + ' ' + money(o.fields.awardCents || 0); }).join(', ') + ')' : '') +\n ', ' + declined.length + ' declined, ' + passed.length + ' passed on.',\n );\n }\n return { open: open.length, dueSoon: soon.length, awaiting: awaiting.length, awardedCents: awardedCents, summary: parts.join(' ') };\n}\n// Find one record by id, exact title, partial title, or every word of the\n// title; a miss lists what there is so the next call can name it.\nfunction pick(records, wanted, label) {\n var text = String(wanted || '').trim();\n var lower = text.toLowerCase();\n if (!lower) throw new Error('Name the ' + label + ' by its id or title.');\n var byId = records.filter(function (r) { return r.id === lower; });\n if (byId.length) return byId[0];\n var exact = records.filter(function (r) { return titleOf(r).toLowerCase() === lower; });\n if (exact.length === 1) return exact[0];\n var partial = records.filter(function (r) {\n var t = titleOf(r).toLowerCase();\n var funder = String((r.fields && r.fields.funder) || '').toLowerCase();\n return t.indexOf(lower) >= 0 || (funder && funder.indexOf(lower) >= 0);\n });\n if (partial.length === 1) return partial[0];\n if (!partial.length) {\n var words = (lower.match(/[a-z0-9]{3,}/g) || []).filter(function (w) { return STOP_WORDS.indexOf(w) < 0; });\n partial = words.length\n ? records.filter(function (r) {\n var t = (titleOf(r) + ' ' + String((r.fields && r.fields.funder) || '')).toLowerCase();\n return words.every(function (w) { return t.indexOf(w) >= 0 || t.indexOf(w.replace(/ies$/, 'y').replace(/s$/, '')) >= 0; });\n })\n : [];\n if (partial.length === 1) return partial[0];\n }\n var known = (partial.length > 1 ? partial : records).map(function (r) { return r.id + ' ' + titleOf(r); }).join(', ');\n throw new Error(\n (partial.length > 1 ? 'More than one ' + label + \" matches '\" + text + \"': \" : 'No ' + label + \" matches '\" + text + \"'. Known: \") +\n (known || 'none yet') + '. Pass the id.',\n );\n}\nfunction pickPreferring(preferred, all, wanted, label) {\n try {\n return pick(preferred, wanted, label);\n } catch (error) {\n return pick(all, wanted, label);\n }\n}\nfunction requirementTitles(single, list) {\n var items = [];\n if (Array.isArray(list)) items = list.map(function (x) { return String(x); });\n else if (typeof list === 'string') items = list.split(/\\s*(?:;|\\n)\\s*/);\n if (single) items.unshift(String(single));\n var seen = [];\n return items\n .map(function (x) { return x.replace(/^[\\s*-]+/, '').trim(); })\n .filter(function (x) {\n if (!x || seen.indexOf(x.toLowerCase()) >= 0) return false;\n seen.push(x.toLowerCase());\n return true;\n });\n}\n// ── grants-rules-end ──\n\nconst opportunities = rosterStore(gezel.fs, 'opportunities.json', {\n stages: ['prospect', 'drafting', 'submitted', 'awarded', 'declined', 'passed'],\n idPrefix: 'op',\n});\nconst requirements = rosterStore(gezel.fs, 'requirements.json', { stages: ['todo', 'done'], idPrefix: 'req' });\n\nfunction text(value: unknown): string {\n return typeof value === 'string' ? value.trim() : '';\n}\nasync function findOpportunity(wanted: string) {\n const all = await opportunities.list();\n const live = all.filter((o) => OPEN_STAGES.includes(o.status) || o.status === 'submitted');\n return pickPreferring(live, all, wanted, 'opportunity');\n}\n\n// The desk's one reminder sits two weeks ahead of the soonest open deadline.\nasync function remindNextDeadline(): Promise<void> {\n const now = Date.now();\n const lead = 14 * DAY_MS;\n const reqs = await requirements.list();\n const next = (await opportunities.list())\n .filter((o) => OPEN_STAGES.includes(o.status) && typeof o.fields.deadline === 'string')\n .map((o) => ({ op: o, at: Date.parse(String(o.fields.deadline) + 'T09:00:00') - lead }))\n .filter((o) => o.at > now)\n .sort((a, b) => a.at - b.at)[0];\n try {\n if (!next || next.at - now > 30 * DAY_MS) {\n await gezel.reminder.clear();\n } else {\n const name = titleOf(next.op);\n const ready = readiness(next.op, reqs);\n await gezel.reminder.set({\n at: new Date(next.at).toISOString(),\n title: (name.length > 58 ? name.slice(0, 57) + '…' : name) + ' is due in two weeks',\n body: 'Deadline ' + String(next.op.fields.deadline) + '. ' + (ready.total ? ready.done + ' of ' + ready.total + ' requirements done.' : 'No requirements listed yet.'),\n });\n }\n } catch {\n // Reminders are a convenience; the pipeline is the record.\n }\n}\n\n// The fields an add or update sets; a missing deadline to extend is an error.\nfunction changes(existingDeadline: string | null): { fields: Record<string, unknown>; said: string[] } {\n const fields: Record<string, unknown> = {};\n const said: string[] = [];\n if (text(input.funder)) fields.funder = text(input.funder);\n if (text(input.kind)) fields.kind = normalizeKind(input.kind);\n if (text(input.fit)) {\n const fit = normalizeFit(input.fit);\n if (!fit) throw new Error(\"fit must be 'strong', 'good', or 'long shot'.\");\n fields.fit = fit;\n }\n if (text(input.url)) fields.url = text(input.url);\n if (text(input.note)) fields.notes = text(input.note);\n if (typeof input.ask === 'number') {\n const cents = toCents(input.ask);\n if (cents === null) throw new Error('ask must be an amount in dollars, e.g. 8000.');\n fields.askCents = cents;\n said.push('ask ' + money(cents));\n }\n let deadline = existingDeadline;\n if (text(input.deadline)) {\n const day = normalizeDate(input.deadline);\n if (!day) throw new Error(\"deadline must be a date, e.g. '2026-12-15'.\");\n deadline = day;\n fields.deadline = day;\n said.push('deadline ' + day);\n }\n if (typeof input.extendDays === 'number' && input.extendDays !== 0) {\n if (!deadline) throw new Error('There is no deadline to move yet; pass deadline (YYYY-MM-DD).');\n const moved = addDays(deadline, input.extendDays);\n said.push('deadline moved from ' + deadline + ' to ' + moved);\n fields.deadline = moved;\n }\n return { fields, said };\n}\n\nconst withinDays = typeof input.withinDays === 'number' && input.withinDays > 0 ? Math.round(input.withinDays) : 30;\nlet note = '';\n\nif (input.action === 'add') {\n const title = text(input.title) || text(input.opportunity);\n if (!title) throw new Error(\"add needs 'title', e.g. 'Small Press Grant'.\");\n const existing = (await opportunities.list()).find((o) => titleOf(o).toLowerCase() === title.toLowerCase());\n const { fields, said } = changes(existing ? String(existing.fields.deadline ?? '') || null : null);\n if (existing) {\n await opportunities.update(existing.id, { fields, ...(said.length ? { note: said.join('; ') } : {}) });\n note = 'Updated ' + existing.id + ' ' + titleOf(existing) + (said.length ? ': ' + said.join(', ') : '') + '.';\n } else {\n const record = await opportunities.add({ status: 'prospect', fields: { title, kind: 'grant', ...fields } });\n note = 'Added ' + record.id + ' ' + title + (fields.deadline ? ', due ' + String(fields.deadline) : '') + '.';\n }\n} else if (input.action === 'update') {\n const wanted = text(input.opportunity) || text(input.title);\n if (!wanted) throw new Error(\"update needs 'opportunity' (its id or title).\");\n const op = await findOpportunity(wanted);\n const { fields, said } = changes(String(op.fields.deadline ?? '') || null);\n if (!Object.keys(fields).length) {\n throw new Error('Nothing to change: pass deadline, extendDays, ask, fit, funder, kind, url or note.');\n }\n await opportunities.update(op.id, { fields, ...(said.length ? { note: said.join('; ') } : {}) });\n note = 'Updated ' + op.id + ' ' + titleOf(op) + (said.length ? ': ' + said.join(', ') : '') + '.';\n} else if (input.action === 'stage') {\n const stage = normalizeStage(input.stage);\n if (!stage) throw new Error(\"stage must be 'prospect', 'drafting', 'submitted', or 'passed'.\");\n const wanted = text(input.opportunity) || text(input.title);\n if (!wanted) throw new Error(\"stage needs 'opportunity' (its id or title).\");\n const op = await findOpportunity(wanted);\n if (op.status !== stage) await opportunities.transition(op.id, stage, text(input.note) ? { note: text(input.note) } : {});\n const ready = readiness(op, await requirements.list());\n if (stage === 'submitted') {\n await opportunities.update(op.id, { fields: { submittedAt: localDay(Date.now()) } });\n note =\n titleOf(op) + ' is submitted.' +\n (ready.open.length ? ' ' + ready.open.length + ' requirement' + (ready.open.length === 1 ? ' was' : 's were') + ' still open: ' + ready.open.map(titleOf).join(', ') + '.' : '');\n } else {\n note = titleOf(op) + (stage === 'passed' ? ' is passed on.' : ' is now ' + stage + '.');\n }\n} else if (input.action === 'outcome') {\n const outcome = normalizeOutcome(input.outcome);\n if (!outcome) throw new Error(\"outcome must be 'awarded', 'declined', or 'passed'.\");\n const wanted = text(input.opportunity) || text(input.title);\n if (!wanted) throw new Error(\"outcome needs 'opportunity' (its id or title).\");\n const op = await findOpportunity(wanted);\n const fields: Record<string, unknown> = { decidedAt: localDay(Date.now()) };\n if (outcome === 'awarded' && typeof input.award === 'number') {\n const cents = toCents(input.award);\n if (cents === null) throw new Error('award must be an amount in dollars, e.g. 6000.');\n fields.awardCents = cents;\n }\n if (text(input.note)) fields.outcomeNote = text(input.note);\n await opportunities.update(op.id, { fields });\n if (op.status !== outcome) await opportunities.transition(op.id, outcome, text(input.note) ? { note: text(input.note) } : {});\n note =\n titleOf(op) + (outcome === 'awarded' ? ' was awarded' + (typeof fields.awardCents === 'number' ? ' ' + money(fields.awardCents as number) : '') : outcome === 'declined' ? ' was declined' : ' is passed on') +\n (outcome === 'awarded' && typeof op.fields.askCents === 'number' ? ' (asked ' + money(op.fields.askCents as number) + ')' : '') + '.';\n} else if (input.action === 'add_requirement') {\n const wanted = text(input.opportunity);\n if (!wanted) throw new Error(\"add_requirement needs 'opportunity' (its id or title) and 'title'.\");\n const op = await findOpportunity(wanted);\n const titles = requirementTitles(text(input.title), input.titles);\n if (!titles.length) throw new Error(\"add_requirement needs 'title', e.g. 'Budget narrative'.\");\n const mine = requirementsFor(op, await requirements.list());\n const added: string[] = [];\n const kept: string[] = [];\n for (const title of titles) {\n const existing = mine.find((r) => titleOf(r).toLowerCase() === title.toLowerCase());\n if (existing) {\n if (text(input.owner)) await requirements.update(existing.id, { fields: { owner: text(input.owner) } });\n kept.push(titleOf(existing));\n continue;\n }\n const record = await requirements.add({\n status: 'todo',\n fields: { opportunityId: op.id, opportunity: titleOf(op), title, ...(text(input.owner) ? { owner: text(input.owner) } : {}) },\n });\n added.push(record.id + ' ' + title);\n }\n note =\n (added.length ? 'Added to ' + titleOf(op) + ': ' + added.join(', ') + '.' : '') +\n (kept.length ? (added.length ? ' ' : '') + 'Already on its list: ' + kept.join(', ') + '.' : '');\n} else if (input.action === 'check_requirement') {\n const wanted = text(input.requirement) || text(input.title);\n if (!wanted) throw new Error(\"check_requirement needs 'requirement' (its id or title).\");\n let pool = await requirements.list();\n const all = pool;\n if (text(input.opportunity)) {\n const op = await findOpportunity(text(input.opportunity));\n pool = pool.filter((r) => r.fields.opportunityId === op.id);\n }\n const done = input.done !== false;\n const req = pickPreferring(\n pool.filter((r) => (done ? r.status !== 'done' : r.status === 'done')),\n pool.length ? pool : all,\n wanted,\n 'requirement',\n );\n const target = done ? 'done' : 'todo';\n if (req.status !== target) await requirements.transition(req.id, target, text(input.note) ? { note: text(input.note) } : {});\n const op = (await opportunities.list()).find((o) => o.id === req.fields.opportunityId);\n const ready = op ? readiness(op, await requirements.list()) : null;\n note =\n (done ? 'Done: ' : 'Reopened: ') + titleOf(req) + (op ? ' for ' + titleOf(op) : '') +\n (ready ? ' (' + ready.done + ' of ' + ready.total + ' requirements done).' : '.');\n} else if (input.action !== 'status') {\n throw new Error(\"Unknown action '\" + input.action + \"'. Use status, add, update, stage, outcome, add_requirement, or check_requirement.\");\n}\n\nconst view = picture(await opportunities.list(), await requirements.list(), Date.now(), withinDays);\nawait remindNextDeadline();\n\ngezel.output({\n open: view.open,\n dueSoon: view.dueSoon,\n awaiting: view.awaiting,\n awarded: view.awardedCents / 100,\n summary: (note ? note + ' ' : '') + view.summary,\n});\n"},"tools":[{"name":"grants_status","description":"The whole pipeline: every open opportunity by deadline, soonest first (missed ones included), each with its funder, fit, ask, stage and the requirements still to do (with ids); what is submitted and awaiting a decision; and the outcomes so far. Call it first when asked what's due or where things stand.","script":"grants-store","inputs":{"type":"object","properties":{"withinDays":{"type":"number"}}},"bind":{"action":"status"},"state":true},{"name":"add_opportunity","description":"Save a funding opportunity or request for proposals: its title, funder, kind, deadline (YYYY-MM-DD), the ask in dollars, and how well it fits. An existing title is updated, never duplicated. Call it as soon as one is mentioned, before you describe it.","script":"grants-store","inputs":{"type":"object","properties":{"title":{"type":"string","description":"e.g. 'Small Press Grant'"},"funder":{"type":"string"},"kind":{"type":"string","enum":["grant","rfp","fellowship","sponsorship","other"]},"deadline":{"type":"string","description":"YYYY-MM-DD"},"ask":{"type":"number","description":"The amount requested, in dollars."},"fit":{"type":"string","enum":["strong","good","long shot"]},"url":{"type":"string"},"note":{"type":"string"}},"required":["title"]},"bind":{"action":"add"}},{"name":"update_opportunity","description":"Change an opportunity already on the list. When the funder moves the deadline by some days or weeks ('extended by two weeks'), pass extendDays (14) and the desk moves it; pass deadline only when they give the new date. Never work the date out yourself. Call it the moment they tell you, before you reply.","script":"grants-store","inputs":{"type":"object","properties":{"opportunity":{"type":"string","description":"The opportunity's id (e.g. 'op-2') or title."},"extendDays":{"type":"number","description":"How many days later the deadline moved, e.g. 14 for two weeks."},"deadline":{"type":"string","description":"A new deadline, YYYY-MM-DD, only when they give the date."},"ask":{"type":"number","description":"A new amount requested, in dollars."},"fit":{"type":"string","enum":["strong","good","long shot"]},"funder":{"type":"string"},"kind":{"type":"string","enum":["grant","rfp","fellowship","sponsorship","other"]},"url":{"type":"string"},"note":{"type":"string"}},"required":["opportunity"]},"bind":{"action":"update"}},{"name":"set_stage","description":"Move an opportunity to prospect, drafting, submitted (the moment it is sent, with any confirmation number as the note) or passed (decided not to apply). Call it as soon as the person says it moved.","script":"grants-store","inputs":{"type":"object","properties":{"opportunity":{"type":"string","description":"The opportunity's id (e.g. 'op-2') or title."},"stage":{"type":"string","enum":["prospect","drafting","submitted","passed"]},"note":{"type":"string","description":"Any confirmation number, exactly as given."}},"required":["opportunity","stage"]},"bind":{"action":"stage"}},{"name":"record_outcome","description":"Record the funder's decision the moment it comes in: awarded (with the amount in dollars), declined, or passed. Put reporting dates or feedback in the note.","script":"grants-store","inputs":{"type":"object","properties":{"opportunity":{"type":"string","description":"The opportunity's id (e.g. 'op-2') or title."},"outcome":{"type":"string","enum":["awarded","declined","passed"]},"award":{"type":"number","description":"The amount awarded, in dollars."},"note":{"type":"string","description":"Reporting dates, feedback or conditions, in their words."}},"required":["opportunity","outcome"]},"bind":{"action":"outcome"}},{"name":"add_requirement","description":"Add what a submission needs to its checklist (a budget narrative, work samples, a board list, letters of support): one as title, or several as titles. Existing items are kept, never duplicated. Call it as soon as the guidelines are read or the person lists them.","script":"grants-store","inputs":{"type":"object","properties":{"opportunity":{"type":"string","description":"The opportunity's id (e.g. 'op-2') or title."},"title":{"type":"string","description":"One thing the submission needs, e.g. 'Budget narrative'."},"titles":{"type":"array","items":{"type":"string"},"description":"Several requirements at once."},"owner":{"type":"string","description":"Who is preparing it."}},"required":["opportunity"]},"bind":{"action":"add_requirement"}},{"name":"check_requirement","description":"Check a requirement off the moment the person says it is ready (done: false reopens it).","script":"grants-store","inputs":{"type":"object","properties":{"requirement":{"type":"string","description":"The requirement's id (e.g. 'req-4') or title."},"opportunity":{"type":"string","description":"The opportunity's id (e.g. 'op-2') or title."},"done":{"type":"boolean","description":"false reopens it."},"note":{"type":"string"}},"required":["requirement"]},"bind":{"action":"check_requirement"}},{"name":"page_add_opportunity","description":"Add or update an opportunity.","script":"grants-store","inputs":{"type":"object","properties":{"title":{"type":"string","description":"e.g. 'Small Press Grant'"},"funder":{"type":"string"},"kind":{"type":"string","enum":["grant","rfp","fellowship","sponsorship","other"]},"deadline":{"type":"string","description":"YYYY-MM-DD"},"ask":{"type":"number","description":"The amount requested, in dollars."},"fit":{"type":"string","enum":["strong","good","long shot"]},"url":{"type":"string"},"note":{"type":"string"}},"required":["title"]},"bind":{"action":"add"}},{"name":"page_add_requirement","description":"Add a requirement to a submission.","script":"grants-store","inputs":{"type":"object","properties":{"opportunity":{"type":"string","description":"The opportunity's id (e.g. 'op-2') or title."},"title":{"type":"string","description":"One thing the submission needs, e.g. 'Budget narrative'."},"titles":{"type":"array","items":{"type":"string"},"description":"Several requirements at once."},"owner":{"type":"string","description":"Who is preparing it."}},"required":["opportunity"]},"bind":{"action":"add_requirement"}},{"name":"page_check_requirement","description":"Check a requirement off, or reopen it.","script":"grants-store","inputs":{"type":"object","properties":{"requirement":{"type":"string","description":"The requirement's id (e.g. 'req-4') or title."},"opportunity":{"type":"string","description":"The opportunity's id (e.g. 'op-2') or title."},"done":{"type":"boolean","description":"false reopens it."},"note":{"type":"string"}},"required":["requirement"]},"bind":{"action":"check_requirement"}},{"name":"page_set_stage","description":"Move an opportunity to another stage.","script":"grants-store","inputs":{"type":"object","properties":{"opportunity":{"type":"string","description":"The opportunity's id (e.g. 'op-2') or title."},"stage":{"type":"string","enum":["prospect","drafting","submitted","passed"]},"note":{"type":"string","description":"Any confirmation number, exactly as given."}},"required":["opportunity","stage"]},"bind":{"action":"stage"},"reaction":{"gezel":"aanjager","prompt":"The person just moved an opportunity on the grants page. The pipeline now reads (its first sentence is what changed):\n{{output.summary}}\nIn two short sentences, confirm the move (if it was submitted, note any requirement that was still open), and name the next deadline to work on. Do not call tools.","hideSeed":true}},{"name":"page_record_outcome","description":"Record the funder's decision.","script":"grants-store","inputs":{"type":"object","properties":{"opportunity":{"type":"string","description":"The opportunity's id (e.g. 'op-2') or title."},"outcome":{"type":"string","enum":["awarded","declined","passed"]},"award":{"type":"number","description":"The amount awarded, in dollars."},"note":{"type":"string","description":"Reporting dates, feedback or conditions, in their words."}},"required":["opportunity","outcome"]},"bind":{"action":"outcome"},"reaction":{"gezel":"aanjager","prompt":"The person just recorded a funder's decision on the grants page. The pipeline now reads (its first sentence is what changed):\n{{output.summary}}\nIn two short sentences, respond to the decision: for an award, suggest the thank-you and noting the reporting dates; for a decline, suggest asking the program officer for feedback. Then name the next deadline. Do not call tools.","hideSeed":true}}],"pages":{"entry":"grants/index.html","api":1,"reads":[{"source":"workspace","path":"opportunities.json"},{"source":"workspace","path":"requirements.json"}],"tools":["page_add_opportunity","page_add_requirement","page_check_requirement","page_set_stage","page_record_outcome"]},"schedules":[],"workspaceSeed":["opportunities.json","requirements.json"],"artifactsSeed":[],"availableVersions":["1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"hiring-desk","name":"Hiring Desk","description":"Run a hiring round from the job post to the signed offer. A recruiter keeps each open role’s pipeline, books interviews, gathers scorecards tied to the role’s requirements, and drafts the interview kit and the offer, while you make every decision.","tags":["hiring","recruiting","candidates","scorecards","job-descriptions","small-business"],"category":"business","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.0.0","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"business":{"type":"string","title":"What kind of business is hiring?","description":"e.g. 'a café in Portland', 'a six-person design studio'.","default":"the business"}},"required":["business"]},"nameTemplate":"Hiring Desk","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"recruiter","voorman":true},{"templateId":"mock-interviewer","voorman":false}],"toolsets":[],"craftbooks":["structured-interview-kit","contract-template"],"scripts":{"hiring-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { logStore, rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'hiring-store',\n description:\n \"Read and update the hiring desk: roles.json (open roles and their requirements), candidates.json (each candidate's stage) and feedback.json (interview scorecards and notes). action:'status' for every pipeline, the interviews coming up and the scorecards still missing; 'add_role' to open or update a role; 'add_candidate' to add a candidate (an existing name in that role is updated, never duplicated); 'move' to change a stage or book an interview; 'feedback' to record a scorecard; 'list' for every candidate.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'status', 'add_role', 'add_candidate', 'move', 'feedback', or 'list'.\",\n required: true,\n },\n title: { type: 'string', description: \"For add_role: the role's title, e.g. 'Barista'.\" },\n requirements: {\n type: 'string',\n description: \"For add_role: the job-related requirements interviewers rate, separated by commas, e.g. 'Coffee and milk skills, Warm customer service'.\",\n },\n openings: { type: 'number', description: 'For add_role: how many people the role will hire.' },\n manager: { type: 'string', description: 'For add_role: the hiring manager.' },\n pay: { type: 'string', description: \"For add_role: pay as the business states it, e.g. '$19-21 an hour plus tips'.\" },\n roleStatus: { type: 'string', description: 'For add_role: open, paused, filled, or closed.' },\n role: { type: 'string', description: \"Role id (e.g. 'role-1') or title.\" },\n candidate: {\n type: 'string',\n description: \"Candidate id (e.g. 'cand-3') or name; a first name is enough when it is unique.\",\n },\n name: { type: 'string', description: \"For add_candidate: the candidate's full name.\" },\n source: { type: 'string', description: 'For add_candidate: where they came from, e.g. referral or job board.' },\n status: { type: 'string', description: 'The stage: sourced, screen, interview, offer, hired, or closed.' },\n interviewOn: {\n type: 'string',\n description: \"The interview date, YYYY-MM-DD or a weekday such as 'thursday'.\",\n },\n interviewTime: { type: 'string', description: \"The interview time as said, e.g. '2:30 pm'.\" },\n interviewer: { type: 'string', description: 'Who will interview.' },\n by: { type: 'string', description: 'For feedback: who did the interview.' },\n ratings: {\n type: 'string',\n description: \"For feedback: 1 to 4 per requirement, e.g. 'Coffee and milk skills 3, Warm customer service 4'.\",\n },\n note: { type: 'string', description: 'What happened, in job-related terms.' },\n withinDays: { type: 'number', description: 'How many days ahead count as coming up (default 7).' },\n },\n outputs: {\n openRoles: { type: 'number', description: 'Roles open or paused.' },\n inPipeline: { type: 'number', description: 'Candidates not yet hired or closed.' },\n interviewsSoon: { type: 'number', description: 'Interviews booked within the window.' },\n summary: { type: 'string', description: 'What changed, then the desk picture or the listing.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── hiring-rules-start ──\n// Pure derivations: dates in local calendar days, record matching, the\n// protected-characteristics guard, scorecard parsing and the desk picture the\n// crew reads. Kept self-contained between these sentinels so tests execute the\n// shipped bytes.\nvar DAY_MS = 86400000;\nvar WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\nvar MONTH_KEYS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];\n\nfunction pad(n) {\n return n < 10 ? '0' + n : String(n);\n}\nfunction localDay(ms) {\n var d = new Date(ms);\n return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());\n}\nfunction noon(day) {\n return new Date(String(day).slice(0, 10) + 'T12:00:00');\n}\nfunction addDays(day, n) {\n var d = noon(day);\n d.setDate(d.getDate() + n);\n return localDay(d.getTime());\n}\nfunction addMonths(day, months) {\n var d = noon(day);\n var date = d.getDate();\n d.setDate(1);\n d.setMonth(d.getMonth() + months);\n // The 31st rolls to the last day of a shorter month, not into the next one.\n d.setDate(Math.min(date, new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate()));\n return localDay(d.getTime());\n}\nfunction daysLeft(day, nowMs) {\n var due = Date.parse(String(day).slice(0, 10) + 'T00:00:00');\n var today = Date.parse(localDay(nowMs) + 'T00:00:00');\n return Math.round((due - today) / DAY_MS);\n}\nfunction dayName(day) {\n return WEEKDAYS[noon(day).getDay()];\n}\nfunction parseDay(text, nowMs, direction) {\n var raw = String(text == null ? '' : text).trim().toLowerCase().replace(/[.,]/g, ' ').replace(/\\s+/g, ' ').trim();\n if (!raw) return null;\n var iso = raw.match(/^(\\d{4})-(\\d{1,2})-(\\d{1,2})(?:t.*)?$/);\n if (iso) return iso[1] + '-' + pad(Number(iso[2])) + '-' + pad(Number(iso[3]));\n var today = localDay(nowMs);\n if (raw === 'today' || raw === 'now') return today;\n if (raw === 'tomorrow') return addDays(today, 1);\n if (raw === 'yesterday') return addDays(today, -1);\n var rel = raw.match(/^(?:in )?(\\d{1,3}) (day|days|week|weeks)( ago| from now)?$/);\n if (rel) {\n var n = Number(rel[1]) * (rel[2].charAt(0) === 'w' ? 7 : 1);\n return addDays(today, rel[3] === ' ago' ? -n : n);\n }\n var wd = raw.match(/^(this |next |last |on |coming )?(sun|mon|tue|wed|thu|fri|sat)[a-z]*$/);\n if (wd) {\n var target = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].indexOf(wd[2]);\n var now = noon(today).getDay();\n if (direction === 'past' || wd[1] === 'last ') {\n var back = (now - target + 7) % 7;\n return addDays(today, -(wd[1] === 'last ' && back === 0 ? 7 : back));\n }\n if (wd[1] === 'this ') return addDays(today, (target - now + 7) % 7);\n return addDays(today, ((target - now + 6) % 7) + 1);\n }\n var md = raw.match(/^(?:[a-z]+day )?([a-z]{3,9}) (\\d{1,2})(?:st|nd|rd|th)?(?: (\\d{4}))?$/);\n var dm = raw.match(/^(?:[a-z]+day )?(\\d{1,2})(?:st|nd|rd|th)? (?:of )?([a-z]{3,9})(?: (\\d{4}))?$/);\n var parts = md ? { month: md[1], date: md[2], year: md[3] } : dm ? { month: dm[2], date: dm[1], year: dm[3] } : null;\n if (parts) {\n var m = MONTH_KEYS.indexOf(parts.month.slice(0, 3));\n if (m < 0) return null;\n var date = Number(parts.date);\n if (date < 1 || date > 31) return null;\n if (parts.year) return parts.year + '-' + pad(m + 1) + '-' + pad(date);\n var year = noon(today).getFullYear();\n var guess = year + '-' + pad(m + 1) + '-' + pad(date);\n var d = daysLeft(guess, nowMs);\n if (direction === 'past' && d > 0) guess = year - 1 + guess.slice(4);\n if (direction !== 'past' && d < 0) guess = year + 1 + guess.slice(4);\n return guess;\n }\n return null;\n}\nfunction matches(records, text, labelOf) {\n var wanted = String(text == null ? '' : text).trim().toLowerCase().replace(/['\\u2019]s\\b/g, '').replace(/\\s+/g, ' ');\n if (!wanted) return [];\n var tiers = [\n function (r) { return String(r.id).toLowerCase() === wanted; },\n function (r) { return labelOf(r).toLowerCase() === wanted; },\n function (r) { return labelOf(r).toLowerCase().indexOf(wanted) === 0; },\n function (r) { return (' ' + labelOf(r).toLowerCase() + ' ').indexOf(' ' + wanted + ' ') >= 0; },\n function (r) { return labelOf(r).toLowerCase().indexOf(wanted) >= 0; },\n function (r) { var l = labelOf(r).toLowerCase(); return l.length >= 3 && wanted.indexOf(l) >= 0; },\n ];\n for (var i = 0; i < tiers.length; i++) {\n var hit = records.filter(tiers[i]);\n if (hit.length) return hit;\n }\n return [];\n}\nfunction describe(records, labelOf) {\n return records.map(function (r) { return r.id + ' ' + labelOf(r); }).join(', ');\n}\nfunction splitList(text) {\n var raw = String(text == null ? '' : text).trim();\n if (/^\\[/.test(raw)) {\n try {\n var parsed = JSON.parse(raw);\n if (Array.isArray(parsed)) return parsed.map(function (s) { return String(s).trim(); }).filter(Boolean);\n } catch (e) {\n // Not JSON after all; split it as text.\n }\n }\n return raw\n .split(/\\s*[,;\\n]+\\s*/)\n .map(function (s) { return s.replace(/^(and|or|plus)\\s+/i, '').replace(/[.\\s]+$/, '').trim(); })\n .filter(Boolean);\n}\nvar STAGES = ['sourced', 'screen', 'interview', 'offer', 'hired', 'closed'];\nvar ROLE_STATUSES = ['open', 'paused', 'filled', 'closed'];\nvar STAGE_WORDS = {\n sourcing: 'sourced', new: 'sourced', applied: 'sourced', screening: 'screen', 'phone screen': 'screen',\n interviewing: 'interview', interviews: 'interview', offered: 'offer', 'offer out': 'offer', hire: 'hired',\n rejected: 'closed', reject: 'closed', declined: 'closed', withdrew: 'closed', withdrawn: 'closed',\n 'not moving forward': 'closed', close: 'closed',\n};\n// A requirement or a rating may never name a protected characteristic.\nvar PROTECTED = /\\b(age|aged|ages|young|younger|youthful|older|elderly|race|racial|ethnic|ethnicity|skin colou?r|religion|religious|gender|sex|sexual orientation|male|female|pregnant|pregnancy|maternity|disabled|disability|disabilities|national origin|nationality|native speaker|marital|married|genetic|veteran status)\\b/i;\nvar STOP = ['and', 'the', 'with', 'for', 'skill', 'skills', 'good', 'great', 'strong', 'very', 'their'];\n\nfunction protectedTerm(text) {\n var m = String(text == null ? '' : text).match(PROTECTED);\n return m ? m[1].toLowerCase() : null;\n}\nfunction protectedMessage(term) {\n return (\n \"Hiring Desk never rates or screens on '\" + term + \"'. Requirements and ratings cover the job only \" +\n '(skills, experience, availability, how someone works); age, race, religion, sex, pregnancy, disability, ' +\n 'national origin and other protected traits stay out of hiring.'\n );\n}\nfunction stageOf(text) {\n var raw = String(text == null ? '' : text).trim().toLowerCase();\n return STAGE_WORDS[raw] || raw;\n}\nfunction words(text) {\n return (String(text == null ? '' : text).toLowerCase().match(/[a-z0-9]+/g) || [])\n .filter(function (w) { return w.length >= 3 && STOP.indexOf(w) < 0; })\n .map(function (w) { return w.length > 4 ? w.replace(/ies$/, 'y').replace(/s$/, '') : w; });\n}\nfunction matchRequirement(label, requirements) {\n var want = words(label);\n var best = null;\n var score = 0;\n (requirements || []).forEach(function (req) {\n var have = words(req);\n var hits = want.filter(function (w) {\n return have.some(function (h) { return h === w || (w.length >= 4 && h.indexOf(w) === 0) || (h.length >= 4 && w.indexOf(h) === 0); });\n }).length;\n if (hits > score) {\n best = req;\n score = hits;\n }\n });\n return best;\n}\nfunction parseRatings(text, requirements) {\n var out = { ratings: {}, unmatched: [], problems: [] };\n var re = /([a-z][a-z '&\\/-]*?)\\s*[:=(-]?\\s*(\\d+(?:\\.\\d+)?)\\s*(?:\\/\\s*\\d+|out of \\d+)?\\)?/gi;\n var m;\n while ((m = re.exec(String(text == null ? '' : text)))) {\n var label = m[1].replace(/^\\s*(and|plus|also|then)\\s+/i, '').replace(/\\s+(is|was|got|scored|a|an)$/i, '').trim();\n if (!label) continue;\n var term = protectedTerm(label);\n if (term) throw new Error(protectedMessage(term));\n var score = Number(m[2]);\n if (!(score >= 1 && score <= 4) || Math.round(score) !== score) {\n out.problems.push(label + ' ' + m[2] + ' is not a whole rating from 1 to 4');\n continue;\n }\n var req = matchRequirement(label, requirements);\n var key = req || label.charAt(0).toUpperCase() + label.slice(1);\n if (!req && out.unmatched.indexOf(key) < 0) out.unmatched.push(key);\n out.ratings[key] = score;\n }\n return out;\n}\nfunction cardsFor(candidate, events) {\n return events.filter(function (e) { return e.kind === 'scorecard' && e.data && e.data.candidateId === candidate.id; });\n}\nfunction averages(candidate, events) {\n var sums = {};\n cardsFor(candidate, events).forEach(function (e) {\n Object.keys(e.data.ratings || {}).forEach(function (k) {\n sums[k] = sums[k] || { total: 0, count: 0 };\n sums[k].total += Number(e.data.ratings[k]);\n sums[k].count += 1;\n });\n });\n var out = {};\n Object.keys(sums).forEach(function (k) { out[k] = Math.round((sums[k].total / sums[k].count) * 10) / 10; });\n return out;\n}\nfunction interviewText(c) {\n var f = c.fields || {};\n return f.interviewAt\n ? dayName(f.interviewAt) + ' ' + f.interviewAt + (f.interviewTime ? ' at ' + f.interviewTime : '') + (f.interviewer ? ' with ' + f.interviewer : '')\n : 'no date booked';\n}\nfunction waitingOnCard(c, events, nowMs) {\n var f = c.fields || {};\n if (c.status !== 'interview' || !f.interviewAt || daysLeft(f.interviewAt, nowMs) >= 0) return false;\n return !cardsFor(c, events).some(function (e) { return String(e.at).slice(0, 10) >= String(f.interviewAt); });\n}\nfunction candidateLine(c, events) {\n var f = c.fields || {};\n var avg = averages(c, events);\n var keys = Object.keys(avg);\n return (\n f.name + ' (' + c.id + ')' +\n (c.status === 'interview' ? ', interview ' + interviewText(c) : '') +\n (keys.length ? ', ratings ' + keys.map(function (k) { return k + ' ' + avg[k]; }).join(', ') : '')\n );\n}\nfunction picture(roles, candidates, events, nowMs, withinDays) {\n var live = roles.filter(function (r) { return r.status === 'open' || r.status === 'paused'; });\n var active = candidates.filter(function (c) { return c.status !== 'hired' && c.status !== 'closed'; });\n var titleOf = function (c) {\n var r = roles.filter(function (x) { return x.id === c.fields.roleId; })[0];\n return r ? r.fields.title : c.fields.roleTitle || 'a role';\n };\n var byDay = function (a, b) { return String(a.fields.interviewAt).localeCompare(String(b.fields.interviewAt)); };\n var soon = active\n .filter(function (c) {\n if (c.status !== 'interview' || !c.fields.interviewAt) return false;\n var d = daysLeft(c.fields.interviewAt, nowMs);\n return d >= 0 && d <= withinDays;\n })\n .sort(byDay);\n var waiting = active.filter(function (c) { return waitingOnCard(c, events, nowMs); }).sort(byDay);\n var parts = [];\n // The interview list comes first and whole: \"who's interviewing this week\" is answered from it alone.\n parts.push(\n soon.length\n ? 'Interviews in the next ' + withinDays + ' days: ' + soon.map(function (c) { return c.fields.name + ' (' + c.id + ') for ' + titleOf(c) + ' on ' + interviewText(c); }).join('; ') + '.'\n : 'No interviews booked in the next ' + withinDays + ' days.',\n );\n if (waiting.length) {\n parts.push('Interviewed but no scorecard yet: ' + waiting.map(function (c) { return c.fields.name + ' (' + c.id + ', ' + titleOf(c) + ', interviewed ' + c.fields.interviewAt + ')'; }).join('; ') + '.');\n }\n parts.push(live.length ? live.length + (live.length === 1 ? ' open role' : ' open roles') + ', ' + active.length + ' candidates in play.' : 'No open roles.');\n live.forEach(function (r) {\n var mine = candidates.filter(function (c) { return c.fields.roleId === r.id; });\n var hired = mine.filter(function (c) { return c.status === 'hired'; }).length;\n var stages = STAGES.slice(0, 4).map(function (s) {\n var list = mine.filter(function (c) { return c.status === s; });\n return s + ': ' + (list.length ? list.map(function (c) { return candidateLine(c, events); }).join('; ') : 'none');\n });\n parts.push(\n r.fields.title + ' (' + r.id + (r.status === 'paused' ? ', paused' : '') + ', ' + hired + ' of ' + (r.fields.openings || 1) + ' hired' +\n (r.fields.manager ? ', manager ' + r.fields.manager : '') +\n '; requirements: ' + ((r.fields.requirements || []).join(', ') || 'none written yet') + ') ' + stages.join(' | ') + '.',\n );\n });\n return { openRoles: live.length, inPipeline: active.length, interviewsSoon: soon.length, summary: parts.join(' ') };\n}\n// ── hiring-rules-end ──\n\nconst roles = rosterStore(gezel.fs, 'roles.json', { stages: ['open', 'paused', 'filled', 'closed'], idPrefix: 'role' });\nconst candidates = rosterStore(gezel.fs, 'candidates.json', {\n stages: ['sourced', 'screen', 'interview', 'offer', 'hired', 'closed'],\n idPrefix: 'cand',\n});\nconst feedback = logStore(gezel.fs, 'feedback.json');\nconst now = Date.now();\nconst roleTitle = (r: { fields: Record<string, unknown> }) => String(r.fields.title ?? '');\nconst candName = (r: { fields: Record<string, unknown> }) => String(r.fields.name ?? '');\n\nasync function resolveRole(text?: string) {\n const all = await roles.list();\n if (!text) {\n const open = all.filter((r) => r.status === 'open');\n if (open.length === 1) return open[0]!;\n throw new Error(\"Pass 'role' (id or title). Roles: \" + (describe(all, roleTitle) || 'none yet; open one with add_role') + '.');\n }\n const hits = matches(all, text, roleTitle);\n if (hits.length === 1) return hits[0]!;\n if (hits.length > 1) throw new Error(\"More than one role matches '\" + text + \"': \" + describe(hits, roleTitle) + '. Pass the id.');\n throw new Error(\"No role matches '\" + text + \"'. Roles: \" + (describe(all, roleTitle) || 'none yet; open one with add_role') + '.');\n}\n\nasync function resolveCandidate(text?: string) {\n if (!text) throw new Error(\"Pass 'candidate': an id like 'cand-3' or a name. Call list_candidates to see them.\");\n const all = await candidates.list();\n const active = all.filter((c) => c.status !== 'hired' && c.status !== 'closed');\n let hits = matches(active, text, candName);\n if (!hits.length) hits = matches(all, text, candName);\n if (hits.length === 1) return hits[0]!;\n if (hits.length > 1) throw new Error(\"More than one candidate matches '\" + text + \"': \" + describe(hits, candName) + '. Pass the id.');\n throw new Error(\"No candidate matches '\" + text + \"'. Candidates: \" + (describe(all, candName) || 'none yet') + '.');\n}\n\nconst withinDays = typeof input.withinDays === 'number' && input.withinDays > 0 ? Math.round(input.withinDays) : 7;\nlet note = '';\n\nif (input.action === 'add_role') {\n if (!input.title || !input.title.trim()) throw new Error(\"add_role needs 'title'.\");\n const title = input.title.trim();\n const reqs = input.requirements === undefined ? [] : splitList(input.requirements);\n for (const text of [title, ...reqs]) {\n const term = protectedTerm(text);\n if (term) throw new Error(protectedMessage(term));\n }\n let openings: number | undefined;\n if (input.openings !== undefined) {\n openings = Math.round(Number(input.openings));\n if (!(openings >= 1)) throw new Error(\"openings must be 1 or more.\");\n }\n const roleStatus = input.roleStatus ? String(input.roleStatus).trim().toLowerCase() : '';\n if (roleStatus && !ROLE_STATUSES.includes(roleStatus)) throw new Error(\"roleStatus must be open, paused, filled, or closed.\");\n const fields: Record<string, unknown> = {\n ...(reqs.length ? { requirements: reqs } : {}),\n ...(openings ? { openings } : {}),\n ...(input.manager ? { manager: input.manager.trim() } : {}),\n ...(input.pay ? { pay: input.pay.trim() } : {}),\n ...(input.note ? { notes: input.note.trim() } : {}),\n };\n const existing = (await roles.list()).find((r) => roleTitle(r).toLowerCase() === title.toLowerCase());\n if (existing) {\n await roles.update(existing.id, { fields });\n if (roleStatus && roleStatus !== existing.status) await roles.transition(existing.id, roleStatus);\n note = 'Updated the ' + roleTitle(existing) + ' role (' + existing.id + ').';\n } else {\n const record = await roles.add({\n status: roleStatus || 'open',\n fields: { title, requirements: [], openings: 1, openedAt: localDay(now), ...fields },\n });\n note = 'Opened ' + title + ' (' + record.id + ')' + (reqs.length ? ' with ' + reqs.length + ' requirements.' : '; add its job-related requirements next.');\n }\n} else if (input.action === 'add_candidate') {\n if (!input.name || !input.name.trim()) throw new Error(\"add_candidate needs 'name'.\");\n const name = input.name.trim();\n const role = await resolveRole(input.role);\n const interviewAt = input.interviewOn ? parseDay(input.interviewOn, now, 'future') : null;\n if (input.interviewOn && !interviewAt) throw new Error(\"interviewOn must be a date like '2026-11-12' or a weekday like 'thursday'.\");\n // A booked interview puts a new candidate straight at the interview stage.\n const stage = input.status ? stageOf(input.status) : interviewAt ? 'interview' : '';\n if (stage && !STAGES.includes(stage)) throw new Error('status must be one of ' + STAGES.join(', ') + '.');\n const fields: Record<string, unknown> = {\n ...(input.source ? { source: input.source.trim() } : {}),\n ...(input.note ? { notes: input.note.trim() } : {}),\n ...(interviewAt ? { interviewAt } : {}),\n ...(input.interviewTime ? { interviewTime: input.interviewTime.trim() } : {}),\n ...(input.interviewer ? { interviewer: input.interviewer.trim() } : {}),\n };\n const existing = (await candidates.list()).find((c) => candName(c).toLowerCase() === name.toLowerCase() && c.fields.roleId === role.id);\n let id = '';\n if (existing) {\n id = existing.id;\n await candidates.update(existing.id, { fields, ...(input.note ? { note: input.note } : {}) });\n if (stage && stage !== existing.status) await candidates.transition(existing.id, stage);\n note = 'Updated ' + name + ' (' + existing.id + ') for ' + roleTitle(role) + '.';\n } else {\n const record = await candidates.add({\n status: stage || 'sourced',\n fields: { name, roleId: role.id, roleTitle: roleTitle(role), ...fields },\n ...(input.note ? { note: input.note } : {}),\n });\n id = record.id;\n note = 'Added ' + name + ' (' + record.id + ') to ' + roleTitle(role) + ' at ' + record.status + '.';\n }\n if (interviewAt) {\n const after = (await candidates.get(id))!;\n await feedback.append({ kind: 'booked', note: 'Interview booked for ' + interviewText(after) + '.', data: { candidateId: id, roleId: role.id, on: interviewAt } });\n note += ' Interview ' + interviewText(after) + '.';\n }\n} else if (input.action === 'move') {\n const cand = await resolveCandidate(input.candidate ?? input.name);\n let to = input.status ? stageOf(input.status) : '';\n const interviewAt = input.interviewOn ? parseDay(input.interviewOn, now, 'future') : null;\n if (input.interviewOn && !interviewAt) throw new Error(\"interviewOn must be a date like '2026-11-12' or a weekday like 'thursday'.\");\n if (!to && interviewAt) to = 'interview';\n if (!to) throw new Error(\"move needs 'status' (\" + STAGES.join(', ') + \") or 'interviewOn'.\");\n if (!STAGES.includes(to)) throw new Error('status must be one of ' + STAGES.join(', ') + '.');\n const fields: Record<string, unknown> = {\n ...(interviewAt ? { interviewAt } : {}),\n ...(input.interviewTime ? { interviewTime: input.interviewTime.trim() } : {}),\n ...(input.interviewer ? { interviewer: input.interviewer.trim() } : {}),\n };\n if (Object.keys(fields).length) await candidates.update(cand.id, { fields });\n if (to !== cand.status) await candidates.transition(cand.id, to, input.note ? { note: input.note } : {});\n else if (input.note) await candidates.update(cand.id, { note: input.note });\n const after = (await candidates.get(cand.id))!;\n if (interviewAt) {\n await feedback.append({\n kind: 'booked',\n note: 'Interview booked for ' + interviewText(after) + '.',\n data: { candidateId: cand.id, roleId: cand.fields.roleId, on: interviewAt },\n });\n }\n note = candName(cand) + (to !== cand.status ? ' moved from ' + cand.status + ' to ' + to : ' stays at ' + to) + (to === 'interview' ? ', interview ' + interviewText(after) : '') + '.';\n if (to === 'hired') {\n const role = await roles.get(String(cand.fields.roleId));\n if (role) {\n const hired = (await candidates.list()).filter((c) => c.fields.roleId === role.id && c.status === 'hired').length;\n const openings = Number(role.fields.openings) || 1;\n if (hired >= openings && role.status === 'open') {\n await roles.transition(role.id, 'filled', { note: hired + ' of ' + openings + ' hired' });\n note += ' ' + roleTitle(role) + ' is now filled.';\n } else {\n note += ' ' + roleTitle(role) + ': ' + hired + ' of ' + openings + ' hired.';\n }\n }\n }\n} else if (input.action === 'feedback') {\n const cand = await resolveCandidate(input.candidate ?? input.name);\n const role = await roles.get(String(cand.fields.roleId));\n const reqs = role && Array.isArray(role.fields.requirements) ? (role.fields.requirements as string[]) : [];\n const parsed = parseRatings(input.ratings, reqs);\n if (parsed.problems.length) throw new Error(parsed.problems.join('; ') + '. Rate each requirement from 1 (no evidence) to 4 (strong evidence).');\n const keys = Object.keys(parsed.ratings);\n if (!keys.length && !input.note && !input.ratings) throw new Error(\"feedback needs 'ratings' (e.g. '\" + (reqs[0] || 'Customer service') + \" 3') or a 'note'.\");\n const by = input.by && input.by.trim() ? input.by.trim() : 'an interviewer';\n const text = input.note ? input.note.trim() : !keys.length && input.ratings ? input.ratings.trim() : undefined;\n await feedback.append({\n kind: keys.length ? 'scorecard' : 'note',\n ...(text ? { note: text } : {}),\n data: {\n candidateId: cand.id,\n roleId: cand.fields.roleId,\n by,\n ...(keys.length ? { ratings: parsed.ratings } : {}),\n ...(parsed.unmatched.length ? { unmatched: parsed.unmatched } : {}),\n },\n });\n note = keys.length\n ? 'Scorecard from ' + by + ' for ' + candName(cand) + ': ' + keys.map((k) => k + ' ' + parsed.ratings[k]).join(', ') + '.'\n : 'Note from ' + by + ' on ' + candName(cand) + ' saved.';\n if (!keys.length && input.ratings) note += ' No ratings found in that text; rate each requirement 1 to 4, e.g. ' + (reqs[0] || 'Customer service') + ' 3.';\n if (parsed.unmatched.length) note += ' Not among the role’s requirements: ' + parsed.unmatched.join(', ') + '.';\n} else if (input.action !== 'status' && input.action !== 'list') {\n throw new Error(\"Unknown action '\" + input.action + \"'. Use status, add_role, add_candidate, move, feedback, or list.\");\n}\n\nconst allRoles = await roles.list();\nconst allCandidates = await candidates.list();\nconst events = await feedback.list();\nconst view = picture(allRoles, allCandidates, events, now, withinDays);\n\ngezel.output({\n openRoles: view.openRoles,\n inPipeline: view.inPipeline,\n interviewsSoon: view.interviewsSoon,\n summary:\n input.action === 'list'\n ? allCandidates\n .map((c) => {\n const role = allRoles.find((r) => r.id === c.fields.roleId);\n return '[' + c.status + '] ' + candidateLine(c, events) + ', ' + (role ? roleTitle(role) : String(c.fields.roleTitle ?? '')) + (c.fields.source ? ', from ' + String(c.fields.source) : '') + (c.fields.notes ? '; ' + String(c.fields.notes) : '');\n })\n .join('\\n') || 'No candidates yet.'\n : (note ? note + ' ' : '') + view.summary,\n});\n"},"tools":[{"name":"hiring_status","description":"The whole hiring desk: interviews coming up (with dates and interviewers), candidates interviewed but missing a scorecard, and every open role’s pipeline by stage with ids and average ratings. Call it first when asked who is interviewing, where a search stands, or how candidates compare.","script":"hiring-store","inputs":{"type":"object","properties":{"withinDays":{"type":"number"}}},"bind":{"action":"status"},"state":true},{"name":"add_role","description":"Open a role or update one: title, the job-related requirements interviewers will rate (comma-separated), openings, hiring manager and pay. An existing title is updated, never duplicated. Call it as soon as a role is mentioned, before you describe it. Requirements are about the job only, never age, family, religion, health, origin or any other protected trait.","script":"hiring-store","inputs":{"type":"object","properties":{"title":{"type":"string"},"requirements":{"type":"string"},"openings":{"type":"number"},"manager":{"type":"string"},"pay":{"type":"string"},"roleStatus":{"type":"string","enum":["open","paused","filled","closed"]},"note":{"type":"string"}},"required":["title"]},"bind":{"action":"add_role"}},{"name":"add_candidate","description":"Add a candidate to a role’s pipeline: full name, role, where they came from, a short job-related note, and the interview date when one is already booked. An existing name in that role is updated, never duplicated. Call it as soon as a candidate is mentioned, before you describe them.","script":"hiring-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"role":{"type":"string"},"source":{"type":"string"},"status":{"type":"string","enum":["sourced","screen","interview","offer","hired","closed"]},"interviewOn":{"type":"string"},"interviewTime":{"type":"string"},"interviewer":{"type":"string"},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"add_candidate"}},{"name":"move_candidate","description":"Move a candidate to the stage the person names (sourced, screen, interview, offer, hired or closed) and book the interview: interviewOn takes YYYY-MM-DD or a weekday like \"thursday\", which the desk turns into the date. Call it the moment the person asks. Never move anyone on your own judgment; hiring decisions are the person’s.","script":"hiring-store","inputs":{"type":"object","properties":{"candidate":{"type":"string"},"status":{"type":"string","enum":["sourced","screen","interview","offer","hired","closed"]},"interviewOn":{"type":"string"},"interviewTime":{"type":"string"},"interviewer":{"type":"string"},"note":{"type":"string"}},"required":["candidate"]},"bind":{"action":"move"}},{"name":"log_feedback","description":"Record how an interview went: who interviewed, ratings from 1 to 4 on the role’s requirements (e.g. \"Coffee and milk skills 3, Warm customer service 4\"), and what the candidate said or did. Call it as soon as the person reports an interview, before you summarize it.","script":"hiring-store","inputs":{"type":"object","properties":{"candidate":{"type":"string"},"by":{"type":"string"},"ratings":{"type":"string"},"note":{"type":"string"}},"required":["candidate"]},"bind":{"action":"feedback"}},{"name":"list_candidates","description":"Every candidate with their role, stage, interview, average ratings and latest note.","script":"hiring-store","inputs":{"type":"object","properties":{}},"bind":{"action":"list"}},{"name":"page_add_role","description":"Open or update a role.","script":"hiring-store","inputs":{"type":"object","properties":{"title":{"type":"string"},"requirements":{"type":"string"},"openings":{"type":"number"},"manager":{"type":"string"},"pay":{"type":"string"},"roleStatus":{"type":"string","enum":["open","paused","filled","closed"]},"note":{"type":"string"}},"required":["title"]},"bind":{"action":"add_role"}},{"name":"page_add_candidate","description":"Add a candidate to a role.","script":"hiring-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"role":{"type":"string"},"source":{"type":"string"},"status":{"type":"string","enum":["sourced","screen","interview","offer","hired","closed"]},"interviewOn":{"type":"string"},"interviewTime":{"type":"string"},"interviewer":{"type":"string"},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"add_candidate"}},{"name":"page_move_candidate","description":"Move a candidate or book an interview.","script":"hiring-store","inputs":{"type":"object","properties":{"candidate":{"type":"string"},"status":{"type":"string","enum":["sourced","screen","interview","offer","hired","closed"]},"interviewOn":{"type":"string"},"interviewTime":{"type":"string"},"interviewer":{"type":"string"},"note":{"type":"string"}},"required":["candidate"]},"bind":{"action":"move"},"reaction":{"gezel":"recruiter","prompt":"The person just moved a candidate on the hiring desk page. The desk now reads (its first sentence is what changed):\n{{output.summary}}\nIn two short sentences, confirm the move and name the one next step for that candidate: book the interview, collect the scorecard, or prepare the offer for the person to approve. Do not call tools.","hideSeed":true}},{"name":"page_log_feedback","description":"Record an interview scorecard.","script":"hiring-store","inputs":{"type":"object","properties":{"candidate":{"type":"string"},"by":{"type":"string"},"ratings":{"type":"string"},"note":{"type":"string"}},"required":["candidate"]},"bind":{"action":"feedback"}}],"pages":{"entry":"desk/index.html","api":1,"reads":[{"source":"workspace","path":"roles.json"},{"source":"workspace","path":"candidates.json"},{"source":"workspace","path":"feedback.json"}],"tools":["page_add_role","page_add_candidate","page_move_candidate","page_log_feedback"]},"schedules":[],"workspaceSeed":["roles.json","candidates.json","feedback.json"],"artifactsSeed":[],"availableVersions":["1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"household-budget","name":"Household Budget","description":"Know where the money actually goes. A calm household treasurer keeps the ledger, closes each month in minutes, and the live dashboard shows in, out, net, and the categories that matter.","tags":["budget","money","household","spending","ledger"],"category":"money","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.6","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"currency":{"type":"string","title":"Currency","description":"Shown on the dashboard; entries are unit-agnostic.","default":"USD"}},"required":["currency"]},"nameTemplate":"Household Budget","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"penningmeester","voorman":true}],"toolsets":[],"craftbooks":["subscription-audit","month-close"],"scripts":{"budget-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { ledgerStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'budget-store',\n description:\n \"Read and update the household ledger (ledger.json). Call action:'status' for this month's shape (in/out/net, top categories); 'add_expense' or 'add_income' the moment money moves (amount in ordinary units, e.g. 12.50); 'month_summary' with month 'YYYY-MM' for any past month.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'status', 'add_expense', 'add_income', or 'month_summary'.\",\n required: true,\n },\n amount: { type: 'number', description: 'Amount in ordinary currency units, e.g. 12.50.' },\n category: { type: 'string', description: \"Category, e.g. 'groceries', 'rent', 'salary'.\" },\n note: { type: 'string', description: 'Short note on the entry.' },\n month: { type: 'string', description: \"Month for month_summary, e.g. '2026-06'.\" },\n },\n outputs: {\n entries: { type: 'number', description: 'Total ledger entries.' },\n summary: { type: 'string', description: 'Human-readable money summary.' },\n netCents: { type: 'number', description: 'Net for the summarized month, in cents.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── budget-rules-start ──\n// Pure derivations shared with tests: cents conversion and the month\n// summary line, kept engine-side so the dashboard, the tools, and the\n// tests agree on one rendering.\n\nfunction toCents(amount) {\n if (typeof amount !== 'number' || !isFinite(amount) || amount <= 0) return null;\n return Math.round(amount * 100);\n}\n\nfunction fmtCents(cents) {\n var sign = cents < 0 ? '-' : '';\n var abs = Math.abs(cents);\n return sign + Math.floor(abs / 100) + '.' + String(abs % 100).padStart(2, '0');\n}\n\nfunction topCategories(byCategory, kind, limit) {\n return Object.entries(byCategory)\n .map(function (pair) {\n return { category: pair[0], cents: kind === 'out' ? pair[1].outCents : pair[1].inCents };\n })\n .filter(function (row) {\n return row.cents > 0;\n })\n .sort(function (a, b) {\n return b.cents - a.cents;\n })\n .slice(0, limit);\n}\n\nfunction monthLine(month, totals) {\n var top = topCategories(totals.byCategory, 'out', 3)\n .map(function (row) {\n return row.category + ' ' + fmtCents(row.cents);\n })\n .join(', ');\n return (\n month +\n ': in ' +\n fmtCents(totals.inCents) +\n ', out ' +\n fmtCents(totals.outCents) +\n ', net ' +\n fmtCents(totals.netCents) +\n (top ? '. Biggest: ' + top + '.' : '. No spending recorded.')\n );\n}\n// ── budget-rules-end ──\n\nconst ledger = ledgerStore(gezel.fs, 'ledger.json');\nconst currentMonth = new Date().toISOString().slice(0, 7);\n\nif (input.action === 'add_expense' || input.action === 'add_income') {\n const cents = toCents(input.amount);\n if (cents === null) throw new Error(\"Pass a positive 'amount' in ordinary units, e.g. 12.50.\");\n if (!input.category) throw new Error(\"Pass a 'category', e.g. 'groceries' or 'salary'.\");\n await ledger.add({\n amountCents: cents,\n kind: input.action === 'add_expense' ? 'out' : 'in',\n category: input.category.toLowerCase(),\n ...(input.note ? { note: input.note } : {}),\n });\n} else if (input.action !== 'status' && input.action !== 'month_summary') {\n throw new Error(\n `Unknown action '${input.action}'. Use status, add_expense, add_income, or month_summary.`,\n );\n}\n\nconst month =\n input.action === 'month_summary' && input.month ? input.month : currentMonth;\nconst totals = await ledger.totals({ month });\nconst all = await ledger.list();\n\ngezel.output({\n entries: all.length,\n summary: monthLine(month, totals),\n netCents: totals.netCents,\n});\n"},"tools":[{"name":"add_expense","description":"Record spending the moment it happens (amount in ordinary units).","script":"budget-store","inputs":{"type":"object","properties":{"amount":{"type":"number"},"category":{"type":"string"},"note":{"type":"string"}},"required":["amount","category"]},"bind":{"action":"add_expense"}},{"name":"add_income","description":"Record money coming in.","script":"budget-store","inputs":{"type":"object","properties":{"amount":{"type":"number"},"category":{"type":"string"},"note":{"type":"string"}},"required":["amount","category"]},"bind":{"action":"add_income"}},{"name":"budget_status","description":"This month's shape: in, out, net, and the biggest categories.","script":"budget-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"}},{"name":"month_summary","description":"Summarize any month ('YYYY-MM').","script":"budget-store","inputs":{"type":"object","properties":{"month":{"type":"string"}},"required":["month"]},"bind":{"action":"month_summary"}},{"name":"record_expense","description":"The dashboard's quick-add expense entry.","script":"budget-store","inputs":{"type":"object","properties":{"amount":{"type":"number"},"category":{"type":"string"},"note":{"type":"string"}},"required":["amount","category"]},"bind":{"action":"add_expense"}},{"name":"page_add_income","description":"Record money coming in.","script":"budget-store","inputs":{"type":"object","properties":{"amount":{"type":"number"},"category":{"type":"string"},"note":{"type":"string"}},"required":["amount","category"]},"bind":{"action":"add_income"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"ledger.json"}],"tools":["record_expense","page_add_income"]},"schedules":[],"workspaceSeed":["ledger.json"],"artifactsSeed":[],"availableVersions":["1.0.6","1.0.5","1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"household-manual","name":"Household Manual","description":"The living manual for your home. A home keeper keeps a card for every system — what care it needs and when — turns problems into flagged history, and the dashboard shows what the house needs this season.","tags":["home","maintenance","appliances","household"],"category":"home","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.5","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"home":{"type":"string","title":"What kind of home?","description":"e.g. 'a 1960s house', 'a third-floor apartment'.","default":"our home"}},"required":["home"]},"nameTemplate":"Household Manual","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"huismeester","voorman":true}],"toolsets":[],"craftbooks":["seasonal-maintenance-sweep"],"scripts":{"house-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'house-store',\n description:\n \"Read and update the home's system cards (systems.json). Call action:'status' for what's due or flagged; 'record_system' when an appliance/system comes up (with care interval in days when known); 'log_maintenance' when care happens; 'flag_attention' for problems; 'house_list' to read every card.\",\n inputs: {\n action: {\n type: 'string',\n description:\n \"One of 'status', 'record_system', 'log_maintenance', 'flag_attention', or 'house_list'.\",\n required: true,\n },\n name: { type: 'string', description: \"System name, e.g. 'Furnace', 'Smoke alarms'.\" },\n kind: { type: 'string', description: 'What it is (appliance, safety, structure, utility).' },\n location: { type: 'string', description: 'Where it lives in the house.' },\n care: { type: 'string', description: \"The care it needs, e.g. 'replace filter'.\" },\n intervalDays: { type: 'number', description: 'Care interval in days, when known.' },\n note: { type: 'string', description: 'Maintenance or attention note.' },\n id: { type: 'string', description: \"System id, e.g. 'sys-2'.\" },\n },\n outputs: {\n systems: { type: 'number', description: 'System cards in the manual.' },\n due: { type: 'number', description: 'Systems with care due.' },\n flagged: { type: 'number', description: 'Systems flagged for attention.' },\n summary: { type: 'string', description: 'What the house needs.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── house-rules-start ──\n// Pure derivations over rosterStore-shaped system cards: statuses are\n// ok -> attention; \"due\" derives from lastDoneAt + intervalDays.\n\nvar DAY_MS = 24 * 60 * 60 * 1000;\n\nfunction isDue(record, nowMs) {\n var f = record.fields || {};\n if (typeof f.intervalDays !== 'number' || f.intervalDays <= 0) return false;\n var last = typeof f.lastDoneAt === 'string' ? Date.parse(f.lastDoneAt) : Date.parse(record.createdAt);\n return isFinite(last) && nowMs - last >= f.intervalDays * DAY_MS;\n}\n\nfunction houseShape(records, nowMs) {\n var due = [];\n var flagged = [];\n records.forEach(function (r) {\n if (isDue(r, nowMs)) due.push(r);\n if (r.status === 'attention') flagged.push(r);\n });\n return { due: due, flagged: flagged };\n}\n\nfunction houseLine(records, nowMs) {\n var shape = houseShape(records, nowMs);\n var names = function (rows) {\n return rows\n .map(function (r) {\n return (r.fields && r.fields.name) || r.id;\n })\n .join(', ');\n };\n if (records.length === 0) return 'No systems recorded yet — start with the ones that need regular care.';\n var bits = [];\n if (shape.due.length) bits.push('care due: ' + names(shape.due));\n if (shape.flagged.length) bits.push('flagged: ' + names(shape.flagged));\n return records.length + ' system(s) on record. ' + (bits.length ? bits.join('; ') + '.' : 'Nothing due — the house is quiet.');\n}\n// ── house-rules-end ──\n\nconst house = rosterStore(gezel.fs, 'systems.json', {\n stages: ['ok', 'attention'],\n idPrefix: 'sys',\n});\n\nasync function resolveSystem(): Promise<string> {\n if (input.id) return input.id;\n if (input.name) {\n const wanted = input.name.toLowerCase();\n const matches = (await house.list()).filter(\n (r) => String(r.fields.name ?? '').toLowerCase() === wanted,\n );\n if (matches.length === 1) return matches[0]!.id;\n }\n throw new Error(\"Pass 'id' (e.g. 'sys-2') or an exact system 'name'.\");\n}\n\nif (input.action === 'record_system') {\n if (!input.name) throw new Error(\"record_system needs 'name'.\");\n await house.add({\n status: 'ok',\n fields: {\n name: input.name,\n ...(input.kind ? { kind: input.kind } : {}),\n ...(input.location ? { location: input.location } : {}),\n ...(input.care ? { care: input.care } : {}),\n ...(typeof input.intervalDays === 'number' ? { intervalDays: input.intervalDays } : {}),\n lastDoneAt: new Date().toISOString(),\n },\n });\n} else if (input.action === 'log_maintenance') {\n const id = await resolveSystem();\n await house.update(id, {\n fields: { lastDoneAt: new Date().toISOString() },\n ...(input.note ? { note: input.note } : {}),\n });\n await house.transition(id, 'ok');\n} else if (input.action === 'flag_attention') {\n const id = await resolveSystem();\n await house.transition(id, 'attention', input.note ? { note: input.note } : {});\n} else if (input.action !== 'status' && input.action !== 'house_list') {\n throw new Error(\n `Unknown action '${input.action}'. Use status, record_system, log_maintenance, flag_attention, or house_list.`,\n );\n}\n\nconst records = await house.list();\nconst shape = houseShape(records, Date.now());\nconst listing =\n input.action === 'house_list'\n ? records\n .map(\n (r) =>\n `${r.id} [${r.status}${isDue(r, Date.now()) ? ', due' : ''}] ${String(r.fields.name ?? '?')}${r.fields.location ? ` — ${String(r.fields.location)}` : ''}${r.fields.care ? ` (${String(r.fields.care)}${r.fields.intervalDays ? ` every ${String(r.fields.intervalDays)}d` : ''})` : ''}`,\n )\n .join('\\n') || 'No systems recorded yet.'\n : '';\n\ngezel.output({\n systems: records.length,\n due: shape.due.length,\n flagged: shape.flagged.length,\n summary: listing || houseLine(records, Date.now()),\n});\n"},"tools":[{"name":"record_system","description":"Add a system or appliance card (with a care interval in days when known).","script":"house-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"kind":{"type":"string"},"location":{"type":"string"},"care":{"type":"string"},"intervalDays":{"type":"number"}},"required":["name"]},"bind":{"action":"record_system"}},{"name":"log_maintenance","description":"Log that care happened (resets the due clock).","script":"house-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"note":{"type":"string"}}},"bind":{"action":"log_maintenance"}},{"name":"flag_attention","description":"Flag a problem on a system (a noise, a drip, a trip).","script":"house-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"note":{"type":"string"}},"required":["note"]},"bind":{"action":"flag_attention"}},{"name":"house_status","description":"What the house needs: care due and flagged problems.","script":"house-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"}},{"name":"house_list","description":"Read every system card.","script":"house-store","inputs":{"type":"object","properties":{}},"bind":{"action":"house_list"}},{"name":"page_record_system","description":"Add a system or appliance card (with a care interval in days when known).","script":"house-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"kind":{"type":"string"},"location":{"type":"string"},"care":{"type":"string"},"intervalDays":{"type":"number"}},"required":["name"]},"bind":{"action":"record_system"}},{"name":"page_log_maintenance","description":"Log that care happened (resets the due clock).","script":"house-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"note":{"type":"string"}}},"bind":{"action":"log_maintenance"}},{"name":"page_flag_attention","description":"Flag a problem on a system (a noise, a drip, a trip).","script":"house-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"note":{"type":"string"}},"required":["note"]},"bind":{"action":"flag_attention"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"systems.json"}],"tools":["page_record_system","page_log_maintenance","page_flag_attention"]},"schedules":[],"workspaceSeed":["systems.json"],"artifactsSeed":[],"availableVersions":["1.0.5","1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"image-feed","name":"Image Feed","description":"A visual feed with a working rhythm — your social media writer runs the posting pipeline, an image maker turns notions into pictures in the feed's own style, and a live gallery shows every post from first idea to published.","tags":["social","instagram","images","visual","posts"],"category":"creative","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.4","releasedAt":"2026-11-02T18:00:00.000Z","extends":"social-media","meesterManaged":true,"mode":"crew","leadLabel":"Social Media Writer","params":{"type":"object","properties":{"brand":{"type":"string","title":"Who does this feed speak for?","description":"The name, brand, or studio this feed speaks for.","default":"Our studio"},"instagramHandle":{"type":"string","title":"Instagram handle","description":"Instagram handle (e.g. @studio). Leave empty if unused.","default":""},"visualStyle":{"type":"string","title":"Visual style","description":"One sentence on how the feed should look — seeded into style-guide.md.","default":"Natural light, honest color, one subject per image."},"voice":{"type":"string","title":"Tone of voice","description":"One sentence on tone of voice for captions.","default":"Warm, plain, and human — never corporate."},"cadence":{"type":"string","title":"Posting cadence","description":"Target posting cadence (e.g. 4 images a week).","default":"4 images a week"}},"required":["brand"]},"nameTemplate":"{{brand}} Image Feed","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"omroeper","voorman":true},{"templateId":"image-generator","voorman":false}],"toolsets":[],"craftbooks":["draft-social-post","social-digest","reception-report"],"scripts":{"posts-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\n\nexport const meta = defineScript({\n name: 'posts-store',\n description:\n \"Read and update the post pipeline under posts/. Call action:'list' to see every post (optional status/platform filters); 'get' for one post's frontmatter, body, variants, and media; 'create' to commit the staged posts/_drafting/ folder as a real post; 'update' to patch frontmatter or move a post one pipeline stage (idea, draft, in-review, approved, scheduled, published, archived from anywhere); 'record_publication' to stamp a platform variant with its permalink after it goes live. Illegal stage jumps fail with the legal next stages — move one stage at a time.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'list', 'get', 'create', 'update', or 'record_publication'.\",\n required: true,\n },\n id: { type: 'string', description: \"Post id — its folder name under posts/, e.g. '2026-08-12-launch-teaser'.\" },\n status: {\n type: 'string',\n description: \"Target status: idea, draft, in-review, approved, scheduled, published, or archived. For 'create', the initial status (defaults to approved).\",\n },\n platform: { type: 'string', description: \"Platform filter for 'list', or the published variant for 'record_publication' (e.g. 'bluesky').\" },\n fields: {\n type: 'json',\n description: \"For 'update': an object of frontmatter patches, e.g. {\\\"scheduledFor\\\": \\\"2026-08-15T09:00:00Z\\\", \\\"campaign\\\": \\\"autumn\\\"}. A null value clears the key.\",\n },\n permalink: { type: 'string', description: 'Public URL of the live post, for record_publication.' },\n postId: { type: 'string', description: \"The platform's own id for the live post, for record_publication.\" },\n corpusRef: { type: 'string', description: 'Connector corpus record reference for the live post, when one exists.' },\n publishedAt: { type: 'string', description: 'ISO timestamp the post went live (defaults to now).' },\n markPublished: {\n type: 'boolean',\n description: 'For record_publication: force the post to published even if other target platforms are not stamped yet.',\n },\n },\n // Only what every action returns is declared: the runtime requires each\n // declared output on every run, so listing per-action fields here failed\n // every call. 'list' also returns posts + total, 'get' returns post, and\n // the writes return id + status.\n outputs: {\n summary: { type: 'string', description: 'Human-readable result.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\nconst POSTS_DIR = 'posts';\nconst DRAFTING = 'posts/_drafting';\nconst INDEX_FILE = 'posts/index.json';\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,99}$/;\nconst PLATFORM_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;\nconst STAGES = ['idea', 'draft', 'in-review', 'approved', 'scheduled', 'published'] as const;\nconst STATUSES: string[] = [...STAGES, 'archived'];\n\n// ── frontmatter ──\n// Hand-rolled, deliberately simple: `---`-delimited `key: value` lines,\n// arrays as [a, b]. Unknown keys and even unparseable lines are preserved\n// in order so a round-trip never loses what a human or another tool wrote.\n\ntype FmEntry = { key: string; value: string | string[] } | { raw: string };\ninterface FmDoc {\n entries: FmEntry[];\n body: string;\n}\n\nfunction parseArrayish(value: string): string[] {\n return value\n .slice(1, -1)\n .split(',')\n .map((part) => part.trim().replace(/^[\"']|[\"']$/g, ''))\n .filter((part) => part.length > 0);\n}\n\nfunction parseFrontmatter(text: string): FmDoc {\n const lines = text.split(/\\r?\\n/);\n if (lines[0]?.trim() !== '---') return { entries: [], body: text };\n const entries: FmEntry[] = [];\n let at = 1;\n for (; at < lines.length; at += 1) {\n const line = lines[at]!;\n if (line.trim() === '---') {\n return { entries, body: lines.slice(at + 1).join('\\n').replace(/^\\n/, '') };\n }\n const sep = line.indexOf(':');\n if (sep <= 0) {\n if (line.trim().length > 0) entries.push({ raw: line });\n continue;\n }\n const key = line.slice(0, sep).trim();\n const value = line.slice(sep + 1).trim();\n if (!key) {\n entries.push({ raw: line });\n continue;\n }\n entries.push({\n key,\n value: value.startsWith('[') && value.endsWith(']') ? parseArrayish(value) : value,\n });\n }\n return { entries: [], body: text };\n}\n\nfunction serializeFrontmatter(doc: FmDoc): string {\n const lines = doc.entries.map((entry) => {\n if ('raw' in entry) return entry.raw;\n const value = Array.isArray(entry.value) ? `[${entry.value.join(', ')}]` : entry.value;\n return `${entry.key}: ${value}`;\n });\n return `---\\n${lines.join('\\n')}\\n---\\n\\n${doc.body.replace(/^\\n+/, '')}`;\n}\n\nfunction fmGet(doc: FmDoc, key: string): string | string[] | undefined {\n for (const entry of doc.entries) {\n if ('key' in entry && entry.key === key) return entry.value;\n }\n return undefined;\n}\n\nfunction fmGetString(doc: FmDoc, key: string): string {\n const value = fmGet(doc, key);\n if (Array.isArray(value)) return value.join(', ');\n return value ?? '';\n}\n\nfunction fmGetArray(doc: FmDoc, key: string): string[] {\n const value = fmGet(doc, key);\n if (Array.isArray(value)) return value;\n if (typeof value === 'string' && value.length > 0) return [value];\n return [];\n}\n\nfunction fmSet(doc: FmDoc, key: string, value: string | string[]): void {\n for (const entry of doc.entries) {\n if ('key' in entry && entry.key === key) {\n entry.value = value;\n return;\n }\n }\n doc.entries.push({ key, value });\n}\n\nfunction fmDelete(doc: FmDoc, key: string): void {\n doc.entries = doc.entries.filter((entry) => !('key' in entry && entry.key === key));\n}\n\n// ── pipeline rules ──\n\nfunction legalNext(from: string): string[] {\n if (from === 'archived') return [];\n const at = STAGES.indexOf(from as (typeof STAGES)[number]);\n const forward = at >= 0 && at < STAGES.length - 1 ? [STAGES[at + 1]!] : [];\n return [...forward, 'archived'];\n}\n\nfunction assertTransition(id: string, from: string, to: string): void {\n if (to === from) return;\n if (!STATUSES.includes(to)) {\n throw new Error(`Unknown status '${to}'. Statuses: ${STATUSES.join(', ')}.`);\n }\n if (!legalNext(from).includes(to)) {\n const next = legalNext(from);\n throw new Error(\n `Cannot move '${id}' from ${from} to ${to} — posts move one stage at a time. ` +\n (next.length > 0 ? `Legal next: ${next.join(', ')}.` : `'${from}' is final; create a new post instead.`),\n );\n }\n}\n\nfunction requireId(): string {\n const id = (input.id ?? '').trim();\n if (!id) throw new Error(\"Pass 'id' — the post's folder name under posts/ (see action:'list').\");\n if (!ID_RE.test(id)) {\n throw new Error(`Invalid post id '${id}'. Ids are lowercase [a-z0-9-], no slashes or dots.`);\n }\n return id;\n}\n\nfunction today(): string {\n return new Date().toISOString().slice(0, 10);\n}\n\nfunction slugify(text: string): string {\n return text\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 60);\n}\n\n// ── store ──\n\ninterface IndexEntry {\n id: string;\n title: string;\n status: string;\n platforms: string[];\n created: string;\n scheduledFor?: string;\n campaign?: string;\n}\n\nasync function readPostDoc(id: string): Promise<FmDoc> {\n let raw: string;\n try {\n raw = await gezel.fs.read(`${POSTS_DIR}/${id}/post.md`);\n } catch {\n throw new Error(`No post '${id}' — posts/${id}/post.md does not exist. Call action:'list' to see what does.`);\n }\n return parseFrontmatter(raw);\n}\n\nasync function writePostDoc(id: string, doc: FmDoc): Promise<void> {\n await gezel.fs.write(`${POSTS_DIR}/${id}/post.md`, serializeFrontmatter(doc));\n}\n\nfunction toIndexEntry(id: string, doc: FmDoc): IndexEntry {\n const entry: IndexEntry = {\n id,\n title: fmGetString(doc, 'title') || id,\n status: fmGetString(doc, 'status') || 'idea',\n platforms: fmGetArray(doc, 'platforms'),\n created: fmGetString(doc, 'created') || today(),\n };\n const scheduledFor = fmGetString(doc, 'scheduledFor');\n if (scheduledFor) entry.scheduledFor = scheduledFor;\n const campaign = fmGetString(doc, 'campaign');\n if (campaign) entry.campaign = campaign;\n return entry;\n}\n\nasync function regenerateIndex(): Promise<IndexEntry[]> {\n let names: string[] = [];\n try {\n names = (await gezel.fs.list(POSTS_DIR))\n .filter((entry) => entry.isDirectory && entry.name !== '_drafting' && ID_RE.test(entry.name))\n .map((entry) => entry.name);\n } catch {\n names = [];\n }\n const posts: IndexEntry[] = [];\n for (const name of names) {\n try {\n posts.push(toIndexEntry(name, await readPostDoc(name)));\n } catch {\n // A folder without a parseable post.md is not a post; leave it be.\n }\n }\n posts.sort((a, b) => (a.created === b.created ? (a.id < b.id ? 1 : -1) : a.created < b.created ? 1 : -1));\n await gezel.fs.write(INDEX_FILE, `${JSON.stringify({ version: 1, posts }, null, 2)}\\n`);\n return posts;\n}\n\nasync function readIndex(): Promise<IndexEntry[]> {\n try {\n const parsed = JSON.parse(await gezel.fs.read(INDEX_FILE)) as { posts?: IndexEntry[] };\n return Array.isArray(parsed.posts) ? parsed.posts : [];\n } catch {\n return [];\n }\n}\n\nasync function listVariants(id: string): Promise<Record<string, Record<string, unknown>>> {\n let names: string[] = [];\n try {\n names = (await gezel.fs.list(`${POSTS_DIR}/${id}/variants`))\n .filter((entry) => !entry.isDirectory && entry.name.endsWith('.md'))\n .map((entry) => entry.name);\n } catch {\n return {};\n }\n const variants: Record<string, Record<string, unknown>> = {};\n for (const name of names) {\n const platform = name.slice(0, -3);\n const doc = parseFrontmatter(await gezel.fs.read(`${POSTS_DIR}/${id}/variants/${name}`));\n const body = doc.body.trim();\n const variant: Record<string, unknown> = {\n charCount: Number(fmGetString(doc, 'charCount')) || body.length,\n body,\n };\n for (const key of ['publishedAt', 'permalink', 'postId', 'corpusRef']) {\n const value = fmGetString(doc, key);\n if (value) variant[key] = value;\n }\n variants[platform] = variant;\n }\n return variants;\n}\n\nasync function listMedia(id: string): Promise<string[]> {\n try {\n return (await gezel.fs.list(`${POSTS_DIR}/${id}/media`))\n .filter((entry) => !entry.isDirectory)\n .map((entry) => entry.name);\n } catch {\n return [];\n }\n}\n\n// ── actions ──\n\nif (input.action === 'list') {\n const all = await readIndex();\n let posts = all;\n if (input.status) posts = posts.filter((post) => post.status === input.status);\n if (input.platform) posts = posts.filter((post) => post.platforms.includes(input.platform!));\n const counts = STATUSES.map((status) => {\n const n = all.filter((post) => post.status === status).length;\n return n > 0 ? `${status} ${n}` : null;\n })\n .filter((line) => line !== null)\n .join(', ');\n gezel.output({\n posts,\n total: all.length,\n summary: all.length === 0 ? 'No posts yet — stage one in posts/_drafting/ and call create.' : `${all.length} post(s): ${counts}.`,\n });\n} else if (input.action === 'get') {\n const id = requireId();\n const doc = await readPostDoc(id);\n const fields: Record<string, unknown> = {};\n for (const entry of doc.entries) {\n if ('key' in entry) fields[entry.key] = entry.value;\n }\n const post = {\n id,\n ...fields,\n status: fmGetString(doc, 'status') || 'idea',\n platforms: fmGetArray(doc, 'platforms'),\n body: doc.body.trim(),\n variants: await listVariants(id),\n media: await listMedia(id),\n };\n gezel.output({\n post,\n id,\n status: post.status,\n summary: `'${fmGetString(doc, 'title') || id}' is ${post.status}; ${Object.keys(post.variants).length} variant(s), ${post.media.length} media file(s).`,\n });\n} else if (input.action === 'create') {\n let staged: FmDoc;\n try {\n staged = parseFrontmatter(await gezel.fs.read(`${DRAFTING}/post.md`));\n } catch {\n throw new Error('Nothing is staged — write posts/_drafting/post.md (frontmatter + body) first, then call create again.');\n }\n const slug = slugify(fmGetString(staged, 'slug') || fmGetString(staged, 'title'));\n if (!slug) throw new Error(\"The staged post.md needs a 'slug' or a 'title' in its frontmatter to name the post folder.\");\n const createdRaw = fmGetString(staged, 'created');\n const created = /^\\d{4}-\\d{2}-\\d{2}$/.test(createdRaw) ? createdRaw : today();\n const id = `${created}-${slug}`;\n if (!ID_RE.test(id)) throw new Error(`Derived post id '${id}' is invalid — keep slug to lowercase letters, digits, and dashes.`);\n const siblings = await gezel.fs.list(POSTS_DIR).catch(() => []);\n if (siblings.some((entry) => entry.name === id)) {\n throw new Error(`posts/${id}/ already exists. Change the staged slug (or created date) and call create again.`);\n }\n const status = input.status ?? 'approved';\n if (!STATUSES.includes(status)) {\n throw new Error(`'${status}' is not a status. Statuses: ${STATUSES.join(', ')}.`);\n }\n fmSet(staged, 'status', status);\n fmSet(staged, 'slug', slug);\n fmSet(staged, 'created', created);\n await gezel.fs.write(`${DRAFTING}/post.md`, serializeFrontmatter(staged));\n await gezel.fs.rename(DRAFTING, `${POSTS_DIR}/${id}`);\n await regenerateIndex();\n gezel.output({\n id,\n status,\n summary: `Committed posts/_drafting/ as posts/${id}/ with status ${status}.`,\n });\n} else if (input.action === 'update') {\n const id = requireId();\n const doc = await readPostDoc(id);\n const patches = (input.fields && typeof input.fields === 'object' && !Array.isArray(input.fields) ? input.fields : {}) as Record<string, unknown>;\n let nextStatus = input.status;\n if (typeof patches.status === 'string' && !nextStatus) nextStatus = patches.status;\n delete patches.status;\n if (!nextStatus && Object.keys(patches).length === 0) {\n throw new Error(\"Nothing to change — pass 'status' and/or a 'fields' object of frontmatter patches.\");\n }\n const from = fmGetString(doc, 'status') || 'idea';\n if (nextStatus) assertTransition(id, from, nextStatus);\n for (const [key, value] of Object.entries(patches)) {\n if (value === null || value === undefined) fmDelete(doc, key);\n else if (Array.isArray(value)) fmSet(doc, key, value.map((item) => String(item)));\n else fmSet(doc, key, String(value));\n }\n if (nextStatus) fmSet(doc, 'status', nextStatus);\n await writePostDoc(id, doc);\n await regenerateIndex();\n const status = nextStatus ?? from;\n gezel.output({\n id,\n status,\n summary: nextStatus && nextStatus !== from ? `Moved '${id}' from ${from} to ${status}.` : `Updated '${id}' (${status}).`,\n });\n} else if (input.action === 'record_publication') {\n const id = requireId();\n const platform = (input.platform ?? '').trim();\n if (!PLATFORM_RE.test(platform)) {\n throw new Error(\"Pass 'platform' — the variant that went live, e.g. 'bluesky', 'x', or 'instagram'.\");\n }\n const doc = await readPostDoc(id);\n const variantPath = `${POSTS_DIR}/${id}/variants/${platform}.md`;\n const variant = parseFrontmatter(await gezel.fs.read(variantPath).catch(() => '---\\n---\\n'));\n fmSet(variant, 'publishedAt', input.publishedAt ?? new Date().toISOString());\n if (input.permalink) fmSet(variant, 'permalink', input.permalink);\n if (input.postId) fmSet(variant, 'postId', input.postId);\n if (input.corpusRef) fmSet(variant, 'corpusRef', input.corpusRef);\n await gezel.fs.write(variantPath, serializeFrontmatter(variant));\n const targets = fmGetArray(doc, 'platforms');\n const stamped = await listVariants(id);\n const allLive = targets.length > 0 && targets.every((target) => typeof stamped[target]?.publishedAt === 'string');\n let status = fmGetString(doc, 'status') || 'idea';\n // Recording reality bypasses the stage chain: once every target variant\n // is live (or the caller says so), the post IS published.\n if (allLive || input.markPublished === true) {\n status = 'published';\n fmSet(doc, 'status', status);\n await writePostDoc(id, doc);\n }\n await regenerateIndex();\n const waiting = targets.filter((target) => typeof stamped[target]?.publishedAt !== 'string');\n gezel.output({\n id,\n status,\n summary:\n status === 'published'\n ? `Recorded ${platform} publication for '${id}' — the post is published.`\n : `Recorded ${platform} publication for '${id}'; still waiting on: ${waiting.join(', ') || '(none)'}.`,\n });\n} else {\n throw new Error(`Unknown action '${input.action}'. Use list, get, create, update, or record_publication.`);\n}\n"},"tools":[{"name":"list_posts","description":"See the whole post pipeline: every post with its status, platforms, and dates. Optionally filter by status or platform.","script":"posts-store","inputs":{"type":"object","properties":{"status":{"type":"string","enum":["idea","draft","in-review","approved","scheduled","published","archived"],"description":"Only posts currently in this status."},"platform":{"type":"string","description":"Only posts targeting this platform, e.g. 'bluesky'."}}},"bind":{"action":"list"}},{"name":"get_post","description":"Read one post in full: frontmatter, body, each platform variant with its character count (and permalink once live), and media files.","script":"posts-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Post id — its folder name under posts/, e.g. '2026-08-12-launch-teaser'."}},"required":["id"]},"bind":{"action":"get"}},{"name":"create_post","description":"Commit the staged posts/_drafting/ folder as a real post. Stage post.md (frontmatter + body), variants/, and media/ there first; the post folder is named from the created date and slug.","script":"posts-store","inputs":{"type":"object","properties":{"status":{"type":"string","enum":["idea","draft","in-review","approved","scheduled","published","archived"],"description":"Initial status for the new post. Defaults to approved."}}},"bind":{"action":"create"}},{"name":"update_post","description":"Patch a post's frontmatter (fields object; null clears a key) and/or move it one pipeline stage. Stages run idea, draft, in-review, approved, scheduled, published — archived from anywhere.","script":"posts-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Post id."},"fields":{"type":"object","description":"Frontmatter patches, e.g. {\"scheduledFor\": \"2026-08-15T09:00:00Z\", \"campaign\": \"autumn\"}."},"status":{"type":"string","enum":["idea","draft","in-review","approved","scheduled","published","archived"],"description":"Target status (one stage at a time)."}},"required":["id"]},"bind":{"action":"update"}},{"name":"record_publication","description":"The moment a variant goes live, stamp it with its permalink and platform post id. The post flips to published once every target platform is stamped (or markPublished is passed).","script":"posts-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Post id."},"platform":{"type":"string","description":"The platform that went live, e.g. 'bluesky'."},"permalink":{"type":"string","description":"Public URL of the live post."},"postId":{"type":"string","description":"The platform's own id for the live post."},"corpusRef":{"type":"string","description":"Connector corpus record reference, when one exists."},"publishedAt":{"type":"string","description":"ISO timestamp it went live (defaults to now)."},"markPublished":{"type":"boolean","description":"Force the post to published even with unstamped platforms."}},"required":["id","platform"]},"bind":{"action":"record_publication"}},{"name":"page_set_status","description":"Page-only: move a post between pipeline columns on the gallery.","script":"posts-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Post id."},"status":{"type":"string","enum":["idea","draft","in-review","approved","scheduled","published","archived"],"description":"The column the post was moved to."}},"required":["id","status"]},"bind":{"action":"update"},"reaction":{"gezel":"omroeper","prompt":"[Feed gallery]: The user moved post {{output.id}} to '{{output.status}}' on the gallery. Reply with ONE short line acknowledging the move. If it landed in 'draft', offer to run the draft-social-post craftbook on it. Do not restate the pipeline.","hideSeed":true}},{"name":"page_get_post","description":"Page-only: the detail drawer's read of one post with variants and media.","script":"posts-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Post id."}},"required":["id"]},"bind":{"action":"get"}}],"pages":{"entry":"gallery/index.html","api":1,"reads":[{"source":"workspace","path":"posts","subtree":true},{"source":"workspace","path":"style-guide.md"},{"source":"artifacts","path":"data","subtree":true}],"tools":["page_set_status","page_get_post"]},"schedules":[{"runMode":"night-shift","craftbook":"social-digest","consent":"ask","overlap":"skip"},{"runMode":"scheduled","cron":"0 15 * * 1","craftbook":"reception-report","consent":"ask","overlap":"skip"}],"workspaceSeed":["style-guide.md","posts/index.json"],"artifactsSeed":[],"notes":"posts/index.json is seeded at its subpath (applyProjectType preserves seed subpaths and creates parents) and is ALSO regenerated by posts-store on every mutation, so the gallery tolerates a missing or stale index. Posts live one folder per post under posts/ (post.md + variants/ + media/), staged in posts/_drafting/ until create_post commits them. page_set_status and page_get_post are the page-only twins of update_post/get_post — pages.tools names are removed from the model surface, so the model keeps its own read tools.","availableVersions":["1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"inventory-reorder","name":"Inventory & Reorder","description":"Know what is in stock and reorder before you run out. A stock keeper tracks every item against its reorder point, keeps each supplier and their lead time, and drafts the purchase orders for you to check and send.","tags":["inventory","reorder","purchase-orders","suppliers","shop","small-business"],"category":"business","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.0.0","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"business":{"type":"string","title":"What kind of business is this?","description":"e.g. 'a café in Portland', 'a small pottery studio'.","default":"the business"}},"required":["business"]},"nameTemplate":"Inventory & Reorder","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"stock-keeper","voorman":true},{"templateId":"kantoormeester","voorman":false}],"toolsets":[],"craftbooks":["reorder-run"],"scripts":{"inventory-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'inventory-store',\n description:\n \"Read and update the stock list (items.json) and purchase orders (orders.json). action:'status' for what is out, low and on order; 'add' to save an item (an existing name is updated, never duplicated); 'stock' to record what was received and used, or a shelf count; 'draft_orders' to draft one purchase order per supplier for everything at or below its reorder point; 'update_order' to mark an order sent, received (its quantities go into stock) or cancelled, or to set a line on a draft; 'list' for everything.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'status', 'add', 'stock', 'draft_orders', 'update_order', or 'list'.\",\n required: true,\n },\n name: { type: 'string', description: \"The item's name, e.g. 'Oat milk'.\" },\n item: { type: 'string', description: \"An item's name or id ('it-3'), for stock changes and draft lines.\" },\n unit: { type: 'string', description: \"How it is counted, e.g. 'carton', 'bag (5 lb)', 'sleeve of 50'.\" },\n onHand: { type: 'number', description: 'How many are on the shelf now.' },\n reorderPoint: { type: 'number', description: 'Reorder when stock falls to this many or fewer.' },\n par: { type: 'number', description: 'Order back up to this many.' },\n supplier: { type: 'string', description: 'Who supplies it.' },\n leadDays: { type: 'number', description: \"The supplier's lead time in days; it applies to every item from them.\" },\n unitCost: { type: 'number', description: 'Price per unit in dollars, e.g. 3.8.' },\n received: { type: 'number', description: 'How many came in. Added to the count.' },\n used: { type: 'number', description: 'How many were sold, used or thrown out. Taken off the count.' },\n count: { type: 'number', description: 'A shelf count. Replaces the number on hand.' },\n order: { type: 'string', description: \"Order id ('po-2') or the supplier's name.\" },\n status: { type: 'string', description: 'For update_order: sent, received, or cancelled.' },\n qty: { type: 'number', description: 'For update_order: the quantity of item on a draft (0 takes it off).' },\n note: { type: 'string', description: 'Anything worth keeping with the change.' },\n },\n outputs: {\n out: { type: 'number', description: 'Items with none on hand.' },\n low: { type: 'number', description: 'Items at or below their reorder point.' },\n onOrder: { type: 'number', description: 'Orders sent and not yet received.' },\n drafts: { type: 'number', description: 'Draft orders waiting for the person.' },\n tracked: { type: 'number', description: 'Items on the stock list.' },\n summary: { type: 'string', description: 'What changed, then the stock picture; or the listing.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── inventory-rules-start ──\n// Pure stock rules: an item's status from its count, the quantity that fills it\n// back to par, and the purchase-order drafts each supplier needs. run() applies\n// one action to a snapshot of the stores and lists the store operations, so the\n// live store and the page's demo share every rule. Kept self-contained between\n// these sentinels; the page loads the same bytes as rules.js.\nvar DAY_MS = 86400000;\nvar OPEN = ['draft', 'sent'];\n\nfunction pad(n) {\n return n < 10 ? '0' + n : String(n);\n}\nfunction localDay(ms) {\n var d = new Date(ms);\n return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());\n}\nfunction addDays(day, n) {\n var d = new Date(String(day).slice(0, 10) + 'T12:00:00');\n d.setDate(d.getDate() + n);\n return localDay(d.getTime());\n}\nfunction daysUntil(day, nowMs) {\n return Math.round((Date.parse(String(day).slice(0, 10) + 'T00:00:00') - Date.parse(localDay(nowMs) + 'T00:00:00')) / DAY_MS);\n}\nfunction when(days) {\n if (days < 0) return -days + (days === -1 ? ' day late' : ' days late');\n if (days === 0) return 'today';\n return 'in ' + days + (days === 1 ? ' day' : ' days');\n}\nfunction num(value) {\n if (value === undefined || value === null || value === '') return null;\n var n = typeof value === 'number' ? value : Number(String(value).replace(/[$,\\s]/g, ''));\n return isFinite(n) ? n : null;\n}\nfunction round2(n) {\n return Math.round(n * 100) / 100;\n}\nfunction key(text) {\n return String(text === undefined || text === null ? '' : text).trim().toLowerCase();\n}\nfunction unitText(unit, n) {\n var u = String(unit || '').trim();\n if (!u) return n === 1 ? 'unit' : 'units';\n if (n === 1) return u;\n var parts = u.split(' ');\n var first = parts[0];\n if (first.length <= 2 || /^(lbs|each|dozen)$/i.test(first) || /s$/i.test(first)) return u;\n parts[0] = /(x|ch|sh)$/i.test(first) ? first + 'es' : /[^aeiou]y$/i.test(first) ? first.slice(0, -1) + 'ies' : first + 's';\n return parts.join(' ');\n}\nfunction amount(n, unit) {\n return round2(n) + ' ' + unitText(unit, n);\n}\nfunction money(cents) {\n var parts = (Math.round(cents) / 100).toFixed(2).split('.');\n return '$' + parts[0].replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',') + '.' + parts[1];\n}\nfunction stockStatus(f) {\n var onHand = num(f.onHand) || 0;\n var point = num(f.reorderPoint) || 0;\n return onHand <= 0 ? 'out' : onHand <= point ? 'low' : 'ok';\n}\n// Reordering fills an item back up to its par level; without a par, to twice its reorder point.\nfunction orderQty(f) {\n var onHand = Math.max(0, num(f.onHand) || 0);\n var point = num(f.reorderPoint) || 0;\n var par = num(f.par) || 0;\n var target = par > point ? par : Math.max(point * 2, point + 1);\n return Math.max(1, Math.ceil(target - onHand));\n}\nfunction lineTotal(line) {\n return Math.round((num(line.qty) || 0) * (num(line.unitCostCents) || 0));\n}\nfunction orderTotal(lines) {\n return lines.reduce(function (sum, line) {\n return sum + lineTotal(line);\n }, 0);\n}\nfunction linesText(lines) {\n return lines\n .map(function (l) {\n return l.name + ' (' + amount(l.qty, l.unit) + ')';\n })\n .join(', ');\n}\nfunction supplierLead(items, supplier) {\n var hit = items.filter(function (r) {\n return key(r.fields.supplier) === key(supplier) && num(r.fields.leadDays) !== null;\n })[0];\n return hit ? num(hit.fields.leadDays) : null;\n}\nfunction suppliers(items) {\n var seen = {};\n var list = [];\n items.forEach(function (r) {\n var k = key(r.fields.supplier);\n if (!k) return;\n if (!seen[k]) {\n seen[k] = { name: r.fields.supplier, leadDays: null, items: 0, low: 0 };\n list.push(seen[k]);\n }\n seen[k].items += 1;\n if (stockStatus(r.fields) !== 'ok') seen[k].low += 1;\n if (seen[k].leadDays === null && num(r.fields.leadDays) !== null) seen[k].leadDays = num(r.fields.leadDays);\n });\n return list.sort(function (a, b) {\n return a.name.localeCompare(b.name);\n });\n}\nfunction words(text) {\n return key(text)\n .split(/[^a-z0-9]+/)\n .filter(function (w) {\n return w.length > 2;\n });\n}\nfunction findItem(items, wanted) {\n var text = String(wanted === undefined || wanted === null ? '' : wanted).trim();\n if (!text) throw new Error(\"Name the item ('Oat milk') or pass its id ('it-3'). Call stock_status to see them.\");\n var byId = items.filter(function (r) {\n return r.id === text;\n });\n if (byId.length) return byId[0];\n var k = key(text);\n var exact = items.filter(function (r) {\n return key(r.fields.name) === k;\n });\n if (exact.length === 1) return exact[0];\n var stem = k.replace(/s$/, '');\n var asked = words(k);\n var tiers = [\n items.filter(function (r) {\n return key(r.fields.name).indexOf(stem) >= 0;\n }),\n items.filter(function (r) {\n var name = key(r.fields.name);\n return (\n asked.length > 0 &&\n asked.every(function (w) {\n return name.indexOf(w.replace(/s$/, '')) >= 0;\n })\n );\n }),\n ];\n for (var i = 0; i < tiers.length; i++) {\n if (tiers[i].length === 1) return tiers[i][0];\n if (tiers[i].length > 1) {\n throw new Error(\"More than one item matches '\" + text + \"': \" + tiers[i].map(itemName).join(', ') + '. Pass the id.');\n }\n }\n throw new Error(\"No item matches '\" + text + \"'. Items: \" + (items.map(itemName).join(', ') || 'none yet') + '.');\n}\nfunction itemName(r) {\n return r.id + ' ' + r.fields.name;\n}\nfunction orderName(o) {\n return o.id + ' ' + o.fields.supplier + ' (' + o.status + ')';\n}\nfunction findOrder(orders, wanted, status) {\n var text = String(wanted === undefined || wanted === null ? '' : wanted).trim();\n var open = orders.filter(function (o) {\n return OPEN.indexOf(o.status) >= 0;\n });\n if (!text) {\n if (open.length === 1) return open[0];\n throw new Error(\"Pass the order id ('po-2') or the supplier's name. Open orders: \" + (open.map(orderName).join(', ') || 'none') + '.');\n }\n var byId = orders.filter(function (o) {\n return o.id === text || o.id === 'po-' + text.replace(/^#/, '');\n });\n if (byId.length) return byId[0];\n var k = key(text);\n var hits = open.filter(function (o) {\n var s = key(o.fields.supplier);\n return s && (s.indexOf(k) >= 0 || k.indexOf(s) >= 0);\n });\n if (!hits.length) {\n hits = open.filter(function (o) {\n return (o.fields.lines || []).some(function (l) {\n var n = key(l.name);\n return n.indexOf(k.replace(/s$/, '')) >= 0 || k.indexOf(n) >= 0;\n });\n });\n }\n var preferred = hits.filter(function (o) {\n return status === 'sent' ? o.status === 'draft' : status === 'received' ? o.status === 'sent' : true;\n });\n if (preferred.length === 1) return preferred[0];\n if (!preferred.length && hits.length === 1) return hits[0];\n if (hits.length) throw new Error(\"More than one open order matches '\" + text + \"': \" + hits.map(orderName).join(', ') + '. Pass the id.');\n throw new Error(\"No open order matches '\" + text + \"'. Open orders: \" + (open.map(orderName).join(', ') || 'none') + '.');\n}\n\n// A working copy of the stores. Each change is applied here and recorded as an operation\n// the live store replays through rosterStore; the demo keeps the copy itself.\nfunction transaction(state, nowMs) {\n var data = JSON.parse(JSON.stringify(state));\n var ops = [];\n var at = new Date(nowMs).toISOString();\n function copy(value) {\n return JSON.parse(JSON.stringify(value));\n }\n function get(store, id) {\n return (\n data[store].filter(function (r) {\n return r.id === id;\n })[0] || null\n );\n }\n return {\n data: data,\n ops: ops,\n get: get,\n add: function (store, prefix, status, fields, note) {\n var max = 0;\n data[store].forEach(function (r) {\n var m = /-(\\d+)$/.exec(r.id);\n if (m && r.id.indexOf(prefix + '-') === 0) max = Math.max(max, Number(m[1]));\n });\n var id = prefix + '-' + (max + 1);\n data[store].push({ id: id, status: status, fields: copy(fields), createdAt: at, updatedAt: at, history: [{ at: at, from: null, to: status, note: note }] });\n ops.push({ store: store, op: 'add', id: id, status: status, fields: copy(fields), note: note });\n return id;\n },\n update: function (store, id, fields, note) {\n var r = get(store, id);\n r.fields = Object.assign({}, r.fields, copy(fields));\n r.updatedAt = at;\n if (note) (r.history = r.history || []).push({ at: at, from: r.status, to: r.status, note: note });\n ops.push({ store: store, op: 'update', id: id, fields: copy(fields), note: note });\n },\n transition: function (store, id, to, note) {\n var r = get(store, id);\n (r.history = r.history || []).push({ at: at, from: r.status, to: to, note: note });\n r.status = to;\n r.updatedAt = at;\n ops.push({ store: store, op: 'transition', id: id, to: to, note: note });\n },\n };\n}\nfunction syncStatus(t, id) {\n var r = t.get('items', id);\n var next = stockStatus(r.fields);\n if (next !== r.status) {\n t.transition('items', id, next, next === 'ok' ? 'Back above the reorder point' : next === 'low' ? 'At or below the reorder point' : 'Out of stock');\n }\n}\n\n// What each supplier needs: items at or below their reorder point that are not already on a sent order.\nfunction needsBySupplier(items, orders) {\n var onSent = {};\n orders.forEach(function (o) {\n if (o.status === 'sent') {\n (o.fields.lines || []).forEach(function (l) {\n onSent[l.itemId] = o.id;\n });\n }\n });\n var groups = [];\n var byKey = {};\n items.forEach(function (r) {\n if (stockStatus(r.fields) === 'ok' || onSent[r.id] || !key(r.fields.supplier)) return;\n var k = key(r.fields.supplier);\n if (!byKey[k]) {\n byKey[k] = { key: k, supplier: r.fields.supplier, items: [] };\n groups.push(byKey[k]);\n }\n byKey[k].items.push(r);\n });\n return groups;\n}\n// Lines the person set by hand stay; every other line follows the stock.\nfunction draftLines(items, existing) {\n var fixed = (existing || []).filter(function (l) {\n return l.fixed;\n });\n return fixed.concat(\n items\n .filter(function (r) {\n return !fixed.some(function (l) {\n return l.itemId === r.id;\n });\n })\n .map(function (r) {\n return { itemId: r.id, name: r.fields.name, unit: r.fields.unit || '', qty: orderQty(r.fields), unitCostCents: num(r.fields.unitCostCents) || 0 };\n }),\n );\n}\nfunction refreshDrafts(t, create, only) {\n var notes = [];\n var groups = needsBySupplier(t.data.items, t.data.orders);\n var done = {};\n function wanted(supplier) {\n return !only || key(supplier).indexOf(key(only)) >= 0 || key(only).indexOf(key(supplier)) >= 0;\n }\n t.data.orders\n .filter(function (o) {\n return o.status === 'draft';\n })\n .forEach(function (o) {\n if (!wanted(o.fields.supplier)) return;\n var k = key(o.fields.supplier);\n var group = done[k]\n ? null\n : groups.filter(function (g) {\n return g.key === k;\n })[0];\n done[k] = true;\n var lines = draftLines(group ? group.items : [], o.fields.lines);\n if (!lines.length) {\n t.transition('orders', o.id, 'cancelled', 'Nothing left to order');\n notes.push('Dropped draft ' + o.id + ' for ' + o.fields.supplier + ': nothing on it needs ordering now.');\n return;\n }\n if (JSON.stringify(lines) === JSON.stringify(o.fields.lines)) return;\n t.update('orders', o.id, { lines: lines, totalCents: orderTotal(lines) }, 'Refreshed from stock');\n notes.push('Updated draft ' + o.id + ' for ' + o.fields.supplier + ': ' + linesText(lines) + ', ' + money(orderTotal(lines)) + '.');\n });\n if (create) {\n groups.forEach(function (g) {\n if (done[g.key] || !wanted(g.supplier)) return;\n var lines = draftLines(g.items, []);\n var id = t.add('orders', 'po', 'draft', { supplier: g.supplier, lines: lines, totalCents: orderTotal(lines) }, 'Drafted from stock');\n notes.push('Drafted ' + id + ' for ' + g.supplier + ': ' + linesText(lines) + ', ' + money(orderTotal(lines)) + '.');\n });\n }\n return notes;\n}\n\nfunction addItem(t, input) {\n var name = String(input.name || '').trim();\n if (!name) throw new Error(\"add needs the item's 'name'.\");\n var fields = {};\n ['onHand', 'reorderPoint', 'par', 'leadDays', 'unitCost'].forEach(function (k) {\n if (input[k] === undefined || input[k] === null || input[k] === '') return;\n var n = num(input[k]);\n if (n === null || n < 0) throw new Error(k + ' must be a number, zero or more (got ' + input[k] + ').');\n if (k === 'unitCost') fields.unitCostCents = Math.round(n * 100);\n else fields[k] = k === 'leadDays' ? Math.round(n) : round2(n);\n });\n if (input.unit) fields.unit = String(input.unit).trim();\n if (input.supplier) fields.supplier = String(input.supplier).trim();\n if (input.note) fields.notes = String(input.note).trim();\n var items = t.data.items;\n var existing = items.filter(function (r) {\n return key(r.fields.name) === key(name);\n })[0];\n var supplier = fields.supplier || (existing && existing.fields.supplier) || '';\n var others = supplier\n ? items.filter(function (r) {\n return key(r.fields.supplier) === key(supplier) && (!existing || r.id !== existing.id);\n })\n : [];\n // One supplier, one spelling and one lead time.\n if (fields.supplier && others.length) fields.supplier = others[0].fields.supplier;\n if (fields.supplier && fields.leadDays === undefined) {\n var lead = supplierLead(others, supplier);\n if (lead !== null) fields.leadDays = lead;\n }\n var id;\n var msg;\n if (existing) {\n t.update('items', existing.id, fields, 'Updated');\n id = existing.id;\n msg = 'Updated ' + existing.fields.name + ' (' + id + ').';\n } else {\n if (fields.onHand === undefined) throw new Error(\"A new item needs 'onHand': how many are on the shelf now.\");\n fields = Object.assign({ name: name }, fields);\n id = t.add('items', 'it', stockStatus(fields), fields, 'Added');\n msg = 'Added ' + name + ' (' + id + ').';\n if (fields.reorderPoint === undefined) msg += ' It has no reorder point yet, so it only flags when it runs out.';\n }\n var lead2 = num(input.leadDays);\n var changed =\n lead2 !== null && supplier\n ? others.filter(function (r) {\n return num(r.fields.leadDays) !== Math.round(lead2);\n })\n : [];\n changed.forEach(function (r) {\n t.update('items', r.id, { leadDays: Math.round(lead2) }, 'Supplier lead time ' + Math.round(lead2) + ' days');\n });\n if (changed.length) msg += ' ' + supplier + \"'s lead time is now \" + Math.round(lead2) + ' days on every item from them.';\n syncStatus(t, id);\n var r = t.get('items', id);\n var status = r.status;\n msg +=\n ' ' + r.fields.name + ' has ' + amount(num(r.fields.onHand) || 0, r.fields.unit) +\n (status === 'ok' ? ' on hand, above its reorder point.' : status === 'low' ? ' on hand, at or below its reorder point of ' + (num(r.fields.reorderPoint) || 0) + '.' : ' on hand, so it is out.');\n return [msg].concat(refreshDrafts(t, false, null)).join(' ');\n}\n\nfunction recordStock(t, input, nowMs) {\n var r = t.get('items', findItem(t.data.items, input.item !== undefined && input.item !== '' ? input.item : input.name !== undefined && input.name !== '' ? input.name : input.id).id);\n var values = {};\n ['received', 'used', 'count'].forEach(function (k) {\n if (input[k] === undefined || input[k] === null || input[k] === '') return;\n var n = num(input[k]);\n if (n === null || n < 0) throw new Error(k + ' must be a number, zero or more (got ' + input[k] + ').');\n values[k] = round2(n);\n });\n if (values.count !== undefined && (values.received !== undefined || values.used !== undefined)) {\n throw new Error(\"Pass 'count' on its own for a shelf count, or 'received' and 'used' for what came in and went out; not both.\");\n }\n if (values.count === undefined && values.received === undefined && values.used === undefined) {\n throw new Error(\"record_stock needs 'received' (came in), 'used' (sold, used or thrown out), or 'count' (counted on the shelf).\");\n }\n var unit = r.fields.unit;\n var point = num(r.fields.reorderPoint) || 0;\n var before = num(r.fields.onHand) || 0;\n var wasStatus = stockStatus(r.fields);\n var done = [];\n var after;\n if (values.count !== undefined) {\n after = values.count;\n done.push('counted ' + amount(values.count, unit));\n } else {\n after = before + (values.received || 0) - (values.used || 0);\n if (values.received) done.push('received ' + amount(values.received, unit));\n if (values.used) done.push('used ' + amount(values.used, unit));\n if (!done.length) done.push('no change');\n }\n var short = after < 0;\n if (short) after = 0;\n after = round2(after);\n var change = done.join(' and ');\n t.update('items', r.id, values.count !== undefined ? { onHand: after, countedAt: localDay(nowMs) } : { onHand: after }, change.charAt(0).toUpperCase() + change.slice(1) + ': ' + round2(before) + ' to ' + after);\n syncStatus(t, r.id);\n var status = t.get('items', r.id).status;\n var msg = r.fields.name + ': ' + change + '; ' + round2(before) + ' before, ' + amount(after, unit) + ' now.';\n if (short) msg += ' More was used than the ' + round2(before) + ' on hand, so it is set to 0; count the shelf to correct it.';\n if (status !== wasStatus) {\n msg += status === 'out' ? ' It is out.' : status === 'low' ? ' It is now at or below its reorder point of ' + point + '.' : ' It is back above its reorder point.';\n } else if (status !== 'ok') {\n msg += ' Still ' + status + ' (reorder point ' + point + ').';\n }\n return [msg].concat(refreshDrafts(t, false, null)).join(' ');\n}\n\nfunction draftOrders(t, input) {\n var only = String(input.supplier || '').trim();\n var notes = refreshDrafts(t, true, only || null);\n var orphans = t.data.items.filter(function (r) {\n return stockStatus(r.fields) !== 'ok' && !key(r.fields.supplier);\n });\n if (!notes.length) {\n notes.push(\n only\n ? 'Nothing from ' + only + ' is at or below its reorder point without an order already.'\n : 'Nothing is at or below its reorder point without an order already, so there is nothing to draft.',\n );\n } else {\n notes.push('These are drafts: check them, place them with the supplier, then mark each one sent.');\n }\n if (orphans.length && !only) {\n notes.push(\n orphans\n .map(function (r) {\n return r.fields.name;\n })\n .join(', ') + (orphans.length === 1 ? ' needs' : ' need') + ' a supplier before it can go on an order.',\n );\n }\n return notes.join(' ');\n}\n\nfunction updateOrder(t, input, nowMs) {\n var status = key(input.status);\n if (status && ['sent', 'received', 'cancelled'].indexOf(status) < 0) throw new Error(\"status must be 'sent', 'received', or 'cancelled'.\");\n var hasLine = input.item !== undefined && input.item !== null && input.item !== '' && num(input.qty) !== null;\n if (!status && !hasLine) throw new Error(\"update_order needs 'status' (sent, received or cancelled), or 'item' and 'qty' to change a line on a draft.\");\n var o = t.get('orders', findOrder(t.data.orders, input.order !== undefined && input.order !== '' ? input.order : input.id !== undefined && input.id !== '' ? input.id : input.supplier, status).id);\n var supplier = o.fields.supplier;\n var msgs = [];\n if (hasLine) {\n if (o.status !== 'draft') throw new Error(o.id + ' is ' + o.status + '; only a draft can change.');\n var qty = num(input.qty);\n if (qty < 0) throw new Error('qty must be zero or more.');\n var item = findItem(t.data.items, input.item);\n var line = { itemId: item.id, name: item.fields.name, unit: item.fields.unit || '', qty: round2(qty), unitCostCents: num(item.fields.unitCostCents) || 0, fixed: true };\n var lines = (o.fields.lines || []).slice();\n var at = -1;\n lines.forEach(function (l, i) {\n if (l.itemId === item.id) at = i;\n });\n if (qty === 0) {\n if (at >= 0) lines.splice(at, 1);\n } else if (at >= 0) lines[at] = line;\n else lines.push(line);\n if (!lines.length) {\n t.transition('orders', o.id, 'cancelled', 'Last line removed');\n msgs.push('Took ' + item.fields.name + ' off ' + o.id + ', which leaves nothing on it, so the draft is dropped.');\n } else {\n t.update('orders', o.id, { lines: lines, totalCents: orderTotal(lines) }, 'Line changed by hand');\n msgs.push(qty === 0 ? 'Took ' + item.fields.name + ' off ' + o.id + '; it now comes to ' + money(orderTotal(lines)) + '.' : o.id + ' now orders ' + amount(qty, item.fields.unit) + ' ' + item.fields.name + ', ' + money(orderTotal(lines)) + ' in all.');\n }\n }\n if (status === 'sent') {\n if (o.status !== 'draft') throw new Error(o.id + ' is already ' + o.status + '.');\n var lead = supplierLead(t.data.items, supplier);\n var today = localDay(nowMs);\n t.update('orders', o.id, lead !== null ? { sentAt: today, leadDays: lead, expectedAt: addDays(today, lead) } : { sentAt: today }, input.note ? String(input.note) : undefined);\n t.transition('orders', o.id, 'sent', 'Sent');\n msgs.push('Marked ' + o.id + ' to ' + supplier + ' sent' + (lead !== null ? '; with a ' + lead + '-day lead it should arrive by ' + addDays(today, lead) + '.' : '.'));\n } else if (status === 'received') {\n if (o.status === 'received' || o.status === 'cancelled') throw new Error(o.id + ' is already ' + o.status + '.');\n var got = [];\n (o.fields.lines || []).forEach(function (l) {\n var r = t.get('items', l.itemId);\n if (!r) return;\n var before = num(r.fields.onHand) || 0;\n var after = round2(before + (num(l.qty) || 0));\n t.update('items', r.id, { onHand: after }, 'Received ' + amount(l.qty, l.unit) + ' on ' + o.id + ': ' + round2(before) + ' to ' + after);\n syncStatus(t, r.id);\n got.push(r.fields.name + ' ' + round2(before) + ' to ' + amount(after, r.fields.unit));\n });\n t.update('orders', o.id, { receivedAt: localDay(nowMs) }, input.note ? String(input.note) : undefined);\n t.transition('orders', o.id, 'received', 'Received');\n msgs.push('Received ' + o.id + ' from ' + supplier + (got.length ? ' and added it to stock: ' + got.join(', ') + '.' : '.'));\n msgs = msgs.concat(refreshDrafts(t, false, null));\n } else if (status === 'cancelled') {\n if (o.status === 'received' || o.status === 'cancelled') throw new Error(o.id + ' is already ' + o.status + '.');\n t.transition('orders', o.id, 'cancelled', input.note ? String(input.note) : 'Cancelled');\n msgs.push('Cancelled ' + o.id + ' to ' + supplier + '.');\n }\n return msgs.join(' ');\n}\n\nfunction onOrderText(r, orders) {\n var o = orders.filter(function (x) {\n return (\n OPEN.indexOf(x.status) >= 0 &&\n (x.fields.lines || []).some(function (l) {\n return l.itemId === r.id;\n })\n );\n })[0];\n if (!o) return '';\n return o.status === 'draft' ? 'on draft ' + o.id : 'on order ' + o.id + (o.fields.expectedAt ? ', expected ' + o.fields.expectedAt : '');\n}\nfunction itemLine(r, orders) {\n var f = r.fields;\n var status = stockStatus(f);\n var onOrder = onOrderText(r, orders);\n var text =\n f.name + ' (' + r.id + '): ' + amount(num(f.onHand) || 0, f.unit) + ' on hand' + (status === 'ok' ? '' : ', ' + status) +\n ', reorder at ' + (num(f.reorderPoint) || 0) + (num(f.par) ? ', par ' + num(f.par) : '');\n if (status !== 'ok') {\n text += onOrder.indexOf('on order') === 0 ? '; ' + onOrder : '; order ' + amount(orderQty(f), f.unit) + (onOrder ? ' (' + onOrder + ')' : '');\n }\n text += f.supplier ? '; supplier ' + f.supplier + (num(f.leadDays) !== null ? ', ' + num(f.leadDays) + '-day lead' : '') : '; no supplier yet';\n return text;\n}\nfunction orderLine(o, nowMs) {\n var f = o.fields;\n var text = o.id + ' ' + f.supplier + ': ' + linesText(f.lines || []) + ', ' + money(num(f.totalCents) || 0);\n if (o.status === 'sent') text += ', sent ' + f.sentAt + (f.expectedAt ? ', expected ' + f.expectedAt + ' (' + when(daysUntil(f.expectedAt, nowMs)) + ')' : '');\n if (o.status === 'received') text += ', received ' + f.receivedAt;\n return text;\n}\nfunction urgency(a, b) {\n var sa = stockStatus(a.fields);\n var sb = stockStatus(b.fields);\n if (sa !== sb) return sa === 'out' ? -1 : sb === 'out' ? 1 : 0;\n var ra = (num(a.fields.onHand) || 0) / Math.max(1, num(a.fields.reorderPoint) || 1);\n var rb = (num(b.fields.onHand) || 0) / Math.max(1, num(b.fields.reorderPoint) || 1);\n return ra - rb || String(a.fields.name).localeCompare(String(b.fields.name));\n}\nfunction picture(items, orders, nowMs) {\n var needs = items\n .filter(function (r) {\n return stockStatus(r.fields) !== 'ok';\n })\n .sort(urgency);\n var out = needs.filter(function (r) {\n return stockStatus(r.fields) === 'out';\n }).length;\n var sent = orders\n .filter(function (o) {\n return o.status === 'sent';\n })\n .sort(function (a, b) {\n return String(a.fields.expectedAt || '').localeCompare(String(b.fields.expectedAt || ''));\n });\n var drafts = orders.filter(function (o) {\n return o.status === 'draft';\n });\n var parts = [items.length + (items.length === 1 ? ' item' : ' items') + ' tracked: ' + out + ' out, ' + (needs.length - out) + ' low.'];\n // One list, out first: asked \"what's running low\", a model reads a separate out-of-stock list as out of scope.\n parts.push(\n needs.length\n ? 'Running low or out, out first: ' + needs.map(function (r) { return itemLine(r, orders); }).join(' | ') + '.'\n : items.length\n ? 'Nothing is at or below its reorder point.'\n : 'Nothing tracked yet.',\n );\n if (sent.length) parts.push('On order: ' + sent.map(function (o) { return orderLine(o, nowMs); }).join(' | ') + '.');\n if (drafts.length) parts.push('Drafts for the person to check and send: ' + drafts.map(function (o) { return orderLine(o, nowMs); }).join(' | ') + '.');\n var list = suppliers(items);\n if (list.length) {\n parts.push(\n 'Suppliers: ' +\n list\n .map(function (s) {\n return s.name + (s.leadDays !== null ? ' (' + s.leadDays + '-day lead)' : ' (no lead time yet)');\n })\n .join(', ') +\n '.',\n );\n }\n return { out: out, low: needs.length - out, onOrder: sent.length, drafts: drafts.length, summary: parts.join(' ') };\n}\nfunction listing(items, orders, nowMs) {\n var lines = items\n .slice()\n .sort(function (a, b) {\n return String(a.fields.name).localeCompare(String(b.fields.name));\n })\n .map(function (r) {\n return '[' + stockStatus(r.fields) + '] ' + itemLine(r, orders) + (num(r.fields.unitCostCents) ? ', ' + money(r.fields.unitCostCents) + ' each' : '');\n });\n var open = orders.filter(function (o) {\n return OPEN.indexOf(o.status) >= 0;\n });\n var closed = orders\n .filter(function (o) {\n return OPEN.indexOf(o.status) < 0;\n })\n .slice(-5);\n open.concat(closed).forEach(function (o) {\n lines.push('[' + o.status + '] ' + orderLine(o, nowMs));\n });\n return lines.join('\\n') || 'Nothing tracked yet.';\n}\nfunction run(action, input, state, nowMs) {\n var t = transaction(state, nowMs);\n var note = '';\n input = input || {};\n if (action === 'add') note = addItem(t, input);\n else if (action === 'stock') note = recordStock(t, input, nowMs);\n else if (action === 'draft_orders') note = draftOrders(t, input);\n else if (action === 'update_order') note = updateOrder(t, input, nowMs);\n else if (action !== 'status' && action !== 'list') {\n throw new Error(\"Unknown action '\" + action + \"'. Use status, add, stock, draft_orders, update_order, or list.\");\n }\n var view = picture(t.data.items, t.data.orders, nowMs);\n return {\n ops: t.ops,\n state: t.data,\n output: {\n out: view.out,\n low: view.low,\n onOrder: view.onOrder,\n drafts: view.drafts,\n tracked: t.data.items.length,\n summary: action === 'list' ? listing(t.data.items, t.data.orders, nowMs) : (note ? note + ' ' : '') + view.summary,\n },\n };\n}\n// ── inventory-rules-end ──\n\nconst stores = {\n items: rosterStore(gezel.fs, 'items.json', { stages: ['ok', 'low', 'out'], idPrefix: 'it' }),\n orders: rosterStore(gezel.fs, 'orders.json', { stages: ['draft', 'sent', 'received', 'cancelled'], idPrefix: 'po' }),\n};\nconst before = { items: await stores.items.list(), orders: await stores.orders.list() };\nconst result = run(String(input.action), input, before, Date.now());\n// Replay the changes through the stores, in order, so the files keep their history.\nfor (const op of result.ops) {\n const store = stores[op.store as 'items' | 'orders'];\n if (op.op === 'add') await store.add({ id: op.id, status: op.status, fields: op.fields, note: op.note });\n else if (op.op === 'update') await store.update(op.id, { fields: op.fields, ...(op.note ? { note: op.note } : {}) });\n else await store.transition(op.id, op.to, op.note ? { note: op.note } : {});\n}\ngezel.output(result.output);\n"},"tools":[{"name":"stock_status","description":"What is out and running low (out first), each with its count, reorder point, the quantity to order, the supplier and lead time, plus orders on the way and drafts waiting, with ids. Call it first when asked what's low or what to order.","script":"inventory-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"},"state":true},{"name":"add_item","description":"Save a stock item: name, unit, how many are on hand now, the reorder point, the par level to order up to, supplier, their lead time in days, and the unit cost in dollars. An existing name is updated, never duplicated. Call it as soon as an item is mentioned, before you describe it.","script":"inventory-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"unit":{"type":"string","description":"How it is counted, e.g. 'carton', 'bag (5 lb)', 'sleeve of 50'."},"onHand":{"type":"number","description":"How many are on the shelf now (needed for a new item)."},"reorderPoint":{"type":"number","description":"Reorder when stock falls to this many or fewer."},"par":{"type":"number","description":"Order back up to this many."},"supplier":{"type":"string"},"leadDays":{"type":"number","description":"The supplier's lead time in days; it applies to every item from them."},"unitCost":{"type":"number","description":"Price per unit in dollars, e.g. 3.8."},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"add"}},{"name":"record_stock","description":"Record stock coming in or going out. Pass received (delivered) and used (sold, used or thrown out) exactly as the person said them; the store does the arithmetic, so never work out the new total yourself. Pass count only when they counted the shelf. Call it the moment they tell you.","script":"inventory-store","inputs":{"type":"object","properties":{"item":{"type":"string","description":"The item's name or id ('it-3')."},"received":{"type":"number","description":"How many came in, as the person said it. The store adds it."},"used":{"type":"number","description":"How many were sold, used or thrown out, as the person said it. The store takes it off."},"count":{"type":"number","description":"Only when they counted the shelf: the number counted."},"note":{"type":"string"}},"required":["item"]},"bind":{"action":"stock"}},{"name":"draft_orders","description":"Draft purchase orders, one per supplier, for every item at or below its reorder point that is not already on order; quantities fill each item back up to its par. Running it again updates the drafts, never duplicates them. The person checks and places them.","script":"inventory-store","inputs":{"type":"object","properties":{"supplier":{"type":"string","description":"Only this supplier; leave out for all of them."}}},"bind":{"action":"draft_orders"}},{"name":"update_order","description":"Change a purchase order: mark it sent when the person says they placed it, received when it arrived (its quantities go into stock), or cancelled; or set one item's quantity on a draft. Call it as soon as they tell you.","script":"inventory-store","inputs":{"type":"object","properties":{"order":{"type":"string","description":"Order id ('po-2') or the supplier's name."},"status":{"type":"string","enum":["sent","received","cancelled"]},"item":{"type":"string","description":"To change a draft: the item whose quantity to set."},"qty":{"type":"number","description":"To change a draft: the new quantity (0 takes the item off)."},"note":{"type":"string"}},"required":["order"]},"bind":{"action":"update_order"}},{"name":"list_stock","description":"Every item with its count, reorder point, par, supplier, lead time and price, and every open order.","script":"inventory-store","inputs":{"type":"object","properties":{}},"bind":{"action":"list"}},{"name":"page_add_item","description":"Add or update a stock item.","script":"inventory-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"unit":{"type":"string","description":"How it is counted, e.g. 'carton', 'bag (5 lb)', 'sleeve of 50'."},"onHand":{"type":"number","description":"How many are on the shelf now (needed for a new item)."},"reorderPoint":{"type":"number","description":"Reorder when stock falls to this many or fewer."},"par":{"type":"number","description":"Order back up to this many."},"supplier":{"type":"string"},"leadDays":{"type":"number","description":"The supplier's lead time in days; it applies to every item from them."},"unitCost":{"type":"number","description":"Price per unit in dollars, e.g. 3.8."},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"add"}},{"name":"page_record_stock","description":"Record stock received, used or counted.","script":"inventory-store","inputs":{"type":"object","properties":{"item":{"type":"string","description":"The item's name or id ('it-3')."},"received":{"type":"number","description":"How many came in, as the person said it. The store adds it."},"used":{"type":"number","description":"How many were sold, used or thrown out, as the person said it. The store takes it off."},"count":{"type":"number","description":"Only when they counted the shelf: the number counted."},"note":{"type":"string"}},"required":["item"]},"bind":{"action":"stock"},"reaction":{"gezel":"stock-keeper","prompt":"The person just logged stock on the inventory page. The stock list now reads (its first sentence is what changed):\n{{output.summary}}\nIn one or two short sentences, confirm the new count and, if that item is now low or out, say how many to order and from whom. Do not call tools.","hideSeed":true}},{"name":"page_draft_orders","description":"Draft purchase orders for everything at or below its reorder point.","script":"inventory-store","inputs":{"type":"object","properties":{"supplier":{"type":"string","description":"Only this supplier; leave out for all of them."}}},"bind":{"action":"draft_orders"}},{"name":"page_update_order","description":"Mark an order sent, received or cancelled.","script":"inventory-store","inputs":{"type":"object","properties":{"order":{"type":"string","description":"Order id ('po-2') or the supplier's name."},"status":{"type":"string","enum":["sent","received","cancelled"]},"item":{"type":"string","description":"To change a draft: the item whose quantity to set."},"qty":{"type":"number","description":"To change a draft: the new quantity (0 takes the item off)."},"note":{"type":"string"}},"required":["order"]},"bind":{"action":"update_order"},"reaction":{"gezel":"stock-keeper","prompt":"The person just updated a purchase order on the inventory page. The stock list now reads (its first sentence is what changed):\n{{output.summary}}\nIn two short sentences, confirm what changed: what went into stock, or when the order should arrive. Do not call tools.","hideSeed":true}}],"pages":{"entry":"stock/index.html","api":1,"reads":[{"source":"workspace","path":"items.json"},{"source":"workspace","path":"orders.json"}],"tools":["page_add_item","page_record_stock","page_draft_orders","page_update_order"]},"schedules":[],"workspaceSeed":["items.json","orders.json"],"artifactsSeed":[],"availableVersions":["1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"job-hunt","name":"Job Hunt","description":"Run your job search like a campaign — a career coach tracks every application through the pipeline, a mock interviewer gets you ready, and a live board keeps the whole slog navigable.","tags":["job","career","interview","resume","offer"],"category":"growth","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.6","releasedAt":"2026-11-02T18:00:00.000Z","extends":"job-hunt","meesterManaged":false,"params":{"type":"object","properties":{"role":{"type":"string","title":"What role are you hunting for?","description":"The role or title you're targeting — e.g. Staff Engineer, Product Designer, Data Analyst.","default":"Software Engineer"},"focus":{"type":"string","title":"Anything about your search?","description":"Optional context for your coach — location constraints, timeline, dream companies.","default":"Just getting started."}},"required":["role"]},"nameTemplate":"{{role}} Job Hunt","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"career-coach","voorman":true},{"templateId":"mock-interviewer","voorman":false}],"toolsets":[],"craftbooks":["tailor-resume","company-research-brief","mock-interview","offer-compare","weekly-pipeline-review"],"scripts":{"application-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { logStore, rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'application-store',\n description:\n \"Read and update the job-search pipeline (applications in pipeline.json, activity in activity.json). Call action:'status' at the start of a session to see where the search stands; 'record_application' the moment the user mentions applying somewhere; 'advance_stage' when reality moves; 'log_activity' for follow-ups, scheduled interviews, and thank-yous.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'status', 'record_application', 'advance_stage', or 'log_activity'.\",\n required: true,\n },\n company: { type: 'string', description: 'Company name (identifies the application when id is omitted).' },\n role: { type: 'string', description: 'Role title for a new application.' },\n link: { type: 'string', description: 'Posting or application link.' },\n notes: { type: 'string', description: 'Free-form notes for a new application.' },\n id: { type: 'string', description: \"Application id (e.g. 'acme-staff-engineer') when advancing or logging.\" },\n stage: {\n type: 'string',\n description: 'Target stage for advance_stage: applied, screening, interview, offer, or closed.',\n },\n outcome: { type: 'string', description: \"With stage 'closed': signed, rejected, or withdrawn.\" },\n kind: {\n type: 'string',\n description: \"Activity kind for log_activity: follow-up, interview-scheduled, thank-you, offer-received, or note.\",\n },\n note: { type: 'string', description: 'The activity note for log_activity, or a note on a stage change.' },\n due: { type: 'string', description: 'Due date (ISO) for a follow-up.' },\n },\n outputs: {\n applications: { type: 'number', description: 'Total applications tracked.' },\n summary: { type: 'string', description: 'Human-readable pipeline summary.' },\n stale: { type: 'json', description: 'Active applications untouched for over 7 days.' },\n followUps: { type: 'json', description: 'Follow-ups due within 7 days or overdue.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\nconst STAGES: [string, ...string[]] = ['applied', 'screening', 'interview', 'offer', 'closed'];\nconst OUTCOMES = ['signed', 'rejected', 'withdrawn'];\nconst WEEK_MS = 7 * 24 * 60 * 60 * 1000;\n\nconst roster = rosterStore(gezel.fs, 'pipeline.json', { stages: STAGES, idPrefix: 'app' });\nconst activity = logStore(gezel.fs, 'activity.json');\n\nfunction slugify(s: string): string {\n return (\n s\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '') || 'application'\n );\n}\n\nasync function freshId(company: string, role?: string): Promise<string> {\n const base = slugify(role ? `${company} ${role}` : company);\n let candidate = base;\n for (let n = 2; (await roster.get(candidate)) !== null; n += 1) {\n candidate = `${base}-${n}`;\n }\n return candidate;\n}\n\nasync function resolveId(): Promise<string> {\n if (input.id) {\n if ((await roster.get(input.id)) === null) throw new Error(`No application '${input.id}'.`);\n return input.id;\n }\n if (input.company) {\n const wanted = input.company.toLowerCase();\n const matches = (await roster.list()).filter(\n (r) => String(r.fields.company ?? '').toLowerCase() === wanted,\n );\n if (matches.length === 1) return matches[0]!.id;\n if (matches.length > 1) {\n throw new Error(\n `Multiple applications match company '${input.company}': ${matches.map((m) => m.id).join(', ')}. Pass id.`,\n );\n }\n }\n throw new Error(\"Pass 'id' or a unique 'company' to identify the application.\");\n}\n\nasync function summarize(): Promise<{\n applications: number;\n summary: string;\n stale: unknown[];\n followUps: unknown[];\n}> {\n const records = await roster.list();\n const counts = await roster.counts();\n const now = Date.now();\n const stale = records\n .filter((r) => r.status !== 'closed' && now - Date.parse(r.updatedAt) > WEEK_MS)\n .map((r) => ({\n id: r.id,\n company: r.fields.company ?? r.id,\n stage: r.status,\n daysQuiet: Math.floor((now - Date.parse(r.updatedAt)) / (24 * 60 * 60 * 1000)),\n }));\n const events = await activity.list();\n const closed = new Set(records.filter((r) => r.status === 'closed').map((r) => r.id));\n // A follow-up is answered by a closed application or any later touch on it\n // (a stage move, an interview, another note); otherwise it stays due forever.\n const answered = (e: { at: string; data?: Record<string, unknown> }): boolean => {\n const app = e.data?.applicationId;\n if (typeof app !== 'string') return false;\n if (closed.has(app)) return true;\n const at = Date.parse(e.at);\n return events.some((later) => later !== e && later.data?.applicationId === app && Date.parse(later.at) > at);\n };\n const followUps = events\n .filter((e) => {\n if (e.kind !== 'follow-up' || answered(e)) return false;\n const due = typeof e.data?.dueAt === 'string' ? Date.parse(e.data.dueAt) : null;\n return due !== null && due <= now + WEEK_MS;\n })\n .map((e) => ({\n note: e.note ?? '',\n dueAt: e.data?.dueAt,\n applicationId: e.data?.applicationId,\n overdue: typeof e.data?.dueAt === 'string' && Date.parse(e.data.dueAt) < now,\n }));\n const active = records.filter((r) => r.status !== 'closed').length;\n const stageLine = STAGES.filter((s) => (counts[s] ?? 0) > 0)\n .map((s) => `${s} ${counts[s]}`)\n .join(', ');\n const summary = records.length\n ? `${active} application(s) in play (${stageLine || 'none'}). ${stale.length} stale, ${followUps.length} follow-up(s) due this week.`\n : 'No applications tracked yet.';\n return { applications: records.length, summary, stale, followUps };\n}\n\nif (input.action === 'record_application') {\n if (!input.company) throw new Error(\"record_application needs 'company'.\");\n const id = await freshId(input.company, input.role);\n const record = await roster.add({\n id,\n fields: {\n company: input.company,\n ...(input.role ? { role: input.role } : {}),\n ...(input.link ? { link: input.link } : {}),\n ...(input.notes ? { notes: input.notes } : {}),\n },\n });\n await activity.append({\n kind: 'applied',\n note: `Applied to ${input.company}${input.role ? ` for ${input.role}` : ''}.`,\n data: { applicationId: record.id },\n });\n} else if (input.action === 'advance_stage') {\n if (!input.stage) throw new Error(\"advance_stage needs 'stage'.\");\n if (!STAGES.includes(input.stage)) {\n throw new Error(`Unknown stage '${input.stage}'. Stages: ${STAGES.join(', ')}.`);\n }\n if (input.outcome && input.stage !== 'closed') {\n throw new Error(\"'outcome' only applies when closing (stage 'closed').\");\n }\n if (input.outcome && !OUTCOMES.includes(input.outcome)) {\n throw new Error(`Unknown outcome '${input.outcome}'. Outcomes: ${OUTCOMES.join(', ')}.`);\n }\n const id = await resolveId();\n await roster.transition(id, input.stage, input.note ? { note: input.note } : {});\n if (input.outcome) await roster.update(id, { fields: { outcome: input.outcome } });\n const company = String((await roster.get(id))?.fields.company ?? id);\n await activity.append({\n kind: 'stage',\n note: `${company} moved to ${input.stage}${input.outcome ? ` (${input.outcome})` : ''}.`,\n data: { applicationId: id },\n });\n} else if (input.action === 'log_activity') {\n if (!input.note) throw new Error(\"log_activity needs 'note'.\");\n let applicationId: string | undefined;\n if (input.id || input.company) {\n applicationId = await resolveId();\n // A logged touch counts as attention — it resets the staleness clock.\n await roster.update(applicationId, input.note ? { note: input.note } : {});\n }\n await activity.append({\n kind: input.kind ?? 'note',\n note: input.note,\n data: {\n ...(applicationId ? { applicationId } : {}),\n ...(input.due ? { dueAt: input.due } : {}),\n },\n });\n} else if (input.action !== 'status') {\n throw new Error(\n `Unknown action '${input.action}'. Use status, record_application, advance_stage, or log_activity.`,\n );\n}\n\ngezel.output(await summarize());\n"},"tools":[{"name":"record_application","description":"Track a new job application the moment it happens.","script":"application-store","inputs":{"type":"object","properties":{"company":{"type":"string","description":"Company name."},"role":{"type":"string","description":"Role title."},"link":{"type":"string","description":"Posting or application link."},"notes":{"type":"string","description":"Anything worth remembering about this one."}},"required":["company"]},"bind":{"action":"record_application"}},{"name":"advance_stage","description":"Move an application to a new pipeline stage (applied, screening, interview, offer, closed).","script":"application-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Application id."},"company":{"type":"string","description":"Company name (when id is omitted)."},"stage":{"type":"string","enum":["applied","screening","interview","offer","closed"],"description":"The stage reality moved to."},"note":{"type":"string","description":"What happened."},"outcome":{"type":"string","enum":["signed","rejected","withdrawn"],"description":"Only when closing: how it ended."}},"required":["stage"]},"bind":{"action":"advance_stage"}},{"name":"log_activity","description":"Log activity on the search — a follow-up to send, an interview scheduled, a thank-you sent.","script":"application-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Application id this activity belongs to."},"company":{"type":"string","description":"Company name (when id is omitted)."},"kind":{"type":"string","enum":["follow-up","interview-scheduled","thank-you","offer-received","note"],"description":"What kind of activity this is."},"note":{"type":"string","description":"The activity itself."},"due":{"type":"string","description":"Due date (ISO) for a follow-up."}},"required":["note"]},"bind":{"action":"log_activity"}},{"name":"pipeline_status","description":"See the whole pipeline: counts per stage, stale applications, and follow-ups due this week.","script":"application-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"}},{"name":"page_record_application","description":"Track a new job application the moment it happens.","script":"application-store","inputs":{"type":"object","properties":{"company":{"type":"string","description":"Company name."},"role":{"type":"string","description":"Role title."},"link":{"type":"string","description":"Posting or application link."},"notes":{"type":"string","description":"Anything worth remembering about this one."}},"required":["company"]},"bind":{"action":"record_application"}},{"name":"page_advance_stage","description":"Move an application to a new pipeline stage (applied, screening, interview, offer, closed).","script":"application-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Application id."},"company":{"type":"string","description":"Company name (when id is omitted)."},"stage":{"type":"string","enum":["applied","screening","interview","offer","closed"],"description":"The stage reality moved to."},"note":{"type":"string","description":"What happened."},"outcome":{"type":"string","enum":["signed","rejected","withdrawn"],"description":"Only when closing: how it ended."}},"required":["stage"]},"bind":{"action":"advance_stage"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"pipeline.json"},{"source":"workspace","path":"activity.json"}],"tools":["page_record_application","page_advance_stage"]},"schedules":[{"runMode":"scheduled","cron":"0 17 * * 5","craftbook":"weekly-pipeline-review","consent":"ask","overlap":"skip"}],"workspaceSeed":["pipeline.json","activity.json"],"artifactsSeed":[],"availableVersions":["1.0.6","1.0.5","1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"language-trainer","name":"Language Trainer","description":"Practice a new language by chatting with a patient tutor who corrects gently and tracks your progress. Comes with a progress dashboard.","tags":["language","learning","tutor","conversation"],"category":"growth","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.1.2","releasedAt":"2026-11-02T18:00:00.000Z","extends":"content-writing","meesterManaged":false,"leanProfile":true,"params":{"type":"object","properties":{"language":{"type":"string","title":"Which language?","description":"The language you want to practice, e.g. Spanish, Japanese, French.","default":"Spanish"}},"required":["language"]},"nameTemplate":"{{language}} Language Trainer","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"language-trainer","voorman":true}],"toolsets":[],"craftbooks":[],"scripts":{"progress-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\n\nexport const meta = defineScript({\n name: 'progress-store',\n description:\n \"The language trainer's state: progress, the role-play scene in play, and the review deck of the student's corrections. action:'state' reads it; 'begin' starts a scene; 'reply' records the tutor's line and the errors it found in the student's last message; 'review' grades a review card; 'end' closes the scene; 'advance' moves up a level.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'state', 'begin', 'reply', 'review', 'end', 'advance' (or the older 'status', 'record').\",\n required: true,\n },\n scenario: { type: 'string', description: \"For begin: a scenario id or title, e.g. 'coffee'.\" },\n say: { type: 'string', description: \"For reply: the tutor's next line, in the language being practiced.\" },\n errors: {\n type: 'json',\n description: \"For reply: mistakes in the student's last message, [{ wrong, right, note? }], at most 3.\",\n },\n done: { type: 'boolean', description: \"For reply: true when the scene's goal is reached.\" },\n id: { type: 'string', description: \"For review: the review card id, e.g. 'r-3'.\" },\n verdict: { type: 'string', description: \"For review: 'got-it' or 'missed'.\" },\n note: { type: 'string', description: 'For advance or record: a short note.' },\n },\n outputs: {\n status: { type: 'string', description: \"'active' while a scene is in play, else 'idle' (or 'started' / 'done').\" },\n display: { type: 'string', description: \"For reply: the tutor's line plus the corrections, as shown.\" },\n level: { type: 'number', description: 'Current level (1+).' },\n streak: { type: 'number', description: 'Days in a row with practice.' },\n dueCount: { type: 'number', description: 'Review cards due now.' },\n message: { type: 'string', description: 'A short summary of the state.' },\n scene: { type: 'json', description: 'The scene in play: title, the part the tutor plays, setting, goal.' },\n dueReviews: { type: 'json', description: 'Up to three corrections due for review, { wrong, right }.' },\n scenarios: { type: 'json', description: 'Scenario ids open at this level (when no scene is in play).' },\n opening: { type: 'boolean', description: 'True right after begin: the tutor opens the scene.' },\n },\n requires: ['workspace.read', 'workspace.write', 'memory.write', 'reminders'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── review-rules-start ──\n// Corrections become review cards on three Leitner boxes: box 1 comes back\n// the next day, box 2 after three days, box 3 after a week. A card the\n// student gets right moves up; a miss, or the same mistake made again in\n// conversation, sends it back to box 1. Kept self-contained between these\n// sentinels so unit tests execute the shipped bytes.\nvar REVIEW_INTERVAL_DAYS = { 1: 1, 2: 3, 3: 7 };\nvar REVIEW_DAY_MS = 24 * 60 * 60 * 1000;\n\nfunction reviewDueAt(card) {\n if (!card.lastSeenAt) return 0;\n return Date.parse(card.lastSeenAt) + (REVIEW_INTERVAL_DAYS[card.box] || 1) * REVIEW_DAY_MS;\n}\n\nfunction dueReviews(cards, nowMs) {\n return cards\n .filter(function (c) {\n return reviewDueAt(c) <= nowMs;\n })\n .sort(function (a, b) {\n return a.box - b.box || reviewDueAt(a) - reviewDueAt(b);\n });\n}\n\nfunction nextReviewAt(cards, nowMs) {\n var next = Infinity;\n for (var i = 0; i < cards.length; i += 1) {\n var at = reviewDueAt(cards[i]);\n if (at > nowMs && at < next) next = at;\n }\n return next;\n}\n\nfunction cleanText(value, max) {\n return typeof value === 'string' ? value.replace(/\\s+/g, ' ').trim().slice(0, max) : '';\n}\n\n// The grading the model returned, made safe to store: at most three\n// mistakes, each a real change, without duplicates.\nfunction normalizeErrors(raw) {\n var list = Array.isArray(raw) ? raw : [];\n var out = [];\n for (var i = 0; i < list.length && out.length < 3; i += 1) {\n var e = list[i] || {};\n var wrong = cleanText(e.wrong, 80);\n var right = cleanText(e.right, 80);\n if (!wrong || !right || wrong.toLowerCase() === right.toLowerCase()) continue;\n if (out.some(function (o) { return o.wrong.toLowerCase() === wrong.toLowerCase(); })) continue;\n var note = cleanText(e.note, 80);\n out.push(note ? { wrong: wrong, right: right, note: note } : { wrong: wrong, right: right });\n }\n return out;\n}\n\n// Each mistake joins the deck, or sends its card back to box 1.\nfunction addCorrections(cards, errors, nowIso) {\n var max = 0;\n for (var i = 0; i < cards.length; i += 1) {\n var m = /^r-(\\d+)$/.exec(cards[i].id);\n if (m) max = Math.max(max, Number(m[1]));\n }\n for (var j = 0; j < errors.length; j += 1) {\n var e = errors[j];\n var found = cards.find(function (c) {\n return c.wrong.toLowerCase() === e.wrong.toLowerCase() && c.right.toLowerCase() === e.right.toLowerCase();\n });\n if (found) {\n found.box = 1;\n found.lastSeenAt = nowIso;\n found.repeats = (found.repeats || 0) + 1;\n } else {\n max += 1;\n cards.push({\n id: 'r-' + max,\n wrong: e.wrong,\n right: e.right,\n note: e.note || '',\n box: 1,\n lastSeenAt: nowIso,\n createdAt: nowIso,\n repeats: 0,\n });\n }\n }\n return cards;\n}\n\nfunction gradeReview(card, verdict, nowIso) {\n card.box = verdict === 'got-it' ? Math.min(3, card.box + 1) : 1;\n card.lastSeenAt = nowIso;\n return card;\n}\n\n// What the student sees: the tutor's line, then the corrections the app\n// recorded, so feedback never depends on the model writing it out.\nfunction displayLine(say, errors, done) {\n var text = say;\n if (errors.length) {\n text +=\n ' — Corrections: ' +\n errors\n .map(function (e) {\n return '\"' + e.wrong + '\" → \"' + e.right + '\"' + (e.note ? ' (' + e.note + ')' : '');\n })\n .join('; ') +\n '.';\n }\n if (done) text += ' Scene complete.';\n return text;\n}\n\n// The streak counts calendar days with practice, in the device's time zone.\nfunction practiceDay(nowMs) {\n var d = new Date(nowMs);\n return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');\n}\n\nfunction nextStreak(streak, lastDay, nowMs) {\n var today = practiceDay(nowMs);\n if (lastDay === today) return streak || 1;\n return lastDay === practiceDay(nowMs - REVIEW_DAY_MS) ? (streak || 0) + 1 : 1;\n}\n// ── review-rules-end ──\n\ninterface Scene {\n id: string;\n title: string;\n role: string;\n setting: string;\n goal: string;\n level: number;\n status: 'active' | 'done';\n turns: number;\n mistakes: number;\n startedAt: string;\n}\n\ninterface Progress {\n language: string;\n level: number;\n sessions: number;\n streak: number;\n lastPracticeDay: string | null;\n scene: Scene | null;\n history: Array<{ day: string; scene: string; turns: number; mistakes: number }>;\n notes: string[];\n}\n\ninterface Scenario {\n id: string;\n title: string;\n level: number;\n role: string;\n setting: string;\n goal: string;\n}\n\ninterface ReviewCard {\n id: string;\n wrong: string;\n right: string;\n note: string;\n box: number;\n lastSeenAt: string | null;\n createdAt: string;\n repeats: number;\n}\n\nasync function readJson<T>(path: string, fallback: T): Promise<T> {\n try {\n return JSON.parse(await gezel.fs.read(path)) as T;\n } catch {\n return fallback;\n }\n}\n\nasync function writeJson(path: string, value: unknown): Promise<void> {\n await gezel.fs.write(path, `${JSON.stringify(value, null, 2)}\\n`);\n}\n\nconst nowMs = Date.now();\nconst nowIso = new Date(nowMs).toISOString();\nconst raw = await readJson<Partial<Progress>>('progress.json', {});\nconst progress: Progress = {\n language: raw.language ?? 'your language',\n level: raw.level ?? 1,\n sessions: raw.sessions ?? 0,\n streak: raw.streak ?? 0,\n lastPracticeDay: raw.lastPracticeDay ?? null,\n scene: raw.scene ?? null,\n history: Array.isArray(raw.history) ? raw.history : [],\n notes: Array.isArray(raw.notes) ? raw.notes : [],\n};\nconst scenarios = (await readJson<{ scenarios?: Scenario[] }>('scenarios.json', {})).scenarios ?? [];\nconst deck = await readJson<{ items?: ReviewCard[] }>('reviews.json', {});\nconst cards: ReviewCard[] = Array.isArray(deck.items) ? deck.items : [];\n\nlet status: string = progress.scene?.status === 'active' ? 'active' : 'idle';\nlet display = '';\nlet progressChanged = false;\nlet cardsChanged = false;\n\nfunction findScenario(query: string): Scenario | undefined {\n const q = query.trim().toLowerCase();\n return (\n scenarios.find((s) => s.id === q) ??\n scenarios.find((s) => s.title.toLowerCase() === q) ??\n scenarios.find((s) => s.title.toLowerCase().includes(q) || q.includes(s.id))\n );\n}\n\nfunction practiced(): void {\n progress.streak = nextStreak(progress.streak, progress.lastPracticeDay, nowMs);\n progress.lastPracticeDay = practiceDay(nowMs);\n}\n\nfunction closeScene(): void {\n const scene = progress.scene;\n if (!scene || scene.status !== 'active') return;\n scene.status = 'done';\n progress.sessions += 1;\n progress.history = [\n ...progress.history,\n { day: practiceDay(nowMs), scene: scene.title, turns: scene.turns, mistakes: scene.mistakes },\n ].slice(-30);\n status = 'done';\n}\n\nswitch (input.action) {\n case 'begin': {\n const scenario = findScenario(String(input.scenario ?? ''));\n if (!scenario) {\n throw new Error(\n `No scenario '${input.scenario ?? ''}'. Choose one of: ${scenarios.map((s) => s.id).join(', ')}.`,\n );\n }\n progress.scene = {\n id: scenario.id,\n title: scenario.title,\n role: scenario.role,\n setting: scenario.setting,\n goal: scenario.goal,\n level: progress.level,\n status: 'active',\n turns: 0,\n mistakes: 0,\n startedAt: nowIso,\n };\n status = 'started';\n progressChanged = true;\n break;\n }\n case 'reply': {\n const say = String(input.say ?? '').replace(/\\s+/g, ' ').trim().slice(0, 240);\n if (!say) throw new Error(\"reply needs 'say': your next line, in the language being practiced.\");\n const errors = normalizeErrors(input.errors);\n if (errors.length) {\n addCorrections(cards, errors, nowIso);\n cardsChanged = true;\n for (const e of errors) {\n const text = `Said \"${e.wrong}\"; it is \"${e.right}\"${e.note ? ` (${e.note})` : ''}`.slice(0, 200);\n try {\n await gezel.memory.save(text, { kind: 'correction', scope: 'gezel' });\n } catch {\n // Memory is a bonus; the deck already holds the correction.\n }\n }\n }\n if (progress.scene?.status === 'active') {\n progress.scene.turns += 1;\n progress.scene.mistakes += errors.length;\n }\n practiced();\n // A scene ends once the student has played it: never on the opener, and\n // not before two lines of their own (a small model marked its first line done).\n const finished = input.done === true && (progress.scene?.turns ?? 0) >= 3;\n if (finished) closeScene();\n display = displayLine(say, errors, finished);\n progressChanged = true;\n break;\n }\n case 'review': {\n const card = cards.find((c) => c.id === input.id);\n if (!card || (input.verdict !== 'got-it' && input.verdict !== 'missed'))\n throw new Error(\"review needs a card 'id' and verdict 'got-it' or 'missed'.\");\n gradeReview(card, input.verdict, nowIso);\n cardsChanged = true;\n practiced();\n progressChanged = true;\n break;\n }\n case 'end': {\n closeScene();\n progressChanged = true;\n break;\n }\n case 'advance': {\n progress.level += 1;\n progress.notes = [\n ...progress.notes,\n `Advanced to level ${progress.level}${input.note ? `: ${input.note}` : ''}`,\n ].slice(-20);\n progressChanged = true;\n break;\n }\n case 'record': {\n practiced();\n if (input.note) progress.notes = [...progress.notes, String(input.note)].slice(-20);\n progressChanged = true;\n break;\n }\n case 'state':\n case 'status':\n break;\n default:\n throw new Error(`Unknown action '${input.action}'.`);\n}\n\nif (progressChanged) await writeJson('progress.json', progress);\nif (cardsChanged) {\n await writeJson('reviews.json', { items: cards });\n // The next card coming due is the one moment a reminder is earned.\n const next = nextReviewAt(cards, nowMs);\n try {\n if (Number.isFinite(next)) {\n const count = dueReviews(cards, next).length;\n await gezel.reminder.set({\n at: new Date(next).toISOString(),\n title: `${progress.language} review`,\n body: `${count} correction${count === 1 ? '' : 's'} ready to practice.`,\n });\n } else await gezel.reminder.clear();\n } catch {\n // A host without reminders still keeps the deck.\n }\n}\n\nconst due = dueReviews(cards, nowMs);\nconst scene = progress.scene;\nconst levelScenes = scenarios.filter((s) => s.level <= progress.level).map((s) => s.id);\ngezel.output({\n status,\n display,\n level: progress.level,\n streak: progress.streak,\n dueCount: due.length,\n scene:\n scene && scene.status === 'active'\n ? {\n title: scene.title,\n youPlay: scene.role,\n setting: scene.setting,\n studentGoal: scene.goal,\n turnsSoFar: scene.turns,\n }\n : null,\n opening: status === 'started',\n dueReviews: due.slice(0, 3).map((c) => ({ wrong: c.wrong, right: c.right })),\n scenarios: status === 'idle' ? levelScenes : [],\n message:\n status === 'active' || status === 'started'\n ? `Scene \"${scene?.title}\": you play the ${scene?.role}. First check the student's last message for mistakes (word gender, verb forms, agreement, word choice) and list each one in errors as { wrong, right }. Then answer in character, only in ${progress.language}.`\n : `Learning ${progress.language}: level ${progress.level}, ${progress.sessions} scene(s), ${progress.streak}-day streak, ${due.length} review(s) due.`,\n});\n"},"tools":[{"name":"practice_state","description":"Read the practice state: the scene in play (the part you play, the setting, the student's goal), the student's level and streak, and corrections due for review.","script":"progress-store","inputs":{"type":"object","properties":{}},"bind":{"action":"state"},"state":true,"answer":{"tool":"reply","when":{"op":"equals","field":"status","value":"active"}}},{"name":"reply","description":"Answer the student during a scene. `say` is your next line in the language being practiced, in character and at their level (one or two short sentences). `errors` lists up to three mistakes in the student's last message as { wrong, right, note? }, quoting their exact words in `wrong`; leave it empty when they made none. Set `done` only after the student has reached the scene's goal, never on your opening line.","script":"progress-store","inputs":{"type":"object","properties":{"say":{"type":"string","description":"Your next line, in the language being practiced (max 240 characters)."},"errors":{"type":"array","description":"Mistakes in the student's last message, at most three; an empty list when there were none.","items":{"type":"object","properties":{"wrong":{"type":"string","description":"The student's exact words."},"right":{"type":"string","description":"The corrected form."},"note":{"type":"string","description":"A very short reason, in English."}},"required":["wrong","right"]}},"done":{"type":"boolean","description":"True when the student reached the scene's goal."}},"required":["say","errors"]},"bind":{"action":"reply"},"turn":{"say":"say","fallback":"Your turn.","show":"display"}},{"name":"begin_scene","description":"Start a role-play scene the student asked for, by scenario id or title (coffee, market, neighbor, directions, pharmacy, luggage, restaurant, hotel, doctor, return). Then open it with reply.","script":"progress-store","inputs":{"type":"object","properties":{"scenario":{"type":"string","description":"Scenario id or title."}},"required":["scenario"]},"bind":{"action":"begin"}},{"name":"advance_level","description":"Advance the student to the next level when the current scenes feel comfortable.","script":"progress-store","inputs":{"type":"object","properties":{"note":{"type":"string"}}},"bind":{"action":"advance"}},{"name":"start_scene","description":"Start a scene from the dashboard.","script":"progress-store","inputs":{"type":"object","properties":{"scenario":{"type":"string"}},"required":["scenario"]},"bind":{"action":"begin"},"reaction":{"gezel":"language-trainer","prompt":"The student started the scene \"{{output.scene.title}}\". You play the {{output.scene.youPlay}}. Setting: {{output.scene.setting}} The student's goal: {{output.scene.studentGoal}} Open the scene with one short line in {{language}}, in character and at level {{output.level}}, through reply with no errors. The scene has only begun: do not set done.","hideSeed":true,"standalone":true,"turn":{"tool":"reply","when":{"op":"equals","field":"status","value":"started"}}}},{"name":"review_card","description":"Grade a review card from the dashboard.","script":"progress-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"verdict":{"type":"string"}},"required":["id","verdict"]},"bind":{"action":"review"}},{"name":"end_scene","description":"End the scene in play from the dashboard.","script":"progress-store","inputs":{"type":"object","properties":{}},"bind":{"action":"end"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"progress.json"},{"source":"workspace","path":"scenarios.json"},{"source":"workspace","path":"reviews.json"}],"tools":["start_scene","review_card","end_scene"]},"schedules":[],"workspaceSeed":["progress.json","scenarios.json","reviews.json"],"artifactsSeed":[],"availableVersions":["1.1.2","1.1.1","1.1.0","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"life-binder","name":"Life Binder","description":"The \"in case of emergency\" file, actually complete. A gentle archivist tracks wills, policies, accounts, and instructions — what exists, where it lives, what's missing.","tags":["estate","documents","emergency","family","insurance"],"category":"money","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.6","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"household":{"type":"string","title":"Who is this binder for?","description":"e.g. 'our family', 'Mom', 'me'.","default":"our family"}},"required":["household"]},"nameTemplate":"Life Binder","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"archivaris","voorman":true}],"toolsets":[],"craftbooks":["annual-document-review"],"scripts":{"binder-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'binder-store',\n description:\n \"Read and update the life binder (documents.json). Call action:'status' for the completeness picture; 'record_document' when a document exists (name + where the original lives); 'mark_missing' / 'mark_reviewed' as reality changes; 'checklist' to read everything.\",\n inputs: {\n action: {\n type: 'string',\n description:\n \"One of 'status', 'record_document', 'mark_missing', 'mark_reviewed', or 'checklist'.\",\n required: true,\n },\n name: { type: 'string', description: \"Document name, e.g. 'Will', 'Home insurance policy'.\" },\n location: { type: 'string', description: 'Where the original lives (drawer, safe, provider).' },\n note: { type: 'string', description: 'Anything a trusted person should know about it.' },\n id: { type: 'string', description: \"Document id, e.g. 'doc-2'.\" },\n },\n outputs: {\n total: { type: 'number', description: 'Documents on the checklist.' },\n present: { type: 'number', description: 'Recorded as existing.' },\n missing: { type: 'number', description: 'Known gaps.' },\n stale: { type: 'number', description: 'Present but unreviewed for over a year.' },\n summary: { type: 'string', description: 'The completeness picture.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── binder-rules-start ──\n// Pure derivations over rosterStore-shaped document records: statuses are\n// missing -> present; staleness is derived (present + unreviewed > 365d).\n\nvar YEAR_MS = 365 * 24 * 60 * 60 * 1000;\n\nfunction isStale(record, nowMs) {\n if (record.status !== 'present') return false;\n var reviewed = record.fields && typeof record.fields.reviewedAt === 'string'\n ? Date.parse(record.fields.reviewedAt)\n : Date.parse(record.updatedAt);\n return isFinite(reviewed) && nowMs - reviewed > YEAR_MS;\n}\n\nfunction binderShape(records, nowMs) {\n var present = 0;\n var missing = [];\n var stale = [];\n records.forEach(function (r) {\n if (r.status === 'present') {\n present += 1;\n if (isStale(r, nowMs)) stale.push(r);\n } else {\n missing.push(r);\n }\n });\n return { present: present, missing: missing, stale: stale };\n}\n\nfunction binderLine(records, nowMs) {\n var shape = binderShape(records, nowMs);\n var gaps = shape.missing\n .map(function (r) {\n return r.fields && r.fields.name ? r.fields.name : r.id;\n })\n .join(', ');\n var staleNames = shape.stale\n .map(function (r) {\n return r.fields && r.fields.name ? r.fields.name : r.id;\n })\n .join(', ');\n return (\n shape.present +\n ' of ' +\n records.length +\n ' in place' +\n (gaps ? '. Missing: ' + gaps : '. Nothing missing') +\n (staleNames ? '. Due a review: ' + staleNames + '.' : '.')\n );\n}\n// ── binder-rules-end ──\n\nconst binder = rosterStore(gezel.fs, 'documents.json', {\n stages: ['missing', 'present'],\n idPrefix: 'doc',\n});\n\nasync function resolveDoc(): Promise<string> {\n if (input.id) return input.id;\n if (input.name) {\n const wanted = input.name.toLowerCase();\n const matches = (await binder.list()).filter(\n (r) => String(r.fields.name ?? '').toLowerCase() === wanted,\n );\n if (matches.length === 1) return matches[0]!.id;\n }\n throw new Error(\"Pass 'id' (e.g. 'doc-2') or an exact document 'name'.\");\n}\n\nif (input.action === 'record_document') {\n if (!input.name) throw new Error(\"record_document needs 'name'.\");\n const existing = (await binder.list()).find(\n (r) => String(r.fields.name ?? '').toLowerCase() === input.name!.toLowerCase(),\n );\n if (existing) {\n await binder.update(existing.id, {\n fields: {\n ...(input.location ? { location: input.location } : {}),\n ...(input.note ? { note: input.note } : {}),\n reviewedAt: new Date().toISOString(),\n },\n });\n await binder.transition(existing.id, 'present');\n } else {\n await binder.add({\n status: 'present',\n fields: {\n name: input.name,\n ...(input.location ? { location: input.location } : {}),\n ...(input.note ? { note: input.note } : {}),\n reviewedAt: new Date().toISOString(),\n },\n });\n }\n} else if (input.action === 'mark_missing') {\n await binder.transition(await resolveDoc(), 'missing');\n} else if (input.action === 'mark_reviewed') {\n const id = await resolveDoc();\n await binder.update(id, { fields: { reviewedAt: new Date().toISOString() } });\n await binder.transition(id, 'present');\n} else if (input.action !== 'status' && input.action !== 'checklist') {\n throw new Error(\n `Unknown action '${input.action}'. Use status, record_document, mark_missing, mark_reviewed, or checklist.`,\n );\n}\n\nconst records = await binder.list();\nconst shape = binderShape(records, Date.now());\nconst listing =\n input.action === 'checklist'\n ? records\n .map(\n (r) =>\n `${r.id} [${r.status}${isStale(r, Date.now()) ? ', stale' : ''}] ${String(r.fields.name ?? '?')}${r.fields.location ? ` — ${String(r.fields.location)}` : ''}`,\n )\n .join('\\n') || 'The checklist is empty.'\n : '';\n\ngezel.output({\n total: records.length,\n present: shape.present,\n missing: shape.missing.length,\n stale: shape.stale.length,\n summary: listing || binderLine(records, Date.now()),\n});\n"},"tools":[{"name":"record_document","description":"Record that a document exists and where the original lives.","script":"binder-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"location":{"type":"string"},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"record_document"}},{"name":"mark_missing","description":"Mark a checklist item as a known gap.","script":"binder-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"}}},"bind":{"action":"mark_missing"}},{"name":"mark_reviewed","description":"Confirm a document was just reviewed and is current.","script":"binder-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"}}},"bind":{"action":"mark_reviewed"}},{"name":"binder_status","description":"The completeness picture: what's in place, missing, or due a review.","script":"binder-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"}},{"name":"checklist","description":"Read the whole checklist with locations.","script":"binder-store","inputs":{"type":"object","properties":{}},"bind":{"action":"checklist"}},{"name":"page_record_document","description":"Record that a document exists and where the original lives.","script":"binder-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"location":{"type":"string"},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"record_document"}},{"name":"page_mark_reviewed","description":"Confirm a document was just reviewed and is current.","script":"binder-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"}}},"bind":{"action":"mark_reviewed"}},{"name":"page_mark_missing","description":"Mark a checklist item as a known gap.","script":"binder-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"}}},"bind":{"action":"mark_missing"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"documents.json"}],"tools":["page_record_document","page_mark_reviewed","page_mark_missing"]},"schedules":[],"workspaceSeed":["documents.json"],"artifactsSeed":[],"availableVersions":["1.0.6","1.0.5","1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"meal-planner","name":"Meal Planner & Pantry","description":"Answer \"what's for dinner?\" once a week. A meal planner plans menus from what's actually in the pantry, keeps taste memory, and the grocery list writes itself.","tags":["meals","cooking","pantry","groceries","menu"],"category":"home","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.5","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"household":{"type":"string","title":"Who eats here?","description":"e.g. 'two adults, two picky kids', 'just me, vegetarian'.","default":"the household"}},"required":["household"]},"nameTemplate":"Meal Planner","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"maaltijdplanner","voorman":true}],"toolsets":[],"craftbooks":["weekly-menu-plan"],"scripts":{"kitchen-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'kitchen-store',\n description:\n \"Read and update the week's menu (menu.json) and the pantry (pantry.json). Call action:'status' for today's dinner + the grocery gap; 'set_menu' day by day; 'pantry_add' / 'pantry_level' as staples change; 'grocery_list' for the run.\",\n inputs: {\n action: {\n type: 'string',\n description:\n \"One of 'status', 'set_menu', 'pantry_add', 'pantry_level', or 'grocery_list'.\",\n required: true,\n },\n day: {\n type: 'string',\n description: \"Day for set_menu: monday..sunday.\",\n },\n meal: { type: 'string', description: 'The dinner for that day.' },\n name: { type: 'string', description: 'Pantry item name.' },\n level: { type: 'string', description: \"Pantry level: 'stocked', 'low', or 'out'.\" },\n id: { type: 'string', description: \"Pantry item id, e.g. 'item-3'.\" },\n },\n outputs: {\n planned: { type: 'number', description: 'Days with a planned dinner.' },\n groceries: { type: 'number', description: 'Items on the grocery list.' },\n summary: { type: 'string', description: 'The kitchen picture.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── kitchen-rules-start ──\n// Pure derivations: the weekly menu shape and the grocery gap (pantry\n// items marked low or out).\n\nvar DAYS = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];\n\nfunction normalizeDay(day) {\n if (typeof day !== 'string') return null;\n var d = day.toLowerCase();\n return DAYS.indexOf(d) >= 0 ? d : null;\n}\n\nfunction todayName(nowMs) {\n // getUTCDay: 0=Sunday.\n var idx = new Date(nowMs).getUTCDay();\n return DAYS[(idx + 6) % 7];\n}\n\nfunction groceryGap(records) {\n return records.filter(function (r) {\n return r.status === 'low' || r.status === 'out';\n });\n}\n\nfunction kitchenLine(menu, records, nowMs) {\n var today = todayName(nowMs);\n var tonight = menu.days && menu.days[today];\n var gap = groceryGap(records);\n var planned = DAYS.filter(function (d) {\n return menu.days && menu.days[d];\n }).length;\n var open = DAYS.filter(function (d) {\n return !(menu.days && menu.days[d]);\n });\n var name = function (r) {\n return (r.fields && r.fields.name) || r.id;\n };\n var stocked = records.filter(function (r) {\n return r.status === 'stocked';\n });\n return (\n (tonight ? 'Tonight: ' + tonight + '.' : 'Nothing planned for tonight.') +\n ' ' +\n planned +\n ' of 7 dinners planned' +\n (open.length ? '; open: ' + open.join(', ') : '') +\n '. In stock: ' +\n (stocked.length ? stocked.map(name).join(', ') : 'nothing recorded') +\n '. Grocery list: ' +\n (gap.length\n ? gap\n .map(function (r) {\n return name(r) + ' (' + r.status + ')';\n })\n .join(', ')\n : 'empty') +\n '.'\n );\n}\n// ── kitchen-rules-end ──\n\nconst MENU_FILE = 'menu.json';\nconst pantry = rosterStore(gezel.fs, 'pantry.json', {\n stages: ['stocked', 'low', 'out'],\n idPrefix: 'item',\n});\n\ninterface Menu {\n version: number;\n days: Record<string, string>;\n updatedAt: string;\n}\n\nasync function loadMenu(): Promise<Menu> {\n try {\n const parsed = JSON.parse(await gezel.fs.read(MENU_FILE)) as Partial<Menu>;\n return {\n version: 1,\n days: parsed.days && typeof parsed.days === 'object' ? (parsed.days as Record<string, string>) : {},\n updatedAt: new Date().toISOString(),\n };\n } catch {\n return { version: 1, days: {}, updatedAt: new Date().toISOString() };\n }\n}\n\nasync function saveMenu(menu: Menu): Promise<void> {\n menu.updatedAt = new Date().toISOString();\n await gezel.fs.write(MENU_FILE, `${JSON.stringify(menu, null, 2)}\\n`);\n}\n\nasync function resolveItem(): Promise<string> {\n if (input.id) return input.id;\n if (input.name) {\n const wanted = input.name.toLowerCase();\n const matches = (await pantry.list()).filter(\n (r) => String(r.fields.name ?? '').toLowerCase() === wanted,\n );\n if (matches.length === 1) return matches[0]!.id;\n }\n throw new Error(\"Pass 'id' (e.g. 'item-3') or an exact pantry item 'name'.\");\n}\n\nconst menu = await loadMenu();\n\nif (input.action === 'set_menu') {\n const day = normalizeDay(input.day);\n if (!day || !input.meal) throw new Error(\"set_menu needs 'day' (monday..sunday) and 'meal'.\");\n menu.days[day] = input.meal;\n await saveMenu(menu);\n} else if (input.action === 'pantry_add') {\n if (!input.name) throw new Error(\"pantry_add needs 'name'.\");\n const level = input.level && ['stocked', 'low', 'out'].includes(input.level) ? input.level : 'stocked';\n // \"We ran out of olive oil\" often arrives as an add: a staple already on the\n // board changes level rather than appearing twice.\n const wanted = input.name.trim().toLowerCase();\n const existing = (await pantry.list()).find(\n (r) => String(r.fields.name ?? '').trim().toLowerCase() === wanted,\n );\n if (existing) {\n if (existing.status !== level) await pantry.transition(existing.id, level);\n } else {\n await pantry.add({ status: level, fields: { name: input.name.trim() } });\n }\n} else if (input.action === 'pantry_level') {\n if (!input.level || !['stocked', 'low', 'out'].includes(input.level)) {\n throw new Error(\"pantry_level needs level 'stocked', 'low', or 'out'.\");\n }\n await pantry.transition(await resolveItem(), input.level);\n} else if (input.action !== 'status' && input.action !== 'grocery_list') {\n throw new Error(\n `Unknown action '${input.action}'. Use status, set_menu, pantry_add, pantry_level, or grocery_list.`,\n );\n}\n\nconst records = await pantry.list();\nconst gap = groceryGap(records);\nconst listing =\n input.action === 'grocery_list'\n ? gap\n .map((r) => `${String(r.fields.name ?? r.id)} (${r.status})`)\n .join('\\n') || 'The grocery list is empty.'\n : '';\n\ngezel.output({\n planned: DAYS.filter((d) => menu.days[d]).length,\n groceries: gap.length,\n summary: listing || kitchenLine(menu, records, Date.now()),\n});\n"},"tools":[{"name":"set_menu","description":"Save a day's dinner to the kitchen board (day: monday..sunday). The board shows only saved dinners, so call this for every dinner you plan before you describe it.","script":"kitchen-store","inputs":{"type":"object","properties":{"day":{"type":"string"},"meal":{"type":"string"}},"required":["day","meal"]},"bind":{"action":"set_menu"}},{"name":"pantry_add","description":"Add a pantry staple to the board, or set its level if it is already there (stocked, low, or out). Call it whenever the person mentions a staple.","script":"kitchen-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"level":{"type":"string","enum":["stocked","low","out"]}},"required":["name"]},"bind":{"action":"pantry_add"}},{"name":"pantry_level","description":"Change a staple's level on the board as the kitchen changes (stocked, low, or out). Call it whenever the person says they bought, used up, or ran low on something.","script":"kitchen-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"level":{"type":"string","enum":["stocked","low","out"]}},"required":["level"]},"bind":{"action":"pantry_level"}},{"name":"kitchen_status","description":"Tonight's dinner, the open days, what's in stock, and the grocery gap.","script":"kitchen-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"}},{"name":"grocery_list","description":"The shopping run: everything low or out.","script":"kitchen-store","inputs":{"type":"object","properties":{}},"bind":{"action":"grocery_list"}},{"name":"page_set_menu","description":"Set a day's dinner (monday..sunday).","script":"kitchen-store","inputs":{"type":"object","properties":{"day":{"type":"string"},"meal":{"type":"string"}},"required":["day","meal"]},"bind":{"action":"set_menu"}},{"name":"page_pantry_add","description":"Add a pantry staple (level stocked, low, or out).","script":"kitchen-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"level":{"type":"string","enum":["stocked","low","out"]}},"required":["name"]},"bind":{"action":"pantry_add"}},{"name":"page_pantry_level","description":"Update a staple's level as the kitchen changes.","script":"kitchen-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"level":{"type":"string","enum":["stocked","low","out"]}},"required":["level"]},"bind":{"action":"pantry_level"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"menu.json"},{"source":"workspace","path":"pantry.json"}],"tools":["page_set_menu","page_pantry_add","page_pantry_level"]},"schedules":[],"workspaceSeed":["menu.json","pantry.json"],"artifactsSeed":[],"availableVersions":["1.0.5","1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"media-library","name":"Media Library","description":"Browse a folder of images, videos, and audio in a live gallery. Preview and play your media without importing or moving the originals.","tags":["photos","images","video","audio","gallery","library","folder"],"category":"creative","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.2","releasedAt":"2026-11-02T18:00:00.000Z","extends":"media-production","nameTemplate":"Media Library","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[],"toolsets":[],"craftbooks":[],"tools":[],"pages":{"imports":[{"id":"library","source":"workspace","path":".","accept":[".jpg",".jpeg",".png",".gif",".webp",".avif",".bmp",".svg",".ico",".heic",".heif",".tif",".tiff",".dng",".raw",".cr2",".cr3",".nef",".arw",".orf",".raf",".mp4",".webm",".mov",".m4v",".ogv",".avi",".mkv",".mpg",".mpeg",".mts",".m2ts",".mp3",".wav",".ogg",".oga",".m4a",".aac",".flac",".opus",".aif",".aiff",".wma"],"maxFileBytes":268435456}],"entry":"index.html","api":1,"reads":[{"source":"workspace","path":".","subtree":true}]},"schedules":[],"workspaceSeed":[],"artifactsSeed":[],"availableVersions":["1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"new-hire-onboarding","name":"New Hire Onboarding","description":"Give each new hire a clear plan for their first weeks. A training coordinator and an office administrator get accounts, equipment and paperwork ready before day one, then walk the first week and the 30, 60 and 90-day check-ins, so nothing is forgotten and nobody starts to an empty desk.","tags":["onboarding","new-hire","first-week","orientation","staff","team","small-business"],"category":"business","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.0.0","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"business":{"type":"string","title":"What kind of business is this?","description":"e.g. 'a café with 12 staff', 'a six-person design studio'.","default":"the business"}},"required":["business"]},"nameTemplate":"New Hire Onboarding","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"training-coordinator","voorman":true},{"templateId":"kantoormeester","voorman":false}],"toolsets":[],"craftbooks":["onboarding-checklist","handbook-section"],"scripts":{"onboarding-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'onboarding-store',\n description:\n \"Read and update the onboarding plans: hires.json (each new hire, their start date, manager and buddy) and tasks.json (every step of every plan, with a phase, an owner and a due date). action:'status' for open steps due soon (overdue first) and each hire's progress; 'add_hire' to add a hire with the standard plan (an existing name is updated, never duplicated); 'add_task' to add a step to a plan; 'complete' to check steps off; 'list' for whole plans.\",\n inputs: {\n action: { type: 'string', description: \"One of 'status', 'add_hire', 'add_task', 'complete', or 'list'.\", required: true },\n name: { type: 'string', description: \"For add_hire: the new hire's full name.\" },\n role: { type: 'string', description: \"For add_hire: their job, e.g. 'Barista'.\" },\n startOn: { type: 'string', description: \"For add_hire: their first day, YYYY-MM-DD or a weekday like 'monday'.\" },\n manager: { type: 'string', description: 'For add_hire: their manager.' },\n buddy: { type: 'string', description: 'For add_hire: the teammate who shows them around the first week.' },\n hire: { type: 'string', description: \"Hire id (e.g. 'h-2') or name; a first name is enough when it is unique.\" },\n title: { type: 'string', description: 'For add_task: what needs doing.' },\n phase: {\n type: 'string',\n description: \"before day one, day one, first week, 30 days, 60 days, or 90 days. For complete: checks off every open step in that phase.\",\n },\n owner: { type: 'string', description: 'For add_task: who does it.' },\n dueOn: { type: 'string', description: 'For add_task: the due date, YYYY-MM-DD; default the phase’s usual day.' },\n task: { type: 'string', description: \"For complete: a step's id (e.g. 't-4') or words from its title; several separated by commas.\" },\n reopen: { type: 'boolean', description: 'For complete: put a checked step back on the list.' },\n note: { type: 'string', description: 'What happened.' },\n withinDays: { type: 'number', description: 'How many days ahead count as due soon (default 7).' },\n },\n outputs: {\n active: { type: 'number', description: 'Hires still onboarding.' },\n overdue: { type: 'number', description: 'Open steps past their due date.' },\n dueSoon: { type: 'number', description: 'Open steps due within the window.' },\n summary: { type: 'string', description: 'What changed, then the onboarding picture or the listing.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── onboarding-rules-start ──\n// Pure derivations: dates in local calendar days, record matching, the\n// standard plan, phase names, task matching, and the picture the crew reads.\n// Kept self-contained between these sentinels so tests execute the shipped\n// bytes.\nvar DAY_MS = 86400000;\nvar WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\nvar MONTH_KEYS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];\n\nfunction pad(n) {\n return n < 10 ? '0' + n : String(n);\n}\nfunction localDay(ms) {\n var d = new Date(ms);\n return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());\n}\nfunction noon(day) {\n return new Date(String(day).slice(0, 10) + 'T12:00:00');\n}\nfunction addDays(day, n) {\n var d = noon(day);\n d.setDate(d.getDate() + n);\n return localDay(d.getTime());\n}\nfunction addMonths(day, months) {\n var d = noon(day);\n var date = d.getDate();\n d.setDate(1);\n d.setMonth(d.getMonth() + months);\n // The 31st rolls to the last day of a shorter month, not into the next one.\n d.setDate(Math.min(date, new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate()));\n return localDay(d.getTime());\n}\nfunction daysLeft(day, nowMs) {\n var due = Date.parse(String(day).slice(0, 10) + 'T00:00:00');\n var today = Date.parse(localDay(nowMs) + 'T00:00:00');\n return Math.round((due - today) / DAY_MS);\n}\nfunction dayName(day) {\n return WEEKDAYS[noon(day).getDay()];\n}\nfunction parseDay(text, nowMs, direction) {\n var raw = String(text == null ? '' : text).trim().toLowerCase().replace(/[.,]/g, ' ').replace(/\\s+/g, ' ').trim();\n if (!raw) return null;\n var iso = raw.match(/^(\\d{4})-(\\d{1,2})-(\\d{1,2})(?:t.*)?$/);\n if (iso) return iso[1] + '-' + pad(Number(iso[2])) + '-' + pad(Number(iso[3]));\n var today = localDay(nowMs);\n if (raw === 'today' || raw === 'now') return today;\n if (raw === 'tomorrow') return addDays(today, 1);\n if (raw === 'yesterday') return addDays(today, -1);\n var rel = raw.match(/^(?:in )?(\\d{1,3}) (day|days|week|weeks)( ago| from now)?$/);\n if (rel) {\n var n = Number(rel[1]) * (rel[2].charAt(0) === 'w' ? 7 : 1);\n return addDays(today, rel[3] === ' ago' ? -n : n);\n }\n var wd = raw.match(/^(this |next |last |on |coming )?(sun|mon|tue|wed|thu|fri|sat)[a-z]*$/);\n if (wd) {\n var target = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].indexOf(wd[2]);\n var now = noon(today).getDay();\n if (direction === 'past' || wd[1] === 'last ') {\n var back = (now - target + 7) % 7;\n return addDays(today, -(wd[1] === 'last ' && back === 0 ? 7 : back));\n }\n if (wd[1] === 'this ') return addDays(today, (target - now + 7) % 7);\n return addDays(today, ((target - now + 6) % 7) + 1);\n }\n var md = raw.match(/^(?:[a-z]+day )?([a-z]{3,9}) (\\d{1,2})(?:st|nd|rd|th)?(?: (\\d{4}))?$/);\n var dm = raw.match(/^(?:[a-z]+day )?(\\d{1,2})(?:st|nd|rd|th)? (?:of )?([a-z]{3,9})(?: (\\d{4}))?$/);\n var parts = md ? { month: md[1], date: md[2], year: md[3] } : dm ? { month: dm[2], date: dm[1], year: dm[3] } : null;\n if (parts) {\n var m = MONTH_KEYS.indexOf(parts.month.slice(0, 3));\n if (m < 0) return null;\n var date = Number(parts.date);\n if (date < 1 || date > 31) return null;\n if (parts.year) return parts.year + '-' + pad(m + 1) + '-' + pad(date);\n var year = noon(today).getFullYear();\n var guess = year + '-' + pad(m + 1) + '-' + pad(date);\n var d = daysLeft(guess, nowMs);\n if (direction === 'past' && d > 0) guess = year - 1 + guess.slice(4);\n if (direction !== 'past' && d < 0) guess = year + 1 + guess.slice(4);\n return guess;\n }\n return null;\n}\nfunction matches(records, text, labelOf) {\n var wanted = String(text == null ? '' : text).trim().toLowerCase().replace(/['\\u2019]s\\b/g, '').replace(/\\s+/g, ' ');\n if (!wanted) return [];\n var tiers = [\n function (r) { return String(r.id).toLowerCase() === wanted; },\n function (r) { return labelOf(r).toLowerCase() === wanted; },\n function (r) { return labelOf(r).toLowerCase().indexOf(wanted) === 0; },\n function (r) { return (' ' + labelOf(r).toLowerCase() + ' ').indexOf(' ' + wanted + ' ') >= 0; },\n function (r) { return labelOf(r).toLowerCase().indexOf(wanted) >= 0; },\n function (r) { var l = labelOf(r).toLowerCase(); return l.length >= 3 && wanted.indexOf(l) >= 0; },\n ];\n for (var i = 0; i < tiers.length; i++) {\n var hit = records.filter(tiers[i]);\n if (hit.length) return hit;\n }\n return [];\n}\nfunction describe(records, labelOf) {\n return records.map(function (r) { return r.id + ' ' + labelOf(r); }).join(', ');\n}\nfunction splitList(text) {\n var raw = String(text == null ? '' : text).trim();\n if (/^\\[/.test(raw)) {\n try {\n var parsed = JSON.parse(raw);\n if (Array.isArray(parsed)) return parsed.map(function (s) { return String(s).trim(); }).filter(Boolean);\n } catch (e) {\n // Not JSON after all; split it as text.\n }\n }\n return raw\n .split(/\\s*[,;\\n]+\\s*/)\n .map(function (s) { return s.replace(/^(and|or|plus)\\s+/i, '').replace(/[.\\s]+$/, '').trim(); })\n .filter(Boolean);\n}\nvar PHASES = ['before day one', 'day one', 'first week', '30 days', '60 days', '90 days'];\nvar PHASE_OFFSET = { 'before day one': -2, 'day one': 0, 'first week': 4, '30 days': 30, '60 days': 60, '90 days': 90 };\n// The standard plan every new hire starts with; offsets are days from the first day.\nvar PLAN = [\n ['before day one', 'Send a welcome note with the start time, place and what to bring', 'manager', -5],\n ['before day one', 'Set up email and scheduling accounts', 'office', -3],\n ['before day one', 'Prepare uniform, keys and workspace', 'office', -2],\n ['before day one', 'Collect tax, payroll and emergency-contact forms', 'office', -1],\n ['day one', 'Tour, introductions and safety basics', 'manager', 0],\n ['day one', 'Pair with a buddy for the first week', 'manager', 0],\n ['first week', 'Shadow shifts with the buddy', 'buddy', 3],\n ['first week', 'Enroll in the training the role needs', 'training', 4],\n ['first week', 'First-week check-in', 'manager', 5],\n ['30 days', '30-day check-in: what is going well, what is unclear', 'manager', 30],\n ['30 days', 'Required certificates on file', 'training', 30],\n ['60 days', '60-day check-in', 'manager', 60],\n ['90 days', '90-day review and goals for the next quarter', 'manager', 90],\n];\nvar TASK_STOP = ['with', 'from', 'that', 'this', 'have', 'done', 'were', 'they', 'their', 'into', 'about', 'what'];\n\nfunction ownerFor(kind, hire) {\n var f = (hire && hire.fields) || {};\n if (kind === 'manager') return f.manager || 'Manager';\n if (kind === 'buddy') return f.buddy || 'Buddy';\n if (kind === 'office') return 'Office';\n if (kind === 'training') return 'Training';\n return String(kind || '');\n}\nfunction planFor(hire) {\n return PLAN.map(function (p) {\n return { phase: p[0], title: p[1], ownerKind: p[2], owner: ownerFor(p[2], hire), offset: p[3], dueAt: addDays(hire.fields.startOn, p[3]) };\n });\n}\nfunction phaseOf(text) {\n var raw = String(text == null ? '' : text).trim().toLowerCase();\n if (!raw) return null;\n if (PHASES.indexOf(raw) >= 0) return raw;\n if (/before|prior|ahead|pre-?start|preboard/.test(raw)) return 'before day one';\n if (/\\b(day (one|1)|first day|start day|day of)\\b/.test(raw)) return 'day one';\n if (/\\b(first|1st) week\\b|\\bweek (one|1)\\b|^week$/.test(raw)) return 'first week';\n if (/\\b(30|thirty)\\b|first month|one month/.test(raw)) return '30 days';\n if (/\\b(60|sixty)\\b|two months/.test(raw)) return '60 days';\n if (/\\b(90|ninety)\\b|three months/.test(raw)) return '90 days';\n return null;\n}\nfunction keyWords(text) {\n return (String(text == null ? '' : text).toLowerCase().match(/[a-z0-9]+/g) || [])\n .filter(function (w) { return w.length >= 4 && TASK_STOP.indexOf(w) < 0; })\n .map(function (w) { return w.length > 4 ? w.replace(/s$/, '') : w; });\n}\nfunction taskMatches(tasks, text) {\n var hit = matches(tasks, text, function (t) { return String(t.fields.title || ''); });\n if (hit.length) return hit;\n var want = keyWords(text);\n if (!want.length) return [];\n var best = [];\n var score = 0;\n tasks.forEach(function (t) {\n var have = keyWords(t.fields.title);\n var s = want.filter(function (w) { return have.indexOf(w) >= 0; }).length;\n if (s > score) {\n best = [t];\n score = s;\n } else if (s === score && s > 0) best.push(t);\n });\n return score >= Math.min(2, want.length) ? best : [];\n}\nfunction whenText(day, nowMs) {\n var d = daysLeft(day, nowMs);\n return d < 0 ? -d + (d === -1 ? ' day late' : ' days late') : d === 0 ? 'due today' : d === 1 ? 'due tomorrow' : 'due ' + dayName(day) + ' ' + day;\n}\nfunction startText(hire, nowMs) {\n var d = daysLeft(hire.fields.startOn, nowMs);\n return d > 0 ? 'starts ' + dayName(hire.fields.startOn) + ' ' + hire.fields.startOn + ', in ' + d + (d === 1 ? ' day' : ' days') : d === 0 ? 'starts today' : 'day ' + (1 - d) + ', started ' + hire.fields.startOn;\n}\nfunction taskLine(t, nowMs) {\n return t.fields.title + ' (' + t.id + ', ' + (t.fields.owner || 'no owner') + ', ' + whenText(t.fields.dueAt, nowMs) + ')';\n}\nfunction picture(hires, tasks, nowMs, withinDays) {\n var active = hires.filter(function (h) { return h.status !== 'done'; }).sort(function (a, b) { return String(a.fields.startOn).localeCompare(String(b.fields.startOn)); });\n var byDue = function (a, b) { return String(a.fields.dueAt).localeCompare(String(b.fields.dueAt)); };\n var open = tasks.filter(function (t) { return t.status !== 'done' && active.some(function (h) { return h.id === t.fields.hireId; }); });\n var overdue = open.filter(function (t) { return daysLeft(t.fields.dueAt, nowMs) < 0; }).sort(byDue);\n var soon = open.filter(function (t) { var d = daysLeft(t.fields.dueAt, nowMs); return d >= 0 && d <= withinDays; }).sort(byDue);\n var parts = [active.length + (active.length === 1 ? ' new hire' : ' new hires') + ' onboarding, ' + overdue.length + (overdue.length === 1 ? ' step' : ' steps') + ' overdue.'];\n // One list, overdue first: \"what's due this week\" and \"what's overdue\" are both answered from it.\n var due = overdue.concat(soon);\n parts.push(\n due.length\n ? 'Open steps due within ' + withinDays + ' days, overdue first: ' + due.map(function (t) { return t.fields.hireName + ': ' + taskLine(t, nowMs); }).join(' | ') + '.'\n : 'Nothing due in the next ' + withinDays + ' days.',\n );\n active.forEach(function (h) {\n var mine = tasks.filter(function (t) { return t.fields.hireId === h.id; });\n var left = mine.filter(function (t) { return t.status !== 'done'; }).sort(byDue);\n var before = daysLeft(h.fields.startOn, nowMs) > 0 ? left.filter(function (t) { return t.fields.phase === 'before day one'; }) : [];\n parts.push(\n h.fields.name + ' (' + h.id + ', ' + (h.fields.role || 'no role') + ', ' + startText(h, nowMs) +\n (h.fields.manager ? ', manager ' + h.fields.manager : '') + (h.fields.buddy ? ', buddy ' + h.fields.buddy : '') + '): ' +\n (mine.length - left.length) + ' of ' + mine.length + ' steps done' +\n (before.length ? '; still to do before day one: ' + before.map(function (t) { return taskLine(t, nowMs); }).join('; ') : left.length ? '; next: ' + taskLine(left[0], nowMs) : '') + '.',\n );\n });\n return { active: active.length, overdue: overdue.length, dueSoon: soon.length, summary: parts.join(' ') };\n}\n// ── onboarding-rules-end ──\n\nconst hires = rosterStore(gezel.fs, 'hires.json', { stages: ['active', 'done'], idPrefix: 'h' });\nconst tasks = rosterStore(gezel.fs, 'tasks.json', { stages: ['todo', 'done'], idPrefix: 't' });\nconst now = Date.now();\nconst withinDays = typeof input.withinDays === 'number' && input.withinDays > 0 ? Math.round(input.withinDays) : 7;\nconst nameOf = (r: { fields: Record<string, unknown> }) => String(r.fields.name ?? '');\nconst titleOf = (r: { fields: Record<string, unknown> }) => String(r.fields.title ?? '');\n\nasync function resolveHire(text?: string) {\n const all = await hires.list();\n if (!text) {\n const active = all.filter((h) => h.status !== 'done');\n if (active.length === 1) return active[0]!;\n throw new Error(\"Pass 'hire' (id or name). New hires: \" + (describe(all, nameOf) || 'none yet; add one with add_hire') + '.');\n }\n let hits = matches(all.filter((h) => h.status !== 'done'), text, nameOf);\n if (!hits.length) hits = matches(all, text, nameOf);\n if (hits.length === 1) return hits[0]!;\n if (hits.length > 1) throw new Error(\"More than one hire matches '\" + text + \"': \" + describe(hits, nameOf) + '. Pass the id.');\n throw new Error(\"No new hire matches '\" + text + \"'. New hires: \" + (describe(all, nameOf) || 'none yet; add one with add_hire') + '.');\n}\n\n// A plan whose every step is checked off is finished; a new or reopened step puts it back.\nasync function settle(hireId: string): Promise<string> {\n const hire = await hires.get(hireId);\n if (!hire) return '';\n const mine = (await tasks.list()).filter((t) => t.fields.hireId === hireId);\n const left = mine.filter((t) => t.status !== 'done').length;\n if (!left && mine.length && hire.status !== 'done') {\n await hires.transition(hireId, 'done', { note: 'Every step done' });\n return ' ' + nameOf(hire) + \"'s plan is complete.\";\n }\n if (left && hire.status === 'done') await hires.transition(hireId, 'active');\n return '';\n}\n\nlet note = '';\n\nif (input.action === 'add_hire') {\n if (!input.name || !input.name.trim()) throw new Error(\"add_hire needs 'name'.\");\n const name = input.name.trim();\n const startOn = input.startOn ? parseDay(input.startOn, now, 'future') : null;\n if (input.startOn && !startOn) throw new Error(\"startOn must be a date like '2026-11-09' or a weekday like 'monday'.\");\n const fields: Record<string, unknown> = {\n ...(input.role ? { role: input.role.trim() } : {}),\n ...(startOn ? { startOn } : {}),\n ...(input.manager ? { manager: input.manager.trim() } : {}),\n ...(input.buddy ? { buddy: input.buddy.trim() } : {}),\n ...(input.note ? { notes: input.note.trim() } : {}),\n };\n const existing = (await hires.list()).find((h) => nameOf(h).toLowerCase() === name.toLowerCase());\n if (existing) {\n const updated = await hires.update(existing.id, { fields });\n // A moved start date or a named manager/buddy carries into the open standard steps.\n let moved = 0;\n for (const t of (await tasks.list()).filter((x) => x.fields.hireId === existing.id && x.status !== 'done')) {\n const patch: Record<string, unknown> = {};\n if (typeof t.fields.offset === 'number' && startOn && startOn !== existing.fields.startOn) patch.dueAt = addDays(startOn, t.fields.offset);\n if (t.fields.ownerKind && (input.manager || input.buddy)) patch.owner = ownerFor(t.fields.ownerKind, updated);\n if (Object.keys(patch).length) {\n await tasks.update(t.id, { fields: patch });\n if (patch.dueAt) moved += 1;\n }\n }\n note = 'Updated ' + name + ' (' + existing.id + ')' + (moved ? '; moved ' + moved + ' open steps to the new start date.' : '.');\n } else {\n if (!startOn) throw new Error(\"A new hire needs 'startOn', their first day (YYYY-MM-DD or a weekday).\");\n const hire = await hires.add({ status: 'active', fields: { name, role: '', ...fields } });\n for (const step of planFor(hire)) {\n await tasks.add({\n status: 'todo',\n fields: {\n hireId: hire.id,\n hireName: name,\n title: step.title,\n phase: step.phase,\n owner: step.owner,\n ownerKind: step.ownerKind,\n offset: step.offset,\n dueAt: step.dueAt,\n },\n });\n }\n note = 'Added ' + name + ' (' + hire.id + '), first day ' + dayName(startOn) + ' ' + startOn + ', with the standard ' + PLAN.length + '-step plan.';\n }\n} else if (input.action === 'add_task') {\n if (!input.title || !input.title.trim()) throw new Error(\"add_task needs 'title'.\");\n const hire = await resolveHire(input.hire);\n const phase = input.phase ? phaseOf(input.phase) : null;\n if (input.phase && !phase) throw new Error('phase must be one of ' + PHASES.join(', ') + '.');\n const dueAt = input.dueOn ? parseDay(input.dueOn, now, 'future') : null;\n if (input.dueOn && !dueAt) throw new Error(\"dueOn must be a date like '2026-11-12'.\");\n const title = input.title.trim();\n const existing = (await tasks.list()).find((t) => t.fields.hireId === hire.id && titleOf(t).toLowerCase() === title.toLowerCase());\n const usePhase = phase ?? (existing ? String(existing.fields.phase) : 'first week');\n const fields: Record<string, unknown> = {\n phase: usePhase,\n ...(input.owner ? { owner: input.owner.trim() } : {}),\n ...(input.note ? { notes: input.note.trim() } : {}),\n dueAt: dueAt ?? (existing && !phase ? existing.fields.dueAt : addDays(String(hire.fields.startOn), PHASE_OFFSET[usePhase])),\n };\n if (existing) {\n await tasks.update(existing.id, { fields });\n note = 'Updated the step ' + title + ' (' + existing.id + ') for ' + nameOf(hire) + '.';\n } else {\n const record = await tasks.add({ status: 'todo', fields: { hireId: hire.id, hireName: nameOf(hire), title, owner: '', ...fields } });\n note = 'Added ' + title + ' (' + record.id + ') to ' + nameOf(hire) + \"'s \" + usePhase + ', ' + whenText(String(record.fields.dueAt), now) + '.';\n }\n note += await settle(hire.id);\n} else if (input.action === 'complete') {\n const all = await tasks.list();\n const hire = input.hire ? await resolveHire(input.hire) : null;\n const scope = all.filter((t) => (!hire || t.fields.hireId === hire.id) && (input.reopen ? t.status === 'done' : t.status !== 'done'));\n let picked: typeof all = [];\n if (input.task) {\n for (const piece of String(input.task).split(/\\s*[,;]\\s*/).filter(Boolean)) {\n const hits = taskMatches(scope, piece);\n if (hits.length > 1) throw new Error(\"More than one step matches '\" + piece + \"': \" + hits.map((t: (typeof all)[number]) => t.id + ' ' + String(t.fields.hireName) + ': ' + titleOf(t)).join('; ') + '. Pass the id or the hire.');\n if (!hits.length) {\n const done = all.find((t) => t.id === piece.trim() || (!input.reopen && t.status === 'done' && titleOf(t).toLowerCase() === piece.trim().toLowerCase()));\n if (done && !input.reopen) continue;\n throw new Error(\"No open step matches '\" + piece + \"'\" + (hire ? ' for ' + nameOf(hire) : '') + '. Open steps: ' + (scope.slice(0, 12).map((t) => t.id + ' ' + String(t.fields.hireName) + ': ' + titleOf(t)).join('; ') || 'none') + '.');\n }\n if (!picked.some((t) => t.id === hits[0].id)) picked.push(hits[0]);\n }\n } else if (input.phase) {\n const phase = phaseOf(input.phase);\n if (!phase) throw new Error('phase must be one of ' + PHASES.join(', ') + '.');\n if (!hire) throw new Error(\"Pass 'hire' with 'phase'.\");\n picked = scope.filter((t) => t.fields.phase === phase);\n } else {\n throw new Error(\"complete needs 'task' (an id or words from the step) or 'hire' with 'phase'.\");\n }\n for (const t of picked) {\n if (input.reopen) await tasks.transition(t.id, 'todo', input.note ? { note: input.note } : {});\n else {\n await tasks.update(t.id, { fields: { doneAt: localDay(now), ...(input.note ? { notes: input.note.trim() } : {}) } });\n await tasks.transition(t.id, 'done', input.note ? { note: input.note } : {});\n }\n }\n const hireIds = Array.from(new Set(picked.map((t) => String(t.fields.hireId))));\n note = picked.length\n ? (input.reopen ? 'Reopened ' : 'Checked off ') + picked.map((t) => String(t.fields.hireName) + ': ' + titleOf(t)).join('; ') + '.'\n : 'Nothing left to check off there.';\n for (const id of hireIds) note += await settle(id);\n} else if (input.action !== 'status' && input.action !== 'list') {\n throw new Error(\"Unknown action '\" + input.action + \"'. Use status, add_hire, add_task, complete, or list.\");\n}\n\nconst allHires = await hires.list();\nconst allTasks = await tasks.list();\nconst view = picture(allHires, allTasks, now, withinDays);\nlet summary = (note ? note + ' ' : '') + view.summary;\nif (input.action === 'list') {\n const wanted = input.hire ? [await resolveHire(input.hire)] : allHires;\n summary =\n wanted\n .map((h) => {\n const mine = allTasks.filter((t) => t.fields.hireId === h.id).sort((a, b) => String(a.fields.dueAt).localeCompare(String(b.fields.dueAt)));\n return (\n nameOf(h) + ' (' + h.id + ', ' + String(h.fields.role || 'no role') + ', ' + startText(h, now) + (h.status === 'done' ? ', plan complete' : '') + '):\\n' +\n mine.map((t) => '[' + t.status + '] ' + String(t.fields.phase) + ': ' + taskLine(t, now)).join('\\n')\n );\n })\n .join('\\n\\n') || 'No new hires yet.';\n}\ngezel.output({ active: view.active, overdue: view.overdue, dueSoon: view.dueSoon, summary });\n"},"tools":[{"name":"onboarding_status","description":"Every new hire's onboarding at a glance: open steps due within 7 days with overdue first, then each hire's start date, progress and what is still to do before day one, with hire and step ids. Call it first when asked what is due, what is overdue, or how someone's first weeks are going.","script":"onboarding-store","inputs":{"type":"object","properties":{"withinDays":{"type":"number"}}},"bind":{"action":"status"},"state":true},{"name":"add_hire","description":"Add a new hire with the standard plan (accounts, equipment and paperwork before day one, a first-day welcome, a first week with a buddy, and 30, 60 and 90-day check-ins), or update one: full name, role, first day (YYYY-MM-DD or a weekday like 'monday'), manager and buddy. An existing name is updated, never duplicated, and a new start date moves the open steps. Call it as soon as a new hire is mentioned.","script":"onboarding-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"role":{"type":"string"},"startOn":{"type":"string"},"manager":{"type":"string"},"buddy":{"type":"string"},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"add_hire"}},{"name":"add_task","description":"Add a step to a new hire's plan: the hire, what needs doing, the phase (before day one, day one, first week, 30 days, 60 days or 90 days), who owns it, and a due date if one was given. An existing title is updated, never duplicated. Call it as soon as the person asks.","script":"onboarding-store","inputs":{"type":"object","properties":{"hire":{"type":"string"},"title":{"type":"string"},"phase":{"type":"string","enum":["before day one","day one","first week","30 days","60 days","90 days"]},"owner":{"type":"string"},"dueOn":{"type":"string"},"note":{"type":"string"}},"required":["title"]},"bind":{"action":"add_task"}},{"name":"complete_task","description":"Check off steps the moment the person says they are done: task (a step's id or words from its title, several separated by commas) and the hire's name, or the hire with a phase to check off everything in it. Call it before you reply.","script":"onboarding-store","inputs":{"type":"object","properties":{"hire":{"type":"string"},"task":{"type":"string"},"phase":{"type":"string","enum":["before day one","day one","first week","30 days","60 days","90 days"]},"note":{"type":"string"}}},"bind":{"action":"complete"}},{"name":"list_plan","description":"A whole plan, or every plan: each step with its phase, owner, due date and whether it is done.","script":"onboarding-store","inputs":{"type":"object","properties":{"hire":{"type":"string"}}},"bind":{"action":"list"}},{"name":"page_add_hire","description":"Add or update a new hire with the standard plan.","script":"onboarding-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"role":{"type":"string"},"startOn":{"type":"string"},"manager":{"type":"string"},"buddy":{"type":"string"},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"add_hire"}},{"name":"page_complete_task","description":"Check off or reopen a step.","script":"onboarding-store","inputs":{"type":"object","properties":{"hire":{"type":"string"},"task":{"type":"string"},"phase":{"type":"string","enum":["before day one","day one","first week","30 days","60 days","90 days"]},"note":{"type":"string"},"reopen":{"type":"boolean"}}},"bind":{"action":"complete"}},{"name":"page_add_task","description":"Add a step to a plan.","script":"onboarding-store","inputs":{"type":"object","properties":{"hire":{"type":"string"},"title":{"type":"string"},"phase":{"type":"string","enum":["before day one","day one","first week","30 days","60 days","90 days"]},"owner":{"type":"string"},"dueOn":{"type":"string"},"note":{"type":"string"}},"required":["title"]},"bind":{"action":"add_task"},"reaction":{"gezel":"training-coordinator","prompt":"The person just added a step to a new hire's plan on the onboarding page. The plans now read (the first sentence is what changed):\n{{output.summary}}\nIn two short sentences, confirm the step with its owner and due date, and name that hire's next open step. Do not call tools.","hideSeed":true}}],"pages":{"entry":"plans/index.html","api":1,"reads":[{"source":"workspace","path":"hires.json"},{"source":"workspace","path":"tasks.json"}],"tools":["page_add_hire","page_complete_task","page_add_task"]},"schedules":[],"workspaceSeed":["hires.json","tasks.json"],"artifactsSeed":[],"availableVersions":["1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"novel-writing-room","name":"Novel Writing Room","description":"A room for the long haul of a novel. A warm writing partner logs every writing session, keeps the chapter board honest, and reads drafts like a friend who wants the book to exist — with a live board of words and chapters.","tags":["writing","novel","fiction","drafting","wordcount"],"category":"writing","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.5","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"title":{"type":"string","title":"Working title","description":"The novel, as it is known today. Change it any time.","default":"Untitled"},"weeklyWordGoal":{"type":"number","title":"Words per week","description":"The weekly writing rhythm to aim for.","default":5000}},"required":["title","weeklyWordGoal"]},"nameTemplate":"Novel: {{title}}","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"schrijfmaat","voorman":true}],"toolsets":[],"craftbooks":["copy-review","ebook-compile"],"scripts":{"manuscript-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { logStore, rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'manuscript-store',\n description:\n \"Read and update the manuscript record (sessions.json + chapters.json). Call action:'status' for total words, weekly pace, and the chapter board; 'log_session' after every writing session (words written); 'add_chapter' / 'chapter_stage' to keep the board honest; 'outline' to list every chapter.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'status', 'log_session', 'add_chapter', 'chapter_stage', or 'outline'.\",\n required: true,\n },\n words: { type: 'number', description: 'Words written this session (log_session).' },\n note: { type: 'string', description: 'Anything worth remembering.' },\n title: { type: 'string', description: 'Chapter title (add_chapter).' },\n summary: { type: 'string', description: 'One-line chapter summary (add_chapter).' },\n id: { type: 'string', description: \"Chapter id, e.g. 'ch-3' (chapter_stage).\" },\n stage: {\n type: 'string',\n description: \"Target stage: 'outline', 'drafting', 'revised', or 'done' (chapter_stage).\",\n },\n },\n outputs: {\n totalWords: { type: 'number', description: 'Words logged across all sessions.' },\n thisWeekWords: { type: 'number', description: 'Words logged this week (Monday UTC start).' },\n chapters: { type: 'number', description: 'Chapters on the board.' },\n summary: { type: 'string', description: 'The manuscript picture.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── novel-rules-start ──\n// Pure derivations over logStore-shaped writing sessions (kind 'writing',\n// data {words}) and rosterStore-shaped chapters (stages outline → drafting\n// → revised → done). Weeks start Monday 00:00 UTC; nowIso is a parameter\n// so the rules stay clock-independent and testable.\n\nfunction sessionWords(e) {\n var words = e && e.data ? Number(e.data.words) : NaN;\n return isFinite(words) && words > 0 ? Math.round(words) : 0;\n}\n\nfunction totalWords(events) {\n return events.reduce(function (sum, e) {\n return sum + sessionWords(e);\n }, 0);\n}\n\nfunction weekStartMs(nowIso) {\n var day = new Date(nowIso.slice(0, 10) + 'T00:00:00Z');\n var sinceMonday = (day.getUTCDay() + 6) % 7;\n return day.getTime() - sinceMonday * 86400000;\n}\n\nfunction thisWeekWords(events, nowIso) {\n var start = weekStartMs(nowIso);\n return totalWords(\n events.filter(function (e) {\n return Date.parse(e.at) >= start;\n }),\n );\n}\n\nfunction chapterShape(records) {\n var byStage = { outline: 0, drafting: 0, revised: 0, done: 0 };\n records.forEach(function (r) {\n if (byStage[r.status] !== undefined) byStage[r.status] += 1;\n });\n return byStage;\n}\n\nfunction novelLine(events, records, nowIso, weeklyWordGoal) {\n var total = totalWords(events);\n var week = thisWeekWords(events, nowIso);\n var shape = chapterShape(records);\n var goal = weeklyWordGoal > 0 ? weeklyWordGoal : 0;\n return (\n total +\n ' words logged; ' +\n week +\n (goal > 0 ? ' of ' + goal : '') +\n ' this week. Chapters: ' +\n shape.outline +\n ' outlined, ' +\n shape.drafting +\n ' drafting, ' +\n shape.revised +\n ' revised, ' +\n shape.done +\n ' done.'\n );\n}\n// ── novel-rules-end ──\n\nconst sessions = logStore(gezel.fs, 'sessions.json');\nconst chapters = rosterStore(gezel.fs, 'chapters.json', {\n stages: ['outline', 'drafting', 'revised', 'done'],\n idPrefix: 'ch',\n});\n\nasync function readWeeklyWordGoal(): Promise<number> {\n try {\n const parsed = JSON.parse(await gezel.fs.read('sessions.json')) as { weeklyWordGoal?: unknown };\n const goal = Number(parsed.weeklyWordGoal);\n return Number.isFinite(goal) && goal > 0 ? Math.round(goal) : 0;\n } catch {\n return 0;\n }\n}\n\nif (input.action === 'log_session') {\n const words = Number(input.words);\n if (!Number.isFinite(words) || words <= 0) {\n throw new Error(\"log_session needs a positive 'words' count.\");\n }\n await sessions.append({\n kind: 'writing',\n ...(input.note ? { note: input.note } : {}),\n data: { words: Math.round(words) },\n });\n} else if (input.action === 'add_chapter') {\n if (!input.title) throw new Error(\"add_chapter needs a 'title'.\");\n await chapters.add({\n fields: { title: input.title, ...(input.summary ? { summary: input.summary } : {}) },\n ...(input.note ? { note: input.note } : {}),\n });\n} else if (input.action === 'chapter_stage') {\n if (!input.id || !input.stage) {\n throw new Error(\"chapter_stage needs 'id' (e.g. 'ch-3') and 'stage'.\");\n }\n await chapters.transition(input.id, input.stage, input.note ? { note: input.note } : undefined);\n} else if (input.action !== 'status' && input.action !== 'outline') {\n throw new Error(\n `Unknown action '${input.action}'. Use status, log_session, add_chapter, chapter_stage, or outline.`,\n );\n}\n\nconst events = await sessions.list();\nconst records = await chapters.list();\nconst weeklyWordGoal = await readWeeklyWordGoal();\nconst nowIso = new Date().toISOString();\nconst listing =\n input.action === 'outline'\n ? records\n .map(\n (r) =>\n `${r.id} [${r.status}] ${String(r.fields.title ?? '')}${r.fields.summary ? ` — ${String(r.fields.summary)}` : ''}`,\n )\n .join('\\n') || 'No chapters on the board yet.'\n : '';\n\ngezel.output({\n totalWords: totalWords(events),\n thisWeekWords: thisWeekWords(events, nowIso),\n chapters: records.length,\n summary: listing || novelLine(events, records, nowIso, weeklyWordGoal),\n});\n"},"tools":[{"name":"log_session","description":"Log a writing session (words written) the moment it is reported.","script":"manuscript-store","inputs":{"type":"object","properties":{"words":{"type":"number"},"note":{"type":"string"}},"required":["words"]},"bind":{"action":"log_session"}},{"name":"add_chapter","description":"Put a chapter on the board (starts in outline).","script":"manuscript-store","inputs":{"type":"object","properties":{"title":{"type":"string"},"summary":{"type":"string"}},"required":["title"]},"bind":{"action":"add_chapter"}},{"name":"chapter_stage","description":"Move a chapter between stages: 'outline', 'drafting', 'revised', 'done'.","script":"manuscript-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"stage":{"type":"string"},"note":{"type":"string"}},"required":["id","stage"]},"bind":{"action":"chapter_stage"}},{"name":"novel_status","description":"Total words, this week against the goal, the chapter shape.","script":"manuscript-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"}},{"name":"outline","description":"Every chapter with its stage and summary.","script":"manuscript-store","inputs":{"type":"object","properties":{}},"bind":{"action":"outline"}},{"name":"page_log_session","description":"Log a writing session (words written) the moment it is reported.","script":"manuscript-store","inputs":{"type":"object","properties":{"words":{"type":"number"},"note":{"type":"string"}},"required":["words"]},"bind":{"action":"log_session"}},{"name":"page_add_chapter","description":"Put a chapter on the board (starts in outline).","script":"manuscript-store","inputs":{"type":"object","properties":{"title":{"type":"string"},"summary":{"type":"string"}},"required":["title"]},"bind":{"action":"add_chapter"}},{"name":"page_chapter_stage","description":"Move a chapter between stages: 'outline', 'drafting', 'revised', 'done'.","script":"manuscript-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"stage":{"type":"string"},"note":{"type":"string"}},"required":["id","stage"]},"bind":{"action":"chapter_stage"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"sessions.json"},{"source":"workspace","path":"chapters.json"}],"tools":["page_log_session","page_add_chapter","page_chapter_stage"]},"schedules":[],"workspaceSeed":["sessions.json","chapters.json"],"artifactsSeed":[],"availableVersions":["1.0.5","1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"quotes-and-bids","name":"Quotes & Bids","description":"Price the job and send quotes and bids that win work. An estimator builds each quote line by line from materials and labor at your own rates, keeps every total exact to the cent, follows up on what you sent, and tracks what you win and lose.","tags":["quotes","estimates","bids","trades","pricing","small-business"],"category":"business","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.0.0","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"business":{"type":"string","title":"What kind of business is this?","description":"e.g. 'a three-person electrical contractor', 'a painting and drywall crew'.","default":"the business"}},"required":["business"]},"nameTemplate":"Quotes & Bids","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"estimator","voorman":true},{"templateId":"kantoormeester","voorman":false}],"toolsets":[{"id":"docblocks","need":"suggested","autoAllow":[],"reason":"Turns a finished quote into a PDF or Word document to send."}],"craftbooks":["proposal-sow","invoice-generator"],"scripts":{"quote-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'quote-store',\n description:\n \"Price jobs and track quotes (quotes.json) at the business's own rates, tax and terms (rates.json). action:'status' for every quote with its exact total, the follow-ups due and the win/loss record; 'add' to start a quote (an existing title is updated, never duplicated); 'add_line' and 'remove_line' to price it (the script works out every amount and the tax); 'send', 'follow_up' and 'outcome' as it moves; 'set_rate' and 'set_terms' for the business's rates, tax and quote terms; 'show' for one quote line by line.\",\n inputs: {\n action: {\n type: 'string',\n description:\n \"One of 'status', 'add', 'add_line', 'remove_line', 'send', 'follow_up', 'outcome', 'set_rate', 'set_terms', 'show', or 'list'.\",\n required: true,\n },\n id: { type: 'string', description: \"Quote id, e.g. 'q-3'.\" },\n title: {\n type: 'string',\n description: \"The job, e.g. 'Harbor Street Café kitchen rewire'. Also finds the quote (or its client) when no id is given.\",\n },\n client: { type: 'string', description: 'Who the quote is for.' },\n contact: { type: 'string', description: 'The person there.' },\n site: { type: 'string', description: 'Where the work is.' },\n kind: { type: 'string', description: 'labor, materials, or other.' },\n description: { type: 'string', description: \"What the line is, e.g. 'Electrician labor' or '200A panel'.\" },\n qty: { type: 'number', description: 'Quantity, e.g. 16 hours or 2 panels (default 1).' },\n addQty: { type: 'number', description: \"Add to the quantity of the line with this description, e.g. 6 more hours.\" },\n unit: { type: 'string', description: 'hour, each, foot, or lot.' },\n rate: { type: 'number', description: 'Price per unit in dollars, e.g. 95.' },\n rateName: { type: 'string', description: \"A saved rate by name, e.g. 'Electrician'; it fills the rate, unit and kind.\" },\n line: { type: 'number', description: 'Line number, for remove_line.' },\n name: { type: 'string', description: \"For set_rate: the rate's name, e.g. 'Electrician'.\" },\n taxRate: { type: 'number', description: 'For set_terms: the sales tax percent the business charges, e.g. 8.25 (0 for none).' },\n taxOn: { type: 'string', description: 'For set_terms: materials (tax on materials only) or all (the whole quote).' },\n validDays: { type: 'number', description: 'How many days a quote stays valid after sending.' },\n followUpDays: { type: 'number', description: 'For set_terms: days after sending to follow up.' },\n followUpAt: { type: 'string', description: 'Next follow-up date, YYYY-MM-DD.' },\n inDays: { type: 'number', description: 'Next follow-up this many days from today, instead of followUpAt.' },\n outcome: { type: 'string', description: 'won or lost.' },\n note: { type: 'string', description: 'What happened or why, in the words given.' },\n withinDays: { type: 'number', description: 'How many days ahead counts for follow-ups (default 7).' },\n },\n outputs: {\n drafts: { type: 'number', description: 'Quotes still being priced.' },\n waiting: { type: 'number', description: 'Quotes sent and waiting for an answer.' },\n followUpsDue: { type: 'number', description: 'Follow-ups overdue or due today.' },\n total: { type: 'number', description: 'The total of the quote this call acted on, in dollars (0 when none).' },\n summary: { type: 'string', description: 'What changed, then the quotes picture; or one quote line by line; or the listing.' },\n },\n requires: ['workspace.read', 'workspace.write', 'reminders'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── quote-rules-start ──\n// Pure derivations: money in integer cents, line amounts and quote totals that\n// are exact to the cent (quantities to a thousandth, tax rates in basis\n// points, both rounded half up), local calendar days for follow-ups, finding a\n// quote or a line by name, and the quotes picture the crew reads. Kept\n// self-contained between these sentinels so unit tests execute the shipped\n// bytes.\nvar DAY_MS = 86400000;\nvar STAGES = ['draft', 'sent', 'won', 'lost'];\nvar KINDS = ['labor', 'materials', 'other'];\nvar NAME_STOP = ['the', 'and', 'for', 'with', 'our', 'quote', 'bid', 'job', 'estimate'];\n\nfunction pad(n) {\n return n < 10 ? '0' + n : String(n);\n}\nfunction localDay(ms) {\n var d = new Date(ms);\n return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());\n}\nfunction normalizeDate(text) {\n var raw = String(text || '').trim();\n if (/^\\d{4}-\\d{2}-\\d{2}/.test(raw)) return raw.slice(0, 10);\n var parsed = Date.parse(raw);\n return isFinite(parsed) ? localDay(parsed) : null;\n}\nfunction daysLeft(day, nowMs) {\n var due = Date.parse(String(day).slice(0, 10) + 'T00:00:00');\n var today = Date.parse(localDay(nowMs) + 'T00:00:00');\n return Math.round((due - today) / DAY_MS);\n}\nfunction addDays(day, n) {\n var d = new Date(String(day).slice(0, 10) + 'T12:00:00');\n d.setDate(d.getDate() + n);\n return localDay(d.getTime());\n}\nfunction when(days) {\n if (days < 0) return -days + (days === -1 ? ' day late' : ' days late');\n if (days === 0) return 'today';\n if (days === 1) return 'tomorrow';\n return 'in ' + days + ' days';\n}\nfunction cap(text) {\n return String(text).charAt(0).toUpperCase() + String(text).slice(1);\n}\nfunction ago(days) {\n return days <= 0 ? 'today' : days === 1 ? 'yesterday' : days + ' days ago';\n}\n// Dollars as a number or text ('$1,850', '95.50') to integer cents; null when it is not money.\nfunction toCents(value) {\n if (typeof value === 'string') value = Number(value.replace(/[$,\\s]/g, ''));\n if (typeof value !== 'number' || !isFinite(value)) return null;\n return (value < 0 ? -1 : 1) * Math.round(Math.abs(value) * 100);\n}\n// A quantity in thousandths, so 6.5 hours or 12.25 feet multiply exactly.\nfunction toMilli(qty) {\n if (typeof qty === 'string') qty = Number(qty.replace(/[,\\s]/g, ''));\n return typeof qty === 'number' && isFinite(qty) && qty > 0 ? Math.round(qty * 1000) : null;\n}\nfunction money(cents) {\n var n = Math.round(Number(cents) || 0);\n var abs = Math.abs(n);\n var whole = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\n return (n < 0 ? '-$' : '$') + whole + '.' + pad(abs % 100);\n}\nfunction percent(bp) {\n return (bp / 100).toFixed(2).replace(/\\.?0+$/, '') + '%';\n}\nfunction fold(text) {\n return String(text || '')\n .normalize('NFD')\n .replace(/[̀-ͯ]/g, '')\n .replace(/[‘’]/g, \"'\")\n .toLowerCase()\n .trim();\n}\n// Quantity times rate, rounded half away from zero to the cent.\nfunction lineAmount(qtyMilli, rateCents) {\n var x = qtyMilli * rateCents;\n return (x < 0 ? -1 : 1) * Math.floor((Math.abs(x) + 500) / 1000);\n}\nfunction qtyText(qty, unit) {\n var n = Math.round(Number(qty) * 1000) / 1000;\n var u = String(unit || 'each');\n if (n === 1 || u === 'each' || u === 'lot' || /s$/.test(u)) return n + ' ' + u;\n return n + ' ' + (u === 'foot' ? 'feet' : /(x|ch|sh)$/.test(u) ? u + 'es' : u + 's');\n}\nfunction totals(lines, taxBp, taxOn) {\n var t = { labor: 0, materials: 0, other: 0, subtotal: 0, taxable: 0, tax: 0, total: 0 };\n (lines || []).forEach(function (l) {\n var a = Number(l.amountCents) || 0;\n t[KINDS.indexOf(l.kind) >= 0 ? l.kind : 'other'] += a;\n t.subtotal += a;\n });\n t.taxable = Math.max(0, taxOn === 'all' ? t.subtotal : t.materials);\n t.tax = Math.floor((t.taxable * (taxBp || 0) + 5000) / 10000);\n t.total = t.subtotal + t.tax;\n return t;\n}\nfunction quoteTotals(record) {\n var f = record.fields || {};\n return totals(f.lines, f.taxBp, f.taxOn);\n}\n// The fields a quote stores beside its lines, so a reader never re-adds them.\nfunction totalFields(lines, taxBp, taxOn) {\n var t = totals(lines, taxBp, taxOn);\n return { laborCents: t.labor, materialsCents: t.materials, otherCents: t.other, subtotalCents: t.subtotal, taxCents: t.tax, totalCents: t.total };\n}\nfunction normalizeTerms(doc) {\n var d = doc && typeof doc === 'object' ? doc : {};\n var whole = function (v, fallback) {\n return typeof v === 'number' && Number.isInteger(v) && v > 0 ? v : fallback;\n };\n return {\n version: 1,\n taxBp: typeof d.taxBp === 'number' && Number.isInteger(d.taxBp) && d.taxBp >= 0 ? d.taxBp : 0,\n taxOn: d.taxOn === 'all' ? 'all' : 'materials',\n validDays: whole(d.validDays, 30),\n followUpDays: whole(d.followUpDays, 5),\n rates: (Array.isArray(d.rates) ? d.rates : []).filter(function (r) {\n return r && typeof r.name === 'string' && typeof r.rateCents === 'number' && Number.isInteger(r.rateCents);\n }),\n };\n}\nfunction rateText(r) {\n return r.name + ' ' + money(r.rateCents) + '/' + r.unit + ' (' + r.kind + ')';\n}\nfunction findRate(rates, name) {\n var wanted = fold(name);\n if (!wanted) return null;\n var exact = rates.filter(function (r) { return fold(r.name) === wanted; });\n if (exact.length) return exact[0];\n var partial = rates.filter(function (r) { return fold(r.name).indexOf(wanted) >= 0 || wanted.indexOf(fold(r.name)) >= 0; });\n return partial.length === 1 ? partial[0] : null;\n}\nfunction lineText(l) {\n return '#' + l.n + ' ' + l.description + ', ' + qtyText(l.qty, l.unit) + ' x ' + money(l.rateCents) + ' = ' + money(l.amountCents) + ' (' + l.kind + ')';\n}\n// Add a line, or change the one with the same description. Returns the new\n// list and what changed; the caller re-totals.\nfunction upsertLine(lines, input, terms) {\n var list = (lines || []).map(function (l) { return Object.assign({}, l); });\n var saved = input.rateName ? findRate(terms.rates, input.rateName) : null;\n if (input.rateName && !saved) {\n throw new Error(\n \"No saved rate named '\" + input.rateName + \"'. Saved rates: \" +\n (terms.rates.map(rateText).join(', ') || 'none yet; pass rate in dollars') + '.',\n );\n }\n var description = String(input.description || (saved && saved.name) || '').trim();\n if (!description) throw new Error(\"add_line needs 'description', e.g. 'Electrician labor' or '200A panel'.\");\n var existing = list.filter(function (l) { return fold(l.description) === fold(description); })[0] || null;\n if (!existing && !saved && (input.rate === undefined || input.rate === null || input.rate === '')) saved = findRate(terms.rates, description);\n var rateCents =\n input.rate !== undefined && input.rate !== null && input.rate !== ''\n ? toCents(input.rate)\n : saved ? saved.rateCents : existing ? existing.rateCents : null;\n if (rateCents === null) {\n throw new Error(\n \"'\" + description + \"' needs 'rate' (dollars per unit) or 'rateName'\" +\n (terms.rates.length ? ' from the saved rates: ' + terms.rates.map(rateText).join(', ') : '') + '.',\n );\n }\n var kind = KINDS.indexOf(input.kind) >= 0 ? input.kind : saved ? saved.kind : existing ? existing.kind : 'other';\n if (rateCents < 0 && kind !== 'other') throw new Error('Only an \"other\" line can be a credit with a negative rate.');\n var unit = input.unit ? String(input.unit).trim() : saved ? saved.unit : existing ? existing.unit : 'each';\n var add = input.addQty !== undefined && input.addQty !== null && input.addQty !== '' ? toMilli(input.addQty) : null;\n var set = input.qty !== undefined && input.qty !== null && input.qty !== '' ? toMilli(input.qty) : null;\n if (add === null && input.addQty !== undefined && input.addQty !== null && input.addQty !== '') throw new Error('addQty must be a positive number.');\n if (set === null && input.qty !== undefined && input.qty !== null && input.qty !== '') throw new Error('qty must be a positive number.');\n var before = existing ? Math.round(existing.qty * 1000) : 0;\n var qtyMilli = add !== null ? before + add : set !== null ? set : existing ? before : 1000;\n var line = { description: existing ? existing.description : description, kind: kind, qty: qtyMilli / 1000, unit: unit, rateCents: rateCents, amountCents: lineAmount(qtyMilli, rateCents) };\n if (existing) Object.assign(existing, line);\n else list.push(line);\n list.forEach(function (l, i) { l.n = i + 1; });\n var placed = existing || list[list.length - 1];\n return {\n lines: list,\n note:\n (existing ? 'Updated line ' : 'Added line ') + lineText(placed) +\n (existing && add !== null ? ' (' + before / 1000 + ' + ' + add / 1000 + ')' : '') + '.',\n };\n}\nfunction removeLine(lines, input) {\n var list = (lines || []).map(function (l) { return Object.assign({}, l); });\n var hit = null;\n if (input.line !== undefined && input.line !== null && input.line !== '') {\n hit = list.filter(function (l) { return l.n === Number(input.line); })[0] || null;\n } else if (input.description) {\n var wanted = fold(input.description);\n var exact = list.filter(function (l) { return fold(l.description) === wanted; });\n var partial = list.filter(function (l) { return fold(l.description).indexOf(wanted) >= 0; });\n hit = exact[0] || (partial.length === 1 ? partial[0] : null);\n }\n if (!hit) {\n throw new Error(\n \"Name the line by 'line' number or 'description'. Lines: \" + (list.map(lineText).join('; ') || 'none') + '.',\n );\n }\n var rest = list.filter(function (l) { return l !== hit; });\n rest.forEach(function (l, i) { l.n = i + 1; });\n return { lines: rest, note: 'Removed ' + hit.description + ' (' + money(hit.amountCents) + ').' };\n}\nfunction isOpen(record) {\n return record.status === 'draft' || record.status === 'sent';\n}\n// The quote a person means: its id, its exact title, a title or client that\n// contains what they wrote, or one whose name holds every word they used.\n// Several matches prefer the open quotes; a tie is an error that names them.\nfunction findQuote(records, input) {\n if (input.id) {\n var byId = records.filter(function (r) { return r.id === String(input.id).trim(); });\n if (byId.length) return byId[0];\n if (!input.title && !input.client) throw new Error(\"No quote '\" + input.id + \"'. \" + roll(records));\n }\n var wanted = fold(input.title || input.client);\n if (!wanted) throw new Error(\"Pass 'id' (e.g. 'q-3') or the quote's 'title'. \" + roll(records));\n var name = function (r) { return fold(r.fields.title); };\n var both = function (r) { return name(r) + ' ' + fold(r.fields.client); };\n var words = wanted.split(/[^a-z0-9']+/).filter(function (w) { return w.length > 2 && NAME_STOP.indexOf(w) < 0; });\n var tiers = [\n function (r) { return name(r) === wanted; },\n function (r) { return name(r).indexOf(wanted) >= 0 || fold(r.fields.client) === wanted; },\n function (r) {\n return words.length > 0 && words.every(function (w) { return both(r).indexOf(w) >= 0 || both(r).indexOf(w.replace(/s$/, '')) >= 0; });\n },\n ];\n for (var i = 0; i < tiers.length; i++) {\n var hits = records.filter(tiers[i]);\n if (hits.length > 1) {\n var open = hits.filter(isOpen);\n if (open.length) hits = open;\n }\n if (hits.length === 1) return hits[0];\n if (hits.length > 1) {\n throw new Error(\n \"More than one quote matches '\" + (input.title || input.client) + \"': \" +\n hits.map(function (r) { return r.id + ' ' + r.fields.title; }).join(', ') + '. Pass id.',\n );\n }\n }\n throw new Error(\"No quote matches '\" + (input.title || input.client) + \"'. \" + roll(records));\n}\nfunction roll(records) {\n return records.length\n ? 'Quotes: ' + records.map(function (r) { return r.id + ' ' + r.fields.title + ' (' + r.status + ')'; }).join(', ') + '.'\n : 'There are no quotes yet.';\n}\nfunction lastNote(record) {\n var notes = (record.history || []).filter(function (h) { return h.note; });\n return notes.length ? notes[notes.length - 1].note : '';\n}\nfunction quoteLine(record, nowMs) {\n var f = record.fields || {};\n var t = quoteTotals(record);\n var lines = (f.lines || []).length;\n var head =\n record.id + (f.client && fold(f.title).indexOf(fold(f.client)) < 0 ? ', ' + f.client : '') + ', ' + record.status + ', ' +\n lines + (lines === 1 ? ' line' : ' lines') + ', total ' + money(t.total) + (t.tax ? ' with ' + money(t.tax) + ' tax' : '');\n var parts = [head];\n if (record.status === 'sent') {\n if (f.sentAt) parts.push('sent ' + ago(-daysLeft(f.sentAt, nowMs)));\n if (f.followUpAt) parts.push('follow up ' + when(daysLeft(f.followUpAt, nowMs)) + ' (' + f.followUpAt + ')');\n if (f.validUntil) parts.push((daysLeft(f.validUntil, nowMs) < 0 ? 'expired ' : 'valid until ') + f.validUntil);\n }\n if (!isOpen(record) && f.closedAt) parts.push(record.status + ' ' + f.closedAt + (f.reason ? ': ' + f.reason : ''));\n return f.title + ' (' + parts.join('; ') + ')';\n}\nfunction followLine(record, nowMs) {\n var f = record.fields;\n var note = lastNote(record).replace(/[.\\s]+$/, '');\n return (\n f.title + ' (' + record.id + (f.contact ? ', ' + f.contact : '') + ', ' + money(quoteTotals(record).total) +\n (f.sentAt ? ', sent ' + ago(-daysLeft(f.sentAt, nowMs)) : '') + ') ' + when(daysLeft(f.followUpAt, nowMs)) +\n (note && note !== 'Sent to the client' ? '; last note: ' + note : '')\n );\n}\nfunction picture(records, terms, nowMs, withinDays) {\n var byStatus = function (s) { return records.filter(function (r) { return r.status === s; }); };\n var drafts = byStatus('draft');\n var sent = byStatus('sent');\n var won = byStatus('won');\n var lost = byStatus('lost');\n var total = function (list) { return list.reduce(function (t, r) { return t + quoteTotals(r).total; }, 0); };\n var due = sent\n .filter(function (r) { return r.fields.followUpAt && daysLeft(r.fields.followUpAt, nowMs) <= withinDays; })\n .sort(function (a, b) { return String(a.fields.followUpAt).localeCompare(String(b.fields.followUpAt)); });\n var dueNow = due.filter(function (r) { return daysLeft(r.fields.followUpAt, nowMs) <= 0; });\n var recentFirst = function (list) {\n return list.slice().sort(function (a, b) { return String(b.fields.closedAt || '').localeCompare(String(a.fields.closedAt || '')); });\n };\n var parts = [\n records.length + (records.length === 1 ? ' quote: ' : ' quotes: ') + drafts.length + ' draft, ' + sent.length +\n ' sent and waiting (' + money(total(sent)) + '), ' + won.length + ' won, ' + lost.length + ' lost.',\n ];\n // One list, overdue first: a model asked what needs chasing reads a separate late list as out of scope.\n parts.push(\n due.length\n ? 'Follow-ups within ' + withinDays + ' days, overdue first: ' + due.map(function (r) { return followLine(r, nowMs); }).join(' | ') + '.'\n : 'No follow-ups due in the next ' + withinDays + ' days.',\n );\n if (drafts.length) parts.push('Drafts: ' + drafts.map(function (r) { return quoteLine(r, nowMs); }).join(' | ') + '.');\n if (sent.length) parts.push('Sent and waiting: ' + sent.map(function (r) { return quoteLine(r, nowMs); }).join(' | ') + '.');\n if (won.length) parts.push('Won (latest first): ' + recentFirst(won).slice(0, 5).map(function (r) { return quoteLine(r, nowMs); }).join(' | ') + '.');\n if (lost.length) parts.push('Lost (latest first): ' + recentFirst(lost).slice(0, 5).map(function (r) { return quoteLine(r, nowMs); }).join(' | ') + '.');\n if (won.length + lost.length) {\n var decided = total(won) + total(lost);\n parts.push(\n 'Win rate: ' + won.length + ' of ' + (won.length + lost.length) + ' decided quotes (' + Math.round((won.length / (won.length + lost.length)) * 100) + '%), ' +\n money(total(won)) + ' of ' + money(decided) + ' by value.',\n );\n }\n parts.push(\n 'Tax: ' + (terms.taxBp ? percent(terms.taxBp) + ' on ' + (terms.taxOn === 'all' ? 'the whole quote' : 'materials') : 'none set') +\n '. Quotes stay valid ' + terms.validDays + ' days; follow up ' + terms.followUpDays + ' days after sending. Saved rates: ' +\n (terms.rates.map(rateText).join(', ') || 'none yet') + '.',\n );\n return {\n drafts: drafts.length,\n waiting: sent.length,\n followUpsDue: dueNow.length,\n summary: parts.join(' '),\n };\n}\n// One quote line by line, for the person to read or the crew to quote exactly.\nfunction detail(record, nowMs) {\n var f = record.fields || {};\n var t = quoteTotals(record);\n var rows = (f.lines || []).map(lineText);\n return [\n f.title + ' (' + record.id + ', ' + record.status + (f.client ? ', for ' + f.client : '') + (f.site ? ' at ' + f.site : '') + ').',\n rows.length ? 'Lines: ' + rows.join('; ') + '.' : 'No lines yet.',\n 'Labor ' + money(t.labor) + ', materials ' + money(t.materials) + (t.other ? ', other ' + money(t.other) : '') +\n '. Subtotal ' + money(t.subtotal) + '. Tax ' + money(t.tax) +\n (f.taxBp ? ' (' + percent(f.taxBp) + ' on ' + (f.taxOn === 'all' ? 'the whole quote' : 'materials ' + money(t.materials)) + ')' : ' (no tax set)') +\n '. Total ' + money(t.total) + '.',\n record.status === 'sent'\n ? 'Sent ' + f.sentAt + (f.followUpAt ? '; follow up ' + when(daysLeft(f.followUpAt, nowMs)) + ' (' + f.followUpAt + ')' : '') +\n (f.validUntil ? '; valid until ' + f.validUntil : '') + '.'\n : !isOpen(record) && f.closedAt\n ? cap(record.status) + ' ' + f.closedAt + (f.reason ? ': ' + f.reason : '') + '.'\n : '',\n ]\n .filter(Boolean)\n .join(' ');\n}\n// ── quote-rules-end ──\n\ntype Quote = { id: string; status: string; fields: Record<string, unknown>; history?: Array<{ note?: string }> };\ntype Line = Record<string, unknown>;\n\nconst quotes = rosterStore(gezel.fs, 'quotes.json', { stages: ['draft', 'sent', 'won', 'lost'], idPrefix: 'q' });\nconst now = Date.now();\nconst today = localDay(now);\n\nfunction given(value: unknown): boolean {\n return value !== undefined && value !== null && value !== '';\n}\n\nasync function readTerms(): Promise<ReturnType<typeof normalizeTerms>> {\n let raw: string | null = null;\n try {\n raw = await gezel.fs.read('rates.json');\n } catch {\n raw = null;\n }\n if (raw === null) return normalizeTerms(null);\n try {\n return normalizeTerms(JSON.parse(raw));\n } catch {\n throw new Error('rates.json is not valid JSON. Fix or remove it; it will not be overwritten automatically.');\n }\n}\n\nasync function writeTerms(terms: ReturnType<typeof normalizeTerms>): Promise<void> {\n await gezel.fs.write('rates.json', JSON.stringify(terms, null, 2) + '\\n');\n}\n\nfunction followUpInput(): string | undefined {\n if (typeof input.inDays === 'number' && isFinite(input.inDays)) return addDays(today, Math.max(0, Math.round(input.inDays)));\n if (given(input.followUpAt)) {\n const day = normalizeDate(input.followUpAt);\n if (!day) throw new Error(\"followUpAt must be a date, e.g. '2026-11-20', or pass inDays.\");\n return day;\n }\n return undefined;\n}\n\nfunction wholeDays(value: unknown, label: string): number | undefined {\n if (!given(value)) return undefined;\n const n = Number(value);\n if (!isFinite(n) || n < 1 || n > 365) throw new Error(label + ' is a number of days from 1 to 365.');\n return Math.round(n);\n}\n\n// Lines change only on an open quote; a sent one goes back to draft so the\n// client is never holding a price the register no longer shows.\nasync function reprice(record: Quote, lines: Line[], what: string): Promise<string> {\n const f = record.fields;\n const title = String(f.title);\n if (!isOpen(record)) throw new Error(title + ' is ' + record.status + '; its price is settled. Start a new quote for more work.');\n await quotes.update(record.id, { fields: { lines, ...totalFields(lines, f.taxBp, f.taxOn) } });\n let tail = '';\n if (record.status === 'sent') {\n await quotes.update(record.id, { fields: { followUpAt: null } });\n await quotes.transition(record.id, 'draft', { note: 'Revised after sending: ' + what });\n tail = ' It had been sent, so it is back in draft: send it again when the client should see the new price.';\n }\n return what + ' ' + title + ' total now ' + money(totals(lines, f.taxBp, f.taxOn).total) + '.' + tail;\n}\n\n// The quotes' one reminder sits on the soonest follow-up, the morning it is due.\nasync function remindNextFollowUp(): Promise<void> {\n const next = (await quotes.list())\n .filter((r) => r.status === 'sent' && typeof r.fields.followUpAt === 'string')\n .map((r) => ({ record: r, at: Date.parse(String(r.fields.followUpAt) + 'T09:00:00') }))\n .filter((r) => r.at > now)\n .sort((a, b) => a.at - b.at)[0];\n try {\n if (!next || next.at - now > 30 * DAY_MS) await gezel.reminder.clear();\n else {\n const f = next.record.fields;\n await gezel.reminder.set({\n at: new Date(next.at).toISOString(),\n title: ('Follow up on the quote for ' + String(f.client || f.title)).slice(0, 80),\n body: (String(f.title) + ', ' + money(quoteTotals(next.record).total) + ', sent ' + String(f.sentAt) + '.').slice(0, 160),\n });\n }\n } catch {\n // Reminders are a convenience; the quotes are the record.\n }\n}\n\nconst withinDays = typeof input.withinDays === 'number' && input.withinDays > 0 ? Math.round(input.withinDays) : 7;\nlet note = '';\nlet acted: string | null = null;\nlet shown = '';\n\nif (input.action === 'add') {\n const all = (await quotes.list()) as Quote[];\n const title = String(input.title || input.client || '').trim();\n let existing: Quote | null = null;\n if (given(input.id)) existing = findQuote(all, { id: input.id, title: input.title });\n else if (title) existing = all.find((r) => fold(r.fields.title) === fold(title)) ?? null;\n if (!existing && !title) throw new Error(\"add needs 'title': the job, e.g. 'Maple Row panel upgrade'.\");\n const fields: Record<string, unknown> = {};\n if (input.client) fields.client = input.client.trim();\n if (input.contact) fields.contact = input.contact.trim();\n if (input.site) fields.site = input.site.trim();\n if (input.note) fields.note = input.note.trim();\n if (existing) {\n if (given(input.id) && input.title && fold(input.title) !== fold(existing.fields.title)) fields.title = input.title.trim();\n await quotes.update(existing.id, { fields });\n acted = existing.id;\n note = 'Updated ' + String(existing.fields.title) + '.';\n } else {\n const terms = await readTerms();\n const record = await quotes.add({\n status: 'draft',\n fields: { title, ...fields, lines: [], taxBp: terms.taxBp, taxOn: terms.taxOn, ...totalFields([], terms.taxBp, terms.taxOn) },\n });\n acted = record.id;\n note = 'Started ' + record.id + ': ' + title + ' (draft). Add its lines next.';\n }\n} else if (input.action === 'add_line' || input.action === 'remove_line') {\n const record = findQuote((await quotes.list()) as Quote[], input);\n const lines = (record.fields.lines ?? []) as Line[];\n const change = input.action === 'add_line' ? upsertLine(lines, input, await readTerms()) : removeLine(lines, input);\n note = await reprice(record, change.lines, change.note);\n acted = record.id;\n} else if (input.action === 'send') {\n const record = findQuote((await quotes.list()) as Quote[], input);\n const title = String(record.fields.title);\n acted = record.id;\n if (record.status === 'sent') note = title + ' was already sent on ' + String(record.fields.sentAt) + '.';\n else if (!isOpen(record)) throw new Error(title + ' is ' + record.status + '; it cannot be sent again.');\n else {\n if (!((record.fields.lines ?? []) as Line[]).length) throw new Error(title + ' has no lines yet; add them before sending.');\n const terms = await readTerms();\n const validUntil = addDays(today, wholeDays(input.validDays, 'validDays') ?? terms.validDays);\n const follow = followUpInput() ?? addDays(today, terms.followUpDays);\n await quotes.update(record.id, { fields: { sentAt: today, validUntil, followUpAt: follow } });\n await quotes.transition(record.id, 'sent', { note: input.note || 'Sent to the client.' });\n note = 'Sent ' + title + ', total ' + money(quoteTotals(record).total) + '. Valid until ' + validUntil + '; first follow-up ' + follow + '.';\n }\n} else if (input.action === 'follow_up') {\n const record = findQuote((await quotes.list()) as Quote[], input);\n const title = String(record.fields.title);\n if (record.status !== 'sent') {\n throw new Error(title + ' is ' + record.status + (record.status === 'draft' ? '; send it before following up.' : '; it is closed.'));\n }\n const next = followUpInput() ?? addDays(today, (await readTerms()).followUpDays);\n await quotes.update(record.id, { fields: { followUpAt: next, lastFollowUpAt: today }, note: input.note || 'Followed up.' });\n acted = record.id;\n note = 'Logged the follow-up on ' + title + (input.note ? ': ' + input.note.trim() : '') + '. Next follow-up ' + next + '.';\n} else if (input.action === 'outcome') {\n const outcome = String(input.outcome || '').trim().toLowerCase();\n if (outcome !== 'won' && outcome !== 'lost') throw new Error(\"outcome needs 'outcome': won or lost.\");\n const record = findQuote((await quotes.list()) as Quote[], input);\n const title = String(record.fields.title);\n acted = record.id;\n if (record.status === outcome) note = title + ' is already ' + outcome + '.';\n else if (!isOpen(record)) throw new Error(title + ' is already ' + record.status + '.');\n else {\n await quotes.update(record.id, { fields: { closedAt: today, followUpAt: null, ...(input.note ? { reason: input.note.trim() } : {}) } });\n await quotes.transition(record.id, outcome, { note: input.note || (outcome === 'won' ? 'Won.' : 'Lost.') });\n note = (outcome === 'won' ? 'Won ' : 'Lost ') + title + ', ' + money(quoteTotals(record).total) + (input.note ? ' (' + input.note.trim() + ')' : '') + '.';\n }\n} else if (input.action === 'set_rate') {\n const name = String(input.name || input.description || '').trim();\n if (!name) throw new Error(\"set_rate needs 'name', e.g. 'Electrician'.\");\n const rateCents = toCents(input.rate);\n if (rateCents === null || rateCents < 0) throw new Error(\"set_rate needs 'rate' in dollars per unit, e.g. 95.\");\n const kind = KINDS.indexOf(String(input.kind)) >= 0 ? String(input.kind) : 'labor';\n const unit = input.unit ? input.unit.trim() : kind === 'labor' ? 'hour' : 'each';\n const terms = await readTerms();\n const at = terms.rates.findIndex((r) => fold(r.name) === fold(name));\n const rate = { name, kind, unit, rateCents };\n if (at >= 0) terms.rates[at] = rate;\n else terms.rates.push(rate);\n await writeTerms(terms);\n note = (at >= 0 ? 'Updated the rate ' : 'Saved the rate ') + rateText(rate) + '. Lines already on quotes keep their price; new lines use this one.';\n} else if (input.action === 'set_terms') {\n const terms = await readTerms();\n let changed = false;\n if (given(input.taxRate)) {\n const p = Number(String(input.taxRate).replace('%', ''));\n if (!isFinite(p) || p < 0 || p > 50) throw new Error('taxRate is a percent, e.g. 8.25 (0 for none).');\n terms.taxBp = Math.round(p * 100);\n changed = true;\n }\n if (given(input.taxOn)) {\n const on = String(input.taxOn).trim().toLowerCase();\n if (on !== 'materials' && on !== 'all') throw new Error('taxOn is materials or all.');\n terms.taxOn = on;\n changed = true;\n }\n const valid = wholeDays(input.validDays, 'validDays');\n if (valid !== undefined) terms.validDays = valid;\n const follow = wholeDays(input.followUpDays, 'followUpDays');\n if (follow !== undefined) terms.followUpDays = follow;\n if (!changed && valid === undefined && follow === undefined) throw new Error('set_terms needs taxRate, taxOn, validDays or followUpDays.');\n await writeTerms(terms);\n // Drafts follow the business's tax; sent and closed quotes keep the tax they went out with.\n const drafts = (await quotes.list()).filter((r) => r.status === 'draft');\n for (const d of drafts) {\n await quotes.update(d.id, {\n fields: { taxBp: terms.taxBp, taxOn: terms.taxOn, ...totalFields((d.fields.lines ?? []) as Line[], terms.taxBp, terms.taxOn) },\n });\n }\n note =\n 'Tax is ' + (terms.taxBp ? percent(terms.taxBp) + ' on ' + (terms.taxOn === 'all' ? 'the whole quote' : 'materials') : 'not charged') +\n '; quotes stay valid ' + terms.validDays + ' days; follow up ' + terms.followUpDays + ' days after sending.' +\n (drafts.length ? ' Re-totaled ' + drafts.length + (drafts.length === 1 ? ' draft' : ' drafts') + '; sent quotes keep the tax they went out with.' : '');\n} else if (input.action === 'show') {\n const record = findQuote((await quotes.list()) as Quote[], input);\n acted = record.id;\n shown = detail(record, now);\n} else if (input.action !== 'status' && input.action !== 'list') {\n throw new Error(\n \"Unknown action '\" + input.action + \"'. Use status, add, add_line, remove_line, send, follow_up, outcome, set_rate, set_terms, show, or list.\",\n );\n}\n\nconst records = (await quotes.list()) as Quote[];\nconst view = picture(records, await readTerms(), now, withinDays);\nconst touched = acted ? records.find((r) => r.id === acted) : undefined;\nawait remindNextFollowUp();\n\ngezel.output({\n drafts: view.drafts,\n waiting: view.waiting,\n followUpsDue: view.followUpsDue,\n total: touched ? quoteTotals(touched).total / 100 : 0,\n summary: shown\n ? shown\n : input.action === 'list'\n ? records.map((r) => '[' + r.status + '] ' + quoteLine(r, now)).join('\\n') || 'There are no quotes yet.'\n : (note ? note + ' ' : '') + view.summary,\n});\n"},"tools":[{"name":"quotes_status","description":"Every quote with its id and exact total: the follow-ups due (overdue first), the drafts being priced, the quotes sent and waiting, the win/loss record, and the saved rates, tax and terms. Call it first when asked about quotes, follow-ups or totals.","script":"quote-store","inputs":{"type":"object","properties":{"withinDays":{"type":"number"}}},"bind":{"action":"status"},"state":true},{"name":"start_quote","description":"Start a quote the moment a job is mentioned, before you describe it: a short title for the job, the client, contact and site. An existing title is updated, never duplicated. Then price it with add_quote_line.","script":"quote-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Pass it to change an existing quote."},"title":{"type":"string","description":"The job, e.g. \"Maple Row panel upgrade\"."},"client":{"type":"string"},"contact":{"type":"string"},"site":{"type":"string"},"note":{"type":"string"}},"required":["title"]},"bind":{"action":"add"}},{"name":"add_quote_line","description":"Add one line to a quote: labor, materials or other, with a description, quantity, unit and rate in dollars (or rateName for a saved rate). The tool works out the amount, the tax and the total exactly; never add them up yourself. The same description updates that line, and addQty adds to its quantity (e.g. 6 more hours).","script":"quote-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string","description":"The quote’s title or client, when no id."},"description":{"type":"string","description":"What the line is, e.g. \"Electrician labor\" or \"200A panel\"."},"kind":{"type":"string","enum":["labor","materials","other"]},"qty":{"type":"number","description":"The quantity (default 1)."},"addQty":{"type":"number","description":"Instead of qty: how much to add to that line’s quantity, e.g. 6 more hours."},"unit":{"type":"string","description":"hour, each, foot, or lot."},"rate":{"type":"number","description":"Price per unit in dollars."},"rateName":{"type":"string","description":"Or: a saved rate by name, e.g. \"Electrician\"."}},"required":["description"]},"bind":{"action":"add_line"}},{"name":"remove_quote_line","description":"Take a line off a quote, by its number or description.","script":"quote-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string","description":"The quote’s title or client, when no id."},"line":{"type":"number","description":"The line number."},"description":{"type":"string"}}},"bind":{"action":"remove_line"}},{"name":"send_quote","description":"Mark a quote sent the moment the person says it went out. It sets the valid-until date and the first follow-up from the business’s terms.","script":"quote-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string","description":"The quote’s title or client, when no id."},"validDays":{"type":"number"},"followUpAt":{"type":"string","description":"First follow-up date, YYYY-MM-DD, when not the usual."},"note":{"type":"string"}}},"bind":{"action":"send"}},{"name":"log_quote_follow_up","description":"Record a follow-up on a sent quote (a call, an email, what the client said) and when to chase next: followUpAt or inDays, or the usual gap when not given.","script":"quote-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string","description":"The quote’s title or client, when no id."},"note":{"type":"string","description":"What happened, in the person’s words."},"followUpAt":{"type":"string","description":"Next follow-up date, YYYY-MM-DD."},"inDays":{"type":"number","description":"Or: the next follow-up this many days from today."}}},"bind":{"action":"follow_up"}},{"name":"record_quote_outcome","description":"Record that a quote was won or lost the moment the person says so, with the reason in note. Won and lost quotes are closed and their price is settled.","script":"quote-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string","description":"The quote’s title or client, when no id."},"outcome":{"type":"string","enum":["won","lost"]},"note":{"type":"string","description":"Why, in the person’s words."}},"required":["outcome"]},"bind":{"action":"outcome"}},{"name":"save_rate","description":"Save one of the business’s rates: a name (e.g. \"Electrician\"), labor, materials or other, the unit (hour, each, foot) and the price in dollars. The same name updates the rate.","script":"quote-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"kind":{"type":"string","enum":["labor","materials","other"]},"unit":{"type":"string"},"rate":{"type":"number","description":"Dollars per unit."}},"required":["name","rate"]},"bind":{"action":"set_rate"}},{"name":"set_quote_terms","description":"Set the sales tax the business charges (a percent, 0 for none) and whether it applies to materials only or the whole quote, and how many days quotes stay valid and wait before a follow-up. Draft quotes are re-totaled; sent quotes keep their tax.","script":"quote-store","inputs":{"type":"object","properties":{"taxRate":{"type":"number","description":"The sales tax percent the business charges, e.g. 8.25 (0 for none)."},"taxOn":{"type":"string","enum":["materials","all"]},"validDays":{"type":"number"},"followUpDays":{"type":"number"}}},"bind":{"action":"set_terms"}},{"name":"show_quote","description":"One quote line by line: each line’s quantity, rate and amount, then the subtotal, tax and total.","script":"quote-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string","description":"The quote’s title or client, when no id."}}},"bind":{"action":"show"}},{"name":"page_start_quote","description":"Start or update a quote.","script":"quote-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Pass it to change an existing quote."},"title":{"type":"string","description":"The job, e.g. \"Maple Row panel upgrade\"."},"client":{"type":"string"},"contact":{"type":"string"},"site":{"type":"string"},"note":{"type":"string"}},"required":["title"]},"bind":{"action":"add"}},{"name":"page_add_quote_line","description":"Add or change a line on a quote.","script":"quote-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string","description":"The quote’s title or client, when no id."},"description":{"type":"string","description":"What the line is, e.g. \"Electrician labor\" or \"200A panel\"."},"kind":{"type":"string","enum":["labor","materials","other"]},"qty":{"type":"number","description":"The quantity (default 1)."},"addQty":{"type":"number","description":"Instead of qty: how much to add to that line’s quantity, e.g. 6 more hours."},"unit":{"type":"string","description":"hour, each, foot, or lot."},"rate":{"type":"number","description":"Price per unit in dollars."},"rateName":{"type":"string","description":"Or: a saved rate by name, e.g. \"Electrician\"."}},"required":["description"]},"bind":{"action":"add_line"}},{"name":"page_send_quote","description":"Mark a quote sent.","script":"quote-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string","description":"The quote’s title or client, when no id."},"validDays":{"type":"number"},"followUpAt":{"type":"string","description":"First follow-up date, YYYY-MM-DD, when not the usual."},"note":{"type":"string"}}},"bind":{"action":"send"}},{"name":"page_log_quote_follow_up","description":"Record a follow-up on a sent quote.","script":"quote-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string","description":"The quote’s title or client, when no id."},"note":{"type":"string","description":"What happened, in the person’s words."},"followUpAt":{"type":"string","description":"Next follow-up date, YYYY-MM-DD."},"inDays":{"type":"number","description":"Or: the next follow-up this many days from today."}}},"bind":{"action":"follow_up"}},{"name":"page_record_quote_outcome","description":"Record that a quote was won or lost.","script":"quote-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string","description":"The quote’s title or client, when no id."},"outcome":{"type":"string","enum":["won","lost"]},"note":{"type":"string","description":"Why, in the person’s words."}},"required":["outcome"]},"bind":{"action":"outcome"},"reaction":{"gezel":"estimator","prompt":"The person just recorded a quote’s outcome on the quotes page. The quotes now read (its first sentence is what changed):\n{{output.summary}}\nIn two short sentences, confirm the outcome and the win rate now; after a win, offer to turn the quote into an invoice, and after a loss, note what the reason says about pricing the next one. Do not call tools.","hideSeed":true}},{"name":"page_set_quote_terms","description":"Set the sales tax and quote terms.","script":"quote-store","inputs":{"type":"object","properties":{"taxRate":{"type":"number","description":"The sales tax percent the business charges, e.g. 8.25 (0 for none)."},"taxOn":{"type":"string","enum":["materials","all"]},"validDays":{"type":"number"},"followUpDays":{"type":"number"}}},"bind":{"action":"set_terms"}}],"pages":{"entry":"quotes/index.html","api":1,"reads":[{"source":"workspace","path":"quotes.json"},{"source":"workspace","path":"rates.json"}],"tools":["page_start_quote","page_add_quote_line","page_send_quote","page_log_quote_follow_up","page_record_quote_outcome","page_set_quote_terms"]},"schedules":[],"workspaceSeed":["quotes.json","rates.json"],"artifactsSeed":[],"availableVersions":["1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"sales-pipeline","name":"Sales Pipeline","description":"Follow every deal from first contact to close. An account manager keeps each deal’s stage, value and next follow-up, tells you who to call today, and keeps a weighted forecast you can plan the month around.","tags":["crm","pipeline","leads","prospects","follow-ups","forecast","small-business"],"category":"business","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.0.0","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"business":{"type":"string","title":"What kind of business is this?","description":"e.g. 'a three-person electrical contractor', 'a design studio in Austin'.","default":"the business"}},"required":["business"]},"nameTemplate":"Sales Pipeline","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"account-manager","voorman":true},{"templateId":"researcher","voorman":false}],"toolsets":[],"craftbooks":["proposal-sow","meeting-prep-brief","lead-enrichment"],"scripts":{"pipeline-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { logStore, rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'pipeline-store',\n description:\n \"Read and update the sales pipeline (deals.json) and its activity log (activity.json). action:'status' for the follow-ups due, every open deal by stage and the weighted forecast; 'add' to save a deal (an existing title is updated, never duplicated; valueChange adds to its value); 'move' to change its stage (won and lost close it); 'log' to record a call, email, meeting or note (valueChange there too moves the value); 'follow_up' to set the next touch; 'list' for every deal.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'status', 'add', 'move', 'log', 'follow_up', or 'list'.\",\n required: true,\n },\n id: { type: 'string', description: \"Deal id, e.g. 'deal-3'.\" },\n title: {\n type: 'string',\n description: \"The deal's name, e.g. 'Harbor Street Café kitchen rewire'. Also finds it (or its company) when no id is given.\",\n },\n company: { type: 'string', description: 'The customer.' },\n contact: { type: 'string', description: 'The person you deal with there.' },\n value: { type: 'number', description: \"The deal's whole value in dollars, e.g. 12400.\" },\n valueChange: {\n type: 'number',\n description: 'Dollars to add to the current value (negative to take off), e.g. 3400 or -500.',\n },\n probability: { type: 'number', description: \"Chance to win, 0-100, when it differs from the stage's usual chance.\" },\n status: { type: 'string', description: 'lead, qualified, proposal, negotiation, won, or lost.' },\n closeAt: { type: 'string', description: 'Expected close date, YYYY-MM-DD.' },\n followUpAt: { type: 'string', description: 'Next follow-up date, YYYY-MM-DD.' },\n inDays: { type: 'number', description: 'Next follow-up this many days from today, instead of followUpAt.' },\n nextStep: { type: 'string', description: 'What the next follow-up is for.' },\n kind: { type: 'string', description: 'For log: call, email, meeting, or note.' },\n source: { type: 'string', description: \"Where the lead came from, e.g. 'referral'.\" },\n note: { type: 'string', description: 'What happened, or why a deal was lost, in the words given.' },\n withinDays: { type: 'number', description: 'How many days ahead counts for follow-ups (default 7).' },\n },\n outputs: {\n open: { type: 'number', description: 'Open deals.' },\n openValue: { type: 'number', description: 'Value of the open deals, in dollars.' },\n weightedForecast: { type: 'number', description: 'Weighted forecast of the open deals, in dollars.' },\n followUpsDue: { type: 'number', description: 'Follow-ups overdue or due today.' },\n summary: { type: 'string', description: 'What changed, then the pipeline picture, or the listing.' },\n },\n requires: ['workspace.read', 'workspace.write', 'reminders'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── pipeline-rules-start ──\n// Pure derivations: money in integer cents, a deal's chance and weighted\n// value, local calendar days for follow-ups, finding a deal by name, and the\n// pipeline picture the crew reads. Kept self-contained between these\n// sentinels so unit tests execute the shipped bytes.\nvar DAY_MS = 86400000;\nvar STAGES = ['lead', 'qualified', 'proposal', 'negotiation', 'won', 'lost'];\nvar OPEN_STAGES = ['lead', 'qualified', 'proposal', 'negotiation'];\nvar CHANCE = { lead: 10, qualified: 25, proposal: 50, negotiation: 75, won: 100, lost: 0 };\nvar KINDS = ['call', 'email', 'meeting', 'note'];\nvar TOUCHES = ['call', 'email', 'meeting', 'note', 'stage', 'won', 'lost'];\nvar NAME_STOP = ['the', 'and', 'for', 'with', 'our', 'deal', 'job', 'quote', 'bid'];\n\nfunction pad(n) {\n return n < 10 ? '0' + n : String(n);\n}\nfunction localDay(ms) {\n var d = new Date(ms);\n return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());\n}\nfunction normalizeDate(text) {\n var raw = String(text || '').trim();\n if (/^\\d{4}-\\d{2}-\\d{2}/.test(raw)) return raw.slice(0, 10);\n var parsed = Date.parse(raw);\n return isFinite(parsed) ? localDay(parsed) : null;\n}\nfunction daysLeft(day, nowMs) {\n var due = Date.parse(String(day).slice(0, 10) + 'T00:00:00');\n var today = Date.parse(localDay(nowMs) + 'T00:00:00');\n return Math.round((due - today) / DAY_MS);\n}\nfunction addDays(day, n) {\n var d = new Date(String(day).slice(0, 10) + 'T12:00:00');\n d.setDate(d.getDate() + n);\n return localDay(d.getTime());\n}\nfunction when(days) {\n if (days < 0) return -days + (days === -1 ? ' day late' : ' days late');\n if (days === 0) return 'today';\n if (days === 1) return 'tomorrow';\n return 'in ' + days + ' days';\n}\nfunction ago(days) {\n return days <= 0 ? 'today' : days === 1 ? 'yesterday' : days + ' days ago';\n}\n// Dollars as a number or text ('$12,400', '95.50') to integer cents; null when it is not money.\nfunction toCents(value) {\n if (typeof value === 'string') value = Number(value.replace(/[$,\\s]/g, ''));\n if (typeof value !== 'number' || !isFinite(value)) return null;\n return (value < 0 ? -1 : 1) * Math.round(Math.abs(value) * 100);\n}\nfunction money(cents) {\n var n = Math.round(Number(cents) || 0);\n var abs = Math.abs(n);\n var whole = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\n return (n < 0 ? '-$' : '$') + whole + (abs % 100 ? '.' + pad(abs % 100) : '');\n}\nfunction fold(text) {\n return String(text || '')\n .normalize('NFD')\n .replace(/[̀-ͯ]/g, '')\n .replace(/[‘’]/g, \"'\")\n .toLowerCase()\n .trim();\n}\nfunction isOpen(record) {\n return OPEN_STAGES.indexOf(record.status) >= 0;\n}\nfunction chanceOf(record) {\n var p = record.fields && record.fields.probability;\n return typeof p === 'number' && p >= 0 && p <= 100 ? p : CHANCE[record.status] || 0;\n}\nfunction valueOf(record) {\n return Number(record.fields && record.fields.valueCents) || 0;\n}\n// Value times chance, rounded half up to the cent.\nfunction weighted(record) {\n return Math.floor((valueOf(record) * chanceOf(record) + 50) / 100);\n}\nfunction sum(records, of) {\n return records.reduce(function (total, r) {\n return total + of(r);\n }, 0);\n}\n// The deal a person means: its id, its exact title, a title or company that\n// contains what they wrote, or one whose name holds every word they used.\n// Several matches prefer the open deals; a tie is an error that names them.\nfunction findDeal(records, input) {\n if (input.id) {\n var byId = records.filter(function (r) {\n return r.id === String(input.id).trim();\n });\n if (byId.length) return byId[0];\n if (!input.title && !input.company) throw new Error(\"No deal '\" + input.id + \"'. \" + roll(records));\n }\n var wanted = fold(input.title || input.company);\n if (!wanted) throw new Error(\"Pass 'id' (e.g. 'deal-3') or the deal's 'title'. \" + roll(records));\n var name = function (r) {\n return fold(r.fields.title);\n };\n var both = function (r) {\n return name(r) + ' ' + fold(r.fields.company);\n };\n var words = wanted.split(/[^a-z0-9']+/).filter(function (w) {\n return w.length > 2 && NAME_STOP.indexOf(w) < 0;\n });\n var tiers = [\n function (r) {\n return name(r) === wanted;\n },\n function (r) {\n return name(r).indexOf(wanted) >= 0 || fold(r.fields.company) === wanted;\n },\n function (r) {\n return (\n words.length > 0 &&\n words.every(function (w) {\n return both(r).indexOf(w) >= 0 || both(r).indexOf(w.replace(/s$/, '')) >= 0;\n })\n );\n },\n ];\n for (var i = 0; i < tiers.length; i++) {\n var hits = records.filter(tiers[i]);\n if (hits.length > 1) {\n var open = hits.filter(isOpen);\n if (open.length) hits = open;\n }\n if (hits.length === 1) return hits[0];\n if (hits.length > 1) {\n throw new Error(\n \"More than one deal matches '\" + (input.title || input.company) + \"': \" +\n hits.map(function (r) { return r.id + ' ' + r.fields.title; }).join(', ') + '. Pass id.',\n );\n }\n }\n throw new Error(\"No deal matches '\" + (input.title || input.company) + \"'. \" + roll(records));\n}\nfunction roll(records) {\n var open = records.filter(isOpen);\n return open.length\n ? 'Open deals: ' + open.map(function (r) { return r.id + ' ' + r.fields.title; }).join(', ') + '.'\n : 'There are no open deals.';\n}\nfunction lastTouch(record, events) {\n var mine = events.filter(function (e) {\n return e.data && e.data.dealId === record.id && TOUCHES.indexOf(e.kind) >= 0;\n });\n return mine.length ? mine[mine.length - 1].at : record.createdAt;\n}\nfunction dealLine(record, events, nowMs) {\n var f = record.fields || {};\n var head = record.id;\n if (f.company && fold(f.title).indexOf(fold(f.company)) < 0) head += ', ' + f.company;\n if (f.contact) head += ', contact ' + f.contact;\n head += ', ' + record.status + ', ' + money(valueOf(record));\n if (isOpen(record)) head += ' at ' + chanceOf(record) + '% = ' + money(weighted(record)) + ' weighted';\n var parts = [head];\n if (f.followUpAt) parts.push('follow up ' + when(daysLeft(f.followUpAt, nowMs)) + ' (' + f.followUpAt + ')' + (f.nextStep ? ': ' + f.nextStep : ''));\n else if (isOpen(record)) parts.push('no follow-up set');\n if (isOpen(record) && f.closeAt) parts.push('expected to close ' + f.closeAt);\n if (!isOpen(record) && f.closedAt) parts.push(record.status + ' ' + f.closedAt + (f.lostReason ? ': ' + f.lostReason : ''));\n var touched = lastTouch(record, events);\n if (touched) parts.push('last touch ' + ago(-daysLeft(localDay(Date.parse(touched)), nowMs)));\n return f.title + ' (' + parts.join('; ') + ')';\n}\nfunction followLine(record, nowMs) {\n var f = record.fields;\n return (\n f.title + ' (' + record.id + (f.contact ? ', ' + f.contact : '') + ') ' + when(daysLeft(f.followUpAt, nowMs)) +\n (f.nextStep ? ': ' + f.nextStep : '')\n );\n}\nfunction picture(records, events, nowMs, withinDays) {\n var open = records.filter(isOpen);\n var byFollow = function (a, b) {\n return String(a.fields.followUpAt).localeCompare(String(b.fields.followUpAt));\n };\n var due = open\n .filter(function (r) {\n return r.fields.followUpAt && daysLeft(r.fields.followUpAt, nowMs) <= withinDays;\n })\n .sort(byFollow);\n var dueNow = due.filter(function (r) {\n return daysLeft(r.fields.followUpAt, nowMs) <= 0;\n });\n var unset = open.filter(function (r) {\n return !r.fields.followUpAt;\n });\n var month = localDay(nowMs).slice(0, 7);\n var closing = open.filter(function (r) {\n return String(r.fields.closeAt || '').slice(0, 7) === month;\n });\n var recent = function (status) {\n return records.filter(function (r) {\n return r.status === status && r.fields.closedAt && -daysLeft(r.fields.closedAt, nowMs) <= 30;\n });\n };\n var won = recent('won');\n var lost = recent('lost');\n var decided = records.filter(function (r) {\n return r.status === 'won' || r.status === 'lost';\n });\n var wonAll = decided.filter(function (r) {\n return r.status === 'won';\n });\n var parts = [\n open.length + (open.length === 1 ? ' open deal' : ' open deals') + ' worth ' + money(sum(open, valueOf)) +\n '; weighted forecast ' + money(sum(open, weighted)) + '.',\n ];\n // One list, overdue first: a model asked about today reads a separate overdue list as out of scope.\n parts.push(\n due.length\n ? 'Follow-ups within ' + withinDays + ' days, overdue first: ' + due.map(function (r) { return followLine(r, nowMs); }).join(' | ') + '.'\n : 'No follow-ups due in the next ' + withinDays + ' days.',\n );\n if (unset.length) parts.push('No follow-up set: ' + unset.map(function (r) { return r.fields.title + ' (' + r.id + ')'; }).join(', ') + '.');\n var stages = OPEN_STAGES.filter(function (s) {\n return open.some(function (r) { return r.status === s; });\n }).map(function (s) {\n var here = open.filter(function (r) { return r.status === s; });\n return s + ' (' + here.length + ', ' + money(sum(here, valueOf)) + '): ' + here.map(function (r) { return dealLine(r, events, nowMs); }).join(' | ');\n });\n if (stages.length) parts.push('Open deals by stage: ' + stages.join('. ') + '.');\n if (closing.length) {\n parts.push(\n 'Expected to close this month: ' + closing.length + (closing.length === 1 ? ' deal, ' : ' deals, ') + money(sum(closing, valueOf)) +\n ', weighted ' + money(sum(closing, weighted)) + '.',\n );\n }\n if (won.length || lost.length) {\n parts.push(\n 'Last 30 days: won ' + won.length + ' (' + money(sum(won, valueOf)) + ')' +\n (won.length ? ': ' + won.map(function (r) { return r.fields.title; }).join(', ') : '') +\n '; lost ' + lost.length + ' (' + money(sum(lost, valueOf)) + ')' +\n (lost.length ? ': ' + lost.map(function (r) { return r.fields.title + (r.fields.lostReason ? ' (' + r.fields.lostReason + ')' : ''); }).join('; ') : '') + '.',\n );\n }\n if (decided.length) {\n parts.push('Win rate: ' + wonAll.length + ' of ' + decided.length + ' decided deals (' + Math.round((wonAll.length / decided.length) * 100) + '%).');\n }\n return {\n open: open.length,\n openValueCents: sum(open, valueOf),\n weightedCents: sum(open, weighted),\n followUpsDue: dueNow.length,\n summary: records.length ? parts.join(' ') : 'No deals on the pipeline yet.',\n };\n}\n// ── pipeline-rules-end ──\n\ntype Deal = { id: string; status: string; fields: Record<string, unknown>; createdAt: string };\n\nconst deals = rosterStore(gezel.fs, 'deals.json', {\n stages: ['lead', 'qualified', 'proposal', 'negotiation', 'won', 'lost'],\n idPrefix: 'deal',\n});\nconst activity = logStore(gezel.fs, 'activity.json');\nconst now = Date.now();\nconst today = localDay(now);\n\nfunction given(value: unknown): boolean {\n return value !== undefined && value !== null && value !== '';\n}\n\nfunction followUpInput(): string | undefined {\n if (typeof input.inDays === 'number' && isFinite(input.inDays)) return addDays(today, Math.max(0, Math.round(input.inDays)));\n if (given(input.followUpAt)) {\n const day = normalizeDate(input.followUpAt);\n if (!day) throw new Error(\"followUpAt must be a date, e.g. '2026-11-20', or pass inDays.\");\n return day;\n }\n return undefined;\n}\n\nasync function move(record: Deal, to: string, why?: string): Promise<string> {\n if (STAGES.indexOf(to) < 0) throw new Error(\"status must be one of: \" + STAGES.join(', ') + '.');\n const title = String(record.fields.title);\n if (record.status === to) return title + ' is already ' + to + '.';\n const closing = to === 'won' || to === 'lost';\n await deals.update(record.id, {\n fields: {\n probability: null,\n closedAt: closing ? today : null,\n ...(closing ? { followUpAt: null, nextStep: null } : {}),\n ...(to === 'lost' && why ? { lostReason: why } : {}),\n },\n });\n await deals.transition(record.id, to, why ? { note: why } : {});\n await activity.append({\n kind: closing ? to : 'stage',\n note: why || 'Moved from ' + record.status + ' to ' + to + '.',\n data: { dealId: record.id, from: record.status, to },\n });\n return (\n title + ' moved from ' + record.status + ' to ' + to +\n (to === 'won' ? ': ' + money(valueOf(record)) + ' won' : to === 'lost' && why ? ': ' + why : '') + '.'\n );\n}\n\n// The pipeline's one reminder sits on the soonest follow-up, the morning it is due.\nasync function remindNextFollowUp(): Promise<void> {\n const next = (await deals.list())\n .filter((r) => isOpen(r) && typeof r.fields.followUpAt === 'string')\n .map((r) => ({ record: r, at: Date.parse(String(r.fields.followUpAt) + 'T09:00:00') }))\n .filter((r) => r.at > now)\n .sort((a, b) => a.at - b.at)[0];\n try {\n if (!next || next.at - now > 30 * DAY_MS) await gezel.reminder.clear();\n else {\n const f = next.record.fields;\n await gezel.reminder.set({\n at: new Date(next.at).toISOString(),\n title: ('Follow up: ' + String(f.company || f.title)).slice(0, 80),\n body: (String(f.nextStep || f.title) + ' (' + String(f.title) + ', ' + money(valueOf(next.record)) + ').').slice(0, 160),\n });\n }\n } catch {\n // Reminders are a convenience; the pipeline is the record.\n }\n}\n\nconst withinDays = typeof input.withinDays === 'number' && input.withinDays > 0 ? Math.round(input.withinDays) : 7;\nlet note = '';\n\nif (input.action === 'add') {\n const all = (await deals.list()) as Deal[];\n const title = String(input.title || input.company || '').trim();\n let existing: Deal | null = null;\n if (given(input.id)) existing = findDeal(all, { id: input.id, title: input.title });\n // A change to the value is a change to a deal that exists, never a new one.\n else if (given(input.valueChange)) existing = findDeal(all, input);\n else if (title) existing = all.find((r) => fold(r.fields.title) === fold(title)) ?? null;\n if (!existing && !title) throw new Error(\"add needs 'title': the job or opportunity, e.g. 'Fernwood Studio lighting retrofit'.\");\n const status = given(input.status) ? String(input.status).trim().toLowerCase() : '';\n if (status && STAGES.indexOf(status) < 0) throw new Error('status must be one of: ' + STAGES.join(', ') + '.');\n const fields: Record<string, unknown> = {};\n if (input.company) fields.company = input.company.trim();\n if (input.contact) fields.contact = input.contact.trim();\n if (input.source) fields.source = input.source.trim();\n if (input.nextStep) fields.nextStep = input.nextStep.trim();\n if (given(input.closeAt)) {\n const closeAt = normalizeDate(input.closeAt);\n if (!closeAt) throw new Error(\"closeAt must be a date, e.g. '2026-12-15'.\");\n fields.closeAt = closeAt;\n }\n const follow = followUpInput();\n if (follow) fields.followUpAt = follow;\n if (given(input.probability)) {\n const p = Number(input.probability);\n if (!isFinite(p) || p < 0 || p > 100) throw new Error('probability is a percent from 0 to 100.');\n fields.probability = Math.round(p);\n }\n if (given(input.value) && !given(input.valueChange)) {\n const cents = toCents(input.value);\n if (cents === null || cents < 0) throw new Error('value is the amount in dollars, e.g. 12400.');\n fields.valueCents = cents;\n }\n if (existing) {\n let valueNote = '';\n if (given(input.valueChange)) {\n const change = toCents(input.valueChange);\n if (change === null) throw new Error('valueChange is an amount in dollars, e.g. 3400 or -500.');\n const before = valueOf(existing);\n if (before + change < 0) throw new Error(String(existing.fields.title) + ' is ' + money(before) + '; that change would take it below zero.');\n fields.valueCents = before + change;\n valueNote = ': value ' + money(before) + (change < 0 ? ' - ' + money(-change) : ' + ' + money(change)) + ' = ' + money(before + change);\n } else if (fields.valueCents !== undefined) {\n valueNote = ': value now ' + money(fields.valueCents);\n }\n if (given(input.id) && input.title && fold(input.title) !== fold(existing.fields.title)) fields.title = input.title.trim();\n await deals.update(existing.id, { fields });\n note = 'Updated ' + String(existing.fields.title) + valueNote + '.';\n if (status && status !== existing.status) {\n note += ' ' + (await move({ ...existing, fields: { ...existing.fields, ...fields } }, status, input.note));\n } else if (input.note) {\n await activity.append({ kind: 'note', note: input.note, data: { dealId: existing.id } });\n }\n } else {\n const start = status || 'lead';\n const closing = start === 'won' || start === 'lost';\n const record = await deals.add({\n status: start,\n fields: { title, valueCents: 0, ...fields, ...(closing ? { closedAt: today } : {}) },\n });\n await activity.append({\n kind: closing ? start : 'note',\n note: input.note || 'Deal added at ' + start + '.',\n data: { dealId: record.id },\n });\n note = 'Added ' + record.id + ': ' + title + ', ' + money(valueOf(record)) + ', ' + start + '.';\n }\n} else if (input.action === 'move') {\n const record = findDeal((await deals.list()) as Deal[], input);\n if (!given(input.status)) throw new Error(\"move needs 'status': qualified, proposal, negotiation, won, or lost.\");\n note = await move(record, String(input.status).trim().toLowerCase(), input.note);\n} else if (input.action === 'log') {\n const record = findDeal((await deals.list()) as Deal[], input);\n if (!input.note) throw new Error(\"log needs 'note': what happened.\");\n const kind = KINDS.indexOf(String(input.kind)) >= 0 ? String(input.kind) : 'note';\n await activity.append({ kind, note: input.note, data: { dealId: record.id } });\n const next = followUpInput();\n const due = typeof record.fields.followUpAt === 'string' && daysLeft(record.fields.followUpAt, now) <= 0;\n const fields: Record<string, unknown> = {};\n let valueNote = '';\n if (given(input.valueChange)) {\n const change = toCents(input.valueChange);\n if (change === null) throw new Error('valueChange is an amount in dollars, e.g. 3400 or -500.');\n const before = valueOf(record);\n if (before + change < 0) throw new Error(String(record.fields.title) + ' is ' + money(before) + '; that change would take it below zero.');\n fields.valueCents = before + change;\n valueNote = ' Value ' + money(before) + (change < 0 ? ' - ' + money(-change) : ' + ' + money(change)) + ' = ' + money(before + change) + '.';\n } else if (/\\$\\s?\\d/.test(input.note)) {\n // A note that names an amount usually means the value moved; say it did not.\n valueNote = ' Its value is unchanged at ' + money(valueOf(record)) + '; if the note changes it, call add_deal with valueChange.';\n }\n if (next) {\n fields.followUpAt = next;\n if (input.nextStep) fields.nextStep = input.nextStep.trim();\n } else if (kind !== 'note' && due) {\n // The touch was the follow-up that was due.\n fields.followUpAt = null;\n fields.nextStep = null;\n }\n await deals.update(record.id, { fields });\n note =\n 'Logged ' + (kind === 'email' ? 'an ' : 'a ') + kind + ' on ' + String(record.fields.title) +\n (next ? '; next follow-up ' + next + (input.nextStep ? ': ' + input.nextStep.trim() : '') + '.' : kind !== 'note' && due ? '; that was the follow-up that was due, so none is set now.' : '.') +\n valueNote;\n} else if (input.action === 'follow_up') {\n const record = findDeal((await deals.list()) as Deal[], input);\n const next = followUpInput();\n if (!next) throw new Error(\"follow_up needs followUpAt (YYYY-MM-DD) or inDays.\");\n if (!isOpen(record)) throw new Error(String(record.fields.title) + ' is ' + record.status + '; move it back to an open stage first.');\n await deals.update(record.id, { fields: { followUpAt: next, ...(input.nextStep ? { nextStep: input.nextStep.trim() } : {}) } });\n await activity.append({\n kind: 'follow-up',\n note: 'Follow up ' + next + (input.nextStep ? ': ' + input.nextStep.trim() : '') + '.',\n data: { dealId: record.id },\n });\n note = String(record.fields.title) + ': follow up ' + when(daysLeft(next, now)) + ' (' + next + ')' + (input.nextStep ? ', ' + input.nextStep.trim() : '') + '.';\n} else if (input.action !== 'status' && input.action !== 'list') {\n throw new Error(\"Unknown action '\" + input.action + \"'. Use status, add, move, log, follow_up, or list.\");\n}\n\nconst records = (await deals.list()) as Deal[];\nconst events = await activity.list();\nconst view = picture(records, events, now, withinDays);\nawait remindNextFollowUp();\n\ngezel.output({\n open: view.open,\n openValue: view.openValueCents / 100,\n weightedForecast: Math.round(view.weightedCents) / 100,\n followUpsDue: view.followUpsDue,\n summary:\n input.action === 'list'\n ? records\n .slice()\n .sort((a, b) => Number(!isOpen(a)) - Number(!isOpen(b)))\n .map((r) => '[' + r.status + '] ' + dealLine(r, events, now))\n .join('\\n') || 'No deals on the pipeline yet.'\n : (note ? note + ' ' : '') + view.summary,\n});\n"},"tools":[{"name":"pipeline_status","description":"The whole pipeline: follow-ups due (overdue first), every open deal by stage with its id, value, chance and weighted value, the weighted forecast, and what was won or lost lately. Call it first when asked about deals, follow-ups or the forecast.","script":"pipeline-store","inputs":{"type":"object","properties":{"withinDays":{"type":"number"}}},"bind":{"action":"status"},"state":true},{"name":"add_deal","description":"Save a deal the moment it is mentioned, before you describe it: title, company, contact, value in dollars, stage, expected close date and next follow-up. An existing title (or id) is updated, never duplicated. When a deal’s value grows or shrinks, pass its title and valueChange (e.g. 3400) instead of working out the new total.","script":"pipeline-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Pass it to change an existing deal."},"title":{"type":"string","description":"The job or opportunity, e.g. \"Fernwood Studio lighting retrofit\"."},"company":{"type":"string"},"contact":{"type":"string"},"value":{"type":"number","description":"The whole value in dollars."},"valueChange":{"type":"number","description":"When the value grows or shrinks: the dollars added (or, negative, taken off). The tool works out the new total."},"status":{"type":"string","enum":["lead","qualified","proposal","negotiation","won","lost"]},"probability":{"type":"number","description":"Chance to win, 0-100, only when it differs from the stage’s usual chance."},"closeAt":{"type":"string","description":"Expected close date, YYYY-MM-DD."},"followUpAt":{"type":"string","description":"Next follow-up date, YYYY-MM-DD."},"inDays":{"type":"number","description":"Or: the next follow-up this many days from today."},"nextStep":{"type":"string"},"source":{"type":"string"},"note":{"type":"string"}},"required":["title"]},"bind":{"action":"add"}},{"name":"move_deal","description":"Move a deal to another stage the moment the person says it moved: lead, qualified, proposal, negotiation, won, or lost (with the reason in note). Won and lost close the deal and clear its follow-up.","script":"pipeline-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string","description":"The deal’s title or company, when no id."},"status":{"type":"string","enum":["lead","qualified","proposal","negotiation","won","lost"]},"note":{"type":"string","description":"Why, or what was agreed."}},"required":["status"]},"bind":{"action":"move"}},{"name":"log_activity","description":"Record a call, email, meeting or note on a deal as soon as it is mentioned, in the person’s words. Pass followUpAt or inDays when they name the next touch; a call, email or meeting on a due follow-up clears it. When what happened changes the deal’s value, pass valueChange too.","script":"pipeline-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string","description":"The deal’s title or company, when no id."},"kind":{"type":"string","enum":["call","email","meeting","note"]},"note":{"type":"string"},"valueChange":{"type":"number","description":"When the value grows or shrinks: the dollars added (or, negative, taken off). The tool works out the new total."},"followUpAt":{"type":"string","description":"Next follow-up date, YYYY-MM-DD."},"inDays":{"type":"number","description":"Or: the next follow-up this many days from today."},"nextStep":{"type":"string"}},"required":["note"]},"bind":{"action":"log"}},{"name":"schedule_follow_up","description":"Set a deal’s next follow-up: a date (followUpAt, YYYY-MM-DD) or a number of days from today (inDays), and what it is for.","script":"pipeline-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string","description":"The deal’s title or company, when no id."},"followUpAt":{"type":"string"},"inDays":{"type":"number"},"nextStep":{"type":"string"}}},"bind":{"action":"follow_up"}},{"name":"list_deals","description":"Every deal, open and closed, with its stage, value, follow-up and last touch.","script":"pipeline-store","inputs":{"type":"object","properties":{}},"bind":{"action":"list"}},{"name":"page_add_deal","description":"Add or update a deal.","script":"pipeline-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Pass it to change an existing deal."},"title":{"type":"string","description":"The job or opportunity, e.g. \"Fernwood Studio lighting retrofit\"."},"company":{"type":"string"},"contact":{"type":"string"},"value":{"type":"number","description":"The whole value in dollars."},"valueChange":{"type":"number","description":"When the value grows or shrinks: the dollars added (or, negative, taken off). The tool works out the new total."},"status":{"type":"string","enum":["lead","qualified","proposal","negotiation","won","lost"]},"probability":{"type":"number","description":"Chance to win, 0-100, only when it differs from the stage’s usual chance."},"closeAt":{"type":"string","description":"Expected close date, YYYY-MM-DD."},"followUpAt":{"type":"string","description":"Next follow-up date, YYYY-MM-DD."},"inDays":{"type":"number","description":"Or: the next follow-up this many days from today."},"nextStep":{"type":"string"},"source":{"type":"string"},"note":{"type":"string"}},"required":["title"]},"bind":{"action":"add"}},{"name":"page_log_activity","description":"Record a call, email, meeting or note on a deal.","script":"pipeline-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string","description":"The deal’s title or company, when no id."},"kind":{"type":"string","enum":["call","email","meeting","note"]},"note":{"type":"string"},"followUpAt":{"type":"string","description":"Next follow-up date, YYYY-MM-DD."},"inDays":{"type":"number","description":"Or: the next follow-up this many days from today."},"nextStep":{"type":"string"}},"required":["note"]},"bind":{"action":"log"}},{"name":"page_move_deal","description":"Move a deal to another stage.","script":"pipeline-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string","description":"The deal’s title or company, when no id."},"status":{"type":"string","enum":["lead","qualified","proposal","negotiation","won","lost"]},"note":{"type":"string","description":"Why, or what was agreed."}},"required":["status"]},"bind":{"action":"move"},"reaction":{"gezel":"account-manager","prompt":"The person just moved a deal on the pipeline page. The pipeline now reads (its first sentence is what changed):\n{{output.summary}}\nIn two short sentences, confirm the move and the weighted forecast now, and name the next follow-up to make. Do not call tools.","hideSeed":true}}],"pages":{"entry":"pipeline/index.html","api":1,"reads":[{"source":"workspace","path":"deals.json"},{"source":"workspace","path":"activity.json"}],"tools":["page_add_deal","page_log_activity","page_move_deal"]},"schedules":[],"workspaceSeed":["deals.json","activity.json"],"artifactsSeed":[],"availableVersions":["1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"shift-roster","name":"Shift Roster","description":"Build the shift roster and keep every shift covered. A shift scheduler drafts the week from who is available, checks coverage and hours against the rules you set, and leaves every week for you to approve.","tags":["shifts","roster","rota","coverage","staff","small-business"],"category":"business","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.0.0","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"business":{"type":"string","title":"What kind of business is this?","description":"e.g. 'a café with 12 staff', 'a small bike shop'.","default":"the business"}},"required":["business"]},"nameTemplate":"Shift Roster","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"shift-scheduler","voorman":true}],"toolsets":[],"craftbooks":["weekly-schedule-draft"],"scripts":{"roster-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'roster-store',\n description:\n \"Read and update the shift roster: staff.json, shifts.json, availability.json and rules.json. action:'status' for this week and next (open spots, conflicts, hours, the schedule); 'add_staff' (an existing name is updated); 'availability' to mark someone unavailable or available again; 'add_shift' (an existing date, start and role is updated); 'copy_week' to start a week from another, keeping only assignments that pass every rule; 'assign' to put someone on a shift or take them off; 'rules' for the scheduling rules the business states; 'approve' (the person only) to approve a week.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'status', 'add_staff', 'availability', 'add_shift', 'copy_week', 'assign', 'rules', or 'approve'.\",\n required: true,\n },\n week: { type: 'string', description: 'Any date in the week, YYYY-MM-DD.' },\n fromWeek: { type: 'string', description: 'For copy_week: any date in the week to copy from (default: the week before).' },\n name: { type: 'string', description: \"A person's name, for add_staff.\" },\n roles: { type: 'string', description: \"What they work, comma-separated, e.g. 'barista, kitchen'.\" },\n maxHours: { type: 'number', description: 'Their own weekly hour limit, as the business states it (0 removes it).' },\n status: { type: 'string', description: 'For add_staff: active or inactive.' },\n staff: { type: 'string', description: 'The person to put on a shift or whose availability changes: name or id.' },\n remove: { type: 'string', description: 'For assign: the person to take off the shift.' },\n day: { type: 'string', description: \"For availability: a weekday ('tuesday'), 'weekdays', 'weekends', 'every day', or a date.\" },\n part: { type: 'string', description: 'For availability: all day, morning, afternoon, or evening.' },\n from: { type: 'string', description: 'For availability: unavailable from this time.' },\n to: { type: 'string', description: 'For availability: unavailable until this time.' },\n available: { type: 'boolean', description: 'For availability: true when they can work that day again.' },\n id: { type: 'string', description: \"A shift id, e.g. 'sh-4'.\" },\n date: { type: 'string', description: 'A shift date, YYYY-MM-DD.' },\n start: { type: 'string', description: \"Shift start, e.g. '06:00'.\" },\n end: { type: 'string', description: \"Shift end, e.g. '14:00'.\" },\n role: { type: 'string', description: \"What the shift works, e.g. 'barista'.\" },\n needed: { type: 'number', description: 'How many people the shift needs.' },\n maxWeekHours: { type: 'number', description: 'Rule: most hours a week per person (0 removes it).' },\n minRestHours: { type: 'number', description: 'Rule: fewest hours between one shift and the next (0 removes it).' },\n maxShiftHours: { type: 'number', description: 'Rule: longest shift in hours (0 removes it).' },\n rule: { type: 'string', description: \"Another rule in the business's own words, kept for the crew to read.\" },\n forget: { type: 'string', description: 'Drop the written rule containing this text.' },\n note: { type: 'string', description: 'Anything worth keeping with the change.' },\n byPerson: { type: 'boolean', description: 'Set by the page: the person made this change themselves.' },\n },\n outputs: {\n openSpots: { type: 'number', description: 'Upcoming spots nobody is on yet.' },\n conflicts: { type: 'number', description: 'Assignments that break availability or a stated rule.' },\n toApprove: { type: 'number', description: 'Shifts waiting for the person to approve.' },\n shifts: { type: 'number', description: 'Shifts in the weeks shown.' },\n week: { type: 'string', description: 'The Monday of the first week shown.' },\n summary: { type: 'string', description: 'What changed, then the roster picture.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── roster-rules-start ──\n// Pure roster rules: shift times and hours, who can take a shift (role,\n// availability, overlaps, and the rest and hours limits the business stated),\n// each week's coverage and conflicts, and run(), which applies one action to a\n// snapshot of the stores and lists the store operations, so the live store and\n// the page's demo share every rule. Kept self-contained between these\n// sentinels; the page loads the same bytes as rules.js.\nvar DAY_MS = 86400000;\nvar WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];\nvar SHORT_DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];\nvar PARTS = { 'all day': null, morning: ['00:00', '12:00'], afternoon: ['12:00', '17:00'], evening: ['17:00', '24:00'] };\n\nfunction pad(n) {\n return n < 10 ? '0' + n : String(n);\n}\nfunction localDay(ms) {\n var d = new Date(ms);\n return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());\n}\nfunction addDays(day, n) {\n var d = new Date(String(day).slice(0, 10) + 'T12:00:00');\n d.setDate(d.getDate() + n);\n return localDay(d.getTime());\n}\nfunction weekdayIndex(day) {\n return new Date(String(day).slice(0, 10) + 'T12:00:00').getDay();\n}\nfunction mondayOf(day) {\n return addDays(day, -((weekdayIndex(day) + 6) % 7));\n}\nfunction key(text) {\n return String(text === undefined || text === null ? '' : text).trim().toLowerCase();\n}\nfunction num(value) {\n if (value === undefined || value === null || value === '') return null;\n var n = typeof value === 'number' ? value : Number(String(value).trim());\n return isFinite(n) ? n : null;\n}\nfunction round1(n) {\n return Math.round(n * 10) / 10;\n}\nfunction given(value) {\n return value !== undefined && value !== null && value !== '';\n}\nfunction normalizeDate(text, nowMs) {\n var raw = key(text);\n if (!raw) return null;\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(raw)) return raw;\n var today = localDay(nowMs);\n if (raw === 'today' || raw === 'this week') return today;\n if (raw === 'tomorrow') return addDays(today, 1);\n if (raw === 'next week') return addDays(mondayOf(today), 7);\n var bare = raw.replace(/^(this|next|on)\\s+/, '').replace(/s$/, '');\n var w = WEEKDAYS.indexOf(bare);\n if (w >= 0) return addDays(today, (w - weekdayIndex(today) + 7) % 7);\n if (/\\d{4}/.test(raw)) {\n var parsed = Date.parse(String(text).trim());\n if (isFinite(parsed)) return localDay(parsed);\n }\n return null;\n}\nfunction normalizeTime(text) {\n var raw = key(text).replace(/\\s+/g, '').replace(/\\./g, '');\n if (!raw) return null;\n if (raw === 'noon') return '12:00';\n if (raw === 'midnight') return '00:00';\n var m = /^(\\d{1,2})(?::?(\\d{2}))?(am|pm|a|p)?$/.exec(raw);\n if (!m) return null;\n var h = Number(m[1]);\n var min = m[2] ? Number(m[2]) : 0;\n if (m[3]) {\n if (h < 1 || h > 12) return null;\n if (m[3].charAt(0) === 'p' && h !== 12) h += 12;\n if (m[3].charAt(0) === 'a' && h === 12) h = 0;\n }\n if (h > 24 || min > 59 || (h === 24 && min > 0)) return null;\n return pad(h % 24) + ':' + pad(min);\n}\nfunction minutes(hhmm) {\n var p = String(hhmm).split(':');\n return Number(p[0]) * 60 + Number(p[1] || 0);\n}\n// A shift that ends at or before its start runs past midnight.\nfunction span(f) {\n var s = minutes(f.start);\n var e = minutes(f.end);\n var over = e <= s;\n return {\n startAt: Date.parse(f.date + 'T' + f.start + ':00'),\n endAt: Date.parse((over ? addDays(f.date, 1) : f.date) + 'T' + f.end + ':00'),\n startMin: s,\n endMin: over ? e + 1440 : e,\n hours: ((over ? e + 1440 : e) - s) / 60,\n };\n}\nfunction normalizeDay(text, nowMs) {\n var raw = key(text);\n if (!raw) return null;\n if (/^(every ?day|daily|all week|always)$/.test(raw)) return 'every day';\n if (/^(weekdays?|mon(day)?\\s*(-|to|through)\\s*fri(day)?)$/.test(raw)) return 'weekdays';\n if (/^weekends?$/.test(raw)) return 'weekends';\n var bare = raw.replace(/^(every|on)\\s+/, '').replace(/s$/, '');\n if (WEEKDAYS.indexOf(bare) >= 0) return bare;\n return normalizeDate(text, nowMs);\n}\nfunction dayText(day) {\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(day)) return 'on ' + SHORT_DAYS[weekdayIndex(day)] + ' ' + day;\n if (day === 'every day') return 'every day';\n if (day === 'weekdays' || day === 'weekends') return 'on ' + day;\n return 'on ' + day.charAt(0).toUpperCase() + day.slice(1) + 's';\n}\nfunction windowText(f) {\n if (!f.from || !f.to) return 'all day';\n if (f.from === '00:00') return 'until ' + f.to;\n if (f.to === '24:00') return 'from ' + f.from;\n return f.from + '–' + f.to;\n}\nfunction availText(f) {\n return dayText(f.day) + ' ' + windowText(f);\n}\nfunction dayMatches(day, date) {\n var d = key(day);\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(d)) return d === date;\n var w = weekdayIndex(date);\n if (d === 'every day') return true;\n if (d === 'weekdays') return w >= 1 && w <= 5;\n if (d === 'weekends') return w === 0 || w === 6;\n return WEEKDAYS[w] === d;\n}\nfunction blocks(entry, shiftFields) {\n if (entry.status !== 'active') return false;\n var f = entry.fields;\n if (!dayMatches(f.day, shiftFields.date)) return false;\n if (!f.from || !f.to) return true;\n var sp = span(shiftFields);\n var from = minutes(f.from);\n var to = minutes(f.to);\n if (to <= from) to += 1440;\n return sp.startMin < to && from < sp.endMin;\n}\nfunction staffOn(s) {\n return Array.isArray(s.fields.staff) ? s.fields.staff : [];\n}\nfunction neededOf(s) {\n return Math.max(1, Math.round(num(s.fields.needed) || 1));\n}\nfunction person(data, id) {\n return (\n data.staff.filter(function (p) {\n return p.id === id;\n })[0] || null\n );\n}\nfunction nameOf(data, id) {\n var p = person(data, id);\n return p ? p.fields.name : id;\n}\nfunction namesOn(data, s) {\n return staffOn(s)\n .map(function (id) {\n return nameOf(data, id);\n })\n .join(', ');\n}\nfunction limitFor(p, rules) {\n var own = num(p.fields.maxHours);\n if (own !== null && own > 0) return own;\n var all = num(rules.maxWeekHours);\n return all !== null && all > 0 ? all : null;\n}\nfunction byStart(a, b) {\n return (a.fields.date + ' ' + a.fields.start).localeCompare(b.fields.date + ' ' + b.fields.start) || String(a.fields.role).localeCompare(String(b.fields.role));\n}\nfunction weekShifts(shifts, monday) {\n var end = addDays(monday, 7);\n return shifts\n .filter(function (s) {\n return s.fields.date >= monday && s.fields.date < end;\n })\n .sort(byStart);\n}\nfunction hoursFor(shifts, id, monday) {\n return weekShifts(shifts, monday)\n .filter(function (s) {\n return staffOn(s).indexOf(id) >= 0;\n })\n .reduce(function (h, s) {\n return h + span(s.fields).hours;\n }, 0);\n}\nfunction shiftLabel(s) {\n var f = s.fields;\n return SHORT_DAYS[weekdayIndex(f.date)] + ' ' + f.date + ' ' + f.start + '–' + f.end + (f.role ? ' ' + f.role : '') + ' (' + s.id + ')';\n}\n// Why a person cannot take a shift, from the roster's facts and the business's stated rules only.\nfunction problems(p, shift, data, opts) {\n var rules = data.rules || {};\n var f = shift.fields;\n var sp = span(f);\n var name = p.fields.name;\n var out = [];\n if (p.status !== 'active') out.push(name + ' is not on the active staff');\n var roles = p.fields.roles || [];\n if (f.role && roles.length && roles.indexOf(key(f.role)) < 0) out.push(name + ' does not work ' + f.role + ' (works ' + roles.join(', ') + ')');\n data.availability.forEach(function (a) {\n if (a.fields.staffId === p.id && blocks(a, f)) out.push(name + ' is unavailable ' + availText(a.fields));\n });\n var rest = num(rules.minRestHours);\n data.shifts.forEach(function (s) {\n if (s.id === shift.id || staffOn(s).indexOf(p.id) < 0) return;\n var o = span(s.fields);\n if (opts.earlierOnly && (o.startAt > sp.startAt || (o.startAt === sp.startAt && s.id > shift.id))) return;\n if (o.startAt < sp.endAt && sp.startAt < o.endAt) {\n out.push(name + ' is also on ' + shiftLabel(s) + ', which overlaps');\n return;\n }\n if (rest) {\n var gap = (o.endAt <= sp.startAt ? sp.startAt - o.endAt : o.startAt - sp.endAt) / 3600000;\n if (gap < rest) out.push(name + ' would get ' + round1(gap) + ' hours of rest next to ' + shiftLabel(s) + ' (rule: at least ' + rest + ')');\n }\n });\n if (opts.hours) {\n var limit = limitFor(p, rules);\n if (limit !== null) {\n var h =\n hoursFor(\n data.shifts.filter(function (s) {\n return s.id !== shift.id;\n }),\n p.id,\n mondayOf(f.date),\n ) + sp.hours;\n if (h > limit) out.push(name + ' would have ' + round1(h) + ' hours that week (limit ' + limit + ')');\n }\n }\n return out;\n}\n// Who could take a shift, fewest hours that week first.\nfunction freeFor(shift, data) {\n var monday = mondayOf(shift.fields.date);\n return data.staff\n .filter(function (p) {\n return p.status === 'active' && staffOn(shift).indexOf(p.id) < 0 && !problems(p, shift, data, { hours: true }).length;\n })\n .map(function (p) {\n return { id: p.id, name: p.fields.name, hours: round1(hoursFor(data.shifts, p.id, monday)) };\n })\n .sort(function (a, b) {\n return a.hours - b.hours || a.name.localeCompare(b.name);\n });\n}\nfunction weekView(data, monday, nowMs) {\n var rules = data.rules || {};\n var list = weekShifts(data.shifts, monday);\n var gaps = [];\n var conflicts = [];\n var hours = {};\n var toApprove = 0;\n var maxLen = num(rules.maxShiftHours);\n list.forEach(function (s) {\n var on = staffOn(s);\n var sp = span(s.fields);\n if (s.status !== 'approved') toApprove += 1;\n if (on.length < neededOf(s)) gaps.push({ shift: s, open: neededOf(s) - on.length, past: sp.endAt <= nowMs });\n if (maxLen && sp.hours > maxLen) conflicts.push({ shiftId: s.id, text: shiftLabel(s) + ' is ' + round1(sp.hours) + ' hours long (rule: at most ' + maxLen + ')' });\n on.forEach(function (id) {\n hours[id] = (hours[id] || 0) + sp.hours;\n var p = person(data, id);\n if (!p) {\n conflicts.push({ shiftId: s.id, text: shiftLabel(s) + ' lists ' + id + ', who is not on the staff list' });\n return;\n }\n problems(p, s, data, { hours: false, earlierOnly: true }).forEach(function (text) {\n conflicts.push({ shiftId: s.id, staffId: id, text: shiftLabel(s) + ': ' + text });\n });\n });\n });\n data.staff.forEach(function (p) {\n var limit = limitFor(p, rules);\n var h = hours[p.id] || 0;\n if (limit !== null && h > limit) conflicts.push({ staffId: p.id, text: p.fields.name + ' has ' + round1(h) + ' hours in the week of Mon ' + monday + ' (limit ' + limit + ')' });\n });\n return { monday: monday, shifts: list, gaps: gaps, conflicts: conflicts, hours: hours, toApprove: toApprove };\n}\nfunction rulesText(rules) {\n var list = [];\n if (num(rules.maxWeekHours)) list.push('at most ' + rules.maxWeekHours + ' hours a week per person, unless their own limit says otherwise');\n if (num(rules.minRestHours)) list.push('at least ' + rules.minRestHours + ' hours between shifts');\n if (num(rules.maxShiftHours)) list.push('shifts no longer than ' + rules.maxShiftHours + ' hours');\n (rules.notes || []).forEach(function (n) {\n list.push('\"' + String(n).replace(/[.\\s]+$/, '') + '\"');\n });\n return list.length\n ? 'Rules the business set: ' + list.join('; ') + '.'\n : 'The business has not stated any scheduling rules; the roster checks only availability, overlaps, roles and personal hour limits.';\n}\nfunction picture(data, nowMs, week) {\n var rules = data.rules || {};\n var first = mondayOf(week || localDay(nowMs));\n var mondays = week ? [first] : [first, addDays(first, 7)];\n var views = mondays.map(function (m) {\n return weekView(data, m, nowMs);\n });\n var label = function (i) {\n return week ? 'The week of Mon ' + views[i].monday : (i === 0 ? 'This week' : 'Next week') + ' (from Mon ' + views[i].monday + ')';\n };\n var parts = [];\n views.forEach(function (v, i) {\n var open = v.gaps.reduce(function (sum, g) {\n return sum + g.open;\n }, 0);\n parts.push(\n label(i) + ': ' +\n (v.shifts.length\n ? v.shifts.length + (v.shifts.length === 1 ? ' shift, ' : ' shifts, ') + open + (open === 1 ? ' open spot, ' : ' open spots, ') +\n v.conflicts.length + (v.conflicts.length === 1 ? ' conflict, ' : ' conflicts, ') +\n (v.toApprove ? v.toApprove + ' waiting for the person to approve' : 'all approved')\n : 'no shifts yet') + '.',\n );\n });\n // One list, soonest first: the answer to \"where are we short?\".\n var gaps = [];\n views.forEach(function (v) {\n v.gaps.forEach(function (g) {\n if (!g.past) gaps.push(g);\n });\n });\n var openSpots = gaps.reduce(function (sum, g) {\n return sum + g.open;\n }, 0);\n parts.push(\n gaps.length\n ? 'Open spots, soonest first: ' +\n gaps\n .map(function (g) {\n var free = freeFor(g.shift, data);\n return (\n shiftLabel(g.shift) + ' needs ' + g.open + ' more' + (staffOn(g.shift).length ? ' (on it: ' + namesOn(data, g.shift) + ')' : '') + '; free: ' +\n (free.length\n ? free\n .slice(0, 4)\n .map(function (x) {\n return x.name + ' (' + x.id + ', ' + x.hours + 'h)';\n })\n .join(', ')\n : 'nobody passes every rule')\n );\n })\n .join(' | ') + '.'\n : 'No open spots.',\n );\n var conflicts = [];\n views.forEach(function (v) {\n v.conflicts.forEach(function (c) {\n conflicts.push(c.text);\n });\n });\n parts.push(conflicts.length ? 'Conflicts to fix: ' + conflicts.join(' | ') + '.' : 'No conflicts with availability or the rules.');\n views.forEach(function (v, i) {\n if (!v.shifts.length) return;\n var people = data.staff.filter(function (p) {\n return p.status === 'active' || v.hours[p.id];\n });\n parts.push(\n (week ? 'Hours that week' : i === 0 ? 'Hours this week' : 'Hours next week') + ': ' +\n people\n .map(function (p) {\n var limit = limitFor(p, rules);\n var roles = p.fields.roles || [];\n return p.fields.name + ' (' + p.id + (roles.length ? ', ' + roles.join('/') : '') + ') ' + round1(v.hours[p.id] || 0) + (limit !== null ? ' of ' + limit : '') + 'h';\n })\n .join(', ') + '.',\n );\n var days = [];\n // Mark drafts per shift only when a week is part approved; the headline covers the rest.\n var mixed = v.toApprove > 0 && v.toApprove < v.shifts.length;\n for (var d = 0; d < 7; d++) {\n var date = addDays(v.monday, d);\n var todays = v.shifts.filter(function (s) {\n return s.fields.date === date;\n });\n if (!todays.length) continue;\n days.push(\n SHORT_DAYS[weekdayIndex(date)] + ' ' + date.slice(5) + ': ' +\n todays\n .map(function (s) {\n var on = staffOn(s);\n return (\n s.fields.start + '–' + s.fields.end + ' ' + (s.fields.role || 'shift') + ' ' + (on.length ? namesOn(data, s) : 'nobody') +\n (on.length < neededOf(s) ? ' (' + (neededOf(s) - on.length) + ' open)' : '') + (mixed && s.status !== 'approved' ? ' [draft]' : '') + ' (' + s.id + ')'\n );\n })\n .join('; '),\n );\n }\n parts.push((week ? 'By day' : i === 0 ? 'This week by day' : 'Next week by day') + ': ' + days.join(' / ') + '.');\n });\n if (!data.staff.length) parts.push('No staff on the roster yet.');\n var away = data.availability.filter(function (a) {\n return a.status === 'active';\n });\n if (away.length) {\n parts.push(\n 'Unavailable: ' +\n away\n .map(function (a) {\n return nameOf(data, a.fields.staffId) + ' ' + availText(a.fields);\n })\n .join('; ') + '.',\n );\n }\n parts.push(rulesText(rules));\n return {\n monday: first,\n openSpots: openSpots,\n conflicts: conflicts.length,\n toApprove: views.reduce(function (sum, v) {\n return sum + v.toApprove;\n }, 0),\n shifts: views.reduce(function (sum, v) {\n return sum + v.shifts.length;\n }, 0),\n summary: parts.join(' '),\n };\n}\n\nfunction findStaff(staff, wanted) {\n var text = String(given(wanted) ? wanted : '').trim();\n if (!text) throw new Error(\"Name the person ('Ana') or pass their id ('st-1').\");\n var byId = staff.filter(function (p) {\n return p.id === text;\n });\n if (byId.length) return byId[0];\n var k = key(text);\n var exact = staff.filter(function (p) {\n return key(p.fields.name) === k;\n });\n if (exact.length === 1) return exact[0];\n var partial = staff.filter(function (p) {\n var name = key(p.fields.name);\n return name.indexOf(k) === 0 || name.split(/\\s+/).indexOf(k) >= 0 || k.split(/\\s+/).indexOf(name.split(/\\s+/)[0]) >= 0;\n });\n if (partial.length === 1) return partial[0];\n var list = staff\n .map(function (p) {\n return p.id + ' ' + p.fields.name;\n })\n .join(', ');\n if (partial.length > 1) throw new Error(\"More than one person matches '\" + text + \"': \" + partial.map(function (p) { return p.id + ' ' + p.fields.name; }).join(', ') + '. Pass the id.');\n throw new Error(\"Nobody on the staff list matches '\" + text + \"'. Staff: \" + (list || 'none yet; add them with add_staff') + '.');\n}\nfunction findShift(shifts, input, nowMs) {\n var id = String(given(input.id) ? input.id : given(input.shift) ? input.shift : '').trim();\n if (id) {\n var hit = shifts.filter(function (s) {\n return s.id === id;\n })[0];\n if (hit) return hit;\n if (/^sh-\\d+$/.test(id)) throw new Error('No shift ' + id + '. Call roster_status to see the shifts and their ids.');\n }\n var date = given(input.date) ? normalizeDate(input.date, nowMs) : id ? normalizeDate(id, nowMs) : null;\n if (!date) throw new Error(\"Pass the shift's id ('sh-4'), or its date (YYYY-MM-DD) with its start time or role.\");\n var start = given(input.start) ? normalizeTime(input.start) : null;\n var role = key(input.role);\n var that = shifts\n .filter(function (s) {\n return s.fields.date === date;\n })\n .sort(byStart);\n var hits = that.filter(function (s) {\n return (!start || s.fields.start === start) && (!role || key(s.fields.role) === role);\n });\n if (hits.length === 1) return hits[0];\n if (hits.length > 1) throw new Error('More than one shift matches on ' + date + ': ' + hits.map(shiftLabel).join(', ') + '. Pass the id.');\n throw new Error('No shift matches on ' + date + '. Shifts that day: ' + (that.map(shiftLabel).join(', ') || 'none') + '.');\n}\n\n// A working copy of the stores. Each change is applied here and recorded as an operation\n// the live store replays through rosterStore (rules.json is written whole); the demo keeps the copy.\nfunction transaction(state, nowMs) {\n var data = JSON.parse(JSON.stringify(state));\n data.rules = data.rules || { version: 1, notes: [] };\n var ops = [];\n var at = new Date(nowMs).toISOString();\n function copy(value) {\n return JSON.parse(JSON.stringify(value));\n }\n function get(store, id) {\n return (\n data[store].filter(function (r) {\n return r.id === id;\n })[0] || null\n );\n }\n return {\n data: data,\n ops: ops,\n get: get,\n focus: null,\n add: function (store, prefix, status, fields, note) {\n var max = 0;\n data[store].forEach(function (r) {\n var m = /-(\\d+)$/.exec(r.id);\n if (m && r.id.indexOf(prefix + '-') === 0) max = Math.max(max, Number(m[1]));\n });\n var id = prefix + '-' + (max + 1);\n data[store].push({ id: id, status: status, fields: copy(fields), createdAt: at, updatedAt: at, history: [{ at: at, from: null, to: status, note: note }] });\n ops.push({ store: store, op: 'add', id: id, status: status, fields: copy(fields), note: note });\n return id;\n },\n update: function (store, id, fields, note) {\n var r = get(store, id);\n r.fields = Object.assign({}, r.fields, copy(fields));\n r.updatedAt = at;\n if (note) (r.history = r.history || []).push({ at: at, from: r.status, to: r.status, note: note });\n ops.push({ store: store, op: 'update', id: id, fields: copy(fields), note: note });\n },\n transition: function (store, id, to, note) {\n var r = get(store, id);\n (r.history = r.history || []).push({ at: at, from: r.status, to: to, note: note });\n r.status = to;\n r.updatedAt = at;\n ops.push({ store: store, op: 'transition', id: id, to: to, note: note });\n },\n setRules: function (value) {\n data.rules = copy(value);\n ops.push({ store: 'rules', op: 'set', value: copy(value) });\n },\n };\n}\n// The crew proposes; the person approves. A crew change to an approved shift sends it back for approval.\nfunction reopen(t, id, byPerson) {\n var s = t.get('shifts', id);\n if (!byPerson && s.status === 'approved') {\n t.transition('shifts', id, 'draft', 'Changed by the crew; needs approval again');\n return true;\n }\n return false;\n}\nfunction parseRoles(text) {\n var raw = Array.isArray(text) ? text.join(',') : String(text || '');\n return raw\n .split(/,|\\/|;|&|\\band\\b/)\n .map(key)\n .filter(function (r, i, all) {\n return r && all.indexOf(r) === i;\n });\n}\nfunction addStaff(t, input, nowMs) {\n var name = String(input.name || '').trim();\n if (!name) throw new Error(\"add_staff needs the person's 'name'.\");\n var fields = {};\n if (given(input.roles)) fields.roles = parseRoles(input.roles);\n if (given(input.maxHours)) {\n var h = num(input.maxHours);\n if (h === null || h < 0) throw new Error('maxHours must be a number of hours, zero or more (0 removes their limit).');\n fields.maxHours = h > 0 ? h : null;\n }\n if (input.note) fields.notes = String(input.note).trim();\n var status = key(input.status);\n if (status && status !== 'active' && status !== 'inactive') throw new Error(\"status must be 'active' or 'inactive'.\");\n var existing = t.data.staff.filter(function (p) {\n return key(p.fields.name) === key(name);\n })[0];\n var id;\n var msg;\n if (existing) {\n id = existing.id;\n if (Object.keys(fields).length) t.update('staff', id, fields, 'Updated');\n if (status && status !== existing.status) t.transition('staff', id, status, status === 'inactive' ? 'No longer on the active staff' : 'Back on the active staff');\n msg = 'Updated ' + existing.fields.name + ' (' + id + ').';\n } else {\n id = t.add('staff', 'st', status || 'active', Object.assign({ name: name, roles: [] }, fields), 'Added');\n msg = 'Added ' + name + ' (' + id + ').';\n }\n var p = t.get('staff', id);\n var roles = p.fields.roles || [];\n msg += ' ' + p.fields.name + ' works ' + (roles.length ? roles.join(', ') : 'any role') + (num(p.fields.maxHours) ? ', up to ' + p.fields.maxHours + ' hours a week' : '') + (p.status === 'inactive' ? ', and is not on the active staff' : '') + '.';\n if (p.status === 'inactive') {\n var upcoming = t.data.shifts.filter(function (s) {\n return staffOn(s).indexOf(id) >= 0 && span(s.fields).endAt > nowMs;\n });\n if (upcoming.length) msg += ' Still on ' + upcoming.sort(byStart).map(shiftLabel).join(', ') + '; those spots need someone else.';\n }\n return msg;\n}\nfunction setAvailability(t, input, nowMs) {\n var p = findStaff(t.data.staff, given(input.staff) ? input.staff : input.name);\n // The page's form picks \"one date\" and fills date; the crew passes the date as day.\n var day = key(input.day) === 'one date' ? normalizeDate(input.date, nowMs) : normalizeDay(input.day, nowMs);\n if (!day) throw new Error(\"day must be a weekday ('tuesday') for every week, 'weekdays', 'weekends', 'every day', or a date (YYYY-MM-DD) for one day.\");\n var from = null;\n var to = null;\n if (given(input.part) && key(input.part) !== 'all day') {\n var w = PARTS[key(input.part)];\n if (!w) throw new Error(\"part must be 'all day', 'morning', 'afternoon', or 'evening'.\");\n from = w[0];\n to = w[1];\n }\n if (given(input.from) || given(input.to)) {\n from = given(input.from) ? normalizeTime(input.from) : '00:00';\n to = given(input.to) ? normalizeTime(input.to) : '24:00';\n if (!from || !to) throw new Error(\"from and to must be times like '14:00' or '2pm'.\");\n if (to === '00:00') to = '24:00';\n if (minutes(to) <= minutes(from)) throw new Error(\"'to' must be later in the day than 'from'.\");\n }\n var available = input.available === true || key(input.available) === 'true' || key(input.available) === 'yes';\n var mine = t.data.availability.filter(function (a) {\n return a.status === 'active' && a.fields.staffId === p.id && key(a.fields.day) === day;\n });\n if (available) {\n if (!mine.length) return p.fields.name + ' had nothing marked ' + dayText(day) + '.';\n mine.forEach(function (a) {\n t.transition('availability', a.id, 'cleared', input.note ? String(input.note) : 'Available again');\n });\n return p.fields.name + ' is available ' + dayText(day) + ' again.';\n }\n var fields = { staffId: p.id, name: p.fields.name, day: day, from: from, to: to };\n if (input.note) fields.note = String(input.note).trim();\n var id;\n if (mine.length) {\n id = mine[0].id;\n t.update('availability', id, fields, 'Changed');\n } else id = t.add('availability', 'av', 'active', fields, 'Added');\n var entry = t.get('availability', id);\n var clash = t.data.shifts\n .filter(function (s) {\n return staffOn(s).indexOf(p.id) >= 0 && span(s.fields).endAt > nowMs && blocks(entry, s.fields);\n })\n .sort(byStart);\n var msg = 'Noted: ' + p.fields.name + ' is unavailable ' + availText(fields) + '.';\n if (clash.length) {\n msg +=\n ' That clashes with ' +\n clash\n .map(function (s) {\n var free = freeFor(s, t.data);\n return shiftLabel(s) + (free.length ? ' (free: ' + free.slice(0, 3).map(function (x) { return x.name; }).join(', ') + ')' : ' (nobody else is free)');\n })\n .join('; ') +\n '; the person decides who covers it.';\n t.focus = mondayOf(clash[0].fields.date);\n }\n return msg;\n}\nfunction addShift(t, input, nowMs) {\n var byPerson = input.byPerson === true;\n var date = normalizeDate(input.date, nowMs);\n if (!date) throw new Error(\"date must be YYYY-MM-DD (a weekday name means the next one).\");\n var start = given(input.start) ? normalizeTime(input.start) : null;\n var end = given(input.end) ? normalizeTime(input.end) : null;\n if (given(input.start) && !start) throw new Error(\"start must be a time like '06:00' or '6am'.\");\n if (given(input.end) && !end) throw new Error(\"end must be a time like '14:00' or '2pm'.\");\n var role = key(input.role);\n var needed = given(input.needed) ? Math.round(num(input.needed)) : null;\n if (given(input.needed) && !(needed >= 1)) throw new Error('needed must be 1 or more people.');\n t.focus = mondayOf(date);\n var existing = start\n ? t.data.shifts.filter(function (s) {\n return s.fields.date === date && s.fields.start === start && key(s.fields.role) === role;\n })[0]\n : null;\n if (existing) {\n var fields = {};\n if (end) fields.end = end;\n if (needed !== null) fields.needed = needed;\n if (input.note) fields.note = String(input.note).trim();\n if (fields.end && fields.end === existing.fields.start) throw new Error('start and end are the same time.');\n t.update('shifts', existing.id, fields, 'Changed');\n var back = reopen(t, existing.id, byPerson);\n var s0 = t.get('shifts', existing.id);\n return 'Updated ' + shiftLabel(s0) + ': needs ' + neededOf(s0) + ', has ' + staffOn(s0).length + '.' + (back ? ' It needs the person’s approval again.' : '');\n }\n if (!start || !end) throw new Error(\"A new shift needs 'start' and 'end', e.g. '06:00' and '14:00'.\");\n if (start === end) throw new Error('start and end are the same time.');\n var fieldsNew = { date: date, start: start, end: end, role: role, needed: needed || 1, staff: [] };\n if (input.note) fieldsNew.note = String(input.note).trim();\n var id = t.add('shifts', 'sh', 'draft', fieldsNew, 'Added');\n var s = t.get('shifts', id);\n var free = freeFor(s, t.data);\n return (\n 'Added ' + shiftLabel(s) + ', needs ' + neededOf(s) + '. Free for it: ' +\n (free.length\n ? free\n .slice(0, 4)\n .map(function (x) {\n return x.name + ' (' + x.hours + 'h)';\n })\n .join(', ')\n : 'nobody passes every rule yet') + '.'\n );\n}\nfunction copyWeek(t, input, nowMs) {\n var target = given(input.week) ? normalizeDate(input.week, nowMs) : addDays(mondayOf(localDay(nowMs)), 7);\n if (!target) throw new Error('week must be a date in the week to fill, YYYY-MM-DD.');\n var to = mondayOf(target);\n var source = given(input.fromWeek) ? normalizeDate(input.fromWeek, nowMs) : addDays(to, -7);\n if (!source) throw new Error('fromWeek must be a date in the week to copy, YYYY-MM-DD.');\n var from = mondayOf(source);\n if (from === to) throw new Error('Pick two different weeks to copy between.');\n t.focus = to;\n var list = weekShifts(t.data.shifts, from);\n if (!list.length) return 'The week of Mon ' + from + ' has no shifts to copy.';\n var shiftBy = Math.round((Date.parse(to + 'T12:00:00') - Date.parse(from + 'T12:00:00')) / DAY_MS);\n var added = 0;\n var skipped = 0;\n var kept = 0;\n var left = [];\n list.forEach(function (s) {\n var date = addDays(s.fields.date, shiftBy);\n var exists = t.data.shifts.filter(function (x) {\n return x.fields.date === date && x.fields.start === s.fields.start && key(x.fields.role) === key(s.fields.role);\n })[0];\n if (exists) {\n skipped += 1;\n return;\n }\n var draft = { id: '(copy)', status: 'draft', fields: { date: date, start: s.fields.start, end: s.fields.end, role: s.fields.role || '', needed: neededOf(s), staff: [] } };\n staffOn(s).forEach(function (pid) {\n var p = person(t.data, pid);\n if (!p) return;\n var why = problems(p, draft, t.data, { hours: true });\n if (why.length) left.push(why[0]);\n else draft.fields.staff.push(pid);\n });\n kept += draft.fields.staff.length;\n t.add('shifts', 'sh', 'draft', draft.fields, 'Copied from ' + s.id);\n added += 1;\n });\n return (\n 'Copied ' + added + (added === 1 ? ' shift' : ' shifts') + ' from the week of Mon ' + from + ' into the week of Mon ' + to +\n (skipped ? ' (' + skipped + ' were already there)' : '') + ', keeping ' + kept + (kept === 1 ? ' assignment' : ' assignments') +\n (left.length ? ' and leaving ' + left.length + (left.length === 1 ? ' spot' : ' spots') + ' open: ' + left.join('; ') : '') +\n '. The copied shifts are drafts for the person to approve.'\n );\n}\nfunction assign(t, input, nowMs) {\n var byPerson = input.byPerson === true;\n var s = findShift(t.data.shifts, input, nowMs);\n t.focus = mondayOf(s.fields.date);\n var adding = given(input.staff) ? findStaff(t.data.staff, input.staff) : null;\n var removing = given(input.remove) ? findStaff(t.data.staff, input.remove) : null;\n if (!adding && !removing) throw new Error(\"assign needs 'staff' (who to put on the shift) or 'remove' (who to take off).\");\n var on = staffOn(s).slice();\n var notes = [];\n var changed = false;\n if (removing) {\n if (on.indexOf(removing.id) < 0) throw new Error(removing.fields.name + ' is not on ' + shiftLabel(s) + '. On it: ' + (namesOn(t.data, s) || 'nobody') + '.');\n on.splice(on.indexOf(removing.id), 1);\n t.update('shifts', s.id, { staff: on.slice() }, 'Took ' + removing.fields.name + ' off');\n changed = true;\n notes.push('Took ' + removing.fields.name + ' off ' + shiftLabel(s) + '.');\n }\n if (adding) {\n if (on.indexOf(adding.id) >= 0) notes.push(adding.fields.name + ' is already on ' + shiftLabel(s) + '.');\n else {\n if (on.length >= neededOf(s)) {\n throw new Error(shiftLabel(s) + ' already has its ' + neededOf(s) + ' (' + namesOn(t.data, t.get('shifts', s.id)) + '). Take someone off with remove, or raise needed with add_shift.');\n }\n var why = problems(adding, t.get('shifts', s.id), t.data, { hours: true });\n if (why.length && !byPerson) {\n var free = freeFor(t.get('shifts', s.id), t.data);\n throw new Error(\n adding.fields.name + \" can't take \" + shiftLabel(s) + ': ' + why.join('; ') + '. Free for it: ' +\n (free.length\n ? free\n .slice(0, 4)\n .map(function (x) {\n return x.name + ' (' + x.id + ', ' + x.hours + 'h)';\n })\n .join(', ')\n : 'nobody passes every rule; tell the person') + '.',\n );\n }\n on.push(adding.id);\n t.update('shifts', s.id, { staff: on.slice() }, 'Put ' + adding.fields.name + ' on');\n changed = true;\n notes.push('Put ' + adding.fields.name + ' on ' + shiftLabel(s) + '.' + (why.length ? ' Saved as the person asked, though ' + why.join('; ') + '.' : ''));\n }\n }\n var back = changed ? reopen(t, s.id, byPerson) : false;\n var after = t.get('shifts', s.id);\n var open = neededOf(after) - staffOn(after).length;\n notes.push(open > 0 ? 'It still needs ' + open + ' more.' : 'It is covered.');\n if (back) notes.push('It needs the person’s approval again.');\n return notes.join(' ');\n}\nfunction setRules(t, input) {\n var rules = JSON.parse(JSON.stringify(t.data.rules || {}));\n rules.version = 1;\n rules.notes = Array.isArray(rules.notes) ? rules.notes : [];\n var changed = false;\n ['maxWeekHours', 'minRestHours', 'maxShiftHours'].forEach(function (k) {\n if (!given(input[k])) return;\n var v = num(input[k]);\n if (v === null || v < 0) throw new Error(k + ' must be a number of hours, zero or more (0 removes the rule).');\n rules[k] = v > 0 ? v : null;\n changed = true;\n });\n var rule = String(input.rule || '').trim();\n if (rule) {\n if (rules.notes.map(key).indexOf(key(rule)) < 0) rules.notes.push(rule);\n changed = true;\n }\n var forget = key(input.forget);\n if (forget) {\n rules.notes = rules.notes.filter(function (n) {\n return key(n).indexOf(forget) < 0;\n });\n changed = true;\n }\n if (!changed) throw new Error(\"set_rules needs maxWeekHours, minRestHours, maxShiftHours, a rule in the business's own words, or forget.\");\n t.setRules(rules);\n return 'Saved the rules; the conflicts below are checked against them.';\n}\nfunction approve(t, input, nowMs) {\n var day = given(input.week) ? normalizeDate(input.week, nowMs) : localDay(nowMs);\n if (!day) throw new Error('week must be a date in the week to approve, YYYY-MM-DD.');\n var monday = mondayOf(day);\n t.focus = monday;\n var list = weekShifts(t.data.shifts, monday).filter(function (s) {\n return s.status !== 'approved';\n });\n if (!list.length) return 'Nothing in the week of Mon ' + monday + ' is waiting for approval.';\n list.forEach(function (s) {\n t.transition('shifts', s.id, 'approved', 'Approved by the person');\n });\n var v = weekView(t.data, monday, nowMs);\n var open = v.gaps.reduce(function (sum, g) {\n return sum + g.open;\n }, 0);\n return (\n 'Approved ' + list.length + (list.length === 1 ? ' shift' : ' shifts') + ' for the week of Mon ' + monday + '.' +\n (open ? ' ' + open + (open === 1 ? ' spot is' : ' spots are') + ' still open.' : ' Every shift is covered.') +\n (v.conflicts.length ? ' ' + v.conflicts.length + (v.conflicts.length === 1 ? ' conflict remains.' : ' conflicts remain.') : '')\n );\n}\nfunction run(action, input, state, nowMs) {\n input = input || {};\n var t = transaction(state, nowMs);\n var note = '';\n var week = null;\n if (action === 'add_staff') note = addStaff(t, input, nowMs);\n else if (action === 'availability') note = setAvailability(t, input, nowMs);\n else if (action === 'add_shift') note = addShift(t, input, nowMs);\n else if (action === 'copy_week') note = copyWeek(t, input, nowMs);\n else if (action === 'assign') note = assign(t, input, nowMs);\n else if (action === 'rules') note = setRules(t, input);\n else if (action === 'approve') note = approve(t, input, nowMs);\n else if (action === 'status') {\n if (given(input.week)) {\n week = normalizeDate(input.week, nowMs);\n if (!week) throw new Error('week must be a date in the week, YYYY-MM-DD.');\n }\n } else throw new Error(\"Unknown action '\" + action + \"'. Use status, add_staff, availability, add_shift, copy_week, assign, rules, or approve.\");\n // A change outside this week and next is reported on its own week.\n var thisWeek = mondayOf(localDay(nowMs));\n if (!week && t.focus && t.focus !== thisWeek && t.focus !== addDays(thisWeek, 7)) week = t.focus;\n var view = picture(t.data, nowMs, week);\n return {\n ops: t.ops,\n state: t.data,\n output: {\n openSpots: view.openSpots,\n conflicts: view.conflicts,\n toApprove: view.toApprove,\n shifts: view.shifts,\n week: view.monday,\n summary: (note ? note + ' ' : '') + view.summary,\n },\n };\n}\n// ── roster-rules-end ──\n\nconst stores = {\n staff: rosterStore(gezel.fs, 'staff.json', { stages: ['active', 'inactive'], idPrefix: 'st' }),\n shifts: rosterStore(gezel.fs, 'shifts.json', { stages: ['draft', 'approved'], idPrefix: 'sh' }),\n availability: rosterStore(gezel.fs, 'availability.json', { stages: ['active', 'cleared'], idPrefix: 'av' }),\n};\nasync function readRules(): Promise<Record<string, unknown>> {\n let raw: string;\n try {\n raw = await gezel.fs.read('rules.json');\n } catch {\n return { version: 1, notes: [] };\n }\n try {\n return JSON.parse(raw);\n } catch {\n throw new Error('rules.json is not valid JSON. Fix or remove it; it is not overwritten automatically.');\n }\n}\nconst before = {\n staff: await stores.staff.list(),\n shifts: await stores.shifts.list(),\n availability: await stores.availability.list(),\n rules: await readRules(),\n};\nconst result = run(String(input.action), input, before, Date.now());\n// Replay the changes through the stores, in order, so the files keep their history.\nfor (const op of result.ops) {\n if (op.store === 'rules') {\n await gezel.fs.write('rules.json', JSON.stringify(op.value, null, 2) + '\\n');\n continue;\n }\n const store = stores[op.store as 'staff' | 'shifts' | 'availability'];\n if (op.op === 'add') await store.add({ id: op.id, status: op.status, fields: op.fields, note: op.note });\n else if (op.op === 'update') await store.update(op.id, { fields: op.fields, ...(op.note ? { note: op.note } : {}) });\n else await store.transition(op.id, op.to, op.note ? { note: op.note } : {});\n}\ngezel.output(result.output);\n"},"tools":[{"name":"roster_status","description":"This week and next: the open spots (soonest first, with who is free for each), conflicts, everyone's hours against their limits, the schedule by day, availability and the business's rules, all with ids. Call it first when asked where you're short, who is working, or how many hours someone has. Pass week for another week.","script":"roster-store","inputs":{"type":"object","properties":{"week":{"type":"string","description":"Any date in the week, YYYY-MM-DD."}}},"bind":{"action":"status"},"state":true},{"name":"add_staff","description":"Save a person on the roster: name, the roles they work, and their own weekly hour limit if the business states one. An existing name is updated, never duplicated; status inactive takes someone off the active staff. Call it as soon as a person is mentioned, before you describe it.","script":"roster-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"roles":{"type":"string","description":"What they work, comma-separated, e.g. 'barista, kitchen'."},"maxHours":{"type":"number","description":"Their own weekly hour limit, only as the business states it."},"status":{"type":"string","enum":["active","inactive"]},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"add_staff"}},{"name":"set_availability","description":"Record when someone can't work: a weekday for every week, weekdays, weekends, every day, or one date, all day or for part of it. available true clears it. Call it the moment the person tells you; it names any shift that now clashes.","script":"roster-store","inputs":{"type":"object","properties":{"staff":{"type":"string","description":"Name or id."},"day":{"type":"string","description":"A weekday ('tuesday') for every week, 'weekdays', 'weekends', 'every day', or a date (YYYY-MM-DD) for one day."},"part":{"type":"string","enum":["all day","morning","afternoon","evening"]},"from":{"type":"string","description":"Unavailable from this time, e.g. '17:00'."},"to":{"type":"string","description":"Unavailable until this time, e.g. '12:00'."},"available":{"type":"boolean","description":"True when they can work that day again."},"date":{"type":"string","description":"Only with day 'one date': the date, YYYY-MM-DD."},"note":{"type":"string"}},"required":["staff","day"]},"bind":{"action":"availability"}},{"name":"add_shift","description":"Add a shift: date, start, end, role and how many people it needs. A shift with the same date, start and role is updated, never duplicated. Call it as soon as a shift is mentioned.","script":"roster-store","inputs":{"type":"object","properties":{"date":{"type":"string","description":"YYYY-MM-DD."},"start":{"type":"string","description":"e.g. '06:00'."},"end":{"type":"string","description":"e.g. '14:00'."},"role":{"type":"string","description":"What the shift works, e.g. 'barista' or 'kitchen'."},"needed":{"type":"number","description":"How many people it needs."},"note":{"type":"string"}},"required":["date"]},"bind":{"action":"add_shift","byPerson":false}},{"name":"copy_week","description":"Start a week from another one (default: the week before), keeping each person only where they still pass every rule and availability. Existing shifts are never duplicated. Use it to draft next week in one call.","script":"roster-store","inputs":{"type":"object","properties":{"week":{"type":"string","description":"Any date in the week to fill."},"fromWeek":{"type":"string","description":"Any date in the week to copy (default: the week before)."}}},"bind":{"action":"copy_week"}},{"name":"assign_shift","description":"Put someone on a shift (staff) or take someone off (remove), by the shift's id. It refuses a person who is unavailable, already working, short of rest or over their hours, and names who is free instead. Your assignments are proposals: the person approves each week on the roster page.","script":"roster-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"The shift id from roster_status, e.g. 'sh-4'."},"date":{"type":"string","description":"Without an id: the shift date, YYYY-MM-DD."},"start":{"type":"string","description":"Without an id: the start time."},"role":{"type":"string","description":"Without an id: the role."},"staff":{"type":"string","description":"Who to put on it: name or id."},"remove":{"type":"string","description":"Who to take off it: name or id."}}},"bind":{"action":"assign","byPerson":false}},{"name":"set_rules","description":"Record a scheduling rule the business states: most hours a week, fewest hours between shifts, longest shift, or another rule in their words. Only ever record rules they state; never add your own.","script":"roster-store","inputs":{"type":"object","properties":{"maxWeekHours":{"type":"number","description":"Most hours a week per person (0 removes the rule)."},"minRestHours":{"type":"number","description":"Fewest hours between shifts (0 removes the rule)."},"maxShiftHours":{"type":"number","description":"Longest shift in hours (0 removes the rule)."},"rule":{"type":"string","description":"Any other rule, in the business's own words."},"forget":{"type":"string","description":"Drop the written rule containing this text."}}},"bind":{"action":"rules"}},{"name":"page_add_staff","description":"Add or update a person.","script":"roster-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"roles":{"type":"string","description":"What they work, comma-separated, e.g. 'barista, kitchen'."},"maxHours":{"type":"number","description":"Their own weekly hour limit, only as the business states it."},"status":{"type":"string","enum":["active","inactive"]},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"add_staff"}},{"name":"page_add_shift","description":"Add or update a shift.","script":"roster-store","inputs":{"type":"object","properties":{"date":{"type":"string","description":"YYYY-MM-DD."},"start":{"type":"string","description":"e.g. '06:00'."},"end":{"type":"string","description":"e.g. '14:00'."},"role":{"type":"string","description":"What the shift works, e.g. 'barista' or 'kitchen'."},"needed":{"type":"number","description":"How many people it needs."},"note":{"type":"string"}},"required":["date"]},"bind":{"action":"add_shift","byPerson":true}},{"name":"page_assign_shift","description":"Put someone on a shift or take them off.","script":"roster-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"The shift id from roster_status, e.g. 'sh-4'."},"date":{"type":"string","description":"Without an id: the shift date, YYYY-MM-DD."},"start":{"type":"string","description":"Without an id: the start time."},"role":{"type":"string","description":"Without an id: the role."},"staff":{"type":"string","description":"Who to put on it: name or id."},"remove":{"type":"string","description":"Who to take off it: name or id."}}},"bind":{"action":"assign","byPerson":true}},{"name":"page_set_availability","description":"Record when someone cannot work.","script":"roster-store","inputs":{"type":"object","properties":{"staff":{"type":"string","description":"Name or id."},"day":{"type":"string","description":"A weekday ('tuesday') for every week, 'weekdays', 'weekends', 'every day', or a date (YYYY-MM-DD) for one day."},"part":{"type":"string","enum":["all day","morning","afternoon","evening"]},"from":{"type":"string","description":"Unavailable from this time, e.g. '17:00'."},"to":{"type":"string","description":"Unavailable until this time, e.g. '12:00'."},"available":{"type":"boolean","description":"True when they can work that day again."},"date":{"type":"string","description":"Only with day 'one date': the date, YYYY-MM-DD."},"note":{"type":"string"}},"required":["staff","day"]},"bind":{"action":"availability"},"reaction":{"gezel":"shift-scheduler","prompt":"The person just changed someone's availability on the roster page. The roster now reads (its first sentence is what changed):\n{{output.summary}}\nIn one or two short sentences: if that change clashes with a shift, propose one person from the free list to cover it and ask whether to make the swap; otherwise just confirm it. Do not call tools.","hideSeed":true}},{"name":"page_set_rules","description":"Record the business’s scheduling rules.","script":"roster-store","inputs":{"type":"object","properties":{"maxWeekHours":{"type":"number","description":"Most hours a week per person (0 removes the rule)."},"minRestHours":{"type":"number","description":"Fewest hours between shifts (0 removes the rule)."},"maxShiftHours":{"type":"number","description":"Longest shift in hours (0 removes the rule)."},"rule":{"type":"string","description":"Any other rule, in the business's own words."},"forget":{"type":"string","description":"Drop the written rule containing this text."}}},"bind":{"action":"rules"}},{"name":"page_approve_week","description":"Approve every draft shift in a week.","script":"roster-store","inputs":{"type":"object","properties":{"week":{"type":"string","description":"Any date in the week, YYYY-MM-DD."}}},"bind":{"action":"approve","byPerson":true},"reaction":{"gezel":"shift-scheduler","prompt":"The person just approved a week on the roster page. The roster now reads (its first sentence is what changed):\n{{output.summary}}\nIn two short sentences, confirm the approval and name any open spot still to fill. Do not call tools.","hideSeed":true}}],"pages":{"entry":"roster/index.html","api":1,"reads":[{"source":"workspace","path":"staff.json"},{"source":"workspace","path":"shifts.json"},{"source":"workspace","path":"availability.json"},{"source":"workspace","path":"rules.json"}],"tools":["page_add_staff","page_add_shift","page_assign_shift","page_set_availability","page_set_rules","page_approve_week"]},"schedules":[],"workspaceSeed":["staff.json","shifts.json","availability.json","rules.json"],"artifactsSeed":[],"availableVersions":["1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"social-feed","name":"Social Feed","description":"Run a social feed like a small newsroom — a social media writer keeps every post moving through a real pipeline (idea to published, nothing by accident), a copywriter sharpens each variant for its platform, and a live board shows exactly where every post stands.","tags":["social","bluesky","x","linkedin","posts","publishing"],"category":"communication","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.5","releasedAt":"2026-11-02T18:00:00.000Z","extends":"social-media","meesterManaged":true,"mode":"crew","leadLabel":"Social Media Writer","params":{"type":"object","properties":{"brand":{"type":"string","title":"Who does this feed speak for?","description":"The name or brand this feed speaks for.","default":"Our brand"},"blueskyHandle":{"type":"string","title":"Bluesky handle","description":"Bluesky handle (e.g. you.bsky.social). Leave empty if unused.","default":""},"xHandle":{"type":"string","title":"X handle","description":"X handle (e.g. @brand). Leave empty if unused.","default":""},"linkedinHandle":{"type":"string","title":"LinkedIn profile or page","description":"LinkedIn profile or page name (e.g. in/yourname). Leave empty if unused.","default":""},"voice":{"type":"string","title":"Tone of voice","description":"One sentence on tone of voice — seeded into voice-guide.md.","default":"Warm, plain, and human — never corporate."},"cadence":{"type":"string","title":"Posting cadence","description":"Target posting cadence (e.g. 3 posts a week).","default":"3 posts a week"}},"required":["brand"]},"nameTemplate":"{{brand}} Social Feed","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"omroeper","voorman":true},{"templateId":"copywriter","voorman":false}],"toolsets":[],"craftbooks":["draft-social-post","social-digest","reception-report"],"scripts":{"posts-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\n\nexport const meta = defineScript({\n name: 'posts-store',\n description:\n \"Read and update the post pipeline under posts/. Call action:'list' to see every post (optional status/platform filters); 'get' for one post's frontmatter, body, variants, and media; 'create' to add a post from a title and body, or to commit the staged posts/_drafting/ folder as a real post; 'update' to patch frontmatter or move a post one pipeline stage (idea, draft, in-review, approved, scheduled, published, archived from anywhere); 'record_publication' to stamp a platform variant with its permalink after it goes live. Illegal stage jumps fail with the legal next stages — move one stage at a time.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'list', 'get', 'create', 'update', or 'record_publication'.\",\n required: true,\n },\n id: { type: 'string', description: \"Post id — its folder name under posts/, e.g. '2026-08-12-launch-teaser'.\" },\n status: {\n type: 'string',\n description: \"Target status: idea, draft, in-review, approved, scheduled, published, or archived. For 'create', the initial status (defaults to approved).\",\n },\n platform: { type: 'string', description: \"Platform filter for 'list', or the published variant for 'record_publication' (e.g. 'bluesky').\" },\n fields: {\n type: 'json',\n description: \"For 'update': an object of frontmatter patches, e.g. {\\\"scheduledFor\\\": \\\"2026-08-15T09:00:00Z\\\", \\\"campaign\\\": \\\"autumn\\\"}. A null value clears the key.\",\n },\n title: { type: 'string', description: \"For 'create': the post's title, to write it in one call.\" },\n body: { type: 'string', description: \"For 'create': the post's text, to write it in one call.\" },\n platforms: { type: 'string', description: \"For 'create': comma-separated platforms, e.g. 'linkedin, bluesky'.\" },\n permalink: { type: 'string', description: 'Public URL of the live post, for record_publication.' },\n postId: { type: 'string', description: \"The platform's own id for the live post, for record_publication.\" },\n corpusRef: { type: 'string', description: 'Connector corpus record reference for the live post, when one exists.' },\n publishedAt: { type: 'string', description: 'ISO timestamp the post went live (defaults to now).' },\n markPublished: {\n type: 'boolean',\n description: 'For record_publication: force the post to published even if other target platforms are not stamped yet.',\n },\n },\n // Only what every action returns is declared: the runtime requires each\n // declared output on every run, so listing per-action fields here failed\n // every call. 'list' also returns posts + total, 'get' returns post, and\n // the writes return id + status.\n outputs: {\n summary: { type: 'string', description: 'Human-readable result.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\nconst POSTS_DIR = 'posts';\nconst DRAFTING = 'posts/_drafting';\nconst INDEX_FILE = 'posts/index.json';\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,99}$/;\nconst PLATFORM_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;\nconst STAGES = ['idea', 'draft', 'in-review', 'approved', 'scheduled', 'published'] as const;\nconst STATUSES: string[] = [...STAGES, 'archived'];\n\n// ── frontmatter ──\n// Hand-rolled, deliberately simple: `---`-delimited `key: value` lines,\n// arrays as [a, b]. Unknown keys and even unparseable lines are preserved\n// in order so a round-trip never loses what a human or another tool wrote.\n\ntype FmEntry = { key: string; value: string | string[] } | { raw: string };\ninterface FmDoc {\n entries: FmEntry[];\n body: string;\n}\n\nfunction parseArrayish(value: string): string[] {\n return value\n .slice(1, -1)\n .split(',')\n .map((part) => part.trim().replace(/^[\"']|[\"']$/g, ''))\n .filter((part) => part.length > 0);\n}\n\nfunction parseFrontmatter(text: string): FmDoc {\n const lines = text.split(/\\r?\\n/);\n if (lines[0]?.trim() !== '---') return { entries: [], body: text };\n const entries: FmEntry[] = [];\n let at = 1;\n for (; at < lines.length; at += 1) {\n const line = lines[at]!;\n if (line.trim() === '---') {\n return { entries, body: lines.slice(at + 1).join('\\n').replace(/^\\n/, '') };\n }\n const sep = line.indexOf(':');\n if (sep <= 0) {\n if (line.trim().length > 0) entries.push({ raw: line });\n continue;\n }\n const key = line.slice(0, sep).trim();\n const value = line.slice(sep + 1).trim();\n if (!key) {\n entries.push({ raw: line });\n continue;\n }\n entries.push({\n key,\n value: value.startsWith('[') && value.endsWith(']') ? parseArrayish(value) : value,\n });\n }\n return { entries: [], body: text };\n}\n\nfunction serializeFrontmatter(doc: FmDoc): string {\n const lines = doc.entries.map((entry) => {\n if ('raw' in entry) return entry.raw;\n const value = Array.isArray(entry.value) ? `[${entry.value.join(', ')}]` : entry.value;\n return `${entry.key}: ${value}`;\n });\n return `---\\n${lines.join('\\n')}\\n---\\n\\n${doc.body.replace(/^\\n+/, '')}`;\n}\n\nfunction fmGet(doc: FmDoc, key: string): string | string[] | undefined {\n for (const entry of doc.entries) {\n if ('key' in entry && entry.key === key) return entry.value;\n }\n return undefined;\n}\n\nfunction fmGetString(doc: FmDoc, key: string): string {\n const value = fmGet(doc, key);\n if (Array.isArray(value)) return value.join(', ');\n return value ?? '';\n}\n\nfunction fmGetArray(doc: FmDoc, key: string): string[] {\n const value = fmGet(doc, key);\n if (Array.isArray(value)) return value;\n if (typeof value === 'string' && value.length > 0) return [value];\n return [];\n}\n\nfunction fmSet(doc: FmDoc, key: string, value: string | string[]): void {\n for (const entry of doc.entries) {\n if ('key' in entry && entry.key === key) {\n entry.value = value;\n return;\n }\n }\n doc.entries.push({ key, value });\n}\n\nfunction fmDelete(doc: FmDoc, key: string): void {\n doc.entries = doc.entries.filter((entry) => !('key' in entry && entry.key === key));\n}\n\n// ── pipeline rules ──\n\nfunction legalNext(from: string): string[] {\n if (from === 'archived') return [];\n const at = STAGES.indexOf(from as (typeof STAGES)[number]);\n const forward = at >= 0 && at < STAGES.length - 1 ? [STAGES[at + 1]!] : [];\n return [...forward, 'archived'];\n}\n\nfunction assertTransition(id: string, from: string, to: string): void {\n if (to === from) return;\n if (!STATUSES.includes(to)) {\n throw new Error(`Unknown status '${to}'. Statuses: ${STATUSES.join(', ')}.`);\n }\n if (!legalNext(from).includes(to)) {\n const next = legalNext(from);\n throw new Error(\n `Cannot move '${id}' from ${from} to ${to} — posts move one stage at a time. ` +\n (next.length > 0 ? `Legal next: ${next.join(', ')}.` : `'${from}' is final; create a new post instead.`),\n );\n }\n}\n\nfunction requireId(): string {\n const id = (input.id ?? '').trim();\n if (!id) throw new Error(\"Pass 'id' — the post's folder name under posts/ (see action:'list').\");\n if (!ID_RE.test(id)) {\n throw new Error(`Invalid post id '${id}'. Ids are lowercase [a-z0-9-], no slashes or dots.`);\n }\n return id;\n}\n\nfunction today(): string {\n return new Date().toISOString().slice(0, 10);\n}\n\nfunction slugify(text: string): string {\n return text\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 60);\n}\n\n// ── store ──\n\ninterface IndexEntry {\n id: string;\n title: string;\n status: string;\n platforms: string[];\n created: string;\n scheduledFor?: string;\n campaign?: string;\n}\n\nasync function readPostDoc(id: string): Promise<FmDoc> {\n let raw: string;\n try {\n raw = await gezel.fs.read(`${POSTS_DIR}/${id}/post.md`);\n } catch {\n throw new Error(`No post '${id}' — posts/${id}/post.md does not exist. Call action:'list' to see what does.`);\n }\n return parseFrontmatter(raw);\n}\n\nasync function writePostDoc(id: string, doc: FmDoc): Promise<void> {\n await gezel.fs.write(`${POSTS_DIR}/${id}/post.md`, serializeFrontmatter(doc));\n}\n\nfunction toIndexEntry(id: string, doc: FmDoc): IndexEntry {\n const entry: IndexEntry = {\n id,\n title: fmGetString(doc, 'title') || id,\n status: fmGetString(doc, 'status') || 'idea',\n platforms: fmGetArray(doc, 'platforms'),\n created: fmGetString(doc, 'created') || today(),\n };\n const scheduledFor = fmGetString(doc, 'scheduledFor');\n if (scheduledFor) entry.scheduledFor = scheduledFor;\n const campaign = fmGetString(doc, 'campaign');\n if (campaign) entry.campaign = campaign;\n return entry;\n}\n\nasync function regenerateIndex(): Promise<IndexEntry[]> {\n let names: string[] = [];\n try {\n names = (await gezel.fs.list(POSTS_DIR))\n .filter((entry) => entry.isDirectory && entry.name !== '_drafting' && ID_RE.test(entry.name))\n .map((entry) => entry.name);\n } catch {\n names = [];\n }\n const posts: IndexEntry[] = [];\n for (const name of names) {\n try {\n posts.push(toIndexEntry(name, await readPostDoc(name)));\n } catch {\n // A folder without a parseable post.md is not a post; leave it be.\n }\n }\n posts.sort((a, b) => (a.created === b.created ? (a.id < b.id ? 1 : -1) : a.created < b.created ? 1 : -1));\n await gezel.fs.write(INDEX_FILE, `${JSON.stringify({ version: 1, posts }, null, 2)}\\n`);\n return posts;\n}\n\nasync function readIndex(): Promise<IndexEntry[]> {\n try {\n const parsed = JSON.parse(await gezel.fs.read(INDEX_FILE)) as { posts?: IndexEntry[] };\n return Array.isArray(parsed.posts) ? parsed.posts : [];\n } catch {\n return [];\n }\n}\n\nasync function listVariants(id: string): Promise<Record<string, Record<string, unknown>>> {\n let names: string[] = [];\n try {\n names = (await gezel.fs.list(`${POSTS_DIR}/${id}/variants`))\n .filter((entry) => !entry.isDirectory && entry.name.endsWith('.md'))\n .map((entry) => entry.name);\n } catch {\n return {};\n }\n const variants: Record<string, Record<string, unknown>> = {};\n for (const name of names) {\n const platform = name.slice(0, -3);\n const doc = parseFrontmatter(await gezel.fs.read(`${POSTS_DIR}/${id}/variants/${name}`));\n const body = doc.body.trim();\n const variant: Record<string, unknown> = {\n charCount: Number(fmGetString(doc, 'charCount')) || body.length,\n body,\n };\n for (const key of ['publishedAt', 'permalink', 'postId', 'corpusRef']) {\n const value = fmGetString(doc, key);\n if (value) variant[key] = value;\n }\n variants[platform] = variant;\n }\n return variants;\n}\n\nasync function listMedia(id: string): Promise<string[]> {\n try {\n return (await gezel.fs.list(`${POSTS_DIR}/${id}/media`))\n .filter((entry) => !entry.isDirectory)\n .map((entry) => entry.name);\n } catch {\n return [];\n }\n}\n\n// ── actions ──\n\nif (input.action === 'list') {\n const all = await readIndex();\n let posts = all;\n if (input.status) posts = posts.filter((post) => post.status === input.status);\n if (input.platform) posts = posts.filter((post) => post.platforms.includes(input.platform!));\n const counts = STATUSES.map((status) => {\n const n = all.filter((post) => post.status === status).length;\n return n > 0 ? `${status} ${n}` : null;\n })\n .filter((line) => line !== null)\n .join(', ');\n gezel.output({\n posts,\n total: all.length,\n summary: all.length === 0 ? 'No posts yet — stage one in posts/_drafting/ and call create.' : `${all.length} post(s): ${counts}.`,\n });\n} else if (input.action === 'get') {\n const id = requireId();\n const doc = await readPostDoc(id);\n const fields: Record<string, unknown> = {};\n for (const entry of doc.entries) {\n if ('key' in entry) fields[entry.key] = entry.value;\n }\n const post = {\n id,\n ...fields,\n status: fmGetString(doc, 'status') || 'idea',\n platforms: fmGetArray(doc, 'platforms'),\n body: doc.body.trim(),\n variants: await listVariants(id),\n media: await listMedia(id),\n };\n gezel.output({\n post,\n id,\n status: post.status,\n summary: `'${fmGetString(doc, 'title') || id}' is ${post.status}; ${Object.keys(post.variants).length} variant(s), ${post.media.length} media file(s).`,\n });\n} else if (input.action === 'create') {\n let staged: FmDoc;\n if (input.title && input.body) {\n // The post itself in one call: a project's first draft is made with its\n // own tools, and a lead without file tools could never stage a draft.\n staged = { entries: [], body: String(input.body).trim() };\n fmSet(staged, 'title', String(input.title).replace(/\\s+/g, ' ').trim());\n const platforms = String(input.platforms ?? '')\n .split(',')\n .map((platform) => platform.trim().toLowerCase())\n .filter((platform) => PLATFORM_RE.test(platform));\n if (platforms.length > 0) fmSet(staged, 'platforms', platforms);\n await gezel.fs.write(`${DRAFTING}/post.md`, serializeFrontmatter(staged));\n } else {\n try {\n staged = parseFrontmatter(await gezel.fs.read(`${DRAFTING}/post.md`));\n } catch {\n throw new Error('Nothing is staged — give a title and body, or write posts/_drafting/post.md (frontmatter + body) first, then call create again.');\n }\n }\n const slug = slugify(fmGetString(staged, 'slug') || fmGetString(staged, 'title'));\n if (!slug) throw new Error(\"The staged post.md needs a 'slug' or a 'title' in its frontmatter to name the post folder.\");\n const createdRaw = fmGetString(staged, 'created');\n const created = /^\\d{4}-\\d{2}-\\d{2}$/.test(createdRaw) ? createdRaw : today();\n const id = `${created}-${slug}`;\n if (!ID_RE.test(id)) throw new Error(`Derived post id '${id}' is invalid — keep slug to lowercase letters, digits, and dashes.`);\n const siblings = await gezel.fs.list(POSTS_DIR).catch(() => []);\n if (siblings.some((entry) => entry.name === id)) {\n throw new Error(`posts/${id}/ already exists. Change the staged slug (or created date) and call create again.`);\n }\n const status = input.status ?? 'approved';\n if (!STATUSES.includes(status)) {\n throw new Error(`'${status}' is not a status. Statuses: ${STATUSES.join(', ')}.`);\n }\n fmSet(staged, 'status', status);\n fmSet(staged, 'slug', slug);\n fmSet(staged, 'created', created);\n await gezel.fs.write(`${DRAFTING}/post.md`, serializeFrontmatter(staged));\n await gezel.fs.rename(DRAFTING, `${POSTS_DIR}/${id}`);\n await regenerateIndex();\n gezel.output({\n id,\n status,\n summary: `Committed posts/_drafting/ as posts/${id}/ with status ${status}.`,\n });\n} else if (input.action === 'update') {\n const id = requireId();\n const doc = await readPostDoc(id);\n const patches = (input.fields && typeof input.fields === 'object' && !Array.isArray(input.fields) ? input.fields : {}) as Record<string, unknown>;\n let nextStatus = input.status;\n if (typeof patches.status === 'string' && !nextStatus) nextStatus = patches.status;\n delete patches.status;\n if (!nextStatus && Object.keys(patches).length === 0) {\n throw new Error(\"Nothing to change — pass 'status' and/or a 'fields' object of frontmatter patches.\");\n }\n const from = fmGetString(doc, 'status') || 'idea';\n if (nextStatus) assertTransition(id, from, nextStatus);\n for (const [key, value] of Object.entries(patches)) {\n if (value === null || value === undefined) fmDelete(doc, key);\n else if (Array.isArray(value)) fmSet(doc, key, value.map((item) => String(item)));\n else fmSet(doc, key, String(value));\n }\n if (nextStatus) fmSet(doc, 'status', nextStatus);\n await writePostDoc(id, doc);\n await regenerateIndex();\n const status = nextStatus ?? from;\n gezel.output({\n id,\n status,\n summary: nextStatus && nextStatus !== from ? `Moved '${id}' from ${from} to ${status}.` : `Updated '${id}' (${status}).`,\n });\n} else if (input.action === 'record_publication') {\n const id = requireId();\n const platform = (input.platform ?? '').trim();\n if (!PLATFORM_RE.test(platform)) {\n throw new Error(\"Pass 'platform' — the variant that went live, e.g. 'bluesky', 'x', or 'instagram'.\");\n }\n const doc = await readPostDoc(id);\n const variantPath = `${POSTS_DIR}/${id}/variants/${platform}.md`;\n const variant = parseFrontmatter(await gezel.fs.read(variantPath).catch(() => '---\\n---\\n'));\n fmSet(variant, 'publishedAt', input.publishedAt ?? new Date().toISOString());\n if (input.permalink) fmSet(variant, 'permalink', input.permalink);\n if (input.postId) fmSet(variant, 'postId', input.postId);\n if (input.corpusRef) fmSet(variant, 'corpusRef', input.corpusRef);\n await gezel.fs.write(variantPath, serializeFrontmatter(variant));\n const targets = fmGetArray(doc, 'platforms');\n const stamped = await listVariants(id);\n const allLive = targets.length > 0 && targets.every((target) => typeof stamped[target]?.publishedAt === 'string');\n let status = fmGetString(doc, 'status') || 'idea';\n // Recording reality bypasses the stage chain: once every target variant\n // is live (or the caller says so), the post IS published.\n if (allLive || input.markPublished === true) {\n status = 'published';\n fmSet(doc, 'status', status);\n await writePostDoc(id, doc);\n }\n await regenerateIndex();\n const waiting = targets.filter((target) => typeof stamped[target]?.publishedAt !== 'string');\n gezel.output({\n id,\n status,\n summary:\n status === 'published'\n ? `Recorded ${platform} publication for '${id}' — the post is published.`\n : `Recorded ${platform} publication for '${id}'; still waiting on: ${waiting.join(', ') || '(none)'}.`,\n });\n} else {\n throw new Error(`Unknown action '${input.action}'. Use list, get, create, update, or record_publication.`);\n}\n"},"tools":[{"name":"list_posts","description":"See the whole post pipeline: every post with its status, platforms, and dates. Optionally filter by status or platform.","script":"posts-store","inputs":{"type":"object","properties":{"status":{"type":"string","enum":["idea","draft","in-review","approved","scheduled","published","archived"],"description":"Only posts currently in this status."},"platform":{"type":"string","description":"Only posts targeting this platform, e.g. 'bluesky'."}}},"bind":{"action":"list"}},{"name":"get_post","description":"Read one post in full: frontmatter, body, each platform variant with its character count (and permalink once live), and media files.","script":"posts-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Post id — its folder name under posts/, e.g. '2026-08-12-launch-teaser'."}},"required":["id"]},"bind":{"action":"get"}},{"name":"create_post","description":"Add a post: give its title and body (and platforms) to write it in one call, or commit a draft staged in posts/_drafting/ (post.md with frontmatter + body, variants/, media/). The post folder is named from the created date and slug.","script":"posts-store","inputs":{"type":"object","properties":{"title":{"type":"string","description":"The post's title."},"body":{"type":"string","description":"The post's text, in the voice guide's voice."},"platforms":{"type":"string","description":"Comma-separated platforms, e.g. 'linkedin, bluesky'."},"status":{"type":"string","enum":["idea","draft","in-review","approved","scheduled","published","archived"],"description":"Initial status for the new post. Defaults to approved."}}},"bind":{"action":"create"}},{"name":"update_post","description":"Patch a post's frontmatter (fields object; null clears a key) and/or move it one pipeline stage. Stages run idea, draft, in-review, approved, scheduled, published — archived from anywhere.","script":"posts-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Post id."},"fields":{"type":"object","description":"Frontmatter patches, e.g. {\"scheduledFor\": \"2026-08-15T09:00:00Z\", \"campaign\": \"autumn\"}."},"status":{"type":"string","enum":["idea","draft","in-review","approved","scheduled","published","archived"],"description":"Target status (one stage at a time)."}},"required":["id"]},"bind":{"action":"update"}},{"name":"record_publication","description":"The moment a variant goes live, stamp it with its permalink and platform post id. The post flips to published once every target platform is stamped (or markPublished is passed).","script":"posts-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Post id."},"platform":{"type":"string","description":"The platform that went live, e.g. 'bluesky'."},"permalink":{"type":"string","description":"Public URL of the live post."},"postId":{"type":"string","description":"The platform's own id for the live post."},"corpusRef":{"type":"string","description":"Connector corpus record reference, when one exists."},"publishedAt":{"type":"string","description":"ISO timestamp it went live (defaults to now)."},"markPublished":{"type":"boolean","description":"Force the post to published even with unstamped platforms."}},"required":["id","platform"]},"bind":{"action":"record_publication"}},{"name":"page_set_status","description":"Page-only: move a post between pipeline columns on the board.","script":"posts-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Post id."},"status":{"type":"string","enum":["idea","draft","in-review","approved","scheduled","published","archived"],"description":"The column the post was moved to."}},"required":["id","status"]},"bind":{"action":"update"},"reaction":{"gezel":"omroeper","prompt":"[Feed board]: The user moved post {{output.id}} to '{{output.status}}' on the board. Reply with ONE short line acknowledging the move. If it landed in 'draft', offer to run the draft-social-post craftbook on it. Do not restate the pipeline.","hideSeed":true}},{"name":"page_get_post","description":"Page-only: the detail drawer's read of one post with variants and media.","script":"posts-store","inputs":{"type":"object","properties":{"id":{"type":"string","description":"Post id."}},"required":["id"]},"bind":{"action":"get"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"posts","subtree":true},{"source":"workspace","path":"voice-guide.md"},{"source":"artifacts","path":"data","subtree":true}],"tools":["page_set_status","page_get_post"]},"schedules":[{"runMode":"night-shift","craftbook":"social-digest","consent":"ask","overlap":"skip"},{"runMode":"scheduled","cron":"0 15 * * 1","craftbook":"reception-report","consent":"ask","overlap":"skip"}],"workspaceSeed":["voice-guide.md","posts/index.json"],"artifactsSeed":[],"notes":"posts/index.json is seeded at its subpath (applyProjectType preserves seed subpaths and creates parents) and is ALSO regenerated by posts-store on every mutation, so the board tolerates a missing or stale index. Posts live one folder per post under posts/ (post.md + variants/ + media/), staged in posts/_drafting/ until create_post commits them. page_set_status and page_get_post are the page-only twins of update_post/get_post — pages.tools names are removed from the model surface, so the model keeps its own read tools.","availableVersions":["1.0.5","1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"software-project","name":"Software Project","description":"A working codebase with a real crew: a lead developer who builds and fixes, a reviewer who checks the work, and a librarian who reads the code while you sleep and files what it finds. Weekly dependency and documentation sweeps keep the quiet rot out.","tags":["code","software","development","engineering","repository"],"category":"code","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26236","version":"1.0.1","releasedAt":"2026-10-25T16:48:51Z","meesterManaged":true,"gezels":[{"templateId":"developer","voorman":true},{"templateId":"reviewer","voorman":false},{"templateId":"boekwachter","voorman":false}],"toolsets":[],"craftbooks":["bug-fix-tdd","refactor-module","test-suite-backfill","code-review","root-cause-investigation","release-readiness-review"],"tools":[],"schedules":[{"runMode":"scheduled","cron":"0 9 * * 1","craftbook":"dependency-audit","consent":"ask","overlap":"skip"},{"runMode":"scheduled","cron":"0 9 * * 3","craftbook":"documentation-drift-review","consent":"ask","overlap":"skip"}],"workspaceSeed":[],"artifactsSeed":[],"availableVersions":["1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"sop-library","name":"SOP Library","description":"Write down how the work gets done, and keep it current. A librarian files every procedure by area with an owner and a last-reviewed date, flags the ones going stale, and answers “how do I…” from your own written steps.","tags":["procedures","sop","operations","how-to","playbook","small-business"],"category":"business","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.0.0","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"business":{"type":"string","title":"What kind of business is this?","description":"e.g. 'a café in Portland', 'a three-person electrical contractor'.","default":"the business"}},"required":["business"]},"nameTemplate":"SOP Library","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"boekwachter","voorman":true},{"templateId":"copywriter","voorman":false}],"toolsets":[],"craftbooks":["handbook-section","doc-rewrite","knowledge-base-article"],"scripts":{"sop-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'sop-store',\n description:\n \"Read and update the SOP library: its index (sops/index.json) and one markdown file per procedure under sops/. action:'status' for what is flagged, past its review date or due soon; 'find' to answer a 'how do I…' question from the written steps; 'save' to write or rewrite a procedure (an existing id or title is updated, never duplicated); 'review' when someone checked one and it is still right; 'flag' when one no longer matches the work; 'retire' when it is no longer used; 'list' for the whole library by area.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'status', 'find', 'save', 'review', 'flag', 'retire', or 'list'.\",\n required: true,\n },\n id: { type: 'string', description: \"Procedure id, e.g. 'sop-3'.\" },\n title: {\n type: 'string',\n description: \"The procedure's name, e.g. 'Closing the espresso machine'. Also finds it when no id is given.\",\n },\n area: { type: 'string', description: 'opening, closing, customers, kitchen, cleaning, safety, money, stock, people, equipment, office, or other.' },\n owner: { type: 'string', description: 'Who keeps it right: usually the person who does the job.' },\n steps: {\n type: 'string',\n description: 'The procedure in markdown: numbered steps, one action each, with any warnings. Replaces the written steps.',\n },\n summary: { type: 'string', description: 'One line on when to use it.' },\n reviewEveryDays: { type: 'number', description: 'How often it should be checked, in days (default 180).' },\n reviewedAt: {\n type: 'string',\n description: 'When it was last checked, YYYY-MM-DD, if not today (for procedures filed from an existing binder).',\n },\n note: { type: 'string', description: 'What changed or who checked it, in the words used.' },\n query: { type: 'string', description: \"For find: the question as asked, e.g. 'how do I close the espresso machine'.\" },\n },\n outputs: {\n outOfDate: { type: 'number', description: 'Procedures flagged for an update or past their review date.' },\n dueSoon: { type: 'number', description: 'Procedures due for review within 30 days.' },\n procedures: { type: 'number', description: 'Procedures in use (not retired).' },\n summary: { type: 'string', description: 'The library picture, the answer to a find, or the listing.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── sop-rules-start ──\n// Pure derivations: when each procedure is next due for review, which ones\n// are out of date, the \"how do I…\" match score, and the lines the crew reads.\n// Kept self-contained between these sentinels so unit tests execute the\n// shipped bytes.\nvar DAY_MS = 86400000;\nvar WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\nvar MONTH_KEYS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];\n\nfunction pad(n) {\n return n < 10 ? '0' + n : String(n);\n}\nfunction localDay(ms) {\n var d = new Date(ms);\n return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());\n}\nfunction noon(day) {\n return new Date(String(day).slice(0, 10) + 'T12:00:00');\n}\nfunction addDays(day, n) {\n var d = noon(day);\n d.setDate(d.getDate() + n);\n return localDay(d.getTime());\n}\nfunction addMonths(day, months) {\n var d = noon(day);\n var date = d.getDate();\n d.setDate(1);\n d.setMonth(d.getMonth() + months);\n // The 31st rolls to the last day of a shorter month, not into the next one.\n d.setDate(Math.min(date, new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate()));\n return localDay(d.getTime());\n}\nfunction daysLeft(day, nowMs) {\n var due = Date.parse(String(day).slice(0, 10) + 'T00:00:00');\n var today = Date.parse(localDay(nowMs) + 'T00:00:00');\n return Math.round((due - today) / DAY_MS);\n}\nfunction dayName(day) {\n return WEEKDAYS[noon(day).getDay()];\n}\nfunction parseDay(text, nowMs, direction) {\n var raw = String(text == null ? '' : text).trim().toLowerCase().replace(/[.,]/g, ' ').replace(/\\s+/g, ' ').trim();\n if (!raw) return null;\n var iso = raw.match(/^(\\d{4})-(\\d{1,2})-(\\d{1,2})(?:t.*)?$/);\n if (iso) return iso[1] + '-' + pad(Number(iso[2])) + '-' + pad(Number(iso[3]));\n var today = localDay(nowMs);\n if (raw === 'today' || raw === 'now') return today;\n if (raw === 'tomorrow') return addDays(today, 1);\n if (raw === 'yesterday') return addDays(today, -1);\n var rel = raw.match(/^(?:in )?(\\d{1,3}) (day|days|week|weeks)( ago| from now)?$/);\n if (rel) {\n var n = Number(rel[1]) * (rel[2].charAt(0) === 'w' ? 7 : 1);\n return addDays(today, rel[3] === ' ago' ? -n : n);\n }\n var wd = raw.match(/^(this |next |last |on |coming )?(sun|mon|tue|wed|thu|fri|sat)[a-z]*$/);\n if (wd) {\n var target = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].indexOf(wd[2]);\n var now = noon(today).getDay();\n if (direction === 'past' || wd[1] === 'last ') {\n var back = (now - target + 7) % 7;\n return addDays(today, -(wd[1] === 'last ' && back === 0 ? 7 : back));\n }\n if (wd[1] === 'this ') return addDays(today, (target - now + 7) % 7);\n return addDays(today, ((target - now + 6) % 7) + 1);\n }\n var md = raw.match(/^(?:[a-z]+day )?([a-z]{3,9}) (\\d{1,2})(?:st|nd|rd|th)?(?: (\\d{4}))?$/);\n var dm = raw.match(/^(?:[a-z]+day )?(\\d{1,2})(?:st|nd|rd|th)? (?:of )?([a-z]{3,9})(?: (\\d{4}))?$/);\n var parts = md ? { month: md[1], date: md[2], year: md[3] } : dm ? { month: dm[2], date: dm[1], year: dm[3] } : null;\n if (parts) {\n var m = MONTH_KEYS.indexOf(parts.month.slice(0, 3));\n if (m < 0) return null;\n var date = Number(parts.date);\n if (date < 1 || date > 31) return null;\n if (parts.year) return parts.year + '-' + pad(m + 1) + '-' + pad(date);\n var year = noon(today).getFullYear();\n var guess = year + '-' + pad(m + 1) + '-' + pad(date);\n var d = daysLeft(guess, nowMs);\n if (direction === 'past' && d > 0) guess = year - 1 + guess.slice(4);\n if (direction !== 'past' && d < 0) guess = year + 1 + guess.slice(4);\n return guess;\n }\n return null;\n}\nfunction matches(records, text, labelOf) {\n var wanted = String(text == null ? '' : text).trim().toLowerCase().replace(/['\\u2019]s\\b/g, '').replace(/\\s+/g, ' ');\n if (!wanted) return [];\n var tiers = [\n function (r) { return String(r.id).toLowerCase() === wanted; },\n function (r) { return labelOf(r).toLowerCase() === wanted; },\n function (r) { return labelOf(r).toLowerCase().indexOf(wanted) === 0; },\n function (r) { return (' ' + labelOf(r).toLowerCase() + ' ').indexOf(' ' + wanted + ' ') >= 0; },\n function (r) { return labelOf(r).toLowerCase().indexOf(wanted) >= 0; },\n function (r) { var l = labelOf(r).toLowerCase(); return l.length >= 3 && wanted.indexOf(l) >= 0; },\n ];\n for (var i = 0; i < tiers.length; i++) {\n var hit = records.filter(tiers[i]);\n if (hit.length) return hit;\n }\n return [];\n}\nfunction describe(records, labelOf) {\n return records.map(function (r) { return r.id + ' ' + labelOf(r); }).join(', ');\n}\nfunction splitList(text) {\n var raw = String(text == null ? '' : text).trim();\n if (/^\\[/.test(raw)) {\n try {\n var parsed = JSON.parse(raw);\n if (Array.isArray(parsed)) return parsed.map(function (s) { return String(s).trim(); }).filter(Boolean);\n } catch (e) {\n // Not JSON after all; split it as text.\n }\n }\n return raw\n .split(/\\s*[,;\\n]+\\s*/)\n .map(function (s) { return s.replace(/^(and|or|plus)\\s+/i, '').replace(/[.\\s]+$/, '').trim(); })\n .filter(Boolean);\n}\nvar AREAS = [\"opening\",\"closing\",\"customers\",\"kitchen\",\"cleaning\",\"safety\",\"money\",\"stock\",\"people\",\"equipment\",\"office\",\"other\"];\nvar DEFAULT_REVIEW_DAYS = 180;\nvar SOON_DAYS = 30;\nvar STOP = ['how', 'do', 'does', 'did', 'done', 'we', 'you', 'they', 'an', 'the', 'to', 'of', 'in', 'on', 'at', 'for', 'with', 'and', 'or', 'is', 'are', 'was', 'what', 'when', 'where', 'who', 'which', 'should', 'can', 'could', 'our', 'my', 'your', 'it', 'its', 'this', 'that', 'there', 'about', 'get', 'me', 'us', 'be', 'have', 'has', 'if', 'then', 'up', 'out', 'into', 'again', 'any', 'some', 'need', 'procedure', 'procedures', 'sop', 'steps', 'step', 'way', 'right', 'properly', 'please', 'tell', 'show'];\n\n// \"closing\", \"closed\" and \"close\" all become \"clos\"; \"machines\" and \"machine\" become \"machin\".\nfunction stem(word) {\n var w = word;\n if (w.length > 5 && /ing$/.test(w)) w = w.slice(0, -3);\n else if (w.length > 4 && /ed$/.test(w)) w = w.slice(0, -2);\n else if (w.length > 4 && /es$/.test(w)) w = w.slice(0, -2);\n else if (w.length > 3 && /s$/.test(w) && !/ss$/.test(w)) w = w.slice(0, -1);\n if (w.length > 4 && /e$/.test(w)) w = w.slice(0, -1);\n return w;\n}\nfunction tokens(text) {\n var seen = [];\n String(text == null ? '' : text).toLowerCase().split(/[^a-z0-9]+/).forEach(function (w) {\n if (w.length < 2 || STOP.indexOf(w) >= 0) return;\n var s = stem(w);\n if (seen.indexOf(s) < 0) seen.push(s);\n });\n return seen;\n}\n// Title words count three times, area and summary twice, the steps once.\nfunction score(record, body, query) {\n var q = tokens(query);\n if (!q.length) return 0;\n var f = record.fields || {};\n var title = tokens(f.title), meta = tokens((f.area || '') + ' ' + (f.summary || '')), text = tokens(body);\n var total = 0, hit = 0;\n q.forEach(function (w) {\n var s = title.indexOf(w) >= 0 ? 3 : meta.indexOf(w) >= 0 ? 2 : text.indexOf(w) >= 0 ? 1 : 0;\n if (s) hit += 1;\n total += s;\n });\n return hit ? total + hit / q.length : 0;\n}\nfunction reviewDays(f) {\n var n = Number(f.reviewEveryDays);\n return n > 0 ? Math.round(n) : DEFAULT_REVIEW_DAYS;\n}\nfunction nextReview(f) {\n return f.lastReviewedAt ? addDays(String(f.lastReviewedAt).slice(0, 10), reviewDays(f)) : null;\n}\n// retired, flagged (needs-update), draft, unreviewed, stale (past its review date), soon, ok.\nfunction reviewState(record, nowMs) {\n if (record.status === 'retired') return 'retired';\n if (record.status === 'needs-update') return 'flagged';\n if (record.status === 'draft') return 'draft';\n var f = record.fields || {};\n if (!f.lastReviewedAt) return 'unreviewed';\n var d = daysLeft(nextReview(f), nowMs);\n return d < 0 ? 'stale' : d <= SOON_DAYS ? 'soon' : 'ok';\n}\nfunction flagNote(record) {\n var history = record.history || [];\n for (var i = history.length - 1; i >= 0; i--) {\n if (history[i].to === 'needs-update' && history[i].note) return history[i].note;\n }\n return '';\n}\nfunction ago(days) {\n return days === 0 ? 'today' : days === 1 ? 'yesterday' : days + ' days ago';\n}\nfunction line(record, nowMs) {\n var f = record.fields || {};\n var state = reviewState(record, nowMs);\n var next = nextReview(f);\n var reviewed = f.lastReviewedAt ? 'last reviewed ' + f.lastReviewedAt + ' (' + ago(-daysLeft(f.lastReviewedAt, nowMs)) + ')' : 'never reviewed';\n var what =\n state === 'flagged' ? 'flagged for an update' + (flagNote(record) ? ': \"' + flagNote(record) + '\"' : '') + '; ' + reviewed\n : state === 'draft' ? 'draft, no steps written yet'\n : state === 'retired' ? 'retired'\n : state === 'unreviewed' ? 'never reviewed'\n : state === 'stale' ? reviewed + '; review overdue by ' + -daysLeft(next, nowMs) + ' days (every ' + reviewDays(f) + ' days)'\n : state === 'soon' ? reviewed + '; review due in ' + daysLeft(next, nowMs) + ' days'\n : reviewed + '; next review ' + next;\n return f.title + ' (' + record.id + ', ' + (f.area || 'other') + ', owner ' + (f.owner || 'none yet') + '): ' + what;\n}\n// Known-wrong first, then the most overdue, then reviews coming due.\nfunction urgency(record, nowMs) {\n var state = reviewState(record, nowMs);\n if (state === 'flagged') return -1000000;\n if (state === 'unreviewed') return -500000;\n var next = nextReview(record.fields || {});\n return next ? daysLeft(next, nowMs) : 0;\n}\nfunction picture(records, nowMs) {\n var live = records.filter(function (r) { return r.status !== 'retired'; });\n var states = live.map(function (r) { return reviewState(r, nowMs); });\n var pick = function (names) { return live.filter(function (r, i) { return names.indexOf(states[i]) >= 0; }); };\n var outOfDate = pick(['flagged', 'unreviewed', 'stale']);\n var soon = pick(['soon']);\n var drafts = pick(['draft']);\n var areas = [];\n live.forEach(function (r) { var a = (r.fields && r.fields.area) || 'other'; if (areas.indexOf(a) < 0) areas.push(a); });\n areas.sort(function (a, b) { return AREAS.indexOf(a) - AREAS.indexOf(b); });\n var parts = [\n live.length + (live.length === 1 ? ' procedure' : ' procedures') + ' in ' + areas.length + (areas.length === 1 ? ' area' : ' areas') + '; ' +\n outOfDate.length + ' out of date, ' + soon.length + ' due for review within ' + SOON_DAYS + ' days.',\n ];\n // One list, most urgent first: a model asked what is out of date reads one list, not side lists.\n var attention = outOfDate.concat(soon).sort(function (a, b) { return urgency(a, nowMs) - urgency(b, nowMs); });\n parts.push(\n attention.length\n ? 'Out of date or due for review, most urgent first: ' + attention.map(function (r) { return line(r, nowMs); }).join(' | ') + '.'\n : live.length ? 'Every procedure is current.' : 'The library is empty.',\n );\n if (drafts.length) parts.push('Drafts with no steps yet: ' + drafts.map(function (r) { return r.fields.title + ' (' + r.id + ')'; }).join(', ') + '.');\n if (areas.length) {\n parts.push(\n 'By area: ' + areas.map(function (a) {\n return a + ': ' + live.filter(function (r) { return ((r.fields && r.fields.area) || 'other') === a; }).map(function (r) { return r.fields.title + ' (' + r.id + ')'; }).join(', ');\n }).join('; ') + '.',\n );\n // The steps live in the files: a model answering from this summary alone would invent them.\n parts.push(\"Steps are not in this summary; for a 'how do I…' question, call find_procedure with the question and answer from its steps.\");\n }\n return { outOfDate: outOfDate.length, dueSoon: soon.length, procedures: live.length, summary: parts.join(' ') };\n}\nfunction procedureLabel(r) {\n return String((r.fields && r.fields.title) || '');\n}\n// By id or title first, then every telling word of the request.\nfunction findProcedures(records, text) {\n var hit = matches(records, text, procedureLabel);\n if (hit.length) return hit;\n var want = tokens(text);\n if (!want.length) return [];\n return records.filter(function (r) {\n var have = tokens(procedureLabel(r));\n return want.every(function (w) { return have.indexOf(w) >= 0; });\n });\n}\nfunction slugOf(title) {\n var slug = String(title).toLowerCase().normalize('NFD').replace(/[\\u0300-\\u036f]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60).replace(/-+$/, '');\n return slug || 'procedure';\n}\n// The title is the file's one heading; a pasted copy of it is dropped.\nfunction bodyOf(title, steps) {\n var text = String(steps).replace(/\\r\\n/g, '\\n').trim().replace(/^#\\s+[^\\n]*\\n+/, '');\n return '# ' + title + '\\n\\n' + text + '\\n';\n}\n// ── sop-rules-end ──\n\nconst library = rosterStore(gezel.fs, 'sops/index.json', {\n stages: ['draft', 'current', 'needs-update', 'retired'],\n idPrefix: 'sop',\n});\ntype Procedure = Awaited<ReturnType<typeof library.list>>[number];\n\nconst now = Date.now();\nconst today = localDay(now);\nlet note = '';\nlet answer = '';\n\nfunction clip(text: string, max: number): string {\n return text.length > max ? text.slice(0, max - 1) + '…' : text;\n}\nfunction known(all: Procedure[]): string {\n return describe(all, procedureLabel) || 'none yet';\n}\nasync function readBody(file: unknown): Promise<string> {\n if (typeof file !== 'string' || !file) return '';\n try {\n return await gezel.fs.read(file);\n } catch {\n return '';\n }\n}\n\nasync function resolveProcedure(): Promise<Procedure> {\n const all = await library.list();\n const text = input.id || input.title;\n if (!text) throw new Error(\"Pass 'id' (e.g. 'sop-3') or the procedure's 'title'. Procedures: \" + known(all) + '.');\n const hits = findProcedures(all, text);\n if (hits.length === 1) return hits[0]!;\n if (hits.length > 1) throw new Error(\"More than one procedure matches '\" + text + \"': \" + describe(hits, procedureLabel) + '. Pass id.');\n throw new Error(\"No procedure matches '\" + text + \"'. Procedures: \" + known(all) + '.');\n}\n\nif (input.action === 'save') {\n const all = await library.list();\n const wanted = String(input.title ?? '').trim().toLowerCase();\n let existing = input.id\n ? all.find((r) => r.id === input.id)\n : all.find((r) => String(r.fields.title ?? '').toLowerCase() === wanted);\n if (input.id && !existing) throw new Error('No procedure ' + input.id + '. Procedures: ' + known(all) + '.');\n if (!existing && !wanted) throw new Error(\"save needs 'title'.\");\n const steps = typeof input.steps === 'string' && input.steps.trim() ? input.steps : '';\n // A reworded title (\"Espresso machine closing\") is the same procedure.\n if (!existing) {\n const words = tokens(input.title).sort().join(' ');\n const same = all.filter((r) => words && tokens(r.fields.title).sort().join(' ') === words);\n if (same.length === 1) existing = same[0];\n }\n // A loose title names an existing procedure when the call only changes its details. New steps\n // never overwrite a loosely matched one: the caller names it by id or gives the new one its own title.\n if (!existing) {\n const loose = findProcedures(all, input.title).filter((r) => r.status !== 'retired');\n if (loose.length > 1) {\n throw new Error(\"More than one procedure matches '\" + input.title + \"': \" + describe(loose, procedureLabel) + '. Pass id to change one, or give a new procedure its own full title.');\n }\n if (loose.length === 1 && !steps) existing = loose[0];\n else if (loose.length === 1) {\n throw new Error(\"'\" + input.title + \"' looks like \" + String(loose[0]!.fields.title) + ' (' + loose[0]!.id + \"). To rewrite it, pass id '\" + loose[0]!.id + \"'; to add a separate procedure, give it its own full title.\");\n }\n }\n const area = AREAS.indexOf(String(input.area ?? '').toLowerCase()) >= 0 ? String(input.area).toLowerCase() : undefined;\n let reviewedAt: string | null = null;\n if (input.reviewedAt) {\n reviewedAt = parseDay(input.reviewedAt, now, 'past');\n if (!reviewedAt) throw new Error(\"reviewedAt must be a date, e.g. '2026-03-14'.\");\n if (daysLeft(reviewedAt, now) > 0) reviewedAt = today;\n }\n const fields: Record<string, unknown> = {\n ...(area ? { area } : {}),\n ...(input.owner ? { owner: input.owner.trim() } : {}),\n ...(input.summary ? { summary: input.summary.trim() } : {}),\n ...(typeof input.reviewEveryDays === 'number' && input.reviewEveryDays > 0 ? { reviewEveryDays: Math.round(input.reviewEveryDays) } : {}),\n };\n if (existing) {\n const title = input.id && input.title && input.title.trim() ? input.title.trim() : String(existing.fields.title);\n if (title !== existing.fields.title) fields.title = title;\n if (steps) {\n await gezel.fs.write(String(existing.fields.file), bodyOf(title, steps));\n fields.lastReviewedAt = reviewedAt ?? today;\n } else if (reviewedAt) {\n fields.lastReviewedAt = reviewedAt;\n }\n await library.update(existing.id, { fields, ...(steps ? { note: input.note ?? 'Steps rewritten.' } : input.note ? { note: input.note } : {}) });\n if (steps && existing.status !== 'current') await library.transition(existing.id, 'current', { note: 'Steps rewritten.' });\n note = 'Updated ' + title + (steps ? ' with new steps' : '') + '.';\n } else {\n const title = String(input.title).trim();\n const taken = all.map((r) => String(r.fields.file ?? ''));\n const slug = slugOf(title);\n let file = 'sops/' + slug + '.md';\n for (let n = 2; taken.indexOf(file) >= 0; n++) file = 'sops/' + slug + '-' + n + '.md';\n await gezel.fs.write(file, bodyOf(title, steps || '_No steps yet. Ask the person who does this job to walk through it once, and write down each action in order._'));\n const record = await library.add({\n status: steps ? 'current' : 'draft',\n fields: { title, area: area ?? 'other', file, ...fields, ...(steps ? { lastReviewedAt: reviewedAt ?? today } : {}) },\n });\n note = 'Added ' + record.id + ' ' + title + ' at ' + file + (steps ? '' : ' as a draft') + '.';\n }\n} else if (input.action === 'find') {\n const query = String(input.query ?? input.title ?? '').trim();\n if (!query) throw new Error(\"find needs 'query': the question as asked.\");\n const live = (await library.list()).filter((r) => r.status !== 'retired');\n const scored: Array<{ r: Procedure; body: string; s: number }> = [];\n for (const r of live) {\n const body = await readBody(r.fields.file);\n const s = score(r, body, query);\n if (s > 0) scored.push({ r, body, s });\n }\n scored.sort((a, b) => b.s - a.s);\n const best = scored[0];\n if (!best) {\n answer = \"No procedure in the library matches '\" + query + \"'. Say so plainly, and offer to write one down with the person who does that job.\";\n } else {\n const state = reviewState(best.r, now);\n answer =\n \"Best match for '\" + query + \"': \" + line(best.r, now) + '. File ' + String(best.r.fields.file) + '.\\n\\n' +\n clip(best.body.trim() || '(The file is empty.)', 4000) +\n (state === 'stale' || state === 'flagged' || state === 'unreviewed' ? '\\n\\nThis procedure is out of date; say so when you answer, and suggest the owner checks it.' : '') +\n (state === 'draft' ? '\\n\\nThis is a draft with no steps yet; say so rather than inventing steps.' : '') +\n (scored.length > 1 ? '\\n\\nAlso related: ' + scored.slice(1, 4).map((x) => String(x.r.fields.title) + ' (' + x.r.id + ')').join(', ') + '.' : '');\n }\n} else if (input.action === 'review') {\n const r = await resolveProcedure();\n if (r.status === 'retired') throw new Error(String(r.fields.title) + ' is retired; save it again with steps to bring it back.');\n if (r.status === 'draft') throw new Error(String(r.fields.title) + ' is a draft with no steps yet; save its steps first.');\n await library.update(r.id, { fields: { lastReviewedAt: today }, note: input.note ?? 'Reviewed; still right.' });\n if (r.status === 'needs-update') await library.transition(r.id, 'current', { note: 'Reviewed; still right.' });\n note = String(r.fields.title) + ' marked reviewed today; next review ' + addDays(today, reviewDays(r.fields)) + '.';\n} else if (input.action === 'flag') {\n if (!input.note || !input.note.trim()) throw new Error(\"flag needs 'note': what changed or what is wrong, in the person's words.\");\n const r = await resolveProcedure();\n await library.transition(r.id, 'needs-update', { note: input.note.trim() });\n note = String(r.fields.title) + ' flagged for an update: ' + input.note.trim().replace(/[.\\s]+$/, '') + '.';\n} else if (input.action === 'retire') {\n const r = await resolveProcedure();\n await library.transition(r.id, 'retired', { note: input.note ?? 'Retired.' });\n note = String(r.fields.title) + ' retired; its file stays at ' + String(r.fields.file) + '.';\n} else if (input.action !== 'status' && input.action !== 'list') {\n throw new Error(\"Unknown action '\" + input.action + \"'. Use status, find, save, review, flag, retire, or list.\");\n}\n\nconst records = await library.list();\nconst shelf = picture(records, now);\nconst listing = () =>\n records\n .slice()\n .sort((a, b) => AREAS.indexOf(String(a.fields.area)) - AREAS.indexOf(String(b.fields.area)) || String(a.fields.title).localeCompare(String(b.fields.title)))\n .map((r) => '[' + r.status + '] ' + line(r, now) + '; file ' + String(r.fields.file))\n .join('\\n') || 'The library is empty.';\n\ngezel.output({\n outOfDate: shelf.outOfDate,\n dueSoon: shelf.dueSoon,\n procedures: shelf.procedures,\n summary: input.action === 'list' ? listing() : input.action === 'find' ? answer : (note ? note + ' ' : '') + shelf.summary,\n});\n"},"tools":[{"name":"library_status","description":"What in the library is out of date (flagged for an update or past its review date, most urgent first) and what is due for review within 30 days, each with owner and last-reviewed date, plus every procedure by area. Call it first when asked what needs reviewing or which procedures exist.","script":"sop-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"},"state":true},{"name":"find_procedure","description":"Answer a 'how do I…' question from the library: returns the best-matching procedure's steps exactly as written, with its owner and last-reviewed date. Call it before answering any how-to question, and answer from those steps, never from general knowledge.","script":"sop-store","inputs":{"type":"object","properties":{"query":{"type":"string"}},"required":["query"]},"bind":{"action":"find"}},{"name":"save_procedure","description":"Write a procedure into the library: title, area, owner and the steps in markdown (numbered, one action each). An existing id or title is rewritten, never duplicated, and saving new steps counts as a review. Call it as soon as the person describes how a job is done, before you describe it.","script":"sop-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"area":{"type":"string","enum":["opening","closing","customers","kitchen","cleaning","safety","money","stock","people","equipment","office","other"]},"owner":{"type":"string"},"steps":{"type":"string"},"summary":{"type":"string"},"reviewEveryDays":{"type":"number"},"reviewedAt":{"type":"string"},"note":{"type":"string"}},"required":["title"]},"bind":{"action":"save"}},{"name":"mark_reviewed","description":"Record that someone checked a procedure and it is still right; it restarts the review clock. Call it the moment the person says it's been checked.","script":"sop-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"note":{"type":"string"}}},"bind":{"action":"review"}},{"name":"flag_procedure","description":"Flag a procedure that no longer matches how the work is done, with what changed in the words the person used. Call it the moment a change is mentioned, then offer to rewrite the steps.","script":"sop-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"note":{"type":"string"}},"required":["note"]},"bind":{"action":"flag"}},{"name":"retire_procedure","description":"Retire a procedure the business no longer uses. Its file stays in sops/, but it leaves the library and its answers.","script":"sop-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"note":{"type":"string"}}},"bind":{"action":"retire"}},{"name":"list_procedures","description":"Every procedure by area with owner, status, file path and review dates.","script":"sop-store","inputs":{"type":"object","properties":{}},"bind":{"action":"list"}},{"name":"page_save_procedure","description":"Write or rewrite a procedure.","script":"sop-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"area":{"type":"string","enum":["opening","closing","customers","kitchen","cleaning","safety","money","stock","people","equipment","office","other"]},"owner":{"type":"string"},"steps":{"type":"string"},"summary":{"type":"string"},"reviewEveryDays":{"type":"number"},"reviewedAt":{"type":"string"},"note":{"type":"string"}},"required":["title"]},"bind":{"action":"save"}},{"name":"page_mark_reviewed","description":"Record that a procedure was checked and is still right.","script":"sop-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"note":{"type":"string"}}},"bind":{"action":"review"},"reaction":{"gezel":"boekwachter","prompt":"The person just marked a procedure reviewed on the library page. The library now reads (its first sentence is what changed):\n{{output.summary}}\nIn two short sentences, confirm the next review date and name the next procedure that is out of date or due. Do not call tools.","hideSeed":true}},{"name":"page_flag_procedure","description":"Flag a procedure for an update.","script":"sop-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"note":{"type":"string"}},"required":["note"]},"bind":{"action":"flag"},"reaction":{"gezel":"boekwachter","prompt":"The person just flagged a procedure for an update on the library page. The library now reads (its first sentence is what changed):\n{{output.summary}}\nIn two short sentences, confirm what was flagged and offer to redraft its steps with the person who does the job. Do not call tools.","hideSeed":true}}],"pages":{"entry":"library/index.html","api":1,"reads":[{"source":"workspace","path":"sops","subtree":true}],"tools":["page_save_procedure","page_mark_reviewed","page_flag_procedure"]},"schedules":[],"workspaceSeed":["sops/index.json"],"artifactsSeed":[],"availableVersions":["1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"support-desk","name":"Support Desk","description":"Answer customer questions and keep every request moving. A support lead logs each question as a ticket, drafts replies from your own help articles, and notices the questions those articles do not answer yet.","tags":["support","customer-service","help-desk","knowledge-base","faq","small-business"],"category":"business","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.0.0","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"business":{"type":"string","title":"What kind of business is this?","description":"e.g. 'a small publisher', 'a café in Portland'.","default":"the business"},"voice":{"type":"string","title":"How should replies sound?","description":"e.g. 'warm and plain', 'brief and formal'.","default":"warm and plain"}},"required":["business"]},"nameTemplate":"Support Desk","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"support-lead","voorman":true},{"templateId":"boekwachter","voorman":false}],"toolsets":[],"craftbooks":["inbox-triage","faq-from-docs","knowledge-base-article"],"scripts":{"support-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'support-store',\n description:\n \"Read and update the support desk: its tickets (tickets.json) and the help articles in kb/. action:'status' for what needs a reply, what waits on the customer and the questions no help article answers; 'add' to log a ticket (the same subject from the same customer updates the open ticket, never duplicates it); 'reply' to save a suggested reply and the article or gap behind it; 'set_status' to move a ticket; 'save_article' to write a help article in kb/ and close the gap it answers; 'list' for every ticket.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'status', 'add', 'reply', 'set_status', 'save_article', or 'list'.\",\n required: true,\n },\n id: { type: 'string', description: \"Ticket id, e.g. 'tk-3'.\" },\n subject: {\n type: 'string',\n description: \"The ticket's subject, e.g. 'Book arrived with a torn cover'. Also finds it when no id is given.\",\n },\n customer: { type: 'string', description: 'Who wrote in.' },\n channel: { type: 'string', description: 'email, phone, chat, social, in-person, or other.' },\n category: {\n type: 'string',\n description: 'order, delivery, billing, product, account, business, complaint, or other.',\n },\n priority: { type: 'string', description: 'normal, urgent, or low.' },\n message: { type: 'string', description: 'What the customer asked, in their words.' },\n receivedAt: { type: 'string', description: 'The day it came in, YYYY-MM-DD (default today).' },\n reply: { type: 'string', description: 'The suggested reply, ready for the person to send.' },\n article: { type: 'string', description: \"The help article the reply draws on, e.g. 'kb/refunds.md'.\" },\n gap: {\n type: 'string',\n description: \"A short topic for a question no help article answers yet, e.g. 'wholesale terms'.\",\n },\n status: { type: 'string', description: 'For set_status: new, open, waiting, or resolved.' },\n note: { type: 'string', description: 'What happened.' },\n title: { type: 'string', description: \"For save_article: the article's title.\" },\n body: { type: 'string', description: 'For save_article: the article in markdown.' },\n topic: { type: 'string', description: 'For save_article: the gap it answers, as the status names it.' },\n },\n outputs: {\n needsReply: { type: 'number', description: 'Tickets that are new or open.' },\n waiting: { type: 'number', description: 'Tickets waiting on the customer.' },\n gaps: { type: 'number', description: 'Questions no help article answers yet.' },\n summary: { type: 'string', description: 'The desk picture, or the listing.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── support-rules-start ──\n// Pure derivations: a ticket's age in local calendar days, the reply queue\n// (urgent first, then oldest), the knowledge-base gaps grouped by topic, and\n// the desk picture the crew reads. Kept self-contained between these\n// sentinels so unit tests execute the shipped bytes.\nvar DAY_MS = 86400000;\nvar STAGES = ['new', 'open', 'waiting', 'resolved'];\nvar CATEGORIES = ['order', 'delivery', 'billing', 'product', 'account', 'business', 'complaint', 'other'];\nvar CHANNELS = ['email', 'phone', 'chat', 'social', 'in-person', 'other'];\nvar PRIORITIES = ['normal', 'urgent', 'low'];\nvar CATEGORY_ALIASES = {\n orders: 'order', shipping: 'delivery', shipment: 'delivery', damaged: 'delivery', refund: 'billing', refunds: 'billing',\n payment: 'billing', invoice: 'billing', charge: 'billing', question: 'product', products: 'product', login: 'account',\n download: 'account', subscription: 'account', wholesale: 'business', partnership: 'business', press: 'business',\n booking: 'business', feedback: 'complaint', complaints: 'complaint',\n};\n\nfunction pad(n) {\n return n < 10 ? '0' + n : String(n);\n}\nfunction localDay(ms) {\n var d = new Date(ms);\n return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());\n}\nfunction normalizeDate(text) {\n var raw = String(text || '').trim();\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(raw)) return raw;\n var parsed = Date.parse(raw);\n return isFinite(parsed) ? localDay(parsed) : null;\n}\nfunction ageDays(day, nowMs) {\n var start = Date.parse(String(day || '').slice(0, 10) + 'T00:00:00');\n if (!isFinite(start)) return 0;\n var today = Date.parse(localDay(nowMs) + 'T00:00:00');\n return Math.max(0, Math.round((today - start) / DAY_MS));\n}\nfunction age(days) {\n return days === 0 ? 'came in today' : days === 1 ? '1 day old' : days + ' days old';\n}\nfunction categoryOf(text) {\n var key = String(text || '').trim().toLowerCase();\n if (CATEGORIES.indexOf(key) >= 0) return key;\n return CATEGORY_ALIASES[key] || null;\n}\nfunction topicKey(text) {\n return String(text || '').trim().toLowerCase().replace(/\\s+/g, ' ');\n}\nfunction sameTopic(a, b) {\n var x = topicKey(a), y = topicKey(b);\n return !!x && !!y && (x === y || x.indexOf(y) >= 0 || y.indexOf(x) >= 0);\n}\nfunction slug(text) {\n var s = String(text || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60).replace(/-+$/, '');\n return s || 'article';\n}\nfunction articlePath(text) {\n var p = String(text || '').trim().replace(/\\\\/g, '/').replace(/^\\.?\\/+/, '');\n if (!p || p.split('/').indexOf('..') >= 0) return null;\n return p.indexOf('kb/') === 0 ? p : 'kb/' + p;\n}\nfunction urgency(record) {\n var p = record.fields && record.fields.priority;\n return p === 'urgent' ? 0 : p === 'low' ? 2 : 1;\n}\nfunction oldestFirst(a, b) {\n return String(a.fields.receivedAt || '').localeCompare(String(b.fields.receivedAt || '')) || String(a.id).localeCompare(String(b.id), undefined, { numeric: true });\n}\nfunction replyQueue(records) {\n return records\n .filter(function (r) { return r.status === 'new' || r.status === 'open'; })\n .slice()\n .sort(function (a, b) { return urgency(a) - urgency(b) || oldestFirst(a, b); });\n}\nfunction waitingList(records) {\n return records.filter(function (r) { return r.status === 'waiting'; }).slice().sort(oldestFirst);\n}\n// A gap is a question no help article answers yet: a ticket with a kbGap\n// topic and no kbArticle. Tickets are grouped by topic, the most asked first.\nfunction openGaps(records) {\n var groups = [];\n records.forEach(function (r) {\n var f = r.fields || {};\n if (!f.kbGap || f.kbArticle) return;\n var group = groups.find(function (g) { return topicKey(g.topic) === topicKey(f.kbGap); });\n if (!group) {\n group = { topic: String(f.kbGap).trim(), tickets: [] };\n groups.push(group);\n }\n group.tickets.push(r);\n });\n return groups.sort(function (a, b) { return b.tickets.length - a.tickets.length || a.topic.localeCompare(b.topic); });\n}\nfunction excerpt(text, length) {\n var t = String(text || '').replace(/\\s+/g, ' ').trim();\n return t.length > length ? t.slice(0, length - 1).trim() + '…' : t;\n}\n// The gap topic already on the desk that a new mention means, so one question keeps one name.\nfunction knownTopic(records, text) {\n var hit = openGaps(records).find(function (g) { return sameTopic(g.topic, text); });\n return hit ? hit.topic : String(text || '').trim();\n}\nfunction line(record, nowMs, withMessage) {\n var f = record.fields || {};\n var active = record.status === 'new' || record.status === 'open';\n return (\n f.subject +\n ' (' + record.id + ', ' + (f.category || 'other') + (f.customer ? ', from ' + f.customer : '') + ', ' + age(ageDays(f.receivedAt, nowMs)) + ')' +\n (f.priority === 'urgent' ? ', urgent' : '') +\n (active ? ', ' + record.status : '') +\n (f.suggestedReply ? ', reply drafted' : active ? ', no reply drafted yet' : '') +\n (f.kbArticle ? ', help article ' + f.kbArticle : f.kbGap ? ', no help article for \"' + f.kbGap + '\"' : '') +\n (withMessage && f.message ? ': \"' + excerpt(f.message, 140) + '\"' : '')\n );\n}\nfunction picture(records, articles, nowMs) {\n var counts = {};\n STAGES.forEach(function (s) { counts[s] = 0; });\n records.forEach(function (r) { counts[r.status] = (counts[r.status] || 0) + 1; });\n var queue = replyQueue(records);\n var waiting = waitingList(records);\n var gaps = openGaps(records);\n var parts = [\n records.length + (records.length === 1 ? ' ticket' : ' tickets') + ' on the desk: ' + counts.new + ' new, ' + counts.open + ' open, ' +\n counts.waiting + ' waiting on the customer, ' + counts.resolved + ' resolved.',\n ];\n parts.push(\n queue.length\n ? 'Needs a reply, urgent first, then oldest: ' + queue.map(function (r) { return line(r, nowMs, true); }).join(' | ') + '.'\n : 'Nothing needs a reply.',\n );\n if (waiting.length) parts.push('Waiting on the customer: ' + waiting.map(function (r) { return line(r, nowMs, false); }).join(' | ') + '.');\n parts.push(\n gaps.length\n ? 'Questions no help article answers yet, most asked first: ' +\n gaps.map(function (g) {\n return '\"' + g.topic + '\" (' + g.tickets.length + (g.tickets.length === 1 ? ' ticket: ' : ' tickets: ') + g.tickets.map(function (r) { return r.id; }).join(', ') + ')';\n }).join(' | ') + '.'\n : 'No knowledge-base gaps recorded.',\n );\n parts.push(articles.length ? 'Help articles in kb/: ' + articles.join(', ') + '.' : 'No help articles in kb/ yet.');\n return { needsReply: queue.length, waiting: waiting.length, gaps: gaps.length, summary: parts.join(' ') };\n}\n// ── support-rules-end ──\n\nconst tickets = rosterStore(gezel.fs, 'tickets.json', {\n stages: ['new', 'open', 'waiting', 'resolved'],\n idPrefix: 'tk',\n});\n\nasync function articles(): Promise<string[]> {\n try {\n return (await gezel.fs.list('kb'))\n .filter((e) => !e.isDirectory)\n .map((e) => 'kb/' + e.name)\n .sort();\n } catch {\n return [];\n }\n}\n\n// By id, or by (partial) subject; a missing id is tried as a subject too.\nasync function resolve(): Promise<string> {\n const all = await tickets.list();\n if (input.id) {\n const byId = all.find((r) => r.id === input.id!.trim().toLowerCase());\n if (byId) return byId.id;\n }\n const text = input.subject ?? input.id;\n if (text) {\n const wanted = text.trim().toLowerCase();\n const exact = all.filter((r) => String(r.fields.subject ?? '').toLowerCase() === wanted);\n if (exact.length === 1) return exact[0]!.id;\n let partial = all.filter((r) => String(r.fields.subject ?? '').toLowerCase().includes(wanted));\n if (partial.length > 1) {\n const active = partial.filter((r) => r.status !== 'resolved');\n if (active.length === 1) return active[0]!.id;\n partial = active.length ? active : partial;\n throw new Error(\"More than one ticket matches '\" + text + \"': \" + partial.map((r) => r.id + ' ' + String(r.fields.subject)).join(', ') + '. Pass id.');\n }\n if (partial.length === 1) return partial[0]!.id;\n }\n throw new Error(\n \"Pass 'id' (e.g. 'tk-3') or the ticket's 'subject'. Tickets: \" +\n (all.map((r) => r.id + ' ' + String(r.fields.subject)).join(', ') || 'none yet') + '.',\n );\n}\n\nconst LABELS: Record<string, string> = {\n new: 'back to new',\n open: 'open',\n waiting: 'waiting on the customer',\n resolved: 'resolved',\n};\nlet note = '';\n\nif (input.action === 'add') {\n const subject = (input.subject ?? '').trim();\n if (!subject) throw new Error(\"add needs 'subject'.\");\n const receivedAt = input.receivedAt ? normalizeDate(input.receivedAt) : null;\n if (input.receivedAt && !receivedAt) throw new Error(\"receivedAt must be a date, e.g. '2026-11-02'.\");\n const category = categoryOf(input.category);\n const channel = CHANNELS.includes(String(input.channel)) ? String(input.channel) : undefined;\n const priority = PRIORITIES.includes(String(input.priority)) ? String(input.priority) : undefined;\n const who = (input.customer ?? '').trim().toLowerCase();\n const all = await tickets.list();\n const existing = all.find(\n (r) =>\n r.status !== 'resolved' &&\n String(r.fields.subject ?? '').toLowerCase() === subject.toLowerCase() &&\n (!who || !r.fields.customer || String(r.fields.customer).toLowerCase() === who),\n );\n const fields: Record<string, unknown> = {\n ...(input.customer && !existing?.fields.customer ? { customer: input.customer.trim() } : {}),\n ...(channel ? { channel } : {}),\n ...(category ? { category } : {}),\n ...(priority ? { priority } : {}),\n ...(input.message ? { message: input.message.trim() } : {}),\n ...(receivedAt ? { receivedAt } : {}),\n ...(input.gap?.trim() ? { kbGap: knownTopic(all, input.gap) } : {}),\n };\n if (existing) {\n await tickets.update(existing.id, { fields });\n note = 'Updated ' + existing.id + ' (' + String(existing.fields.subject) + ').';\n } else {\n const record = await tickets.add({\n status: 'new',\n fields: {\n subject,\n category: 'other',\n channel: 'other',\n priority: 'normal',\n receivedAt: localDay(Date.now()),\n ...fields,\n },\n });\n note = 'Logged ' + record.id + ': ' + subject + '.';\n }\n} else if (input.action === 'reply') {\n if (!input.reply?.trim() && !input.gap?.trim() && !input.article?.trim()) {\n throw new Error(\"reply needs 'reply' (the suggested reply), 'article' or 'gap'.\");\n }\n const article = input.article ? articlePath(input.article) : null;\n if (input.article && !article) throw new Error(\"article must be a path inside kb/, e.g. 'kb/refunds.md'.\");\n const id = await resolve();\n const record = (await tickets.get(id))!;\n const gap = input.gap?.trim() ? knownTopic(await tickets.list(), input.gap) : '';\n await tickets.update(id, {\n fields: {\n ...(input.reply?.trim() ? { suggestedReply: input.reply.trim() } : {}),\n ...(article ? { kbArticle: article } : {}),\n ...(gap ? { kbGap: gap } : {}),\n },\n });\n if (record.status === 'new' && input.reply?.trim()) await tickets.transition(id, 'open', { note: 'Reply drafted' });\n note =\n (input.reply?.trim() ? 'Saved a suggested reply on ' : 'Updated ') + String(record.fields.subject) + ' (' + id + ')' +\n (article ? ', drawn from ' + article : '') +\n (gap && !article ? '; noted the gap \"' + gap + '\"' : '') + '.';\n} else if (input.action === 'set_status') {\n const status = String(input.status ?? '').trim().toLowerCase();\n if (!STAGES.includes(status)) throw new Error(\"set_status needs status 'new', 'open', 'waiting' or 'resolved'.\");\n const id = await resolve();\n const record = (await tickets.get(id))!;\n await tickets.transition(id, status, input.note ? { note: input.note } : {});\n if (status === 'resolved') await tickets.update(id, { fields: { resolvedAt: localDay(Date.now()) } });\n note = String(record.fields.subject) + ' (' + id + ') is ' + LABELS[status] + '.';\n} else if (input.action === 'save_article') {\n const title = (input.title ?? '').trim();\n const body = (input.body ?? '').trim();\n if (!title || !body) throw new Error(\"save_article needs 'title' and 'body' (markdown).\");\n const path = 'kb/' + slug(title) + '.md';\n await gezel.fs.write(path, (/^#\\s/.test(body) ? body : '# ' + title + '\\n\\n' + body) + '\\n');\n let closed = 0;\n if (input.topic?.trim()) {\n for (const r of await tickets.list()) {\n if (r.fields.kbGap && !r.fields.kbArticle && sameTopic(r.fields.kbGap, input.topic)) {\n await tickets.update(r.id, { fields: { kbArticle: path } });\n closed += 1;\n }\n }\n }\n note =\n 'Saved ' + path +\n (closed ? '; it answers the \"' + input.topic!.trim() + '\" gap on ' + closed + (closed === 1 ? ' ticket' : ' tickets') : input.topic?.trim() ? '; no open gap matched \"' + input.topic.trim() + '\"' : '') + '.';\n} else if (input.action !== 'status' && input.action !== 'list') {\n throw new Error(\"Unknown action '\" + input.action + \"'. Use status, add, reply, set_status, save_article, or list.\");\n}\n\nconst records = await tickets.list();\nconst kb = await articles();\nconst now = Date.now();\nconst view = picture(records, kb, now);\n\ngezel.output({\n needsReply: view.needsReply,\n waiting: view.waiting,\n gaps: view.gaps,\n summary:\n input.action === 'list'\n ? records.map((r) => '[' + r.status + '] ' + line(r, now, true)).join('\\n') || 'No tickets yet.'\n : (note ? note + ' ' : '') + view.summary,\n});\n"},"tools":[{"name":"desk_status","description":"The support desk now: every ticket that needs a reply (urgent first, then oldest) with what the customer asked and whether a reply is drafted, what waits on the customer, the questions no help article answers yet, and the help articles in kb/. Every ticket has its id. Call it first when asked about the queue.","script":"support-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"},"state":true},{"name":"add_ticket","description":"Log a customer request as a ticket: subject, customer, channel, category, priority, their message in their words, and the day it came in (YYYY-MM-DD, default today). The same subject from the same customer updates the open ticket, never duplicates it. Call it as soon as a request is mentioned, before you describe it.","script":"support-store","inputs":{"type":"object","properties":{"subject":{"type":"string"},"customer":{"type":"string"},"channel":{"type":"string","enum":["email","phone","chat","social","in-person","other"]},"category":{"type":"string","enum":["order","delivery","billing","product","account","business","complaint","other"]},"priority":{"type":"string","enum":["normal","urgent","low"]},"message":{"type":"string"},"receivedAt":{"type":"string"},"gap":{"type":"string"}},"required":["subject"]},"bind":{"action":"add"}},{"name":"suggest_reply","description":"Save a suggested reply on a ticket, ready for the person to send, with the help article in kb/ it draws on. When no article answers the question, pass gap with a short topic (reuse a topic from the status) so it shows as a knowledge-base gap. Call it as soon as the reply is drafted, before you show it.","script":"support-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"subject":{"type":"string"},"reply":{"type":"string"},"article":{"type":"string"},"gap":{"type":"string"}}},"bind":{"action":"reply"}},{"name":"set_ticket_status","description":"Move a ticket: open (being worked on), waiting (on the customer), resolved, or back to new. Call it the moment the person says a ticket moved.","script":"support-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"subject":{"type":"string"},"status":{"type":"string","enum":["new","open","waiting","resolved"]},"note":{"type":"string"}},"required":["status"]},"bind":{"action":"set_status"}},{"name":"save_kb_article","description":"Write a help article to kb/ (title and markdown body) and close the knowledge-base gap it answers (topic, as the status names it). Saving the same title again updates the article. Leave prices, dates and policies the business has not stated as [bracketed] blanks. Call it as soon as the article is written, before you describe it.","script":"support-store","inputs":{"type":"object","properties":{"title":{"type":"string"},"body":{"type":"string"},"topic":{"type":"string"}},"required":["title","body"]},"bind":{"action":"save_article"}},{"name":"list_tickets","description":"Every ticket, resolved ones too, with its status, category, customer, age and message.","script":"support-store","inputs":{"type":"object","properties":{}},"bind":{"action":"list"}},{"name":"page_add_ticket","description":"Log a ticket.","script":"support-store","inputs":{"type":"object","properties":{"subject":{"type":"string"},"customer":{"type":"string"},"channel":{"type":"string","enum":["email","phone","chat","social","in-person","other"]},"category":{"type":"string","enum":["order","delivery","billing","product","account","business","complaint","other"]},"priority":{"type":"string","enum":["normal","urgent","low"]},"message":{"type":"string"},"receivedAt":{"type":"string"},"gap":{"type":"string"}},"required":["subject"]},"bind":{"action":"add"}},{"name":"page_suggest_reply","description":"Save a reply on a ticket.","script":"support-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"subject":{"type":"string"},"reply":{"type":"string"},"article":{"type":"string"},"gap":{"type":"string"}}},"bind":{"action":"reply"}},{"name":"page_set_ticket_status","description":"Move a ticket.","script":"support-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"subject":{"type":"string"},"status":{"type":"string","enum":["new","open","waiting","resolved"]},"note":{"type":"string"}},"required":["status"]},"bind":{"action":"set_status"},"reaction":{"gezel":"support-lead","prompt":"The person just moved a ticket on the support desk page. The desk now reads (its first sentence is what changed):\n{{output.summary}}\nIn two short sentences, confirm what changed and name the next ticket that needs a reply, and whether its reply is drafted. Do not call tools.","hideSeed":true}}],"pages":{"imports":[{"id":"kb","source":"workspace","path":"kb","accept":[".md",".markdown",".txt",".html",".docx",".pdf"],"maxFileBytes":26214400}],"entry":"desk/index.html","api":1,"reads":[{"source":"workspace","path":"tickets.json"},{"source":"workspace","path":"kb","subtree":true}],"tools":["page_add_ticket","page_suggest_reply","page_set_ticket_status"]},"schedules":[],"workspaceSeed":["tickets.json"],"artifactsSeed":[],"availableVersions":["1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"team-goals","name":"Team Goals","description":"Set your team's goals and check progress toward them. A planner keeps each goal's key results, current against target, logs the weekly check-ins, and turns what a meeting agreed into actions with an owner and a date.","tags":["okrs","key-results","objectives","check-ins","meetings","team","small-business"],"category":"business","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.0.0","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"team":{"type":"string","title":"Whose goals are these?","description":"e.g. 'a six-person design studio', 'the kitchen team'.","default":"the team"}},"required":["team"]},"nameTemplate":"Team Goals","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"planner","voorman":true}],"toolsets":[],"craftbooks":["weekly-review","status-report","meeting-notes-to-actions","standup-summary","kpi-scorecard"],"scripts":{"goals-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { logStore, rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'goals-store',\n description:\n \"Read and update the team's goals (goals.json), their key results (keyresults.json), weekly check-ins (checkins.json) and meeting actions (actions.json). action:'status' for the whole picture; 'add_goal' and 'add_key_result' save one (an existing title is updated, never duplicated); 'update_key_result' records progress (change is added to the current value, value replaces it); 'set_goal_status' closes or reopens a goal; 'checkin' logs a weekly check-in; 'add_action' and 'complete_action' keep the meeting actions.\",\n inputs: {\n action: {\n type: 'string',\n description:\n \"One of 'status', 'add_goal', 'add_key_result', 'update_key_result', 'set_goal_status', 'checkin', 'add_action', or 'complete_action'.\",\n required: true,\n },\n goal: { type: 'string', description: \"A goal's id ('g-2') or (part of) its title.\" },\n keyResult: { type: 'string', description: \"A key result's id ('kr-3') or (part of) its title.\" },\n id: { type: 'string', description: \"A meeting action's id, e.g. 'act-2'.\" },\n title: {\n type: 'string',\n description: \"The title of the goal, key result or action being saved, e.g. 'Win four new retainer clients'.\",\n },\n owner: { type: 'string', description: 'Who owns it.' },\n startAt: { type: 'string', description: 'When a goal started, YYYY-MM-DD (default today).' },\n dueAt: { type: 'string', description: 'When it is due, YYYY-MM-DD.' },\n start: { type: 'number', description: 'Where a key result started.' },\n current: { type: 'number', description: 'Where a key result stands now.' },\n target: { type: 'number', description: 'Where a key result should end up.' },\n unit: { type: 'string', description: \"What a key result counts: 'clients', '%', '$', 'hours'.\" },\n change: {\n type: 'number',\n description: 'How much a key result moved: 2 for two more, -1 for one fewer. Added to its current value.',\n },\n value: { type: 'number', description: \"A key result's new total, only when the person gives the total.\" },\n how: { type: 'string', description: \"The page form's choice between change and value; the script reads change or value.\" },\n who: { type: 'string', description: 'Who is checking in.' },\n confidence: { type: 'string', description: 'on-track, at-risk, or off-track.' },\n status: { type: 'string', description: 'For set_goal_status: active, done, or dropped.' },\n from: { type: 'string', description: \"The meeting an action came from, e.g. 'Monday team meeting'.\" },\n note: { type: 'string', description: 'What happened, in their words.' },\n },\n outputs: {\n active: { type: 'number', description: 'Active goals.' },\n offPace: { type: 'number', description: 'Active goals at risk, behind or past due.' },\n openActions: { type: 'number', description: 'Meeting actions still open.' },\n summary: {\n type: 'string',\n description: 'What changed first, then every active goal (furthest behind first) with its key results, the check-ins and the open actions.',\n },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── goals-rules-start ──\n// Pure derivations: key-result progress (current against target, from where it\n// started), a goal's pace against the share of its time already gone, the\n// week's check-ins, and the lines the crew reads. Kept self-contained between\n// these sentinels so unit tests execute the shipped bytes.\nvar DAY_MS = 86400000;\nvar STOP_WORDS = ['the', 'and', 'for', 'our', 'with', 'from', 'that', 'this', 'into', 'more'];\n\nfunction pad(n) {\n return n < 10 ? '0' + n : String(n);\n}\nfunction localDay(ms) {\n var d = new Date(ms);\n return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());\n}\nfunction normalizeDate(text) {\n var raw = String(text || '').trim();\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(raw)) return raw;\n var parsed = Date.parse(raw);\n return isFinite(parsed) ? localDay(parsed) : null;\n}\nfunction dayMs(day) {\n return Date.parse(String(day).slice(0, 10) + 'T00:00:00');\n}\nfunction daysLeft(dueAt, nowMs) {\n return Math.round((dayMs(dueAt) - dayMs(localDay(nowMs))) / DAY_MS);\n}\nfunction when(days) {\n if (days < 0) return -days + (days === -1 ? ' day late' : ' days late');\n if (days === 0) return 'due today';\n return 'in ' + days + (days === 1 ? ' day' : ' days');\n}\nfunction round2(n) {\n return Math.round(n * 100) / 100;\n}\nfunction fmt(n) {\n var r = round2(Number(n) || 0);\n var parts = String(Math.abs(r)).split('.');\n parts[0] = parts[0].replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\n return (r < 0 ? '-' : '') + parts.join('.');\n}\nfunction amount(n, unit) {\n var u = String(unit || '').trim();\n if (u === '%' || /^percent/i.test(u)) return fmt(n) + '%';\n if (u === '$' || /^(dollars?|usd)$/i.test(u)) return '$' + fmt(n);\n if (fmt(n) === '1' && /^[a-z]+[^su]s$/i.test(u)) u = u.slice(0, -1);\n return fmt(n) + (u ? ' ' + u : '');\n}\nfunction percent(p) {\n return Math.round(p * 100) + '%';\n}\nfunction normalizeConfidence(text) {\n var t = String(text || '').trim().toLowerCase().replace(/[\\s_]+/g, '-');\n if (/^(on-?track|green|good|fine)/.test(t)) return 'on-track';\n if (/^(at-?risk|amber|yellow|watch|shaky|unsure)/.test(t)) return 'at-risk';\n if (/^(off-?track|behind|red|blocked|stuck|slipping)/.test(t)) return 'off-track';\n return null;\n}\nfunction normalizeGoalStatus(text) {\n var t = String(text || '').trim().toLowerCase();\n if (/^(active|open|reopen|restart|resume)/.test(t)) return 'active';\n if (/^(done|complete|finished|met|achieved|closed)/.test(t)) return 'done';\n if (/^(dropped|drop|cancel|abandon|parked|shelved)/.test(t)) return 'dropped';\n return null;\n}\n// How far a key result has come from where it started toward its target, 0..1.\n// A target below the start (fewer overdue invoices) counts down the same way.\nfunction krProgress(f) {\n var start = Number(f.start) || 0;\n var target = Number(f.target);\n var current = Number(f.current) || 0;\n if (!isFinite(target)) return 0;\n if (target === start) return current >= target ? 1 : 0;\n return Math.max(0, Math.min(1, (current - start) / (target - start)));\n}\n// The share of a goal's window already gone, 0..1, or null without a due date.\nfunction timeGone(f, nowMs) {\n var due = dayMs(f.dueAt || '');\n if (!isFinite(due)) return null;\n var start = dayMs(f.startAt || '');\n var today = dayMs(localDay(nowMs));\n if (!isFinite(start) || due <= start) return today >= due ? 1 : 0;\n return Math.max(0, Math.min(1, (today - start) / (due - start)));\n}\nfunction pace(progress, gone) {\n if (progress === null) return 'no key results yet';\n if (progress >= 1) return 'target met';\n if (gone === null) return 'no due date';\n if (gone >= 1) return 'past due';\n if (progress >= gone - 0.1) return 'on track';\n if (progress >= gone - 0.25) return 'at risk';\n return 'behind';\n}\nfunction titleOf(record) {\n return String((record && record.fields && record.fields.title) || '');\n}\nfunction goalKeyResults(goal, krs) {\n return krs.filter(function (k) {\n return k.fields && k.fields.goalId === goal.id && k.status !== 'closed';\n });\n}\nfunction goalProgress(goal, krs) {\n var mine = goalKeyResults(goal, krs);\n if (!mine.length) return null;\n return (\n mine.reduce(function (sum, k) {\n return sum + krProgress(k.fields);\n }, 0) / mine.length\n );\n}\n// How far behind its time a goal is: the gap the board sorts by, worst first.\nfunction lag(goal, krs, nowMs) {\n var p = goalProgress(goal, krs);\n var gone = timeGone(goal.fields || {}, nowMs);\n if (p === null) return -2;\n if (gone === null) return -1;\n return gone - p;\n}\nfunction krLine(k) {\n var f = k.fields || {};\n var from = Number(f.start) || 0;\n return (\n k.id + ' ' + f.title + ': now ' + amount(f.current || 0, f.unit) + ', target ' + amount(f.target, f.unit) +\n (from ? ' (started at ' + amount(from, f.unit) + ')' : '') + ', ' + percent(krProgress(f)) + ' of the way'\n );\n}\nfunction lastCheckin(goal, events) {\n var mine = events.filter(function (e) {\n return e.kind === 'checkin' && e.data && e.data.goalId === goal.id;\n });\n return mine.length ? mine[mine.length - 1] : null;\n}\nfunction checkedInSince(goal, events, sinceMs) {\n var owner = String((goal.fields && goal.fields.owner) || '').trim().toLowerCase();\n return events.some(function (e) {\n if (e.kind !== 'checkin' || !e.data || Date.parse(e.at) < sinceMs) return false;\n if (e.data.goalId) return e.data.goalId === goal.id;\n return !!owner && String(e.data.who || '').trim().toLowerCase() === owner;\n });\n}\nfunction goalLine(goal, krs, events, nowMs) {\n var f = goal.fields || {};\n var p = goalProgress(goal, krs);\n var gone = timeGone(f, nowMs);\n var mine = goalKeyResults(goal, krs);\n var last = lastCheckin(goal, events);\n return (\n goal.id + ' ' + f.title + ' (owner ' + (f.owner || 'unassigned') +\n (f.dueAt ? ', due ' + f.dueAt + ', ' + when(daysLeft(f.dueAt, nowMs)) : '') + '): ' +\n (p === null ? 'no key results yet' : percent(p) + ' done' + (gone === null ? '' : ' with ' + percent(gone) + ' of the time gone') + ', ' + pace(p, gone)) +\n (mine.length ? '. Key results: ' + mine.map(krLine).join('; ') : '') + '. ' +\n (last\n ? 'Last check-in ' + localDay(Date.parse(last.at)) + (last.data.who ? ' by ' + last.data.who : '') +\n (last.data.confidence ? ', ' + String(last.data.confidence).replace('-', ' ') : '') + (last.note ? ': ' + String(last.note).replace(/[.!?\\s]+$/, '') : '')\n : 'No check-in yet') + '.'\n );\n}\nfunction actionLine(a, nowMs) {\n var f = a.fields || {};\n return a.id + ' ' + f.title + ' (' + (f.owner || 'no owner') + (f.dueAt ? ', due ' + f.dueAt + ', ' + when(daysLeft(f.dueAt, nowMs)) : '') + ')';\n}\nfunction picture(goals, krs, events, actions, nowMs) {\n var active = goals\n .filter(function (g) { return g.status === 'active'; })\n .sort(function (a, b) { return lag(b, krs, nowMs) - lag(a, krs, nowMs); });\n var paces = active.map(function (g) { return pace(goalProgress(g, krs), timeGone(g.fields || {}, nowMs)); });\n var offPace = paces.filter(function (p) { return p === 'at risk' || p === 'behind' || p === 'past due'; }).length;\n var onTrack = paces.filter(function (p) { return p === 'on track' || p === 'target met'; }).length;\n var open = actions\n .filter(function (a) { return a.status !== 'done'; })\n .sort(function (a, b) { return String(a.fields.dueAt || '9999').localeCompare(String(b.fields.dueAt || '9999')); });\n var since = dayMs(localDay(nowMs)) - 6 * DAY_MS;\n var quiet = active.filter(function (g) { return !checkedInSince(g, events, since); });\n var parts = [];\n parts.push(\n active.length\n ? active.length + (active.length === 1 ? ' active goal: ' : ' active goals: ') + onTrack + ' on track, ' + offPace + ' at risk or behind.' +\n (active.length > 1 ? ' Goals, furthest behind first:' : '')\n : goals.length ? 'No active goals.' : 'No active goals yet.',\n );\n active.forEach(function (g) { parts.push(goalLine(g, krs, events, nowMs)); });\n if (active.length) {\n parts.push(\n quiet.length\n ? 'No check-in in the last 7 days: ' + quiet.map(function (g) { return (g.fields.owner || 'unassigned') + ' for ' + g.id + ' ' + g.fields.title; }).join('; ') + '.'\n : 'Every active goal has a check-in from the last 7 days.',\n );\n }\n parts.push(open.length ? 'Open actions, late ones first, then soonest due: ' + open.map(function (a) { return actionLine(a, nowMs); }).join('; ') + '.' : 'No open meeting actions.');\n var closed = goals.filter(function (g) { return g.status !== 'active'; });\n if (closed.length) parts.push('Closed goals: ' + closed.map(function (g) { return g.id + ' ' + g.fields.title + ' (' + g.status + ')'; }).join('; ') + '.');\n return { active: active.length, offPace: offPace, openActions: open.length, summary: parts.join(' ') };\n}\n// Find one record by id, exact title, partial title, or every word of the\n// title; a miss lists what there is so the next call can name it.\nfunction pick(records, wanted, label) {\n var text = String(wanted || '').trim();\n var lower = text.toLowerCase();\n if (!lower) throw new Error('Name the ' + label + ' by its id or title.');\n var byId = records.filter(function (r) { return r.id === lower; });\n if (byId.length) return byId[0];\n var exact = records.filter(function (r) { return titleOf(r).toLowerCase() === lower; });\n if (exact.length === 1) return exact[0];\n var partial = records.filter(function (r) { return titleOf(r).toLowerCase().indexOf(lower) >= 0; });\n if (partial.length === 1) return partial[0];\n if (!partial.length) {\n var words = (lower.match(/[a-z0-9]{3,}/g) || []).filter(function (w) { return STOP_WORDS.indexOf(w) < 0; });\n partial = words.length\n ? records.filter(function (r) {\n var t = titleOf(r).toLowerCase();\n return words.every(function (w) { return t.indexOf(w) >= 0 || t.indexOf(w.replace(/ies$/, 'y').replace(/s$/, '')) >= 0; });\n })\n : [];\n if (partial.length === 1) return partial[0];\n }\n var known = (partial.length > 1 ? partial : records).map(function (r) { return r.id + ' ' + titleOf(r); }).join(', ');\n throw new Error(\n (partial.length > 1 ? 'More than one ' + label + \" matches '\" + text + \"': \" : 'No ' + label + \" matches '\" + text + \"'. Known: \") +\n (known || 'none yet') + '. Pass the id.',\n );\n}\nfunction pickPreferring(preferred, all, wanted, label) {\n try {\n return pick(preferred, wanted, label);\n } catch (error) {\n return pick(all, wanted, label);\n }\n}\n// ── goals-rules-end ──\n\nconst goals = rosterStore(gezel.fs, 'goals.json', { stages: ['active', 'done', 'dropped'], idPrefix: 'g' });\nconst keyResults = rosterStore(gezel.fs, 'keyresults.json', { stages: ['active', 'closed'], idPrefix: 'kr' });\nconst checkins = logStore(gezel.fs, 'checkins.json');\nconst actions = rosterStore(gezel.fs, 'actions.json', { stages: ['open', 'done'], idPrefix: 'act' });\n\nfunction text(value: unknown): string {\n return typeof value === 'string' ? value.trim() : '';\n}\nfunction dateInput(value: unknown, name: string): string | null {\n if (!text(value)) return null;\n const day = normalizeDate(value);\n if (!day) throw new Error(name + \" must be a date, e.g. '2026-12-31'.\");\n return day;\n}\nasync function findGoal(wanted: string) {\n const all = await goals.list();\n return pickPreferring(all.filter((g) => g.status === 'active'), all, wanted, 'goal');\n}\n\nconst now = Date.now();\nlet note = '';\n\nif (input.action === 'add_goal') {\n const title = text(input.title) || text(input.goal);\n if (!title) throw new Error(\"add_goal needs 'title', e.g. 'Win four new retainer clients'.\");\n const dueAt = dateInput(input.dueAt, 'dueAt');\n const startAt = dateInput(input.startAt, 'startAt');\n const fields: Record<string, unknown> = {\n ...(dueAt ? { dueAt } : {}),\n ...(startAt ? { startAt } : {}),\n ...(text(input.owner) ? { owner: text(input.owner) } : {}),\n ...(text(input.note) ? { why: text(input.note) } : {}),\n };\n const existing = (await goals.list()).find((g) => titleOf(g).toLowerCase() === title.toLowerCase());\n if (existing) {\n await goals.update(existing.id, { fields });\n note = 'Updated ' + existing.id + ' ' + titleOf(existing) + '.';\n } else {\n const record = await goals.add({ status: 'active', fields: { title, startAt: startAt ?? localDay(now), ...fields } });\n note = 'Added ' + record.id + ' ' + title + (dueAt ? ', due ' + dueAt : '') + '.';\n }\n} else if (input.action === 'add_key_result') {\n if (!text(input.goal)) throw new Error(\"add_key_result needs 'goal' (its id or title) and 'title'.\");\n const goal = await findGoal(text(input.goal));\n const title = text(input.title) || text(input.keyResult);\n if (!title) throw new Error(\"add_key_result needs 'title', e.g. 'New retainer clients'.\");\n const unit = text(input.unit);\n const existing = (await keyResults.list()).find(\n (k) => k.fields.goalId === goal.id && titleOf(k).toLowerCase() === title.toLowerCase(),\n );\n const fields: Record<string, unknown> = {\n ...(typeof input.target === 'number' ? { target: round2(input.target) } : {}),\n ...(typeof input.current === 'number' ? { current: round2(input.current) } : {}),\n ...(typeof input.start === 'number' ? { start: round2(input.start) } : {}),\n ...(unit ? { unit } : {}),\n };\n if (existing) {\n await keyResults.update(existing.id, { fields, note: 'Edited.' });\n note = 'Updated ' + existing.id + ' ' + titleOf(existing) + '.';\n } else {\n if (typeof input.target !== 'number') throw new Error(\"A new key result needs 'target', the number it should reach.\");\n const start = typeof input.start === 'number' ? input.start : typeof input.current === 'number' ? input.current : 0;\n const current = typeof input.current === 'number' ? input.current : start;\n const record = await keyResults.add({\n status: goal.status === 'active' ? 'active' : 'closed',\n fields: { goalId: goal.id, goal: titleOf(goal), title, start: round2(start), current: round2(current), target: round2(input.target), ...(unit ? { unit } : {}) },\n });\n note = 'Added ' + record.id + ' ' + title + ' to ' + goal.id + ': now ' + amount(current, unit) + ', target ' + amount(input.target, unit) + '.';\n }\n} else if (input.action === 'update_key_result') {\n const all = await keyResults.list();\n let pool = all;\n if (text(input.goal)) {\n const goal = await findGoal(text(input.goal));\n pool = all.filter((k) => k.fields.goalId === goal.id);\n }\n const wanted = text(input.keyResult) || text(input.title);\n let kr;\n if (wanted) kr = pickPreferring(pool.filter((k) => k.status !== 'closed'), all, wanted, 'key result');\n else if (pool !== all && pool.length === 1) kr = pool[0]!;\n else {\n throw new Error(\n \"update_key_result needs 'keyResult' (its id or title). Known: \" +\n (pool.map((k) => k.id + ' ' + titleOf(k)).join(', ') || 'none yet') + '.',\n );\n }\n const change = typeof input.change === 'number' ? input.change : null;\n const value = typeof input.value === 'number' ? input.value : null;\n if (change === null && value === null) {\n throw new Error(\"update_key_result needs 'change' (how much it moved: 2, or -1) or 'value' (the new total).\");\n }\n const before = Number(kr.fields.current) || 0;\n const after = round2(change !== null ? before + change : (value as number));\n const unit = String(kr.fields.unit ?? '');\n await keyResults.update(kr.id, {\n fields: { current: after },\n note: fmt(before) + ' to ' + fmt(after) + (text(input.note) ? ': ' + text(input.note) : ''),\n });\n await checkins.append({\n kind: 'progress',\n ...(text(input.note) ? { note: text(input.note) } : {}),\n data: { goalId: kr.fields.goalId, keyResultId: kr.id, from: before, to: after, ...(text(input.who) ? { who: text(input.who) } : {}) },\n });\n note =\n titleOf(kr) + ' moved from ' + amount(before, unit) + ' to ' + amount(after, unit) + ' (target ' + amount(kr.fields.target, unit) + ', ' +\n percent(krProgress({ ...kr.fields, current: after })) + ' of the way).';\n} else if (input.action === 'set_goal_status') {\n const status = normalizeGoalStatus(input.status);\n if (!status) throw new Error(\"set_goal_status needs status 'active', 'done', or 'dropped'.\");\n if (!text(input.goal)) throw new Error(\"set_goal_status needs 'goal' (its id or title).\");\n const goal = pick(await goals.list(), text(input.goal), 'goal');\n if (goal.status !== status) await goals.transition(goal.id, status, text(input.note) ? { note: text(input.note) } : {});\n for (const k of await keyResults.list()) {\n if (k.fields.goalId !== goal.id) continue;\n const next = status === 'active' ? 'active' : 'closed';\n if (k.status !== next) await keyResults.transition(k.id, next);\n }\n note = titleOf(goal) + (status === 'active' ? ' is active again.' : status === 'done' ? ' is done.' : ' was dropped.');\n} else if (input.action === 'checkin') {\n const confidence = text(input.confidence) ? normalizeConfidence(input.confidence) : null;\n if (text(input.confidence) && !confidence) throw new Error(\"confidence must be 'on-track', 'at-risk', or 'off-track'.\");\n if (!text(input.note) && !confidence) throw new Error(\"A check-in needs 'note' (what they said) or 'confidence'.\");\n const goal = text(input.goal) ? await findGoal(text(input.goal)) : null;\n const who = text(input.who) || (goal ? String(goal.fields.owner ?? '') : '');\n await checkins.append({\n kind: 'checkin',\n ...(text(input.note) ? { note: text(input.note) } : {}),\n data: { ...(goal ? { goalId: goal.id } : {}), ...(who ? { who } : {}), ...(confidence ? { confidence } : {}) },\n });\n note =\n 'Logged ' + (who ? who + \"'s check-in\" : 'a check-in') + (goal ? ' on ' + titleOf(goal) : '') +\n (confidence ? ': ' + confidence.replace('-', ' ') : '') + '.';\n} else if (input.action === 'add_action') {\n const title = text(input.title);\n if (!title) throw new Error(\"add_action needs 'title', e.g. 'Send Alder Co the proposal'.\");\n const dueAt = dateInput(input.dueAt, 'dueAt');\n let goalId = '';\n let unlinked = '';\n if (text(input.goal)) {\n try {\n goalId = (await findGoal(text(input.goal))).id;\n } catch {\n unlinked = \" No goal matched '\" + text(input.goal) + \"', so it is not linked to one.\";\n }\n }\n const fields: Record<string, unknown> = {\n ...(text(input.owner) ? { owner: text(input.owner) } : {}),\n ...(dueAt ? { dueAt } : {}),\n ...(goalId ? { goalId } : {}),\n ...(text(input.from) ? { from: text(input.from) } : {}),\n };\n const existing = (await actions.list()).find((a) => a.status !== 'done' && titleOf(a).toLowerCase() === title.toLowerCase());\n if (existing) {\n await actions.update(existing.id, { fields });\n note = 'Updated ' + existing.id + ' ' + titleOf(existing) + '.' + unlinked;\n } else {\n const record = await actions.add({ status: 'open', fields: { title, ...fields } });\n note = 'Added ' + record.id + ' ' + title + (text(input.owner) ? ' for ' + text(input.owner) : '') + (dueAt ? ', due ' + dueAt : '') + '.' + unlinked;\n }\n} else if (input.action === 'complete_action') {\n const wanted = text(input.id) || text(input.title);\n if (!wanted) throw new Error(\"complete_action needs 'id' (e.g. 'act-2') or the action's 'title'.\");\n const all = await actions.list();\n const done = pickPreferring(all.filter((a) => a.status !== 'done'), all, wanted, 'action');\n if (done.status !== 'done') await actions.transition(done.id, 'done', text(input.note) ? { note: text(input.note) } : {});\n note = 'Done: ' + titleOf(done) + (done.fields.owner ? ' (' + String(done.fields.owner) + ')' : '') + '.';\n} else if (input.action !== 'status') {\n throw new Error(\n \"Unknown action '\" + input.action + \"'. Use status, add_goal, add_key_result, update_key_result, set_goal_status, checkin, add_action, or complete_action.\",\n );\n}\n\nconst view = picture(await goals.list(), await keyResults.list(), await checkins.list(), await actions.list(), Date.now());\n\ngezel.output({\n active: view.active,\n offPace: view.offPace,\n openActions: view.openActions,\n summary: (note ? note + ' ' : '') + view.summary,\n});\n"},"tools":[{"name":"goals_status","description":"The whole picture, furthest behind first: every active goal with its key results (current against target, with ids), its pace against the time gone, its last check-in, which goals have no check-in this week, and the open meeting actions with owners and due dates. Call it first when asked how things are going.","script":"goals-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"},"state":true},{"name":"add_goal","description":"Save a goal: its title, owner and due date (YYYY-MM-DD). An existing title is updated, never duplicated. Call it as soon as a goal is named, before you describe it, then add its key results with add_key_result.","script":"goals-store","inputs":{"type":"object","properties":{"title":{"type":"string"},"owner":{"type":"string"},"dueAt":{"type":"string","description":"YYYY-MM-DD"},"startAt":{"type":"string","description":"YYYY-MM-DD; defaults to today"},"note":{"type":"string","description":"Why the goal matters, in their words."}},"required":["title"]},"bind":{"action":"add_goal"}},{"name":"add_key_result","description":"Save a key result under a goal: what it measures, where it stands now, and the target. An existing title on that goal is updated, never duplicated. Call it as soon as one is named.","script":"goals-store","inputs":{"type":"object","properties":{"goal":{"type":"string","description":"The goal's id or title."},"title":{"type":"string","description":"What the key result measures."},"current":{"type":"number","description":"Where it stands now."},"target":{"type":"number","description":"Where it should end up."},"start":{"type":"number","description":"Where it started (defaults to current)."},"unit":{"type":"string","description":"'clients', '%', '$', 'hours'..."}},"required":["goal","title"]},"bind":{"action":"add_key_result"}},{"name":"update_key_result","description":"Record progress on a key result the moment the person reports it. When they say how much it moved ('two more clients', 'down 3 points'), pass change (2, -3) and the board adds it to the current value; pass value only when they give the new total. Never add it up yourself.","script":"goals-store","inputs":{"type":"object","properties":{"keyResult":{"type":"string","description":"The key result's id (e.g. 'kr-3') or title."},"goal":{"type":"string","description":"Optional: the goal's id or title, to narrow the search."},"change":{"type":"number","description":"How much it moved: 2 for two more, -1 for one fewer."},"value":{"type":"number","description":"The new total, only when the person gives the total."},"note":{"type":"string"}}},"bind":{"action":"update_key_result"}},{"name":"log_checkin","description":"Log a weekly check-in on a goal: who, how confident they are (on-track, at-risk or off-track), and what they said. Call it as soon as someone reports in, before you reply.","script":"goals-store","inputs":{"type":"object","properties":{"goal":{"type":"string","description":"The goal's id or title."},"who":{"type":"string"},"confidence":{"type":"string","enum":["on-track","at-risk","off-track"]},"note":{"type":"string","description":"What they said, in their words."}}},"bind":{"action":"checkin"}},{"name":"add_action","description":"Save one action agreed in a meeting: what, who owns it, when it is due (YYYY-MM-DD), and the goal it serves. An open action with the same title is updated, never duplicated. Call it for each action as soon as it is agreed, before you summarize.","script":"goals-store","inputs":{"type":"object","properties":{"title":{"type":"string","description":"The action, e.g. \"Send Alder Co the proposal\"."},"owner":{"type":"string"},"dueAt":{"type":"string","description":"YYYY-MM-DD"},"goal":{"type":"string","description":"Optional: the goal it serves (id or title)."},"from":{"type":"string","description":"The meeting it came from, e.g. 'Monday team meeting'."}},"required":["title"]},"bind":{"action":"add_action"}},{"name":"complete_action","description":"Mark a meeting action done the moment the person says it is.","script":"goals-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"note":{"type":"string"}}},"bind":{"action":"complete_action"}},{"name":"set_goal_status","description":"Close a goal as done or dropped, or reopen it.","script":"goals-store","inputs":{"type":"object","properties":{"goal":{"type":"string"},"status":{"type":"string","enum":["active","done","dropped"]},"note":{"type":"string"}},"required":["goal","status"]},"bind":{"action":"set_goal_status"}},{"name":"page_add_goal","description":"Add or update a goal.","script":"goals-store","inputs":{"type":"object","properties":{"title":{"type":"string"},"owner":{"type":"string"},"dueAt":{"type":"string","description":"YYYY-MM-DD"},"startAt":{"type":"string","description":"YYYY-MM-DD; defaults to today"},"note":{"type":"string","description":"Why the goal matters, in their words."}},"required":["title"]},"bind":{"action":"add_goal"}},{"name":"page_add_key_result","description":"Add or update a key result.","script":"goals-store","inputs":{"type":"object","properties":{"goal":{"type":"string","description":"The goal's id or title."},"title":{"type":"string","description":"What the key result measures."},"current":{"type":"number","description":"Where it stands now."},"target":{"type":"number","description":"Where it should end up."},"start":{"type":"number","description":"Where it started (defaults to current)."},"unit":{"type":"string","description":"'clients', '%', '$', 'hours'..."}},"required":["goal","title"]},"bind":{"action":"add_key_result"}},{"name":"page_update_key_result","description":"Record progress on a key result.","script":"goals-store","inputs":{"type":"object","properties":{"keyResult":{"type":"string","description":"The key result's id (e.g. 'kr-3') or title."},"goal":{"type":"string","description":"Optional: the goal's id or title, to narrow the search."},"change":{"type":"number","description":"How much it moved: 2 for two more, -1 for one fewer."},"value":{"type":"number","description":"The new total, only when the person gives the total."},"note":{"type":"string"},"how":{"type":"string"}}},"bind":{"action":"update_key_result"},"reaction":{"gezel":"planner","prompt":"The person just recorded progress on the goals page. The board now reads (its first sentence is what changed):\n{{output.summary}}\nIn two short sentences, confirm what moved and how that goal is pacing now, and name the one next step that would help it most. Do not call tools.","hideSeed":true}},{"name":"page_log_checkin","description":"Log a check-in.","script":"goals-store","inputs":{"type":"object","properties":{"goal":{"type":"string","description":"The goal's id or title."},"who":{"type":"string"},"confidence":{"type":"string","enum":["on-track","at-risk","off-track"]},"note":{"type":"string","description":"What they said, in their words."}}},"bind":{"action":"checkin"},"reaction":{"gezel":"planner","prompt":"The person just logged a check-in on the goals page. The board now reads (its first sentence is what changed):\n{{output.summary}}\nIn two short sentences, acknowledge the check-in, and if that goal is at risk or behind, suggest one concrete action the team could agree to. Do not call tools.","hideSeed":true}},{"name":"page_add_action","description":"Add a meeting action.","script":"goals-store","inputs":{"type":"object","properties":{"title":{"type":"string","description":"The action, e.g. \"Send Alder Co the proposal\"."},"owner":{"type":"string"},"dueAt":{"type":"string","description":"YYYY-MM-DD"},"goal":{"type":"string","description":"Optional: the goal it serves (id or title)."},"from":{"type":"string","description":"The meeting it came from, e.g. 'Monday team meeting'."}},"required":["title"]},"bind":{"action":"add_action"}},{"name":"page_complete_action","description":"Mark a meeting action done.","script":"goals-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"note":{"type":"string"}}},"bind":{"action":"complete_action"}}],"pages":{"entry":"goals/index.html","api":1,"reads":[{"source":"workspace","path":"goals.json"},{"source":"workspace","path":"keyresults.json"},{"source":"workspace","path":"checkins.json"},{"source":"workspace","path":"actions.json"}],"tools":["page_add_goal","page_add_key_result","page_update_key_result","page_log_checkin","page_add_action","page_complete_action"]},"schedules":[],"workspaceSeed":["goals.json","keyresults.json","checkins.json","actions.json"],"artifactsSeed":[],"availableVersions":["1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"training-tracker","name":"Training Tracker","description":"Track who has finished which training, and what is due next. A training coordinator keeps a people-by-courses matrix, records certificates with their expiry dates, books refreshers before anything lapses, and turns your own checklists into short quizzes.","tags":["certifications","refreshers","food-safety","quizzes","compliance","staff","small-business"],"category":"business","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.0.0","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"business":{"type":"string","title":"What kind of business is this?","description":"e.g. 'a café with 12 staff', 'a three-person electrical contractor'.","default":"the business"}},"required":["business"]},"nameTemplate":"Training Tracker","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"training-coordinator","voorman":true},{"templateId":"study-buddy","voorman":false}],"toolsets":[],"craftbooks":["interactive-quiz","handbook-section","onboarding-checklist"],"scripts":{"training-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { logStore, rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'training-store',\n description:\n \"Read and update the training tracker: people.json (who works here and their role), courses.json (each course, how long it stays valid and who needs it), completions.json (completions with expiry dates, and bookings) and quizzes.json. action:'status' for who needs what, by course, lapsed first; 'add_person' and 'add_course' to add or update one (an existing name or title is updated, never duplicated); 'complete' to record a completion; 'book' to book a session; 'save_quiz' to save a quiz; 'list' for everyone's training.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'status', 'add_person', 'add_course', 'complete', 'book', 'save_quiz', or 'list'.\",\n required: true,\n },\n name: { type: 'string', description: \"For add_person: the person's full name.\" },\n role: { type: 'string', description: \"For add_person: their job, e.g. 'Barista'. It decides which courses they need.\" },\n startedAt: { type: 'string', description: \"For add_person: their first day, YYYY-MM-DD or a weekday like 'monday'.\" },\n personStatus: { type: 'string', description: \"For add_person: active, or left when someone leaves.\" },\n title: { type: 'string', description: \"For add_course: the course's title. For save_quiz: the quiz's title.\" },\n validMonths: { type: 'number', description: 'For add_course: months a completion stays valid; 0 when it never expires.' },\n requiredFor: { type: 'string', description: \"For add_course: 'everyone', or the roles that need it, e.g. 'barista, cook'.\" },\n provider: { type: 'string', description: 'For add_course: who runs or certifies it.' },\n person: { type: 'string', description: \"Person id (e.g. 'p-3') or name; several names separated by commas.\" },\n course: { type: 'string', description: \"Course id (e.g. 'c-2') or title.\" },\n completedAt: { type: 'string', description: 'For complete: the day it was finished, YYYY-MM-DD; default today.' },\n certificate: { type: 'string', description: 'For complete: the certificate or reference number exactly as given.' },\n on: { type: 'string', description: \"For book: the session date, YYYY-MM-DD or a weekday like 'thursday'.\" },\n everyoneDue: {\n type: 'boolean',\n description: 'For book: true books everyone whose certificate for the course has lapsed, runs out within the window, or was never done.',\n },\n source: { type: 'string', description: \"For save_quiz: the document it was written from, e.g. 'docs/opening-checklist.md'.\" },\n questions: {\n type: 'string',\n description: \"For save_quiz: one question per line, 'Question? | right answer | wrong answer | wrong answer'.\",\n },\n note: { type: 'string', description: 'Anything else worth keeping.' },\n withinDays: { type: 'number', description: 'How many days ahead count as due (default 30).' },\n },\n outputs: {\n expired: { type: 'number', description: 'Required certificates that have lapsed.' },\n expiringSoon: { type: 'number', description: 'Required certificates that run out within the window.' },\n missing: { type: 'number', description: 'Required courses never done.' },\n people: { type: 'number', description: 'People on the tracker.' },\n summary: { type: 'string', description: 'What changed, then who needs what, or the listing.' },\n },\n requires: ['workspace.read', 'workspace.write', 'reminders'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── training-rules-start ──\n// Pure derivations: dates in local calendar days, record matching, who needs\n// which course, each person-course cell, the picture the crew reads, and quiz\n// parsing. Kept self-contained between these sentinels so tests execute the\n// shipped bytes.\nvar DAY_MS = 86400000;\nvar WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\nvar MONTH_KEYS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];\n\nfunction pad(n) {\n return n < 10 ? '0' + n : String(n);\n}\nfunction localDay(ms) {\n var d = new Date(ms);\n return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());\n}\nfunction noon(day) {\n return new Date(String(day).slice(0, 10) + 'T12:00:00');\n}\nfunction addDays(day, n) {\n var d = noon(day);\n d.setDate(d.getDate() + n);\n return localDay(d.getTime());\n}\nfunction addMonths(day, months) {\n var d = noon(day);\n var date = d.getDate();\n d.setDate(1);\n d.setMonth(d.getMonth() + months);\n // The 31st rolls to the last day of a shorter month, not into the next one.\n d.setDate(Math.min(date, new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate()));\n return localDay(d.getTime());\n}\nfunction daysLeft(day, nowMs) {\n var due = Date.parse(String(day).slice(0, 10) + 'T00:00:00');\n var today = Date.parse(localDay(nowMs) + 'T00:00:00');\n return Math.round((due - today) / DAY_MS);\n}\nfunction dayName(day) {\n return WEEKDAYS[noon(day).getDay()];\n}\nfunction parseDay(text, nowMs, direction) {\n var raw = String(text == null ? '' : text).trim().toLowerCase().replace(/[.,]/g, ' ').replace(/\\s+/g, ' ').trim();\n if (!raw) return null;\n var iso = raw.match(/^(\\d{4})-(\\d{1,2})-(\\d{1,2})(?:t.*)?$/);\n if (iso) return iso[1] + '-' + pad(Number(iso[2])) + '-' + pad(Number(iso[3]));\n var today = localDay(nowMs);\n if (raw === 'today' || raw === 'now') return today;\n if (raw === 'tomorrow') return addDays(today, 1);\n if (raw === 'yesterday') return addDays(today, -1);\n var rel = raw.match(/^(?:in )?(\\d{1,3}) (day|days|week|weeks)( ago| from now)?$/);\n if (rel) {\n var n = Number(rel[1]) * (rel[2].charAt(0) === 'w' ? 7 : 1);\n return addDays(today, rel[3] === ' ago' ? -n : n);\n }\n var wd = raw.match(/^(this |next |last |on |coming )?(sun|mon|tue|wed|thu|fri|sat)[a-z]*$/);\n if (wd) {\n var target = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].indexOf(wd[2]);\n var now = noon(today).getDay();\n if (direction === 'past' || wd[1] === 'last ') {\n var back = (now - target + 7) % 7;\n return addDays(today, -(wd[1] === 'last ' && back === 0 ? 7 : back));\n }\n if (wd[1] === 'this ') return addDays(today, (target - now + 7) % 7);\n return addDays(today, ((target - now + 6) % 7) + 1);\n }\n var md = raw.match(/^(?:[a-z]+day )?([a-z]{3,9}) (\\d{1,2})(?:st|nd|rd|th)?(?: (\\d{4}))?$/);\n var dm = raw.match(/^(?:[a-z]+day )?(\\d{1,2})(?:st|nd|rd|th)? (?:of )?([a-z]{3,9})(?: (\\d{4}))?$/);\n var parts = md ? { month: md[1], date: md[2], year: md[3] } : dm ? { month: dm[2], date: dm[1], year: dm[3] } : null;\n if (parts) {\n var m = MONTH_KEYS.indexOf(parts.month.slice(0, 3));\n if (m < 0) return null;\n var date = Number(parts.date);\n if (date < 1 || date > 31) return null;\n if (parts.year) return parts.year + '-' + pad(m + 1) + '-' + pad(date);\n var year = noon(today).getFullYear();\n var guess = year + '-' + pad(m + 1) + '-' + pad(date);\n var d = daysLeft(guess, nowMs);\n if (direction === 'past' && d > 0) guess = year - 1 + guess.slice(4);\n if (direction !== 'past' && d < 0) guess = year + 1 + guess.slice(4);\n return guess;\n }\n return null;\n}\nfunction matches(records, text, labelOf) {\n var wanted = String(text == null ? '' : text).trim().toLowerCase().replace(/['\\u2019]s\\b/g, '').replace(/\\s+/g, ' ');\n if (!wanted) return [];\n var tiers = [\n function (r) { return String(r.id).toLowerCase() === wanted; },\n function (r) { return labelOf(r).toLowerCase() === wanted; },\n function (r) { return labelOf(r).toLowerCase().indexOf(wanted) === 0; },\n function (r) { return (' ' + labelOf(r).toLowerCase() + ' ').indexOf(' ' + wanted + ' ') >= 0; },\n function (r) { return labelOf(r).toLowerCase().indexOf(wanted) >= 0; },\n function (r) { var l = labelOf(r).toLowerCase(); return l.length >= 3 && wanted.indexOf(l) >= 0; },\n ];\n for (var i = 0; i < tiers.length; i++) {\n var hit = records.filter(tiers[i]);\n if (hit.length) return hit;\n }\n return [];\n}\nfunction describe(records, labelOf) {\n return records.map(function (r) { return r.id + ' ' + labelOf(r); }).join(', ');\n}\nfunction splitList(text) {\n var raw = String(text == null ? '' : text).trim();\n if (/^\\[/.test(raw)) {\n try {\n var parsed = JSON.parse(raw);\n if (Array.isArray(parsed)) return parsed.map(function (s) { return String(s).trim(); }).filter(Boolean);\n } catch (e) {\n // Not JSON after all; split it as text.\n }\n }\n return raw\n .split(/\\s*[,;\\n]+\\s*/)\n .map(function (s) { return s.replace(/^(and|or|plus)\\s+/i, '').replace(/[.\\s]+$/, '').trim(); })\n .filter(Boolean);\n}\nfunction roleKey(text) {\n return String(text == null ? '' : text)\n .trim()\n .toLowerCase()\n .replace(/\\s+/g, ' ')\n .replace(/([a-z]{3,}[^s])s$/, '$1');\n}\nfunction requires(course, person) {\n var rf = String((course.fields && course.fields.requiredFor) || 'everyone').toLowerCase();\n if (!rf.trim() || /\\b(everyone|everybody|all|whole team|all staff)\\b/.test(rf)) return true;\n var mine = roleKey(person.fields && person.fields.role);\n if (!mine) return false;\n return splitList(rf).map(roleKey).some(function (r) {\n return r && (r === mine || mine.indexOf(r) >= 0 || r.indexOf(mine) >= 0);\n });\n}\nfunction eventsFor(events, kind, personId, courseId) {\n return events.filter(function (e) {\n return e.kind === kind && e.data && e.data.personId === personId && e.data.courseId === courseId;\n });\n}\nfunction cell(person, course, events, nowMs, windowDays) {\n var done = eventsFor(events, 'completed', person.id, course.id).sort(function (a, b) {\n return String(a.data.completedAt).localeCompare(String(b.data.completedAt));\n });\n var last = done.length ? done[done.length - 1] : null;\n // A booking made before the latest completion was recorded is used up by it.\n var since = last ? String(last.at) : '';\n var booking = eventsFor(events, 'booked', person.id, course.id)\n .filter(function (e) { return daysLeft(e.data.on, nowMs) >= 0 && String(e.at) > since; })\n .sort(function (a, b) { return String(a.data.on).localeCompare(String(b.data.on)); })[0] || null;\n var required = requires(course, person);\n var expiresAt = last ? last.data.expiresAt || null : null;\n var days = expiresAt ? daysLeft(expiresAt, nowMs) : null;\n var state;\n if (last) state = !expiresAt ? 'done' : days < 0 ? 'expired' : days <= windowDays ? 'expiring' : 'current';\n else state = required ? 'missing' : 'optional';\n if (!required && (state === 'expired' || state === 'expiring')) state = 'optional';\n return { state: state, required: required, last: last, booking: booking, expiresAt: expiresAt, days: days };\n}\nfunction needText(person, c, nowMs) {\n var f = person.fields || {};\n var starts = f.startedAt && daysLeft(f.startedAt, nowMs) > 0 ? ', starts ' + f.startedAt : '';\n var what =\n c.state === 'expired'\n ? 'lapsed ' + c.expiresAt + ', ' + -c.days + (c.days === -1 ? ' day ago' : ' days ago')\n : c.state === 'expiring'\n ? 'runs out ' + c.expiresAt + ', ' + (c.days === 0 ? 'today' : 'in ' + c.days + (c.days === 1 ? ' day' : ' days'))\n : 'never done';\n return f.name + ' (' + person.id + starts + ') ' + what + (c.booking ? ', booked ' + dayName(c.booking.data.on) + ' ' + c.booking.data.on : '');\n}\nfunction needs(people, course, events, nowMs, windowDays) {\n var rank = { expired: 0, missing: 1, expiring: 2 };\n return people\n .map(function (p) { return { person: p, cell: cell(p, course, events, nowMs, windowDays) }; })\n .filter(function (x) { return x.cell.required && rank[x.cell.state] !== undefined; })\n .sort(function (a, b) {\n return rank[a.cell.state] - rank[b.cell.state] || (a.cell.days === null ? 0 : a.cell.days) - (b.cell.days === null ? 0 : b.cell.days);\n });\n}\nfunction validity(course) {\n var m = Number(course.fields.validMonths) || 0;\n return m ? 'every ' + m + ' months' : 'once';\n}\nfunction picture(people, courses, events, nowMs, windowDays) {\n var staff = people.filter(function (p) { return p.status !== 'left'; });\n var live = courses.filter(function (c) { return c.status !== 'retired'; });\n var counts = { expired: 0, expiring: 0, missing: 0 };\n var parts = [];\n var lines = [];\n live.forEach(function (course) {\n var list = needs(staff, course, events, nowMs, windowDays);\n list.forEach(function (x) { counts[x.cell.state] += 1; });\n if (list.length) {\n lines.push(course.fields.title + ' (' + course.id + ', ' + validity(course) + '): ' + list.map(function (x) { return needText(x.person, x.cell, nowMs); }).join('; '));\n }\n });\n parts.push(\n staff.length + (staff.length === 1 ? ' person, ' : ' people, ') + live.length + (live.length === 1 ? ' course: ' : ' courses: ') +\n counts.expired + ' lapsed, ' + counts.expiring + ' running out within ' + windowDays + ' days, ' + counts.missing + ' never done.',\n );\n // One list per course, lapsed first: \"who needs the refresher this month\" is answered from its line alone.\n parts.push(lines.length ? 'Who needs what within ' + windowDays + ' days, by course, lapsed first: ' + lines.join(' | ') + '.' : 'Everyone is current for the next ' + windowDays + ' days.');\n var later = [];\n staff.forEach(function (p) {\n live.forEach(function (course) {\n var c = cell(p, course, events, nowMs, windowDays);\n if (c.required && c.state === 'current') later.push({ who: p.fields.name, what: course.fields.title, at: c.expiresAt });\n });\n });\n later.sort(function (a, b) { return String(a.at).localeCompare(String(b.at)); });\n if (later.length) parts.push('Next to run out after that: ' + later[0].who + \"'s \" + later[0].what + ' on ' + later[0].at + '.');\n return { expired: counts.expired, expiringSoon: counts.expiring, missing: counts.missing, people: staff.length, summary: parts.join(' ') };\n}\nfunction personLine(person, courses, events, nowMs, windowDays) {\n var f = person.fields || {};\n var items = courses\n .filter(function (c) { return c.status !== 'retired'; })\n .map(function (course) {\n var c = cell(person, course, events, nowMs, windowDays);\n if (!c.required && !c.last) return null;\n var cert = c.last && c.last.data.certificate ? ', ' + c.last.data.certificate : '';\n var text =\n c.state === 'missing'\n ? 'not done'\n : c.state === 'done'\n ? 'done ' + c.last.data.completedAt + cert\n : c.state + (c.expiresAt ? ' (valid until ' + c.expiresAt + ')' : '') + cert;\n return course.fields.title + ' ' + text + (c.booking ? ', booked ' + c.booking.data.on : '');\n })\n .filter(Boolean);\n return f.name + ' (' + person.id + ', ' + (f.role || 'no role') + (person.status === 'left' ? ', left' : '') + '): ' + (items.join('; ') || 'no courses apply');\n}\nfunction parseQuestions(text) {\n var raw = String(text == null ? '' : text).trim();\n var out = [];\n var skipped = [];\n function add(q, right, wrong) {\n q = String(q || '').trim();\n right = String(right || '').trim();\n wrong = (wrong || []).map(function (w) { return String(w).trim(); }).filter(Boolean);\n if (!q || !right) return false;\n var choices = [right].concat(wrong);\n var shift = out.length % choices.length;\n var rotated = choices.slice(choices.length - shift).concat(choices.slice(0, choices.length - shift));\n out.push({ q: q, choices: rotated, answer: shift });\n return true;\n }\n if (/^\\[/.test(raw)) {\n try {\n var parsed = JSON.parse(raw);\n if (Array.isArray(parsed)) {\n parsed.forEach(function (o, i) {\n if (!o || typeof o !== 'object') return skipped.push(i + 1);\n var right = o.answer || o.correct || o.right;\n var wrong = o.wrong || o.distractors || (o.options || o.choices || []).filter(function (c) { return c !== right; });\n if (!add(o.question || o.q, right, wrong)) skipped.push(i + 1);\n });\n return { questions: out, skipped: skipped };\n }\n } catch (e) {\n // Not JSON after all; read it line by line.\n }\n }\n raw.split(/\\r?\\n/).forEach(function (line, i) {\n var clean = line.replace(/^\\s*(?:q?\\d{1,2}[.):]|[-*])\\s*/i, '').trim();\n if (!clean) return;\n var parts = clean.split('|').map(function (s) { return s.trim(); });\n if (parts.length < 2) {\n var qa = clean.match(/^(.+?\\?)\\s*(?:answer|a)?\\s*[:=-]+\\s*(.+)$/i);\n if (qa) parts = [qa[1], qa[2]];\n }\n if (parts.length < 2 || !add(parts[0], parts[1], parts.slice(2))) skipped.push(i + 1);\n });\n return { questions: out, skipped: skipped };\n}\n// ── training-rules-end ──\n\nconst people = rosterStore(gezel.fs, 'people.json', { stages: ['active', 'left'], idPrefix: 'p' });\nconst courses = rosterStore(gezel.fs, 'courses.json', { stages: ['active', 'retired'], idPrefix: 'c' });\nconst log = logStore(gezel.fs, 'completions.json');\nconst quizzes = rosterStore(gezel.fs, 'quizzes.json', { stages: ['ready', 'retired'], idPrefix: 'qz' });\nconst now = Date.now();\nconst withinDays = typeof input.withinDays === 'number' && input.withinDays > 0 ? Math.round(input.withinDays) : 30;\nconst nameOf = (r: { fields: Record<string, unknown> }) => String(r.fields.name ?? '');\nconst titleOf = (r: { fields: Record<string, unknown> }) => String(r.fields.title ?? '');\n\nasync function resolveCourse(text?: string) {\n const all = await courses.list();\n if (!text) throw new Error(\"Pass 'course' (id or title). Courses: \" + (describe(all, titleOf) || 'none yet; add one with add_course') + '.');\n let hits = matches(all.filter((c) => c.status !== 'retired'), text, titleOf);\n if (!hits.length) hits = matches(all, text, titleOf);\n if (hits.length === 1) return hits[0]!;\n if (hits.length > 1) throw new Error(\"More than one course matches '\" + text + \"': \" + describe(hits, titleOf) + '. Pass the id.');\n throw new Error(\"No course matches '\" + text + \"'. Courses: \" + (describe(all, titleOf) || 'none yet; add one with add_course') + '.');\n}\n\nasync function resolvePeople(text?: string) {\n const all = await people.list();\n if (!text) throw new Error(\"Pass 'person': a name or id, or several separated by commas.\");\n const wanted = String(text).split(/\\s*(?:,|;|&|\\band\\b)\\s*/i).map((s) => s.trim()).filter(Boolean);\n const found: typeof all = [];\n for (const one of wanted) {\n let hits = matches(all.filter((p) => p.status !== 'left'), one, nameOf);\n if (!hits.length) hits = matches(all, one, nameOf);\n if (hits.length > 1) throw new Error(\"More than one person matches '\" + one + \"': \" + describe(hits, nameOf) + '. Pass the id.');\n if (!hits.length) throw new Error(\"No person matches '\" + one + \"'. People: \" + (describe(all, nameOf) || 'none yet; add them with add_person') + '.');\n if (!found.some((p) => p.id === hits[0]!.id)) found.push(hits[0]!);\n }\n return found;\n}\n\n// The tracker's one reminder sits on the next certificate to run out, 14 days ahead of it.\nasync function remindNextExpiry(): Promise<void> {\n const lead = 14 * DAY_MS;\n const staff = (await people.list()).filter((p) => p.status !== 'left');\n const live = (await courses.list()).filter((c) => c.status !== 'retired');\n const events = await log.list();\n const upcoming: Array<{ title: string; body: string; at: number }> = [];\n for (const p of staff) {\n for (const course of live) {\n const c = cell(p, course, events, now, withinDays);\n if (!c.required || !c.expiresAt || c.booking) continue;\n const at = Date.parse(String(c.expiresAt) + 'T09:00:00') - lead;\n if (at > now) {\n upcoming.push({\n at,\n title: (nameOf(p) + \"'s \" + titleOf(course)).slice(0, 56) + ' runs out in two weeks',\n body: 'Valid until ' + c.expiresAt + '. Book the refresher from the training tracker.',\n });\n }\n }\n }\n const next = upcoming.sort((a, b) => a.at - b.at)[0];\n try {\n if (!next || next.at - now > 30 * DAY_MS) await gezel.reminder.clear();\n else await gezel.reminder.set({ at: new Date(next.at).toISOString(), title: next.title, body: next.body });\n } catch {\n // Reminders are a convenience; the tracker is the record.\n }\n}\n\nlet note = '';\n\nif (input.action === 'add_person') {\n if (!input.name || !input.name.trim()) throw new Error(\"add_person needs 'name'.\");\n const name = input.name.trim();\n const startedAt = input.startedAt ? parseDay(input.startedAt, now, 'future') : null;\n if (input.startedAt && !startedAt) throw new Error(\"startedAt must be a date like '2026-11-09' or a weekday like 'monday'.\");\n const status = input.personStatus ? String(input.personStatus).trim().toLowerCase() : '';\n if (status && status !== 'active' && status !== 'left') throw new Error(\"personStatus must be 'active' or 'left'.\");\n const fields: Record<string, unknown> = {\n ...(input.role ? { role: input.role.trim() } : {}),\n ...(startedAt ? { startedAt } : {}),\n ...(input.note ? { notes: input.note.trim() } : {}),\n };\n const existing = (await people.list()).find((p) => nameOf(p).toLowerCase() === name.toLowerCase());\n if (existing) {\n await people.update(existing.id, { fields });\n if (status && status !== existing.status) await people.transition(existing.id, status);\n note = 'Updated ' + name + ' (' + existing.id + ')' + (status === 'left' ? '; they are off the matrix now.' : '.');\n } else {\n const record = await people.add({ status: status || 'active', fields: { name, role: '', ...fields } });\n const needed = (await courses.list()).filter((c) => c.status !== 'retired' && requires(c, record));\n note = 'Added ' + name + ' (' + record.id + ')' + (needed.length ? '; they need ' + needed.map(titleOf).join(', ') + '.' : '.');\n }\n} else if (input.action === 'add_course') {\n if (!input.title || !input.title.trim()) throw new Error(\"add_course needs 'title'.\");\n const title = input.title.trim();\n let validMonths: number | undefined;\n if (input.validMonths !== undefined) {\n validMonths = Math.round(Number(input.validMonths));\n if (!(validMonths >= 0)) throw new Error('validMonths must be 0 (never expires) or more.');\n }\n const fields: Record<string, unknown> = {\n ...(validMonths !== undefined ? { validMonths } : {}),\n ...(input.requiredFor ? { requiredFor: input.requiredFor.trim() } : {}),\n ...(input.provider ? { provider: input.provider.trim() } : {}),\n ...(input.note ? { notes: input.note.trim() } : {}),\n };\n const existing = (await courses.list()).find((c) => titleOf(c).toLowerCase() === title.toLowerCase());\n if (existing) {\n await courses.update(existing.id, { fields });\n note = 'Updated ' + title + ' (' + existing.id + ').';\n } else {\n const record = await courses.add({ status: 'active', fields: { title, validMonths: 0, requiredFor: 'everyone', ...fields } });\n note = 'Added ' + title + ' (' + record.id + '), ' + validity(record) + ', for ' + String(record.fields.requiredFor) + '.';\n }\n} else if (input.action === 'complete') {\n const course = await resolveCourse(input.course);\n const who = await resolvePeople(input.person);\n const completedAt = input.completedAt ? parseDay(input.completedAt, now, 'past') : localDay(now);\n if (!completedAt) throw new Error(\"completedAt must be a date like '2026-11-02', or 'today'.\");\n const months = Number(course.fields.validMonths) || 0;\n const expiresAt = months > 0 ? addMonths(completedAt, months) : null;\n const certificate = input.certificate ? input.certificate.trim() : '';\n for (const p of who) {\n await log.append({\n kind: 'completed',\n note: input.note ? input.note.trim() : certificate ? 'Certificate ' + certificate + '.' : 'Completed.',\n data: { personId: p.id, courseId: course.id, completedAt, expiresAt, ...(certificate ? { certificate } : {}) },\n });\n }\n note =\n who.map(nameOf).join(', ') + ' completed ' + titleOf(course) + ' on ' + completedAt +\n (expiresAt ? '; valid until ' + expiresAt : '; it does not expire') + (certificate ? ', certificate ' + certificate : '') + '.';\n} else if (input.action === 'book') {\n const course = await resolveCourse(input.course);\n const on = parseDay(input.on, now, 'future');\n if (!on) throw new Error(\"book needs 'on': a date like '2026-11-12' or a weekday like 'thursday'.\");\n const events = await log.list();\n let who: Awaited<ReturnType<typeof resolvePeople>> = [];\n if (input.everyoneDue) {\n const staff = (await people.list()).filter((p) => p.status !== 'left');\n who = needs(staff, course, events, now, withinDays).filter((x: { cell: { booking: unknown } }) => !x.cell.booking).map((x: { person: (typeof staff)[number] }) => x.person);\n } else {\n who = await resolvePeople(input.person);\n }\n const fresh = who.filter((p) => !eventsFor(events, 'booked', p.id, course.id).some((e: { data: { on: string } }) => e.data.on === on));\n for (const p of fresh) {\n await log.append({ kind: 'booked', note: input.note ? input.note.trim() : 'Booked.', data: { personId: p.id, courseId: course.id, on } });\n }\n note = fresh.length\n ? 'Booked ' + titleOf(course) + ' on ' + dayName(on) + ' ' + on + ' for ' + fresh.map(nameOf).join(', ') + '.'\n : input.everyoneDue\n ? 'Nobody else needs ' + titleOf(course) + ' within ' + withinDays + ' days; nothing new booked.'\n : 'Already booked; nothing changed.';\n} else if (input.action === 'save_quiz') {\n if (!input.questions) throw new Error(\"save_quiz needs 'questions', one per line: 'Question? | right answer | wrong answer | wrong answer'.\");\n const parsed = parseQuestions(input.questions);\n if (parsed.questions.length < 3) {\n throw new Error(\"A quiz needs at least 3 questions, one per line: 'Question? | right answer | wrong answer | wrong answer'. Read \" + parsed.questions.length + '.');\n }\n const course = input.course ? await resolveCourse(input.course) : null;\n const title = (input.title && input.title.trim()) || (course ? titleOf(course) + ' quiz' : 'Quiz');\n const fields: Record<string, unknown> = {\n title,\n questions: parsed.questions,\n ...(course ? { courseId: course.id, courseTitle: titleOf(course) } : {}),\n ...(input.source ? { source: input.source.trim() } : {}),\n };\n const existing = (await quizzes.list()).find((q) => titleOf(q).toLowerCase() === title.toLowerCase());\n if (existing) await quizzes.update(existing.id, { fields });\n else await quizzes.add({ status: 'ready', fields });\n note =\n 'Saved the quiz ' + title + ' with ' + parsed.questions.length + ' questions' + (course ? ' for ' + titleOf(course) : '') +\n (parsed.skipped.length ? '; skipped line ' + parsed.skipped.join(', ') + \" (write them as 'Question? | right | wrong | wrong')\" : '') + '.';\n} else if (input.action !== 'status' && input.action !== 'list') {\n throw new Error(\"Unknown action '\" + input.action + \"'. Use status, add_person, add_course, complete, book, save_quiz, or list.\");\n}\n\nconst allPeople = await people.list();\nconst allCourses = await courses.list();\nconst events = await log.list();\nconst view = picture(allPeople, allCourses, events, now, withinDays);\nawait remindNextExpiry();\n\nlet summary = (note ? note + ' ' : '') + view.summary;\nif (input.action === 'list') {\n const wanted = input.person ? await resolvePeople(input.person) : allPeople;\n summary = wanted.map((p) => personLine(p, allCourses, events, now, withinDays)).join('\\n') || 'Nobody on the tracker yet.';\n}\ngezel.output({ expired: view.expired, expiringSoon: view.expiringSoon, missing: view.missing, people: view.people, summary });\n"},"tools":[{"name":"training_status","description":"Who needs which course within the next 30 days, one list per course with lapsed certificates first, then training never done, then certificates about to run out, each with person and course ids and any booking. Call it first when asked who needs a course, what is expiring, or where someone stands.","script":"training-store","inputs":{"type":"object","properties":{"withinDays":{"type":"number"}}},"bind":{"action":"status"},"state":true},{"name":"add_person","description":"Add someone to the training tracker or update them: full name, job role (it decides which courses they need) and first day. An existing name is updated, never duplicated. Call it as soon as a new person is mentioned, before you describe them. Use personStatus 'left' when someone leaves.","script":"training-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"role":{"type":"string"},"startedAt":{"type":"string"},"personStatus":{"type":"string","enum":["active","left"]},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"add_person"}},{"name":"add_course","description":"Add or update a course or certificate the business tracks: title, months it stays valid (0 if it never expires), who needs it ('everyone' or roles such as 'barista, cook') and the provider. An existing title is updated, never duplicated. Call it as soon as a course is mentioned.","script":"training-store","inputs":{"type":"object","properties":{"title":{"type":"string"},"validMonths":{"type":"number"},"requiredFor":{"type":"string"},"provider":{"type":"string"},"note":{"type":"string"}},"required":["title"]},"bind":{"action":"add_course"}},{"name":"record_completion","description":"Record that one or more people finished a course: person (a name, or several separated by commas), course, the day (default today) and the certificate number exactly as given. The expiry date is worked out from the course. Call it the moment the person reports it, before you reply.","script":"training-store","inputs":{"type":"object","properties":{"person":{"type":"string"},"course":{"type":"string"},"completedAt":{"type":"string"},"certificate":{"type":"string"},"note":{"type":"string"}},"required":["person","course"]},"bind":{"action":"complete"}},{"name":"book_training","description":"Book a session: course, the date (YYYY-MM-DD or a weekday like 'thursday', which the tracker turns into the date), and either person (one or several, comma-separated) or everyoneDue: true for everyone whose certificate has lapsed, runs out within 30 days, or was never done. Call it as soon as the person asks.","script":"training-store","inputs":{"type":"object","properties":{"course":{"type":"string"},"on":{"type":"string"},"person":{"type":"string"},"everyoneDue":{"type":"boolean"},"note":{"type":"string"}},"required":["course","on"]},"bind":{"action":"book"}},{"name":"save_quiz","description":"Save a short quiz written from the business's own document: title, the course it supports, the source document, and questions, one per line as 'Question? | right answer | wrong answer | wrong answer'. Read the document first and quote it accurately. An existing title is replaced.","script":"training-store","inputs":{"type":"object","properties":{"title":{"type":"string"},"course":{"type":"string"},"source":{"type":"string"},"questions":{"type":"string"}},"required":["questions"]},"bind":{"action":"save_quiz"}},{"name":"list_training","description":"Everyone's training, or one person's: each course they need with its status, dates, certificate and booking.","script":"training-store","inputs":{"type":"object","properties":{"person":{"type":"string"}}},"bind":{"action":"list"}},{"name":"page_add_person","description":"Add or update a person.","script":"training-store","inputs":{"type":"object","properties":{"name":{"type":"string"},"role":{"type":"string"},"startedAt":{"type":"string"},"personStatus":{"type":"string","enum":["active","left"]},"note":{"type":"string"}},"required":["name"]},"bind":{"action":"add_person"}},{"name":"page_add_course","description":"Add or update a course.","script":"training-store","inputs":{"type":"object","properties":{"title":{"type":"string"},"validMonths":{"type":"number"},"requiredFor":{"type":"string"},"provider":{"type":"string"},"note":{"type":"string"}},"required":["title"]},"bind":{"action":"add_course"}},{"name":"page_record_completion","description":"Record a completion.","script":"training-store","inputs":{"type":"object","properties":{"person":{"type":"string"},"course":{"type":"string"},"completedAt":{"type":"string"},"certificate":{"type":"string"},"note":{"type":"string"}},"required":["person","course"]},"bind":{"action":"complete"}},{"name":"page_book_training","description":"Book a session.","script":"training-store","inputs":{"type":"object","properties":{"course":{"type":"string"},"on":{"type":"string"},"person":{"type":"string"},"everyoneDue":{"type":"boolean"},"note":{"type":"string"}},"required":["course","on"]},"bind":{"action":"book"},"reaction":{"gezel":"training-coordinator","prompt":"The person just booked a session on the training page. The tracker now reads (its first sentence is what changed):\n{{output.summary}}\nIn two short sentences, confirm who is booked and when, then name anyone who still needs that course and is not booked. Do not call tools.","hideSeed":true}}],"pages":{"imports":[{"id":"docs","source":"workspace","path":"docs","accept":[".md",".txt",".pdf",".docx",".png",".jpg",".jpeg",".webp",".heic"],"maxFileBytes":26214400}],"entry":"tracker/index.html","api":1,"reads":[{"source":"workspace","path":"people.json"},{"source":"workspace","path":"courses.json"},{"source":"workspace","path":"completions.json"},{"source":"workspace","path":"quizzes.json"},{"source":"workspace","path":"docs","subtree":true}],"tools":["page_add_person","page_add_course","page_record_completion","page_book_training"]},"schedules":[],"workspaceSeed":["people.json","courses.json","completions.json","quizzes.json"],"artifactsSeed":[],"availableVersions":["1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"trip-planner","name":"Trip Planner","description":"Plan a trip you'll actually be present for. A trip planner builds the day-by-day itinerary with slack in it, keeps the packing list checkable on a live board, and helps the journal happen.","tags":["travel","trip","itinerary","packing","journal"],"category":"events","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","version":"1.0.6","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"destination":{"type":"string","title":"Where to?","description":"e.g. 'Kyoto', 'the Scottish Highlands'.","default":"somewhere wonderful"},"start":{"type":"string","title":"Departure date","description":"e.g. 2026-09-12. A rough date is fine.","default":"2026-12-01"},"travellers":{"type":"string","title":"Who's going?","description":"e.g. '4', or 'two adults and a toddler'. Leave empty if you're not sure yet.","default":""}},"required":["destination","start"]},"nameTemplate":"Trip: {{destination}}","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"reisleider","voorman":true}],"toolsets":[],"craftbooks":["pre-departure-countdown"],"scripts":{"trip-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { logStore, rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'trip-store',\n description:\n \"Read and update the trip: itinerary + packing (trip.json) and the journal (journal.json). Call action:'status' for the shape of the trip; 'set_trip' with start / travellers / destination as the traveler tells you; 'plan_day' with date + plan; 'pack_add' / 'pack_check' for the packing list; 'journal_entry' during the trip.\",\n inputs: {\n action: {\n type: 'string',\n description:\n \"One of 'status', 'set_trip', 'plan_day', 'pack_add', 'pack_check', 'journal_entry', or 'itinerary'.\",\n required: true,\n },\n date: {\n type: 'string',\n description: \"The day being planned: 2026-09-14 once the dates are known, otherwise 'Day 1', 'Day 2', ...\",\n },\n plan: {\n type: 'string',\n description:\n \"The day in plain sentences, one per line: what the day is for, then a couple of alternatives, then the free time. No 'Anchor:' or 'Options:' labels.\",\n },\n start: {\n type: 'string',\n description: \"The departure date they gave: 2026-09-12 when they named a day, otherwise their words ('next spring'). Never choose one for them.\",\n },\n travellers: { type: 'string', description: \"Who is going: a number ('4') or a phrase ('two adults and a toddler').\" },\n joining: {\n type: 'string',\n description: \"Who joins the existing party: a name ('Marta') or a count ('2'). Added to whoever is already going.\",\n },\n destination: { type: 'string', description: 'Where the trip goes.' },\n item: { type: 'string', description: 'Packing item name.' },\n id: { type: 'string', description: \"Packing item id, e.g. 'pack-3'.\" },\n note: { type: 'string', description: 'Journal entry text.' },\n },\n outputs: {\n daysPlanned: { type: 'number', description: 'Days with a plan.' },\n unpacked: { type: 'number', description: 'Packing items still unpacked.' },\n summary: { type: 'string', description: 'The trip picture (or the itinerary).' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── trip-rules-start ──\n// Pure derivations over the trip doc: countdown, day keys and itinerary rendering.\n\nfunction plural(n, one, many) {\n return n + ' ' + (n === 1 ? one : many);\n}\n\nfunction daysUntil(dateStr, nowMs) {\n if (!/^\\d{4}-\\d{2}-\\d{2}/.test(String(dateStr || ''))) return null;\n var when = Date.parse(dateStr);\n if (!isFinite(when)) return null;\n return Math.ceil((when - nowMs) / (24 * 60 * 60 * 1000));\n}\n\n// \"2026-09-14T10:00\" -> \"2026-09-14\"; \"day 3\" / \"Day3\" / \"3\" -> \"Day 3\".\nfunction dayKey(raw) {\n var text = String(raw || '').trim();\n var iso = text.match(/^\\d{4}-\\d{2}-\\d{2}/);\n if (iso) return iso[0];\n var numbered = text.match(/^(?:day\\s*)?(\\d{1,3})$/i);\n if (numbered) return 'Day ' + Number(numbered[1]);\n return text;\n}\n\n// Numbered days sort by number (\"Day 10\" after \"Day 9\"); dates sort as text.\nfunction sortedDays(days) {\n return Object.keys(days).sort(function (a, b) {\n var na = a.match(/^Day (\\d+)$/);\n var nb = b.match(/^Day (\\d+)$/);\n if (na && nb) return Number(na[1]) - Number(nb[1]);\n return a < b ? -1 : a > b ? 1 : 0;\n });\n}\n\n// \"4 people\" / \"4 travellers\" -> \"4\", so the board can say \"4 travelers\";\n// a phrase (\"two adults and a toddler\") is kept as written.\nfunction partyCount(raw) {\n var text = String(raw || '').trim();\n var counted = text.match(/^(\\d{1,3})\\s*(?:people|persons|travell?ers|adults|guests|of us)?$/i);\n if (counted) return String(Number(counted[1]));\n // \"4 travelers + Marta\", \"4 plus 2\": whoever joins a numbered party adds to it.\n var joined = text.match(/^(\\d{1,3})\\s*(?:people|persons|travell?ers|adults|guests|of us)?\\s*(?:\\+|plus)\\s*(.+)$/i);\n if (!joined) return text;\n var extra = /^\\d{1,3}$/.test(joined[2].trim())\n ? Number(joined[2].trim())\n : joined[2].split(/\\s*(?:,|&|\\band\\b|\\+)\\s*/i).filter(Boolean).length;\n return String(Number(joined[1]) + extra);\n}\n\nfunction joinParty(current, joining) {\n var who = String(joining || '').trim();\n var party = String(current || '').trim();\n if (!who) return party;\n if (!party) return partyCount(who);\n if (/^\\d+$/.test(party)) return partyCount(party + ' + ' + who);\n return party + ', plus ' + who;\n}\n\nfunction travellersLine(travellers) {\n var text = String(travellers || '').trim();\n if (!text) return '';\n if (/^\\d+$/.test(text)) return plural(Number(text), 'traveler', 'travelers');\n return text;\n}\n\nfunction renderItinerary(days) {\n var keys = sortedDays(days);\n if (keys.length === 0) return 'No days planned yet.';\n return keys\n .map(function (d) {\n return d + ': ' + days[d];\n })\n .join('\\n');\n}\n\nfunction tripLine(trip, unpackedCount, nowMs) {\n var start = daysUntil(trip.startDate, nowMs);\n var planned = Object.keys(trip.days || {}).length;\n var who = travellersLine(trip.travellers);\n var lead =\n start === null\n ? trip.startDate && trip.startDate !== 'soon'\n ? 'Leaving ' + trip.startDate + '. '\n : 'No departure date yet. '\n : start > 0\n ? plural(start, 'day', 'days') + ' until departure. '\n : start === 0\n ? 'Departure day! '\n : 'On the road (or home again). ';\n return (\n (who ? who + '. ' : '') +\n lead +\n plural(planned, 'day', 'days') + ' planned. Packing: ' +\n (unpackedCount === 0 ? 'all packed.' : plural(unpackedCount, 'item', 'items') + ' still unpacked.')\n );\n}\n// ── trip-rules-end ──\n\nconst TRIP_FILE = 'trip.json';\nconst packing = rosterStore(gezel.fs, 'packing.json', {\n stages: ['unpacked', 'packed'],\n idPrefix: 'pack',\n});\nconst journal = logStore(gezel.fs, 'journal.json');\n\ninterface Trip {\n version: number;\n destination: string;\n startDate: string;\n travellers: string;\n days: Record<string, string>;\n updatedAt: string;\n}\n\nasync function loadTrip(): Promise<Trip> {\n try {\n const parsed = JSON.parse(await gezel.fs.read(TRIP_FILE)) as Partial<Trip>;\n return {\n version: 1,\n destination: typeof parsed.destination === 'string' ? parsed.destination : '',\n startDate: typeof parsed.startDate === 'string' ? parsed.startDate : '',\n travellers: typeof parsed.travellers === 'string' ? parsed.travellers : '',\n days: parsed.days && typeof parsed.days === 'object' ? (parsed.days as Record<string, string>) : {},\n updatedAt: new Date().toISOString(),\n };\n } catch {\n return {\n version: 1,\n destination: '',\n startDate: '',\n travellers: '',\n days: {},\n updatedAt: new Date().toISOString(),\n };\n }\n}\n\nasync function saveTrip(trip: Trip): Promise<void> {\n trip.updatedAt = new Date().toISOString();\n await gezel.fs.write(TRIP_FILE, `${JSON.stringify(trip, null, 2)}\\n`);\n}\n\nconst trip = await loadTrip();\n\nif (input.action === 'set_trip') {\n if (!input.start && !input.travellers && !input.joining && !input.destination) {\n throw new Error(\"set_trip needs at least one of 'start', 'travellers', 'joining', or 'destination'.\");\n }\n if (input.start) trip.startDate = input.start.trim();\n if (input.travellers) trip.travellers = partyCount(input.travellers);\n if (input.joining) trip.travellers = joinParty(trip.travellers, input.joining);\n if (input.destination) trip.destination = input.destination.trim();\n await saveTrip(trip);\n} else if (input.action === 'plan_day') {\n if (!input.date || !input.plan) throw new Error(\"plan_day needs 'date' (YYYY-MM-DD, or 'Day 1') and 'plan'.\");\n trip.days[dayKey(input.date)] = input.plan;\n await saveTrip(trip);\n} else if (input.action === 'pack_add') {\n if (!input.item) throw new Error(\"pack_add needs 'item'.\");\n await packing.add({ status: 'unpacked', fields: { name: input.item } });\n} else if (input.action === 'pack_check') {\n let id = input.id;\n if (!id && input.item) {\n const wanted = input.item.toLowerCase();\n const matches = (await packing.list()).filter(\n (r) => String(r.fields.name ?? '').toLowerCase() === wanted,\n );\n if (matches.length === 1) id = matches[0]!.id;\n }\n if (!id) throw new Error(\"Pass 'id' (e.g. 'pack-3') or an exact packing 'item'.\");\n await packing.transition(id, 'packed');\n} else if (input.action === 'journal_entry') {\n if (!input.note) throw new Error(\"journal_entry needs 'note'.\");\n await journal.append({ kind: 'entry', note: input.note });\n} else if (input.action !== 'status' && input.action !== 'itinerary') {\n throw new Error(\n `Unknown action '${input.action}'. Use status, set_trip, plan_day, pack_add, pack_check, journal_entry, or itinerary.`,\n );\n}\n\nconst packItems = await packing.list();\nconst unpacked = packItems.filter((r) => r.status === 'unpacked').length;\n\ngezel.output({\n daysPlanned: Object.keys(trip.days).length,\n unpacked,\n summary:\n input.action === 'itinerary' ? renderItinerary(trip.days) : tripLine(trip, unpacked, Date.now()),\n});\n"},"tools":[{"name":"set_trip","description":"Change the trip's details: the departure date, who is going, or the destination. When someone joins, pass their name as joining and the trip adds them to the party; pass travellers only to replace the whole party. Record their words; never choose a date for them.","script":"trip-store","inputs":{"type":"object","properties":{"start":{"type":"string","description":"The departure date they gave: YYYY-MM-DD when they named a day, otherwise their words ('next spring')."},"travellers":{"type":"string","description":"The whole party after the change: a number (\"5\") or a phrase (\"two adults and a toddler\"), never just the newcomer."},"destination":{"type":"string"},"joining":{"type":"string","description":"Who joins the existing party: a name ('Marta') or a count ('2'). The trip adds them to whoever is already going."}}},"bind":{"action":"set_trip"}},{"name":"plan_day","description":"Set one day's plan in plain sentences, one per line: what the day is for, then a couple of alternatives, then the free time. Use the date (YYYY-MM-DD) once it is known, otherwise 'Day 1', 'Day 2', … Never write 'Anchor:' or 'Options:' labels.","script":"trip-store","inputs":{"type":"object","properties":{"date":{"type":"string","description":"YYYY-MM-DD, or 'Day 1' when the dates are not set yet."},"plan":{"type":"string","description":"The day in plain sentences, one per line."}},"required":["date","plan"]},"bind":{"action":"plan_day"}},{"name":"pack_add","description":"Add an item to the packing list.","script":"trip-store","inputs":{"type":"object","properties":{"item":{"type":"string"}},"required":["item"]},"bind":{"action":"pack_add"}},{"name":"pack_check","description":"Mark an item packed.","script":"trip-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"item":{"type":"string"}}},"bind":{"action":"pack_check"}},{"name":"journal_entry","description":"Capture a trip moment — a line a day.","script":"trip-store","inputs":{"type":"object","properties":{"note":{"type":"string"}},"required":["note"]},"bind":{"action":"journal_entry"}},{"name":"trip_status","description":"Who is going, the countdown, days planned, and the packing state.","script":"trip-store","inputs":{"type":"object","properties":{}},"bind":{"action":"status"}},{"name":"itinerary","description":"Read the full day-by-day itinerary.","script":"trip-store","inputs":{"type":"object","properties":{}},"bind":{"action":"itinerary"}},{"name":"mark_packed","description":"The dashboard's packing checkbox.","script":"trip-store","inputs":{"type":"object","properties":{"id":{"type":"string"}},"required":["id"]},"bind":{"action":"pack_check"}},{"name":"page_plan_day","description":"Set one day's plan in plain sentences, one per line: what the day is for, then a couple of alternatives, then the free time. Use the date (YYYY-MM-DD) once it is known, otherwise 'Day 1', 'Day 2', … Never write 'Anchor:' or 'Options:' labels.","script":"trip-store","inputs":{"type":"object","properties":{"date":{"type":"string","description":"YYYY-MM-DD, or 'Day 1' when the dates are not set yet."},"plan":{"type":"string","description":"The day in plain sentences, one per line."}},"required":["date","plan"]},"bind":{"action":"plan_day"}},{"name":"page_pack_add","description":"Add an item to the packing list.","script":"trip-store","inputs":{"type":"object","properties":{"item":{"type":"string"}},"required":["item"]},"bind":{"action":"pack_add"}},{"name":"page_journal_entry","description":"Capture a trip moment — a line a day.","script":"trip-store","inputs":{"type":"object","properties":{"note":{"type":"string"}},"required":["note"]},"bind":{"action":"journal_entry"}}],"pages":{"entry":"dashboard/index.html","api":1,"reads":[{"source":"workspace","path":"trip.json"},{"source":"workspace","path":"packing.json"},{"source":"workspace","path":"journal.json"}],"tools":["mark_packed","page_plan_day","page_pack_add","page_journal_entry"]},"schedules":[],"workspaceSeed":["trip.json","packing.json","journal.json"],"artifactsSeed":[],"availableVersions":["1.0.6","1.0.5","1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"vendor-contracts","name":"Vendor & Contract Desk","description":"Keep your vendors and contracts, with their renewal dates, in one place. An office administrator tracks what each contract costs a year, when its term ends, how much notice it needs and whether it renews on its own, and reminds you two weeks before a notice date.","tags":["vendors","contracts","agreements","suppliers","renewals","small-business"],"category":"business","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.0.0","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"params":{"type":"object","properties":{"business":{"type":"string","title":"What kind of business is this?","description":"e.g. 'a café in Portland', 'a six-person design studio'.","default":"the business"}},"required":["business"]},"nameTemplate":"Vendor & Contract Desk","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"kantoormeester","voorman":true},{"templateId":"reviewer","voorman":false}],"toolsets":[],"craftbooks":["subscription-audit","comparison-matrix","contract-template"],"scripts":{"contracts-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'contracts-store',\n description:\n \"Read and update the vendor and contract desk (contracts.json and vendors.json). action:'status' for what needs deciding (notice dates and automatic renewals, missed ones first) and yearly spend; 'add' to save a contract (an existing id or title is updated, never duplicated; percentChange and monthlyChange adjust its price); 'renew' when one was renewed; 'cancel' when notice was given; 'set_status' to mark one under review, active again, or ended; 'add_vendor' to save a vendor; 'attach_file' to link a contract file under contract-files/; 'list' for every contract and vendor.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'status', 'add', 'renew', 'cancel', 'set_status', 'add_vendor', 'attach_file', or 'list'.\",\n required: true,\n },\n id: { type: 'string', description: \"Contract id, e.g. 'ct-3'.\" },\n title: {\n type: 'string',\n description: \"The contract's name, e.g. 'Linen service'. Also finds it when no id is given.\",\n },\n vendor: { type: 'string', description: 'The vendor or supplier, e.g. Bayside Linen. Also finds its contract.' },\n category: {\n type: 'string',\n description: 'food, supplies, linen, equipment, software, utilities, services, premises, insurance, or other.',\n },\n endAt: {\n type: 'string',\n description: 'When the current term ends, YYYY-MM-DD (for month-to-month, the next billing date). For renew: the new end date.',\n },\n autoRenew: { type: 'string', description: 'yes when it renews on its own unless notice is given, otherwise no.' },\n renewMonths: { type: 'number', description: 'Length of each term in months (default 12; 1 for month-to-month).' },\n noticeDays: { type: 'number', description: 'Days of notice needed before the end date to cancel or change it.' },\n annualCost: { type: 'number', description: 'What it costs a year, in dollars.' },\n monthlyCost: { type: 'number', description: 'What it costs a month, in dollars (kept as a yearly cost).' },\n percentChange: { type: 'number', description: 'A price change in percent: 6 for a 6% increase, -10 for a 10% cut.' },\n monthlyChange: { type: 'number', description: 'A price change in dollars a month: 40 for $40 more a month.' },\n owner: { type: 'string', description: 'Who looks after it.' },\n contact: { type: 'string', description: \"For add_vendor: the vendor's contact, phone or email.\" },\n status: { type: 'string', description: 'For set_status: active, reviewing, or ended.' },\n note: { type: 'string', description: 'What happened, with any reference number exactly as written.' },\n file: { type: 'string', description: \"Workspace path of a contract file, e.g. 'contract-files/linen-2026.pdf'.\" },\n withinDays: { type: 'number', description: 'How many days ahead counts as coming up (default 90).' },\n },\n outputs: {\n decisionsDue: { type: 'number', description: 'Contracts needing attention within the window.' },\n autoRenewWarnings: { type: 'number', description: 'Contracts that renew on their own whose notice date is near or already passed.' },\n annualSpend: { type: 'number', description: 'Yearly spend across live contracts, in dollars.' },\n contracts: { type: 'number', description: 'Contracts on the desk.' },\n summary: { type: 'string', description: 'The desk picture, or the listing.' },\n },\n requires: ['workspace.read', 'workspace.write', 'reminders'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── contracts-rules-start ──\n// Pure derivations: a contract's current term end (one that renews on its own\n// and passed its end date has renewed itself), its notice date, what it needs\n// now, and the desk line the crew reads. Kept self-contained between these\n// sentinels so unit tests execute the shipped bytes.\nvar DAY_MS = 86400000;\nvar WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\nvar MONTH_KEYS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];\n\nfunction pad(n) {\n return n < 10 ? '0' + n : String(n);\n}\nfunction localDay(ms) {\n var d = new Date(ms);\n return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());\n}\nfunction noon(day) {\n return new Date(String(day).slice(0, 10) + 'T12:00:00');\n}\nfunction addDays(day, n) {\n var d = noon(day);\n d.setDate(d.getDate() + n);\n return localDay(d.getTime());\n}\nfunction addMonths(day, months) {\n var d = noon(day);\n var date = d.getDate();\n d.setDate(1);\n d.setMonth(d.getMonth() + months);\n // The 31st rolls to the last day of a shorter month, not into the next one.\n d.setDate(Math.min(date, new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate()));\n return localDay(d.getTime());\n}\nfunction daysLeft(day, nowMs) {\n var due = Date.parse(String(day).slice(0, 10) + 'T00:00:00');\n var today = Date.parse(localDay(nowMs) + 'T00:00:00');\n return Math.round((due - today) / DAY_MS);\n}\nfunction dayName(day) {\n return WEEKDAYS[noon(day).getDay()];\n}\nfunction parseDay(text, nowMs, direction) {\n var raw = String(text == null ? '' : text).trim().toLowerCase().replace(/[.,]/g, ' ').replace(/\\s+/g, ' ').trim();\n if (!raw) return null;\n var iso = raw.match(/^(\\d{4})-(\\d{1,2})-(\\d{1,2})(?:t.*)?$/);\n if (iso) return iso[1] + '-' + pad(Number(iso[2])) + '-' + pad(Number(iso[3]));\n var today = localDay(nowMs);\n if (raw === 'today' || raw === 'now') return today;\n if (raw === 'tomorrow') return addDays(today, 1);\n if (raw === 'yesterday') return addDays(today, -1);\n var rel = raw.match(/^(?:in )?(\\d{1,3}) (day|days|week|weeks)( ago| from now)?$/);\n if (rel) {\n var n = Number(rel[1]) * (rel[2].charAt(0) === 'w' ? 7 : 1);\n return addDays(today, rel[3] === ' ago' ? -n : n);\n }\n var wd = raw.match(/^(this |next |last |on |coming )?(sun|mon|tue|wed|thu|fri|sat)[a-z]*$/);\n if (wd) {\n var target = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].indexOf(wd[2]);\n var now = noon(today).getDay();\n if (direction === 'past' || wd[1] === 'last ') {\n var back = (now - target + 7) % 7;\n return addDays(today, -(wd[1] === 'last ' && back === 0 ? 7 : back));\n }\n if (wd[1] === 'this ') return addDays(today, (target - now + 7) % 7);\n return addDays(today, ((target - now + 6) % 7) + 1);\n }\n var md = raw.match(/^(?:[a-z]+day )?([a-z]{3,9}) (\\d{1,2})(?:st|nd|rd|th)?(?: (\\d{4}))?$/);\n var dm = raw.match(/^(?:[a-z]+day )?(\\d{1,2})(?:st|nd|rd|th)? (?:of )?([a-z]{3,9})(?: (\\d{4}))?$/);\n var parts = md ? { month: md[1], date: md[2], year: md[3] } : dm ? { month: dm[2], date: dm[1], year: dm[3] } : null;\n if (parts) {\n var m = MONTH_KEYS.indexOf(parts.month.slice(0, 3));\n if (m < 0) return null;\n var date = Number(parts.date);\n if (date < 1 || date > 31) return null;\n if (parts.year) return parts.year + '-' + pad(m + 1) + '-' + pad(date);\n var year = noon(today).getFullYear();\n var guess = year + '-' + pad(m + 1) + '-' + pad(date);\n var d = daysLeft(guess, nowMs);\n if (direction === 'past' && d > 0) guess = year - 1 + guess.slice(4);\n if (direction !== 'past' && d < 0) guess = year + 1 + guess.slice(4);\n return guess;\n }\n return null;\n}\nfunction matches(records, text, labelOf) {\n var wanted = String(text == null ? '' : text).trim().toLowerCase().replace(/['\\u2019]s\\b/g, '').replace(/\\s+/g, ' ');\n if (!wanted) return [];\n var tiers = [\n function (r) { return String(r.id).toLowerCase() === wanted; },\n function (r) { return labelOf(r).toLowerCase() === wanted; },\n function (r) { return labelOf(r).toLowerCase().indexOf(wanted) === 0; },\n function (r) { return (' ' + labelOf(r).toLowerCase() + ' ').indexOf(' ' + wanted + ' ') >= 0; },\n function (r) { return labelOf(r).toLowerCase().indexOf(wanted) >= 0; },\n function (r) { var l = labelOf(r).toLowerCase(); return l.length >= 3 && wanted.indexOf(l) >= 0; },\n ];\n for (var i = 0; i < tiers.length; i++) {\n var hit = records.filter(tiers[i]);\n if (hit.length) return hit;\n }\n return [];\n}\nfunction describe(records, labelOf) {\n return records.map(function (r) { return r.id + ' ' + labelOf(r); }).join(', ');\n}\nfunction splitList(text) {\n var raw = String(text == null ? '' : text).trim();\n if (/^\\[/.test(raw)) {\n try {\n var parsed = JSON.parse(raw);\n if (Array.isArray(parsed)) return parsed.map(function (s) { return String(s).trim(); }).filter(Boolean);\n } catch (e) {\n // Not JSON after all; split it as text.\n }\n }\n return raw\n .split(/\\s*[,;\\n]+\\s*/)\n .map(function (s) { return s.replace(/^(and|or|plus)\\s+/i, '').replace(/[.\\s]+$/, '').trim(); })\n .filter(Boolean);\n}\nvar CATEGORIES = [\"food\",\"supplies\",\"linen\",\"equipment\",\"software\",\"utilities\",\"services\",\"premises\",\"insurance\",\"other\"];\nvar DEFAULT_NOTICE_DAYS = 30;\nvar FILLER = ['the', 'our', 'contract', 'contracts', 'agreement', 'with', 'for', 'and', 'from', 'deal'];\n\nfunction yes(value) {\n return value === true || /^(yes|true|y|auto|automatic|automatically)$/i.test(String(value == null ? '' : value).trim());\n}\nfunction money(cents) {\n var n = Math.round(Number(cents) || 0);\n var sign = n < 0 ? '-' : '';\n n = Math.abs(n);\n var dollars = String(Math.floor(n / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\n return sign + '$' + dollars + (n % 100 ? '.' + pad(n % 100) : '');\n}\nfunction inDays(days) {\n if (days < 0) return -days + (days === -1 ? ' day ago' : ' days ago');\n if (days === 0) return 'today';\n return 'in ' + days + (days === 1 ? ' day' : ' days');\n}\nfunction termMonths(f) {\n var m = Number(f.renewMonths);\n return m > 0 ? Math.round(m) : 12;\n}\nfunction noticeOf(f) {\n if (f.noticeDays === undefined || f.noticeDays === null || f.noticeDays === '') return null;\n var n = Number(f.noticeDays);\n return n >= 0 ? Math.round(n) : null;\n}\n// Rolled from the recorded date a whole number of terms at a time, so a 31st never drifts.\n// A contract with notice given (fixed) ends on its recorded date.\nfunction termEnd(f, nowMs, fixed) {\n if (!f.endAt) return null;\n var first = String(f.endAt).slice(0, 10);\n if (fixed || !yes(f.autoRenew)) return first;\n var end = first;\n for (var k = 1; k <= 600 && daysLeft(end, nowMs) < 0; k++) end = addMonths(first, k * termMonths(f));\n return end;\n}\nfunction view(record, nowMs) {\n var f = record.fields || {};\n var end = termEnd(f, nowMs, record.status === 'cancelling' || record.status === 'ended');\n var notice = noticeOf(f);\n var noticeBy = end ? addDays(end, -(notice === null ? DEFAULT_NOTICE_DAYS : notice)) : null;\n return {\n end: end,\n noticeBy: noticeBy,\n notice: notice,\n auto: yes(f.autoRenew),\n rolled: !!end && end !== String(f.endAt).slice(0, 10),\n toNotice: noticeBy ? daysLeft(noticeBy, nowMs) : null,\n toEnd: end ? daysLeft(end, nowMs) : null,\n };\n}\n// notice: renews on its own unless notice goes out by a date inside the window.\n// locked: renews on its own and this term's notice date has passed.\n// ending: a fixed term ends; decide inside the window. expired: it ended unrenewed.\nfunction stateOf(record, nowMs, withinDays) {\n var v = view(record, nowMs);\n if (record.status === 'ended') return 'ended';\n if (!v.end) return 'undated';\n if (record.status === 'cancelling') return v.toEnd < 0 ? 'ended' : 'cancelling';\n if (v.auto) return v.toNotice < 0 ? 'locked' : v.toNotice <= withinDays ? 'notice' : 'later';\n if (v.toEnd < 0) return 'expired';\n return v.toNotice <= withinDays ? 'ending' : 'later';\n}\nfunction renewText(f) {\n var m = termMonths(f);\n return m === 1 ? 'for another month' : 'for another ' + m + ' months';\n}\nfunction costText(f) {\n return typeof f.annualCents === 'number' ? money(f.annualCents) + ' a year' : 'cost not recorded';\n}\nfunction line(record, nowMs, withinDays) {\n var f = record.fields || {};\n var v = view(record, nowMs);\n var s = stateOf(record, nowMs, withinDays);\n var assumed = v.notice === null ? ' (notice period not recorded; ' + DEFAULT_NOTICE_DAYS + ' days assumed)' : '';\n var what =\n s === 'ended' ? 'ended' + (v.end ? ' ' + v.end : '')\n : s === 'undated' ? 'no end date recorded'\n : s === 'cancelling' ? 'notice given; ends ' + v.end + ' (' + inDays(v.toEnd) + ')'\n : s === 'locked' ? 'its notice date ' + v.noticeBy + ' has passed, so it renews automatically on ' + v.end + ' (' + inDays(v.toEnd) + ') ' + renewText(f)\n : s === 'expired' ? 'ended ' + v.end + ' (' + inDays(v.toEnd) + ') and does not renew on its own: record a renewal or mark it ended'\n : v.auto ? 'give notice by ' + v.noticeBy + ' (' + inDays(v.toNotice) + ') or it renews automatically on ' + v.end + ' ' + renewText(f) + assumed\n : 'ends ' + v.end + ' (' + inDays(v.toEnd) + ') and does not renew on its own; decide by ' + v.noticeBy + ' (' + inDays(v.toNotice) + ')' + assumed;\n return (\n f.title + ' (' + record.id + ', ' + (f.vendor || 'no vendor') + (f.owner ? ', owner ' + f.owner : '') + '): ' + what +\n (record.status === 'reviewing' ? '; under review' : '') +\n '; ' + costText(f) +\n (f.file ? '; contract file ' + f.file : '')\n );\n}\n// Missed dates first (ended unrenewed, then too late to cancel), then the soonest date to act on.\nfunction urgency(record, nowMs, withinDays) {\n var v = view(record, nowMs);\n var s = stateOf(record, nowMs, withinDays);\n if (s === 'expired') return -100000 + v.toEnd;\n if (s === 'locked') return -50000 + v.toEnd;\n return v.toNotice;\n}\nfunction picture(contracts, vendorCount, nowMs, withinDays) {\n var states = contracts.map(function (r) { return stateOf(r, nowMs, withinDays); });\n var pick = function (names) {\n return contracts.filter(function (r, i) { return names.indexOf(states[i]) >= 0; });\n };\n var live = contracts.filter(function (r, i) { return states[i] !== 'ended'; });\n var annual = live.reduce(function (sum, r) { return sum + (Number(r.fields && r.fields.annualCents) || 0); }, 0);\n var due = pick(['expired', 'locked', 'notice', 'ending']).sort(function (a, b) {\n return urgency(a, nowMs, withinDays) - urgency(b, nowMs, withinDays);\n });\n var warnings = pick(['locked', 'notice']).length;\n var parts = [\n live.length + ' live ' + (live.length === 1 ? 'contract' : 'contracts') + ' with ' + vendorCount + ' ' + (vendorCount === 1 ? 'vendor' : 'vendors') + ', ' + money(annual) + ' a year' + (warnings ? '; ' + warnings + (warnings === 1 ? ' renews on its own' : ' renew on their own') + ' soon' : '') + '.',\n ];\n // One list, missed dates first: a model asked what needs deciding reads one list, not side lists.\n parts.push(\n due.length\n ? 'Needing a decision within ' + withinDays + ' days, most urgent first: ' + due.map(function (r) { return line(r, nowMs, withinDays); }).join(' | ') + '.'\n : 'Nothing needs a decision in the next ' + withinDays + ' days.',\n );\n var cancelling = pick(['cancelling']);\n if (cancelling.length) parts.push('Notice already given: ' + cancelling.map(function (r) { return line(r, nowMs, withinDays); }).join(' | ') + '.');\n var undated = pick(['undated']);\n if (undated.length) parts.push('No end date recorded: ' + undated.map(function (r) { return r.fields.title + ' (' + r.id + ')'; }).join(', ') + '.');\n var later = pick(['later']).sort(function (a, b) { return view(a, nowMs).toNotice - view(b, nowMs).toNotice; });\n if (later.length) {\n var next = view(later[0], nowMs);\n parts.push('Next after that: ' + later[0].fields.title + ', ' + (next.auto ? 'give notice by ' : 'decide by ') + next.noticeBy + '.');\n }\n var spend = {};\n live.forEach(function (r) {\n var kind = (r.fields && r.fields.category) || 'other';\n spend[kind] = (spend[kind] || 0) + (Number(r.fields && r.fields.annualCents) || 0);\n });\n var kinds = Object.keys(spend).filter(function (k) { return spend[k] > 0; }).sort(function (a, b) { return spend[b] - spend[a]; });\n if (kinds.length) parts.push('Yearly spend by kind: ' + kinds.map(function (k) { return k + ' ' + money(spend[k]); }).join(', ') + '.');\n return { decisionsDue: due.length, autoRenewWarnings: warnings, annualCents: annual, summary: parts.join(' ') };\n}\nfunction contractLabel(r) {\n return String((r.fields && r.fields.title) || '');\n}\n// By id or title first, then the vendor's name, then every telling word of the request.\nfunction findContracts(records, text) {\n var hit = matches(records, text, contractLabel);\n if (hit.length) return hit;\n hit = matches(records, text, function (r) { return String((r.fields && r.fields.vendor) || ''); });\n if (hit.length) return hit;\n var want = String(text == null ? '' : text).toLowerCase().split(/[^a-z0-9]+/).filter(function (w) {\n return w.length > 2 && FILLER.indexOf(w) < 0;\n });\n if (!want.length) return [];\n return records.filter(function (r) {\n var have = (contractLabel(r) + ' ' + String((r.fields && r.fields.vendor) || '')).toLowerCase().split(/[^a-z0-9]+/);\n return want.every(function (w) {\n var stem = w.replace(/s$/, '');\n return have.some(function (h) { return h.indexOf(stem) === 0; });\n });\n });\n}\n// ── contracts-rules-end ──\n\nconst contracts = rosterStore(gezel.fs, 'contracts.json', {\n stages: ['active', 'reviewing', 'cancelling', 'ended'],\n idPrefix: 'ct',\n});\nconst vendors = rosterStore(gezel.fs, 'vendors.json', {\n stages: ['active', 'inactive'],\n idPrefix: 'vn',\n});\ntype Contract = Awaited<ReturnType<typeof contracts.list>>[number];\n\nconst now = Date.now();\nconst today = localDay(now);\nconst withinDays = typeof input.withinDays === 'number' && input.withinDays > 0 ? Math.round(input.withinDays) : 90;\nlet note = '';\n\nfunction clip(text: string, max: number): string {\n return text.length > max ? text.slice(0, max - 1) + '…' : text;\n}\nfunction known(all: Contract[]): string {\n return describe(all, contractLabel) || 'none yet';\n}\n\nasync function resolveContract(): Promise<Contract> {\n const all = await contracts.list();\n const text = input.id || input.title || input.vendor;\n if (!text) throw new Error(\"Pass 'id' (e.g. 'ct-3') or the contract's 'title'. Contracts: \" + known(all) + '.');\n const hits = findContracts(all, text);\n if (hits.length === 1) return hits[0]!;\n if (hits.length > 1) throw new Error(\"More than one contract matches '\" + text + \"': \" + describe(hits, contractLabel) + '. Pass id.');\n throw new Error(\"No contract matches '\" + text + \"'. Contracts: \" + known(all) + '.');\n}\n\nasync function ensureVendor(name: string, category: string | undefined) {\n const wanted = name.trim().toLowerCase();\n const found = (await vendors.list()).find((v) => String(v.fields.name ?? '').toLowerCase() === wanted);\n if (found) return found;\n return vendors.add({ status: 'active', fields: { name: name.trim(), category: category ?? 'other' } });\n}\n\nfunction dollars(value: unknown): number | undefined {\n return typeof value === 'number' && isFinite(value) && value >= 0 ? Math.round(value * 100) : undefined;\n}\n\n// The yearly cost a call states or implies: a stated cost wins, then the relative changes apply.\nfunction priced(current: unknown): { cents?: number; change: string } {\n const monthly = dollars(input.monthlyCost);\n const stated = dollars(input.annualCost) ?? (monthly === undefined ? undefined : monthly * 12);\n const relative = typeof input.percentChange === 'number' || typeof input.monthlyChange === 'number';\n if (!relative) return { cents: stated, change: '' };\n const base = stated ?? (typeof current === 'number' ? current : undefined);\n if (base === undefined) throw new Error('There is no recorded cost to change yet; pass annualCost or monthlyCost.');\n let next = base;\n if (typeof input.percentChange === 'number') next = Math.round(next * (1 + input.percentChange / 100));\n if (typeof input.monthlyChange === 'number') next += Math.round(input.monthlyChange * 100) * 12;\n next = Math.max(0, next);\n return { cents: next, change: 'price from ' + money(base) + ' to ' + money(next) + ' a year' };\n}\n\n// The desk's one reminder sits two weeks ahead of the soonest notice date (or a fixed term's end).\nasync function remindNextNotice(all: Contract[]): Promise<void> {\n const lead = 14 * DAY_MS;\n const next = all\n .filter((r) => r.status === 'active' || r.status === 'reviewing')\n .map((r) => {\n const v = view(r, now);\n const day = v.toNotice !== null && v.toNotice >= 0 ? v.noticeBy : !v.auto && v.toEnd !== null && v.toEnd >= 0 ? v.end : null;\n return { r, v, day, at: day ? Date.parse(day + 'T09:00:00') - lead : NaN };\n })\n .filter((x) => x.day && x.at > now)\n .sort((a, b) => a.at - b.at)[0];\n try {\n if (!next || next.at - now > 30 * DAY_MS) {\n await gezel.reminder.clear();\n } else {\n const title = String(next.r.fields.title);\n const onNotice = next.day === next.v.noticeBy;\n await gezel.reminder.set({\n at: new Date(next.at).toISOString(),\n title: clip(onNotice ? 'Notice on ' + title + ' is due in two weeks' : title + ' ends in two weeks', 80),\n body: clip(\n onNotice\n ? next.v.auto\n ? 'Give notice by ' + next.day + ' or it renews on ' + next.v.end + '. Open the contract desk to decide.'\n : 'Decide by ' + next.day + ' whether to renew; it ends ' + next.v.end + '.'\n : 'It ends ' + next.v.end + ' and does not renew on its own.',\n 160,\n ),\n });\n }\n } catch {\n // Reminders are a convenience; the desk is the record.\n }\n}\n\nif (input.action === 'add') {\n const all = await contracts.list();\n const wanted = String(input.title ?? '').trim().toLowerCase();\n let existing = input.id\n ? all.find((r) => r.id === input.id)\n : all.find((r) => String(r.fields.title ?? '').toLowerCase() === wanted);\n if (input.id && !existing) throw new Error('No contract ' + input.id + '. Contracts: ' + known(all) + '.');\n const endAt = input.endAt ? parseDay(input.endAt, now, 'future') : null;\n if (input.endAt && !endAt) throw new Error(\"endAt must be a date, e.g. '2027-03-31'.\");\n const relative = typeof input.percentChange === 'number' || typeof input.monthlyChange === 'number';\n // A call with no end date cannot start a contract, so a loose title names an existing one.\n if (!existing && wanted && (!endAt || relative)) {\n const loose = findContracts(all, input.title);\n if (loose.length === 1) existing = loose[0];\n else if (loose.length > 1) throw new Error(\"More than one contract matches '\" + input.title + \"': \" + describe(loose, contractLabel) + '. Pass id.');\n else if (relative) throw new Error(\"No contract matches '\" + input.title + \"' to change its price. Contracts: \" + known(all) + '.');\n }\n if (!existing && !wanted) throw new Error(\"add needs 'title'.\");\n if (input.noticeDays !== undefined && !(Number(input.noticeDays) >= 0)) throw new Error('noticeDays must be zero or more.');\n const category = CATEGORIES.indexOf(String(input.category)) >= 0 ? String(input.category) : undefined;\n const vendor = input.vendor ? await ensureVendor(input.vendor, category) : null;\n const price = priced(existing ? existing.fields.annualCents : undefined);\n const fields: Record<string, unknown> = {\n ...(vendor ? { vendor: String(vendor.fields.name), vendorId: vendor.id } : {}),\n ...(category ? { category } : {}),\n ...(endAt ? { endAt } : {}),\n ...(input.autoRenew ? { autoRenew: yes(input.autoRenew) ? 'yes' : 'no' } : {}),\n ...(typeof input.renewMonths === 'number' && input.renewMonths > 0 ? { renewMonths: Math.round(input.renewMonths) } : {}),\n ...(typeof input.noticeDays === 'number' ? { noticeDays: Math.round(input.noticeDays) } : {}),\n ...(price.cents !== undefined ? { annualCents: price.cents } : {}),\n ...(input.owner ? { owner: input.owner.trim() } : {}),\n ...(input.note ? { notes: input.note.trim() } : {}),\n };\n if (existing) {\n await contracts.update(existing.id, { fields, ...(price.change ? { note: 'Price change: ' + price.change + '.' } : {}) });\n note = 'Updated ' + String(existing.fields.title) + (price.change ? ': ' + price.change : '') + '.';\n } else {\n if (!endAt) throw new Error(\"A new contract needs 'endAt': when its current term ends (YYYY-MM-DD; for month-to-month, the next billing date).\");\n const record = await contracts.add({\n status: 'active',\n fields: {\n title: String(input.title).trim(),\n category: category ?? (vendor ? String(vendor.fields.category ?? 'other') : 'other'),\n autoRenew: 'no',\n ...fields,\n },\n });\n note = 'Added ' + record.id + ' ' + String(record.fields.title) + '.';\n }\n} else if (input.action === 'renew') {\n const r = await resolveContract();\n const v = view(r, now);\n const months = typeof input.renewMonths === 'number' && input.renewMonths > 0 ? Math.round(input.renewMonths) : termMonths(r.fields);\n const nextEnd = input.endAt ? parseDay(input.endAt, now, 'future') : v.end ? addMonths(v.end, months) : null;\n if (input.endAt && !nextEnd) throw new Error(\"endAt must be a date, e.g. '2027-12-14'.\");\n if (!nextEnd) throw new Error(\"renew needs 'endAt': the new end date.\");\n const price = priced(r.fields.annualCents);\n const fields: Record<string, unknown> = {\n endAt: nextEnd,\n lastRenewedAt: today,\n ...(typeof input.renewMonths === 'number' && input.renewMonths > 0 ? { renewMonths: months } : {}),\n ...(price.cents !== undefined ? { annualCents: price.cents } : {}),\n };\n await contracts.update(r.id, { fields, note: input.note ?? 'Renewed through ' + nextEnd + '.' });\n if (r.status !== 'active') await contracts.transition(r.id, 'active', { note: 'Renewed.' });\n const after = view({ id: r.id, status: 'active', fields: { ...r.fields, ...fields } }, now);\n note =\n String(r.fields.title) + ' renewed through ' + nextEnd + (price.cents !== undefined ? ' at ' + money(price.cents) + ' a year' : '') +\n (after.auto ? '; next notice date ' + after.noticeBy : '') + '.';\n} else if (input.action === 'cancel') {\n const r = await resolveContract();\n if (r.status === 'ended') throw new Error(String(r.fields.title) + ' has already ended.');\n const v = view(r, now);\n if (v.end && v.end !== r.fields.endAt) await contracts.update(r.id, { fields: { endAt: v.end } });\n await contracts.transition(r.id, 'cancelling', { note: input.note ?? 'Notice given.' });\n const late = v.auto && v.toNotice !== null && v.toNotice < 0;\n note =\n 'Notice recorded for ' + String(r.fields.title) + (v.end ? '; it ends ' + v.end : '') + '.' +\n (late ? ' Its notice date ' + v.noticeBy + ' had already passed, so confirm with ' + String(r.fields.vendor || 'the vendor') + ' whether it renews for one more term first.' : '');\n} else if (input.action === 'set_status') {\n if (['active', 'reviewing', 'ended'].indexOf(String(input.status)) < 0) throw new Error(\"set_status needs status 'active', 'reviewing' or 'ended'.\");\n const r = await resolveContract();\n await contracts.transition(r.id, String(input.status), input.note ? { note: input.note } : {});\n note = String(r.fields.title) + (input.status === 'reviewing' ? ' is under review.' : input.status === 'ended' ? ' has ended.' : ' is active.');\n} else if (input.action === 'add_vendor') {\n const name = String(input.vendor ?? input.title ?? '').trim();\n if (!name) throw new Error(\"add_vendor needs 'vendor': the vendor's name.\");\n const category = CATEGORIES.indexOf(String(input.category)) >= 0 ? String(input.category) : undefined;\n const found = (await vendors.list()).find((v) => String(v.fields.name ?? '').toLowerCase() === name.toLowerCase());\n const fields: Record<string, unknown> = {\n ...(category ? { category } : {}),\n ...(input.contact ? { contact: input.contact.trim() } : {}),\n ...(input.note ? { notes: input.note.trim() } : {}),\n };\n if (found) {\n await vendors.update(found.id, { fields });\n note = 'Updated vendor ' + String(found.fields.name) + '.';\n } else {\n const v = await vendors.add({ status: 'active', fields: { name, category: category ?? 'other', ...fields } });\n note = 'Added vendor ' + v.id + ' ' + name + '.';\n }\n} else if (input.action === 'attach_file') {\n const raw = String(input.file ?? '').trim().replace(/\\\\/g, '/').replace(/^\\.?\\/+/, '');\n if (!raw) throw new Error(\"attach_file needs 'file', e.g. 'contract-files/linen-2026.pdf'.\");\n if (raw.split('/').indexOf('..') >= 0) throw new Error('file must be a path inside the workspace.');\n const file = raw.indexOf('/') < 0 ? 'contract-files/' + raw : raw;\n const r = await resolveContract();\n await contracts.update(r.id, { fields: { file }, note: 'Contract file: ' + file + '.' });\n note = 'Linked ' + file + ' to ' + String(r.fields.title) + '.';\n} else if (input.action !== 'status' && input.action !== 'list') {\n throw new Error(\"Unknown action '\" + input.action + \"'. Use status, add, renew, cancel, set_status, add_vendor, attach_file, or list.\");\n}\n\nconst all = await contracts.list();\nconst vendorList = await vendors.list();\nconst desk = picture(all, vendorList.filter((v) => v.status === 'active').length, now, withinDays);\nawait remindNextNotice(all);\n\nfunction vendorLine(v: (typeof vendorList)[number]): string {\n const name = String(v.fields.name ?? '');\n const own = all.filter(\n (r) => (r.fields.vendorId === v.id || String(r.fields.vendor ?? '').toLowerCase() === name.toLowerCase()) && stateOf(r, now, withinDays) !== 'ended',\n );\n const cents = own.reduce((sum, r) => sum + (Number(r.fields.annualCents) || 0), 0);\n return (\n name + ' (' + v.id + ', ' + String(v.fields.category ?? 'other') + (v.fields.contact ? ', contact ' + String(v.fields.contact) : '') + (v.status !== 'active' ? ', inactive' : '') + '): ' +\n (own.length ? own.length + (own.length === 1 ? ' contract, ' : ' contracts, ') + money(cents) + ' a year' : 'no contract on the desk')\n );\n}\n\n// Vendors without a contract (the electrician you call) are otherwise invisible to a status read.\nconst callOnly = vendorList.filter((v) => v.status === 'active' && vendorLine(v).endsWith('no contract on the desk')).slice(0, 8);\nconst extra = callOnly.length\n ? ' Vendors with no contract on the desk: ' +\n callOnly.map((v) => String(v.fields.name) + ' (' + String(v.fields.category ?? 'other') + (v.fields.contact ? ', ' + String(v.fields.contact) : '') + ')').join(', ') + '.'\n : '';\n\ngezel.output({\n decisionsDue: desk.decisionsDue,\n autoRenewWarnings: desk.autoRenewWarnings,\n annualSpend: desk.annualCents / 100,\n contracts: all.length,\n summary:\n input.action === 'list'\n ? (all.map((r) => '[' + r.status + '] ' + line(r, now, withinDays)).join('\\n') || 'No contracts yet.') +\n '\\n\\nVendors:\\n' + (vendorList.map(vendorLine).join('\\n') || 'none yet')\n : (note ? note + ' ' : '') + desk.summary + extra,\n});\n"},"tools":[{"name":"contracts_status","description":"What needs deciding on the contract desk: notice dates and automatic renewals within 90 days, missed ones first, each with vendor, owner, dates and yearly cost, plus yearly spend by kind. Call it first when asked what's coming up or what the business spends.","script":"contracts-store","inputs":{"type":"object","properties":{"withinDays":{"type":"number"}}},"bind":{"action":"status"},"state":true},{"name":"add_contract","description":"Save a contract: title, vendor, kind, yearly or monthly cost in dollars, when the current term ends (YYYY-MM-DD), whether it renews on its own, notice days and owner. An existing id or title is updated, never duplicated. For a price change pass percentChange or monthlyChange and let the desk do the math. Call it as soon as a contract or a price change is mentioned, before you describe it.","script":"contracts-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"vendor":{"type":"string"},"category":{"type":"string","enum":["food","supplies","linen","equipment","software","utilities","services","premises","insurance","other"]},"endAt":{"type":"string"},"autoRenew":{"type":"string","enum":["yes","no"]},"renewMonths":{"type":"number"},"noticeDays":{"type":"number"},"annualCost":{"type":"number"},"monthlyCost":{"type":"number"},"owner":{"type":"string"},"note":{"type":"string"},"percentChange":{"type":"number"},"monthlyChange":{"type":"number"}},"required":["title"]},"bind":{"action":"add"}},{"name":"renew_contract","description":"Record that a contract was renewed. Leave endAt out to extend it one more term from its current end date; pass annualCost or monthlyCost when the price changed. Call it the moment the person says it's renewed.","script":"contracts-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"vendor":{"type":"string"},"endAt":{"type":"string"},"renewMonths":{"type":"number"},"annualCost":{"type":"number"},"monthlyCost":{"type":"number"},"percentChange":{"type":"number"},"note":{"type":"string"}}},"bind":{"action":"renew"}},{"name":"cancel_contract","description":"Record that notice went out to end a contract, with how it was sent and any reference exactly as written. It stays on the desk until its end date. Call it the moment the person says notice was given.","script":"contracts-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"vendor":{"type":"string"},"note":{"type":"string"}}},"bind":{"action":"cancel"}},{"name":"set_contract_status","description":"Mark a contract under review (renegotiating or comparing quotes), active again, or ended.","script":"contracts-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"vendor":{"type":"string"},"status":{"type":"string","enum":["active","reviewing","ended"]},"note":{"type":"string"}},"required":["status"]},"bind":{"action":"set_status"}},{"name":"add_vendor","description":"Save a vendor with its kind and contact, including one with no contract (the electrician you call when something breaks). An existing name is updated, never duplicated.","script":"contracts-store","inputs":{"type":"object","properties":{"vendor":{"type":"string"},"category":{"type":"string","enum":["food","supplies","linen","equipment","software","utilities","services","premises","insurance","other"]},"contact":{"type":"string"},"note":{"type":"string"}},"required":["vendor"]},"bind":{"action":"add_vendor"}},{"name":"attach_contract_file","description":"Link a contract file the person added under contract-files/ to its contract.","script":"contracts-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"vendor":{"type":"string"},"file":{"type":"string"}},"required":["file"]},"bind":{"action":"attach_file"}},{"name":"list_contracts","description":"Every contract and vendor with status, dates, yearly cost, contact and contract file.","script":"contracts-store","inputs":{"type":"object","properties":{}},"bind":{"action":"list"}},{"name":"page_add_contract","description":"Add or update a contract.","script":"contracts-store","inputs":{"type":"object","properties":{"title":{"type":"string"},"vendor":{"type":"string"},"category":{"type":"string","enum":["food","supplies","linen","equipment","software","utilities","services","premises","insurance","other"]},"endAt":{"type":"string"},"autoRenew":{"type":"string","enum":["yes","no"]},"renewMonths":{"type":"number"},"noticeDays":{"type":"number"},"annualCost":{"type":"number"},"monthlyCost":{"type":"number"},"owner":{"type":"string"},"note":{"type":"string"}},"required":["title","endAt"]},"bind":{"action":"add"}},{"name":"page_renew_contract","description":"Record a renewal.","script":"contracts-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"vendor":{"type":"string"},"endAt":{"type":"string"},"renewMonths":{"type":"number"},"annualCost":{"type":"number"},"monthlyCost":{"type":"number"},"percentChange":{"type":"number"},"note":{"type":"string"}}},"bind":{"action":"renew"},"reaction":{"gezel":"kantoormeester","prompt":"The person just recorded a renewal on the contract desk page. The desk now reads (its first sentence is what changed):\n{{output.summary}}\nIn two short sentences, confirm the new end date and next notice date, and name the next contract that needs a decision. Do not call tools.","hideSeed":true}},{"name":"page_cancel_contract","description":"Record that notice was given.","script":"contracts-store","inputs":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"vendor":{"type":"string"},"note":{"type":"string"}}},"bind":{"action":"cancel"},"reaction":{"gezel":"kantoormeester","prompt":"The person just recorded a notice on the contract desk page. The desk now reads (its first sentence is what changed):\n{{output.summary}}\nIn two short sentences, confirm when the contract ends and anything to check with the vendor, and name the next contract that needs a decision. Do not call tools.","hideSeed":true}},{"name":"page_add_vendor","description":"Add or update a vendor.","script":"contracts-store","inputs":{"type":"object","properties":{"vendor":{"type":"string"},"category":{"type":"string","enum":["food","supplies","linen","equipment","software","utilities","services","premises","insurance","other"]},"contact":{"type":"string"},"note":{"type":"string"}},"required":["vendor"]},"bind":{"action":"add_vendor"}}],"pages":{"imports":[{"id":"contract-files","source":"workspace","path":"contract-files","accept":[".pdf",".png",".jpg",".jpeg",".webp",".heic",".docx",".txt",".md"],"maxFileBytes":26214400}],"entry":"desk/index.html","api":1,"reads":[{"source":"workspace","path":"contracts.json"},{"source":"workspace","path":"vendors.json"},{"source":"workspace","path":"contract-files","subtree":true}],"tools":["page_add_contract","page_renew_contract","page_cancel_contract","page_add_vendor"]},"schedules":[],"workspaceSeed":["contracts.json","vendors.json"],"artifactsSeed":[],"availableVersions":["1.0.0"]}},{"manifest":{"schemaVersion":1,"kind":"project-type","id":"word-clues","name":"Word Clues","description":"Find your six words on a board of sixteen from one-word clues, and steer clear of the trap. Two gezels take turns giving clues: a lively clue giver and a careful puzzler.","tags":["game","words","clues","play"],"category":"game","maintainer":{"name":"Gezel"},"logo":"logo.webp","license":"MIT","minGezelVersion":"1.26280","version":"1.0.4","releasedAt":"2026-11-02T18:00:00.000Z","meesterManaged":false,"tabVisibility":{"overview":false,"tasks":false,"approvals":false,"workspace":false,"artifacts":false,"map":false},"leanProfile":true,"nameTemplate":"Word Clues","aboutTemplate":"about.md","missionTemplate":"mission.md","gezels":[{"templateId":"woordsmid","voorman":true},{"templateId":"puzzelaar","voorman":false}],"toolsets":[],"craftbooks":[],"scripts":{"clue-store":"import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\n\nexport const meta = defineScript({\n name: 'clue-store',\n description:\n \"The word-clue game's engine (game.json). action:'board' reads the game; 'give_clue' records a clue; 'guess' reveals a word the player picked; 'pass' ends the player's guessing; 'new_game' deals a fresh board.\",\n inputs: {\n action: {\n type: 'string',\n description: \"One of 'board', 'give_clue', 'guess', 'pass', 'new_game'.\",\n required: true,\n },\n clue: { type: 'string', description: 'For give_clue: one word, not on the board.' },\n count: { type: 'number', description: 'For give_clue: how many of the player’s words it points at.' },\n say: { type: 'string', description: 'For give_clue: one short line of table talk.' },\n word: { type: 'string', description: 'For guess: the board word the player picked.' },\n },\n outputs: {\n status: {\n type: 'string',\n description: \"'clue_needed', 'guessing', 'won', 'lost' or 'new'.\",\n },\n giver: { type: 'string', description: \"Whose clue is next: 'a' (Clue Giver) or 'b' (Puzzler).\" },\n result: { type: 'string', description: \"For guess: 'target', 'neutral', 'trap', or ''.\" },\n display: { type: 'string', description: 'For give_clue: the clue as shown to the player.' },\n modelState: { type: 'json', description: 'What the clue-giver sees: its words, the trap, the rest.' },\n summary: { type: 'string', description: 'A short summary of the game.' },\n },\n requires: ['workspace.read', 'workspace.write'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── clue-rules-start ──\n// The board is sixteen words: six are the player's, nine are neutral, one\n// is the trap. A clue-giver who knows the board gives one word and a count;\n// the player then picks up to count + 1 words. A neutral word ends their\n// turn, the trap ends the game, and finding all six wins it. Kept\n// self-contained between these sentinels so unit tests execute the shipped\n// bytes.\nvar BOARD_SIZE = 16;\nvar TARGETS = 6;\n\nfunction shuffle(list, random) {\n var out = list.slice();\n for (var i = out.length - 1; i > 0; i -= 1) {\n var j = Math.floor(random() * (i + 1));\n var t = out[i];\n out[i] = out[j];\n out[j] = t;\n }\n return out;\n}\n\nfunction deal(bank, random) {\n var picked = shuffle(bank, random).slice(0, BOARD_SIZE);\n var cells = picked.map(function (word, i) {\n return { word: word, kind: i < TARGETS ? 'target' : i === TARGETS ? 'trap' : 'neutral', revealed: false };\n });\n return shuffle(cells, random);\n}\n\nfunction remaining(words, kind) {\n return words.filter(function (w) { return w.kind === kind && !w.revealed; }).map(function (w) { return w.word; });\n}\n\n// Why a clue is not allowed on this board, or '' when it is.\nfunction clueProblem(words, clue, count) {\n var c = String(clue || '').trim().toLowerCase();\n if (!/^[a-zÀ-ɏ'-]{2,24}$/.test(c)) return 'A clue is one word of letters, like \"ocean\".';\n for (var i = 0; i < words.length; i += 1) {\n var w = words[i].word.toLowerCase();\n if (w === c) return '\"' + c + '\" is on the board.';\n // Forms of a board word (plurals, compounds that start with it) give the\n // answer away; a word that merely contains one (\"planet\", \"net\") does not.\n var shorter = c.length < w.length ? c : w;\n var longer = c.length < w.length ? w : c;\n if (shorter.length >= 3 && longer.indexOf(shorter) === 0)\n return '\"' + c + '\" is a form of the board word \"' + w + '\".';\n }\n var left = remaining(words, 'target').length;\n if (!(count >= 1 && count <= left && Math.floor(count) === count))\n return 'The count must be a whole number from 1 to ' + left + '.';\n return '';\n}\n\nfunction applyGuess(game, word) {\n var pick = String(word || '').trim().toLowerCase();\n var cell = game.words.find(function (w) { return w.word.toLowerCase() === pick; });\n if (!cell) return { error: '\"' + word + '\" is not on the board.' };\n if (cell.revealed) return { error: '\"' + cell.word + '\" is already revealed.' };\n cell.revealed = true;\n var result = cell.kind;\n if (result === 'trap') {\n game.status = 'lost';\n } else if (remaining(game.words, 'target').length === 0) {\n game.status = 'won';\n } else if (result === 'neutral') {\n endGuessing(game);\n } else {\n game.clue.guessesLeft -= 1;\n if (game.clue.guessesLeft <= 0) endGuessing(game);\n }\n return { result: result };\n}\n\nfunction endGuessing(game) {\n game.status = 'clue_needed';\n game.giver = game.giver === 'a' ? 'b' : 'a';\n}\n// ── clue-rules-end ──\n\ninterface Cell {\n word: string;\n kind: 'target' | 'neutral' | 'trap';\n revealed: boolean;\n}\n\ninterface Game {\n version: number;\n status: 'new' | 'clue_needed' | 'guessing' | 'won' | 'lost';\n giver: 'a' | 'b';\n words: Cell[];\n clue: { word: string; count: number; guessesLeft: number; giver: 'a' | 'b' } | null;\n round: number;\n history: Array<{ round: number; clue: string; count: number; found: string[] }>;\n stats: { played: number; won: number; lost: number };\n}\n\nconst GAME_FILE = 'game.json';\n\nasync function load(): Promise<Game> {\n let parsed: Partial<Game> = {};\n try {\n parsed = JSON.parse(await gezel.fs.read(GAME_FILE)) as Partial<Game>;\n } catch {\n // A missing game is a new one.\n }\n return {\n version: 1,\n status: parsed.status ?? 'new',\n giver: parsed.giver === 'b' ? 'b' : 'a',\n words: Array.isArray(parsed.words) ? parsed.words : [],\n clue: parsed.clue ?? null,\n round: parsed.round ?? 0,\n history: Array.isArray(parsed.history) ? parsed.history : [],\n stats: parsed.stats ?? { played: 0, won: 0, lost: 0 },\n };\n}\n\nasync function save(game: Game): Promise<void> {\n await gezel.fs.write(GAME_FILE, `${JSON.stringify(game, null, 2)}\\n`);\n}\n\n// A table nobody has dealt yet gets its first board from the first look at\n// it, so a clue-giver asked to start a game can (new_game is the page's).\nasync function dealInto(game: Game): Promise<void> {\n let bank: string[] = [];\n try {\n bank = (JSON.parse(await gezel.fs.read('words.json')) as { words?: string[] }).words ?? [];\n } catch {\n bank = [];\n }\n if (bank.length < BOARD_SIZE) throw new Error('words.json needs at least 16 words.');\n game.words = deal(bank, Math.random);\n game.status = 'clue_needed';\n game.giver = game.stats.played % 2 === 0 ? 'a' : 'b';\n game.clue = null;\n game.round = 0;\n game.history = [];\n}\n\nconst game = await load();\nlet result = '';\nlet display = '';\nlet changed = false;\n\nswitch (input.action) {\n case 'new_game': {\n await dealInto(game);\n changed = true;\n break;\n }\n case 'give_clue': {\n if (game.status !== 'clue_needed')\n throw new Error(\n game.status === 'guessing'\n ? 'The player is still guessing; no clue is needed yet.'\n : game.status === 'new'\n ? 'No board is dealt yet. Call board first; it deals one.'\n : 'The game is over. Offer a new game instead of a clue.',\n );\n const count = Number(input.count);\n const problem = clueProblem(game.words, input.clue, count);\n if (problem) {\n // Point a struggling clue-giver at one word to hint at: a small model\n // given the whole board tends to offer a board word back.\n const left = remaining(game.words, 'target');\n const hint = left[Math.floor(Math.random() * left.length)];\n throw new Error(\n `${problem} Your clue must be a new word that is not on the board. Think of a word linked to \"${hint}\", and give it with count 1.`,\n );\n }\n const word = String(input.clue).trim().toUpperCase();\n game.clue = { word, count, guessesLeft: count + 1, giver: game.giver };\n game.status = 'guessing';\n game.round += 1;\n game.history = [...game.history, { round: game.round, clue: word, count, found: [] }];\n const say = String(input.say ?? '').replace(/\\s+/g, ' ').trim().slice(0, 160);\n display = `Clue: ${word}, ${count}.${say ? ` ${say}` : ''}`;\n changed = true;\n break;\n }\n case 'guess': {\n if (game.status !== 'guessing') throw new Error('Wait for a clue before guessing.');\n const outcome = applyGuess(game, input.word);\n if (outcome.error) throw new Error(outcome.error);\n result = outcome.result;\n if (result === 'target') game.history[game.history.length - 1]?.found.push(String(input.word));\n if (game.status === 'won' || game.status === 'lost') {\n game.stats.played += 1;\n if (game.status === 'won') game.stats.won += 1;\n else game.stats.lost += 1;\n }\n changed = true;\n break;\n }\n case 'pass': {\n if (game.status !== 'guessing') throw new Error('There is no guessing turn to end.');\n endGuessing(game);\n changed = true;\n break;\n }\n case 'board': {\n if (game.status === 'new' && game.words.length === 0) {\n await dealInto(game);\n changed = true;\n }\n break;\n }\n default:\n throw new Error(`Unknown action '${input.action}'.`);\n}\n\nif (changed) await save(game);\n\nconst over = game.status === 'won' || game.status === 'lost';\ngezel.output({\n status: game.status,\n giver: game.giver,\n result,\n display,\n modelState: {\n status: game.status,\n yourWords: remaining(game.words, 'target'),\n trap: game.words.find((w) => w.kind === 'trap')?.word ?? '',\n otherWords: remaining(game.words, 'neutral'),\n rule: 'Your clue must be a word that is NOT in yourWords, otherWords or trap.',\n found: game.words.filter((w) => w.kind === 'target' && w.revealed).map((w) => w.word),\n round: game.round,\n ...(game.clue && game.status === 'guessing' ? { currentClue: `${game.clue.word} ${game.clue.count}` } : {}),\n },\n summary: over\n ? `The player ${game.status === 'won' ? 'found all six words' : 'hit the trap'} in ${game.round} round(s). Games: ${game.stats.won} won, ${game.stats.lost} lost.`\n : `Round ${game.round}: ${remaining(game.words, 'target').length} of 6 words still to find.`,\n});\n"},"tools":[{"name":"board","description":"Read the game: your words still to find, the trap, the other words, and whether a clue is needed. Deals the first board when none is on the table.","script":"clue-store","inputs":{"type":"object","properties":{}},"bind":{"action":"board"},"state":true,"answer":{"tool":"give_clue","when":{"op":"equals","field":"status","value":"clue_needed"}}},{"name":"give_clue","description":"Give the player's next clue: one word that is not on the board, the number of their words it points at, and one short line of table talk.","script":"clue-store","inputs":{"type":"object","properties":{"clue":{"type":"string","description":"One word, not on the board."},"count":{"type":"number","description":"How many of the player's words it points at."},"say":{"type":"string","description":"One short line of table talk (max 160 characters)."}},"required":["clue","count"]},"bind":{"action":"give_clue"},"turn":{"say":"say","fallback":"Your clue is on the board.","show":"display"}},{"name":"new_game","description":"Deal a fresh board.","script":"clue-store","inputs":{"type":"object","properties":{}},"bind":{"action":"new_game"}},{"name":"guess","description":"The player picks a word on the board.","script":"clue-store","inputs":{"type":"object","properties":{"word":{"type":"string"}},"required":["word"]},"bind":{"action":"guess"}},{"name":"pass","description":"The player stops guessing this turn.","script":"clue-store","inputs":{"type":"object","properties":{}},"bind":{"action":"pass"}},{"name":"ask_clue_a","description":"The board asks for the next clue.","script":"clue-store","inputs":{"type":"object","properties":{}},"bind":{"action":"board"},"reaction":{"gezel":"woordsmid","prompt":"It is your turn in Word Clues. The game engine returned this state:\n```json\n{{output.modelState}}\n```\nIf `status` is `clue_needed`, call give_clue once: `clue` is one NEW word, not on the board, that links some of `yourWords`, `count` is how many it points at, and `say` is one short line of table talk. Never pick a clue that also fits `trap`, and avoid ones that fit `otherWords`. If the game is over, give no clue: say one warm line about how it went and offer another game.","hideSeed":true,"standalone":true,"turn":{"tool":"give_clue","when":{"op":"equals","field":"status","value":"clue_needed"}}}},{"name":"ask_clue_b","description":"The board asks for the next clue.","script":"clue-store","inputs":{"type":"object","properties":{}},"bind":{"action":"board"},"reaction":{"gezel":"puzzelaar","prompt":"It is your turn in Word Clues. The game engine returned this state:\n```json\n{{output.modelState}}\n```\nIf `status` is `clue_needed`, call give_clue once: `clue` is one NEW word, not on the board, that links some of `yourWords`, `count` is how many it points at, and `say` is one short line of table talk. Never pick a clue that also fits `trap`, and avoid ones that fit `otherWords`. If the game is over, give no clue: say one warm line about how it went and offer another game.","hideSeed":true,"standalone":true,"turn":{"tool":"give_clue","when":{"op":"equals","field":"status","value":"clue_needed"}}}}],"pages":{"entry":"board/index.html","api":1,"reads":[{"source":"workspace","path":"game.json"}],"tools":["new_game","guess","pass","ask_clue_a","ask_clue_b"]},"schedules":[],"workspaceSeed":["game.json","words.json"],"artifactsSeed":[],"availableVersions":["1.0.4","1.0.3","1.0.2","1.0.1","1.0.0"]}}]}