wtf-p 0.8.0 → 0.8.2

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 (656) hide show
  1. package/README.md +34 -19
  2. package/bin/lib/adapter-compiler.js +411 -78
  3. package/bin/lib/clio-registration.js +44 -17
  4. package/bin/uninstall.js +19 -4
  5. package/package.json +3 -3
  6. package/protocol/actions/advance.json +232 -0
  7. package/protocol/actions/checkpoint.json +10 -1
  8. package/protocol/actions/execute-outline.json +10 -2
  9. package/protocol/actions/export-latex.json +15 -2
  10. package/protocol/actions/plan-revision.json +22 -4
  11. package/protocol/actions/polish-prose.json +13 -3
  12. package/protocol/actions/research-gap.json +16 -3
  13. package/protocol/actions/verify-work.json +13 -4
  14. package/protocol/aliases.lock.json +1 -0
  15. package/protocol/catalog.json +4 -2
  16. package/protocol/project/README.md +39 -0
  17. package/protocol/project/schemas/interaction.schema.json +100 -0
  18. package/protocol/project/templates/interaction.json +16 -0
  19. package/protocol/roles/research-synthesizer.md +1 -1
  20. package/protocol/skills/wtfp-deliver-research/SKILL.md +1 -1
  21. package/protocol/skills/wtfp-deliver-research/references/actions.md +2 -2
  22. package/protocol/skills/wtfp-manage-project/SKILL.md +2 -1
  23. package/protocol/skills/wtfp-manage-project/references/actions.md +13 -1
  24. package/protocol/skills/wtfp-plan-section/SKILL.md +1 -1
  25. package/protocol/skills/wtfp-plan-section/references/actions.md +4 -3
  26. package/protocol/skills/wtfp-research-literature/SKILL.md +1 -1
  27. package/protocol/skills/wtfp-research-literature/references/actions.md +1 -1
  28. package/protocol/skills/wtfp-review-manuscript/SKILL.md +1 -1
  29. package/protocol/skills/wtfp-review-manuscript/references/actions.md +2 -1
  30. package/protocol/skills/wtfp-write-section/SKILL.md +1 -1
  31. package/protocol/skills/wtfp-write-section/references/actions.md +1 -1
  32. package/protocol/workflows/advance.md +38 -0
  33. package/protocol/workflows/checkpoint.md +2 -2
  34. package/protocol/workflows/discuss-section.md +1 -1
  35. package/protocol/workflows/execute-outline.md +2 -2
  36. package/protocol/workflows/export-latex.md +4 -4
  37. package/protocol/workflows/plan-revision.md +4 -3
  38. package/protocol/workflows/plan-section.md +3 -3
  39. package/protocol/workflows/polish-prose.md +3 -3
  40. package/protocol/workflows/research-gap.md +5 -5
  41. package/protocol/workflows/verify-work.md +5 -3
  42. package/protocol/workflows/write-section.md +4 -4
  43. package/vendors/antigravity/.wtfp-generated.json +195 -183
  44. package/vendors/antigravity/actions/advance.json +232 -0
  45. package/vendors/antigravity/actions/checkpoint.json +10 -1
  46. package/vendors/antigravity/actions/execute-outline.json +10 -2
  47. package/vendors/antigravity/actions/export-latex.json +15 -2
  48. package/vendors/antigravity/actions/plan-revision.json +22 -4
  49. package/vendors/antigravity/actions/polish-prose.json +13 -3
  50. package/vendors/antigravity/actions/research-gap.json +16 -3
  51. package/vendors/antigravity/actions/verify-work.json +13 -4
  52. package/vendors/antigravity/agents/wtfp-research-synthesizer.md +1 -1
  53. package/vendors/antigravity/aliases.lock.json +1 -0
  54. package/vendors/antigravity/catalog.json +4 -2
  55. package/vendors/antigravity/compatibility/action-availability.json +13 -1
  56. package/vendors/antigravity/plugin.json +2 -1
  57. package/vendors/antigravity/project/README.md +39 -0
  58. package/vendors/antigravity/project/schemas/interaction.schema.json +100 -0
  59. package/vendors/antigravity/project/templates/interaction.json +16 -0
  60. package/vendors/antigravity/roles/research-synthesizer.md +1 -1
  61. package/vendors/antigravity/rules/wtfp-project-state.md +43 -1
  62. package/vendors/antigravity/{commands/wtfp-add-todo.md → skills/wtfp-add-todo/SKILL.md} +2 -3
  63. package/vendors/antigravity/skills/wtfp-advance/SKILL.md +18 -0
  64. package/vendors/antigravity/{commands/wtfp-analyze-bib.md → skills/wtfp-analyze-bib/SKILL.md} +2 -1
  65. package/vendors/antigravity/{commands/wtfp-audit-milestone.md → skills/wtfp-audit-milestone/SKILL.md} +2 -1
  66. package/vendors/antigravity/{commands/wtfp-check-refs.md → skills/wtfp-check-refs/SKILL.md} +2 -1
  67. package/vendors/antigravity/{commands/wtfp-check-todos.md → skills/wtfp-check-todos/SKILL.md} +2 -1
  68. package/vendors/antigravity/{commands/wtfp-checkpoint.md → skills/wtfp-checkpoint/SKILL.md} +4 -17
  69. package/vendors/antigravity/{commands/wtfp-contribute.md → skills/wtfp-contribute/SKILL.md} +2 -1
  70. package/vendors/antigravity/{commands/wtfp-create-outline.md → skills/wtfp-create-outline/SKILL.md} +2 -9
  71. package/vendors/antigravity/{commands/wtfp-create-poster.md → skills/wtfp-create-poster/SKILL.md} +3 -7
  72. package/vendors/antigravity/{commands/wtfp-create-slides.md → skills/wtfp-create-slides/SKILL.md} +3 -7
  73. package/vendors/antigravity/skills/wtfp-deliver-research/SKILL.md +1 -1
  74. package/vendors/antigravity/skills/wtfp-deliver-research/references/actions.md +2 -2
  75. package/vendors/antigravity/{commands/wtfp-discuss-section.md → skills/wtfp-discuss-section/SKILL.md} +3 -6
  76. package/vendors/antigravity/{commands/wtfp-execute-outline.md → skills/wtfp-execute-outline/SKILL.md} +4 -13
  77. package/vendors/antigravity/{commands/wtfp-export-latex.md → skills/wtfp-export-latex/SKILL.md} +2 -1
  78. package/vendors/antigravity/{commands/wtfp-help.md → skills/wtfp-help/SKILL.md} +4 -3
  79. package/vendors/antigravity/{commands/wtfp-insert-section.md → skills/wtfp-insert-section/SKILL.md} +2 -1
  80. package/vendors/antigravity/{commands/wtfp-list-assumptions.md → skills/wtfp-list-assumptions/SKILL.md} +3 -11
  81. package/vendors/antigravity/skills/wtfp-manage-project/SKILL.md +2 -1
  82. package/vendors/antigravity/skills/wtfp-manage-project/references/actions.md +29 -1
  83. package/vendors/antigravity/{commands/wtfp-map-project.md → skills/wtfp-map-project/SKILL.md} +2 -1
  84. package/vendors/antigravity/{commands/wtfp-new-paper.md → skills/wtfp-new-paper/SKILL.md} +2 -1
  85. package/vendors/antigravity/{commands/wtfp-pause-writing.md → skills/wtfp-pause-writing/SKILL.md} +2 -7
  86. package/vendors/antigravity/{commands/wtfp-plan-milestone-gaps.md → skills/wtfp-plan-milestone-gaps/SKILL.md} +2 -7
  87. package/vendors/antigravity/{commands/wtfp-plan-revision.md → skills/wtfp-plan-revision/SKILL.md} +10 -10
  88. package/vendors/antigravity/skills/wtfp-plan-section/SKILL.md +1 -1
  89. package/vendors/antigravity/skills/wtfp-plan-section/references/actions.md +4 -3
  90. package/vendors/antigravity/{commands/wtfp-polish-prose.md → skills/wtfp-polish-prose/SKILL.md} +9 -10
  91. package/vendors/antigravity/{commands/wtfp-progress.md → skills/wtfp-progress/SKILL.md} +3 -23
  92. package/vendors/antigravity/{commands/wtfp-quick.md → skills/wtfp-quick/SKILL.md} +2 -5
  93. package/vendors/antigravity/{commands/wtfp-remove-section.md → skills/wtfp-remove-section/SKILL.md} +2 -1
  94. package/vendors/antigravity/{commands/wtfp-report-bug.md → skills/wtfp-report-bug/SKILL.md} +2 -1
  95. package/vendors/antigravity/{commands/wtfp-request-feature.md → skills/wtfp-request-feature/SKILL.md} +2 -1
  96. package/vendors/antigravity/{commands/wtfp-research-gap.md → skills/wtfp-research-gap/SKILL.md} +2 -1
  97. package/vendors/antigravity/skills/wtfp-research-literature/SKILL.md +1 -1
  98. package/vendors/antigravity/skills/wtfp-research-literature/references/actions.md +1 -1
  99. package/vendors/antigravity/{commands/wtfp-resume-writing.md → skills/wtfp-resume-writing/SKILL.md} +2 -13
  100. package/vendors/antigravity/skills/wtfp-review-manuscript/SKILL.md +1 -1
  101. package/vendors/antigravity/skills/wtfp-review-manuscript/references/actions.md +2 -1
  102. package/vendors/antigravity/{commands/wtfp-review-section.md → skills/wtfp-review-section/SKILL.md} +2 -9
  103. package/vendors/antigravity/{commands/wtfp-settings.md → skills/wtfp-settings/SKILL.md} +2 -1
  104. package/vendors/antigravity/{commands/wtfp-submit-milestone.md → skills/wtfp-submit-milestone/SKILL.md} +2 -13
  105. package/vendors/antigravity/{commands/wtfp-update.md → skills/wtfp-update/SKILL.md} +2 -1
  106. package/vendors/antigravity/{commands/wtfp-verify-work.md → skills/wtfp-verify-work/SKILL.md} +9 -6
  107. package/vendors/antigravity/skills/wtfp-write-section/SKILL.md +1 -1
  108. package/vendors/antigravity/skills/wtfp-write-section/references/actions.md +1 -1
  109. package/vendors/antigravity/tools/README.md +1 -1
  110. package/vendors/antigravity/workflows/advance.md +38 -0
  111. package/vendors/antigravity/workflows/checkpoint.md +2 -2
  112. package/vendors/antigravity/workflows/discuss-section.md +1 -1
  113. package/vendors/antigravity/workflows/execute-outline.md +2 -2
  114. package/vendors/antigravity/workflows/export-latex.md +4 -4
  115. package/vendors/antigravity/workflows/plan-revision.md +4 -3
  116. package/vendors/antigravity/workflows/plan-section.md +3 -3
  117. package/vendors/antigravity/workflows/polish-prose.md +3 -3
  118. package/vendors/antigravity/workflows/research-gap.md +5 -5
  119. package/vendors/antigravity/workflows/verify-work.md +5 -3
  120. package/vendors/antigravity/workflows/write-section.md +4 -4
  121. package/vendors/claude/.claude-plugin/marketplace.json +2 -2
  122. package/vendors/claude/.claude-plugin/plugin.json +1 -1
  123. package/vendors/claude/.wtfp-generated.json +135 -111
  124. package/vendors/claude/actions/advance.json +232 -0
  125. package/vendors/claude/actions/checkpoint.json +10 -1
  126. package/vendors/claude/actions/execute-outline.json +10 -2
  127. package/vendors/claude/actions/export-latex.json +15 -2
  128. package/vendors/claude/actions/plan-revision.json +22 -4
  129. package/vendors/claude/actions/polish-prose.json +13 -3
  130. package/vendors/claude/actions/research-gap.json +16 -3
  131. package/vendors/claude/actions/verify-work.json +13 -4
  132. package/vendors/claude/agents/wtfp-research-synthesizer.md +1 -1
  133. package/vendors/claude/ai.iowarp.clio/agents/wtfp-argument-verifier.md +7 -8
  134. package/vendors/claude/ai.iowarp.clio/agents/wtfp-citation-expert.md +5 -5
  135. package/vendors/claude/ai.iowarp.clio/agents/wtfp-citation-formatter.md +3 -3
  136. package/vendors/claude/ai.iowarp.clio/agents/wtfp-coherence-checker.md +9 -10
  137. package/vendors/claude/ai.iowarp.clio/agents/wtfp-outliner.md +3 -3
  138. package/vendors/claude/ai.iowarp.clio/agents/wtfp-plan-checker.md +7 -8
  139. package/vendors/claude/ai.iowarp.clio/agents/wtfp-prose-polisher.md +4 -4
  140. package/vendors/claude/ai.iowarp.clio/agents/wtfp-research-synthesizer.md +6 -6
  141. package/vendors/claude/ai.iowarp.clio/agents/wtfp-section-planner.md +3 -3
  142. package/vendors/claude/ai.iowarp.clio/agents/wtfp-section-reviewer.md +9 -10
  143. package/vendors/claude/ai.iowarp.clio/agents/wtfp-section-writer.md +3 -3
  144. package/vendors/claude/ai.iowarp.clio/fleets/wtfp-draft-review.md +1 -1
  145. package/vendors/claude/ai.iowarp.clio/fleets/wtfp-plan-section.md +1 -1
  146. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/add-todo.md +8 -2
  147. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/advance.md +15 -0
  148. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/analyze-bib.md +26 -8
  149. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/audit-milestone.md +12 -16
  150. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/check-refs.md +26 -8
  151. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/check-todos.md +11 -0
  152. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/checkpoint.md +13 -16
  153. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/create-outline.md +25 -10
  154. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/create-poster.md +12 -6
  155. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/create-slides.md +12 -6
  156. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/discuss-section.md +12 -5
  157. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/execute-outline.md +27 -14
  158. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/export-latex.md +16 -12
  159. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/help.md +4 -1
  160. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/insert-section.md +11 -0
  161. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/list-assumptions.md +7 -10
  162. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/map-project.md +8 -0
  163. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/new-paper.md +11 -0
  164. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/pause-writing.md +8 -6
  165. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/plan-milestone-gaps.md +11 -6
  166. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/plan-revision.md +19 -9
  167. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/plan-section.md +28 -17
  168. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/polish-prose.md +32 -11
  169. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/progress.md +10 -22
  170. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/quick.md +25 -6
  171. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/research-gap.md +37 -16
  172. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/resume-writing.md +11 -12
  173. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/review-section.md +22 -10
  174. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/settings.md +11 -0
  175. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/submit-milestone.md +11 -12
  176. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/verify-work.md +18 -5
  177. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/write-section.md +29 -16
  178. package/vendors/claude/aliases.lock.json +1 -0
  179. package/vendors/claude/catalog.json +4 -2
  180. package/vendors/claude/commands/add-todo.md +0 -2
  181. package/vendors/claude/commands/advance.md +16 -0
  182. package/vendors/claude/commands/analyze-bib.md +0 -6
  183. package/vendors/claude/commands/audit-milestone.md +0 -16
  184. package/vendors/claude/commands/check-refs.md +0 -6
  185. package/vendors/claude/commands/checkpoint.md +2 -16
  186. package/vendors/claude/commands/create-outline.md +0 -8
  187. package/vendors/claude/commands/create-poster.md +1 -6
  188. package/vendors/claude/commands/create-slides.md +1 -6
  189. package/vendors/claude/commands/discuss-section.md +1 -5
  190. package/vendors/claude/commands/execute-outline.md +2 -12
  191. package/vendors/claude/commands/export-latex.md +4 -12
  192. package/vendors/claude/commands/help.md +1 -1
  193. package/vendors/claude/commands/list-assumptions.md +1 -10
  194. package/vendors/claude/commands/pause-writing.md +0 -6
  195. package/vendors/claude/commands/plan-milestone-gaps.md +0 -6
  196. package/vendors/claude/commands/plan-revision.md +8 -9
  197. package/vendors/claude/commands/plan-section.md +3 -15
  198. package/vendors/claude/commands/polish-prose.md +7 -9
  199. package/vendors/claude/commands/progress.md +1 -22
  200. package/vendors/claude/commands/quick.md +0 -4
  201. package/vendors/claude/commands/research-gap.md +5 -13
  202. package/vendors/claude/commands/resume-writing.md +0 -12
  203. package/vendors/claude/commands/review-section.md +0 -8
  204. package/vendors/claude/commands/submit-milestone.md +0 -12
  205. package/vendors/claude/commands/verify-work.md +7 -5
  206. package/vendors/claude/commands/write-section.md +4 -14
  207. package/vendors/claude/compatibility/action-availability.json +10 -1
  208. package/vendors/claude/output-styles/wtfp-academic-writing.md +7 -7
  209. package/vendors/claude/plugin.json +15 -1
  210. package/vendors/claude/project/README.md +39 -0
  211. package/vendors/claude/project/schemas/interaction.schema.json +100 -0
  212. package/vendors/claude/project/templates/interaction.json +16 -0
  213. package/vendors/claude/roles/research-synthesizer.md +1 -1
  214. package/vendors/claude/skills/wtfp-deliver-research/SKILL.md +1 -1
  215. package/vendors/claude/skills/wtfp-deliver-research/references/actions.md +2 -2
  216. package/vendors/claude/skills/wtfp-manage-project/SKILL.md +2 -1
  217. package/vendors/claude/skills/wtfp-manage-project/references/actions.md +29 -1
  218. package/vendors/claude/skills/wtfp-plan-section/SKILL.md +1 -1
  219. package/vendors/claude/skills/wtfp-plan-section/references/actions.md +4 -3
  220. package/vendors/claude/skills/wtfp-research-literature/SKILL.md +1 -1
  221. package/vendors/claude/skills/wtfp-research-literature/references/actions.md +1 -1
  222. package/vendors/claude/skills/wtfp-review-manuscript/SKILL.md +1 -1
  223. package/vendors/claude/skills/wtfp-review-manuscript/references/actions.md +2 -1
  224. package/vendors/claude/skills/wtfp-write-section/SKILL.md +1 -1
  225. package/vendors/claude/skills/wtfp-write-section/references/actions.md +1 -1
  226. package/vendors/claude/tools/README.md +1 -1
  227. package/vendors/claude/workflows/advance.md +38 -0
  228. package/vendors/claude/workflows/checkpoint.md +2 -2
  229. package/vendors/claude/workflows/discuss-section.md +1 -1
  230. package/vendors/claude/workflows/execute-outline.md +2 -2
  231. package/vendors/claude/workflows/export-latex.md +4 -4
  232. package/vendors/claude/workflows/plan-revision.md +4 -3
  233. package/vendors/claude/workflows/plan-section.md +3 -3
  234. package/vendors/claude/workflows/polish-prose.md +3 -3
  235. package/vendors/claude/workflows/research-gap.md +5 -5
  236. package/vendors/claude/workflows/verify-work.md +5 -3
  237. package/vendors/claude/workflows/write-section.md +4 -4
  238. package/vendors/clio-extension/.wtfp-generated.json +73 -13
  239. package/vendors/clio-extension/actions/advance.json +232 -0
  240. package/vendors/clio-extension/actions/checkpoint.json +10 -1
  241. package/vendors/clio-extension/actions/execute-outline.json +10 -2
  242. package/vendors/clio-extension/actions/export-latex.json +15 -2
  243. package/vendors/clio-extension/actions/plan-revision.json +22 -4
  244. package/vendors/clio-extension/actions/polish-prose.json +13 -3
  245. package/vendors/clio-extension/actions/research-gap.json +16 -3
  246. package/vendors/clio-extension/actions/verify-work.json +13 -4
  247. package/vendors/clio-extension/clio-coder-extension.yaml +48 -10
  248. package/vendors/clio-extension/compatibility/action-availability.json +11 -5
  249. package/vendors/clio-extension/project/schemas/interaction.schema.json +100 -0
  250. package/vendors/clio-extension/project/templates/checkpoint.json +25 -0
  251. package/vendors/clio-extension/project/templates/config.json +31 -0
  252. package/vendors/clio-extension/project/templates/decisions.json +35 -0
  253. package/vendors/clio-extension/project/templates/evidence.json +18 -0
  254. package/vendors/clio-extension/project/templates/interaction.json +16 -0
  255. package/vendors/clio-extension/project/templates/manifest.json +30 -0
  256. package/vendors/clio-extension/project/templates/outline.json +38 -0
  257. package/vendors/clio-extension/project/templates/section.json +32 -0
  258. package/vendors/clio-extension/project/templates/source.json +20 -0
  259. package/vendors/clio-extension/project/templates/state.json +22 -0
  260. package/vendors/clio-extension/project/templates/validation.json +32 -0
  261. package/vendors/clio-extension/runtime/claim-coverage.cjs +332 -0
  262. package/vendors/clio-extension/runtime/desk-trust.cjs +112 -0
  263. package/vendors/clio-extension/runtime/extension.test.ts +2034 -65
  264. package/vendors/clio-extension/runtime/extension.ts +3032 -435
  265. package/vendors/clio-extension/runtime/write-guard.json +629 -18
  266. package/vendors/codex/plugins/wtfp/.codex-plugin/plugin.json +1 -1
  267. package/vendors/codex/plugins/wtfp/.wtfp-generated.json +55 -39
  268. package/vendors/codex/plugins/wtfp/actions/advance.json +232 -0
  269. package/vendors/codex/plugins/wtfp/actions/checkpoint.json +10 -1
  270. package/vendors/codex/plugins/wtfp/actions/execute-outline.json +10 -2
  271. package/vendors/codex/plugins/wtfp/actions/export-latex.json +15 -2
  272. package/vendors/codex/plugins/wtfp/actions/plan-revision.json +22 -4
  273. package/vendors/codex/plugins/wtfp/actions/polish-prose.json +13 -3
  274. package/vendors/codex/plugins/wtfp/actions/research-gap.json +16 -3
  275. package/vendors/codex/plugins/wtfp/actions/verify-work.json +13 -4
  276. package/vendors/codex/plugins/wtfp/agents/wtfp-research-synthesizer.toml +1 -1
  277. package/vendors/codex/plugins/wtfp/aliases.lock.json +1 -0
  278. package/vendors/codex/plugins/wtfp/catalog.json +4 -2
  279. package/vendors/codex/plugins/wtfp/compatibility/action-availability.json +13 -1
  280. package/vendors/codex/plugins/wtfp/plugin.json +1 -1
  281. package/vendors/codex/plugins/wtfp/project/README.md +39 -0
  282. package/vendors/codex/plugins/wtfp/project/schemas/interaction.schema.json +100 -0
  283. package/vendors/codex/plugins/wtfp/project/templates/interaction.json +16 -0
  284. package/vendors/codex/plugins/wtfp/roles/research-synthesizer.md +1 -1
  285. package/vendors/codex/plugins/wtfp/skills/wtfp-deliver-research/SKILL.md +1 -1
  286. package/vendors/codex/plugins/wtfp/skills/wtfp-deliver-research/references/actions.md +2 -2
  287. package/vendors/codex/plugins/wtfp/skills/wtfp-manage-project/SKILL.md +2 -1
  288. package/vendors/codex/plugins/wtfp/skills/wtfp-manage-project/references/actions.md +29 -1
  289. package/vendors/codex/plugins/wtfp/skills/wtfp-plan-section/SKILL.md +1 -1
  290. package/vendors/codex/plugins/wtfp/skills/wtfp-plan-section/references/actions.md +4 -3
  291. package/vendors/codex/plugins/wtfp/skills/wtfp-research-literature/SKILL.md +1 -1
  292. package/vendors/codex/plugins/wtfp/skills/wtfp-research-literature/references/actions.md +1 -1
  293. package/vendors/codex/plugins/wtfp/skills/wtfp-review-manuscript/SKILL.md +1 -1
  294. package/vendors/codex/plugins/wtfp/skills/wtfp-review-manuscript/references/actions.md +2 -1
  295. package/vendors/codex/plugins/wtfp/skills/wtfp-write-section/SKILL.md +1 -1
  296. package/vendors/codex/plugins/wtfp/skills/wtfp-write-section/references/actions.md +1 -1
  297. package/vendors/codex/plugins/wtfp/tools/README.md +1 -1
  298. package/vendors/codex/plugins/wtfp/workflows/advance.md +38 -0
  299. package/vendors/codex/plugins/wtfp/workflows/checkpoint.md +2 -2
  300. package/vendors/codex/plugins/wtfp/workflows/discuss-section.md +1 -1
  301. package/vendors/codex/plugins/wtfp/workflows/execute-outline.md +2 -2
  302. package/vendors/codex/plugins/wtfp/workflows/export-latex.md +4 -4
  303. package/vendors/codex/plugins/wtfp/workflows/plan-revision.md +4 -3
  304. package/vendors/codex/plugins/wtfp/workflows/plan-section.md +3 -3
  305. package/vendors/codex/plugins/wtfp/workflows/polish-prose.md +3 -3
  306. package/vendors/codex/plugins/wtfp/workflows/research-gap.md +5 -5
  307. package/vendors/codex/plugins/wtfp/workflows/verify-work.md +5 -3
  308. package/vendors/codex/plugins/wtfp/workflows/write-section.md +4 -4
  309. package/vendors/copilot/.wtfp-generated.json +74 -54
  310. package/vendors/copilot/marketplace.json +2 -2
  311. package/vendors/copilot/plugins/wtfp/.claude-plugin/plugin.json +1 -1
  312. package/vendors/copilot/plugins/wtfp/.wtfp-generated.json +79 -59
  313. package/vendors/copilot/plugins/wtfp/actions/advance.json +232 -0
  314. package/vendors/copilot/plugins/wtfp/actions/checkpoint.json +10 -1
  315. package/vendors/copilot/plugins/wtfp/actions/execute-outline.json +10 -2
  316. package/vendors/copilot/plugins/wtfp/actions/export-latex.json +15 -2
  317. package/vendors/copilot/plugins/wtfp/actions/plan-revision.json +22 -4
  318. package/vendors/copilot/plugins/wtfp/actions/polish-prose.json +13 -3
  319. package/vendors/copilot/plugins/wtfp/actions/research-gap.json +16 -3
  320. package/vendors/copilot/plugins/wtfp/actions/verify-work.json +13 -4
  321. package/vendors/copilot/plugins/wtfp/agents/wtfp-research-synthesizer.md +1 -1
  322. package/vendors/copilot/plugins/wtfp/aliases.lock.json +1 -0
  323. package/vendors/copilot/plugins/wtfp/catalog.json +4 -2
  324. package/vendors/copilot/plugins/wtfp/commands/wtfp-add-todo.md +0 -2
  325. package/vendors/copilot/plugins/wtfp/commands/wtfp-advance.md +17 -0
  326. package/vendors/copilot/plugins/wtfp/commands/wtfp-checkpoint.md +2 -16
  327. package/vendors/copilot/plugins/wtfp/commands/wtfp-create-outline.md +0 -8
  328. package/vendors/copilot/plugins/wtfp/commands/wtfp-create-poster.md +1 -6
  329. package/vendors/copilot/plugins/wtfp/commands/wtfp-create-slides.md +1 -6
  330. package/vendors/copilot/plugins/wtfp/commands/wtfp-discuss-section.md +1 -5
  331. package/vendors/copilot/plugins/wtfp/commands/wtfp-execute-outline.md +2 -12
  332. package/vendors/copilot/plugins/wtfp/commands/wtfp-help.md +1 -1
  333. package/vendors/copilot/plugins/wtfp/commands/wtfp-list-assumptions.md +1 -10
  334. package/vendors/copilot/plugins/wtfp/commands/wtfp-pause-writing.md +0 -6
  335. package/vendors/copilot/plugins/wtfp/commands/wtfp-plan-milestone-gaps.md +0 -6
  336. package/vendors/copilot/plugins/wtfp/commands/wtfp-plan-revision.md +8 -9
  337. package/vendors/copilot/plugins/wtfp/commands/wtfp-plan-section.md +3 -15
  338. package/vendors/copilot/plugins/wtfp/commands/wtfp-polish-prose.md +7 -9
  339. package/vendors/copilot/plugins/wtfp/commands/wtfp-progress.md +1 -22
  340. package/vendors/copilot/plugins/wtfp/commands/wtfp-quick.md +0 -4
  341. package/vendors/copilot/plugins/wtfp/commands/wtfp-resume-writing.md +0 -12
  342. package/vendors/copilot/plugins/wtfp/commands/wtfp-review-section.md +0 -8
  343. package/vendors/copilot/plugins/wtfp/commands/wtfp-submit-milestone.md +0 -12
  344. package/vendors/copilot/plugins/wtfp/commands/wtfp-verify-work.md +7 -5
  345. package/vendors/copilot/plugins/wtfp/commands/wtfp-write-section.md +4 -14
  346. package/vendors/copilot/plugins/wtfp/compatibility/action-availability.json +13 -1
  347. package/vendors/copilot/plugins/wtfp/project/README.md +39 -0
  348. package/vendors/copilot/plugins/wtfp/project/schemas/interaction.schema.json +100 -0
  349. package/vendors/copilot/plugins/wtfp/project/templates/interaction.json +16 -0
  350. package/vendors/copilot/plugins/wtfp/roles/research-synthesizer.md +1 -1
  351. package/vendors/copilot/plugins/wtfp/skills/wtfp-deliver-research/SKILL.md +1 -1
  352. package/vendors/copilot/plugins/wtfp/skills/wtfp-deliver-research/references/actions.md +2 -2
  353. package/vendors/copilot/plugins/wtfp/skills/wtfp-manage-project/SKILL.md +2 -1
  354. package/vendors/copilot/plugins/wtfp/skills/wtfp-manage-project/references/actions.md +29 -1
  355. package/vendors/copilot/plugins/wtfp/skills/wtfp-plan-section/SKILL.md +1 -1
  356. package/vendors/copilot/plugins/wtfp/skills/wtfp-plan-section/references/actions.md +4 -3
  357. package/vendors/copilot/plugins/wtfp/skills/wtfp-research-literature/SKILL.md +1 -1
  358. package/vendors/copilot/plugins/wtfp/skills/wtfp-research-literature/references/actions.md +1 -1
  359. package/vendors/copilot/plugins/wtfp/skills/wtfp-review-manuscript/SKILL.md +1 -1
  360. package/vendors/copilot/plugins/wtfp/skills/wtfp-review-manuscript/references/actions.md +2 -1
  361. package/vendors/copilot/plugins/wtfp/skills/wtfp-write-section/SKILL.md +1 -1
  362. package/vendors/copilot/plugins/wtfp/skills/wtfp-write-section/references/actions.md +1 -1
  363. package/vendors/copilot/plugins/wtfp/tools/README.md +1 -1
  364. package/vendors/copilot/plugins/wtfp/workflows/advance.md +38 -0
  365. package/vendors/copilot/plugins/wtfp/workflows/checkpoint.md +2 -2
  366. package/vendors/copilot/plugins/wtfp/workflows/discuss-section.md +1 -1
  367. package/vendors/copilot/plugins/wtfp/workflows/execute-outline.md +2 -2
  368. package/vendors/copilot/plugins/wtfp/workflows/export-latex.md +4 -4
  369. package/vendors/copilot/plugins/wtfp/workflows/plan-revision.md +4 -3
  370. package/vendors/copilot/plugins/wtfp/workflows/plan-section.md +3 -3
  371. package/vendors/copilot/plugins/wtfp/workflows/polish-prose.md +3 -3
  372. package/vendors/copilot/plugins/wtfp/workflows/research-gap.md +5 -5
  373. package/vendors/copilot/plugins/wtfp/workflows/verify-work.md +5 -3
  374. package/vendors/copilot/plugins/wtfp/workflows/write-section.md +4 -4
  375. package/vendors/copilot/project/.github/agents/wtfp-research-synthesizer.agent.md +1 -1
  376. package/vendors/copilot/project/.github/prompts/wtfp-add-todo.prompt.md +0 -2
  377. package/vendors/copilot/project/.github/prompts/wtfp-advance.prompt.md +18 -0
  378. package/vendors/copilot/project/.github/prompts/wtfp-help.prompt.md +1 -1
  379. package/vendors/copilot/project/.github/prompts/wtfp-list-assumptions.prompt.md +1 -10
  380. package/vendors/copilot/project/.github/prompts/wtfp-pause-writing.prompt.md +0 -6
  381. package/vendors/copilot/project/.github/skills/wtfp-deliver-research/SKILL.md +1 -1
  382. package/vendors/copilot/project/.github/skills/wtfp-deliver-research/references/actions.md +2 -2
  383. package/vendors/copilot/project/.github/skills/wtfp-manage-project/SKILL.md +2 -1
  384. package/vendors/copilot/project/.github/skills/wtfp-manage-project/references/actions.md +25 -1
  385. package/vendors/copilot/project/.github/skills/wtfp-plan-section/SKILL.md +1 -1
  386. package/vendors/copilot/project/.github/skills/wtfp-plan-section/references/actions.md +4 -3
  387. package/vendors/copilot/project/.github/skills/wtfp-research-literature/SKILL.md +1 -1
  388. package/vendors/copilot/project/.github/skills/wtfp-research-literature/references/actions.md +1 -1
  389. package/vendors/copilot/project/.github/skills/wtfp-review-manuscript/SKILL.md +1 -1
  390. package/vendors/copilot/project/.github/skills/wtfp-review-manuscript/references/actions.md +2 -1
  391. package/vendors/copilot/project/.github/skills/wtfp-write-section/SKILL.md +1 -1
  392. package/vendors/copilot/project/.github/skills/wtfp-write-section/references/actions.md +1 -1
  393. package/vendors/copilot/project/.github/wtfp/actions/advance.json +232 -0
  394. package/vendors/copilot/project/.github/wtfp/actions/checkpoint.json +10 -1
  395. package/vendors/copilot/project/.github/wtfp/actions/execute-outline.json +10 -2
  396. package/vendors/copilot/project/.github/wtfp/actions/export-latex.json +15 -2
  397. package/vendors/copilot/project/.github/wtfp/actions/plan-revision.json +22 -4
  398. package/vendors/copilot/project/.github/wtfp/actions/polish-prose.json +13 -3
  399. package/vendors/copilot/project/.github/wtfp/actions/research-gap.json +16 -3
  400. package/vendors/copilot/project/.github/wtfp/actions/verify-work.json +13 -4
  401. package/vendors/copilot/project/.github/wtfp/aliases.lock.json +1 -0
  402. package/vendors/copilot/project/.github/wtfp/catalog.json +4 -2
  403. package/vendors/copilot/project/.github/wtfp/compatibility/action-availability.json +14 -1
  404. package/vendors/copilot/project/.github/wtfp/project/README.md +39 -0
  405. package/vendors/copilot/project/.github/wtfp/project/schemas/interaction.schema.json +100 -0
  406. package/vendors/copilot/project/.github/wtfp/project/templates/interaction.json +16 -0
  407. package/vendors/copilot/project/.github/wtfp/roles/research-synthesizer.md +1 -1
  408. package/vendors/copilot/project/.github/wtfp/skills/wtfp-deliver-research/SKILL.md +1 -1
  409. package/vendors/copilot/project/.github/wtfp/skills/wtfp-deliver-research/references/actions.md +2 -2
  410. package/vendors/copilot/project/.github/wtfp/skills/wtfp-manage-project/SKILL.md +2 -1
  411. package/vendors/copilot/project/.github/wtfp/skills/wtfp-manage-project/references/actions.md +13 -1
  412. package/vendors/copilot/project/.github/wtfp/skills/wtfp-plan-section/SKILL.md +1 -1
  413. package/vendors/copilot/project/.github/wtfp/skills/wtfp-plan-section/references/actions.md +4 -3
  414. package/vendors/copilot/project/.github/wtfp/skills/wtfp-research-literature/SKILL.md +1 -1
  415. package/vendors/copilot/project/.github/wtfp/skills/wtfp-research-literature/references/actions.md +1 -1
  416. package/vendors/copilot/project/.github/wtfp/skills/wtfp-review-manuscript/SKILL.md +1 -1
  417. package/vendors/copilot/project/.github/wtfp/skills/wtfp-review-manuscript/references/actions.md +2 -1
  418. package/vendors/copilot/project/.github/wtfp/skills/wtfp-write-section/SKILL.md +1 -1
  419. package/vendors/copilot/project/.github/wtfp/skills/wtfp-write-section/references/actions.md +1 -1
  420. package/vendors/copilot/project/.github/wtfp/workflows/advance.md +38 -0
  421. package/vendors/copilot/project/.github/wtfp/workflows/checkpoint.md +2 -2
  422. package/vendors/copilot/project/.github/wtfp/workflows/discuss-section.md +1 -1
  423. package/vendors/copilot/project/.github/wtfp/workflows/execute-outline.md +2 -2
  424. package/vendors/copilot/project/.github/wtfp/workflows/export-latex.md +4 -4
  425. package/vendors/copilot/project/.github/wtfp/workflows/plan-revision.md +4 -3
  426. package/vendors/copilot/project/.github/wtfp/workflows/plan-section.md +3 -3
  427. package/vendors/copilot/project/.github/wtfp/workflows/polish-prose.md +3 -3
  428. package/vendors/copilot/project/.github/wtfp/workflows/research-gap.md +5 -5
  429. package/vendors/copilot/project/.github/wtfp/workflows/verify-work.md +5 -3
  430. package/vendors/copilot/project/.github/wtfp/workflows/write-section.md +4 -4
  431. package/vendors/copilot/project/README.md +1 -1
  432. package/vendors/gemini/.wtfp-generated.json +84 -64
  433. package/vendors/gemini/actions/advance.json +232 -0
  434. package/vendors/gemini/actions/checkpoint.json +10 -1
  435. package/vendors/gemini/actions/execute-outline.json +10 -2
  436. package/vendors/gemini/actions/export-latex.json +15 -2
  437. package/vendors/gemini/actions/plan-revision.json +22 -4
  438. package/vendors/gemini/actions/polish-prose.json +13 -3
  439. package/vendors/gemini/actions/research-gap.json +16 -3
  440. package/vendors/gemini/actions/verify-work.json +13 -4
  441. package/vendors/gemini/agents/wtfp-research-synthesizer.md +1 -1
  442. package/vendors/gemini/aliases.lock.json +1 -0
  443. package/vendors/gemini/catalog.json +4 -2
  444. package/vendors/gemini/commands/wtfp/add-todo.toml +54 -144
  445. package/vendors/gemini/commands/wtfp/advance.toml +14 -0
  446. package/vendors/gemini/commands/wtfp/check-todos.toml +54 -2
  447. package/vendors/gemini/commands/wtfp/checkpoint.toml +66 -738
  448. package/vendors/gemini/commands/wtfp/create-outline.toml +39 -431
  449. package/vendors/gemini/commands/wtfp/create-poster.toml +43 -299
  450. package/vendors/gemini/commands/wtfp/create-slides.toml +43 -299
  451. package/vendors/gemini/commands/wtfp/discuss-section.toml +45 -262
  452. package/vendors/gemini/commands/wtfp/execute-outline.toml +53 -486
  453. package/vendors/gemini/commands/wtfp/help.toml +44 -3
  454. package/vendors/gemini/commands/wtfp/insert-section.toml +44 -4
  455. package/vendors/gemini/commands/wtfp/list-assumptions.toml +45 -513
  456. package/vendors/gemini/commands/wtfp/map-project.toml +39 -0
  457. package/vendors/gemini/commands/wtfp/new-paper.toml +39 -0
  458. package/vendors/gemini/commands/wtfp/pause-writing.toml +54 -309
  459. package/vendors/gemini/commands/wtfp/plan-milestone-gaps.toml +42 -370
  460. package/vendors/gemini/commands/wtfp/plan-revision.toml +229 -277
  461. package/vendors/gemini/commands/wtfp/plan-section.toml +47 -629
  462. package/vendors/gemini/commands/wtfp/polish-prose.toml +217 -268
  463. package/vendors/gemini/commands/wtfp/progress.toml +55 -1143
  464. package/vendors/gemini/commands/wtfp/quick.toml +41 -220
  465. package/vendors/gemini/commands/wtfp/resume-writing.toml +54 -698
  466. package/vendors/gemini/commands/wtfp/review-section.toml +42 -411
  467. package/vendors/gemini/commands/wtfp/settings.toml +54 -2
  468. package/vendors/gemini/commands/wtfp/submit-milestone.toml +42 -620
  469. package/vendors/gemini/commands/wtfp/verify-work.toml +169 -57
  470. package/vendors/gemini/commands/wtfp/write-section.toml +45 -486
  471. package/vendors/gemini/compatibility/action-availability.json +13 -1
  472. package/vendors/gemini/gemini-extension.json +1 -1
  473. package/vendors/gemini/project/README.md +39 -0
  474. package/vendors/gemini/project/schemas/interaction.schema.json +100 -0
  475. package/vendors/gemini/project/templates/interaction.json +16 -0
  476. package/vendors/gemini/roles/research-synthesizer.md +1 -1
  477. package/vendors/gemini/skills/wtfp-deliver-research/SKILL.md +1 -1
  478. package/vendors/gemini/skills/wtfp-deliver-research/references/actions.md +2 -2
  479. package/vendors/gemini/skills/wtfp-manage-project/SKILL.md +2 -1
  480. package/vendors/gemini/skills/wtfp-manage-project/references/actions.md +29 -1
  481. package/vendors/gemini/skills/wtfp-plan-section/SKILL.md +1 -1
  482. package/vendors/gemini/skills/wtfp-plan-section/references/actions.md +4 -3
  483. package/vendors/gemini/skills/wtfp-research-literature/SKILL.md +1 -1
  484. package/vendors/gemini/skills/wtfp-research-literature/references/actions.md +1 -1
  485. package/vendors/gemini/skills/wtfp-review-manuscript/SKILL.md +1 -1
  486. package/vendors/gemini/skills/wtfp-review-manuscript/references/actions.md +2 -1
  487. package/vendors/gemini/skills/wtfp-write-section/SKILL.md +1 -1
  488. package/vendors/gemini/skills/wtfp-write-section/references/actions.md +1 -1
  489. package/vendors/gemini/tools/README.md +1 -1
  490. package/vendors/gemini/workflows/advance.md +38 -0
  491. package/vendors/gemini/workflows/checkpoint.md +2 -2
  492. package/vendors/gemini/workflows/discuss-section.md +1 -1
  493. package/vendors/gemini/workflows/execute-outline.md +2 -2
  494. package/vendors/gemini/workflows/export-latex.md +4 -4
  495. package/vendors/gemini/workflows/plan-revision.md +4 -3
  496. package/vendors/gemini/workflows/plan-section.md +3 -3
  497. package/vendors/gemini/workflows/polish-prose.md +3 -3
  498. package/vendors/gemini/workflows/research-gap.md +5 -5
  499. package/vendors/gemini/workflows/verify-work.md +5 -3
  500. package/vendors/gemini/workflows/write-section.md +4 -4
  501. package/vendors/opencode/.wtfp-generated.json +83 -63
  502. package/vendors/opencode/actions/advance.json +232 -0
  503. package/vendors/opencode/actions/checkpoint.json +10 -1
  504. package/vendors/opencode/actions/execute-outline.json +10 -2
  505. package/vendors/opencode/actions/export-latex.json +15 -2
  506. package/vendors/opencode/actions/plan-revision.json +22 -4
  507. package/vendors/opencode/actions/polish-prose.json +13 -3
  508. package/vendors/opencode/actions/research-gap.json +16 -3
  509. package/vendors/opencode/actions/verify-work.json +13 -4
  510. package/vendors/opencode/agents/wtfp/research-synthesizer.md +1 -1
  511. package/vendors/opencode/aliases.lock.json +1 -0
  512. package/vendors/opencode/catalog.json +4 -2
  513. package/vendors/opencode/commands/wtfp/add-todo.md +54 -144
  514. package/vendors/opencode/commands/wtfp/advance.md +16 -0
  515. package/vendors/opencode/commands/wtfp/check-todos.md +54 -2
  516. package/vendors/opencode/commands/wtfp/checkpoint.md +66 -738
  517. package/vendors/opencode/commands/wtfp/create-outline.md +39 -431
  518. package/vendors/opencode/commands/wtfp/create-poster.md +43 -299
  519. package/vendors/opencode/commands/wtfp/create-slides.md +43 -299
  520. package/vendors/opencode/commands/wtfp/discuss-section.md +45 -262
  521. package/vendors/opencode/commands/wtfp/execute-outline.md +53 -486
  522. package/vendors/opencode/commands/wtfp/help.md +44 -3
  523. package/vendors/opencode/commands/wtfp/insert-section.md +44 -4
  524. package/vendors/opencode/commands/wtfp/list-assumptions.md +45 -513
  525. package/vendors/opencode/commands/wtfp/map-project.md +39 -0
  526. package/vendors/opencode/commands/wtfp/new-paper.md +39 -0
  527. package/vendors/opencode/commands/wtfp/pause-writing.md +54 -309
  528. package/vendors/opencode/commands/wtfp/plan-milestone-gaps.md +42 -370
  529. package/vendors/opencode/commands/wtfp/plan-revision.md +229 -277
  530. package/vendors/opencode/commands/wtfp/plan-section.md +47 -629
  531. package/vendors/opencode/commands/wtfp/polish-prose.md +217 -268
  532. package/vendors/opencode/commands/wtfp/progress.md +55 -1143
  533. package/vendors/opencode/commands/wtfp/quick.md +41 -220
  534. package/vendors/opencode/commands/wtfp/resume-writing.md +54 -698
  535. package/vendors/opencode/commands/wtfp/review-section.md +42 -411
  536. package/vendors/opencode/commands/wtfp/settings.md +54 -2
  537. package/vendors/opencode/commands/wtfp/submit-milestone.md +42 -620
  538. package/vendors/opencode/commands/wtfp/verify-work.md +169 -57
  539. package/vendors/opencode/commands/wtfp/write-section.md +45 -486
  540. package/vendors/opencode/compatibility/action-availability.json +13 -1
  541. package/vendors/opencode/project/README.md +39 -0
  542. package/vendors/opencode/project/schemas/interaction.schema.json +100 -0
  543. package/vendors/opencode/project/templates/interaction.json +16 -0
  544. package/vendors/opencode/roles/research-synthesizer.md +1 -1
  545. package/vendors/opencode/skills/wtfp-deliver-research/SKILL.md +1 -1
  546. package/vendors/opencode/skills/wtfp-deliver-research/references/actions.md +2 -2
  547. package/vendors/opencode/skills/wtfp-manage-project/SKILL.md +2 -1
  548. package/vendors/opencode/skills/wtfp-manage-project/references/actions.md +29 -1
  549. package/vendors/opencode/skills/wtfp-plan-section/SKILL.md +1 -1
  550. package/vendors/opencode/skills/wtfp-plan-section/references/actions.md +4 -3
  551. package/vendors/opencode/skills/wtfp-research-literature/SKILL.md +1 -1
  552. package/vendors/opencode/skills/wtfp-research-literature/references/actions.md +1 -1
  553. package/vendors/opencode/skills/wtfp-review-manuscript/SKILL.md +1 -1
  554. package/vendors/opencode/skills/wtfp-review-manuscript/references/actions.md +2 -1
  555. package/vendors/opencode/skills/wtfp-write-section/SKILL.md +1 -1
  556. package/vendors/opencode/skills/wtfp-write-section/references/actions.md +1 -1
  557. package/vendors/opencode/tools/README.md +1 -1
  558. package/vendors/opencode/workflows/advance.md +38 -0
  559. package/vendors/opencode/workflows/checkpoint.md +2 -2
  560. package/vendors/opencode/workflows/discuss-section.md +1 -1
  561. package/vendors/opencode/workflows/execute-outline.md +2 -2
  562. package/vendors/opencode/workflows/export-latex.md +4 -4
  563. package/vendors/opencode/workflows/plan-revision.md +4 -3
  564. package/vendors/opencode/workflows/plan-section.md +3 -3
  565. package/vendors/opencode/workflows/polish-prose.md +3 -3
  566. package/vendors/opencode/workflows/research-gap.md +5 -5
  567. package/vendors/opencode/workflows/verify-work.md +5 -3
  568. package/vendors/opencode/workflows/write-section.md +4 -4
  569. package/vendors/plugin/.wtfp-generated.json +101 -81
  570. package/vendors/plugin/actions/advance.json +232 -0
  571. package/vendors/plugin/actions/checkpoint.json +10 -1
  572. package/vendors/plugin/actions/execute-outline.json +10 -2
  573. package/vendors/plugin/actions/export-latex.json +15 -2
  574. package/vendors/plugin/actions/plan-revision.json +22 -4
  575. package/vendors/plugin/actions/polish-prose.json +13 -3
  576. package/vendors/plugin/actions/research-gap.json +16 -3
  577. package/vendors/plugin/actions/verify-work.json +13 -4
  578. package/vendors/plugin/ai.iowarp.clio/agents/wtfp-argument-verifier.md +7 -8
  579. package/vendors/plugin/ai.iowarp.clio/agents/wtfp-citation-expert.md +5 -5
  580. package/vendors/plugin/ai.iowarp.clio/agents/wtfp-citation-formatter.md +3 -3
  581. package/vendors/plugin/ai.iowarp.clio/agents/wtfp-coherence-checker.md +9 -10
  582. package/vendors/plugin/ai.iowarp.clio/agents/wtfp-outliner.md +3 -3
  583. package/vendors/plugin/ai.iowarp.clio/agents/wtfp-plan-checker.md +7 -8
  584. package/vendors/plugin/ai.iowarp.clio/agents/wtfp-prose-polisher.md +4 -4
  585. package/vendors/plugin/ai.iowarp.clio/agents/wtfp-research-synthesizer.md +6 -6
  586. package/vendors/plugin/ai.iowarp.clio/agents/wtfp-section-planner.md +3 -3
  587. package/vendors/plugin/ai.iowarp.clio/agents/wtfp-section-reviewer.md +9 -10
  588. package/vendors/plugin/ai.iowarp.clio/agents/wtfp-section-writer.md +3 -3
  589. package/vendors/plugin/ai.iowarp.clio/playbooks/wtfp-draft-review.md +1 -1
  590. package/vendors/plugin/ai.iowarp.clio/playbooks/wtfp-plan-section.md +1 -1
  591. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/add-todo.md +21 -4
  592. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/advance.md +101 -0
  593. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/analyze-bib.md +27 -8
  594. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/audit-milestone.md +26 -5
  595. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/check-refs.md +40 -7
  596. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/check-todos.md +25 -5
  597. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/checkpoint.md +27 -7
  598. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/create-outline.md +26 -8
  599. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/create-poster.md +27 -13
  600. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/create-slides.md +27 -13
  601. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/discuss-section.md +26 -6
  602. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/execute-outline.md +42 -9
  603. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/export-latex.md +35 -24
  604. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/help.md +4 -1
  605. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/insert-section.md +25 -5
  606. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/list-assumptions.md +21 -17
  607. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/map-project.md +21 -4
  608. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/new-paper.md +25 -5
  609. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/pause-writing.md +21 -4
  610. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/plan-milestone-gaps.md +25 -5
  611. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/plan-revision.md +33 -20
  612. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/plan-section.md +42 -10
  613. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/polish-prose.md +43 -10
  614. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/progress.md +26 -30
  615. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/quick.md +40 -7
  616. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/research-gap.md +51 -13
  617. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/resume-writing.md +25 -5
  618. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/review-section.md +36 -7
  619. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/settings.md +25 -5
  620. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/submit-milestone.md +27 -5
  621. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/verify-work.md +30 -8
  622. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/write-section.md +44 -11
  623. package/vendors/plugin/aliases.lock.json +1 -0
  624. package/vendors/plugin/catalog.json +4 -2
  625. package/vendors/plugin/compatibility/action-availability.json +11 -5
  626. package/vendors/plugin/plugin.json +16 -2
  627. package/vendors/plugin/project/README.md +39 -0
  628. package/vendors/plugin/project/schemas/interaction.schema.json +100 -0
  629. package/vendors/plugin/project/templates/interaction.json +16 -0
  630. package/vendors/plugin/roles/research-synthesizer.md +1 -1
  631. package/vendors/plugin/skills/wtfp-deliver-research/SKILL.md +1 -1
  632. package/vendors/plugin/skills/wtfp-deliver-research/references/actions.md +2 -2
  633. package/vendors/plugin/skills/wtfp-manage-project/SKILL.md +2 -1
  634. package/vendors/plugin/skills/wtfp-manage-project/references/actions.md +13 -1
  635. package/vendors/plugin/skills/wtfp-plan-section/SKILL.md +1 -1
  636. package/vendors/plugin/skills/wtfp-plan-section/references/actions.md +4 -3
  637. package/vendors/plugin/skills/wtfp-research-literature/SKILL.md +1 -1
  638. package/vendors/plugin/skills/wtfp-research-literature/references/actions.md +1 -1
  639. package/vendors/plugin/skills/wtfp-review-manuscript/SKILL.md +1 -1
  640. package/vendors/plugin/skills/wtfp-review-manuscript/references/actions.md +2 -1
  641. package/vendors/plugin/skills/wtfp-write-section/SKILL.md +1 -1
  642. package/vendors/plugin/skills/wtfp-write-section/references/actions.md +1 -1
  643. package/vendors/plugin/tools/README.md +1 -1
  644. package/vendors/plugin/workflows/advance.md +38 -0
  645. package/vendors/plugin/workflows/checkpoint.md +2 -2
  646. package/vendors/plugin/workflows/discuss-section.md +1 -1
  647. package/vendors/plugin/workflows/execute-outline.md +2 -2
  648. package/vendors/plugin/workflows/export-latex.md +4 -4
  649. package/vendors/plugin/workflows/plan-revision.md +4 -3
  650. package/vendors/plugin/workflows/plan-section.md +3 -3
  651. package/vendors/plugin/workflows/polish-prose.md +3 -3
  652. package/vendors/plugin/workflows/research-gap.md +5 -5
  653. package/vendors/plugin/workflows/verify-work.md +5 -3
  654. package/vendors/plugin/workflows/write-section.md +4 -4
  655. package/vendors/antigravity/commands/wtfp-plan-section.md +0 -78
  656. package/vendors/antigravity/commands/wtfp-write-section.md +0 -77
@@ -2,26 +2,47 @@
2
2
  /**
3
3
  * WTF-P writing desk for Clio Coder. Human-edited source; the adapter
4
4
  * compiler copies it to vendors/clio-extension/runtime/ beside the
5
- * generated write-guard.json and json-schema.cjs.
5
+ * generated write-guard.json, json-schema.cjs and claim-coverage.cjs.
6
6
  *
7
- * The desk reads the portable `.planning` records and the manuscript, and
8
- * draws them. It writes only two things, both under `.planning`: an author's
9
- * answer to a gate (the checkpoint record and `state.active_checkpoint_uris`),
10
- * each schema-validated before an atomic replace. Everything else stays with
11
- * the actions' own workflows.
7
+ * The desk reads the portable `.planning` records and the manuscript and
8
+ * draws them. It is also the project's one JSON record writer on Clio: each
9
+ * write is validated, compared with the version its writer read, and
10
+ * committed under a project lock, with paired records journaled so a failed
11
+ * process leaves a state the next write completes. It alone records an
12
+ * author's answer, as a sealed interaction record; a resolution counts as the
13
+ * author's only while such a record still matches the checkpoint it answered.
12
14
  */
13
- import { randomUUID } from "node:crypto";
14
- import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
15
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
16
+ import {
17
+ appendFileSync,
18
+ closeSync,
19
+ existsSync,
20
+ fsyncSync,
21
+ lstatSync,
22
+ mkdirSync,
23
+ openSync,
24
+ readdirSync,
25
+ readFileSync,
26
+ realpathSync,
27
+ renameSync,
28
+ statSync,
29
+ unlinkSync,
30
+ writeFileSync,
31
+ writeSync,
32
+ } from "node:fs";
15
33
  import { createRequire } from "node:module";
16
34
  import path from "node:path";
35
+ import { performance } from "node:perf_hooks";
17
36
  import { fileURLToPath } from "node:url";
18
37
  import type {
19
38
  ExtensionApiV2,
20
39
  ExtensionContextV2,
40
+ ExtensionEffect,
21
41
  ExtensionHookResult,
22
42
  ExtensionIsland,
23
43
  ExtensionOutputV2,
24
44
  ExtensionSkin,
45
+ InterviewNext,
25
46
  InterviewStep,
26
47
  View,
27
48
  ViewTone,
@@ -32,11 +53,65 @@ const { SchemaRegistry, validateInstance } = require("./json-schema.cjs") as {
32
53
  SchemaRegistry: new (files: string[]) => { get(file: string): unknown };
33
54
  validateInstance: (value: unknown, schema: unknown, file: string, registry: unknown) => string[];
34
55
  };
56
+ const deskTrust = require("./desk-trust.cjs") as {
57
+ canonical(value: unknown): string;
58
+ checkpointDigest(record: Json): string;
59
+ seal(record: Json, key: Buffer): Json;
60
+ trustOf(checkpoint: Json, interactions: Json[], key: Buffer | null, projectId: string | null): { trust: Trust; answer?: Json };
61
+ };
62
+ const coverage = require("./claim-coverage.cjs") as {
63
+ STRUCTURAL_SCOPE: string;
64
+ analyzeCoverage(input: unknown): CoverageReport;
65
+ indexRecords(
66
+ entries: Array<{ file: string; record: Json }>,
67
+ collection: string,
68
+ location?: (id: string) => string,
69
+ ): { byUri: Record<string, Json>; ignored: Array<{ file: string; reason: string }> };
70
+ unsupportedRequired(report: CoverageReport, section: string): string[];
71
+ };
72
+
73
+ interface CoverageFinding {
74
+ severity: "blocker" | "error" | "warning" | "info";
75
+ code: string;
76
+ subject: string;
77
+ message: string;
78
+ }
79
+
80
+ interface CoverageReport {
81
+ scope: string;
82
+ findings: CoverageFinding[];
83
+ claims: Array<{ section: string; claim: string; status: string; evidence_required: boolean; support: "full" | "partial" | "none"; contested: boolean }>;
84
+ }
35
85
 
36
86
  const PACKAGE_ROOT = fileURLToPath(new URL("../", import.meta.url));
37
87
  const SCHEMAS = path.join(PACKAGE_ROOT, "project", "schemas");
88
+ const TEMPLATES = path.join(PACKAGE_ROOT, "project", "templates");
89
+
90
+ /**
91
+ * The example record of a type, so a model creating one sees every field it
92
+ * needs at once instead of learning them from one refusal per call.
93
+ */
94
+ function templateFor(type: string): string {
95
+ try {
96
+ return JSON.stringify(JSON.parse(readFileSync(path.join(TEMPLATES, `${type}.json`), "utf8")));
97
+ } catch {
98
+ return "";
99
+ }
100
+ }
101
+
102
+ function withTemplate(message: string, type: string): string {
103
+ const template = templateFor(type);
104
+ return template ? `${message}\nA ${type} record looks like this example; replace its ids, project_id and content, and omit ${CREATED_AT[type] ? `updated_at and ${CREATED_AT[type]}, which the desk sets` : "updated_at, which the desk sets"}: ${template}` : message;
105
+ }
106
+ interface GuardAction {
107
+ /** The Clio agent IDs of the roles the action's contract delegates to. */
108
+ agents: string[];
109
+ produces: Array<{ uri: string; mode: string }>;
110
+ }
38
111
  const GUARD = JSON.parse(readFileSync(new URL("./write-guard.json", import.meta.url), "utf8")) as {
39
- actions: Record<string, string[]>;
112
+ schema: string;
113
+ actions: Record<string, GuardAction>;
114
+ paperWriters: string[];
40
115
  };
41
116
  const SKIN = JSON.parse(readFileSync(new URL("../skins/wtfp.json", import.meta.url), "utf8")) as ExtensionSkin;
42
117
  const RECORD_LIMIT = 1024 * 1024;
@@ -51,9 +126,29 @@ const WORDMARK = [
51
126
  ];
52
127
  const WORD_METHOD =
53
128
  "Body words: front matter, headings, code, math, comments, citation keys and markup are left out; a word is a run of letters or digits, joined across an apostrophe or hyphen.";
129
+ /** Files only the desk writes. A model tool call that would change one is refused. */
130
+ const DESK_OWNED = [".planning/interactions", ".planning/.wtfp-lock", ".planning/.wtfp-journal.json"];
131
+ const LOCK = ".planning/.wtfp-lock";
132
+ const JOURNAL = ".planning/.wtfp-journal.json";
133
+ const LOCK_WAIT_MS = 2000;
134
+ const LOCK_STALE_MS = 30_000;
135
+ const SEAL_KEY = "seal-key";
136
+ /** The option id a plan-approval checkpoint uses for approval; any other answer leaves the plan unapproved. */
137
+ const APPROVE = "approve";
54
138
 
55
139
  // --- records -----------------------------------------------------------------
56
140
 
141
+ type Json = Record<string, unknown>;
142
+ type ServedPlugin = ExtensionContextV2["snapshot"]["plugin"];
143
+
144
+ /**
145
+ * How far an author answer can be trusted. `attested` means a sealed desk
146
+ * interaction still matches the checkpoint; `unattested` is a resolution the
147
+ * desk never observed (a hand edit, another host or an older desk); `foreign`
148
+ * was sealed with another machine's key and cannot be checked here.
149
+ */
150
+ type Trust = "pending" | "attested" | "unattested" | "foreign" | "policy" | "expired" | "snapshot";
151
+
57
152
  interface Checkpoint {
58
153
  file: string;
59
154
  id: string;
@@ -65,9 +160,23 @@ interface Checkpoint {
65
160
  context?: string;
66
161
  options?: Array<{ id: string; label: string; implication?: string }>;
67
162
  created_at?: string;
163
+ resolution?: { resolved_by?: string; selected_option?: string; summary?: string; resolved_at?: string };
164
+ trust: Trust;
165
+ /** The sealed interaction behind an attested resolution. */
166
+ answer?: Json;
68
167
  [key: string]: unknown;
69
168
  }
70
169
 
170
+ interface PlanState {
171
+ state: "none" | "missing" | "awaiting" | "approved" | "policy" | "changed" | "declined" | "unconfirmed";
172
+ uri: string | null;
173
+ file: string | null;
174
+ sha256: string | null;
175
+ reason: string;
176
+ /** When the author's sealed approval of these bytes was given. */
177
+ approvedAt?: string;
178
+ }
179
+
71
180
  interface SectionRow {
72
181
  id: string;
73
182
  title: string;
@@ -75,17 +184,45 @@ interface SectionRow {
75
184
  status: string;
76
185
  target: number;
77
186
  words: number;
187
+ recorded: number | null;
78
188
  manuscript: string | null;
79
189
  claims: { total: number; verified: number; unsupported: number };
80
190
  stages: { discuss: boolean; plan: boolean; write: boolean; review: boolean };
81
191
  gates: Checkpoint[];
82
- research: { required: boolean; present: boolean };
192
+ /** `claimless`: the record names no live claim that requires evidence, so coverage is vacuous. */
193
+ research: { required: boolean; present: boolean; claimless: boolean };
83
194
  dependsOn: string[];
195
+ plan: PlanState;
196
+ unsupported: string[];
197
+ record: Json | null;
198
+ /** The author's acceptance after review, from verify-work and its sealed checkpoint. */
199
+ acceptance: Acceptance;
200
+ /** When the manuscript file was last written, in epoch milliseconds, or null when it does not exist. */
201
+ writtenAt: number | null;
202
+ }
203
+
204
+ interface Acceptance {
205
+ /** A review validation or linked review exists for the section. */
206
+ reviewed: boolean;
207
+ /** A verify-work validation is at least as new as the latest review. */
208
+ verified: boolean;
209
+ /** The attested author answer on that validation's acceptance checkpoint, if any. */
210
+ decision: "accept" | "revise" | null;
211
+ /** The note the author attached to that answer, if any. */
212
+ note?: string;
213
+ }
214
+
215
+ interface Finding {
216
+ severity: "blocker" | "error" | "warning" | "info";
217
+ code: string;
218
+ subject: string;
219
+ message: string;
84
220
  }
85
221
 
86
222
  interface Desk {
87
223
  workspace: string;
88
224
  present: boolean;
225
+ projectId: string | null;
89
226
  title: string;
90
227
  documentType: string;
91
228
  venue: string | null;
@@ -94,21 +231,26 @@ interface Desk {
94
231
  phase: string;
95
232
  status: string;
96
233
  confirmPlan: boolean;
234
+ outputFormat: string;
97
235
  sections: SectionRow[];
98
236
  checkpoints: Checkpoint[];
237
+ interactions: Json[];
99
238
  sources: Record<string, number>;
100
239
  evidence: number;
101
240
  issues: Record<"blocker" | "error" | "warning" | "info", number>;
102
241
  invalid: Array<{ file: string; errors: string[] }>;
103
242
  targetWords: number;
104
243
  paperExists: boolean;
244
+ journal: boolean;
245
+ coverage: CoverageReport;
246
+ /** The latest milestone audit: fresh when nothing the desk tracks was recorded after it; errors counts its error and blocker issues. */
247
+ audit: { fresh: boolean; errors: number } | null;
248
+ /** A passed submit-milestone validation that no later draft or record outdates. */
249
+ delivered: boolean;
105
250
  /** The WTF-P plugin while Clio serves it; null when it is not installed and enabled. */
106
251
  served: ServedPlugin;
107
252
  }
108
253
 
109
- type Json = Record<string, unknown>;
110
- type ServedPlugin = ExtensionContextV2["snapshot"]["plugin"];
111
-
112
254
  /** Actions the desk answers itself; they stay reachable as `/ext:wtfp:<name>` without the plugin. */
113
255
  const DESK_COMMANDS = new Set(["progress", "help", "check-todos"]);
114
256
 
@@ -131,22 +273,61 @@ function actionName(served: ServedPlugin, action: string): string {
131
273
 
132
274
  function inside(root: string, candidate: string): boolean {
133
275
  const relative = path.relative(root, candidate);
134
- return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
276
+ return relative === "" || (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
135
277
  }
136
278
 
137
- function readText(workspace: string, relative: string): string | null {
279
+ function posix(relative: string): string {
280
+ return relative.split(path.sep).join("/");
281
+ }
282
+
283
+ /**
284
+ * A project-relative path inside the workspace whose existing components are
285
+ * all real files or directories. A symbolic link anywhere on the way could
286
+ * carry a read or write outside the project, so it yields null.
287
+ */
288
+ function contained(workspace: string, relative: string): string | null {
138
289
  const file = path.resolve(workspace, relative);
139
- if (!inside(workspace, file) || !existsSync(file)) return null;
290
+ if (!inside(workspace, file)) return null;
291
+ let current = workspace;
292
+ for (const part of path.relative(workspace, file).split(path.sep).filter(Boolean)) {
293
+ current = path.join(current, part);
294
+ let stat;
295
+ try {
296
+ stat = lstatSync(current);
297
+ } catch {
298
+ return file;
299
+ }
300
+ if (stat.isSymbolicLink()) return null;
301
+ }
302
+ return file;
303
+ }
304
+
305
+ /** The workspace's real path, against which Clio reports every landing. */
306
+ function realWorkspace(workspace: string): string {
307
+ try {
308
+ return realpathSync(workspace);
309
+ } catch {
310
+ return workspace;
311
+ }
312
+ }
313
+
314
+ function readBytes(workspace: string, relative: string): Buffer | null {
315
+ const file = contained(workspace, relative);
316
+ if (file === null || !existsSync(file)) return null;
140
317
  const stat = lstatSync(file);
141
318
  if (!stat.isFile() || stat.size > RECORD_LIMIT) return null;
142
- return readFileSync(file, "utf8");
319
+ return readFileSync(file);
320
+ }
321
+
322
+ function readText(workspace: string, relative: string): string | null {
323
+ return readBytes(workspace, relative)?.toString("utf8") ?? null;
143
324
  }
144
325
 
145
326
  function readRecord(workspace: string, relative: string): Json | null {
146
- const text = readText(workspace, relative);
147
- if (text === null) return null;
327
+ const source = readText(workspace, relative);
328
+ if (source === null) return null;
148
329
  try {
149
- const value = JSON.parse(text) as unknown;
330
+ const value = JSON.parse(source) as unknown;
150
331
  return value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Json) : null;
151
332
  } catch {
152
333
  // An unreadable record shows up as a schema problem from validation, not here.
@@ -155,10 +336,10 @@ function readRecord(workspace: string, relative: string): Json | null {
155
336
  }
156
337
 
157
338
  function listJson(workspace: string, relative: string): string[] {
158
- const directory = path.resolve(workspace, relative);
159
- if (!inside(workspace, directory) || !existsSync(directory)) return [];
339
+ const directory = contained(workspace, relative);
340
+ if (directory === null || !existsSync(directory) || !lstatSync(directory).isDirectory()) return [];
160
341
  return readdirSync(directory, { withFileTypes: true })
161
- .filter((entry) => entry.isFile() && entry.name.endsWith(".json"))
342
+ .filter((entry) => entry.isFile() && entry.name.endsWith(".json") && !entry.name.startsWith("."))
162
343
  .map((entry) => path.posix.join(relative, entry.name))
163
344
  .sort();
164
345
  }
@@ -167,17 +348,48 @@ function text(value: unknown, fallback = ""): string {
167
348
  return typeof value === "string" && value.length > 0 ? value : fallback;
168
349
  }
169
350
 
351
+ function sha256(data: string | Buffer): string {
352
+ return createHash("sha256").update(data).digest("hex");
353
+ }
354
+
355
+ /** JSON with object keys in code-unit order and no insignificant whitespace; the input to every digest and seal. */
356
+ function canonical(value: unknown): string {
357
+ return deskTrust.canonical(value);
358
+ }
359
+
360
+ /** What a checkpoint asks, independent of whether and how it was answered. */
361
+ export function checkpointDigest(record: Json): string {
362
+ return deskTrust.checkpointDigest(record);
363
+ }
364
+
365
+ function timestamp(): string {
366
+ return new Date().toISOString().replace(/\.\d{3}Z$/u, "Z");
367
+ }
368
+
369
+ const EXTENSIONS: Record<string, string> = { markdown: ".md", latex: ".tex", typst: ".typ" };
370
+
170
371
  /** `project://paper/{artifact}` to a manuscript file, trying the authored formats in order. */
171
- function manuscriptFile(workspace: string, uri: unknown): string | null {
372
+ function manuscriptFile(workspace: string, uri: unknown, format = "markdown"): string | null {
172
373
  if (typeof uri !== "string" || !uri.startsWith("project://paper/")) return null;
173
374
  const artifact = uri.slice("project://paper/".length);
174
- if (artifact.length === 0 || artifact.split("/").some((part) => part === ".." || part === "")) return null;
375
+ if (artifact.length === 0 || artifact.split("/").some((part) => part === ".." || part === "." || part === "")) return null;
175
376
  for (const candidate of [artifact, `${artifact}.md`, `${artifact}.tex`, `${artifact}.typ`]) {
176
377
  const relative = path.posix.join("paper", candidate);
177
- const file = path.resolve(workspace, relative);
178
- if (inside(workspace, file) && existsSync(file) && lstatSync(file).isFile()) return relative;
378
+ const file = contained(workspace, relative);
379
+ if (file !== null && existsSync(file) && lstatSync(file).isFile()) return relative;
179
380
  }
180
- return path.posix.join("paper", artifact);
381
+ return path.posix.join("paper", /\.(md|tex|typ)$/u.test(artifact) ? artifact : `${artifact}${EXTENSIONS[format] ?? ".md"}`);
382
+ }
383
+
384
+ /** A section-scoped artifact URI to its conventional file, or null when it names no file. */
385
+ function artifactFile(workspace: string, uri: string, format = "markdown"): string | null {
386
+ if (uri.startsWith("project://paper/")) return manuscriptFile(workspace, uri, format);
387
+ const named = new RegExp(`^project://sections/(${IDENTIFIER})/(context|research|summary|handoff)$`, "u").exec(uri);
388
+ if (named) return `.planning/sections/${named[1]}/${named[2]}.md`;
389
+ const listed = new RegExp(`^project://sections/(${IDENTIFIER})/(plans|reviews)/(${IDENTIFIER})$`, "u").exec(uri);
390
+ if (listed) return `.planning/sections/${listed[1]}/${listed[2]}/${listed[3]}.md`;
391
+ const route = RECORD_URIS.find((entry) => entry.pattern.test(uri));
392
+ return route ? route.file(route.pattern.exec(uri)?.[1] ?? "") : null;
181
393
  }
182
394
 
183
395
  /** The one counting method every meter and tolerance uses (see WORD_METHOD). */
@@ -200,16 +412,6 @@ export function bodyWords(source: string, file: string): number {
200
412
  return (body.match(/[\p{L}\p{N}]+(?:['’-][\p{L}\p{N}]+)*/gu) ?? []).length;
201
413
  }
202
414
 
203
- function sectionGates(checkpoints: Checkpoint[], id: string, manuscript: string | null): Checkpoint[] {
204
- const scopes = [`project://sections/${id}`, ...(manuscript ? [`project://${manuscript}`] : [])];
205
- return checkpoints.filter(
206
- (checkpoint) =>
207
- checkpoint.status === "pending" &&
208
- checkpoint.blocking &&
209
- scopes.some((scope) => checkpoint.scope_uri === scope || checkpoint.scope_uri.startsWith(`${scope}/`)),
210
- );
211
- }
212
-
213
415
  let registry: InstanceType<typeof SchemaRegistry> | undefined;
214
416
  function schemaRegistry(): InstanceType<typeof SchemaRegistry> {
215
417
  registry ??= new SchemaRegistry(
@@ -220,6 +422,18 @@ function schemaRegistry(): InstanceType<typeof SchemaRegistry> {
220
422
  return registry;
221
423
  }
222
424
 
425
+ /** The top-level fields a record type's schema defines. */
426
+ function recordFields(schema: string): Set<string> {
427
+ const match = /^wtfp\.project\.([a-z][a-z0-9-]*)\/v1$/u.exec(schema);
428
+ if (!match) return new Set();
429
+ try {
430
+ const parsed = JSON.parse(readFileSync(path.join(SCHEMAS, `${match[1]}.schema.json`), "utf8")) as Json;
431
+ return new Set(Object.keys((parsed.properties as Json | undefined) ?? {}));
432
+ } catch {
433
+ return new Set();
434
+ }
435
+ }
436
+
223
437
  /** Schema errors for one record, as the canonical validator reports them. */
224
438
  function validateRecord(value: unknown): string[] {
225
439
  if (value === null || typeof value !== "object" || Array.isArray(value)) return ["$: planning record must be a JSON object"];
@@ -233,7 +447,7 @@ function validateRecord(value: unknown): string[] {
233
447
 
234
448
  function validateFile(workspace: string, relative: string): string[] {
235
449
  const source = readText(workspace, relative);
236
- if (source === null) return [];
450
+ if (source === null) return contained(workspace, relative) === null ? ["$: reached through a symbolic link; the desk does not follow links"] : [];
237
451
  try {
238
452
  return validateRecord(JSON.parse(source));
239
453
  } catch (error) {
@@ -242,10 +456,11 @@ function validateFile(workspace: string, relative: string): string[] {
242
456
  }
243
457
 
244
458
  function planningRecords(workspace: string, relative = ".planning"): string[] {
245
- const directory = path.resolve(workspace, relative);
246
- if (!existsSync(directory)) return [];
459
+ const directory = contained(workspace, relative);
460
+ if (directory === null || !existsSync(directory) || !lstatSync(directory).isDirectory()) return [];
247
461
  const out: string[] = [];
248
462
  for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
463
+ if (entry.name.startsWith(".")) continue;
249
464
  const child = path.posix.join(relative, entry.name);
250
465
  if (entry.isDirectory() && entry.name !== "archives") out.push(...planningRecords(workspace, child));
251
466
  else if (entry.isFile() && entry.name.endsWith(".json")) out.push(child);
@@ -253,44 +468,313 @@ function planningRecords(workspace: string, relative = ".planning"): string[] {
253
468
  return out;
254
469
  }
255
470
 
256
- function loadDesk(workspace: string): Desk {
471
+ // --- seals -------------------------------------------------------------------
472
+
473
+ /** The desk's seal over an interaction record (evaluation/lib/desk-trust.js, shared with the campaign collector). */
474
+ function sealed(record: Json, key: Buffer): Json {
475
+ return deskTrust.seal(record, key);
476
+ }
477
+
478
+ async function storedKey(ctx: ExtensionContextV2, create: boolean): Promise<Buffer | null> {
479
+ const current = await ctx.store.get<string>(SEAL_KEY);
480
+ if (typeof current.value === "string" && /^[a-f0-9]{64}$/u.test(current.value)) return Buffer.from(current.value, "hex");
481
+ if (!create) return null;
482
+ // ifVersion keeps two sessions from each minting a key; the loser reads the winner's.
483
+ await ctx.store.set(SEAL_KEY, randomBytes(32).toString("hex"), { ifVersion: current.version });
484
+ const settled = await ctx.store.get<string>(SEAL_KEY);
485
+ return typeof settled.value === "string" ? Buffer.from(settled.value, "hex") : null;
486
+ }
487
+
488
+ function trustOf(checkpoint: Checkpoint, interactions: Json[], key: Buffer | null, projectId: string | null): { trust: Trust; answer?: Json } {
489
+ return deskTrust.trustOf(checkpoint, interactions, key, projectId);
490
+ }
491
+
492
+ /** Recorded as answered, but with no author answer sealed by this desk behind it. */
493
+ function unconfirmed(checkpoint: Checkpoint): boolean {
494
+ return checkpoint.trust === "unattested" || checkpoint.trust === "foreign" || checkpoint.trust === "policy";
495
+ }
496
+
497
+ /** A blocking checkpoint holds its scope until the author's answer is attested here. */
498
+ function holds(checkpoint: Checkpoint): boolean {
499
+ return checkpoint.blocking && (checkpoint.trust === "pending" || unconfirmed(checkpoint));
500
+ }
501
+
502
+ function scopes(id: string, manuscript: string | null): string[] {
503
+ return [`project://sections/${id}`, ...(manuscript ? [`project://${manuscript.replace(/\.(md|tex|typ)$/u, "")}`] : [])];
504
+ }
505
+
506
+ function sectionGates(checkpoints: Checkpoint[], id: string, manuscript: string | null): Checkpoint[] {
507
+ const owned = scopes(id, manuscript);
508
+ return checkpoints.filter(
509
+ (checkpoint) =>
510
+ holds(checkpoint) && owned.some((scope) => checkpoint.scope_uri === scope || checkpoint.scope_uri.startsWith(`${scope}/`) || checkpoint.scope_uri.startsWith(`${scope}.`)),
511
+ );
512
+ }
513
+
514
+ // --- the author's acceptance after review -------------------------------------
515
+
516
+ function writtenAt(workspace: string, manuscript: string | null): number | null {
517
+ if (manuscript === null || contained(workspace, manuscript) === null) return null;
518
+ try {
519
+ return statSync(path.join(workspace, manuscript)).mtimeMs;
520
+ } catch {
521
+ return null;
522
+ }
523
+ }
524
+
525
+ /**
526
+ * A plan the author approved after the manuscript was last written has not
527
+ * been applied yet: a revision plan approved for a reviewed section is drafted
528
+ * before anything reviews or accepts the section again. Answers are stamped to
529
+ * the second, so a write later in the same second counts as applying it.
530
+ */
531
+ function unappliedPlan(section: SectionRow): boolean {
532
+ if (section.plan.state !== "approved" || !section.plan.approvedAt) return false;
533
+ const approved = Date.parse(section.plan.approvedAt);
534
+ return Number.isFinite(approved) && (section.writtenAt === null || section.writtenAt < approved);
535
+ }
536
+
537
+ const ACCEPT = "accept";
538
+ const REVISE = "revise";
539
+
540
+ /** Whether a validation's subject is this section, one of its artifacts, or its manuscript. */
541
+ function validates(record: Json, id: string, manuscriptUri: string): boolean {
542
+ const subject = text(record.subject_uri);
543
+ const section = `project://sections/${id}`;
544
+ return subject === section || subject.startsWith(`${section}/`) || subject === manuscriptUri || subject.startsWith(`${manuscriptUri}/`);
545
+ }
546
+
547
+ /**
548
+ * Where a reviewed section stands with its author. Review is critique only;
549
+ * verify-work records the acceptance checks and closes with a checkpoint scoped
550
+ * to its validation, and only an attested answer on that checkpoint counts.
551
+ */
552
+ /** When the desk wrote each validation record, by file time. */
553
+ const recordedAt = new WeakMap<Json, number>();
554
+
555
+ function acceptanceOf(validations: Json[], checkpoints: Checkpoint[], id: string, manuscriptUri: string, reviewsLinked: boolean, drafted: number | null): Acceptance {
556
+ const mine = validations.filter((record) => validates(record, id, manuscriptUri));
557
+ const latest = (action: string): Json | undefined =>
558
+ mine.filter((record) => record.action_id === action).sort((a, b) => text(b.executed_at).localeCompare(text(a.executed_at)))[0];
559
+ const review = latest("review-section");
560
+ const verify = latest("verify-work");
561
+ // A review counts only for the draft it read: a revision written after it waits for a new review.
562
+ const reviewed = review !== undefined ? drafted === null || (recordedAt.get(review) ?? 0) >= drafted : reviewsLinked && drafted === null;
563
+ const verified = verify !== undefined && (review === undefined || text(verify.executed_at) >= text(review.executed_at));
564
+ if (!verified || verify === undefined) return { reviewed, verified: false, decision: null };
565
+ const answered = checkpoints
566
+ .filter((checkpoint) => checkpoint.scope_uri === `project://validations/${text(verify.id)}` && checkpoint.trust === "attested" && checkpoint.status === "resolved")
567
+ .sort((a, b) => text(b.answer?.answered_at).localeCompare(text(a.answer?.answered_at)))[0];
568
+ const picked = answered?.resolution?.selected_option;
569
+ const note = authorNote(answered);
570
+ return { reviewed, verified: true, decision: picked === ACCEPT || picked === REVISE ? picked : null, ...(note ? { note } : {}) };
571
+ }
572
+
573
+ /** How the desk records the text an author attaches to a gate answer, inside the checkpoint's resolution summary. */
574
+ const NOTE_LEAD = " The author's note: ";
575
+ const NOTE_LIMIT = 4000;
576
+
577
+ /** The note an author attached to an answer this desk attested; null when there is none or the answer is not the author's. */
578
+ function authorNote(checkpoint: Checkpoint | undefined): string | null {
579
+ if (!checkpoint || checkpoint.trust !== "attested") return null;
580
+ const summary = checkpoint.resolution?.summary ?? "";
581
+ const at = summary.indexOf(NOTE_LEAD);
582
+ return at < 0 ? null : summary.slice(at + NOTE_LEAD.length).trim() || null;
583
+ }
584
+
585
+ // --- the approved-plan predicate ---------------------------------------------
586
+
587
+ /**
588
+ * Whether a section's current plan may drive its manuscript. The current plan
589
+ * is the last one linked from the section record; it must be a real contained
590
+ * file, and while confirm_plan is on, an attested author answer of `approve`
591
+ * on a checkpoint scoped to that plan must have been given for exactly these
592
+ * bytes. A later edit, a declined or unconfirmed answer, or no answer at all
593
+ * leaves it unapproved.
594
+ */
595
+ function planState(workspace: string, id: string, record: Json | null, checkpoints: Checkpoint[], confirmPlan: boolean): PlanState {
596
+ const plans = Array.isArray((record?.artifacts as Json | undefined)?.plans) ? ((record?.artifacts as Json).plans as unknown[]) : [];
597
+ const uri = plans.length > 0 && typeof plans[plans.length - 1] === "string" ? (plans[plans.length - 1] as string) : null;
598
+ if (uri === null) return { state: "none", uri: null, file: null, sha256: null, reason: "no plan is linked from the section record" };
599
+ const file = new RegExp(`^project://sections/${id}/plans/${IDENTIFIER}$`, "u").test(uri) ? artifactFile(workspace, uri) : null;
600
+ const bytes = file === null ? null : readBytes(workspace, file);
601
+ if (file === null || bytes === null)
602
+ return { state: "missing", uri, file, sha256: null, reason: `${uri} does not resolve to a plan file in this project` };
603
+ const digest = sha256(bytes);
604
+ const policy: PlanState = { state: "policy", uri, file, sha256: digest, reason: "confirm_plan is off, so the linked plan stands without an author approval" };
605
+ const asked = checkpoints.filter((checkpoint) => checkpoint.scope_uri === uri && checkpoint.kind !== "state-snapshot");
606
+ const answered = asked
607
+ .filter((checkpoint) => checkpoint.trust === "attested" && checkpoint.answer)
608
+ .sort((a, b) => text(b.answer?.answered_at).localeCompare(text(a.answer?.answered_at)));
609
+ const latest = answered[0];
610
+ // An author's explicit answer on this plan decides even when confirm_plan is off: a rejection is never overridden by policy.
611
+ if (latest) {
612
+ if (latest.resolution?.selected_option !== APPROVE || latest.status !== "resolved") {
613
+ const note = authorNote(latest);
614
+ return {
615
+ state: "declined",
616
+ uri,
617
+ file,
618
+ sha256: digest,
619
+ reason: `the author answered "${latest.resolution?.selected_option ?? latest.status}" on ${latest.id}, not approve${note ? `, with this note for the next plan: ${note}` : ""}`,
620
+ };
621
+ }
622
+ const shown = ((latest.answer?.presented as Json | undefined)?.artifact as Json | undefined)?.sha256;
623
+ if (shown !== digest)
624
+ return confirmPlan ? { state: "changed", uri, file, sha256: digest, reason: `the plan changed after the author approved it on ${latest.id}` } : policy;
625
+ return { state: "approved", uri, file, sha256: digest, reason: `approved by the author on ${latest.id}`, approvedAt: text(latest.answer?.answered_at) };
626
+ }
627
+ if (!confirmPlan) return policy;
628
+ if (asked.some((checkpoint) => checkpoint.trust === "pending"))
629
+ return { state: "awaiting", uri, file, sha256: digest, reason: "its approval checkpoint waits on the author" };
630
+ if (asked.some((checkpoint) => checkpoint.trust === "unattested" || checkpoint.trust === "foreign"))
631
+ return { state: "unconfirmed", uri, file, sha256: digest, reason: "its recorded approval was not observed by this desk; confirm it at the gate" };
632
+ return { state: "awaiting", uri, file, sha256: digest, reason: `no approval checkpoint is scoped to ${uri}` };
633
+ }
634
+
635
+ function planReady(plan: PlanState): boolean {
636
+ return plan.state === "approved" || plan.state === "policy";
637
+ }
638
+
639
+ /** Why a section's manuscript may not be written now; empty when it may. */
640
+ function blockers(desk: Desk, section: SectionRow): string[] {
641
+ const reasons: string[] = [];
642
+ for (const gate of section.gates)
643
+ reasons.push(
644
+ gate.trust === "pending"
645
+ ? `the author has not answered "${gate.request}" (${gate.id})`
646
+ : `the recorded answer to ${gate.id} was not observed by this desk and must be confirmed`,
647
+ );
648
+ if (!planReady(section.plan)) reasons.push(`${section.plan.reason}`);
649
+ const gap = evidenceGap(section);
650
+ if (gap) reasons.push(`${gap}; run research-gap first`);
651
+ return reasons;
652
+ }
653
+
654
+ /** Why a literature-heavy section's evidence does not cover it yet; null when it does or when it needs no research. */
655
+ function evidenceGap(section: SectionRow): string | null {
656
+ if (!section.research.required) return null;
657
+ if (section.unsupported.length > 0)
658
+ return `${section.unsupported.length} required ${section.unsupported.length === 1 ? "claim lacks" : "claims lack"} verified evidence (${section.unsupported.slice(0, 3).join(", ")})`;
659
+ if (section.research.claimless) return "it requires research but records no claim that needs evidence, so no source can be shown to cover it";
660
+ return null;
661
+ }
662
+
663
+ // --- loading -----------------------------------------------------------------
664
+
665
+ function loadDesk(workspace: string, key: Buffer | null = null): Desk {
257
666
  const manifest = readRecord(workspace, ".planning/project.json");
258
667
  const config = readRecord(workspace, ".planning/config.json");
259
668
  const state = readRecord(workspace, ".planning/state.json");
260
669
  const outline = readRecord(workspace, ".planning/structure/outline.json");
261
670
  const target = (manifest?.target ?? {}) as Json;
262
671
  const progress = (state?.progress ?? {}) as Json;
672
+ const projectId = typeof manifest?.id === "string" ? manifest.id : null;
673
+ const interactions = listJson(workspace, ".planning/interactions").flatMap((file) => {
674
+ const record = readRecord(workspace, file);
675
+ return record && record.schema === "wtfp.project.interaction/v1" ? [record] : [];
676
+ });
263
677
  const checkpoints: Checkpoint[] = listJson(workspace, ".planning/checkpoints").flatMap((file) => {
264
678
  const record = readRecord(workspace, file);
265
679
  if (!record || typeof record.id !== "string") return [];
266
- return [
267
- {
268
- ...record,
269
- file,
270
- id: record.id,
271
- kind: text(record.kind, "decision"),
272
- status: text(record.status, "pending"),
273
- blocking: record.blocking === true,
274
- scope_uri: text(record.scope_uri),
275
- request: text(record.request, record.id),
276
- } as Checkpoint,
277
- ];
680
+ const checkpoint = {
681
+ ...record,
682
+ file,
683
+ id: record.id,
684
+ kind: text(record.kind, "decision"),
685
+ status: text(record.status, "pending"),
686
+ blocking: record.blocking === true,
687
+ scope_uri: text(record.scope_uri),
688
+ request: text(record.request, record.id),
689
+ } as Checkpoint;
690
+ Object.assign(checkpoint, trustOf(checkpoint, interactions, key, projectId));
691
+ return [checkpoint];
278
692
  });
279
693
  checkpoints.sort((a, b) => text(a.created_at).localeCompare(text(b.created_at)) || a.id.localeCompare(b.id));
694
+ const gates = (config?.gates ?? {}) as Json;
695
+ const confirmPlan = gates.confirm_plan !== false;
696
+ const outputFormat = text(config?.output_format, "markdown");
697
+
698
+ // Only a record that passes its schema can support a claim, and an id carried by two records names neither.
699
+ const ignored: Array<{ file: string; reason: string }> = [];
700
+ const sources: Record<string, number> = {};
701
+ const indexed = (collection: string): Record<string, Json> => {
702
+ const entries: Array<{ file: string; record: Json }> = [];
703
+ for (const file of listJson(workspace, `.planning/${collection}`)) {
704
+ const record = readRecord(workspace, file);
705
+ if (!record) continue;
706
+ if (collection === "sources") sources[text(record.status, "unknown")] = (sources[text(record.status, "unknown")] ?? 0) + 1;
707
+ if (validateRecord(record).length > 0) ignored.push({ file, reason: "it fails its schema" });
708
+ else entries.push({ file, record });
709
+ }
710
+ const index = coverage.indexRecords(entries, collection, (id) => `.planning/${collection}/${id}.json`);
711
+ ignored.push(...index.ignored);
712
+ return index.byUri;
713
+ };
714
+ const sourceRecords = indexed("sources");
715
+ const evidenceRecords = indexed("evidence");
716
+
717
+ const validations = listJson(workspace, ".planning/validations")
718
+ .map((file) => {
719
+ const record = readRecord(workspace, file);
720
+ // The desk writes every record itself, so the file's time is a clock the model cannot set.
721
+ if (record) recordedAt.set(record, writtenAt(workspace, file) ?? 0);
722
+ return record;
723
+ })
724
+ .filter((record): record is Json => record !== null);
725
+
280
726
  const outlined = Array.isArray(outline?.sections) ? (outline.sections as Json[]) : [];
281
- const sections: SectionRow[] = outlined.map((entry) => {
727
+ const loaded = outlined.map((entry) => {
282
728
  const id = text(entry.id, "section");
283
- const base = `.planning/sections/${id}`;
284
- const record = readRecord(workspace, `${base}/section.json`);
729
+ // A section file holds the section its directory names; a record with another id is not this section's.
730
+ const file = `.planning/sections/${id}/section.json`;
731
+ const found = readRecord(workspace, file);
732
+ if (found && found.id !== id) ignored.push({ file, reason: `it holds section ${String(found.id)}, not ${id}` });
733
+ const record = found && found.id === id ? found : null;
285
734
  const artifacts = (record?.artifacts ?? {}) as Json;
286
- const manuscript = manuscriptFile(workspace, artifacts.manuscript ?? `project://paper/${id}`);
735
+ const manuscript = manuscriptFile(workspace, artifacts.manuscript ?? `project://paper/${id}`, outputFormat);
287
736
  const source = manuscript ? readText(workspace, manuscript) : null;
737
+ return { entry, id, record, artifacts, manuscript, source };
738
+ });
739
+ // A manuscript that exists but cannot be read safely, or that a drafted section lacks, leaves its citations unchecked.
740
+ const unread = loaded.flatMap((item) => {
741
+ if (item.source !== null) return [];
742
+ const drafted = ["writing", "reviewing", "complete"].includes(text(item.record?.status));
743
+ if (item.manuscript === null)
744
+ return drafted ? [{ section: item.id, file: text((item.artifacts as Json).manuscript), reason: "its manuscript link does not name a file under paper/" }] : [];
745
+ let present = false;
746
+ try {
747
+ lstatSync(path.join(workspace, item.manuscript));
748
+ present = true;
749
+ } catch {
750
+ present = false;
751
+ }
752
+ if (present) return [{ section: item.id, file: item.manuscript, reason: "it is a link, not a regular file, or too large" }];
753
+ const status = text(item.record?.status);
754
+ return ["writing", "reviewing", "complete"].includes(status) ? [{ section: item.id, file: item.manuscript, reason: `the section is ${status} but its manuscript does not exist` }] : [];
755
+ });
756
+ const report = coverage.analyzeCoverage({
757
+ projectId,
758
+ outline,
759
+ sections: loaded.filter((item) => item.record).map((item) => ({ uri: `project://sections/${item.id}`, record: item.record })),
760
+ evidence: evidenceRecords,
761
+ sources: sourceRecords,
762
+ manuscripts: loaded
763
+ .filter((item) => item.source !== null && item.manuscript !== null)
764
+ .map((item) => ({ section: item.id, file: item.manuscript, text: item.source })),
765
+ ignored,
766
+ unread,
767
+ });
768
+
769
+ const sections: SectionRow[] = loaded.map(({ entry, id, record, artifacts, manuscript, source }) => {
770
+ const base = `.planning/sections/${id}`;
288
771
  const words = source === null || manuscript === null ? 0 : bodyWords(source, manuscript);
289
772
  const status = text(record?.status, "not-started");
290
773
  const claims = Array.isArray(record?.claims) ? (record.claims as Json[]) : [];
291
774
  const plans = Array.isArray(artifacts.plans) ? artifacts.plans : [];
292
775
  const reviews = Array.isArray(artifacts.reviews) ? artifacts.reviews : [];
293
776
  const research = (entry.research ?? {}) as Json;
777
+ const unsupported = coverage.unsupportedRequired(report, id);
294
778
  return {
295
779
  id,
296
780
  title: text(entry.title, id),
@@ -298,32 +782,33 @@ function loadDesk(workspace: string): Desk {
298
782
  status,
299
783
  target: typeof entry.word_target === "number" ? entry.word_target : Number(record?.word_target ?? 0),
300
784
  words,
785
+ recorded: typeof record?.word_count === "number" ? record.word_count : null,
301
786
  manuscript,
302
787
  claims: {
303
788
  total: claims.length,
304
789
  verified: claims.filter((claim) => claim.status === "verified").length,
305
- unsupported: claims.filter(
306
- (claim) =>
307
- claim.evidence_required === true &&
308
- (!Array.isArray(claim.evidence_uris) || claim.evidence_uris.length === 0),
309
- ).length,
790
+ unsupported: unsupported.length,
310
791
  },
311
792
  stages: {
312
- discuss: existsSync(path.join(workspace, base, "context.md")),
793
+ discuss: readBytes(workspace, `${base}/context.md`) !== null,
313
794
  plan: plans.length > 0 || ["planned", "writing", "reviewing", "complete"].includes(status),
314
795
  write: words > 0 || ["reviewing", "complete"].includes(status),
315
796
  review: reviews.length > 0 || status === "complete",
316
797
  },
317
798
  gates: sectionGates(checkpoints, id, manuscript),
318
- research: { required: research.required === true, present: existsSync(path.join(workspace, base, "research.md")) },
799
+ research: {
800
+ required: research.required === true,
801
+ present: readBytes(workspace, `${base}/research.md`) !== null,
802
+ claimless: !claims.some((claim) => claim.evidence_required === true && claim.status !== "rejected"),
803
+ },
319
804
  dependsOn: Array.isArray(entry.depends_on) ? entry.depends_on.filter((dep): dep is string => typeof dep === "string") : [],
805
+ plan: planState(workspace, id, record, checkpoints, confirmPlan),
806
+ unsupported,
807
+ record,
808
+ acceptance: acceptanceOf(validations, checkpoints, id, text(artifacts.manuscript, `project://paper/${id}`), reviews.length > 0, writtenAt(workspace, manuscript)),
809
+ writtenAt: writtenAt(workspace, manuscript),
320
810
  };
321
811
  });
322
- const sources: Record<string, number> = {};
323
- for (const file of listJson(workspace, ".planning/sources")) {
324
- const status = text(readRecord(workspace, file)?.status, "unknown");
325
- sources[status] = (sources[status] ?? 0) + 1;
326
- }
327
812
  const issues = { blocker: 0, error: 0, warning: 0, info: 0 };
328
813
  for (const file of listJson(workspace, ".planning/validations")) {
329
814
  const record = readRecord(workspace, file);
@@ -332,22 +817,27 @@ function loadDesk(workspace: string): Desk {
332
817
  if (severity in issues) issues[severity] += 1;
333
818
  }
334
819
  }
335
- const gates = (config?.gates ?? {}) as Json;
820
+ const journal = contained(workspace, JOURNAL);
336
821
  return {
337
822
  workspace,
338
823
  present: manifest !== null,
824
+ projectId,
339
825
  title: text(manifest?.title, "Untitled paper"),
340
826
  documentType: text(manifest?.document_type, "paper"),
341
827
  venue: typeof target.venue === "string" ? target.venue : null,
342
828
  deadline: typeof target.deadline === "string" ? target.deadline : null,
343
829
  argument: text(manifest?.core_argument),
344
830
  phase: text(state?.phase, manifest ? "initialized" : "none"),
831
+ audit: auditOf(validations, sections),
832
+ delivered: deliveredOf(validations, sections),
345
833
  status: text(state?.status, "active"),
346
- confirmPlan: gates.confirm_plan !== false,
834
+ confirmPlan,
835
+ outputFormat,
347
836
  sections,
348
837
  checkpoints,
838
+ interactions,
349
839
  sources,
350
- evidence: listJson(workspace, ".planning/evidence").length,
840
+ evidence: Object.keys(evidenceRecords).length,
351
841
  issues,
352
842
  invalid: [],
353
843
  targetWords:
@@ -358,101 +848,886 @@ function loadDesk(workspace: string): Desk {
358
848
  : typeof target.word_limit === "number"
359
849
  ? target.word_limit
360
850
  : sections.reduce((sum, section) => sum + section.target, 0),
361
- paperExists: existsSync(path.join(workspace, "paper")),
851
+ paperExists: contained(workspace, "paper") !== null && existsSync(path.join(workspace, "paper")),
852
+ journal: journal !== null && existsSync(journal),
853
+ coverage: report,
362
854
  served: null,
363
855
  };
364
856
  }
365
857
 
366
- // --- the rule ladder ---------------------------------------------------------
367
-
368
- interface Next {
369
- command: string | null;
370
- reason: string;
858
+ /**
859
+ * Disagreements between the records and the files they describe. Each one is
860
+ * a reason not to trust a count or a link until the action that owns it runs
861
+ * again; none is repaired here.
862
+ */
863
+ function reconcile(workspace: string, desk: Desk): Finding[] {
864
+ const out: Finding[] = [];
865
+ const add = (severity: Finding["severity"], code: string, subject: string, message: string): void => {
866
+ out.push({ severity, code, subject, message });
867
+ };
868
+ if (desk.journal) add("blocker", "write-interrupted", "project://state", "A journaled record write was interrupted; the next desk write or /ext:wtfp:validate completes it.");
869
+ if (!desk.present) return out;
870
+ const state = readRecord(workspace, ".planning/state.json");
871
+ const manifest = readRecord(workspace, ".planning/project.json");
872
+ const progress = (state?.progress ?? {}) as Json;
873
+ if (state) {
874
+ if (typeof progress.sections_total === "number" && progress.sections_total !== desk.sections.length)
875
+ add("warning", "state-sections-total", "project://state", `state counts ${progress.sections_total} sections; the outline has ${desk.sections.length}.`);
876
+ const complete = desk.sections.filter((section) => section.status === "complete").length;
877
+ if (typeof progress.sections_complete === "number" && progress.sections_complete !== complete)
878
+ add("warning", "state-sections-complete", "project://state", `state counts ${progress.sections_complete} complete sections; the section records say ${complete}.`);
879
+ const recorded = desk.sections.reduce((sum, section) => sum + (section.recorded ?? 0), 0);
880
+ if (typeof progress.word_count === "number" && progress.word_count !== recorded)
881
+ add("warning", "state-word-count", "project://state", `state records ${progress.word_count} words; the section records sum to ${recorded}.`);
882
+ const active = new Set(Array.isArray(state.active_checkpoint_uris) ? (state.active_checkpoint_uris as string[]) : []);
883
+ const pending = new Set(desk.checkpoints.filter((checkpoint) => checkpoint.status === "pending").map((checkpoint) => `project://checkpoints/${checkpoint.id}`));
884
+ for (const uri of active)
885
+ if (!pending.has(uri)) add("warning", "state-active-stale", uri, `state lists ${uri} as active, but it is not a pending checkpoint.`);
886
+ for (const uri of pending)
887
+ if (!active.has(uri)) add("info", "state-active-missing", uri, `${uri} is pending but state does not list it as active.`);
888
+ }
889
+ const manuscripts = new Set(Array.isArray((manifest?.artifacts as Json | undefined)?.manuscripts) ? ((manifest?.artifacts as Json).manuscripts as string[]) : []);
890
+ for (const section of desk.sections) {
891
+ const subject = `project://sections/${section.id}`;
892
+ if (!section.record) {
893
+ if (section.status !== "not-started") add("error", "section-missing", subject, `the outline names ${section.id}, but its section record is missing.`);
894
+ continue;
895
+ }
896
+ const artifacts = (section.record.artifacts ?? {}) as Json;
897
+ for (const uri of [
898
+ ...(Array.isArray(artifacts.plans) ? (artifacts.plans as string[]) : []),
899
+ ...(Array.isArray(artifacts.reviews) ? (artifacts.reviews as string[]) : []),
900
+ ...["context", "research", "summary", "handoff"].map((key) => artifacts[key]).filter((uri): uri is string => typeof uri === "string"),
901
+ ]) {
902
+ const file = artifactFile(workspace, uri, desk.outputFormat);
903
+ if (file === null || readBytes(workspace, file) === null) add("error", "artifact-dangling", subject, `${uri} is linked but does not resolve to a file.`);
904
+ }
905
+ for (const uri of Array.isArray(section.record.checkpoint_uris) ? (section.record.checkpoint_uris as string[]) : [])
906
+ if (!desk.checkpoints.some((checkpoint) => `project://checkpoints/${checkpoint.id}` === uri))
907
+ add("error", "checkpoint-dangling", subject, `${uri} is linked but no such checkpoint exists.`);
908
+ if (section.words > 0) {
909
+ if (section.recorded !== section.words)
910
+ add("warning", "words-unmeasured", subject, `${section.manuscript} has ${section.words} body words; the section record says ${section.recorded ?? "nothing"}. It changed after the last measurement.`);
911
+ const uri = typeof artifacts.manuscript === "string" ? artifacts.manuscript : `project://paper/${section.id}`;
912
+ if (!manuscripts.has(uri)) add("warning", "manuscript-unindexed", subject, `${uri} has text but is missing from the manifest's manuscripts index.`);
913
+ if (!planReady(section.plan))
914
+ add("warning", "draft-without-approved-plan", subject, `${section.manuscript} has text, but ${section.plan.reason}. The desk did not authorize those writes; they were imported or written outside an orchestrated action.`);
915
+ }
916
+ }
917
+ for (const checkpoint of desk.checkpoints)
918
+ if (checkpoint.blocking && unconfirmed(checkpoint))
919
+ add("warning", "resolution-unattested", `project://checkpoints/${checkpoint.id}`, `${checkpoint.id} is recorded as ${checkpoint.status}, but no author answer sealed by this desk stands behind it; it still holds its scope.`);
920
+ return out;
371
921
  }
372
922
 
373
- /** One rung of the ladder; a step only the absent plugin can run says so instead of naming it. */
374
- function step(served: ServedPlugin, action: string, args: string, reason: string): Next {
375
- const command = commandFor(served, action, args);
376
- return command ? { command, reason } : { command: null, reason: `${reason} Its next step, ${action}, needs the WTF-P plugin.` };
377
- }
923
+ // --- the lock and the journal ------------------------------------------------
378
924
 
379
- function nextAction(desk: Desk): Next {
380
- const served = desk.served;
381
- if (!desk.present)
382
- return desk.paperExists
383
- ? step(served, "map-project", "", "A manuscript exists but no WTF-P project records do.")
384
- : step(served, "new-paper", "", "Start a project: brief, decisions and outline.");
385
- const gate = desk.checkpoints.find((checkpoint) => checkpoint.status === "pending" && checkpoint.blocking);
386
- if (gate) return step(served, "check-todos", "", `Gate waiting on you: ${gate.request}`);
387
- if (desk.sections.length === 0) return step(served, "create-outline", "", "No outline yet.");
388
- const complete = new Set(desk.sections.filter((section) => section.status === "complete").map((section) => section.id));
389
- const ordered = [...desk.sections].sort((a, b) => a.wave - b.wave);
390
- for (const section of ordered) {
391
- if (section.status === "complete") continue;
392
- if (!section.dependsOn.every((dep) => complete.has(dep)) && section.status === "not-started") continue;
393
- return sectionNext(served, section);
925
+ const SLEEP = new Int32Array(new SharedArrayBuffer(4));
926
+
927
+ /** Runs `work` while this process holds the project's write lock. */
928
+ function withLock<T>(workspace: string, work: () => T): T {
929
+ const planning = contained(workspace, ".planning");
930
+ if (planning === null) throw new Error(".planning is a symbolic link or escapes the project; the desk writes only real project directories");
931
+ mkdirSync(planning, { recursive: true });
932
+ const lock = path.join(workspace, LOCK);
933
+ const deadline = performance.now() + LOCK_WAIT_MS;
934
+ for (;;) {
935
+ try {
936
+ const handle = openSync(lock, "wx", 0o600);
937
+ writeSync(handle, `${process.pid} ${new Date().toISOString()}\n`);
938
+ closeSync(handle);
939
+ break;
940
+ } catch (error) {
941
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
942
+ try {
943
+ if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS) {
944
+ unlinkSync(lock);
945
+ continue;
946
+ }
947
+ } catch {
948
+ continue;
949
+ }
950
+ if (performance.now() > deadline) throw new Error(`another writer holds ${LOCK}; nothing was written, try again`);
951
+ Atomics.wait(SLEEP, 0, 0, 20);
952
+ }
953
+ }
954
+ try {
955
+ return work();
956
+ } finally {
957
+ try {
958
+ unlinkSync(lock);
959
+ } catch {
960
+ // Already gone: a stale-lock sweep by another process is the only way, and it changes nothing here.
961
+ }
394
962
  }
395
- if (desk.phase === "delivered") return { command: null, reason: "Delivered." };
396
- if (desk.phase === "ready") return step(served, "submit-milestone", "", "Every section is complete and audited.");
397
- return step(served, "audit-milestone", "", "Every section is complete; audit before delivery.");
398
963
  }
399
964
 
400
- /** The next step for one section, by the same ladder the band follows. */
401
- function sectionNext(served: ServedPlugin, section: SectionRow): Next {
402
- const id = section.id;
403
- if (section.gates.length > 0) return step(served, "check-todos", "", `${section.title} waits on a gate.`);
404
- switch (section.status) {
405
- case "complete":
406
- return step(served, "review-section", id, `${section.title} is complete; review it again if it changed.`);
407
- case "blocked":
408
- return step(served, "check-todos", "", `${section.title} is blocked.`);
409
- case "reviewing":
410
- return step(served, "review-section", id, `${section.title} is drafted and waits for review.`);
411
- case "writing":
412
- case "planned":
413
- return step(served, "write-section", id, `${section.title} has an approved plan.`);
414
- default:
415
- if (!section.stages.discuss) return step(served, "discuss-section", id, `Settle what ${section.title} must argue.`);
416
- if (section.research.required && !section.research.present)
417
- return step(served, "research-gap", id, `${section.title} needs verified evidence first.`);
418
- return step(served, "plan-section", id, `${section.title} is ready to plan.`);
965
+ /**
966
+ * Writes a new file and flushes it where the process may. Node's permission
967
+ * model, which Clio runs the desk under, refuses every flush (fsync,
968
+ * fdatasync, flush: true) with ERR_ACCESS_DENIED, so there a write is still
969
+ * all-or-nothing by its rename but not durable across power loss. A file that
970
+ * could not be written whole is removed.
971
+ */
972
+ function writeDurably(file: string, data: string): void {
973
+ const handle = openSync(file, "wx", 0o644);
974
+ try {
975
+ writeSync(handle, data);
976
+ try {
977
+ fsyncSync(handle);
978
+ } catch (error) {
979
+ if ((error as NodeJS.ErrnoException).code !== "ERR_ACCESS_DENIED") throw error;
980
+ }
981
+ } catch (error) {
982
+ closeSync(handle);
983
+ try {
984
+ unlinkSync(file);
985
+ } catch {
986
+ // Already removed.
987
+ }
988
+ throw error;
419
989
  }
990
+ closeSync(handle);
420
991
  }
421
992
 
422
- // --- views -------------------------------------------------------------------
423
-
424
- function meter(words: number, target: number, cells = 8): string {
425
- if (target <= 0) return "";
426
- const filled = Math.max(0, Math.min(cells, Math.round((words / target) * cells)));
427
- return `${"▰".repeat(filled)}${"▱".repeat(cells - filled)}`;
993
+ /** Fault injection for the package tests; unset in every real session. */
994
+ function fault(point: string): void {
995
+ if (process.env.WTFP_DESK_TEST_FAULT === point) throw new Error(`injected fault at ${point}`);
428
996
  }
429
997
 
430
- /** Within 15 percent of the target, by the same count the meter draws. */
431
- function tolerance(words: number, target: number): ViewTone {
432
- if (target <= 0 || words === 0) return "muted";
433
- const delta = Math.abs(words - target) / target;
434
- return delta <= 0.15 ? "positive" : words > target ? "warning" : "neutral";
998
+ interface PendingWrite {
999
+ uri: string;
1000
+ file: string;
1001
+ text: string;
1002
+ sha256: string;
1003
+ revision: number | null;
435
1004
  }
436
1005
 
437
- function stageStrip(section: SectionRow): string {
438
- const active = (stage: keyof SectionRow["stages"]): boolean =>
439
- (stage === "discuss" && section.status === "researching") ||
440
- (stage === "write" && section.status === "writing") ||
441
- (stage === "review" && section.status === "reviewing");
442
- const mark = (stage: keyof SectionRow["stages"], letter: string): string =>
443
- `${letter}${section.stages[stage] && !active(stage) ? "✓" : active(stage) ? "▸" : "·"}`;
444
- return `${mark("discuss", "D")} ${mark("plan", "P")} ${mark("write", "W")} ${mark("review", "R")}`;
1006
+ interface JournalEntry {
1007
+ file: string;
1008
+ staging: string;
1009
+ sha256: string;
445
1010
  }
446
1011
 
447
- function daysLeft(deadline: string | null): string | null {
448
- if (!deadline) return null;
449
- const due = Date.parse(`${deadline}T23:59:59Z`);
450
- if (Number.isNaN(due)) return null;
451
- const days = Math.ceil((due - Date.now()) / 86_400_000);
452
- return days < 0 ? `${-days} days past ${deadline}` : days === 0 ? `due today (${deadline})` : `${days} days to ${deadline}`;
1012
+ const UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
1013
+ const STAGING = new RegExp(`\\.${UUID}\\.partial$`, "u");
1014
+
1015
+ /** Whether a journal entry is one `commit` could have written: a record file and its own staged copy. */
1016
+ function journaled(entry: unknown): entry is JournalEntry {
1017
+ if (entry === null || typeof entry !== "object") return false;
1018
+ const { file, staging, sha256: digest } = entry as Json;
1019
+ return (
1020
+ typeof file === "string" &&
1021
+ RECORD_URIS.some((route) => route.filePattern.test(file)) &&
1022
+ typeof staging === "string" &&
1023
+ new RegExp(`^${file.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&")}\\.${UUID}\\.partial$`, "u").test(staging) &&
1024
+ typeof digest === "string" &&
1025
+ /^[a-f0-9]{64}$/u.test(digest)
1026
+ );
453
1027
  }
454
1028
 
455
- function totalWords(desk: Desk): number {
1029
+ /**
1030
+ * A failure after the commit point. The write is in place, or the journal
1031
+ * finishes it, so it must never be reported as not written. `pending` says
1032
+ * recovery still has to finish it.
1033
+ */
1034
+ class AfterCommit extends Error {
1035
+ readonly pending: boolean;
1036
+ constructor(message: string, pending: boolean) {
1037
+ super(message);
1038
+ this.pending = pending;
1039
+ }
1040
+ }
1041
+
1042
+ /** What a failed write tells the agent: before the commit point nothing changed; after it, the write stands. */
1043
+ function failure(refused: string, error: unknown): string {
1044
+ const message = error instanceof Error ? error.message : String(error);
1045
+ if (error instanceof AfterCommit)
1046
+ return error.pending
1047
+ ? `Committed; recovery pending: ${message}. The next desk write or /ext:wtfp:validate completes it.`
1048
+ : `Committed, but ${message}`;
1049
+ return `${refused}: ${message}`;
1050
+ }
1051
+
1052
+ function stagingFiles(workspace: string, relative = ".planning"): string[] {
1053
+ const directory = contained(workspace, relative);
1054
+ if (directory === null || !existsSync(directory) || !lstatSync(directory).isDirectory()) return [];
1055
+ const out: string[] = [];
1056
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
1057
+ const child = path.posix.join(relative, entry.name);
1058
+ if (entry.isDirectory() && entry.name !== "archives") out.push(...stagingFiles(workspace, child));
1059
+ else if (entry.isFile() && STAGING.test(entry.name)) out.push(child);
1060
+ }
1061
+ return out;
1062
+ }
1063
+
1064
+ /**
1065
+ * Finishes or discards an interrupted commit; call with the lock held. A
1066
+ * journal exists only after every staged file was written whole, so finishing it is
1067
+ * always safe. Staged files without a journal never became visible and are
1068
+ * removed. Returns what it did, or null when there was nothing to do.
1069
+ */
1070
+ function recover(workspace: string): string | null {
1071
+ const journal = path.join(workspace, JOURNAL);
1072
+ if (!existsSync(journal)) {
1073
+ const orphans = stagingFiles(workspace);
1074
+ for (const orphan of orphans) unlinkSync(path.join(workspace, orphan));
1075
+ return orphans.length > 0 ? `Removed ${orphans.length} staged file${orphans.length === 1 ? "" : "s"} from a write that never committed.` : null;
1076
+ }
1077
+ let entries: JournalEntry[];
1078
+ try {
1079
+ const parsed = JSON.parse(readFileSync(journal, "utf8")) as { entries?: JournalEntry[] };
1080
+ entries = Array.isArray(parsed.entries) ? parsed.entries : [];
1081
+ } catch {
1082
+ const aside = `${JOURNAL}.unreadable-${randomUUID()}`;
1083
+ renameSync(journal, path.join(workspace, aside));
1084
+ return `Set aside an unreadable journal as ${aside}; check the records it may have touched before continuing.`;
1085
+ }
1086
+ // The desk journals only its own record writes, each staged beside its target; anything else did not come from a commit.
1087
+ const foreign = entries.filter((entry) => !journaled(entry));
1088
+ if (foreign.length > 0) {
1089
+ const aside = `${JOURNAL}.untrusted-${randomUUID()}`;
1090
+ renameSync(journal, path.join(workspace, aside));
1091
+ return `Set aside a journal naming writes the desk never journals (${foreign.map((entry) => String((entry as Partial<JournalEntry>)?.file)).join(", ")}) as ${aside}; nothing it named was moved.`;
1092
+ }
1093
+ const finished: string[] = [];
1094
+ const drifted: string[] = [];
1095
+ for (const entry of entries) {
1096
+ const target = contained(workspace, entry.file);
1097
+ const staging = contained(workspace, entry.staging);
1098
+ if (target === null || staging === null) {
1099
+ drifted.push(entry.file);
1100
+ continue;
1101
+ }
1102
+ if (existsSync(staging)) {
1103
+ renameSync(staging, target);
1104
+ finished.push(entry.file);
1105
+ }
1106
+ const bytes = readBytes(workspace, entry.file);
1107
+ if (bytes === null || sha256(bytes) !== entry.sha256) drifted.push(entry.file);
1108
+ }
1109
+ unlinkSync(journal);
1110
+ for (const orphan of stagingFiles(workspace)) unlinkSync(path.join(workspace, orphan));
1111
+ return [
1112
+ `Completed an interrupted write of ${entries.map((entry) => entry.file).join(", ")}${finished.length === 0 ? " (every file had already landed)" : ""}.`,
1113
+ ...(drifted.length > 0 ? [`These no longer hold what that write committed: ${drifted.join(", ")}; read them before relying on them.`] : []),
1114
+ ].join(" ");
1115
+ }
1116
+
1117
+ /**
1118
+ * Makes every write visible or, before the commit point, none. One write is
1119
+ * a staged file renamed over its target. Several are staged, then a journal
1120
+ * naming all of them is written, which is the commit point, then each is
1121
+ * renamed into place and the journal removed. Call with the lock held.
1122
+ */
1123
+ function commit(workspace: string, writes: PendingWrite[]): void {
1124
+ const staged: JournalEntry[] = [];
1125
+ try {
1126
+ for (const write of writes) {
1127
+ const target = contained(workspace, write.file);
1128
+ if (target === null) throw new Error(`refusing to write ${write.file} through a symbolic link`);
1129
+ mkdirSync(path.dirname(target), { recursive: true });
1130
+ if (contained(workspace, write.file) === null) throw new Error(`refusing to write ${write.file} through a symbolic link`);
1131
+ const staging = `${write.file}.${randomUUID()}.partial`;
1132
+ writeDurably(path.join(workspace, staging), write.text);
1133
+ staged.push({ file: write.file, staging, sha256: write.sha256 });
1134
+ }
1135
+ fault("before-commit");
1136
+ if (staged.length > 1) {
1137
+ const journal = `${JOURNAL}.${randomUUID()}.partial`;
1138
+ writeDurably(path.join(workspace, journal), `${JSON.stringify({ schema: "wtfp.clio-journal/v1", at: timestamp(), entries: staged }, null, 2)}\n`);
1139
+ renameSync(path.join(workspace, journal), path.join(workspace, JOURNAL));
1140
+ }
1141
+ } catch (error) {
1142
+ for (const entry of staged) {
1143
+ try {
1144
+ unlinkSync(path.join(workspace, entry.staging));
1145
+ } catch {
1146
+ // Already removed.
1147
+ }
1148
+ }
1149
+ throw error;
1150
+ }
1151
+ if (staged.length === 1) {
1152
+ // One write commits by its rename; a failed rename changed nothing.
1153
+ const [entry] = staged as [JournalEntry];
1154
+ try {
1155
+ renameSync(path.join(workspace, entry.staging), path.join(workspace, entry.file));
1156
+ } catch (error) {
1157
+ try {
1158
+ unlinkSync(path.join(workspace, entry.staging));
1159
+ } catch {
1160
+ // Already removed.
1161
+ }
1162
+ throw error;
1163
+ }
1164
+ } else {
1165
+ // Committed: a failure from here leaves the journal for recover() to finish.
1166
+ try {
1167
+ staged.forEach((entry, index) => {
1168
+ if (index > 0) fault("between-renames");
1169
+ renameSync(path.join(workspace, entry.staging), path.join(workspace, entry.file));
1170
+ });
1171
+ unlinkSync(path.join(workspace, JOURNAL));
1172
+ } catch (error) {
1173
+ throw new AfterCommit(error instanceof Error ? error.message : String(error), true);
1174
+ }
1175
+ }
1176
+ // Stands in for another process changing a file between the rename and the readback.
1177
+ if (process.env.WTFP_DESK_TEST_FAULT === "tamper-after-rename" && staged[0]) appendFileSync(path.join(workspace, staged[0].file), " ");
1178
+ for (const entry of staged) {
1179
+ const back = readBytes(workspace, entry.file);
1180
+ if (back === null || sha256(back) !== entry.sha256)
1181
+ throw new AfterCommit(`readback of ${entry.file} differs from what was written; another writer changed it after the commit, so read it again before relying on it`, false);
1182
+ }
1183
+ }
1184
+
1185
+ // --- portable record writes --------------------------------------------------
1186
+
1187
+ const IDENTIFIER = "[a-z][a-z0-9]*(?:-[a-z0-9]+)*";
1188
+ /** The adapter mapping of project/README.md: logical URI to record type and project-relative file. */
1189
+ const RECORD_URIS: ReadonlyArray<{ pattern: RegExp; type: string; file: (id: string) => string; filePattern: RegExp }> = [
1190
+ { pattern: /^project:\/\/manifest$/u, type: "manifest", file: () => ".planning/project.json", filePattern: /^\.planning\/project\.json$/u },
1191
+ { pattern: /^project:\/\/config$/u, type: "config", file: () => ".planning/config.json", filePattern: /^\.planning\/config\.json$/u },
1192
+ { pattern: /^project:\/\/state$/u, type: "state", file: () => ".planning/state.json", filePattern: /^\.planning\/state\.json$/u },
1193
+ { pattern: /^project:\/\/decisions$/u, type: "decisions", file: () => ".planning/decisions.json", filePattern: /^\.planning\/decisions\.json$/u },
1194
+ {
1195
+ pattern: /^project:\/\/structure\/outline$/u,
1196
+ type: "outline",
1197
+ file: () => ".planning/structure/outline.json",
1198
+ filePattern: /^\.planning\/structure\/outline\.json$/u,
1199
+ },
1200
+ ...(
1201
+ [
1202
+ ["section", "sections", (id: string) => `.planning/sections/${id}/section.json`, `^\\.planning/sections/${IDENTIFIER}/section\\.json$`],
1203
+ ["source", "sources", (id: string) => `.planning/sources/${id}.json`, `^\\.planning/sources/${IDENTIFIER}\\.json$`],
1204
+ ["evidence", "evidence", (id: string) => `.planning/evidence/${id}.json`, `^\\.planning/evidence/${IDENTIFIER}\\.json$`],
1205
+ ["checkpoint", "checkpoints", (id: string) => `.planning/checkpoints/${id}.json`, `^\\.planning/checkpoints/${IDENTIFIER}\\.json$`],
1206
+ ["validation", "validations", (id: string) => `.planning/validations/${id}.json`, `^\\.planning/validations/${IDENTIFIER}\\.json$`],
1207
+ ["interaction", "interactions", (id: string) => `.planning/interactions/${id}.json`, `^\\.planning/interactions/${IDENTIFIER}\\.json$`],
1208
+ ] as const
1209
+ ).map(([type, collection, file, filePattern]) => ({
1210
+ pattern: new RegExp(`^project://${collection}/(${IDENTIFIER})$`, "u"),
1211
+ type,
1212
+ file,
1213
+ filePattern: new RegExp(filePattern, "u"),
1214
+ })),
1215
+ ];
1216
+ const REVISIONED = new Set(["state", "outline", "decisions"]);
1217
+ const STAMPED = new Set(["state", "outline", "decisions", "manifest", "section"]);
1218
+ /** The time a record type is created at; the desk stamps it on create when the writer leaves it out, since a model has no clock. */
1219
+ const CREATED_AT: Readonly<Record<string, string>> = { validation: "executed_at", checkpoint: "created_at", evidence: "verified_at" };
1220
+
1221
+ interface RecordWrite {
1222
+ uri: string;
1223
+ record: Json;
1224
+ expect_revision?: number;
1225
+ expect_sha256?: string;
1226
+ }
1227
+
1228
+ /** Interaction modes from the least to the most the workflow asks the author. */
1229
+ const MODES = ["autonomous", "standard", "guided"];
1230
+
1231
+ const list = (value: unknown): Json[] => (Array.isArray(value) ? (value as Json[]) : []);
1232
+
1233
+ /**
1234
+ * Changes that weaken an author's control or what the desk holds, each as the
1235
+ * line the author is shown before it may land: a gate, check or safeguard
1236
+ * turned off, a less interactive mode, a locked decision changed, a section
1237
+ * dropped from the outline or no longer researched, a manuscript re-pointed
1238
+ * away from the file its gates hold, plan history rewritten, or a claim
1239
+ * released from needing evidence.
1240
+ */
1241
+ function weakening(type: string, prior: Json | null, next: Json): string[] {
1242
+ const changes: string[] = [];
1243
+ if (type === "config") {
1244
+ for (const group of ["gates", "workflow", "safety"]) {
1245
+ const before = (prior?.[group] ?? {}) as Json;
1246
+ for (const [key, value] of Object.entries((next[group] ?? {}) as Json))
1247
+ if (value === false && before[key] !== false) changes.push(`${group}.${key}: on → off`);
1248
+ }
1249
+ const from = prior ? text(prior.interaction_mode, "standard") : null;
1250
+ const to = text(next.interaction_mode, "standard");
1251
+ if (from === null ? to === "autonomous" : MODES.indexOf(to) < MODES.indexOf(from)) changes.push(`interaction_mode: ${from ?? "unset"} → ${to}`);
1252
+ }
1253
+ if (type === "outline" && prior) {
1254
+ const after = new Map(list(next.sections).map((entry) => [entry.id, entry]));
1255
+ for (const entry of list(prior.sections)) {
1256
+ const kept = after.get(entry.id);
1257
+ if (!kept) changes.push(`removes ${String(entry.id)} from the outline, so the desk no longer holds its manuscript`);
1258
+ else if ((entry.research as Json | undefined)?.required === true && (kept.research as Json | undefined)?.required !== true)
1259
+ changes.push(`${String(entry.id)}: research.required on → off, so its claims may be drafted without verified evidence`);
1260
+ }
1261
+ }
1262
+ if (type === "section" && prior) {
1263
+ const id = text(next.id);
1264
+ const before = (prior.artifacts ?? {}) as Json;
1265
+ const after = (next.artifacts ?? {}) as Json;
1266
+ const mapped = (artifacts: Json): string => text(artifacts.manuscript, `project://paper/${id}`);
1267
+ if (mapped(before) !== mapped(after))
1268
+ changes.push(`${id}: manuscript ${mapped(before)} → ${mapped(after)}, so the desk no longer holds the old file`);
1269
+ const plansBefore = Array.isArray(before.plans) ? (before.plans as unknown[]) : [];
1270
+ const plansAfter = Array.isArray(after.plans) ? (after.plans as unknown[]) : [];
1271
+ if (plansBefore.some((uri, index) => plansAfter[index] !== uri))
1272
+ changes.push(`${id}: rewrites the plan history (${plansBefore.join(", ") || "none"} → ${plansAfter.join(", ") || "none"}); plans are only ever appended`);
1273
+ const claims = new Map(list(next.claims).map((claim) => [claim.id, claim]));
1274
+ for (const claim of list(prior.claims))
1275
+ if (claim.evidence_required === true && claims.get(claim.id)?.evidence_required !== true)
1276
+ changes.push(`${id}: claim ${String(claim.id)} no longer requires evidence`);
1277
+ }
1278
+ if (type === "decisions" && prior) {
1279
+ const after = new Map((Array.isArray(next.items) ? (next.items as Json[]) : []).map((item) => [item.id, item]));
1280
+ for (const item of Array.isArray(prior.items) ? (prior.items as Json[]) : []) {
1281
+ if (item.authority !== "author" || item.disposition !== "locked") continue;
1282
+ const changed = after.get(item.id);
1283
+ if (!changed) changes.push(`removes the author's locked decision ${String(item.id)}: ${text(item.statement)}`);
1284
+ else if (canonical(changed) !== canonical(item))
1285
+ changes.push(`changes the author's locked decision ${String(item.id)} (${text(item.disposition as string)} → ${text(changed.disposition as string)}): ${text(changed.statement)}`);
1286
+ }
1287
+ }
1288
+ return changes;
1289
+ }
1290
+
1291
+ /**
1292
+ * Why the agent may not make this checkpoint change; null when it may.
1293
+ * `superseded` says whether the checkpoint asks about a plan that is no longer
1294
+ * its section's current plan, so retiring it can authorize nothing.
1295
+ */
1296
+ function checkpointRefusal(prior: Json | null, next: Json, superseded: boolean): string | null {
1297
+ const snapshot = next.kind === "state-snapshot";
1298
+ const answered = (status: unknown): boolean => status === "resolved" || status === "waived";
1299
+ if (prior && prior.kind !== next.kind) return "a checkpoint's kind cannot change";
1300
+ if (snapshot) return null;
1301
+ if (prior && answered(prior.status)) return "it is answered, so its record is immutable; create a new checkpoint to ask again";
1302
+ if (next.status === "pending" && next.resolution !== undefined) return "a pending checkpoint carries no resolution";
1303
+ if (answered(next.status)) {
1304
+ if ((next.resolution as Json | undefined)?.resolved_by === "author")
1305
+ return "only the author's answer at the desk resolves it as the author's; call extension_wtfp__gate with its id";
1306
+ if (next.blocking === true) return "a blocking checkpoint is resolved only by the author; call extension_wtfp__gate with its id";
1307
+ }
1308
+ if (prior && prior.status === "pending" && prior.blocking === true) {
1309
+ if (next.blocking !== true) return "a pending blocking checkpoint cannot be made nonblocking";
1310
+ if (next.scope_uri !== prior.scope_uri) return "a pending blocking checkpoint cannot change scope";
1311
+ if (next.status === "expired" && !superseded)
1312
+ return "a pending blocking checkpoint cannot be expired by the agent; the author can waive it at the desk";
1313
+ }
1314
+ return null;
1315
+ }
1316
+
1317
+ /** Whether an armed action's contract declares this write. */
1318
+ function declares(armed: Armed, uri: string, mode: string): boolean {
1319
+ return armed.produces.some((output) => output.mode === mode && patternMatches(output.uri, uri, armed.section));
1320
+ }
1321
+
1322
+ function patternMatches(pattern: string, uri: string, section: string | null): boolean {
1323
+ const expression = pattern
1324
+ .split(/(\{[a-z]+\})/u)
1325
+ .map((part) => {
1326
+ if (part === "{section}" && section) return section.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
1327
+ if (part === "{artifact}") return "[A-Za-z0-9._~-]+(?:/[A-Za-z0-9._~-]+)*";
1328
+ if (/^\{[a-z]+\}$/u.test(part)) return IDENTIFIER;
1329
+ return part.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
1330
+ })
1331
+ .join("");
1332
+ return new RegExp(`^${expression}$`, "u").test(uri);
1333
+ }
1334
+
1335
+ interface Prepared {
1336
+ write: PendingWrite;
1337
+ type: string;
1338
+ prior: Json | null;
1339
+ priorSha: string | null;
1340
+ confirm: string[];
1341
+ }
1342
+
1343
+ /**
1344
+ * Checks one record write against everything the desk enforces and returns
1345
+ * the bytes to commit. Call with the lock held. `origin` is "agent" for a
1346
+ * model's tool call and "desk" for the desk's own writes of the author's
1347
+ * answers and its derived counts.
1348
+ */
1349
+ function prepare(workspace: string, input: RecordWrite, origin: "agent" | "desk", armed: Armed | null): Prepared {
1350
+ try {
1351
+ return prepareRecord(workspace, input, origin, armed);
1352
+ } catch (error) {
1353
+ // A create refused for its content carries the record's example, so the next call can succeed.
1354
+ const route = RECORD_URIS.find((entry) => entry.pattern.test(input.uri));
1355
+ const creating = route !== undefined && !existsSync(path.join(workspace, route.file(route.pattern.exec(input.uri)?.[1] ?? "")));
1356
+ const content = error instanceof Error && /holds wtfp\.project|whose id is|project_id|belongs to project|would not validate/u.test(error.message);
1357
+ if (creating && content && route) throw new Error(withTemplate((error as Error).message, route.type));
1358
+ throw error;
1359
+ }
1360
+ }
1361
+
1362
+ function prepareRecord(workspace: string, input: RecordWrite, origin: "agent" | "desk", armed: Armed | null): Prepared {
1363
+ const { uri } = input;
1364
+ const record = input.record;
1365
+ if (record === null || typeof record !== "object" || Array.isArray(record)) throw new Error(`${uri}: record must be a JSON object`);
1366
+ const route = RECORD_URIS.find((entry) => entry.pattern.test(uri));
1367
+ if (!route) throw new Error(notARecord(uri));
1368
+ if (route.type === "interaction" && origin === "agent")
1369
+ throw new Error(`${uri}: only the desk records an author's answer; ask with extension_wtfp__gate`);
1370
+ const id = route.pattern.exec(uri)?.[1] ?? "";
1371
+ if (record.schema !== `wtfp.project.${route.type}/v1`) throw new Error(`${uri} holds wtfp.project.${route.type}/v1 records`);
1372
+ if (id && record.id !== id) throw new Error(`${uri} must hold the record whose id is ${id}`);
1373
+ const file = route.file(id);
1374
+ if (contained(workspace, file) === null) throw new Error(`refusing to write ${uri} through a symbolic link or outside the project`);
1375
+ const manifest = readRecord(workspace, ".planning/project.json");
1376
+ const projectId = route.type === "manifest" ? record.id : record.project_id;
1377
+ if (manifest && typeof manifest.id === "string" && projectId !== manifest.id)
1378
+ throw new Error(
1379
+ projectId === undefined
1380
+ ? `${uri} needs project_id "${manifest.id}"`
1381
+ : `${uri} belongs to project ${String(projectId)}, not ${manifest.id}`,
1382
+ );
1383
+ const bytes = readBytes(workspace, file);
1384
+ if (bytes === null && existsSync(path.join(workspace, file))) throw new Error(`${file} is not a regular file the desk can replace`);
1385
+ const priorSha = bytes === null ? null : sha256(bytes);
1386
+ let prior: Json | null = null;
1387
+ if (bytes !== null) {
1388
+ try {
1389
+ const parsed = JSON.parse(bytes.toString("utf8")) as unknown;
1390
+ prior = parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Json) : null;
1391
+ } catch {
1392
+ prior = null;
1393
+ }
1394
+ }
1395
+ const priorRevision = typeof prior?.revision === "number" ? prior.revision : null;
1396
+ const expectation = input.expect_revision !== undefined || input.expect_sha256 !== undefined;
1397
+ if (bytes === null) {
1398
+ if (expectation) throw new Error(`${uri} no longer exists; read the project again before writing`);
1399
+ } else if (!expectation) {
1400
+ throw new Error(
1401
+ `${uri} already exists; read it with extension_wtfp__read_record and pass ${REVISIONED.has(route.type) ? "the revision you read as expect_revision" : "the sha256 you read as expect_sha256"} so a newer change is never overwritten, then send the write again. A missing version is not a refusal and does not end the step`,
1402
+ );
1403
+ } else {
1404
+ const byRevision = input.expect_revision !== undefined && REVISIONED.has(route.type) && input.expect_revision === priorRevision;
1405
+ const bySha = input.expect_sha256 !== undefined && input.expect_sha256 === priorSha;
1406
+ if (!byRevision && !bySha)
1407
+ throw new Error(
1408
+ REVISIONED.has(route.type) && input.expect_revision !== undefined
1409
+ ? `${uri} is at revision ${String(priorRevision)}, not ${input.expect_revision}; read it again and send the write again. A stale read is not a refusal and does not end the step`
1410
+ : `${uri} changed since it was read; read it again and send the write again. A stale read is not a refusal and does not end the step`,
1411
+ );
1412
+ }
1413
+ if (origin === "agent" && armed && !declares(armed, uri, bytes === null ? "create" : "update"))
1414
+ throw new Error(`${armed.action} does not declare ${bytes === null ? "creating" : "updating"} ${uri}; record what remains as a handoff instead`);
1415
+ if (origin === "agent" && route.type === "checkpoint") {
1416
+ const plan = new RegExp(`^project://sections/(${IDENTIFIER})/plans/${IDENTIFIER}$`, "u").exec(text(prior?.scope_uri));
1417
+ const owner = plan ? readRecord(workspace, `.planning/sections/${plan[1]}/section.json`) : null;
1418
+ const plans = plan && owner?.id === plan[1] ? ((owner.artifacts as Json | undefined)?.plans as unknown[] | undefined) : undefined;
1419
+ const superseded = plan !== null && Array.isArray(plans) && plans.length > 0 && plans[plans.length - 1] !== prior?.scope_uri;
1420
+ const refusal = checkpointRefusal(prior, record, superseded);
1421
+ if (refusal) throw new Error(`${uri}: ${refusal}`);
1422
+ }
1423
+ const next: Json = { ...record };
1424
+ let revision: number | null = null;
1425
+ if (REVISIONED.has(route.type)) {
1426
+ revision = priorRevision === null ? (typeof record.revision === "number" ? record.revision : 0) : priorRevision + 1;
1427
+ next.revision = revision;
1428
+ }
1429
+ if (STAMPED.has(route.type)) next.updated_at = timestamp();
1430
+ const createdAt = CREATED_AT[route.type];
1431
+ // A model has no clock: an invented time can order a validation before the answer it follows, so the desk's time stands.
1432
+ if (bytes === null && createdAt && (origin === "agent" || next[createdAt] === undefined)) next[createdAt] = timestamp();
1433
+ const errors = validateRecord(next);
1434
+ // Every error at once: a model fixing one per call resends its whole context each time.
1435
+ if (errors.length > 0)
1436
+ throw new Error(
1437
+ `${uri} would not validate: ${errors.slice(0, 8).join("; ")}${errors.length > 8 ? `; and ${errors.length - 8} more` : ""}. Fix these and send the write again; a record that does not validate is not a refusal and does not end the step`,
1438
+ );
1439
+ const serialized = `${JSON.stringify(next, null, 2)}\n`;
1440
+ return {
1441
+ write: { uri, file, text: serialized, sha256: sha256(serialized), revision },
1442
+ type: route.type,
1443
+ prior,
1444
+ priorSha,
1445
+ confirm: origin === "agent" ? weakening(route.type, prior, next) : [],
1446
+ };
1447
+ }
1448
+
1449
+ function normalizeWrites(input: Json): RecordWrite[] {
1450
+ if (Array.isArray(input.writes)) {
1451
+ if (input.uri !== undefined || input.record !== undefined) throw new Error("pass either uri and record or writes, not both");
1452
+ if (input.writes.length === 0 || input.writes.length > 16) throw new Error("writes holds one to sixteen records");
1453
+ return input.writes as RecordWrite[];
1454
+ }
1455
+ if (typeof input.uri !== "string") throw new Error("uri is required");
1456
+ return [{ uri: input.uri, record: input.record as Json, expect_revision: input.expect_revision as number | undefined, expect_sha256: input.expect_sha256 as string | undefined }];
1457
+ }
1458
+
1459
+ // --- views -------------------------------------------------------------------
1460
+
1461
+ interface Next {
1462
+ command: string | null;
1463
+ reason: string;
1464
+ /** The catalog action this step runs, when one does. */
1465
+ action?: string;
1466
+ /** The section the action takes as its input, when it takes one. */
1467
+ section?: string | null;
1468
+ /** The checkpoint that must be answered first, when a gate holds the way. */
1469
+ gate?: string;
1470
+ }
1471
+
1472
+ /** One rung of the ladder; a step only the absent plugin can run says so instead of naming it. */
1473
+ function step(served: ServedPlugin, action: string, args: string, reason: string, gate?: string): Next {
1474
+ const command = commandFor(served, action, args);
1475
+ const named = { action, section: args || null, ...(gate ? { gate } : {}) };
1476
+ return command ? { command, reason, ...named } : { command: null, reason: `${reason} Its next step, ${action}, needs the WTF-P plugin.`, ...named };
1477
+ }
1478
+
1479
+ function openGates(desk: Desk): Checkpoint[] {
1480
+ return desk.checkpoints.filter((checkpoint) => holds(checkpoint));
1481
+ }
1482
+
1483
+ function nextAction(desk: Desk): Next {
1484
+ const served = desk.served;
1485
+ if (!desk.present)
1486
+ return desk.paperExists
1487
+ ? step(served, "map-project", "", "A manuscript exists but no WTF-P project records do.")
1488
+ : step(served, "new-paper", "", "Start a project: brief, decisions and outline.");
1489
+ if (desk.journal) return { command: "/ext:wtfp:validate", reason: "A record write was interrupted; validating completes it." };
1490
+ const gate = openGates(desk)[0];
1491
+ if (gate)
1492
+ return step(
1493
+ served,
1494
+ "check-todos",
1495
+ "",
1496
+ gate.trust === "pending" ? `Gate waiting on you: ${gate.request}` : `Confirm the recorded answer to ${gate.id}: ${gate.request}`,
1497
+ gate.id,
1498
+ );
1499
+ if (desk.sections.length === 0) return step(served, "create-outline", "", "No outline yet.");
1500
+ // new-paper writes an outline but no section records, and only create-outline
1501
+ // declares creating one; every later action may only update it.
1502
+ const unrecorded = desk.sections.filter((section) => section.record === null).map((section) => section.id);
1503
+ if (unrecorded.length > 0)
1504
+ return step(served, "create-outline", "", `The outline lists ${unrecorded.join(", ")} without a section record; create-outline creates them.`);
1505
+ const complete = new Set(desk.sections.filter((section) => section.status === "complete").map((section) => section.id));
1506
+ const ordered = [...desk.sections].sort((a, b) => a.wave - b.wave);
1507
+ for (const section of ordered) {
1508
+ if (section.status === "complete") continue;
1509
+ if (!section.dependsOn.every((dep) => complete.has(dep)) && section.status === "not-started") continue;
1510
+ return sectionNext(served, section);
1511
+ }
1512
+ if (desk.phase === "delivered" || desk.delivered) return { command: null, reason: "Delivered: every section is complete, audited and archived; a later change reopens review." };
1513
+ // audit-milestone writes only its validation, so the audit itself, not a phase it cannot set, says the draft is ready.
1514
+ if (desk.phase === "ready" || (desk.audit?.fresh && desk.audit.errors === 0)) return step(served, "submit-milestone", "", "Every section is complete and audited.");
1515
+ if (desk.audit?.fresh)
1516
+ return step(served, "plan-milestone-gaps", "", `The milestone audit found ${desk.audit.errors} ${desk.audit.errors === 1 ? "error" : "errors"} to close before delivery.`);
1517
+ return step(served, "audit-milestone", "", "Every section is complete; audit before delivery.");
1518
+ }
1519
+
1520
+ /**
1521
+ * The latest audit-milestone validation, by the desk's file time. It is fresh
1522
+ * when no other validation and no manuscript was written after it, so an audit
1523
+ * of an earlier draft never stands for the current one.
1524
+ */
1525
+ function auditOf(validations: Json[], sections: SectionRow[]): Desk["audit"] {
1526
+ const at = (record: Json): number => recordedAt.get(record) ?? 0;
1527
+ const audits = validations.filter((record) => record.action_id === "audit-milestone").sort((a, b) => at(b) - at(a));
1528
+ const latest = audits[0];
1529
+ if (!latest) return null;
1530
+ const later = validations.some((record) => record.action_id !== "audit-milestone" && at(record) > at(latest)) || sections.some((section) => (section.writtenAt ?? 0) > at(latest));
1531
+ const errors = (Array.isArray(latest.issues) ? (latest.issues as Json[]) : []).filter((issue) => issue.severity === "error" || issue.severity === "blocker").length;
1532
+ return { fresh: !later && latest.status !== "failed", errors: latest.status === "failed" ? Math.max(errors, 1) : errors };
1533
+ }
1534
+
1535
+ /** Whether the latest passed milestone submission still stands: nothing but audits and submissions came after it. */
1536
+ function deliveredOf(validations: Json[], sections: SectionRow[]): boolean {
1537
+ const at = (record: Json): number => recordedAt.get(record) ?? 0;
1538
+ const submitted = validations.filter((record) => record.action_id === "submit-milestone" && record.status === "passed").sort((a, b) => at(b) - at(a))[0];
1539
+ if (!submitted) return false;
1540
+ const delivery = new Set(["audit-milestone", "submit-milestone"]);
1541
+ return !validations.some((record) => !delivery.has(text(record.action_id)) && at(record) > at(submitted)) && !sections.some((section) => (section.writtenAt ?? 0) > at(submitted));
1542
+ }
1543
+
1544
+ /** A drafted section's next step: review the current draft, then the author's acceptance or a revision. */
1545
+ function reviewNext(served: ServedPlugin, section: SectionRow): Next {
1546
+ const id = section.id;
1547
+ const acceptance = section.acceptance;
1548
+ if (unappliedPlan(section)) return step(served, "write-section", id, `${section.title} has an approved revision plan that no draft has applied yet.`);
1549
+ if (!acceptance.reviewed) return step(served, "review-section", id, `${section.title} is drafted and waits for review.`);
1550
+ if (!acceptance.verified)
1551
+ return step(served, "verify-work", id, `${section.title} is reviewed; the author checks it against its plan and accepts it or sends it back.`);
1552
+ if (acceptance.decision === REVISE)
1553
+ return step(served, "plan-revision", id, `The author sent ${section.title} back for revision${acceptance.note ? `, with this note: ${acceptance.note}` : "."}`);
1554
+ return step(
1555
+ served,
1556
+ "verify-work",
1557
+ id,
1558
+ acceptance.decision === ACCEPT ? `The author accepted ${section.title}; verify-work marks it complete.` : `${section.title} waits for the author's acceptance.`,
1559
+ );
1560
+ }
1561
+
1562
+ /** The next step for one section, by the same ladder the band follows. */
1563
+ function sectionNext(served: ServedPlugin, section: SectionRow): Next {
1564
+ const id = section.id;
1565
+ if (section.gates.length > 0) return step(served, "check-todos", "", `${section.title} waits on a gate.`, section.gates[0]?.id);
1566
+ switch (section.status) {
1567
+ case "complete":
1568
+ return step(served, "review-section", id, `${section.title} is complete; review it again if it changed.`);
1569
+ case "blocked":
1570
+ return step(served, "check-todos", "", `${section.title} is blocked.`);
1571
+ case "reviewing":
1572
+ return reviewNext(served, section);
1573
+ case "writing":
1574
+ case "planned":
1575
+ if (evidenceGap(section))
1576
+ return step(served, "research-gap", id, `${section.title}: ${evidenceGap(section)}.`);
1577
+ if (!planReady(section.plan))
1578
+ return step(served, "plan-section", id, `${section.title} cannot be drafted: ${section.plan.reason}.`);
1579
+ // A draft written after its plan's approval is past drafting even when the record still says writing.
1580
+ if (section.plan.state === "approved" && section.plan.approvedAt && section.writtenAt !== null && Date.parse(section.plan.approvedAt) <= section.writtenAt)
1581
+ return reviewNext(served, section);
1582
+ return step(served, "write-section", id, `${section.title} has an approved plan.`);
1583
+ default:
1584
+ if (!section.stages.discuss) return step(served, "discuss-section", id, `Settle what ${section.title} must argue.`);
1585
+ if (section.research.required && !section.research.present)
1586
+ return step(served, "research-gap", id, `${section.title} needs verified evidence first.`);
1587
+ if (evidenceGap(section))
1588
+ return step(served, "research-gap", id, `${section.title}: ${evidenceGap(section)}.`);
1589
+ return step(served, "plan-section", id, `${section.title} is ready to plan.`);
1590
+ }
1591
+ }
1592
+
1593
+ // --- driver --------------------------------------------------------------------
1594
+
1595
+ /**
1596
+ * The actions `/wtfp:advance` may chain. Each runs under its own contract; the
1597
+ * driver never runs an action that starts, maps or reshapes the project, since
1598
+ * those are the author's to begin.
1599
+ */
1600
+ const DRIVEN = new Set(["create-outline", "discuss-section", "research-gap", "plan-section", "write-section", "review-section", "verify-work", "plan-revision", "audit-milestone", "submit-milestone"]);
1601
+ /** Steps one advance run may take before it hands the session back. */
1602
+ const MAX_DRIVE_STEPS = 24;
1603
+
1604
+ /** One `/wtfp:advance` run: the steps the desk armed and the gates it put to the author. */
1605
+ interface Drive {
1606
+ workspace: string;
1607
+ /** `finish`: the step was handed back once to record outputs it skipped. */
1608
+ steps: Array<{ action: string; section: string | null; fingerprint: string; finish?: boolean }>;
1609
+ asked: string[];
1610
+ }
1611
+
1612
+ type DriveDecision =
1613
+ | { kind: "step"; action: string; section: string | null; prompt: string; reason: string; finish?: boolean }
1614
+ | { kind: "gate"; checkpoint: string; reason: string }
1615
+ | { kind: "stop"; reason: string };
1616
+
1617
+ /** What the project looks like to the ladder; an unchanged fingerprint means a step changed nothing it reads. */
1618
+ function driveFingerprint(desk: Desk): string {
1619
+ return sha256(
1620
+ JSON.stringify({
1621
+ phase: desk.phase,
1622
+ status: desk.status,
1623
+ sections: desk.sections.map((section) => [
1624
+ section.id,
1625
+ section.status,
1626
+ section.stages,
1627
+ section.plan.state,
1628
+ section.plan.sha256,
1629
+ section.unsupported,
1630
+ section.research,
1631
+ section.words,
1632
+ section.recorded,
1633
+ section.acceptance,
1634
+ section.gates.map((gate) => [gate.id, gate.status, gate.trust]),
1635
+ ]),
1636
+ checkpoints: desk.checkpoints.map((checkpoint) => [checkpoint.id, checkpoint.status, checkpoint.trust]),
1637
+ sources: desk.sources,
1638
+ evidence: desk.evidence,
1639
+ }),
1640
+ );
1641
+ }
1642
+
1643
+ /**
1644
+ * The driver's next move, chosen by the same ladder `progress` follows. The
1645
+ * desk, never the model, picks the action and section; the model only runs it.
1646
+ */
1647
+ function driveStep(desk: Desk, drive: Drive): DriveDecision {
1648
+ if (!desk.present)
1649
+ return { kind: "stop", reason: "There is no WTF-P project here yet. Start one with new-paper, or map-project for an existing manuscript; advance continues a project, it never starts one." };
1650
+ const next = nextAction(desk);
1651
+ if (next.gate) {
1652
+ if (drive.asked.includes(next.gate)) return { kind: "stop", reason: `${next.gate} is still waiting on you. ${next.reason}` };
1653
+ return { kind: "gate", checkpoint: next.gate, reason: next.reason };
1654
+ }
1655
+ if (!next.action || next.action === "check-todos") return { kind: "stop", reason: next.reason };
1656
+ if (!DRIVEN.has(next.action))
1657
+ return { kind: "stop", reason: `${next.reason} The next action, ${next.command ?? next.action}, starts or reshapes the project, so it is yours to run.` };
1658
+ if (next.command === null) return { kind: "stop", reason: next.reason };
1659
+ if (!GUARD.actions[next.action]) return { kind: "stop", reason: `${next.action} is not available on this host, so the desk cannot arm it.` };
1660
+ if (drive.steps.length >= MAX_DRIVE_STEPS)
1661
+ return { kind: "stop", reason: `This run took ${MAX_DRIVE_STEPS} steps, its limit. Run advance again to continue from ${next.command}.` };
1662
+ const section = next.section ?? null;
1663
+ const fingerprint = driveFingerprint(desk);
1664
+ const last = drive.steps[drive.steps.length - 1];
1665
+ if (last && last.action === next.action && last.section === section && last.fingerprint === fingerprint) {
1666
+ // Live, review-section reported findings and skipped its review record; one hand-back names what to record.
1667
+ const creates = (GUARD.actions[next.action]?.produces ?? []).filter((output) => output.mode === "create").map((output) => output.uri.replace("{section}", section ?? "{section}"));
1668
+ if (!last.finish && creates.length > 0)
1669
+ return {
1670
+ kind: "step",
1671
+ action: next.action,
1672
+ section,
1673
+ prompt: `ai.iowarp.clio/prompts/wtfp/${next.action}.md`,
1674
+ reason: `Continue ${next.command}; it has not failed. It recorded nothing the next step depends on, so record its outputs for what it found, whatever the outcome (${creates.join(", ")}), then call extension_wtfp__next_step. Do not repeat its work.`,
1675
+ finish: true,
1676
+ };
1677
+ return { kind: "stop", reason: `${next.command} ran and changed nothing the next step depends on, so the desk stops instead of repeating it. ${next.reason}` };
1678
+ }
1679
+ return { kind: "step", action: next.action, section, prompt: `ai.iowarp.clio/prompts/wtfp/${next.action}.md`, reason: next.reason };
1680
+ }
1681
+
1682
+ /**
1683
+ * Every next_step result ends with this rule, so a turn Clio compacted after
1684
+ * dropping the advance prompt can still continue from the last result alone.
1685
+ */
1686
+ const DRIVER_RULE =
1687
+ "Driver rule for this /wtfp:advance run: the desk, not you, picks every step, so finish the step it armed and call extension_wtfp__next_step with after naming that step (\"start\" for the first call), call extension_wtfp__gate with the checkpoint it names and then extension_wtfp__next_step, and on a stop, a failed step or a refused call report the steps taken and end the turn without choosing another action.";
1688
+
1689
+ /** Where a step's prompt lives, stated so it survives the loss of the advance prompt's resolved plugin root. */
1690
+ function stepPrompt(prompt: string): string {
1691
+ return `<plugin root>/${prompt}, where <plugin root> is the WTF-P plugin root (two directories above the base_dir of the loaded wtfp-manage-project skill; the prompt's \${pluginRoot} paths mean that root)`;
1692
+ }
1693
+
1694
+ /** The arming of an advance run between steps: nothing may be written until the desk arms a step. */
1695
+ function idleArm(workspace: string): Armed {
1696
+ return { action: "advance", produces: [], section: null, workspace };
1697
+ }
1698
+
1699
+ function meter(words: number, target: number, cells = 8): string {
1700
+ if (target <= 0) return "";
1701
+ const filled = Math.max(0, Math.min(cells, Math.round((words / target) * cells)));
1702
+ return `${"▰".repeat(filled)}${"▱".repeat(cells - filled)}`;
1703
+ }
1704
+
1705
+ /** Within 15 percent of the target, by the same count the meter draws. */
1706
+ function tolerance(words: number, target: number): ViewTone {
1707
+ if (target <= 0 || words === 0) return "muted";
1708
+ const delta = Math.abs(words - target) / target;
1709
+ return delta <= 0.15 ? "positive" : words > target ? "warning" : "neutral";
1710
+ }
1711
+
1712
+ function stageStrip(section: SectionRow): string {
1713
+ const active = (stage: keyof SectionRow["stages"]): boolean =>
1714
+ (stage === "discuss" && section.status === "researching") ||
1715
+ (stage === "write" && section.status === "writing") ||
1716
+ (stage === "review" && section.status === "reviewing");
1717
+ const mark = (stage: keyof SectionRow["stages"], letter: string): string =>
1718
+ `${letter}${section.stages[stage] && !active(stage) ? "✓" : active(stage) ? "▸" : "·"}`;
1719
+ return `${mark("discuss", "D")} ${mark("plan", "P")} ${mark("write", "W")} ${mark("review", "R")}`;
1720
+ }
1721
+
1722
+ function daysLeft(deadline: string | null): string | null {
1723
+ if (!deadline) return null;
1724
+ const due = Date.parse(`${deadline}T23:59:59Z`);
1725
+ if (Number.isNaN(due)) return null;
1726
+ const days = Math.ceil((due - Date.now()) / 86_400_000);
1727
+ return days < 0 ? `${-days} days past ${deadline}` : days === 0 ? `due today (${deadline})` : `${days} days to ${deadline}`;
1728
+ }
1729
+
1730
+ function totalWords(desk: Desk): number {
456
1731
  return desk.sections.reduce((sum, section) => sum + section.words, 0);
457
1732
  }
458
1733
 
@@ -510,6 +1785,27 @@ function header(desk: Desk): View {
510
1785
  };
511
1786
  }
512
1787
 
1788
+ function planBadge(section: SectionRow): { text: string; tone: ViewTone } | null {
1789
+ switch (section.plan.state) {
1790
+ case "approved":
1791
+ return { text: "plan ✓", tone: "positive" };
1792
+ case "policy":
1793
+ return { text: "plan", tone: "info" };
1794
+ case "changed":
1795
+ return { text: "plan changed", tone: "warning" };
1796
+ case "declined":
1797
+ return { text: "plan declined", tone: "warning" };
1798
+ case "unconfirmed":
1799
+ return { text: "plan unconfirmed", tone: "warning" };
1800
+ case "awaiting":
1801
+ return section.status === "not-started" ? null : { text: "plan awaits you", tone: "warning" };
1802
+ case "missing":
1803
+ return { text: "plan missing", tone: "error" };
1804
+ default:
1805
+ return null;
1806
+ }
1807
+ }
1808
+
513
1809
  function board(desk: Desk): View {
514
1810
  if (desk.sections.length === 0)
515
1811
  return { t: "text", text: `No outline yet. ${nextAction(desk).command ?? ""}`.trim(), tone: "muted" };
@@ -523,35 +1819,39 @@ function board(desk: Desk): View {
523
1819
  return {
524
1820
  title: `Wave ${wave} · ${done}/${cards.length}`,
525
1821
  tone: done === cards.length ? "positive" : "info",
526
- cards: cards.slice(0, 60).map((section) => ({
527
- key: section.id,
528
- title: section.title,
529
- detail: [
530
- stageStrip(section),
531
- section.target > 0 ? `${meter(section.words, section.target)} ${section.words}/${section.target}w` : `${section.words}w`,
532
- section.claims.total > 0
533
- ? `${section.claims.verified}/${section.claims.total} claims${section.claims.unsupported > 0 ? `, ${section.claims.unsupported} unsupported` : ""}`
534
- : "",
535
- ]
536
- .filter(Boolean)
537
- .join(" "),
538
- badges: [
539
- {
540
- text: section.status,
541
- tone: (section.status === "complete"
542
- ? "positive"
543
- : section.status === "blocked"
544
- ? "error"
545
- : section.status === "not-started"
546
- ? "muted"
547
- : "info") as ViewTone,
548
- },
549
- ...(section.gates.length > 0 ? [{ text: `GATE ×${section.gates.length}`, tone: "warning" as ViewTone }] : []),
550
- ...(section.words > 0 && section.target > 0
551
- ? [{ text: `${Math.round((section.words / section.target) * 100)}%`, tone: tolerance(section.words, section.target) }]
552
- : []),
553
- ],
554
- })),
1822
+ cards: cards.slice(0, 60).map((section) => {
1823
+ const plan = planBadge(section);
1824
+ return {
1825
+ key: section.id,
1826
+ title: section.title,
1827
+ detail: [
1828
+ stageStrip(section),
1829
+ section.target > 0 ? `${meter(section.words, section.target)} ${section.words}/${section.target}w` : `${section.words}w`,
1830
+ section.claims.total > 0
1831
+ ? `${section.claims.verified}/${section.claims.total} claims${section.claims.unsupported > 0 ? `, ${section.claims.unsupported} unsupported` : ""}`
1832
+ : "",
1833
+ ]
1834
+ .filter(Boolean)
1835
+ .join(" "),
1836
+ badges: [
1837
+ {
1838
+ text: section.status,
1839
+ tone: (section.status === "complete"
1840
+ ? "positive"
1841
+ : section.status === "blocked"
1842
+ ? "error"
1843
+ : section.status === "not-started"
1844
+ ? "muted"
1845
+ : "info") as ViewTone,
1846
+ },
1847
+ ...(plan ? [plan] : []),
1848
+ ...(section.gates.length > 0 ? [{ text: `GATE ×${section.gates.length}`, tone: "warning" as ViewTone }] : []),
1849
+ ...(section.words > 0 && section.target > 0
1850
+ ? [{ text: `${Math.round((section.words / section.target) * 100)}%`, tone: tolerance(section.words, section.target) }]
1851
+ : []),
1852
+ ],
1853
+ };
1854
+ }),
555
1855
  };
556
1856
  }),
557
1857
  };
@@ -564,12 +1864,12 @@ function agentLabel(agentId: string): string {
564
1864
 
565
1865
  function islands(desk: Desk, running: Record<string, { agentId: string; at: number }>): ExtensionIsland[] {
566
1866
  const out: ExtensionIsland[] = [];
567
- const gate = desk.checkpoints.find((checkpoint) => checkpoint.status === "pending" && checkpoint.blocking);
1867
+ const gate = openGates(desk)[0];
568
1868
  if (gate)
569
1869
  out.push({
570
1870
  key: "gate",
571
1871
  title: "⚑ Gate",
572
- meta: gate.kind,
1872
+ meta: gate.trust === "pending" ? gate.kind : "unconfirmed",
573
1873
  tone: "warning",
574
1874
  view: {
575
1875
  t: "box",
@@ -589,7 +1889,14 @@ function islands(desk: Desk, running: Record<string, { agentId: string; at: numb
589
1889
  } as View,
590
1890
  ]
591
1891
  : []),
592
- { t: "text", text: "Leader c answers it; only your answer resolves it.", tone: "muted" },
1892
+ {
1893
+ t: "text",
1894
+ text:
1895
+ gate.trust === "pending"
1896
+ ? "Leader c answers it; only your answer resolves it."
1897
+ : "Recorded as answered, but not by you at this desk. Leader c confirms it.",
1898
+ tone: "muted",
1899
+ },
593
1900
  ],
594
1901
  },
595
1902
  });
@@ -609,7 +1916,7 @@ function islands(desk: Desk, running: Record<string, { agentId: string; at: numb
609
1916
  { label: "provisional", value: String(provisional), tone: provisional > 0 ? "warning" : "muted" },
610
1917
  ...(lost > 0 ? [{ label: "unavailable or retracted", value: String(lost), tone: "error" as ViewTone }] : []),
611
1918
  { label: "evidence items", value: String(desk.evidence) },
612
- { label: "claims without evidence", value: String(unsupported), tone: unsupported > 0 ? "warning" : "positive" },
1919
+ { label: "required claims without support", value: String(unsupported), tone: unsupported > 0 ? "warning" : "positive" },
613
1920
  ],
614
1921
  },
615
1922
  });
@@ -704,7 +2011,7 @@ async function running(ctx: ExtensionContextV2): Promise<Running> {
704
2011
  }
705
2012
 
706
2013
  async function deskFor(ctx: ExtensionContextV2): Promise<Desk> {
707
- const desk = loadDesk(ctx.snapshot.workspace);
2014
+ const desk = loadDesk(ctx.snapshot.workspace, await storedKey(ctx, false));
708
2015
  desk.invalid = (await ctx.state.get<Desk["invalid"]>("invalid")).value ?? [];
709
2016
  desk.served = ctx.snapshot.plugin ?? null;
710
2017
  return desk;
@@ -721,7 +2028,7 @@ async function picture(
721
2028
  status: current.present
722
2029
  ? {
723
2030
  text: `WTF-P · ${current.phase} · ${totalWords(current).toLocaleString("en-US")}/${current.targetWords.toLocaleString("en-US")}w`,
724
- tone: current.checkpoints.some((checkpoint) => checkpoint.status === "pending" && checkpoint.blocking) ? "warning" : "neutral",
2031
+ tone: openGates(current).length > 0 || current.journal ? "warning" : "neutral",
725
2032
  }
726
2033
  : null,
727
2034
  band: band(current),
@@ -762,35 +2069,105 @@ async function revalidate(ctx: ExtensionContextV2, files: string[]): Promise<Vie
762
2069
  // --- gates -------------------------------------------------------------------
763
2070
 
764
2071
  const KEEP = "__keep";
2072
+ const RESOLVE = "__resolve";
2073
+ const WAIVE = "__waive";
2074
+
2075
+ /** What the author was shown, kept until the answer arrives so a changed question cannot take an old answer. */
2076
+ interface Asked {
2077
+ checkpoint: string;
2078
+ workspace: string;
2079
+ project: string | null;
2080
+ content_sha256: string;
2081
+ options: string[];
2082
+ artifact: { uri: string; sha256: string } | null;
2083
+ asked_at: string;
2084
+ confirming: boolean;
2085
+ }
765
2086
 
766
- function pendingGates(desk: Desk, skip: readonly string[]): Checkpoint[] {
2087
+ /** The gates that want the author: pending ones, and blocking answers the desk never saw. */
2088
+ function askable(desk: Desk, skip: readonly string[]): Checkpoint[] {
767
2089
  return desk.checkpoints.filter(
768
- (checkpoint) => checkpoint.status === "pending" && checkpoint.kind !== "state-snapshot" && !skip.includes(checkpoint.id),
2090
+ (checkpoint) =>
2091
+ checkpoint.kind !== "state-snapshot" &&
2092
+ !skip.includes(checkpoint.id) &&
2093
+ (checkpoint.status === "pending" || (checkpoint.blocking && unconfirmed(checkpoint))),
769
2094
  );
770
2095
  }
771
2096
 
772
- function gateStep(checkpoint: Checkpoint): InterviewStep {
773
- const choices =
774
- checkpoint.options && checkpoint.options.length > 0
775
- ? checkpoint.options.map((option) => ({
776
- value: option.id,
777
- label: option.label,
778
- ...(option.implication ? { detail: option.implication } : {}),
779
- }))
780
- : [
781
- { value: "__resolve", label: checkpoint.kind === "human-verify" ? "Verified" : "Done", detail: "Mark it resolved by you." },
782
- { value: "__waive", label: "Waive it", detail: "Record that you chose to skip it." },
783
- ];
2097
+ function planGate(checkpoint: Checkpoint): boolean {
2098
+ return new RegExp(`^project://sections/${IDENTIFIER}/plans/${IDENTIFIER}$`, "u").test(checkpoint.scope_uri);
2099
+ }
2100
+
2101
+ /** verify-work's closing question: an acceptance checkpoint scoped to its validation. */
2102
+ function acceptanceGate(checkpoint: Checkpoint): boolean {
2103
+ return new RegExp(`^project://validations/${IDENTIFIER}$`, "u").test(checkpoint.scope_uri) && (checkpoint.options ?? []).some((option) => option.id === ACCEPT);
2104
+ }
2105
+
2106
+ /**
2107
+ * The words the author sees for an option. On a plan gate the desk owns them:
2108
+ * `approve` is what authorizes drafting, so it always reads as approval and
2109
+ * nothing else does, whatever the checkpoint's own labels say.
2110
+ */
2111
+ function shown(checkpoint: Checkpoint, option: { id: string; label: string; implication?: string }): { label: string; detail?: string } {
2112
+ if (planGate(checkpoint)) {
2113
+ if (option.id === APPROVE) return { label: "Approve this plan as shown", detail: "Drafting may start from exactly these plan bytes; any later change asks you again." };
2114
+ if (/approv/iu.test(option.label)) return { label: `Do not draft from this plan yet (${option.id})`, detail: "Any answer but approval leaves the plan unapproved." };
2115
+ }
2116
+ // Only `accept` completes a section, so only it reads as acceptance.
2117
+ if (acceptanceGate(checkpoint)) {
2118
+ if (option.id === ACCEPT) return { label: "Accept this section as written", detail: "It is marked complete; a later change needs review and your acceptance again." };
2119
+ if (option.id === REVISE) return { label: "Send it back for revision", detail: "The next step plans a revision for you to approve." };
2120
+ if (/accept/iu.test(option.label)) return { label: `Do not accept it yet (${option.id})`, detail: "Any answer but accept leaves the section unaccepted." };
2121
+ }
2122
+ return { label: option.label, ...(option.implication ? { detail: option.implication } : {}) };
2123
+ }
2124
+
2125
+ function choices(checkpoint: Checkpoint): Array<{ value: string; label: string; detail?: string }> {
2126
+ return checkpoint.options && checkpoint.options.length > 0
2127
+ ? checkpoint.options.map((option) => ({ value: option.id, ...shown(checkpoint, option) }))
2128
+ : [
2129
+ { value: RESOLVE, label: checkpoint.kind === "human-verify" ? "Verified" : "Done", detail: "Mark it resolved by you." },
2130
+ { value: WAIVE, label: "Waive it", detail: "Record that you chose to skip it." },
2131
+ ];
2132
+ }
2133
+
2134
+ function subjectOf(workspace: string, desk: Desk, checkpoint: Checkpoint): { uri: string; sha256: string } | null {
2135
+ const file = artifactFile(workspace, checkpoint.scope_uri, desk.outputFormat);
2136
+ const bytes = file === null ? null : readBytes(workspace, file);
2137
+ return bytes === null ? null : { uri: checkpoint.scope_uri, sha256: sha256(bytes) };
2138
+ }
2139
+
2140
+ async function ask(ctx: ExtensionContextV2, desk: Desk, checkpoint: Checkpoint, hint?: string): Promise<InterviewStep> {
2141
+ const nonce = randomBytes(6).toString("hex");
2142
+ const artifact = subjectOf(ctx.snapshot.workspace, desk, checkpoint);
2143
+ const offered = [...choices(checkpoint), { value: KEEP, label: "Keep it pending", detail: "Answer later; its writes stay blocked." }];
2144
+ const confirming = checkpoint.status !== "pending";
2145
+ await ctx.state.set(`ask:${nonce}`, {
2146
+ checkpoint: checkpoint.id,
2147
+ workspace: ctx.snapshot.workspace,
2148
+ project: desk.projectId,
2149
+ content_sha256: checkpointDigest(checkpoint),
2150
+ options: offered.map((option) => option.value),
2151
+ artifact,
2152
+ asked_at: timestamp(),
2153
+ confirming,
2154
+ } satisfies Asked);
2155
+ const recorded = checkpoint.resolution?.selected_option ?? (checkpoint.status === "waived" ? "waived" : "done");
784
2156
  return {
785
- key: checkpoint.id,
786
- title: checkpoint.blocking ? "Blocking gate" : "Pending task",
2157
+ key: `gate.${nonce}`,
2158
+ title: confirming ? "Confirm a recorded answer" : checkpoint.blocking ? "Blocking gate" : "Pending task",
787
2159
  // The question carries the request; the intro adds only what it cannot.
788
2160
  intro: {
789
2161
  t: "box",
790
2162
  dir: "col",
791
2163
  children: [
2164
+ ...(hint ? [{ t: "text", text: hint, tone: "warning", wrap: "wrap" } as View] : []),
792
2165
  ...(checkpoint.context ? [{ t: "text", text: checkpoint.context, wrap: "wrap" } as View] : []),
793
- { t: "text", text: `${checkpoint.kind} · ${checkpoint.scope_uri.replace(/^project:\/\//u, "")}`, tone: "muted" },
2166
+ ...(confirming
2167
+ ? [{ t: "text", text: `Recorded as "${recorded}" by the author, but this desk did not see that answer. Confirm it or choose again.`, tone: "warning", wrap: "wrap" } as View]
2168
+ : []),
2169
+ { t: "text", text: `${checkpoint.kind} · ${checkpoint.scope_uri.replace(/^project:\/\//u, "")} · ${checkpoint.id}`, tone: "muted" },
2170
+ ...(artifact ? [{ t: "text", text: `You are answering about ${artifact.uri.replace(/^project:\/\//u, "")} as it is now (sha256 ${artifact.sha256.slice(0, 12)}).`, tone: "muted", wrap: "wrap" } as View] : []),
794
2171
  ],
795
2172
  },
796
2173
  questions: [
@@ -798,149 +2175,510 @@ function gateStep(checkpoint: Checkpoint): InterviewStep {
798
2175
  id: "choice",
799
2176
  label: checkpoint.request.length > 120 ? `${checkpoint.request.slice(0, 117)}...` : checkpoint.request,
800
2177
  kind: "single",
801
- options: [...choices, { value: KEEP, label: "Keep it pending", detail: "Answer later; its writes stay blocked." }],
2178
+ options: offered,
802
2179
  },
803
2180
  ],
804
2181
  };
805
2182
  }
806
2183
 
807
- function writeRecord(workspace: string, relative: string, value: Json): void {
808
- const errors = validateRecord(value);
809
- if (errors.length > 0) throw new Error(`${relative} would not validate: ${errors[0]}`);
810
- const file = path.resolve(workspace, relative);
811
- if (!inside(path.join(workspace, ".planning"), file)) throw new Error(`refusing to write outside .planning: ${relative}`);
812
- mkdirSync(path.dirname(file), { recursive: true });
813
- const staging = `${file}.${randomUUID()}.partial`;
814
- try {
815
- writeFileSync(staging, `${JSON.stringify(value, null, 2)}\n`, { encoding: "utf8", flag: "wx" });
816
- renameSync(staging, file);
817
- } finally {
818
- if (existsSync(staging)) unlinkSync(staging);
819
- }
820
- const back = JSON.parse(readFileSync(file, "utf8")) as unknown;
821
- if (JSON.stringify(back) !== JSON.stringify(value)) throw new Error(`readback of ${relative} differs from what was written`);
822
- }
823
-
824
- /** The one place an author's answer is recorded: only from the interview the operator answered. */
825
- function resolveGate(workspace: string, checkpoint: Checkpoint, choice: string): string {
826
- const now = new Date().toISOString().replace(/\.\d{3}Z$/u, "Z");
827
- const option = checkpoint.options?.find((entry) => entry.id === choice);
828
- const waived = choice === "__waive";
829
- const { file, ...stored } = checkpoint;
830
- const record: Json = {
831
- ...stored,
832
- status: waived ? "waived" : "resolved",
833
- resolution: {
834
- resolved_by: "author",
835
- ...(option ? { selected_option: option.id } : {}),
836
- summary: option
837
- ? `The author chose "${option.label}" at the Clio WTF-P desk.`
838
- : waived
839
- ? "The author waived this gate at the Clio WTF-P desk."
840
- : "The author marked this done at the Clio WTF-P desk.",
841
- resolved_at: now,
842
- },
2184
+ function interactionId(): string {
2185
+ return `interaction-${timestamp().replace(/[^0-9]/gu, "")}-${randomBytes(4).toString("hex")}`;
2186
+ }
2187
+
2188
+ type AnswerResult = { kind: "recorded" | "kept" | "stale" | "refused"; text: string; checkpoint?: string };
2189
+
2190
+ /**
2191
+ * Records one gate answer. The answer counts only if it names an option the
2192
+ * author was offered for this exact checkpoint, project and subject, and only
2193
+ * once: the binding is consumed before anything is written.
2194
+ */
2195
+ async function answer(ctx: ExtensionContextV2, stepKey: string, picked: unknown, note: string | null = null): Promise<AnswerResult> {
2196
+ const workspace = ctx.snapshot.workspace;
2197
+ const nonce = /^gate\.([a-f0-9]{12})$/u.exec(stepKey)?.[1];
2198
+ const asked = nonce ? (await ctx.state.get<Asked>(`ask:${nonce}`)).value : undefined;
2199
+ if (!nonce || !asked) return { kind: "refused", text: "That answer matches no open question; nothing was recorded." };
2200
+ await ctx.state.delete(`ask:${nonce}`);
2201
+ const key = await storedKey(ctx, true);
2202
+ if (key === null) return { kind: "refused", text: "The desk could not establish its seal key; nothing was recorded." };
2203
+ const desk = loadDesk(workspace, key);
2204
+ const checkpoint = desk.checkpoints.find((entry) => entry.id === asked.checkpoint);
2205
+ if (asked.workspace !== workspace || asked.project !== desk.projectId)
2206
+ return { kind: "refused", text: "That answer was given for another project; nothing was recorded." };
2207
+ if (typeof picked !== "string" || !asked.options.includes(picked))
2208
+ return { kind: "refused", text: "That answer is not one of the options offered; nothing was recorded." };
2209
+ if (!checkpoint) return { kind: "refused", text: `${asked.checkpoint} no longer exists; nothing was recorded.` };
2210
+ const stillAskable = checkpoint.status === "pending" || (asked.confirming && checkpoint.blocking && unconfirmed(checkpoint));
2211
+ if (!stillAskable) return { kind: "refused", text: `${checkpoint.id} is already ${checkpoint.status}; nothing was recorded.`, checkpoint: checkpoint.id };
2212
+ const now = timestamp();
2213
+ const artifact = subjectOf(workspace, desk, checkpoint);
2214
+ const base: Json = {
2215
+ schema: "wtfp.project.interaction/v1",
2216
+ id: interactionId(),
2217
+ project_id: desk.projectId,
2218
+ kind: "checkpoint-answer",
2219
+ subject_uri: `project://checkpoints/${checkpoint.id}`,
2220
+ channel: "attested-interview",
2221
+ presented: { content_sha256: asked.content_sha256, options: asked.options.filter((option) => option !== KEEP), ...(asked.artifact ? { artifact: asked.artifact } : {}) },
2222
+ asked_at: asked.asked_at,
2223
+ answered_at: now,
843
2224
  };
844
- writeRecord(workspace, file, record);
845
- const state = readRecord(workspace, ".planning/state.json");
846
- const uri = `project://checkpoints/${checkpoint.id}`;
847
- if (state && Array.isArray(state.active_checkpoint_uris) && state.active_checkpoint_uris.includes(uri)) {
848
- writeRecord(workspace, ".planning/state.json", {
849
- ...state,
850
- revision: typeof state.revision === "number" ? state.revision + 1 : 1,
851
- active_checkpoint_uris: state.active_checkpoint_uris.filter((entry) => entry !== uri),
852
- updated_at: now,
2225
+ const stale = checkpointDigest(checkpoint) !== asked.content_sha256 || (artifact?.sha256 ?? null) !== (asked.artifact?.sha256 ?? null);
2226
+ const option = checkpoint.options?.find((entry) => entry.id === picked);
2227
+ const interaction = sealed(
2228
+ {
2229
+ ...base,
2230
+ outcome: stale ? "discarded-stale" : picked === KEEP ? "kept-pending" : picked === WAIVE ? "waived" : option ? "selected" : "done",
2231
+ ...(option && !stale ? { selected_option: option.id } : {}),
2232
+ },
2233
+ key,
2234
+ );
2235
+ const writes: Array<{ input: RecordWrite }> = [{ input: { uri: `project://interactions/${String(interaction.id)}`, record: interaction } }];
2236
+ let linkedIn: string | null = null;
2237
+ if (!stale && picked !== KEEP) {
2238
+ const { file: _file, trust: _trust, answer: _answer, ...stored } = checkpoint;
2239
+ writes.push({
2240
+ input: {
2241
+ uri: `project://checkpoints/${checkpoint.id}`,
2242
+ expect_sha256: sha256(readBytes(workspace, checkpoint.file) ?? ""),
2243
+ record: {
2244
+ ...stored,
2245
+ status: picked === WAIVE ? "waived" : "resolved",
2246
+ resolution: {
2247
+ resolved_by: "author",
2248
+ ...(option ? { selected_option: option.id } : {}),
2249
+ summary: `${
2250
+ option
2251
+ ? `The author chose "${shown(checkpoint, option).label}" at the Clio WTF-P desk.`
2252
+ : picked === WAIVE
2253
+ ? "The author waived this gate at the Clio WTF-P desk."
2254
+ : "The author marked this done at the Clio WTF-P desk."
2255
+ }${note ? `${NOTE_LEAD}${note}` : ""}`,
2256
+ resolved_at: now,
2257
+ },
2258
+ },
2259
+ },
853
2260
  });
2261
+ const state = readRecord(workspace, ".planning/state.json");
2262
+ const uri = `project://checkpoints/${checkpoint.id}`;
2263
+ if (state && Array.isArray(state.active_checkpoint_uris) && state.active_checkpoint_uris.includes(uri))
2264
+ writes.push({
2265
+ input: {
2266
+ uri: "project://state",
2267
+ expect_revision: typeof state.revision === "number" ? state.revision : 0,
2268
+ record: { ...state, active_checkpoint_uris: (state.active_checkpoint_uris as string[]).filter((entry) => entry !== uri) },
2269
+ },
2270
+ });
2271
+ // The author's approval links the plan in the same commit: live, the model asked the desk for its next
2272
+ // step before linking, and the approved plan sat unlinked while the driver planned again.
2273
+ const planned = option?.id === APPROVE && planGate(checkpoint) ? /^project:\/\/sections\/([^/]+)\/plans\//u.exec(checkpoint.scope_uri)?.[1] : undefined;
2274
+ const sectionFile = planned ? `.planning/sections/${planned}/section.json` : null;
2275
+ const section = sectionFile ? readRecord(workspace, sectionFile) : null;
2276
+ if (planned && sectionFile && section) {
2277
+ const artifacts = isObject(section.artifacts) ? section.artifacts : {};
2278
+ const plans = Array.isArray(artifacts.plans) ? (artifacts.plans as unknown[]) : [];
2279
+ if (plans[plans.length - 1] !== checkpoint.scope_uri) {
2280
+ linkedIn = `project://sections/${planned}`;
2281
+ const status = text(section.status, "not-started");
2282
+ writes.push({
2283
+ input: {
2284
+ uri: `project://sections/${planned}`,
2285
+ expect_sha256: sha256(readBytes(workspace, sectionFile) ?? ""),
2286
+ record: {
2287
+ ...section,
2288
+ status: status === "not-started" ? "planned" : status,
2289
+ artifacts: { ...artifacts, plans: [...plans.filter((entry) => entry !== checkpoint.scope_uri), checkpoint.scope_uri] },
2290
+ },
2291
+ },
2292
+ });
2293
+ }
2294
+ }
854
2295
  }
855
- return option ? `${checkpoint.id}: ${option.label}` : `${checkpoint.id}: ${waived ? "waived" : "done"}`;
2296
+ withLock(workspace, () => {
2297
+ recover(workspace);
2298
+ commit(
2299
+ workspace,
2300
+ writes.map((entry) => prepare(workspace, entry.input, "desk", null).write),
2301
+ );
2302
+ });
2303
+ if (stale)
2304
+ return {
2305
+ kind: "stale",
2306
+ text: `${checkpoint.id} or what it asks about changed while you were answering, so that answer was set aside; it is asked again as it is now.`,
2307
+ checkpoint: checkpoint.id,
2308
+ };
2309
+ if (picked === KEEP) return { kind: "kept", text: `${checkpoint.id}: kept pending`, checkpoint: checkpoint.id };
2310
+ return {
2311
+ kind: "recorded",
2312
+ text: `${option ? `${checkpoint.id}: ${shown(checkpoint, option).label}` : `${checkpoint.id}: ${picked === WAIVE ? "waived" : "done"}`}${
2313
+ linkedIn ? `. The desk linked ${checkpoint.scope_uri} in ${linkedIn} with this answer; do not link it again` : ""
2314
+ }. The desk wrote ${writes
2315
+ .slice(1)
2316
+ .map((entry) => entry.input.uri)
2317
+ .join(", ")}; read any of them again before writing it`,
2318
+ checkpoint: checkpoint.id,
2319
+ };
856
2320
  }
857
2321
 
858
2322
  async function startGates(ctx: ExtensionContextV2): Promise<ExtensionOutputV2> {
859
2323
  const desk = await deskFor(ctx);
860
- const pending = pendingGates(desk, []);
2324
+ const pending = askable(desk, []);
861
2325
  await ctx.state.set("gate-kept", []);
2326
+ await ctx.state.set("gate-recorded", []);
862
2327
  if (pending.length === 0)
863
2328
  return {
864
2329
  text: "No pending gates or author tasks.",
865
2330
  card: { t: "text", text: "✓ No pending gates or author tasks.", tone: "positive" },
866
2331
  };
867
2332
  return {
868
- text: `${pending.length} pending gate${pending.length === 1 ? "" : "s"}.`,
869
- interview: { id: "gate", title: "WTF-P gates", total: pending.length, step: gateStep(pending[0] as Checkpoint) },
2333
+ text: `${pending.length} gate${pending.length === 1 ? "" : "s"} want${pending.length === 1 ? "s" : ""} your answer.`,
2334
+ interview: { id: "gate", title: "WTF-P gates", total: pending.length, step: await ask(ctx, desk, pending[0] as Checkpoint) },
870
2335
  };
871
2336
  }
872
2337
 
873
- // --- runtime tools -----------------------------------------------------------
2338
+ function choiceOf(answers: Record<string, string | string[]>): unknown {
2339
+ const choice = answers.choice;
2340
+ return Array.isArray(choice) ? (choice.length === 1 ? choice[0] : undefined) : choice;
2341
+ }
874
2342
 
875
- const IDENTIFIER = "[a-z][a-z0-9]*(?:-[a-z0-9]+)*";
876
- /** The adapter mapping of project/README.md: logical URI to record type and project-relative file. */
877
- const RECORD_URIS: ReadonlyArray<{ pattern: RegExp; type: string; file: (id: string) => string }> = [
878
- { pattern: /^project:\/\/manifest$/u, type: "manifest", file: () => ".planning/project.json" },
879
- { pattern: /^project:\/\/config$/u, type: "config", file: () => ".planning/config.json" },
880
- { pattern: /^project:\/\/state$/u, type: "state", file: () => ".planning/state.json" },
881
- { pattern: /^project:\/\/decisions$/u, type: "decisions", file: () => ".planning/decisions.json" },
882
- { pattern: /^project:\/\/structure\/outline$/u, type: "outline", file: () => ".planning/structure/outline.json" },
883
- { pattern: new RegExp(`^project://sections/(${IDENTIFIER})$`, "u"), type: "section", file: (id) => `.planning/sections/${id}/section.json` },
884
- { pattern: new RegExp(`^project://sources/(${IDENTIFIER})$`, "u"), type: "source", file: (id) => `.planning/sources/${id}.json` },
885
- { pattern: new RegExp(`^project://evidence/(${IDENTIFIER})$`, "u"), type: "evidence", file: (id) => `.planning/evidence/${id}.json` },
886
- { pattern: new RegExp(`^project://checkpoints/(${IDENTIFIER})$`, "u"), type: "checkpoint", file: (id) => `.planning/checkpoints/${id}.json` },
887
- { pattern: new RegExp(`^project://validations/(${IDENTIFIER})$`, "u"), type: "validation", file: (id) => `.planning/validations/${id}.json` },
2343
+ /** The text the author attached to their chosen option, bounded; null when none. */
2344
+ function noteOf(event: { notes?: Record<string, string> }): string | null {
2345
+ const note = event.notes?.choice?.replace(/\s+/gu, " ").trim() ?? "";
2346
+ return note ? note.slice(0, NOTE_LIMIT) : null;
2347
+ }
2348
+
2349
+ const FREE_TEXT = "A typed answer names no option, so nothing was recorded. Choose an option and attach your text to it with [n] note.";
2350
+
2351
+ /**
2352
+ * A gate answered with free text instead of an option. Nothing is recorded and
2353
+ * the question's binding is spent; the text goes back with how to send it.
2354
+ */
2355
+ async function freeText(ctx: ExtensionContextV2, event: { step: string; answers: Record<string, string | string[]>; other?: Record<string, true> }): Promise<AnswerResult | null> {
2356
+ if (event.other?.choice !== true) return null;
2357
+ const nonce = /^gate\.([a-f0-9]{12})$/u.exec(event.step)?.[1];
2358
+ const asked = nonce ? (await ctx.state.get<Asked>(`ask:${nonce}`)).value : undefined;
2359
+ if (nonce) await ctx.state.delete(`ask:${nonce}`);
2360
+ const typed = String(choiceOf(event.answers) ?? "").replace(/\s+/gu, " ").trim().slice(0, NOTE_LIMIT);
2361
+ return {
2362
+ kind: "refused",
2363
+ text: `The author typed an answer instead of choosing an option, so nothing was recorded and the gate stays pending. Ask again; the author chooses an option and attaches their text with [n] note.${typed ? ` They wrote: "${typed}"` : ""}`,
2364
+ ...(asked ? { checkpoint: asked.checkpoint } : {}),
2365
+ };
2366
+ }
2367
+
2368
+ // --- confirmations of weakening record writes --------------------------------
2369
+
2370
+ interface PendingConfirm {
2371
+ write: RecordWrite;
2372
+ workspace: string;
2373
+ project: string | null;
2374
+ base_sha256: string | null;
2375
+ content_sha256: string;
2376
+ changes: string[];
2377
+ asked_at: string;
2378
+ }
2379
+
2380
+ async function confirmStep(ctx: ExtensionContextV2, write: RecordWrite, prepared: Prepared): Promise<InterviewStep> {
2381
+ const nonce = randomBytes(6).toString("hex");
2382
+ await ctx.state.set(`confirm:${nonce}`, {
2383
+ write,
2384
+ workspace: ctx.snapshot.workspace,
2385
+ project: readRecord(ctx.snapshot.workspace, ".planning/project.json")?.id as string | null,
2386
+ base_sha256: prepared.priorSha,
2387
+ content_sha256: sha256(canonical(write.record)),
2388
+ changes: prepared.confirm,
2389
+ asked_at: timestamp(),
2390
+ } satisfies PendingConfirm);
2391
+ return {
2392
+ key: `confirm.${nonce}`,
2393
+ title: "Confirm a change to your controls",
2394
+ intro: {
2395
+ t: "box",
2396
+ dir: "col",
2397
+ children: [
2398
+ { t: "text", text: `The agent wants to change ${write.uri}. This lowers what the workflow asks you or what the desk holds back:`, wrap: "wrap" },
2399
+ ...prepared.confirm.slice(0, 8).map((change) => ({ t: "text", text: ` ${change}`, tone: "warning", wrap: "wrap" }) as View),
2400
+ ],
2401
+ },
2402
+ questions: [
2403
+ {
2404
+ id: "choice",
2405
+ label: "Apply this change?",
2406
+ kind: "single",
2407
+ options: [
2408
+ { value: "approve", label: "Apply it", detail: "Write the record exactly as shown." },
2409
+ { value: "decline", label: "Keep my current settings", detail: "Nothing is written." },
2410
+ ],
2411
+ },
2412
+ ],
2413
+ };
2414
+ }
2415
+
2416
+ // --- runtime tool handlers ---------------------------------------------------
2417
+
2418
+ async function armedFor(ctx: ExtensionContextV2): Promise<Armed | null> {
2419
+ const armed = (await ctx.state.get<Armed>("armed")).value;
2420
+ if (!armed) return null;
2421
+ // Arming belongs to the workspace and turn it was set in; anything else is stale.
2422
+ if (armed.workspace !== ctx.snapshot.workspace) return null;
2423
+ return armed;
2424
+ }
2425
+
2426
+ async function recordTool(ctx: ExtensionContextV2, input: Json): Promise<{ text: string; data?: unknown; isError?: boolean; interview?: { id: string; title: string; total: number; step: InterviewStep } }> {
2427
+ const workspace = ctx.snapshot.workspace;
2428
+ const armed = await armedFor(ctx);
2429
+ // The manifest lets unknown top-level keys through so the desk, not the gateway, can say where they belong:
2430
+ // a long record whose object closed early leaves its last fields beside it.
2431
+ const stray = Object.keys(input).filter((key) => !["uri", "record", "expect_revision", "expect_sha256", "writes"].includes(key));
2432
+ let folded: string[] = [];
2433
+ if (stray.length > 0) {
2434
+ const record = input.record !== null && typeof input.record === "object" && !Array.isArray(input.record) ? (input.record as Json) : null;
2435
+ const fields = record ? recordFields(text(record.schema)) : new Set<string>();
2436
+ // Fields the record's own schema defines and the record lacks are folded in; validation still judges the result.
2437
+ if (!record || stray.some((key) => !fields.has(key) || key in record))
2438
+ throw new Error(`${stray.join(", ")} ${stray.length === 1 ? "is not a record tool argument" : "are not record tool arguments"}; if ${stray.length === 1 ? "it is a field" : "they are fields"} of the record, put ${stray.length === 1 ? "it" : "them"} inside record and send the call again`);
2439
+ input = { ...input, record: { ...record, ...Object.fromEntries(stray.map((key) => [key, input[key]])) } };
2440
+ for (const key of stray) delete input[key];
2441
+ folded = stray;
2442
+ }
2443
+ const writes = normalizeWrites(input);
2444
+ const uris = writes.map((write) => write.uri);
2445
+ if (new Set(uris).size !== uris.length) throw new Error("each record may appear once in writes");
2446
+ const outcome = withLock(workspace, (): { recovered: string | null; done: PendingWrite[]; confirm: Prepared | null } => {
2447
+ const recovered = recover(workspace);
2448
+ const prepared = writes.map((write) => prepare(workspace, write, "agent", armed));
2449
+ const weakening = prepared.filter((entry) => entry.confirm.length > 0);
2450
+ if (weakening.length > 0) {
2451
+ if (prepared.length > 1) throw new Error(`${weakening[0]?.write.uri} weakens the author's controls; write it alone so the author can confirm it`);
2452
+ return { recovered, done: [], confirm: prepared[0] as Prepared };
2453
+ }
2454
+ commit(workspace, prepared.map((entry) => entry.write));
2455
+ return { recovered, done: prepared.map((entry) => entry.write), confirm: null };
2456
+ });
2457
+ const { recovered, done } = outcome;
2458
+ if (outcome.confirm) {
2459
+ const write = writes[0] as RecordWrite;
2460
+ return {
2461
+ text: `${write.uri} weakens the author's controls; asking the author.`,
2462
+ interview: { id: "confirm-write", title: "WTF-P · your controls", total: 1, step: await confirmStep(ctx, write, outcome.confirm) },
2463
+ };
2464
+ }
2465
+ return {
2466
+ text: [
2467
+ ...(recovered ? [recovered] : []),
2468
+ ...(folded.length > 0 ? [`${folded.join(", ")} arrived beside record and were moved inside it; send record fields inside record.`] : []),
2469
+ ...done.map((write) => `Wrote ${write.uri}${write.revision === null ? "" : ` at revision ${write.revision}`}; it validated and read back (sha256 ${write.sha256}).`),
2470
+ ...(done.length > 1 ? ["They committed together."] : []),
2471
+ ].join(" "),
2472
+ data:
2473
+ done.length === 1
2474
+ ? { uri: done[0]?.uri, file: done[0]?.file, revision: done[0]?.revision, sha256: done[0]?.sha256 }
2475
+ : { writes: done.map((write) => ({ uri: write.uri, file: write.file, revision: write.revision, sha256: write.sha256 })) },
2476
+ };
2477
+ }
2478
+
2479
+ /**
2480
+ * Authored artifacts keep their own format and are read and written with
2481
+ * Clio's file tools; a refusal names the conventional file so the model does
2482
+ * not search the workspace for it.
2483
+ */
2484
+ const ARTIFACT_URIS: ReadonlyArray<{ pattern: RegExp; file: (match: RegExpExecArray) => string }> = [
2485
+ { pattern: new RegExp(`^project://sections/(${IDENTIFIER})/(context|research|summary|handoff)$`, "u"), file: (m) => `.planning/sections/${m[1]}/${m[2]}.md` },
2486
+ { pattern: new RegExp(`^project://sections/(${IDENTIFIER})/(plans|reviews)/(${IDENTIFIER})$`, "u"), file: (m) => `.planning/sections/${m[1]}/${m[2]}/${m[3]}.md` },
2487
+ { pattern: /^project:\/\/paper\/([^\s]+)$/u, file: (m) => `paper/${m[1]}` },
888
2488
  ];
889
- const REVISIONED = new Set(["state", "outline", "decisions"]);
890
- const STAMPED = new Set(["state", "outline", "decisions", "manifest", "section"]);
891
2489
 
892
- function timestamp(): string {
893
- return new Date().toISOString().replace(/\.\d{3}Z$/u, "Z");
2490
+ function notARecord(uri: string): string {
2491
+ for (const artifact of ARTIFACT_URIS) {
2492
+ const match = artifact.pattern.exec(uri);
2493
+ if (match) return `${uri} is an authored artifact, not a JSON record; read or write ${artifact.file(match)} with the file tools`;
2494
+ }
2495
+ const family = /^project:\/\/(sections|sources|evidence|checkpoints|validations)\/([^/]+)$/u.exec(uri);
2496
+ if (family && !new RegExp(`^${IDENTIFIER}$`, "u").test(family[2] ?? ""))
2497
+ return `${uri} has an invalid id; record ids are lowercase letters and digits joined by single hyphens, such as ${(family[2] ?? "").toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-+|-+$/gu, "") || "outline-gate"}`;
2498
+ return `${uri} is not a logical record URI this adapter maps`;
894
2499
  }
895
2500
 
2501
+ /** How much record JSON one family read returns before it names the rest by id. */
2502
+ const FAMILY_LIMIT = 48 * 1024;
2503
+
896
2504
  /**
897
- * The one writer of a portable record: the type and identifier must match the
898
- * URI, the revision the caller read must still be current, and the record must
899
- * validate before it replaces the file. The caller never chooses a revision or
900
- * a timestamp; both follow from the write.
2505
+ * Every record of one family, such as `project://sources`, in one call: each
2506
+ * as a single read returns it, until the family outgrows FAMILY_LIMIT; the
2507
+ * rest are named so they can be read one at a time.
901
2508
  */
902
- function writePortableRecord(workspace: string, uri: string, input: Json, expectRevision?: number): { file: string; revision: number | null } {
2509
+ function readFamily(ctx: ExtensionContextV2, desk: Desk, collection: string, after: string | null = null): { text: string; data: unknown } {
2510
+ const workspace = ctx.snapshot.workspace;
2511
+ const identifier = new RegExp(`^${IDENTIFIER}$`, "u");
2512
+ let ids: string[];
2513
+ if (collection === "sections") {
2514
+ const directory = contained(workspace, ".planning/sections");
2515
+ ids =
2516
+ directory === null || !existsSync(directory) || !lstatSync(directory).isDirectory()
2517
+ ? []
2518
+ : readdirSync(directory, { withFileTypes: true })
2519
+ .filter((entry) => entry.isDirectory() && identifier.test(entry.name) && readBytes(workspace, `.planning/sections/${entry.name}/section.json`) !== null)
2520
+ .map((entry) => entry.name)
2521
+ .sort();
2522
+ } else ids = listJson(workspace, `.planning/${collection}`).map((file) => path.posix.basename(file, ".json")).filter((id) => identifier.test(id));
2523
+ const records: unknown[] = [];
2524
+ const omitted: string[] = [];
2525
+ const failed: string[] = [];
2526
+ let size = 0;
2527
+ const total = ids.length;
2528
+ if (after !== null) ids = ids.filter((id) => id > after);
2529
+ for (const id of ids) {
2530
+ if (omitted.length > 0) {
2531
+ omitted.push(id);
2532
+ continue;
2533
+ }
2534
+ let one: { data: unknown };
2535
+ try {
2536
+ one = readTool(ctx, desk, `project://${collection}/${id}`);
2537
+ } catch (error) {
2538
+ failed.push(`${id} (${error instanceof Error ? error.message : String(error)})`);
2539
+ continue;
2540
+ }
2541
+ const length = JSON.stringify(one.data).length;
2542
+ if (records.length > 0 && size + length > FAMILY_LIMIT) {
2543
+ omitted.push(id);
2544
+ continue;
2545
+ }
2546
+ records.push(one.data);
2547
+ size += length;
2548
+ }
2549
+ const uri = `project://${collection}`;
2550
+ return {
2551
+ text: [
2552
+ total === 0 ? `${uri} holds no records yet.` : `${uri} holds ${total} ${total === 1 ? "record" : "records"}; ${records.length}${after !== null ? ` after ${after}` : ""} returned in full, each with the revision and sha256 to pass back to record.`,
2553
+ omitted.length > 0 ? `${omitted.length} more not returned, to keep this read small; read the next page with ${uri}?after=${String((records[records.length - 1] as Json | undefined)?.uri ?? "").split("/").pop()}.` : "",
2554
+ failed.length > 0 ? `Not readable: ${failed.join("; ")}.` : "",
2555
+ ]
2556
+ .filter(Boolean)
2557
+ .join(" "),
2558
+ data: { uri, records, omitted, ...(failed.length > 0 ? { failed } : {}) },
2559
+ };
2560
+ }
2561
+
2562
+ function readTool(ctx: ExtensionContextV2, desk: Desk, uri: string): { text: string; data: unknown } {
2563
+ const workspace = ctx.snapshot.workspace;
2564
+ const family = new RegExp(`^project://(sections|sources|evidence|checkpoints|validations|interactions)/?\\*?(?:\\?after=(${IDENTIFIER}))?$`, "u").exec(uri);
2565
+ if (family) return readFamily(ctx, desk, family[1] as string, family[2] ?? null);
903
2566
  const route = RECORD_URIS.find((entry) => entry.pattern.test(uri));
904
- if (!route) throw new Error(`${uri} is not a logical record URI this adapter maps`);
905
- const id = route.pattern.exec(uri)?.[1] ?? "";
906
- if (input.schema !== `wtfp.project.${route.type}/v1`) throw new Error(`${uri} holds wtfp.project.${route.type}/v1 records`);
907
- if (id && input.id !== id) throw new Error(`${uri} must hold the record whose id is ${id}`);
908
- const file = route.file(id);
909
- const manifest = readRecord(workspace, ".planning/project.json");
910
- const projectId = route.type === "manifest" ? input.id : input.project_id;
911
- if (manifest && typeof manifest.id === "string" && projectId !== manifest.id)
912
- throw new Error(`${uri} belongs to project ${String(projectId)}, not ${manifest.id}`);
913
- const existing = readRecord(workspace, file);
914
- const record: Json = { ...input };
915
- let revision: number | null = null;
916
- if (REVISIONED.has(route.type)) {
917
- const current = typeof existing?.revision === "number" ? existing.revision : null;
918
- if (current !== null && expectRevision !== undefined && expectRevision !== current)
919
- throw new Error(`${uri} is at revision ${current}, not ${expectRevision}; read it again before writing`);
920
- revision = current === null ? (typeof input.revision === "number" ? input.revision : 0) : current + 1;
921
- record.revision = revision;
2567
+ if (!route) throw new Error(notARecord(uri));
2568
+ const file = route.file(route.pattern.exec(uri)?.[1] ?? "");
2569
+ const bytes = readBytes(workspace, file);
2570
+ if (bytes === null) {
2571
+ if (contained(workspace, file) === null) throw new Error(`${uri} is reached through a symbolic link; the desk does not follow links`);
2572
+ return { text: withTemplate(`${uri} does not exist yet; create it without expect_revision or expect_sha256.`, route.type), data: { uri, file, exists: false } };
2573
+ }
2574
+ let record: unknown;
2575
+ try {
2576
+ record = JSON.parse(bytes.toString("utf8"));
2577
+ } catch (error) {
2578
+ throw new Error(`${file} is not valid JSON (${error instanceof Error ? error.message : String(error)})`);
922
2579
  }
923
- if (STAMPED.has(route.type)) record.updated_at = timestamp();
924
- writeRecord(workspace, file, record);
925
- return { file, revision };
2580
+ const revision = typeof (record as Json).revision === "number" ? ((record as Json).revision as number) : null;
2581
+ const checkpoint = route.type === "checkpoint" ? desk.checkpoints.find((entry) => entry.file === file) : undefined;
2582
+ return {
2583
+ text: `${uri}${revision === null ? "" : ` at revision ${revision}`}, sha256 ${sha256(bytes)}${checkpoint ? `, ${checkpoint.status}, author answer ${checkpoint.trust}` : ""}.`,
2584
+ data: { uri, file, exists: true, revision, sha256: sha256(bytes), record, ...(checkpoint ? { trust: checkpoint.trust } : {}) },
2585
+ };
926
2586
  }
927
2587
 
928
- function measureSection(workspace: string, sectionId: string): { words: number; target: number; file: string | null; total: number } {
929
- const desk = loadDesk(workspace);
2588
+ /**
2589
+ * An immutable milestone snapshot: every `.planning` file outside the archives
2590
+ * and every `paper/` file, copied byte for byte under
2591
+ * `.planning/archives/<archive>/` beside a manifest of their sha256 digests.
2592
+ * Live, a model could not copy a whole project by hand within a turn. Only an
2593
+ * armed action that declares the archive may make one, links are never
2594
+ * followed, and an existing archive is never touched.
2595
+ */
2596
+ function archiveProject(workspace: string, archive: string, armed: Armed | null, projectId: string | null): { uri: string; files: number; manifest: string; sha256: string } {
2597
+ if (!new RegExp(`^${IDENTIFIER}$`, "u").test(archive)) throw new Error(`${archive} is not a valid archive id; use lowercase letters and digits joined by single hyphens`);
2598
+ const uri = `project://archives/${archive}`;
2599
+ if (!armed || !declares(armed, `${uri}/manifest.json`, "archive"))
2600
+ throw new Error(`${armed ? armed.action : "nothing armed"} does not declare archiving ${uri}; only the action that owns a milestone archive may make one`);
2601
+ return withLock(workspace, () => {
2602
+ recover(workspace);
2603
+ const target = `.planning/archives/${archive}`;
2604
+ const destination = contained(workspace, target);
2605
+ if (destination === null) throw new Error(`${target} is reached through a symbolic link; the desk does not follow links`);
2606
+ if (existsSync(destination)) throw new Error(`${uri} already exists, and an archive is immutable; choose another id`);
2607
+ const files: Array<{ path: string; sha256: string; bytes: number }> = [];
2608
+ const walk = (relative: string): void => {
2609
+ const directory = contained(workspace, relative);
2610
+ if (directory === null || !existsSync(directory) || !lstatSync(directory).isDirectory()) return;
2611
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
2612
+ const child = path.posix.join(relative, entry.name);
2613
+ if (entry.name.startsWith(".") || child === ".planning/archives" || entry.isSymbolicLink()) continue;
2614
+ if (entry.isDirectory()) walk(child);
2615
+ else if (entry.isFile()) {
2616
+ const bytes = readBytes(workspace, child);
2617
+ if (bytes === null) throw new Error(`${child} could not be read whole, so the archive would be incomplete`);
2618
+ files.push({ path: child, sha256: sha256(bytes), bytes: bytes.length });
2619
+ }
2620
+ }
2621
+ };
2622
+ walk(".planning");
2623
+ walk("paper");
2624
+ const staging = `${destination}.staging-${randomBytes(4).toString("hex")}`;
2625
+ mkdirSync(staging, { recursive: true });
2626
+ for (const file of files) {
2627
+ const out = path.join(staging, file.path);
2628
+ mkdirSync(path.dirname(out), { recursive: true });
2629
+ writeFileSync(out, readFileSync(path.join(workspace, file.path)));
2630
+ }
2631
+ const manifest = `${JSON.stringify({ archive: uri, project_id: projectId, created_at: timestamp(), files }, null, 2)}\n`;
2632
+ writeFileSync(path.join(staging, "manifest.json"), manifest);
2633
+ renameSync(staging, destination);
2634
+ return { uri, files: files.length, manifest: `${target}/manifest.json`, sha256: sha256(manifest) };
2635
+ });
2636
+ }
2637
+
2638
+ function measureSection(workspace: string, sectionId: string, key: Buffer | null, armed: Armed | null): { words: number; target: number; file: string | null; total: number; recorded: boolean } {
2639
+ return withLock(workspace, () => {
2640
+ recover(workspace);
2641
+ const desk = loadDesk(workspace, key);
2642
+ const section = desk.sections.find((entry) => entry.id === sectionId);
2643
+ if (!section) throw new Error(`no section ${sectionId} in the outline`);
2644
+ const sectionFile = `.planning/sections/${sectionId}/section.json`;
2645
+ const record = readRecord(workspace, sectionFile);
2646
+ if (!record) throw new Error(`${sectionFile} does not exist yet`);
2647
+ const writes: RecordWrite[] = [
2648
+ { uri: `project://sections/${sectionId}`, expect_sha256: sha256(readBytes(workspace, sectionFile) ?? ""), record: { ...record, word_count: section.words } },
2649
+ ];
2650
+ const recorded = desk.sections.reduce((sum, entry) => sum + (entry.id === sectionId ? section.words : (entry.recorded ?? 0)), 0);
2651
+ const state = readRecord(workspace, ".planning/state.json");
2652
+ if (state && typeof state.progress === "object" && state.progress !== null)
2653
+ writes.push({
2654
+ uri: "project://state",
2655
+ expect_revision: typeof state.revision === "number" ? state.revision : 0,
2656
+ record: { ...state, progress: { ...(state.progress as Json), word_count: recorded } },
2657
+ });
2658
+ // An action that may not update these records still gets the desk's count, so it never counts by hand.
2659
+ if (armed && !writes.every((write) => declares(armed, write.uri, "update")))
2660
+ return { words: section.words, target: section.target, file: section.manuscript, total: recorded, recorded: false };
2661
+ const prepared = writes.map((write) => prepare(workspace, write, "agent", armed));
2662
+ commit(workspace, prepared.map((entry) => entry.write));
2663
+ return { words: section.words, target: section.target, file: section.manuscript, total: recorded, recorded: true };
2664
+ });
2665
+ }
2666
+
2667
+ function readiness(desk: Desk, sectionId: string): Json {
930
2668
  const section = desk.sections.find((entry) => entry.id === sectionId);
931
2669
  if (!section) throw new Error(`no section ${sectionId} in the outline`);
932
- const sectionFile = `.planning/sections/${sectionId}/section.json`;
933
- const record = readRecord(workspace, sectionFile);
934
- if (!record) throw new Error(`${sectionFile} does not exist yet`);
935
- writePortableRecord(workspace, `project://sections/${sectionId}`, { ...record, word_count: section.words });
936
- const total = totalWords(desk);
937
- const state = readRecord(workspace, ".planning/state.json");
938
- if (state && typeof state.progress === "object" && state.progress !== null)
939
- writePortableRecord(workspace, "project://state", {
940
- ...state,
941
- progress: { ...(state.progress as Json), word_count: total },
942
- });
943
- return { words: section.words, target: section.target, file: section.manuscript, total };
2670
+ const reasons = blockers(desk, section);
2671
+ return {
2672
+ section: section.id,
2673
+ ready: reasons.length === 0,
2674
+ reasons,
2675
+ plan: { state: section.plan.state, uri: section.plan.uri, sha256: section.plan.sha256, reason: section.plan.reason },
2676
+ gates: section.gates.map((gate) => ({ id: gate.id, status: gate.status, trust: gate.trust, request: gate.request })),
2677
+ research_required: section.research.required,
2678
+ unsupported_required_claims: section.unsupported,
2679
+ findings: desk.coverage.findings.filter((entry) => entry.subject.startsWith(`project://sections/${section.id}`)),
2680
+ coverage_scope: desk.coverage.scope,
2681
+ };
944
2682
  }
945
2683
 
946
2684
  // --- commands ----------------------------------------------------------------
@@ -961,10 +2699,11 @@ function progressCard(desk: Desk): View {
961
2699
  { label: "words", value: `${totals.toLocaleString("en-US")} / ${desk.targetWords.toLocaleString("en-US")}`, tone: tolerance(totals, desk.targetWords) },
962
2700
  { label: "sections", value: `${desk.sections.filter((section) => section.status === "complete").length} of ${desk.sections.length} complete` },
963
2701
  {
964
- label: "pending gates and tasks",
965
- value: String(pendingGates(desk, []).length),
966
- tone: pendingGates(desk, []).length > 0 ? "warning" : "positive",
2702
+ label: "gates waiting on you",
2703
+ value: String(askable(desk, []).length),
2704
+ tone: askable(desk, []).length > 0 ? "warning" : "positive",
967
2705
  },
2706
+ ...(desk.journal ? [{ label: "interrupted write", value: "pending recovery", tone: "error" as ViewTone }] : []),
968
2707
  ...(daysLeft(desk.deadline) ? [{ label: "deadline", value: daysLeft(desk.deadline) as string }] : []),
969
2708
  { label: "next", value: next.command ? `${next.command} · ${next.reason}` : next.reason, tone: "info" },
970
2709
  ],
@@ -973,12 +2712,13 @@ function progressCard(desk: Desk): View {
973
2712
  ? [
974
2713
  {
975
2714
  t: "table",
976
- columns: ["wave", "section", "status", "stages", "words", "claims", "gates"],
2715
+ columns: ["wave", "section", "status", "stages", "plan", "words", "claims", "gates"],
977
2716
  rows: desk.sections.map((section) => [
978
2717
  String(section.wave),
979
2718
  section.title,
980
2719
  section.status,
981
2720
  stageStrip(section),
2721
+ section.plan.state,
982
2722
  section.target > 0 ? `${section.words}/${section.target}` : String(section.words),
983
2723
  `${section.claims.verified}/${section.claims.total}`,
984
2724
  String(section.gates.length),
@@ -997,11 +2737,77 @@ function progressText(desk: Desk): string {
997
2737
  return [
998
2738
  `${desk.title} · ${desk.phase}`,
999
2739
  `${totalWords(desk)}/${desk.targetWords} words; ${desk.sections.filter((section) => section.status === "complete").length}/${desk.sections.length} sections complete`,
1000
- ...desk.sections.map((section) => ` w${section.wave} ${section.id}: ${section.status} ${stageStrip(section)} ${section.words}/${section.target}w`),
2740
+ ...(desk.journal ? ["An interrupted record write awaits recovery."] : []),
2741
+ ...desk.sections.map((section) => ` w${section.wave} ${section.id}: ${section.status} ${stageStrip(section)} plan ${section.plan.state} ${section.words}/${section.target}w`),
1001
2742
  next.command ? `Next: ${next.command} (${next.reason})` : `Next: ${next.reason}`,
1002
2743
  ].join("\n");
1003
2744
  }
1004
2745
 
2746
+ /**
2747
+ * The project as one compact record for an agent: what an action would
2748
+ * otherwise reconstruct from many record reads. It reports, never decides;
2749
+ * an action still reads the records it will change or quote.
2750
+ */
2751
+ function statusDigest(desk: Desk): Json {
2752
+ const next = nextAction(desk);
2753
+ return {
2754
+ present: desk.present,
2755
+ ...(desk.present
2756
+ ? {
2757
+ project: { id: desk.projectId, title: desk.title, document_type: desk.documentType, venue: desk.venue, deadline: desk.deadline, argument: desk.argument },
2758
+ phase: desk.phase,
2759
+ status: desk.status,
2760
+ words: { total: totalWords(desk), target: desk.targetWords, method: WORD_METHOD },
2761
+ sections: desk.sections.map((section) => ({
2762
+ id: section.id,
2763
+ title: section.title,
2764
+ wave: section.wave,
2765
+ status: section.status,
2766
+ depends_on: section.dependsOn,
2767
+ words: section.words,
2768
+ target: section.target,
2769
+ manuscript: section.manuscript,
2770
+ stages: section.stages,
2771
+ plan: { state: section.plan.state, uri: section.plan.uri, reason: section.plan.reason },
2772
+ research_required: section.research.required,
2773
+ claims: section.claims,
2774
+ unsupported_claims: section.unsupported,
2775
+ blockers: blockers(desk, section),
2776
+ })),
2777
+ open_gates: openGates(desk).map((gate) => ({ id: gate.id, kind: gate.kind, scope: gate.scope_uri, request: gate.request, trust: gate.trust })),
2778
+ evidence: { sources: desk.sources, evidence: desk.evidence },
2779
+ issues: desk.issues,
2780
+ invalid_records: desk.invalid.map((entry) => entry.file),
2781
+ interrupted_write: desk.journal,
2782
+ }
2783
+ : {}),
2784
+ next: { action: next.action ?? null, section: next.section ?? null, gate: next.gate ?? null, command: next.command, reason: next.reason },
2785
+ };
2786
+ }
2787
+
2788
+ /** Clio refuses effect text longer than this many UTF-16 code units. */
2789
+ const EFFECT_TEXT_LIMIT = 2000;
2790
+
2791
+ /** Text cut to Clio's effect limit with `tail` appended, never splitting a surrogate pair. */
2792
+ function clip(message: string, tail: string): string {
2793
+ if (message.length <= EFFECT_TEXT_LIMIT) return message;
2794
+ let end = EFFECT_TEXT_LIMIT - tail.length;
2795
+ const last = message.charCodeAt(end - 1);
2796
+ if (last >= 0xd800 && last <= 0xdbff) end -= 1;
2797
+ return `${message.slice(0, end)}${tail}`;
2798
+ }
2799
+
2800
+ /** The desk's status as one reminder within Clio's effect limit. */
2801
+ function statusReminder(desk: Desk): string {
2802
+ const gates = openGates(desk);
2803
+ const lines = [
2804
+ "WTF-P desk status at the start of this turn (extension_wtfp__status returns it as structured data):",
2805
+ progressText(desk),
2806
+ ...(gates.length > 0 ? [`Open gates: ${gates.map((gate) => `${gate.id} (${gate.scope_uri.replace(/^project:\/\//u, "")})`).join(", ")}`] : []),
2807
+ ];
2808
+ return clip(lines.join("\n"), "\n… (truncated; call extension_wtfp__status)");
2809
+ }
2810
+
1005
2811
  function helpCard(served: ServedPlugin): { text: string; card: View } {
1006
2812
  const availability = JSON.parse(
1007
2813
  readFileSync(path.join(PACKAGE_ROOT, "compatibility", "action-availability.json"), "utf8"),
@@ -1015,7 +2821,6 @@ function helpCard(served: ServedPlugin): { text: string; card: View } {
1015
2821
  entry.status === "available" ? text(contract.description) : `unavailable: ${entry.unavailableCapabilities.join(", ")}`,
1016
2822
  ];
1017
2823
  });
1018
- const guarded = Object.keys(GUARD.actions).map((id) => actionName(served, id));
1019
2824
  const local = [...DESK_COMMANDS].map((id) => actionName(served, id));
1020
2825
  return {
1021
2826
  text: rows.map((row) => `${row[0]} ${row[1]}`).join("\n"),
@@ -1031,7 +2836,7 @@ function helpCard(served: ServedPlugin): { text: string; card: View } {
1031
2836
  t: "text",
1032
2837
  wrap: "wrap",
1033
2838
  tone: "muted",
1034
- text: `${served ? "" : "The WTF-P plugin is not installed and enabled, so the actions above are not commands here; install and enable it to run them. "}Answered locally with no model: ${local.join(", ")}, /ext:wtfp:checkpoints, /ext:wtfp:validate. Write guard: ${guarded.join(", ")} may write only under the roots each declares. A manuscript write waits for its section's blocking gates and approved plan. ${WORD_METHOD}`,
2839
+ text: `${served ? "" : "The WTF-P plugin is not installed and enabled, so the actions above are not commands here; install and enable it to run them. "}Answered locally with no model: ${local.join(", ")}, /ext:wtfp:checkpoints, /ext:wtfp:validate. Write guard: a running action may write only what its contract declares, and the workers it dispatches are confined to the same roots. A section's manuscript waits for its blocking gates, an approved plan whose bytes the author approved, and verified evidence for required claims in literature-heavy sections. Only your answers at the desk count as yours. ${WORD_METHOD}`,
1035
2840
  },
1036
2841
  ],
1037
2842
  },
@@ -1050,11 +2855,12 @@ function checkpointsCard(desk: Desk): View {
1050
2855
  children: [
1051
2856
  {
1052
2857
  t: "table",
1053
- columns: ["id", "kind", "status", "blocking", "scope"],
2858
+ columns: ["id", "kind", "status", "answer", "blocking", "scope"],
1054
2859
  rows: desk.checkpoints.slice(0, 100).map((checkpoint) => [
1055
2860
  checkpoint.id,
1056
2861
  checkpoint.kind,
1057
2862
  checkpoint.status,
2863
+ checkpoint.trust,
1058
2864
  checkpoint.blocking ? "yes" : "no",
1059
2865
  checkpoint.scope_uri.replace(/^project:\/\//u, ""),
1060
2866
  ]),
@@ -1064,98 +2870,665 @@ function checkpointsCard(desk: Desk): View {
1064
2870
  }
1065
2871
 
1066
2872
  async function validateAll(ctx: ExtensionContextV2): Promise<ExtensionOutputV2> {
1067
- const files = planningRecords(ctx.snapshot.workspace);
2873
+ const workspace = ctx.snapshot.workspace;
2874
+ let recovered: string | null = null;
2875
+ if (contained(workspace, JOURNAL) !== null && existsSync(path.join(workspace, JOURNAL)))
2876
+ recovered = withLock(workspace, () => recover(workspace));
2877
+ const files = planningRecords(workspace);
1068
2878
  const failures = files
1069
- .map((file) => ({ file, errors: validateFile(ctx.snapshot.workspace, file) }))
2879
+ .map((file) => ({ file, errors: validateFile(workspace, file) }))
1070
2880
  .filter((record) => record.errors.length > 0);
1071
2881
  await ctx.state.set(
1072
2882
  "invalid",
1073
2883
  failures.map((record) => ({ file: record.file, errors: record.errors.slice(0, 5) })),
1074
2884
  );
1075
- const view: View =
1076
- failures.length === 0
1077
- ? { t: "text", text: `✓ ${files.length} planning records valid against their schemas.`, tone: "positive" }
1078
- : {
1079
- t: "box",
1080
- dir: "col",
1081
- border: "round",
1082
- title: "WTF-P · schema violations",
1083
- meta: `${failures.length}/${files.length}`,
1084
- children: failures.slice(0, 6).flatMap((record) => [
1085
- { t: "text", text: record.file, bold: true, tone: "error" } as View,
1086
- ...record.errors.slice(0, 3).map((error) => ({ t: "text", text: ` ${error}`, tone: "muted", wrap: "wrap" }) as View),
1087
- ]),
1088
- };
1089
- return {
1090
- text: failures.length === 0 ? `${files.length} records valid.` : failures.map((record) => `${record.file}: ${record.errors[0]}`).join("\n"),
1091
- card: view,
1092
- ...(await picture(ctx)),
2885
+ const desk = await deskFor(ctx);
2886
+ const findings: Finding[] = [...reconcile(workspace, desk), ...desk.coverage.findings];
2887
+ const order = ["blocker", "error", "warning", "info"];
2888
+ findings.sort((a, b) => order.indexOf(a.severity) - order.indexOf(b.severity));
2889
+ const serious = findings.filter((finding) => finding.severity !== "info");
2890
+ const lines = [
2891
+ ...(recovered ? [recovered] : []),
2892
+ failures.length === 0 ? `${files.length} records valid against their schemas.` : failures.map((record) => `${record.file}: ${record.errors[0]}`).join("\n"),
2893
+ ...findings.map((finding) => `${finding.severity} ${finding.code} ${finding.subject}: ${finding.message}`),
2894
+ ...(desk.coverage.claims.length > 0 ? [desk.coverage.scope] : []),
2895
+ ];
2896
+ const view: View = {
2897
+ t: "box",
2898
+ dir: "col",
2899
+ border: "round",
2900
+ title: failures.length === 0 && serious.length === 0 ? "WTF-P · records consistent" : "WTF-P · findings",
2901
+ meta: `${files.length} records · ${failures.length} invalid · ${serious.length} findings`,
2902
+ children: [
2903
+ ...(recovered ? [{ t: "text", text: recovered, tone: "warning", wrap: "wrap" } as View] : []),
2904
+ failures.length === 0
2905
+ ? ({ t: "text", text: `✓ ${files.length} planning records valid against their schemas.`, tone: "positive" } as View)
2906
+ : ({ t: "text", text: `✗ ${failures.length} of ${files.length} records fail their schemas.`, tone: "error" } as View),
2907
+ ...failures.slice(0, 4).flatMap((record) => [
2908
+ { t: "text", text: record.file, bold: true, tone: "error" } as View,
2909
+ ...record.errors.slice(0, 2).map((error) => ({ t: "text", text: ` ${error}`, tone: "muted", wrap: "wrap" }) as View),
2910
+ ]),
2911
+ ...(findings.length > 0
2912
+ ? [
2913
+ {
2914
+ t: "table",
2915
+ columns: ["severity", "finding", "subject", "detail"],
2916
+ rows: findings.slice(0, 40).map((finding) => [finding.severity, finding.code, finding.subject.replace(/^project:\/\//u, ""), finding.message]),
2917
+ } as View,
2918
+ ]
2919
+ : []),
2920
+ ...(desk.coverage.claims.length > 0 ? [{ t: "text", text: desk.coverage.scope, tone: "muted", wrap: "wrap" } as View] : []),
2921
+ ],
1093
2922
  };
2923
+ return { text: lines.join("\n"), card: view, ...(await picture(ctx, desk)) };
1094
2924
  }
1095
2925
 
1096
2926
  // --- the write guard ---------------------------------------------------------
1097
2927
 
1098
2928
  interface Armed {
1099
2929
  action: string;
1100
- roots: string[];
2930
+ produces: GuardAction["produces"];
2931
+ section: string | null;
2932
+ workspace: string;
1101
2933
  }
1102
2934
 
1103
- function sectionForPaper(desk: Desk, relative: string): SectionRow | undefined {
1104
- return desk.sections.find(
1105
- (section) =>
1106
- section.manuscript !== null &&
1107
- (relative === section.manuscript || relative.startsWith(`${section.manuscript.replace(/\.(md|tex|typ)$/u, "")}.`)),
1108
- );
2935
+ /**
2936
+ * The project roots an armed action's file tools may write, from its declared
2937
+ * outputs. Author-selected materials are never one: a "." root would be the
2938
+ * whole workspace.
2939
+ */
2940
+ function writeRoots(desk: Desk, armed: Armed): string[] {
2941
+ const roots = new Set<string>();
2942
+ const section = armed.section;
2943
+ for (const output of armed.produces) {
2944
+ const uri = output.uri;
2945
+ if (uri.startsWith("project://paper/")) roots.add("paper");
2946
+ else if (uri.startsWith("project://deliverables/")) {
2947
+ const kind = uri.split("/")[3] ?? "";
2948
+ roots.add(kind.startsWith("{") ? "deliverables" : `deliverables/${kind}`);
2949
+ } else if (uri.startsWith("project://archives/")) {
2950
+ const kind = uri.split("/")[3] ?? "";
2951
+ roots.add(kind.startsWith("{") ? ".planning/archives" : `.planning/archives/${kind}`);
2952
+ } else {
2953
+ const match = /^project:\/\/sections\/\{section\}\/(context|research|summary|handoff|plans|reviews)/u.exec(uri);
2954
+ if (match && !section) roots.add(".planning/sections");
2955
+ else if (match) roots.add(match[1] === "plans" || match[1] === "reviews" ? `.planning/sections/${section}/${match[1]}` : `.planning/sections/${section}/${match[1]}.md`);
2956
+ }
2957
+ }
2958
+ if (roots.has("paper") && section) {
2959
+ roots.delete("paper");
2960
+ const row = desk.sections.find((entry) => entry.id === section);
2961
+ for (const root of manuscriptRoots(row)) roots.add(root);
2962
+ }
2963
+ return [...roots].sort();
2964
+ }
2965
+
2966
+ function manuscriptRoots(section: SectionRow | undefined): string[] {
2967
+ if (!section?.manuscript) return [];
2968
+ const stem = section.manuscript.replace(/\.(md|tex|typ)$/u, "");
2969
+ return [section.manuscript, `${stem}/`];
2970
+ }
2971
+
2972
+ /** Every section whose manuscript this file is: its own file, a variant of it, or a file nested under its stem. */
2973
+ function sectionsForPaper(desk: Desk, relative: string): SectionRow[] {
2974
+ return desk.sections.filter((section) => {
2975
+ if (section.manuscript === null) return false;
2976
+ const stem = section.manuscript.replace(/\.(md|tex|typ)$/u, "");
2977
+ return relative === section.manuscript || relative === stem || relative.startsWith(`${stem}.`) || relative.startsWith(`${stem}/`);
2978
+ });
2979
+ }
2980
+
2981
+ function under(root: string, relative: string): boolean {
2982
+ const trimmed = root.replace(/\/$/u, "");
2983
+ return trimmed === "." || relative === trimmed || relative.startsWith(`${trimmed}/`);
2984
+ }
2985
+
2986
+ /** Whether two project paths share a file: one is the other or lies under it. */
2987
+ function overlaps(left: string, right: string): boolean {
2988
+ const a = left.replace(/\/$/u, "");
2989
+ const b = right.replace(/\/$/u, "");
2990
+ return under(a, b) || under(b, a);
2991
+ }
2992
+
2993
+ function block(reason: string): ExtensionHookResult {
2994
+ return { effects: [{ kind: "block_tool", reason }] };
2995
+ }
2996
+
2997
+ /**
2998
+ * What Clio 0.6.3 and later resolve for a tool hook beside its `args`
2999
+ * (public-api-v2 ExtensionToolHookLanding): where a path-taking tool lands,
3000
+ * and a dispatch call's tasks as admission parsed them. The desk judges only
3001
+ * these, never its own reading of a call, so it cannot drift from Clio's
3002
+ * grammar. Clio 0.6.2 sends `args` alone; the desk then refuses writes and
3003
+ * dispatches inside a WTF-P project or action and leaves the rest alone.
3004
+ */
3005
+ interface HostTarget {
3006
+ path: string;
3007
+ resolved: boolean;
3008
+ /** The landing relative to the session's workspace, a worker's task worktree mapped back to the checkout; null outside it. */
3009
+ workspacePath?: string | null;
3010
+ }
3011
+
3012
+ interface HostDispatchTask {
3013
+ role?: string;
3014
+ agent: string;
3015
+ cwd: string;
3016
+ writeRoots: string[];
3017
+ writeBoundaries: string[];
3018
+ worktree: boolean;
3019
+ readOnly: boolean;
3020
+ }
3021
+
3022
+ type HostDispatch =
3023
+ | { kind: "tasks"; mode: string; tasks: HostDispatchTask[]; candidates?: number }
3024
+ | { kind: "list" }
3025
+ | { kind: "apply-winner"; branch: string; cwd: string };
3026
+
3027
+ interface HostLanding {
3028
+ target?: HostTarget;
3029
+ dispatch?: HostDispatch;
3030
+ }
3031
+
3032
+ /** Roles that only judge a dispatch's work; Clio runs them read-only with no write roots. */
3033
+ const GATE_ROLES = new Set(["reviewer", "judge", "member", "synthesis"]);
3034
+
3035
+ const strings = (value: unknown): value is string[] => Array.isArray(value) && value.every((entry) => typeof entry === "string");
3036
+
3037
+ /**
3038
+ * The host's facts for a hook event. A fact in a shape the desk cannot read,
3039
+ * or a dispatch kind it does not know, counts as no fact, and `malformed` says
3040
+ * so: the desk then refuses the call inside a WTF-P project or action and
3041
+ * leaves other folders alone, as for a host that sends none.
3042
+ */
3043
+ function hostLanding(event: unknown): HostLanding & { malformed?: string } {
3044
+ const fields = isObject(event) ? event : {};
3045
+ const landing: HostLanding & { malformed?: string } = {};
3046
+ if (fields.target !== undefined) {
3047
+ const target = fields.target;
3048
+ if (
3049
+ !isObject(target) ||
3050
+ typeof target.path !== "string" ||
3051
+ typeof target.resolved !== "boolean" ||
3052
+ (target.workspacePath !== undefined && target.workspacePath !== null && typeof target.workspacePath !== "string")
3053
+ )
3054
+ landing.malformed = "landing";
3055
+ else landing.target = { path: target.path, resolved: target.resolved, workspacePath: target.workspacePath as string | null | undefined };
3056
+ }
3057
+ if (fields.dispatch !== undefined) {
3058
+ const dispatch = fields.dispatch;
3059
+ const tasks = isObject(dispatch) && dispatch.kind === "tasks" && typeof dispatch.mode === "string" && Array.isArray(dispatch.tasks) ? dispatch.tasks : null;
3060
+ if (isObject(dispatch) && dispatch.kind === "list") landing.dispatch = { kind: "list" };
3061
+ else if (isObject(dispatch) && dispatch.kind === "apply-winner" && typeof dispatch.branch === "string" && typeof dispatch.cwd === "string")
3062
+ landing.dispatch = { kind: "apply-winner", branch: dispatch.branch, cwd: dispatch.cwd };
3063
+ else if (
3064
+ tasks !== null &&
3065
+ tasks.every(
3066
+ (task) =>
3067
+ isObject(task) &&
3068
+ typeof task.agent === "string" &&
3069
+ typeof task.cwd === "string" &&
3070
+ strings(task.writeRoots) &&
3071
+ strings(task.writeBoundaries) &&
3072
+ task.writeRoots.length === task.writeBoundaries.length &&
3073
+ typeof task.worktree === "boolean" &&
3074
+ typeof task.readOnly === "boolean" &&
3075
+ (task.role === undefined || typeof task.role === "string"),
3076
+ )
3077
+ )
3078
+ landing.dispatch = {
3079
+ kind: "tasks",
3080
+ mode: (dispatch as Json).mode as string,
3081
+ tasks: (tasks as Json[]).map((task) => ({
3082
+ ...(task.role === undefined ? {} : { role: task.role as string }),
3083
+ agent: task.agent as string,
3084
+ cwd: task.cwd as string,
3085
+ writeRoots: [...(task.writeRoots as string[])],
3086
+ writeBoundaries: [...(task.writeBoundaries as string[])],
3087
+ worktree: task.worktree as boolean,
3088
+ readOnly: task.readOnly as boolean,
3089
+ })),
3090
+ };
3091
+ else landing.malformed = "dispatch plan";
3092
+ }
3093
+ return landing;
1109
3094
  }
1110
3095
 
1111
- async function guard(ctx: ExtensionContextV2, args: unknown): Promise<ExtensionHookResult> {
1112
- const target = args !== null && typeof args === "object" ? (args as Json).path : undefined;
1113
- if (typeof target !== "string" || target.length === 0) return {};
3096
+ function deskOwned(relative: string): boolean {
3097
+ return DESK_OWNED.some((owned) => under(owned, relative)) || /^\.planning\/(?:.*\/)?\.wtfp-/u.test(relative);
3098
+ }
3099
+
3100
+ /** The manuscripts a write must not reach now: those of sections that are not ready to draft. */
3101
+ function heldManuscripts(desk: Desk): { roots: string[]; notes: string[] } {
3102
+ const roots: string[] = [];
3103
+ const notes: string[] = [];
3104
+ for (const section of desk.sections) {
3105
+ const reasons = blockers(desk, section);
3106
+ if (reasons.length === 0) continue;
3107
+ roots.push(...manuscriptRoots(section));
3108
+ notes.push(`${section.id}: ${reasons.join("; ")}`);
3109
+ }
3110
+ return { roots, notes };
3111
+ }
3112
+
3113
+ /**
3114
+ * The held manuscript a worker root would reach, judged like a direct write:
3115
+ * by every section the path belongs to, so a `.tex` or `.typ` spelling of a
3116
+ * section whose file does not exist yet is held too.
3117
+ */
3118
+ function heldBy(desk: Desk, held: string[], root: string): string | undefined {
3119
+ const hit = held.find((file) => overlaps(root, file));
3120
+ if (hit) return hit;
3121
+ const lexical = root.replace(/\/$/u, "");
3122
+ return sectionsForPaper(desk, lexical).some((section) => blockers(desk, section).length > 0) ? lexical : undefined;
3123
+ }
3124
+
3125
+ /** Whether the session is in a WTF-P project or inside a WTF-P action, where a call the desk cannot judge is refused. */
3126
+ async function projectOrArmed(ctx: ExtensionContextV2): Promise<boolean> {
3127
+ if (await armedFor(ctx)) return true;
3128
+ return loadDesk(ctx.snapshot.workspace, await storedKey(ctx, false)).present;
3129
+ }
3130
+
3131
+ /** Why a host that sends no landing or dispatch plan cannot be guarded. */
3132
+ const NEEDS_HOST_FACTS = "WTF-P needs Clio 0.6.3 or later, which tells the desk where each call lands and what each dispatch starts; this Clio does not, so the desk refuses the call inside a WTF-P project or action.";
3133
+
3134
+ /** Why a call Clio sent no usable facts for is refused, once this Clio has shown it sends them. */
3135
+ async function missingFacts(ctx: ExtensionContextV2, malformed: string | undefined): Promise<string> {
3136
+ if (malformed) return `Clio's ${malformed} for this call is in a form the desk cannot read; refused.`;
3137
+ return (await ctx.state.get<boolean>("host-facts")).value ? "Clio sent no landing for this call, so the desk cannot see where it lands; refused." : NEEDS_HOST_FACTS;
3138
+ }
3139
+
3140
+ /**
3141
+ * Where a write lands, relative to the project, or null outside it, as Clio
3142
+ * resolved it: the file the tool opens, which Clio refuses to change before
3143
+ * the tool runs, and for a worker in a task worktree the checkout path it
3144
+ * merges into.
3145
+ */
3146
+ function writeLanding(target: string, workspace: string, host: HostTarget): { relative: string | null } | { refused: string } {
3147
+ if (!host.resolved) return { refused: `WTF-P write guard: Clio could not resolve where ${target} lands (a link loop, or a component it cannot inspect); refused.` };
3148
+ if (host.workspacePath !== undefined) return { relative: host.workspacePath };
3149
+ const root = realWorkspace(workspace);
3150
+ return { relative: inside(root, host.path) ? posix(path.relative(root, host.path)) || "." : null };
3151
+ }
3152
+
3153
+ async function guardWrite(ctx: ExtensionContextV2, target: string, host?: HostTarget, malformed?: string): Promise<ExtensionHookResult> {
1114
3154
  const workspace = ctx.snapshot.workspace;
1115
3155
  const served = ctx.snapshot.plugin ?? null;
1116
- const absolute = path.resolve(workspace, target);
1117
- const armed = (await ctx.state.get<Armed>("armed")).value;
1118
- if (armed) {
1119
- const roots = armed.roots.map((root) => path.resolve(workspace, root));
1120
- if (!roots.some((root) => inside(root, absolute)))
1121
- return {
1122
- effects: [
1123
- {
1124
- kind: "block_tool",
1125
- reason: `WTF-P write guard: ${actionName(served, armed.action)} may write only under ${armed.roots.join(", ")}; refused ${path.relative(workspace, absolute)}. Record other changes as a handoff instead.`,
1126
- },
1127
- ],
1128
- };
3156
+ if (!host) return (await projectOrArmed(ctx)) ? block(`WTF-P write guard: ${await missingFacts(ctx, malformed)}`) : {};
3157
+ const landed = writeLanding(target, workspace, host);
3158
+ if ("refused" in landed) return block(landed.refused);
3159
+ if (landed.relative === null) return {};
3160
+ const relative = landed.relative;
3161
+ if (deskOwned(relative)) return block(`WTF-P write guard: ${relative} is written only by the desk; nothing else may change it.`);
3162
+ if (under(".planning", relative) && relative.endsWith(".json") && !under(".planning/archives", relative))
3163
+ return block(
3164
+ `WTF-P write guard: ${relative} is a portable record; write it with extension_wtfp__record so it is validated and checked against the version you read.`,
3165
+ );
3166
+ const desk = loadDesk(workspace, await storedKey(ctx, false));
3167
+ const armed = await armedFor(ctx);
3168
+ // Clio's own artifact directory is no project file; a link that leads it into the project lands, and is judged, elsewhere.
3169
+ if (armed && !under(".clio-coder/artifacts", relative)) {
3170
+ const roots = writeRoots(desk, armed);
3171
+ if (!roots.some((allowed) => under(allowed, relative)))
3172
+ return block(
3173
+ armed.action === "advance"
3174
+ ? `WTF-P write guard: nothing is armed between /wtfp:advance steps; refused ${relative}. Call extension_wtfp__next_step; it arms the step that may write, and that step's own prompt says what it writes.`
3175
+ : `WTF-P write guard: ${actionName(served, armed.action)}${armed.section ? ` ${armed.section}` : ""} may write only under ${roots.join(", ") || "nothing (it declares no file outputs)"}; refused ${relative}. Record other changes as a handoff instead.`,
3176
+ );
3177
+ }
3178
+ for (const section of desk.sections) {
3179
+ const linked = Array.isArray((section.record?.artifacts as Json | undefined)?.plans) ? (((section.record?.artifacts as Json).plans as string[]) ?? []) : [];
3180
+ for (const uri of linked)
3181
+ if (artifactFile(workspace, uri) === relative)
3182
+ return block(`WTF-P write guard: ${relative} is a linked plan, and linked plans are immutable; write a revision plan instead.`);
1129
3183
  }
1130
- if (!inside(path.join(workspace, "paper"), absolute)) return {};
1131
- const desk = loadDesk(workspace);
1132
- if (!desk.present) return {};
1133
- const section = sectionForPaper(desk, path.relative(workspace, absolute).split(path.sep).join("/"));
1134
- if (!section) return {};
3184
+ if (!under("paper", relative) || !desk.present) return {};
3185
+ // A file can be the manuscript of more than one section (one nested under another's stem); every one must be ready.
3186
+ const held = sectionsForPaper(desk, relative)
3187
+ .map((section) => ({ section, reasons: blockers(desk, section) }))
3188
+ .find((entry) => entry.reasons.length > 0);
3189
+ if (!held) return {};
3190
+ const { section, reasons } = held;
1135
3191
  const gate = section.gates[0];
1136
- if (gate)
1137
- return {
1138
- effects: [
1139
- {
1140
- kind: "block_tool",
1141
- reason: `WTF-P gate: ${section.title} waits on the author's answer to "${gate.request}" (${gate.id}). Answer it with ${actionName(served, "check-todos")} before writing ${section.manuscript}.`,
1142
- },
1143
- ],
1144
- };
1145
- if (desk.confirmPlan && (section.status === "not-started" || section.status === "researching"))
1146
- return {
1147
- effects: [
1148
- {
1149
- kind: "block_tool",
1150
- reason: `WTF-P gate: ${section.title} has no approved plan, and confirm_plan is on. ${
1151
- commandFor(served, "plan-section", section.id) !== null
1152
- ? `Run ${commandFor(served, "plan-section", section.id)} and approve it`
1153
- : "Planning it needs the WTF-P plugin; approve a plan"
1154
- } before writing ${section.manuscript}.`,
1155
- },
1156
- ],
1157
- };
1158
- return {};
3192
+ return block(
3193
+ `WTF-P gate: ${section.title} cannot be written yet: ${reasons.join("; ")}. ${
3194
+ gate
3195
+ ? `Answer it with ${actionName(served, "check-todos")}.`
3196
+ : !planReady(section.plan)
3197
+ ? commandFor(served, "plan-section", section.id) !== null
3198
+ ? `Run ${commandFor(served, "plan-section", section.id)} and approve its plan at the gate.`
3199
+ : "Planning it needs the WTF-P plugin; approve a plan at the gate."
3200
+ : `Run ${actionName(served, "research-gap")} for it first.`
3201
+ }`,
3202
+ );
3203
+ }
3204
+
3205
+ /** Narrows requested write roots to those inside the allowed ones; a broader request becomes the allowed roots inside it. */
3206
+ function narrow(requested: string[], allowed: string[]): string[] {
3207
+ const out = new Set<string>();
3208
+ for (const want of requested) {
3209
+ for (const root of allowed) {
3210
+ const bare = root.replace(/\/$/u, "");
3211
+ if (under(bare, want)) out.add(want);
3212
+ else if (under(want, bare)) out.add(root);
3213
+ }
3214
+ }
3215
+ return [...out].sort();
3216
+ }
3217
+
3218
+ const WTFP_AGENT = /^wtfp-[a-z-]+$/u;
3219
+
3220
+ /** One worker a dispatch names, as Clio parsed it. */
3221
+ interface DispatchTask {
3222
+ /** The agent Clio resolved, `auto` and an omitted agent included. */
3223
+ agent: string;
3224
+ /** Project-relative write roots, or null when the worker would have no boundary. */
3225
+ roots: string[] | null;
3226
+ /** True when Clio runs the worker read-only, as it does every read-only recipe's; it then has no write roots. */
3227
+ readOnly: boolean;
3228
+ }
3229
+
3230
+ function isObject(value: unknown): value is Json {
3231
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3232
+ }
3233
+
3234
+ /** A write root as a plain project path: no `./`, doubled or trailing slash. */
3235
+ function plainSpelling(root: string): string {
3236
+ return root.trim().replace(/\/{2,}/gu, "/").replace(/^(?:\.\/)+/u, "").replace(/\/$/u, "");
3237
+ }
3238
+
3239
+ /**
3240
+ * The workers a dispatch starts, from the plan Clio parsed. Gate roles only
3241
+ * judge, so they are left out. Every worker runs from the project root, no
3242
+ * writer works in a task worktree whose merge the desk would not see, and a
3243
+ * write root must land where it reads: Clio fixes a boundary at the root's
3244
+ * physical location, so a root through a link would let a worker write
3245
+ * wherever the link points. A root that lands on the whole project is no
3246
+ * boundary. Throws for any of these. Clio judges a rewritten call again, so
3247
+ * the roots the desk itself hands a worker are checked the same way.
3248
+ */
3249
+ function planTasks(plan: Extract<HostDispatch, { kind: "tasks" }>, workspace: string, present: boolean): DispatchTask[] {
3250
+ const root = realWorkspace(workspace);
3251
+ for (const task of plan.tasks)
3252
+ if (task.cwd !== root) throw new Error("WTF-P dispatch guard: a worker's cwd moves the write roots the desk judged; dispatch from the project root without cwd.");
3253
+ if (present && plan.tasks.some((task) => task.worktree && !task.readOnly))
3254
+ throw new Error("WTF-P dispatch guard: the desk cannot see what a task worktree merges back, so a WTF-P project refuses worktree writers, compete candidates included.");
3255
+ // With no role reported, every task is one the call named.
3256
+ return plan.tasks
3257
+ .filter((task) => task.role === undefined || !GATE_ROLES.has(task.role))
3258
+ .map((task) => {
3259
+ let unbounded = task.writeRoots.length === 0;
3260
+ const roots: string[] = [];
3261
+ task.writeRoots.forEach((spelled, index) => {
3262
+ const boundary = task.writeBoundaries[index] as string;
3263
+ const landed = inside(root, boundary) ? posix(path.relative(root, boundary)) || "." : null;
3264
+ if (landed === ".") {
3265
+ unbounded = true;
3266
+ return;
3267
+ }
3268
+ if (landed === null || landed !== plainSpelling(spelled))
3269
+ throw new Error(`WTF-P dispatch guard: write root ${spelled} does not lead where it reads (a link, or a path outside the project); name the real project path.`);
3270
+ roots.push(`${landed}${spelled.trim().endsWith("/") ? "/" : ""}`);
3271
+ });
3272
+ return { agent: task.agent, roots: unbounded ? null : roots, readOnly: task.readOnly };
3273
+ });
3274
+ }
3275
+
3276
+ /** The call's arguments without Clio's private admission keys, which Clio recomputes for any rewritten call. */
3277
+ function withoutHostKeys(args: Json): Json {
3278
+ return Object.fromEntries(Object.entries(args).filter(([key]) => !key.startsWith("__clio_")));
3279
+ }
3280
+
3281
+ /**
3282
+ * The call with each named worker held to its roots, in the shape Clio
3283
+ * prepares for hooks: `tasks` an array of task objects or task strings, one
3284
+ * per named worker, whose own intent overrides the shared one.
3285
+ */
3286
+ function confineCall(args: Json, narrowed: Array<string[] | null>): Json {
3287
+ const confine = (item: unknown, roots: string[] | null): unknown => {
3288
+ if (roots === null) return item;
3289
+ const task = typeof item === "string" ? { task: item } : (item as Json);
3290
+ return { ...task, intent: { ...(isObject(task.intent) ? task.intent : {}), write_roots: roots } };
3291
+ };
3292
+ const tasks = args.tasks;
3293
+ if (args.tasks === undefined && narrowed.length === 1) return { ...withoutHostKeys(args), intent: { ...(isObject(args.intent) ? args.intent : {}), write_roots: narrowed[0] } };
3294
+ if (Array.isArray(tasks) && tasks.length === narrowed.length && tasks.every((item) => isObject(item) || typeof item === "string"))
3295
+ return { ...withoutHostKeys(args), tasks: tasks.map((item, index) => confine(item, narrowed[index] ?? null)) };
3296
+ throw new Error("WTF-P dispatch guard: the desk confines each worker through its intent.write_roots, so send tasks as an array of task objects.");
3297
+ }
3298
+
3299
+ const sameRoots = (left: string[] | null, right: string[] | null): boolean =>
3300
+ left !== null && right !== null && left.length === right.length && [...left].sort().every((root, index) => root === [...right].sort()[index]);
3301
+
3302
+ async function guardDispatch(ctx: ExtensionContextV2, args: Json, host?: HostDispatch, malformed?: string): Promise<ExtensionHookResult> {
3303
+ if (args.list === true || host?.kind === "list") return {};
3304
+ // Clio could not prepare this call and refuses it itself, with its own reason; nothing of it runs.
3305
+ if (!host && typeof args.__clio_dispatch_plan_preparation_error === "string") return {};
3306
+ if (!host) return (await projectOrArmed(ctx)) ? block(`WTF-P dispatch guard: ${await missingFacts(ctx, malformed)}`) : {};
3307
+ const workspace = ctx.snapshot.workspace;
3308
+ const served = ctx.snapshot.plugin ?? null;
3309
+ const desk = loadDesk(workspace, await storedKey(ctx, false));
3310
+ const armed = await armedFor(ctx);
3311
+ if (!desk.present && !armed) {
3312
+ // Outside a WTF-P project and action, only the WTF-P recipes are the desk's business.
3313
+ const wtfp = host.kind === "tasks" ? host.tasks.filter((task) => WTFP_AGENT.test(task.agent)).map((task) => task.agent) : [];
3314
+ return wtfp.length > 0
3315
+ ? block(`WTF-P dispatch guard: ${wtfp.join(", ")} run only inside the WTF-P action that owns them, so the desk can confine their writes; start it with its /wtfp: command.`)
3316
+ : {};
3317
+ }
3318
+ if (desk.present && (args.from_scout !== undefined || host.kind === "apply-winner"))
3319
+ return block("WTF-P dispatch guard: the desk cannot see what a scout continuation or a compete winner writes, so a WTF-P project refuses them.");
3320
+ if (host.kind !== "tasks") return {};
3321
+ const entries = planTasks(host, workspace, desk.present);
3322
+ if (!armed) {
3323
+ const wtfp = entries.filter((entry) => WTFP_AGENT.test(entry.agent));
3324
+ if (wtfp.length > 0)
3325
+ return block(
3326
+ `WTF-P dispatch guard: ${wtfp.map((entry) => entry.agent).join(", ")} run only inside the WTF-P action that owns them, so the desk can confine their writes; start it with its /wtfp: command.`,
3327
+ );
3328
+ // Workers run no desk check, so outside an action each must be kept off the records and the manuscripts still held.
3329
+ const held = [".planning/", ...heldManuscripts(desk).roots];
3330
+ for (const entry of entries) {
3331
+ if (entry.readOnly) continue;
3332
+ if (entry.roots === null)
3333
+ return block(
3334
+ `WTF-P dispatch guard: outside a WTF-P action, give each worker intent.write_roots that leave out ${held.join(", ")}; a worker runs no desk check, so without roots it could change the records or a gated manuscript.`,
3335
+ );
3336
+ for (const root of entry.roots) {
3337
+ const hit = heldBy(desk, held, root);
3338
+ if (hit) return block(`WTF-P dispatch guard: write root ${root} reaches ${hit}, which a worker outside a WTF-P action may not change.`);
3339
+ }
3340
+ }
3341
+ return {};
3342
+ }
3343
+ const name = actionName(served, armed.action);
3344
+ // Inside an action that delegates, a writing worker is one of its roles; a call without agent falls to Clio's default worker.
3345
+ const agents = GUARD.actions[armed.action]?.agents ?? [];
3346
+ const stranger = agents.length > 0 ? entries.find((entry) => !entry.readOnly && !agents.includes(entry.agent)) : undefined;
3347
+ if (stranger)
3348
+ return block(
3349
+ `WTF-P dispatch guard: ${name} delegates only to ${agents.join(", ")}, and this call would start ${stranger.agent}; name the role with agent (for example agent: "${agents.find((agent) => GUARD.paperWriters.includes(agent)) ?? agents[0]}").`,
3350
+ );
3351
+ // A worker never gets a root that holds records: the record tool is the only way records change.
3352
+ const base = writeRoots(desk, armed).filter((root) => ![".", ".planning", ".planning/sections"].includes(root.replace(/\/$/u, "")));
3353
+ const held = heldManuscripts(desk);
3354
+ let allowed = base;
3355
+ const notes: string[] = [];
3356
+ if (base.includes("paper")) {
3357
+ // Without a named section, a worker may reach only manuscripts whose sections are ready now.
3358
+ notes.push(...held.notes);
3359
+ allowed = [...base.filter((root) => root !== "paper"), ...desk.sections.filter((section) => blockers(desk, section).length === 0).flatMap((section) => manuscriptRoots(section))];
3360
+ } else if (armed.section) {
3361
+ const section = desk.sections.find((entry) => entry.id === armed.section);
3362
+ const reasons = section ? blockers(desk, section) : [];
3363
+ if (section && reasons.length > 0 && base.some((root) => root.startsWith("paper/"))) notes.push(`${section.id}: ${reasons.join("; ")}`);
3364
+ }
3365
+ // No worker root may cover a manuscript that is still held, even one nested under a ready section's stem.
3366
+ allowed = [...new Set(allowed.filter((root) => !held.roots.some((file) => overlaps(root, file))))].sort();
3367
+ const sectionScoped = armed.produces.some((output) => output.uri.includes("{section}"));
3368
+ const paperWriters = new Set(GUARD.paperWriters);
3369
+ const narrowed = entries.map((entry): string[] | null => {
3370
+ if (entry.readOnly) return null;
3371
+ const roots = entry.roots === null ? allowed : narrow(entry.roots, allowed);
3372
+ if (paperWriters.has(entry.agent) && !roots.some((root) => root.startsWith("paper/")))
3373
+ throw new Error(
3374
+ entry.roots !== null && allowed.some((root) => root.startsWith("paper/"))
3375
+ ? `WTF-P dispatch guard: ${entry.agent} names write_roots ${entry.roots.join(", ")}, which reach no manuscript ${name} may write; give it intent.write_roots ${allowed.join(", ")} (workspace paths, not project:// URIs).`
3376
+ : `WTF-P dispatch guard: ${entry.agent} would have no manuscript it may write. ${notes.length > 0 ? notes.join(" · ") : "Name the section and approve its plan first."}`,
3377
+ );
3378
+ if (roots.length > 0) return roots;
3379
+ // Clio reads an empty write_roots as no boundary at all, so an empty list is refused, never sent.
3380
+ if (entry.roots !== null && allowed.length > 0)
3381
+ throw new Error(`WTF-P dispatch guard: ${entry.roots.join(", ")} lie outside what ${armed.action} may write (${allowed.join(", ")}).`);
3382
+ throw new Error(
3383
+ sectionScoped && armed.section === null
3384
+ ? `WTF-P dispatch guard: ${name} names no section, so its workers would reach every section's records; name the section in the command.`
3385
+ : `WTF-P dispatch guard: ${name} declares no file outputs a worker may write; only its read-only reviewers may be dispatched.`,
3386
+ );
3387
+ });
3388
+ const writers = entries.filter((entry, index) => narrowed[index] !== null);
3389
+ if (writers.length > 1 && writers.some((entry) => entry.roots === null))
3390
+ return block(
3391
+ `WTF-P dispatch guard: give each task its own intent.write_roots inside ${allowed.join(", ")}, one section's manuscript and summary per writer, so parallel writers stay disjoint.`,
3392
+ );
3393
+ // A worker whose roots already are its confinement, in any order, needs no rewrite.
3394
+ const needed = narrowed.map((roots, index) => (roots === null || sameRoots(roots, entries[index]?.roots ?? null) ? null : roots));
3395
+ if (needed.every((roots) => roots === null)) return {};
3396
+ // Clio admits a rewritten call afresh, without the operator's approval of the original, so a call
3397
+ // that needs approval (more than one worker, a review loop, compete) is refused with the exact roots instead.
3398
+ if (host.tasks.length > 1)
3399
+ return block(
3400
+ `WTF-P dispatch guard: give each worker exactly these intent.write_roots, so the call you approve runs unchanged: ${entries
3401
+ .map((entry, index) => `task ${index + 1} (${entry.agent}): ${(narrowed[index] ?? []).join(", ") || "none, it only reads"}`)
3402
+ .join("; ")}.`,
3403
+ );
3404
+ // Clio admits an extension's rewrite only as a narrowing. A declared intent without write roots is an empty
3405
+ // write ceiling there, although the worker itself treats it as no boundary, so the desk cannot fill the roots in.
3406
+ const declaresEmpty = (item: unknown): boolean =>
3407
+ isObject(item) && isObject(item.intent) && (!Array.isArray(item.intent.write_roots) || item.intent.write_roots.length === 0);
3408
+ if (declaresEmpty(args) || (Array.isArray(args.tasks) && args.tasks.some(declaresEmpty)))
3409
+ return block(
3410
+ `WTF-P dispatch guard: an intent without write_roots bounds nothing for the worker, and Clio will not let the desk fill them in. Send ${entries
3411
+ .map((entry, index) => `${entries.length > 1 ? `task ${index + 1} (${entry.agent}) ` : ""}intent.write_roots ${(needed[index] ?? []).join(", ") || "omitted, since it only reads"}`)
3412
+ .join("; ")} in that intent.`,
3413
+ );
3414
+ const rewritten = confineCall(args, needed);
3415
+ return {
3416
+ effects: [
3417
+ {
3418
+ kind: "rewrite_tool_input",
3419
+ args: rewritten,
3420
+ reason: `WTF-P confines ${name} workers to ${[...new Set(narrowed.flatMap((roots) => roots ?? []))].join(", ") || "no writes"}.`,
3421
+ },
3422
+ ],
3423
+ };
3424
+ }
3425
+
3426
+ const BASH_DESK_PATHS = /\.planning\/(?:interactions\b|\.wtfp-)/u;
3427
+ /** Tools that run a command or script; the desk can only refuse ones that name its own records. */
3428
+ const COMMAND_TOOLS = new Set(["bash", "run_script", "job"]);
3429
+
3430
+ /**
3431
+ * Inside a WTF-P action every question is the author's. Clio answers an
3432
+ * unanswered `ask_user` round with its recommended option after
3433
+ * `safety.unattendedAfterSeconds`, unless the question is `operator_only`, so
3434
+ * the desk marks a lone question that way and refuses a round that would need
3435
+ * splitting, since an `operator_only` question is asked alone.
3436
+ */
3437
+ async function guardQuestions(ctx: ExtensionContextV2, input: Json): Promise<ExtensionHookResult> {
3438
+ if (input.action === "complete") return {};
3439
+ const questions = Array.isArray(input.questions) ? (input.questions as unknown[]) : [];
3440
+ if (questions.length === 0 || questions.every((question) => (question as Json | null)?.operator_only === true)) return {};
3441
+ if (!(await armedFor(ctx))) return {};
3442
+ if (questions.length > 1)
3443
+ return block("WTF-P: inside a WTF-P action each question is the author's to answer. Ask them one call at a time, each with operator_only: true and its own options, so Clio never answers one for an absent author.");
3444
+ return {
3445
+ effects: [
3446
+ {
3447
+ kind: "rewrite_tool_input",
3448
+ args: { ...input, questions: [{ ...(questions[0] as Json), operator_only: true }] },
3449
+ reason: "WTF-P asks the author, and only the author may answer: Clio never takes a recommended option for this question.",
3450
+ },
3451
+ ],
3452
+ };
3453
+ }
3454
+
3455
+ async function guard(ctx: ExtensionContextV2, tool: string, args: unknown, event: unknown = {}): Promise<ExtensionHookResult> {
3456
+ const input = args !== null && typeof args === "object" ? (args as Json) : {};
3457
+ const effects: ExtensionEffect[] = [];
3458
+ if (!(await ctx.state.get<boolean>("protected")).value) {
3459
+ // The host's protected-artifact guard then refuses bash rm, mv, cp and redirects into the desk's own records.
3460
+ effects.push({ kind: "protect_path", path: path.join(ctx.snapshot.workspace, ".planning", "interactions"), reason: "WTF-P author answers are written only by the desk." });
3461
+ await ctx.state.set("protected", true);
3462
+ }
3463
+ let result: ExtensionHookResult = {};
3464
+ try {
3465
+ const host = hostLanding(event);
3466
+ // A host that sends facts once sends them for every call it can resolve, so a later call without them failed in Clio.
3467
+ if ((host.target || host.dispatch) && !(await ctx.state.get<boolean>("host-facts")).value) await ctx.state.set("host-facts", true);
3468
+ if (tool === "dispatch") result = await guardDispatch(ctx, input, host.dispatch, host.malformed);
3469
+ else if (tool === "ask_user") result = await guardQuestions(ctx, input);
3470
+ else if (COMMAND_TOOLS.has(tool)) {
3471
+ if (BASH_DESK_PATHS.test(JSON.stringify(input))) result = block("WTF-P write guard: commands may not touch the desk's own records under .planning.");
3472
+ } else {
3473
+ const raw = input.path ?? input.file_path ?? input.filePath;
3474
+ // The artifact tool trims its path; without one it writes under Clio's own artifact directory, where Clio's landing still says it lands.
3475
+ const target = typeof raw === "string" ? (tool === "artifact" ? raw.trim() : raw) : "";
3476
+ if (target.length > 0 || host.target) result = await guardWrite(ctx, target || "the artifact", host.target, host.malformed);
3477
+ }
3478
+ } catch (error) {
3479
+ result = block(error instanceof Error ? error.message : String(error));
3480
+ }
3481
+ return effects.length === 0 ? result : { ...result, effects: [...effects, ...(result.effects ?? [])] };
3482
+ }
3483
+
3484
+ /**
3485
+ * A note on a successful write or edit that changed a manuscript the armed
3486
+ * action may measure: its recorded word count is stale until measure_section
3487
+ * runs. It rides on the tool result, so it spends none of the turn's shared
3488
+ * continuation budget, and it reaches a dispatched worker too, whose writes
3489
+ * Clio hooks, so it says whose call the measurement is. Each section is noted
3490
+ * once until it is measured again.
3491
+ */
3492
+ async function noteManuscriptWrite(ctx: ExtensionContextV2, event: unknown): Promise<ExtensionHookResult> {
3493
+ const armed = await armedFor(ctx);
3494
+ if (!armed || !armed.produces.some((output) => output.uri.startsWith("project://paper/"))) return {};
3495
+ const target = hostLanding(event).target;
3496
+ if (!target) return {};
3497
+ const landed = writeLanding("", ctx.snapshot.workspace, target);
3498
+ if ("refused" in landed || landed.relative === null || !under("paper", landed.relative)) return {};
3499
+ const desk = loadDesk(ctx.snapshot.workspace);
3500
+ const noted = (await ctx.state.get<string[]>("measure-noted")).value ?? [];
3501
+ const sections = sectionsForPaper(desk, landed.relative)
3502
+ .map((section) => section.id)
3503
+ .filter((id) => !noted.includes(id) && declares(armed, `project://sections/${id}`, "update"));
3504
+ if (sections.length === 0) return {};
3505
+ await ctx.state.set("measure-noted", [...noted, ...sections]);
3506
+ const calls = sections.map((id) => `gateway(op="call", capability="extension_wtfp__measure_section", args={section: "${id}"})`).join(" and ");
3507
+ return {
3508
+ effects: [
3509
+ {
3510
+ kind: "annotate_tool_result",
3511
+ severity: "info",
3512
+ message: clip(
3513
+ `WTF-P: ${landed.relative} is the manuscript of ${sections.join(", ")}, so the desk's recorded word count is stale. When drafting it is done, the WTF-P action records the count with ${calls}; never count words by hand. A dispatched worker leaves this call to the action that dispatched it.`,
3514
+ "…",
3515
+ ),
3516
+ },
3517
+ ],
3518
+ };
3519
+ }
3520
+
3521
+ function arm(text: string, desk: Desk, workspace: string): Armed | null {
3522
+ const match = /^\s*\/wtfp:([a-z][a-z0-9-]*)(?:\s+(\S+))?/u.exec(text);
3523
+ if (!match) return null;
3524
+ // The driver arms nothing itself; next_step arms each step it selects.
3525
+ if (match[1] === "advance") return GUARD.actions.advance ? idleArm(workspace) : null;
3526
+ const action = GUARD.actions[match[1] as string];
3527
+ if (!action) return null;
3528
+ const candidate = match[2] ?? "";
3529
+ const sectionScoped = action.produces.some((output) => output.uri.includes("{section}"));
3530
+ const section = sectionScoped && desk.sections.some((entry) => entry.id === candidate) ? candidate : null;
3531
+ return { action: match[1] as string, produces: action.produces, section, workspace };
1159
3532
  }
1160
3533
 
1161
3534
  // --- registration ------------------------------------------------------------
@@ -1174,7 +3547,7 @@ export default function extension(api: ExtensionApiV2): void {
1174
3547
  api.handle("checkpoints", async (_args, ctx) => {
1175
3548
  const desk = await deskFor(ctx);
1176
3549
  return {
1177
- text: desk.checkpoints.map((checkpoint) => `${checkpoint.id} ${checkpoint.kind} ${checkpoint.status}`).join("\n") || "No checkpoints.",
3550
+ text: desk.checkpoints.map((checkpoint) => `${checkpoint.id} ${checkpoint.kind} ${checkpoint.status} ${checkpoint.trust}`).join("\n") || "No checkpoints.",
1178
3551
  card: checkpointsCard(desk),
1179
3552
  };
1180
3553
  });
@@ -1185,6 +3558,12 @@ export default function extension(api: ExtensionApiV2): void {
1185
3558
  return next.command ? { text: next.command, prompt: { fill: next.command } } : { text: next.reason, toast: { text: next.reason } };
1186
3559
  });
1187
3560
  api.action("gates", async (_event, ctx) => startGates(ctx));
3561
+ api.action("advance", async (_event, ctx) => {
3562
+ const command = commandFor(ctx.snapshot.plugin ?? null, "advance");
3563
+ return command
3564
+ ? { text: command, prompt: { fill: command } }
3565
+ : { text: "advance needs the WTF-P plugin.", toast: { text: "advance needs the WTF-P plugin." } };
3566
+ });
1188
3567
  api.action("validate", async (_event, ctx) => validateAll(ctx));
1189
3568
  api.action("help", async (_event, ctx) => helpCard(ctx.snapshot.plugin ?? null));
1190
3569
  api.action("section", async (event, ctx) => {
@@ -1200,105 +3579,323 @@ export default function extension(api: ExtensionApiV2): void {
1200
3579
  });
1201
3580
 
1202
3581
  api.tool("record", async (input, ctx) => {
1203
- const { uri, record, expect_revision } = input as { uri: string; record: Json; expect_revision?: number };
1204
3582
  try {
1205
- const written = writePortableRecord(ctx.snapshot.workspace, uri, record, expect_revision);
3583
+ return await recordTool(ctx, (input ?? {}) as Json);
3584
+ } catch (error) {
3585
+ return { text: failure("Not written", error), isError: true };
3586
+ }
3587
+ });
3588
+ api.tool("status", async (_input, ctx) => {
3589
+ const desk = await deskFor(ctx);
3590
+ return { text: progressText(desk), data: statusDigest(desk) };
3591
+ });
3592
+ api.tool("read_record", async (input, ctx) => {
3593
+ try {
3594
+ return readTool(ctx, await deskFor(ctx), String((input as Json).uri ?? ""));
3595
+ } catch (error) {
3596
+ return { text: `Not read: ${error instanceof Error ? error.message : String(error)}`, isError: true };
3597
+ }
3598
+ });
3599
+ api.tool("readiness", async (input, ctx) => {
3600
+ try {
3601
+ const report = readiness(await deskFor(ctx), String((input as Json).section ?? ""));
1206
3602
  return {
1207
- text: `Wrote ${uri}${written.revision === null ? "" : ` at revision ${written.revision}`}; it validated and read back.`,
1208
- data: { uri, file: written.file, revision: written.revision },
3603
+ text:
3604
+ report.ready === true
3605
+ ? `${String(report.section)} may be drafted: ${(report.plan as Json).reason as string}. ${coverage.STRUCTURAL_SCOPE}`
3606
+ : `${String(report.section)} may not be drafted yet: ${(report.reasons as string[]).join("; ")}.`,
3607
+ data: report,
1209
3608
  };
1210
3609
  } catch (error) {
1211
- return { text: `Not written: ${error instanceof Error ? error.message : String(error)}`, isError: true };
3610
+ return { text: `No readiness: ${error instanceof Error ? error.message : String(error)}`, isError: true };
3611
+ }
3612
+ });
3613
+ api.tool("archive", async (input, ctx) => {
3614
+ try {
3615
+ const desk = await deskFor(ctx);
3616
+ const made = archiveProject(ctx.snapshot.workspace, String((input as Json).archive ?? ""), await armedFor(ctx), desk.projectId);
3617
+ return {
3618
+ text: `Archived ${made.files} files to ${made.uri}; its manifest ${made.manifest} has sha256 ${made.sha256} and lists each file's sha256. Record the archive in the manifest and state as the procedure says.`,
3619
+ data: made,
3620
+ };
3621
+ } catch (error) {
3622
+ return { text: failure("Not archived", error), isError: true };
1212
3623
  }
1213
3624
  });
1214
3625
  api.tool("measure_section", async (input, ctx) => {
1215
3626
  try {
1216
- const measured = measureSection(ctx.snapshot.workspace, (input as { section: string }).section);
3627
+ const sectionId = String((input as Json).section ?? "");
3628
+ const measured = measureSection(ctx.snapshot.workspace, sectionId, await storedKey(ctx, false), await armedFor(ctx));
3629
+ const noted = (await ctx.state.get<string[]>("measure-noted")).value ?? [];
3630
+ if (noted.includes(sectionId)) await ctx.state.set("measure-noted", noted.filter((id) => id !== sectionId));
1217
3631
  const share = measured.target > 0 ? Math.round((measured.words / measured.target) * 100) : null;
1218
3632
  return {
1219
- text: `${measured.file ?? "the manuscript"} has ${measured.words} body words${share === null ? "" : ` (${share}% of ${measured.target}; within 15% counts as on target)`}. Recorded in the section and state records; the paper totals ${measured.total}. ${WORD_METHOD}`,
3633
+ text: `${measured.file ?? "the manuscript"} has ${measured.words} body words${share === null ? "" : ` (${share}% of ${measured.target}; within 15% counts as on target)`}. ${measured.recorded ? `Recorded in the section and state records, which committed together; the paper totals ${measured.total}.` : `Not recorded: ${actionName(ctx.snapshot.plugin ?? null, (await armedFor(ctx))?.action ?? "this action")} does not update the section's word count; use this count instead of counting by hand.`} ${WORD_METHOD}`,
1220
3634
  data: measured,
1221
3635
  };
1222
3636
  } catch (error) {
1223
- return { text: `Not measured: ${error instanceof Error ? error.message : String(error)}`, isError: true };
3637
+ return { text: failure("Not measured", error), isError: true };
1224
3638
  }
1225
3639
  });
3640
+ api.tool("next_step", async (_input, ctx) => {
3641
+ const workspace = ctx.snapshot.workspace;
3642
+ const drive = (await ctx.state.get<Drive>("drive")).value;
3643
+ if (!drive || drive.workspace !== workspace)
3644
+ return { text: "Only a /wtfp:advance turn can ask the desk for its next step; nothing was armed.", isError: true };
3645
+ let desk = await deskFor(ctx);
3646
+ let recovered: string | null = null;
3647
+ if (desk.journal) {
3648
+ try {
3649
+ recovered = withLock(workspace, () => recover(workspace));
3650
+ } catch (error) {
3651
+ await ctx.state.set("armed", idleArm(workspace));
3652
+ return { text: `${failure("An interrupted record write could not be completed, so the run stops", error)} ${DRIVER_RULE}`, data: { kind: "stop" }, isError: true };
3653
+ }
3654
+ desk = await deskFor(ctx);
3655
+ }
3656
+ const decision = driveStep(desk, drive);
3657
+ const lead = recovered ? `${recovered} ` : "";
3658
+ if (decision.kind !== "step") {
3659
+ // Between steps and after the last one, nothing stays armed for writing.
3660
+ await ctx.state.set("armed", idleArm(workspace));
3661
+ if (decision.kind === "gate") {
3662
+ await ctx.state.set("drive", { ...drive, asked: [...drive.asked, decision.checkpoint] } satisfies Drive);
3663
+ return { text: `${lead}Gate ${decision.checkpoint}: ${decision.reason} Call extension_wtfp__gate with checkpoint ${decision.checkpoint}. ${DRIVER_RULE}`, data: decision };
3664
+ }
3665
+ return { text: `${lead}Stop: ${decision.reason} ${DRIVER_RULE}`, data: decision };
3666
+ }
3667
+ const contract = GUARD.actions[decision.action] as GuardAction;
3668
+ await ctx.state.set("armed", { action: decision.action, produces: contract.produces, section: decision.section, workspace } satisfies Armed);
3669
+ await ctx.state.set("drive", {
3670
+ ...drive,
3671
+ steps: [...drive.steps, { action: decision.action, section: decision.section, fingerprint: driveFingerprint(desk), ...(decision.finish ? { finish: true } : {}) }],
3672
+ } satisfies Drive);
3673
+ const invocation = `/wtfp:${decision.action}${decision.section ? ` ${decision.section}` : ""}`;
3674
+ return {
3675
+ text: `${lead}Step ${drive.steps.length + 1}: ${invocation}. ${decision.reason} The write guard is armed for ${decision.action}${decision.section ? ` ${decision.section}` : ""} only. Read and follow ${stepPrompt(decision.prompt)} with ${decision.section ? `invocation input ${decision.section}` : "no invocation input"}. ${DRIVER_RULE}`,
3676
+ data: decision,
3677
+ };
3678
+ });
1226
3679
  api.tool("gate", async (input, ctx) => {
1227
- const id = (input as { checkpoint: string }).checkpoint;
1228
- const checkpoint = loadDesk(ctx.snapshot.workspace).checkpoints.find((entry) => entry.id === id);
3680
+ const id = String((input as Json).checkpoint ?? "");
3681
+ const desk = await deskFor(ctx);
3682
+ const checkpoint = desk.checkpoints.find((entry) => entry.id === id);
1229
3683
  if (!checkpoint) return { text: `No checkpoint ${id}.`, isError: true };
1230
- if (checkpoint.status !== "pending") return { text: `${id} is already ${checkpoint.status}.` };
1231
- return { text: `Asking the author: ${checkpoint.request}`, interview: { id: "gate-one", title: "WTF-P gate", total: 1, step: gateStep(checkpoint) } };
3684
+ if (!askable(desk, []).includes(checkpoint)) return { text: `${id} is already ${checkpoint.status}${checkpoint.trust === "attested" ? " by the author at this desk" : ""}.` };
3685
+ return { text: `Asking the author: ${checkpoint.request}`, interview: { id: "gate-one", title: "WTF-P gate", total: 1, step: await ask(ctx, desk, checkpoint) } };
1232
3686
  });
1233
- api.interview("gate-one", async (answer, ctx) => {
1234
- if (answer.nav === "cancel") return { done: true, text: "The author did not answer; the gate stays pending." };
1235
- const checkpoint = loadDesk(ctx.snapshot.workspace).checkpoints.find((entry) => entry.id === answer.step);
1236
- const choice = answer.answers.choice;
1237
- const picked = Array.isArray(choice) ? choice[0] : choice;
1238
- if (!checkpoint || checkpoint.status !== "pending" || typeof picked !== "string")
1239
- return { done: true, text: "The gate changed while it was asked; nothing was recorded." };
1240
- if (picked === KEEP) return { done: true, text: `The author kept ${checkpoint.id} pending.` };
1241
- const recorded = resolveGate(ctx.snapshot.workspace, checkpoint, picked);
1242
- return { done: true, text: `Recorded the author's answer: ${recorded}.`, ...(await picture(ctx)) };
3687
+ api.interview("gate-one", async (event, ctx): Promise<InterviewNext> => {
3688
+ if (event.nav === "cancel")
3689
+ return {
3690
+ done: true,
3691
+ text:
3692
+ event.reason === "headless"
3693
+ ? "No author could be asked in this headless session; the gate stays pending and authorizes nothing."
3694
+ : "The author did not answer; the gate stays pending.",
3695
+ };
3696
+ try {
3697
+ const typed = await freeText(ctx, event);
3698
+ if (typed?.checkpoint) {
3699
+ const desk = await deskFor(ctx);
3700
+ const current = desk.checkpoints.find((entry) => entry.id === typed.checkpoint);
3701
+ if (current && askable(desk, []).includes(current)) return { step: await ask(ctx, desk, current, FREE_TEXT), total: 1 };
3702
+ }
3703
+ const result = typed ?? (await answer(ctx, event.step, choiceOf(event.answers), noteOf(event)));
3704
+ if (result.kind === "stale" && result.checkpoint) {
3705
+ const desk = await deskFor(ctx);
3706
+ const current = desk.checkpoints.find((entry) => entry.id === result.checkpoint);
3707
+ if (current && askable(desk, []).includes(current)) return { step: await ask(ctx, desk, current), total: 1 };
3708
+ }
3709
+ if (result.kind === "recorded") return { done: true, text: `Recorded the author's answer: ${result.text}.`, ...(await picture(ctx)) };
3710
+ if (result.kind === "kept") return { done: true, text: `The author kept ${result.checkpoint} pending.`, ...(await picture(ctx)) };
3711
+ return { done: true, text: result.text };
3712
+ } catch (error) {
3713
+ return { done: true, text: failure("Nothing was recorded", error) };
3714
+ }
1243
3715
  });
1244
- api.interview("gate", async (answer, ctx) => {
1245
- if (answer.nav === "cancel")
1246
- return { done: true, text: "Gates left as they were.", toast: { text: "WTF-P gates unchanged" }, ...(await picture(ctx)) };
3716
+ api.interview("gate", async (event, ctx): Promise<InterviewNext> => {
3717
+ if (event.nav === "cancel")
3718
+ return {
3719
+ done: true,
3720
+ text: event.reason === "headless" ? "No author could be asked in this headless session; gates left as they were." : "Gates left as they were.",
3721
+ toast: { text: "WTF-P gates unchanged" },
3722
+ ...(await picture(ctx)),
3723
+ };
1247
3724
  const kept = (await ctx.state.get<string[]>("gate-kept")).value ?? [];
1248
- const desk = await deskFor(ctx);
1249
- const checkpoint = desk.checkpoints.find((entry) => entry.id === answer.step);
1250
- const choice = answer.answers.choice;
1251
- const picked = Array.isArray(choice) ? choice[0] : choice;
1252
- const recorded: string[] = (await ctx.state.get<string[]>("gate-recorded")).value ?? [];
1253
- if (checkpoint && checkpoint.status === "pending" && typeof picked === "string") {
1254
- if (picked === KEEP) kept.push(checkpoint.id);
1255
- else recorded.push(resolveGate(ctx.snapshot.workspace, checkpoint, picked));
3725
+ const recorded = (await ctx.state.get<string[]>("gate-recorded")).value ?? [];
3726
+ let note = "";
3727
+ try {
3728
+ const typed = await freeText(ctx, event);
3729
+ if (typed?.checkpoint) {
3730
+ const desk = await deskFor(ctx);
3731
+ const current = desk.checkpoints.find((entry) => entry.id === typed.checkpoint);
3732
+ const remaining = askable(desk, kept);
3733
+ if (current && remaining.includes(current)) return { step: await ask(ctx, desk, current, FREE_TEXT), total: remaining.length + recorded.length + kept.length };
3734
+ }
3735
+ const result = typed ?? (await answer(ctx, event.step, choiceOf(event.answers), noteOf(event)));
3736
+ if (result.kind === "recorded") recorded.push(result.text);
3737
+ else if (result.kind === "kept" && result.checkpoint) kept.push(result.checkpoint);
3738
+ else if (result.kind === "refused") {
3739
+ note = result.text;
3740
+ if (result.checkpoint) kept.push(result.checkpoint);
3741
+ }
3742
+ } catch (error) {
3743
+ note = failure("Nothing was recorded", error);
1256
3744
  }
1257
3745
  await ctx.state.set("gate-kept", kept);
1258
3746
  await ctx.state.set("gate-recorded", recorded);
1259
- const remaining = pendingGates(loadDesk(ctx.snapshot.workspace), kept);
3747
+ const desk = await deskFor(ctx);
3748
+ const remaining = askable(desk, kept);
1260
3749
  const next = remaining[0];
1261
- if (next) return { step: gateStep(next), total: remaining.length + recorded.length + kept.length };
3750
+ if (next && !note.startsWith("Nothing was recorded")) return { step: await ask(ctx, desk, next), total: remaining.length + recorded.length + kept.length };
1262
3751
  await ctx.state.set("gate-recorded", []);
1263
- const summary = recorded.length > 0 ? `Recorded: ${recorded.join("; ")}.` : "Nothing recorded.";
3752
+ const summary = [recorded.length > 0 ? `Recorded: ${recorded.join("; ")}.` : "Nothing recorded.", note].filter(Boolean).join(" ");
1264
3753
  return {
1265
3754
  done: true,
1266
3755
  text: summary,
1267
- card: { t: "text", text: `✓ ${summary}`, tone: recorded.length > 0 ? "positive" : "muted", wrap: "wrap" },
1268
- ...(await picture(ctx)),
3756
+ card: { t: "text", text: `${recorded.length > 0 ? "✓" : "·"} ${summary}`, tone: recorded.length > 0 ? "positive" : "muted", wrap: "wrap" },
3757
+ ...(await picture(ctx, desk)),
1269
3758
  };
1270
3759
  });
3760
+ api.interview("confirm-write", async (event, ctx): Promise<InterviewNext> => {
3761
+ const nonce = /^confirm\.([a-f0-9]{12})$/u.exec(event.step)?.[1];
3762
+ const pending = nonce ? (await ctx.state.get<PendingConfirm>(`confirm:${nonce}`)).value : undefined;
3763
+ if (nonce) await ctx.state.delete(`confirm:${nonce}`);
3764
+ if (!pending) return { done: true, text: "That answer matches no open question; nothing was written." };
3765
+ if (event.nav === "cancel")
3766
+ return { done: true, text: event.reason === "headless" ? "No author could be asked; the change was not written." : "The author did not answer; the change was not written." };
3767
+ const workspace = ctx.snapshot.workspace;
3768
+ const picked = choiceOf(event.answers);
3769
+ if (pending.workspace !== workspace) return { done: true, text: "That answer was given for another project; nothing was written." };
3770
+ if (picked !== "approve" && picked !== "decline") return { done: true, text: "That answer is not one of the options offered; nothing was written." };
3771
+ const key = await storedKey(ctx, true);
3772
+ if (key === null) return { done: true, text: "The desk could not establish its seal key; nothing was written." };
3773
+ try {
3774
+ const outcome = withLock(workspace, () => {
3775
+ recover(workspace);
3776
+ const file = artifactFile(workspace, pending.write.uri);
3777
+ const current = file === null ? null : readBytes(workspace, file);
3778
+ const stale = (current === null ? null : sha256(current)) !== pending.base_sha256 || sha256(canonical(pending.write.record)) !== pending.content_sha256;
3779
+ const prepared = stale || picked === "decline" ? null : prepare(workspace, pending.write, "desk", null);
3780
+ const interaction = sealed(
3781
+ {
3782
+ schema: "wtfp.project.interaction/v1",
3783
+ id: interactionId(),
3784
+ project_id: pending.project ?? readRecord(workspace, ".planning/project.json")?.id,
3785
+ kind: "record-change",
3786
+ subject_uri: pending.write.uri,
3787
+ channel: "attested-interview",
3788
+ outcome: stale ? "discarded-stale" : picked === "approve" ? "approved" : "declined",
3789
+ presented: { content_sha256: pending.content_sha256, options: ["approve", "decline"], ...(pending.base_sha256 ? { base_sha256: pending.base_sha256 } : {}) },
3790
+ asked_at: pending.asked_at,
3791
+ answered_at: timestamp(),
3792
+ },
3793
+ key,
3794
+ );
3795
+ const writes = [prepare(workspace, { uri: `project://interactions/${String(interaction.id)}`, record: interaction }, "desk", null).write];
3796
+ if (prepared) writes.push(prepared.write);
3797
+ commit(workspace, writes);
3798
+ return stale ? "stale" : picked;
3799
+ });
3800
+ return {
3801
+ done: true,
3802
+ text:
3803
+ outcome === "stale"
3804
+ ? `${pending.write.uri} changed while the author was asked; nothing was written. Read it again and propose the change anew.`
3805
+ : outcome === "approve"
3806
+ ? `The author approved the change; ${pending.write.uri} was written: ${pending.changes.join("; ")}.`
3807
+ : `The author kept the current settings; ${pending.write.uri} was not changed.`,
3808
+ ...(await picture(ctx)),
3809
+ };
3810
+ } catch (error) {
3811
+ return { done: true, text: failure("Nothing was written", error) };
3812
+ }
3813
+ });
1271
3814
 
1272
3815
  api.hook("prompt_submit", async (event, ctx) => {
3816
+ // Clio continuing a stopped yolo turn (tool budget, loop guard, a failure) resumes that turn's drive and armed step.
3817
+ const held = (await ctx.state.get<{ armed?: Armed; drive?: Drive; workspace: string }>("held")).value;
3818
+ await ctx.state.delete("held");
3819
+ if (event.point === "prompt_submit" && (event as { origin?: string }).origin === "continuation") {
3820
+ if (held && held.workspace === ctx.snapshot.workspace) {
3821
+ if (held.armed) await ctx.state.set("armed", held.armed);
3822
+ if (held.drive) await ctx.state.set("drive", held.drive);
3823
+ }
3824
+ return {};
3825
+ }
1273
3826
  const typed = event.point === "prompt_submit" ? (event.text ?? "") : "";
1274
- const match = /^\s*\/wtfp:([a-z][a-z0-9-]*)\b/u.exec(typed);
1275
- const roots = match ? GUARD.actions[match[1] as string] : undefined;
1276
- if (!match || !roots) {
3827
+ const desk = loadDesk(ctx.snapshot.workspace);
3828
+ const armed = arm(typed, desk, ctx.snapshot.workspace);
3829
+ // Only a prompt that starts an advance run starts a drive; any other prompt ends one.
3830
+ await ctx.state.delete("drive");
3831
+ await ctx.state.delete("measure-noted");
3832
+ if (!armed) {
1277
3833
  await ctx.state.delete("armed");
1278
3834
  return {};
1279
3835
  }
1280
- await ctx.state.set("armed", { action: match[1], roots } satisfies Armed);
3836
+ await ctx.state.set("armed", armed);
3837
+ if (armed.action === "advance") {
3838
+ await ctx.state.set("drive", { workspace: ctx.snapshot.workspace, steps: [], asked: [] } satisfies Drive);
3839
+ return {
3840
+ effects: [
3841
+ {
3842
+ kind: "notify_operator",
3843
+ key: "wtfp-guard",
3844
+ message: "WTF-P driver armed: the desk picks each step from the project and confines it to that action's contract; it stops at the first gate only you can answer.",
3845
+ },
3846
+ ],
3847
+ };
3848
+ }
3849
+ const roots = writeRoots(desk, armed);
1281
3850
  return {
1282
3851
  effects: [
1283
3852
  {
1284
3853
  kind: "notify_operator",
1285
3854
  key: "wtfp-guard",
1286
- message: `WTF-P write guard armed for ${actionName(ctx.snapshot.plugin ?? null, match[1] as string)}: write and edit stay under ${roots.join(", ")}.`,
3855
+ message: `WTF-P write guard armed for ${actionName(ctx.snapshot.plugin ?? null, armed.action)}${armed.section ? ` ${armed.section}` : ""}: files stay under ${roots.join(", ") || "nothing"}, records under what it declares.`,
1287
3856
  },
1288
3857
  ],
1289
3858
  };
1290
3859
  });
1291
- api.hook("before_tool", async (event, ctx) =>
1292
- event.point === "before_tool" ? guard(ctx, event.args) : {},
1293
- );
3860
+ api.hook("before_tool", async (event, ctx) => (event.point === "before_tool" ? guard(ctx, event.tool, event.args, event) : {}));
3861
+ api.hook("after_tool", async (event, ctx) => (event.point === "after_tool" && event.outcome === "ok" ? noteManuscriptWrite(ctx, event) : {}));
3862
+ // A WTF-P turn starts from the desk's picture of the project, so the action need not rebuild it from records.
3863
+ api.hook("turn_start", async (event, ctx) => {
3864
+ if (event.point !== "turn_start" || !(await armedFor(ctx))) return {};
3865
+ const desk = await deskFor(ctx);
3866
+ if (!desk.present) return {};
3867
+ return { effects: [{ kind: "inject_reminder", audience: "model", severity: "info", message: statusReminder(desk) }] };
3868
+ });
1294
3869
 
1295
- api.on("session_open", async (_event, ctx) => ({ text: "", ...(await picture(ctx)) }));
3870
+ api.on("session_open", async (_event, ctx) => {
3871
+ const workspace = ctx.snapshot.workspace;
3872
+ let recovered: string | null = null;
3873
+ try {
3874
+ if (contained(workspace, JOURNAL) !== null && existsSync(path.join(workspace, JOURNAL))) recovered = withLock(workspace, () => recover(workspace));
3875
+ } catch (error) {
3876
+ recovered = `An interrupted write could not be completed: ${error instanceof Error ? error.message : String(error)}`;
3877
+ }
3878
+ return { text: recovered ?? "", ...(recovered ? { toast: { text: recovered, tone: "warning" as const } } : {}), ...(await picture(ctx)) };
3879
+ });
3880
+ api.on("turn_end", async (_event, ctx) => {
3881
+ // An action arms for the turn its command starts; nothing it allowed outlives that turn. Clio's own
3882
+ // continuation of the turn may resume it, so the desk holds what it had until the next prompt says whose it is.
3883
+ const armed = (await ctx.state.get<Armed>("armed")).value;
3884
+ const drive = (await ctx.state.get<Drive>("drive")).value;
3885
+ if (armed || drive) await ctx.state.set("held", { ...(armed ? { armed } : {}), ...(drive ? { drive } : {}), workspace: ctx.snapshot.workspace });
3886
+ await ctx.state.delete("armed");
3887
+ await ctx.state.delete("drive");
3888
+ await ctx.state.delete("measure-noted");
3889
+ return undefined;
3890
+ });
1296
3891
  api.on("workspace_enter", async (_event, ctx) => ({ text: "", ...(await picture(ctx)) }));
1297
3892
  // Leaving means the desk no longer holds the screen, whatever the snapshot says yet.
1298
3893
  api.on("workspace_leave", async (_event, ctx) => ({ text: "", ...(await picture(ctx, undefined, null)) }));
1299
3894
  api.on("fs_changed", async (event, ctx) => {
1300
3895
  if (event.event !== "fs_changed") return undefined;
1301
- const records = event.paths.filter((file) => file.startsWith(".planning/") && file.endsWith(".json") && !file.includes("/archives/"));
3896
+ const records = event.paths.filter(
3897
+ (file) => file.startsWith(".planning/") && file.endsWith(".json") && !file.includes("/archives/") && !/(^|\/)\./u.test(file.slice(".planning/".length)),
3898
+ );
1302
3899
  const card = records.length > 0 ? await revalidate(ctx, records) : undefined;
1303
3900
  return { text: "", ...(card ? { card } : {}), ...(await picture(ctx)) };
1304
3901
  });