wtf-p 0.8.0 → 0.8.1

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 (471) hide show
  1. package/README.md +10 -10
  2. package/bin/lib/adapter-compiler.js +154 -35
  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/checkpoint.json +10 -1
  7. package/protocol/actions/execute-outline.json +10 -2
  8. package/protocol/actions/export-latex.json +15 -2
  9. package/protocol/actions/plan-revision.json +17 -4
  10. package/protocol/actions/polish-prose.json +13 -3
  11. package/protocol/actions/research-gap.json +16 -3
  12. package/protocol/actions/verify-work.json +7 -2
  13. package/protocol/project/README.md +37 -0
  14. package/protocol/project/schemas/interaction.schema.json +100 -0
  15. package/protocol/project/templates/interaction.json +16 -0
  16. package/protocol/skills/wtfp-deliver-research/SKILL.md +1 -1
  17. package/protocol/skills/wtfp-deliver-research/references/actions.md +2 -2
  18. package/protocol/skills/wtfp-plan-section/SKILL.md +1 -1
  19. package/protocol/skills/wtfp-plan-section/references/actions.md +4 -3
  20. package/protocol/skills/wtfp-research-literature/SKILL.md +1 -1
  21. package/protocol/skills/wtfp-review-manuscript/SKILL.md +1 -1
  22. package/protocol/skills/wtfp-write-section/SKILL.md +1 -1
  23. package/protocol/skills/wtfp-write-section/references/actions.md +1 -1
  24. package/protocol/workflows/checkpoint.md +2 -2
  25. package/protocol/workflows/execute-outline.md +2 -2
  26. package/protocol/workflows/export-latex.md +4 -4
  27. package/protocol/workflows/plan-revision.md +4 -3
  28. package/protocol/workflows/plan-section.md +2 -2
  29. package/protocol/workflows/polish-prose.md +3 -3
  30. package/protocol/workflows/research-gap.md +2 -2
  31. package/protocol/workflows/verify-work.md +3 -3
  32. package/protocol/workflows/write-section.md +2 -2
  33. package/vendors/antigravity/.wtfp-generated.json +172 -172
  34. package/vendors/antigravity/actions/checkpoint.json +10 -1
  35. package/vendors/antigravity/actions/execute-outline.json +10 -2
  36. package/vendors/antigravity/actions/export-latex.json +15 -2
  37. package/vendors/antigravity/actions/plan-revision.json +17 -4
  38. package/vendors/antigravity/actions/polish-prose.json +13 -3
  39. package/vendors/antigravity/actions/research-gap.json +16 -3
  40. package/vendors/antigravity/actions/verify-work.json +7 -2
  41. package/vendors/antigravity/plugin.json +2 -1
  42. package/vendors/antigravity/project/README.md +37 -0
  43. package/vendors/antigravity/project/schemas/interaction.schema.json +100 -0
  44. package/vendors/antigravity/project/templates/interaction.json +16 -0
  45. package/vendors/antigravity/rules/wtfp-project-state.md +41 -1
  46. package/vendors/antigravity/{commands/wtfp-add-todo.md → skills/wtfp-add-todo/SKILL.md} +2 -1
  47. package/vendors/antigravity/{commands/wtfp-analyze-bib.md → skills/wtfp-analyze-bib/SKILL.md} +2 -1
  48. package/vendors/antigravity/{commands/wtfp-audit-milestone.md → skills/wtfp-audit-milestone/SKILL.md} +2 -1
  49. package/vendors/antigravity/{commands/wtfp-check-refs.md → skills/wtfp-check-refs/SKILL.md} +2 -1
  50. package/vendors/antigravity/{commands/wtfp-check-todos.md → skills/wtfp-check-todos/SKILL.md} +2 -1
  51. package/vendors/antigravity/{commands/wtfp-checkpoint.md → skills/wtfp-checkpoint/SKILL.md} +4 -3
  52. package/vendors/antigravity/{commands/wtfp-contribute.md → skills/wtfp-contribute/SKILL.md} +2 -1
  53. package/vendors/antigravity/{commands/wtfp-create-outline.md → skills/wtfp-create-outline/SKILL.md} +2 -1
  54. package/vendors/antigravity/{commands/wtfp-create-poster.md → skills/wtfp-create-poster/SKILL.md} +2 -1
  55. package/vendors/antigravity/{commands/wtfp-create-slides.md → skills/wtfp-create-slides/SKILL.md} +2 -1
  56. package/vendors/antigravity/skills/wtfp-deliver-research/SKILL.md +1 -1
  57. package/vendors/antigravity/skills/wtfp-deliver-research/references/actions.md +2 -2
  58. package/vendors/antigravity/{commands/wtfp-discuss-section.md → skills/wtfp-discuss-section/SKILL.md} +2 -1
  59. package/vendors/antigravity/{commands/wtfp-execute-outline.md → skills/wtfp-execute-outline/SKILL.md} +4 -3
  60. package/vendors/antigravity/{commands/wtfp-export-latex.md → skills/wtfp-export-latex/SKILL.md} +2 -1
  61. package/vendors/antigravity/{commands/wtfp-help.md → skills/wtfp-help/SKILL.md} +3 -2
  62. package/vendors/antigravity/{commands/wtfp-insert-section.md → skills/wtfp-insert-section/SKILL.md} +2 -1
  63. package/vendors/antigravity/{commands/wtfp-list-assumptions.md → skills/wtfp-list-assumptions/SKILL.md} +2 -1
  64. package/vendors/antigravity/{commands/wtfp-map-project.md → skills/wtfp-map-project/SKILL.md} +2 -1
  65. package/vendors/antigravity/{commands/wtfp-new-paper.md → skills/wtfp-new-paper/SKILL.md} +2 -1
  66. package/vendors/antigravity/{commands/wtfp-pause-writing.md → skills/wtfp-pause-writing/SKILL.md} +2 -1
  67. package/vendors/antigravity/{commands/wtfp-plan-milestone-gaps.md → skills/wtfp-plan-milestone-gaps/SKILL.md} +2 -1
  68. package/vendors/antigravity/{commands/wtfp-plan-revision.md → skills/wtfp-plan-revision/SKILL.md} +10 -4
  69. package/vendors/antigravity/skills/wtfp-plan-section/SKILL.md +1 -1
  70. package/vendors/antigravity/skills/wtfp-plan-section/references/actions.md +4 -3
  71. package/vendors/antigravity/{commands/wtfp-polish-prose.md → skills/wtfp-polish-prose/SKILL.md} +9 -4
  72. package/vendors/antigravity/{commands/wtfp-progress.md → skills/wtfp-progress/SKILL.md} +2 -1
  73. package/vendors/antigravity/{commands/wtfp-quick.md → skills/wtfp-quick/SKILL.md} +2 -1
  74. package/vendors/antigravity/{commands/wtfp-remove-section.md → skills/wtfp-remove-section/SKILL.md} +2 -1
  75. package/vendors/antigravity/{commands/wtfp-report-bug.md → skills/wtfp-report-bug/SKILL.md} +2 -1
  76. package/vendors/antigravity/{commands/wtfp-request-feature.md → skills/wtfp-request-feature/SKILL.md} +2 -1
  77. package/vendors/antigravity/{commands/wtfp-research-gap.md → skills/wtfp-research-gap/SKILL.md} +2 -1
  78. package/vendors/antigravity/skills/wtfp-research-literature/SKILL.md +1 -1
  79. package/vendors/antigravity/{commands/wtfp-resume-writing.md → skills/wtfp-resume-writing/SKILL.md} +2 -1
  80. package/vendors/antigravity/skills/wtfp-review-manuscript/SKILL.md +1 -1
  81. package/vendors/antigravity/{commands/wtfp-review-section.md → skills/wtfp-review-section/SKILL.md} +2 -1
  82. package/vendors/antigravity/{commands/wtfp-settings.md → skills/wtfp-settings/SKILL.md} +2 -1
  83. package/vendors/antigravity/{commands/wtfp-submit-milestone.md → skills/wtfp-submit-milestone/SKILL.md} +2 -1
  84. package/vendors/antigravity/{commands/wtfp-update.md → skills/wtfp-update/SKILL.md} +2 -1
  85. package/vendors/antigravity/{commands/wtfp-verify-work.md → skills/wtfp-verify-work/SKILL.md} +5 -4
  86. package/vendors/antigravity/skills/wtfp-write-section/SKILL.md +1 -1
  87. package/vendors/antigravity/skills/wtfp-write-section/references/actions.md +1 -1
  88. package/vendors/antigravity/workflows/checkpoint.md +2 -2
  89. package/vendors/antigravity/workflows/execute-outline.md +2 -2
  90. package/vendors/antigravity/workflows/export-latex.md +4 -4
  91. package/vendors/antigravity/workflows/plan-revision.md +4 -3
  92. package/vendors/antigravity/workflows/plan-section.md +2 -2
  93. package/vendors/antigravity/workflows/polish-prose.md +3 -3
  94. package/vendors/antigravity/workflows/research-gap.md +2 -2
  95. package/vendors/antigravity/workflows/verify-work.md +3 -3
  96. package/vendors/antigravity/workflows/write-section.md +2 -2
  97. package/vendors/claude/.claude-plugin/marketplace.json +2 -2
  98. package/vendors/claude/.claude-plugin/plugin.json +1 -1
  99. package/vendors/claude/.wtfp-generated.json +84 -76
  100. package/vendors/claude/actions/checkpoint.json +10 -1
  101. package/vendors/claude/actions/execute-outline.json +10 -2
  102. package/vendors/claude/actions/export-latex.json +15 -2
  103. package/vendors/claude/actions/plan-revision.json +17 -4
  104. package/vendors/claude/actions/polish-prose.json +13 -3
  105. package/vendors/claude/actions/research-gap.json +16 -3
  106. package/vendors/claude/actions/verify-work.json +7 -2
  107. package/vendors/claude/ai.iowarp.clio/agents/wtfp-argument-verifier.md +3 -3
  108. package/vendors/claude/ai.iowarp.clio/agents/wtfp-coherence-checker.md +3 -3
  109. package/vendors/claude/ai.iowarp.clio/agents/wtfp-plan-checker.md +3 -3
  110. package/vendors/claude/ai.iowarp.clio/agents/wtfp-section-reviewer.md +3 -3
  111. package/vendors/claude/ai.iowarp.clio/fleets/wtfp-draft-review.md +1 -1
  112. package/vendors/claude/ai.iowarp.clio/fleets/wtfp-plan-section.md +1 -1
  113. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/add-todo.md +8 -0
  114. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/analyze-bib.md +22 -0
  115. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/audit-milestone.md +10 -0
  116. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/check-refs.md +22 -0
  117. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/check-todos.md +9 -0
  118. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/checkpoint.md +11 -2
  119. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/create-outline.md +21 -0
  120. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/create-poster.md +9 -0
  121. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/create-slides.md +9 -0
  122. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/discuss-section.md +9 -0
  123. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/execute-outline.md +24 -3
  124. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/export-latex.md +14 -4
  125. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/help.md +1 -1
  126. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/insert-section.md +9 -0
  127. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/list-assumptions.md +6 -0
  128. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/map-project.md +8 -0
  129. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/new-paper.md +9 -0
  130. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/pause-writing.md +8 -0
  131. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/plan-milestone-gaps.md +9 -0
  132. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/plan-revision.md +17 -3
  133. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/plan-section.md +24 -3
  134. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/polish-prose.md +28 -3
  135. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/progress.md +7 -0
  136. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/quick.md +21 -0
  137. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/research-gap.md +25 -2
  138. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/resume-writing.md +9 -0
  139. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/review-section.md +19 -1
  140. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/settings.md +9 -0
  141. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/submit-milestone.md +9 -0
  142. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/verify-work.md +12 -3
  143. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/write-section.md +24 -3
  144. package/vendors/claude/commands/checkpoint.md +2 -2
  145. package/vendors/claude/commands/execute-outline.md +2 -2
  146. package/vendors/claude/commands/export-latex.md +4 -4
  147. package/vendors/claude/commands/plan-revision.md +8 -3
  148. package/vendors/claude/commands/plan-section.md +2 -2
  149. package/vendors/claude/commands/polish-prose.md +7 -3
  150. package/vendors/claude/commands/research-gap.md +2 -2
  151. package/vendors/claude/commands/verify-work.md +3 -3
  152. package/vendors/claude/commands/write-section.md +2 -2
  153. package/vendors/claude/output-styles/wtfp-academic-writing.md +5 -5
  154. package/vendors/claude/plugin.json +1 -1
  155. package/vendors/claude/project/README.md +37 -0
  156. package/vendors/claude/project/schemas/interaction.schema.json +100 -0
  157. package/vendors/claude/project/templates/interaction.json +16 -0
  158. package/vendors/claude/skills/wtfp-deliver-research/SKILL.md +1 -1
  159. package/vendors/claude/skills/wtfp-deliver-research/references/actions.md +2 -2
  160. package/vendors/claude/skills/wtfp-plan-section/SKILL.md +1 -1
  161. package/vendors/claude/skills/wtfp-plan-section/references/actions.md +4 -3
  162. package/vendors/claude/skills/wtfp-research-literature/SKILL.md +1 -1
  163. package/vendors/claude/skills/wtfp-review-manuscript/SKILL.md +1 -1
  164. package/vendors/claude/skills/wtfp-write-section/SKILL.md +1 -1
  165. package/vendors/claude/skills/wtfp-write-section/references/actions.md +1 -1
  166. package/vendors/claude/workflows/checkpoint.md +2 -2
  167. package/vendors/claude/workflows/execute-outline.md +2 -2
  168. package/vendors/claude/workflows/export-latex.md +4 -4
  169. package/vendors/claude/workflows/plan-revision.md +4 -3
  170. package/vendors/claude/workflows/plan-section.md +2 -2
  171. package/vendors/claude/workflows/polish-prose.md +3 -3
  172. package/vendors/claude/workflows/research-gap.md +2 -2
  173. package/vendors/claude/workflows/verify-work.md +3 -3
  174. package/vendors/claude/workflows/write-section.md +2 -2
  175. package/vendors/clio-extension/.wtfp-generated.json +25 -13
  176. package/vendors/clio-extension/actions/checkpoint.json +10 -1
  177. package/vendors/clio-extension/actions/execute-outline.json +10 -2
  178. package/vendors/clio-extension/actions/export-latex.json +15 -2
  179. package/vendors/clio-extension/actions/plan-revision.json +17 -4
  180. package/vendors/clio-extension/actions/polish-prose.json +13 -3
  181. package/vendors/clio-extension/actions/research-gap.json +16 -3
  182. package/vendors/clio-extension/actions/verify-work.json +7 -2
  183. package/vendors/clio-extension/clio-coder-extension.yaml +33 -10
  184. package/vendors/clio-extension/compatibility/action-availability.json +2 -2
  185. package/vendors/clio-extension/project/schemas/interaction.schema.json +100 -0
  186. package/vendors/clio-extension/runtime/claim-coverage.cjs +332 -0
  187. package/vendors/clio-extension/runtime/desk-trust.cjs +112 -0
  188. package/vendors/clio-extension/runtime/extension.test.ts +1385 -66
  189. package/vendors/clio-extension/runtime/extension.ts +2226 -473
  190. package/vendors/clio-extension/runtime/write-guard.json +563 -18
  191. package/vendors/codex/plugins/wtfp/.codex-plugin/plugin.json +1 -1
  192. package/vendors/codex/plugins/wtfp/.wtfp-generated.json +36 -28
  193. package/vendors/codex/plugins/wtfp/actions/checkpoint.json +10 -1
  194. package/vendors/codex/plugins/wtfp/actions/execute-outline.json +10 -2
  195. package/vendors/codex/plugins/wtfp/actions/export-latex.json +15 -2
  196. package/vendors/codex/plugins/wtfp/actions/plan-revision.json +17 -4
  197. package/vendors/codex/plugins/wtfp/actions/polish-prose.json +13 -3
  198. package/vendors/codex/plugins/wtfp/actions/research-gap.json +16 -3
  199. package/vendors/codex/plugins/wtfp/actions/verify-work.json +7 -2
  200. package/vendors/codex/plugins/wtfp/plugin.json +1 -1
  201. package/vendors/codex/plugins/wtfp/project/README.md +37 -0
  202. package/vendors/codex/plugins/wtfp/project/schemas/interaction.schema.json +100 -0
  203. package/vendors/codex/plugins/wtfp/project/templates/interaction.json +16 -0
  204. package/vendors/codex/plugins/wtfp/skills/wtfp-deliver-research/SKILL.md +1 -1
  205. package/vendors/codex/plugins/wtfp/skills/wtfp-deliver-research/references/actions.md +2 -2
  206. package/vendors/codex/plugins/wtfp/skills/wtfp-plan-section/SKILL.md +1 -1
  207. package/vendors/codex/plugins/wtfp/skills/wtfp-plan-section/references/actions.md +4 -3
  208. package/vendors/codex/plugins/wtfp/skills/wtfp-research-literature/SKILL.md +1 -1
  209. package/vendors/codex/plugins/wtfp/skills/wtfp-review-manuscript/SKILL.md +1 -1
  210. package/vendors/codex/plugins/wtfp/skills/wtfp-write-section/SKILL.md +1 -1
  211. package/vendors/codex/plugins/wtfp/skills/wtfp-write-section/references/actions.md +1 -1
  212. package/vendors/codex/plugins/wtfp/workflows/checkpoint.md +2 -2
  213. package/vendors/codex/plugins/wtfp/workflows/execute-outline.md +2 -2
  214. package/vendors/codex/plugins/wtfp/workflows/export-latex.md +4 -4
  215. package/vendors/codex/plugins/wtfp/workflows/plan-revision.md +4 -3
  216. package/vendors/codex/plugins/wtfp/workflows/plan-section.md +2 -2
  217. package/vendors/codex/plugins/wtfp/workflows/polish-prose.md +3 -3
  218. package/vendors/codex/plugins/wtfp/workflows/research-gap.md +2 -2
  219. package/vendors/codex/plugins/wtfp/workflows/verify-work.md +3 -3
  220. package/vendors/codex/plugins/wtfp/workflows/write-section.md +2 -2
  221. package/vendors/copilot/.wtfp-generated.json +43 -35
  222. package/vendors/copilot/marketplace.json +2 -2
  223. package/vendors/copilot/plugins/wtfp/.claude-plugin/plugin.json +1 -1
  224. package/vendors/copilot/plugins/wtfp/.wtfp-generated.json +42 -34
  225. package/vendors/copilot/plugins/wtfp/actions/checkpoint.json +10 -1
  226. package/vendors/copilot/plugins/wtfp/actions/execute-outline.json +10 -2
  227. package/vendors/copilot/plugins/wtfp/actions/export-latex.json +15 -2
  228. package/vendors/copilot/plugins/wtfp/actions/plan-revision.json +17 -4
  229. package/vendors/copilot/plugins/wtfp/actions/polish-prose.json +13 -3
  230. package/vendors/copilot/plugins/wtfp/actions/research-gap.json +16 -3
  231. package/vendors/copilot/plugins/wtfp/actions/verify-work.json +7 -2
  232. package/vendors/copilot/plugins/wtfp/commands/wtfp-checkpoint.md +2 -2
  233. package/vendors/copilot/plugins/wtfp/commands/wtfp-execute-outline.md +2 -2
  234. package/vendors/copilot/plugins/wtfp/commands/wtfp-plan-revision.md +8 -3
  235. package/vendors/copilot/plugins/wtfp/commands/wtfp-plan-section.md +2 -2
  236. package/vendors/copilot/plugins/wtfp/commands/wtfp-polish-prose.md +7 -3
  237. package/vendors/copilot/plugins/wtfp/commands/wtfp-verify-work.md +3 -3
  238. package/vendors/copilot/plugins/wtfp/commands/wtfp-write-section.md +2 -2
  239. package/vendors/copilot/plugins/wtfp/project/README.md +37 -0
  240. package/vendors/copilot/plugins/wtfp/project/schemas/interaction.schema.json +100 -0
  241. package/vendors/copilot/plugins/wtfp/project/templates/interaction.json +16 -0
  242. package/vendors/copilot/plugins/wtfp/skills/wtfp-deliver-research/SKILL.md +1 -1
  243. package/vendors/copilot/plugins/wtfp/skills/wtfp-deliver-research/references/actions.md +2 -2
  244. package/vendors/copilot/plugins/wtfp/skills/wtfp-plan-section/SKILL.md +1 -1
  245. package/vendors/copilot/plugins/wtfp/skills/wtfp-plan-section/references/actions.md +4 -3
  246. package/vendors/copilot/plugins/wtfp/skills/wtfp-research-literature/SKILL.md +1 -1
  247. package/vendors/copilot/plugins/wtfp/skills/wtfp-review-manuscript/SKILL.md +1 -1
  248. package/vendors/copilot/plugins/wtfp/skills/wtfp-write-section/SKILL.md +1 -1
  249. package/vendors/copilot/plugins/wtfp/skills/wtfp-write-section/references/actions.md +1 -1
  250. package/vendors/copilot/plugins/wtfp/workflows/checkpoint.md +2 -2
  251. package/vendors/copilot/plugins/wtfp/workflows/execute-outline.md +2 -2
  252. package/vendors/copilot/plugins/wtfp/workflows/export-latex.md +4 -4
  253. package/vendors/copilot/plugins/wtfp/workflows/plan-revision.md +4 -3
  254. package/vendors/copilot/plugins/wtfp/workflows/plan-section.md +2 -2
  255. package/vendors/copilot/plugins/wtfp/workflows/polish-prose.md +3 -3
  256. package/vendors/copilot/plugins/wtfp/workflows/research-gap.md +2 -2
  257. package/vendors/copilot/plugins/wtfp/workflows/verify-work.md +3 -3
  258. package/vendors/copilot/plugins/wtfp/workflows/write-section.md +2 -2
  259. package/vendors/copilot/project/.github/skills/wtfp-deliver-research/SKILL.md +1 -1
  260. package/vendors/copilot/project/.github/skills/wtfp-deliver-research/references/actions.md +2 -2
  261. package/vendors/copilot/project/.github/skills/wtfp-plan-section/SKILL.md +1 -1
  262. package/vendors/copilot/project/.github/skills/wtfp-plan-section/references/actions.md +4 -3
  263. package/vendors/copilot/project/.github/skills/wtfp-research-literature/SKILL.md +1 -1
  264. package/vendors/copilot/project/.github/skills/wtfp-review-manuscript/SKILL.md +1 -1
  265. package/vendors/copilot/project/.github/skills/wtfp-write-section/SKILL.md +1 -1
  266. package/vendors/copilot/project/.github/skills/wtfp-write-section/references/actions.md +1 -1
  267. package/vendors/copilot/project/.github/wtfp/actions/checkpoint.json +10 -1
  268. package/vendors/copilot/project/.github/wtfp/actions/execute-outline.json +10 -2
  269. package/vendors/copilot/project/.github/wtfp/actions/export-latex.json +15 -2
  270. package/vendors/copilot/project/.github/wtfp/actions/plan-revision.json +17 -4
  271. package/vendors/copilot/project/.github/wtfp/actions/polish-prose.json +13 -3
  272. package/vendors/copilot/project/.github/wtfp/actions/research-gap.json +16 -3
  273. package/vendors/copilot/project/.github/wtfp/actions/verify-work.json +7 -2
  274. package/vendors/copilot/project/.github/wtfp/project/README.md +37 -0
  275. package/vendors/copilot/project/.github/wtfp/project/schemas/interaction.schema.json +100 -0
  276. package/vendors/copilot/project/.github/wtfp/project/templates/interaction.json +16 -0
  277. package/vendors/copilot/project/.github/wtfp/skills/wtfp-deliver-research/SKILL.md +1 -1
  278. package/vendors/copilot/project/.github/wtfp/skills/wtfp-deliver-research/references/actions.md +2 -2
  279. package/vendors/copilot/project/.github/wtfp/skills/wtfp-plan-section/SKILL.md +1 -1
  280. package/vendors/copilot/project/.github/wtfp/skills/wtfp-plan-section/references/actions.md +4 -3
  281. package/vendors/copilot/project/.github/wtfp/skills/wtfp-research-literature/SKILL.md +1 -1
  282. package/vendors/copilot/project/.github/wtfp/skills/wtfp-review-manuscript/SKILL.md +1 -1
  283. package/vendors/copilot/project/.github/wtfp/skills/wtfp-write-section/SKILL.md +1 -1
  284. package/vendors/copilot/project/.github/wtfp/skills/wtfp-write-section/references/actions.md +1 -1
  285. package/vendors/copilot/project/.github/wtfp/workflows/checkpoint.md +2 -2
  286. package/vendors/copilot/project/.github/wtfp/workflows/execute-outline.md +2 -2
  287. package/vendors/copilot/project/.github/wtfp/workflows/export-latex.md +4 -4
  288. package/vendors/copilot/project/.github/wtfp/workflows/plan-revision.md +4 -3
  289. package/vendors/copilot/project/.github/wtfp/workflows/plan-section.md +2 -2
  290. package/vendors/copilot/project/.github/wtfp/workflows/polish-prose.md +3 -3
  291. package/vendors/copilot/project/.github/wtfp/workflows/research-gap.md +2 -2
  292. package/vendors/copilot/project/.github/wtfp/workflows/verify-work.md +3 -3
  293. package/vendors/copilot/project/.github/wtfp/workflows/write-section.md +2 -2
  294. package/vendors/gemini/.wtfp-generated.json +61 -53
  295. package/vendors/gemini/actions/checkpoint.json +10 -1
  296. package/vendors/gemini/actions/execute-outline.json +10 -2
  297. package/vendors/gemini/actions/export-latex.json +15 -2
  298. package/vendors/gemini/actions/plan-revision.json +17 -4
  299. package/vendors/gemini/actions/polish-prose.json +13 -3
  300. package/vendors/gemini/actions/research-gap.json +16 -3
  301. package/vendors/gemini/actions/verify-work.json +7 -2
  302. package/vendors/gemini/commands/wtfp/add-todo.toml +37 -0
  303. package/vendors/gemini/commands/wtfp/check-todos.toml +37 -0
  304. package/vendors/gemini/commands/wtfp/checkpoint.toml +49 -3
  305. package/vendors/gemini/commands/wtfp/create-outline.toml +37 -0
  306. package/vendors/gemini/commands/wtfp/create-poster.toml +40 -3
  307. package/vendors/gemini/commands/wtfp/create-slides.toml +40 -3
  308. package/vendors/gemini/commands/wtfp/discuss-section.toml +42 -4
  309. package/vendors/gemini/commands/wtfp/execute-outline.toml +51 -6
  310. package/vendors/gemini/commands/wtfp/help.toml +37 -0
  311. package/vendors/gemini/commands/wtfp/insert-section.toml +42 -4
  312. package/vendors/gemini/commands/wtfp/list-assumptions.toml +42 -4
  313. package/vendors/gemini/commands/wtfp/map-project.toml +37 -0
  314. package/vendors/gemini/commands/wtfp/new-paper.toml +37 -0
  315. package/vendors/gemini/commands/wtfp/pause-writing.toml +37 -0
  316. package/vendors/gemini/commands/wtfp/plan-milestone-gaps.toml +38 -1
  317. package/vendors/gemini/commands/wtfp/plan-revision.toml +310 -11
  318. package/vendors/gemini/commands/wtfp/plan-section.toml +44 -6
  319. package/vendors/gemini/commands/wtfp/polish-prose.toml +281 -7
  320. package/vendors/gemini/commands/wtfp/progress.toml +37 -0
  321. package/vendors/gemini/commands/wtfp/quick.toml +39 -2
  322. package/vendors/gemini/commands/wtfp/resume-writing.toml +37 -0
  323. package/vendors/gemini/commands/wtfp/review-section.toml +38 -1
  324. package/vendors/gemini/commands/wtfp/settings.toml +37 -0
  325. package/vendors/gemini/commands/wtfp/submit-milestone.toml +40 -3
  326. package/vendors/gemini/commands/wtfp/verify-work.toml +48 -6
  327. package/vendors/gemini/commands/wtfp/write-section.toml +41 -4
  328. package/vendors/gemini/gemini-extension.json +1 -1
  329. package/vendors/gemini/project/README.md +37 -0
  330. package/vendors/gemini/project/schemas/interaction.schema.json +100 -0
  331. package/vendors/gemini/project/templates/interaction.json +16 -0
  332. package/vendors/gemini/skills/wtfp-deliver-research/SKILL.md +1 -1
  333. package/vendors/gemini/skills/wtfp-deliver-research/references/actions.md +2 -2
  334. package/vendors/gemini/skills/wtfp-plan-section/SKILL.md +1 -1
  335. package/vendors/gemini/skills/wtfp-plan-section/references/actions.md +4 -3
  336. package/vendors/gemini/skills/wtfp-research-literature/SKILL.md +1 -1
  337. package/vendors/gemini/skills/wtfp-review-manuscript/SKILL.md +1 -1
  338. package/vendors/gemini/skills/wtfp-write-section/SKILL.md +1 -1
  339. package/vendors/gemini/skills/wtfp-write-section/references/actions.md +1 -1
  340. package/vendors/gemini/workflows/checkpoint.md +2 -2
  341. package/vendors/gemini/workflows/execute-outline.md +2 -2
  342. package/vendors/gemini/workflows/export-latex.md +4 -4
  343. package/vendors/gemini/workflows/plan-revision.md +4 -3
  344. package/vendors/gemini/workflows/plan-section.md +2 -2
  345. package/vendors/gemini/workflows/polish-prose.md +3 -3
  346. package/vendors/gemini/workflows/research-gap.md +2 -2
  347. package/vendors/gemini/workflows/verify-work.md +3 -3
  348. package/vendors/gemini/workflows/write-section.md +2 -2
  349. package/vendors/opencode/.wtfp-generated.json +60 -52
  350. package/vendors/opencode/actions/checkpoint.json +10 -1
  351. package/vendors/opencode/actions/execute-outline.json +10 -2
  352. package/vendors/opencode/actions/export-latex.json +15 -2
  353. package/vendors/opencode/actions/plan-revision.json +17 -4
  354. package/vendors/opencode/actions/polish-prose.json +13 -3
  355. package/vendors/opencode/actions/research-gap.json +16 -3
  356. package/vendors/opencode/actions/verify-work.json +7 -2
  357. package/vendors/opencode/commands/wtfp/add-todo.md +37 -0
  358. package/vendors/opencode/commands/wtfp/check-todos.md +37 -0
  359. package/vendors/opencode/commands/wtfp/checkpoint.md +49 -3
  360. package/vendors/opencode/commands/wtfp/create-outline.md +37 -0
  361. package/vendors/opencode/commands/wtfp/create-poster.md +40 -3
  362. package/vendors/opencode/commands/wtfp/create-slides.md +40 -3
  363. package/vendors/opencode/commands/wtfp/discuss-section.md +42 -4
  364. package/vendors/opencode/commands/wtfp/execute-outline.md +51 -6
  365. package/vendors/opencode/commands/wtfp/help.md +37 -0
  366. package/vendors/opencode/commands/wtfp/insert-section.md +42 -4
  367. package/vendors/opencode/commands/wtfp/list-assumptions.md +42 -4
  368. package/vendors/opencode/commands/wtfp/map-project.md +37 -0
  369. package/vendors/opencode/commands/wtfp/new-paper.md +37 -0
  370. package/vendors/opencode/commands/wtfp/pause-writing.md +37 -0
  371. package/vendors/opencode/commands/wtfp/plan-milestone-gaps.md +38 -1
  372. package/vendors/opencode/commands/wtfp/plan-revision.md +310 -11
  373. package/vendors/opencode/commands/wtfp/plan-section.md +44 -6
  374. package/vendors/opencode/commands/wtfp/polish-prose.md +281 -7
  375. package/vendors/opencode/commands/wtfp/progress.md +37 -0
  376. package/vendors/opencode/commands/wtfp/quick.md +39 -2
  377. package/vendors/opencode/commands/wtfp/resume-writing.md +37 -0
  378. package/vendors/opencode/commands/wtfp/review-section.md +38 -1
  379. package/vendors/opencode/commands/wtfp/settings.md +37 -0
  380. package/vendors/opencode/commands/wtfp/submit-milestone.md +40 -3
  381. package/vendors/opencode/commands/wtfp/verify-work.md +48 -6
  382. package/vendors/opencode/commands/wtfp/write-section.md +41 -4
  383. package/vendors/opencode/project/README.md +37 -0
  384. package/vendors/opencode/project/schemas/interaction.schema.json +100 -0
  385. package/vendors/opencode/project/templates/interaction.json +16 -0
  386. package/vendors/opencode/skills/wtfp-deliver-research/SKILL.md +1 -1
  387. package/vendors/opencode/skills/wtfp-deliver-research/references/actions.md +2 -2
  388. package/vendors/opencode/skills/wtfp-plan-section/SKILL.md +1 -1
  389. package/vendors/opencode/skills/wtfp-plan-section/references/actions.md +4 -3
  390. package/vendors/opencode/skills/wtfp-research-literature/SKILL.md +1 -1
  391. package/vendors/opencode/skills/wtfp-review-manuscript/SKILL.md +1 -1
  392. package/vendors/opencode/skills/wtfp-write-section/SKILL.md +1 -1
  393. package/vendors/opencode/skills/wtfp-write-section/references/actions.md +1 -1
  394. package/vendors/opencode/workflows/checkpoint.md +2 -2
  395. package/vendors/opencode/workflows/execute-outline.md +2 -2
  396. package/vendors/opencode/workflows/export-latex.md +4 -4
  397. package/vendors/opencode/workflows/plan-revision.md +4 -3
  398. package/vendors/opencode/workflows/plan-section.md +2 -2
  399. package/vendors/opencode/workflows/polish-prose.md +3 -3
  400. package/vendors/opencode/workflows/research-gap.md +2 -2
  401. package/vendors/opencode/workflows/verify-work.md +3 -3
  402. package/vendors/opencode/workflows/write-section.md +2 -2
  403. package/vendors/plugin/.wtfp-generated.json +73 -65
  404. package/vendors/plugin/actions/checkpoint.json +10 -1
  405. package/vendors/plugin/actions/execute-outline.json +10 -2
  406. package/vendors/plugin/actions/export-latex.json +15 -2
  407. package/vendors/plugin/actions/plan-revision.json +17 -4
  408. package/vendors/plugin/actions/polish-prose.json +13 -3
  409. package/vendors/plugin/actions/research-gap.json +16 -3
  410. package/vendors/plugin/actions/verify-work.json +7 -2
  411. package/vendors/plugin/ai.iowarp.clio/agents/wtfp-argument-verifier.md +3 -3
  412. package/vendors/plugin/ai.iowarp.clio/agents/wtfp-coherence-checker.md +3 -3
  413. package/vendors/plugin/ai.iowarp.clio/agents/wtfp-plan-checker.md +3 -3
  414. package/vendors/plugin/ai.iowarp.clio/agents/wtfp-section-reviewer.md +3 -3
  415. package/vendors/plugin/ai.iowarp.clio/playbooks/wtfp-draft-review.md +1 -1
  416. package/vendors/plugin/ai.iowarp.clio/playbooks/wtfp-plan-section.md +1 -1
  417. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/add-todo.md +15 -2
  418. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/analyze-bib.md +30 -3
  419. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/audit-milestone.md +18 -3
  420. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/check-refs.md +30 -3
  421. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/check-todos.md +17 -3
  422. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/checkpoint.md +19 -5
  423. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/create-outline.md +29 -3
  424. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/create-poster.md +9 -0
  425. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/create-slides.md +9 -0
  426. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/discuss-section.md +17 -3
  427. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/execute-outline.md +33 -6
  428. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/export-latex.md +26 -21
  429. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/help.md +1 -1
  430. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/insert-section.md +17 -3
  431. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/list-assumptions.md +6 -0
  432. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/map-project.md +15 -2
  433. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/new-paper.md +17 -3
  434. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/pause-writing.md +15 -2
  435. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/plan-milestone-gaps.md +17 -3
  436. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/plan-revision.md +25 -18
  437. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/plan-section.md +32 -6
  438. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/polish-prose.md +33 -6
  439. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/progress.md +7 -0
  440. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/quick.md +30 -3
  441. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/research-gap.md +33 -5
  442. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/resume-writing.md +17 -3
  443. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/review-section.md +27 -4
  444. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/settings.md +17 -3
  445. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/submit-milestone.md +17 -3
  446. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/verify-work.md +20 -6
  447. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/write-section.md +33 -6
  448. package/vendors/plugin/compatibility/action-availability.json +2 -2
  449. package/vendors/plugin/plugin.json +2 -2
  450. package/vendors/plugin/project/README.md +37 -0
  451. package/vendors/plugin/project/schemas/interaction.schema.json +100 -0
  452. package/vendors/plugin/project/templates/interaction.json +16 -0
  453. package/vendors/plugin/skills/wtfp-deliver-research/SKILL.md +1 -1
  454. package/vendors/plugin/skills/wtfp-deliver-research/references/actions.md +2 -2
  455. package/vendors/plugin/skills/wtfp-plan-section/SKILL.md +1 -1
  456. package/vendors/plugin/skills/wtfp-plan-section/references/actions.md +4 -3
  457. package/vendors/plugin/skills/wtfp-research-literature/SKILL.md +1 -1
  458. package/vendors/plugin/skills/wtfp-review-manuscript/SKILL.md +1 -1
  459. package/vendors/plugin/skills/wtfp-write-section/SKILL.md +1 -1
  460. package/vendors/plugin/skills/wtfp-write-section/references/actions.md +1 -1
  461. package/vendors/plugin/workflows/checkpoint.md +2 -2
  462. package/vendors/plugin/workflows/execute-outline.md +2 -2
  463. package/vendors/plugin/workflows/export-latex.md +4 -4
  464. package/vendors/plugin/workflows/plan-revision.md +4 -3
  465. package/vendors/plugin/workflows/plan-section.md +2 -2
  466. package/vendors/plugin/workflows/polish-prose.md +3 -3
  467. package/vendors/plugin/workflows/research-gap.md +2 -2
  468. package/vendors/plugin/workflows/verify-work.md +3 -3
  469. package/vendors/plugin/workflows/write-section.md +2 -2
  470. package/vendors/antigravity/commands/wtfp-plan-section.md +0 -78
  471. package/vendors/antigravity/commands/wtfp-write-section.md +0 -77
@@ -2,26 +2,46 @@
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
+ writeSync,
31
+ } from "node:fs";
15
32
  import { createRequire } from "node:module";
16
33
  import path from "node:path";
34
+ import { performance } from "node:perf_hooks";
17
35
  import { fileURLToPath } from "node:url";
18
36
  import type {
19
37
  ExtensionApiV2,
20
38
  ExtensionContextV2,
39
+ ExtensionEffect,
21
40
  ExtensionHookResult,
22
41
  ExtensionIsland,
23
42
  ExtensionOutputV2,
24
43
  ExtensionSkin,
44
+ InterviewNext,
25
45
  InterviewStep,
26
46
  View,
27
47
  ViewTone,
@@ -32,11 +52,45 @@ const { SchemaRegistry, validateInstance } = require("./json-schema.cjs") as {
32
52
  SchemaRegistry: new (files: string[]) => { get(file: string): unknown };
33
53
  validateInstance: (value: unknown, schema: unknown, file: string, registry: unknown) => string[];
34
54
  };
55
+ const deskTrust = require("./desk-trust.cjs") as {
56
+ canonical(value: unknown): string;
57
+ checkpointDigest(record: Json): string;
58
+ seal(record: Json, key: Buffer): Json;
59
+ trustOf(checkpoint: Json, interactions: Json[], key: Buffer | null, projectId: string | null): { trust: Trust; answer?: Json };
60
+ };
61
+ const coverage = require("./claim-coverage.cjs") as {
62
+ STRUCTURAL_SCOPE: string;
63
+ analyzeCoverage(input: unknown): CoverageReport;
64
+ indexRecords(
65
+ entries: Array<{ file: string; record: Json }>,
66
+ collection: string,
67
+ location?: (id: string) => string,
68
+ ): { byUri: Record<string, Json>; ignored: Array<{ file: string; reason: string }> };
69
+ unsupportedRequired(report: CoverageReport, section: string): string[];
70
+ };
71
+
72
+ interface CoverageFinding {
73
+ severity: "blocker" | "error" | "warning" | "info";
74
+ code: string;
75
+ subject: string;
76
+ message: string;
77
+ }
78
+
79
+ interface CoverageReport {
80
+ scope: string;
81
+ findings: CoverageFinding[];
82
+ claims: Array<{ section: string; claim: string; status: string; evidence_required: boolean; support: "full" | "partial" | "none"; contested: boolean }>;
83
+ }
35
84
 
36
85
  const PACKAGE_ROOT = fileURLToPath(new URL("../", import.meta.url));
37
86
  const SCHEMAS = path.join(PACKAGE_ROOT, "project", "schemas");
87
+ interface GuardAction {
88
+ produces: Array<{ uri: string; mode: string }>;
89
+ }
38
90
  const GUARD = JSON.parse(readFileSync(new URL("./write-guard.json", import.meta.url), "utf8")) as {
39
- actions: Record<string, string[]>;
91
+ schema: string;
92
+ actions: Record<string, GuardAction>;
93
+ paperWriters: string[];
40
94
  };
41
95
  const SKIN = JSON.parse(readFileSync(new URL("../skins/wtfp.json", import.meta.url), "utf8")) as ExtensionSkin;
42
96
  const RECORD_LIMIT = 1024 * 1024;
@@ -51,9 +105,29 @@ const WORDMARK = [
51
105
  ];
52
106
  const WORD_METHOD =
53
107
  "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.";
108
+ /** Files only the desk writes. A model tool call that would change one is refused. */
109
+ const DESK_OWNED = [".planning/interactions", ".planning/.wtfp-lock", ".planning/.wtfp-journal.json"];
110
+ const LOCK = ".planning/.wtfp-lock";
111
+ const JOURNAL = ".planning/.wtfp-journal.json";
112
+ const LOCK_WAIT_MS = 2000;
113
+ const LOCK_STALE_MS = 30_000;
114
+ const SEAL_KEY = "seal-key";
115
+ /** The option id a plan-approval checkpoint uses for approval; any other answer leaves the plan unapproved. */
116
+ const APPROVE = "approve";
54
117
 
55
118
  // --- records -----------------------------------------------------------------
56
119
 
120
+ type Json = Record<string, unknown>;
121
+ type ServedPlugin = ExtensionContextV2["snapshot"]["plugin"];
122
+
123
+ /**
124
+ * How far an author answer can be trusted. `attested` means a sealed desk
125
+ * interaction still matches the checkpoint; `unattested` is a resolution the
126
+ * desk never observed (a hand edit, another host or an older desk); `foreign`
127
+ * was sealed with another machine's key and cannot be checked here.
128
+ */
129
+ type Trust = "pending" | "attested" | "unattested" | "foreign" | "policy" | "expired" | "snapshot";
130
+
57
131
  interface Checkpoint {
58
132
  file: string;
59
133
  id: string;
@@ -65,9 +139,21 @@ interface Checkpoint {
65
139
  context?: string;
66
140
  options?: Array<{ id: string; label: string; implication?: string }>;
67
141
  created_at?: string;
142
+ resolution?: { resolved_by?: string; selected_option?: string; summary?: string; resolved_at?: string };
143
+ trust: Trust;
144
+ /** The sealed interaction behind an attested resolution. */
145
+ answer?: Json;
68
146
  [key: string]: unknown;
69
147
  }
70
148
 
149
+ interface PlanState {
150
+ state: "none" | "missing" | "awaiting" | "approved" | "policy" | "changed" | "declined" | "unconfirmed";
151
+ uri: string | null;
152
+ file: string | null;
153
+ sha256: string | null;
154
+ reason: string;
155
+ }
156
+
71
157
  interface SectionRow {
72
158
  id: string;
73
159
  title: string;
@@ -75,17 +161,29 @@ interface SectionRow {
75
161
  status: string;
76
162
  target: number;
77
163
  words: number;
164
+ recorded: number | null;
78
165
  manuscript: string | null;
79
166
  claims: { total: number; verified: number; unsupported: number };
80
167
  stages: { discuss: boolean; plan: boolean; write: boolean; review: boolean };
81
168
  gates: Checkpoint[];
82
169
  research: { required: boolean; present: boolean };
83
170
  dependsOn: string[];
171
+ plan: PlanState;
172
+ unsupported: string[];
173
+ record: Json | null;
174
+ }
175
+
176
+ interface Finding {
177
+ severity: "blocker" | "error" | "warning" | "info";
178
+ code: string;
179
+ subject: string;
180
+ message: string;
84
181
  }
85
182
 
86
183
  interface Desk {
87
184
  workspace: string;
88
185
  present: boolean;
186
+ projectId: string | null;
89
187
  title: string;
90
188
  documentType: string;
91
189
  venue: string | null;
@@ -94,21 +192,22 @@ interface Desk {
94
192
  phase: string;
95
193
  status: string;
96
194
  confirmPlan: boolean;
195
+ outputFormat: string;
97
196
  sections: SectionRow[];
98
197
  checkpoints: Checkpoint[];
198
+ interactions: Json[];
99
199
  sources: Record<string, number>;
100
200
  evidence: number;
101
201
  issues: Record<"blocker" | "error" | "warning" | "info", number>;
102
202
  invalid: Array<{ file: string; errors: string[] }>;
103
203
  targetWords: number;
104
204
  paperExists: boolean;
205
+ journal: boolean;
206
+ coverage: CoverageReport;
105
207
  /** The WTF-P plugin while Clio serves it; null when it is not installed and enabled. */
106
208
  served: ServedPlugin;
107
209
  }
108
210
 
109
- type Json = Record<string, unknown>;
110
- type ServedPlugin = ExtensionContextV2["snapshot"]["plugin"];
111
-
112
211
  /** Actions the desk answers itself; they stay reachable as `/ext:wtfp:<name>` without the plugin. */
113
212
  const DESK_COMMANDS = new Set(["progress", "help", "check-todos"]);
114
213
 
@@ -131,22 +230,61 @@ function actionName(served: ServedPlugin, action: string): string {
131
230
 
132
231
  function inside(root: string, candidate: string): boolean {
133
232
  const relative = path.relative(root, candidate);
134
- return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
233
+ return relative === "" || (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
135
234
  }
136
235
 
137
- function readText(workspace: string, relative: string): string | null {
236
+ function posix(relative: string): string {
237
+ return relative.split(path.sep).join("/");
238
+ }
239
+
240
+ /**
241
+ * A project-relative path inside the workspace whose existing components are
242
+ * all real files or directories. A symbolic link anywhere on the way could
243
+ * carry a read or write outside the project, so it yields null.
244
+ */
245
+ function contained(workspace: string, relative: string): string | null {
138
246
  const file = path.resolve(workspace, relative);
139
- if (!inside(workspace, file) || !existsSync(file)) return null;
247
+ if (!inside(workspace, file)) return null;
248
+ let current = workspace;
249
+ for (const part of path.relative(workspace, file).split(path.sep).filter(Boolean)) {
250
+ current = path.join(current, part);
251
+ let stat;
252
+ try {
253
+ stat = lstatSync(current);
254
+ } catch {
255
+ return file;
256
+ }
257
+ if (stat.isSymbolicLink()) return null;
258
+ }
259
+ return file;
260
+ }
261
+
262
+ /** The workspace's real path, against which Clio reports every landing. */
263
+ function realWorkspace(workspace: string): string {
264
+ try {
265
+ return realpathSync(workspace);
266
+ } catch {
267
+ return workspace;
268
+ }
269
+ }
270
+
271
+ function readBytes(workspace: string, relative: string): Buffer | null {
272
+ const file = contained(workspace, relative);
273
+ if (file === null || !existsSync(file)) return null;
140
274
  const stat = lstatSync(file);
141
275
  if (!stat.isFile() || stat.size > RECORD_LIMIT) return null;
142
- return readFileSync(file, "utf8");
276
+ return readFileSync(file);
277
+ }
278
+
279
+ function readText(workspace: string, relative: string): string | null {
280
+ return readBytes(workspace, relative)?.toString("utf8") ?? null;
143
281
  }
144
282
 
145
283
  function readRecord(workspace: string, relative: string): Json | null {
146
- const text = readText(workspace, relative);
147
- if (text === null) return null;
284
+ const source = readText(workspace, relative);
285
+ if (source === null) return null;
148
286
  try {
149
- const value = JSON.parse(text) as unknown;
287
+ const value = JSON.parse(source) as unknown;
150
288
  return value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Json) : null;
151
289
  } catch {
152
290
  // An unreadable record shows up as a schema problem from validation, not here.
@@ -155,10 +293,10 @@ function readRecord(workspace: string, relative: string): Json | null {
155
293
  }
156
294
 
157
295
  function listJson(workspace: string, relative: string): string[] {
158
- const directory = path.resolve(workspace, relative);
159
- if (!inside(workspace, directory) || !existsSync(directory)) return [];
296
+ const directory = contained(workspace, relative);
297
+ if (directory === null || !existsSync(directory) || !lstatSync(directory).isDirectory()) return [];
160
298
  return readdirSync(directory, { withFileTypes: true })
161
- .filter((entry) => entry.isFile() && entry.name.endsWith(".json"))
299
+ .filter((entry) => entry.isFile() && entry.name.endsWith(".json") && !entry.name.startsWith("."))
162
300
  .map((entry) => path.posix.join(relative, entry.name))
163
301
  .sort();
164
302
  }
@@ -167,17 +305,48 @@ function text(value: unknown, fallback = ""): string {
167
305
  return typeof value === "string" && value.length > 0 ? value : fallback;
168
306
  }
169
307
 
308
+ function sha256(data: string | Buffer): string {
309
+ return createHash("sha256").update(data).digest("hex");
310
+ }
311
+
312
+ /** JSON with object keys in code-unit order and no insignificant whitespace; the input to every digest and seal. */
313
+ function canonical(value: unknown): string {
314
+ return deskTrust.canonical(value);
315
+ }
316
+
317
+ /** What a checkpoint asks, independent of whether and how it was answered. */
318
+ export function checkpointDigest(record: Json): string {
319
+ return deskTrust.checkpointDigest(record);
320
+ }
321
+
322
+ function timestamp(): string {
323
+ return new Date().toISOString().replace(/\.\d{3}Z$/u, "Z");
324
+ }
325
+
326
+ const EXTENSIONS: Record<string, string> = { markdown: ".md", latex: ".tex", typst: ".typ" };
327
+
170
328
  /** `project://paper/{artifact}` to a manuscript file, trying the authored formats in order. */
171
- function manuscriptFile(workspace: string, uri: unknown): string | null {
329
+ function manuscriptFile(workspace: string, uri: unknown, format = "markdown"): string | null {
172
330
  if (typeof uri !== "string" || !uri.startsWith("project://paper/")) return null;
173
331
  const artifact = uri.slice("project://paper/".length);
174
- if (artifact.length === 0 || artifact.split("/").some((part) => part === ".." || part === "")) return null;
332
+ if (artifact.length === 0 || artifact.split("/").some((part) => part === ".." || part === "." || part === "")) return null;
175
333
  for (const candidate of [artifact, `${artifact}.md`, `${artifact}.tex`, `${artifact}.typ`]) {
176
334
  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;
335
+ const file = contained(workspace, relative);
336
+ if (file !== null && existsSync(file) && lstatSync(file).isFile()) return relative;
179
337
  }
180
- return path.posix.join("paper", artifact);
338
+ return path.posix.join("paper", /\.(md|tex|typ)$/u.test(artifact) ? artifact : `${artifact}${EXTENSIONS[format] ?? ".md"}`);
339
+ }
340
+
341
+ /** A section-scoped artifact URI to its conventional file, or null when it names no file. */
342
+ function artifactFile(workspace: string, uri: string, format = "markdown"): string | null {
343
+ if (uri.startsWith("project://paper/")) return manuscriptFile(workspace, uri, format);
344
+ const named = new RegExp(`^project://sections/(${IDENTIFIER})/(context|research|summary|handoff)$`, "u").exec(uri);
345
+ if (named) return `.planning/sections/${named[1]}/${named[2]}.md`;
346
+ const listed = new RegExp(`^project://sections/(${IDENTIFIER})/(plans|reviews)/(${IDENTIFIER})$`, "u").exec(uri);
347
+ if (listed) return `.planning/sections/${listed[1]}/${listed[2]}/${listed[3]}.md`;
348
+ const route = RECORD_URIS.find((entry) => entry.pattern.test(uri));
349
+ return route ? route.file(route.pattern.exec(uri)?.[1] ?? "") : null;
181
350
  }
182
351
 
183
352
  /** The one counting method every meter and tolerance uses (see WORD_METHOD). */
@@ -200,16 +369,6 @@ export function bodyWords(source: string, file: string): number {
200
369
  return (body.match(/[\p{L}\p{N}]+(?:['’-][\p{L}\p{N}]+)*/gu) ?? []).length;
201
370
  }
202
371
 
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
372
  let registry: InstanceType<typeof SchemaRegistry> | undefined;
214
373
  function schemaRegistry(): InstanceType<typeof SchemaRegistry> {
215
374
  registry ??= new SchemaRegistry(
@@ -233,7 +392,7 @@ function validateRecord(value: unknown): string[] {
233
392
 
234
393
  function validateFile(workspace: string, relative: string): string[] {
235
394
  const source = readText(workspace, relative);
236
- if (source === null) return [];
395
+ if (source === null) return contained(workspace, relative) === null ? ["$: reached through a symbolic link; the desk does not follow links"] : [];
237
396
  try {
238
397
  return validateRecord(JSON.parse(source));
239
398
  } catch (error) {
@@ -242,10 +401,11 @@ function validateFile(workspace: string, relative: string): string[] {
242
401
  }
243
402
 
244
403
  function planningRecords(workspace: string, relative = ".planning"): string[] {
245
- const directory = path.resolve(workspace, relative);
246
- if (!existsSync(directory)) return [];
404
+ const directory = contained(workspace, relative);
405
+ if (directory === null || !existsSync(directory) || !lstatSync(directory).isDirectory()) return [];
247
406
  const out: string[] = [];
248
407
  for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
408
+ if (entry.name.startsWith(".")) continue;
249
409
  const child = path.posix.join(relative, entry.name);
250
410
  if (entry.isDirectory() && entry.name !== "archives") out.push(...planningRecords(workspace, child));
251
411
  else if (entry.isFile() && entry.name.endsWith(".json")) out.push(child);
@@ -253,44 +413,216 @@ function planningRecords(workspace: string, relative = ".planning"): string[] {
253
413
  return out;
254
414
  }
255
415
 
256
- function loadDesk(workspace: string): Desk {
416
+ // --- seals -------------------------------------------------------------------
417
+
418
+ /** The desk's seal over an interaction record (evaluation/lib/desk-trust.js, shared with the campaign collector). */
419
+ function sealed(record: Json, key: Buffer): Json {
420
+ return deskTrust.seal(record, key);
421
+ }
422
+
423
+ async function storedKey(ctx: ExtensionContextV2, create: boolean): Promise<Buffer | null> {
424
+ const current = await ctx.store.get<string>(SEAL_KEY);
425
+ if (typeof current.value === "string" && /^[a-f0-9]{64}$/u.test(current.value)) return Buffer.from(current.value, "hex");
426
+ if (!create) return null;
427
+ // ifVersion keeps two sessions from each minting a key; the loser reads the winner's.
428
+ await ctx.store.set(SEAL_KEY, randomBytes(32).toString("hex"), { ifVersion: current.version });
429
+ const settled = await ctx.store.get<string>(SEAL_KEY);
430
+ return typeof settled.value === "string" ? Buffer.from(settled.value, "hex") : null;
431
+ }
432
+
433
+ function trustOf(checkpoint: Checkpoint, interactions: Json[], key: Buffer | null, projectId: string | null): { trust: Trust; answer?: Json } {
434
+ return deskTrust.trustOf(checkpoint, interactions, key, projectId);
435
+ }
436
+
437
+ /** Recorded as answered, but with no author answer sealed by this desk behind it. */
438
+ function unconfirmed(checkpoint: Checkpoint): boolean {
439
+ return checkpoint.trust === "unattested" || checkpoint.trust === "foreign" || checkpoint.trust === "policy";
440
+ }
441
+
442
+ /** A blocking checkpoint holds its scope until the author's answer is attested here. */
443
+ function holds(checkpoint: Checkpoint): boolean {
444
+ return checkpoint.blocking && (checkpoint.trust === "pending" || unconfirmed(checkpoint));
445
+ }
446
+
447
+ function scopes(id: string, manuscript: string | null): string[] {
448
+ return [`project://sections/${id}`, ...(manuscript ? [`project://${manuscript.replace(/\.(md|tex|typ)$/u, "")}`] : [])];
449
+ }
450
+
451
+ function sectionGates(checkpoints: Checkpoint[], id: string, manuscript: string | null): Checkpoint[] {
452
+ const owned = scopes(id, manuscript);
453
+ return checkpoints.filter(
454
+ (checkpoint) =>
455
+ holds(checkpoint) && owned.some((scope) => checkpoint.scope_uri === scope || checkpoint.scope_uri.startsWith(`${scope}/`) || checkpoint.scope_uri.startsWith(`${scope}.`)),
456
+ );
457
+ }
458
+
459
+ // --- the approved-plan predicate ---------------------------------------------
460
+
461
+ /**
462
+ * Whether a section's current plan may drive its manuscript. The current plan
463
+ * is the last one linked from the section record; it must be a real contained
464
+ * file, and while confirm_plan is on, an attested author answer of `approve`
465
+ * on a checkpoint scoped to that plan must have been given for exactly these
466
+ * bytes. A later edit, a declined or unconfirmed answer, or no answer at all
467
+ * leaves it unapproved.
468
+ */
469
+ function planState(workspace: string, id: string, record: Json | null, checkpoints: Checkpoint[], confirmPlan: boolean): PlanState {
470
+ const plans = Array.isArray((record?.artifacts as Json | undefined)?.plans) ? ((record?.artifacts as Json).plans as unknown[]) : [];
471
+ const uri = plans.length > 0 && typeof plans[plans.length - 1] === "string" ? (plans[plans.length - 1] as string) : null;
472
+ if (uri === null) return { state: "none", uri: null, file: null, sha256: null, reason: "no plan is linked from the section record" };
473
+ const file = new RegExp(`^project://sections/${id}/plans/${IDENTIFIER}$`, "u").test(uri) ? artifactFile(workspace, uri) : null;
474
+ const bytes = file === null ? null : readBytes(workspace, file);
475
+ if (file === null || bytes === null)
476
+ return { state: "missing", uri, file, sha256: null, reason: `${uri} does not resolve to a plan file in this project` };
477
+ const digest = sha256(bytes);
478
+ const policy: PlanState = { state: "policy", uri, file, sha256: digest, reason: "confirm_plan is off, so the linked plan stands without an author approval" };
479
+ const asked = checkpoints.filter((checkpoint) => checkpoint.scope_uri === uri && checkpoint.kind !== "state-snapshot");
480
+ const answered = asked
481
+ .filter((checkpoint) => checkpoint.trust === "attested" && checkpoint.answer)
482
+ .sort((a, b) => text(b.answer?.answered_at).localeCompare(text(a.answer?.answered_at)));
483
+ const latest = answered[0];
484
+ // An author's explicit answer on this plan decides even when confirm_plan is off: a rejection is never overridden by policy.
485
+ if (latest) {
486
+ if (latest.resolution?.selected_option !== APPROVE || latest.status !== "resolved")
487
+ return { state: "declined", uri, file, sha256: digest, reason: `the author answered "${latest.resolution?.selected_option ?? latest.status}" on ${latest.id}, not approve` };
488
+ const shown = ((latest.answer?.presented as Json | undefined)?.artifact as Json | undefined)?.sha256;
489
+ if (shown !== digest)
490
+ return confirmPlan ? { state: "changed", uri, file, sha256: digest, reason: `the plan changed after the author approved it on ${latest.id}` } : policy;
491
+ return { state: "approved", uri, file, sha256: digest, reason: `approved by the author on ${latest.id}` };
492
+ }
493
+ if (!confirmPlan) return policy;
494
+ if (asked.some((checkpoint) => checkpoint.trust === "pending"))
495
+ return { state: "awaiting", uri, file, sha256: digest, reason: "its approval checkpoint waits on the author" };
496
+ if (asked.some((checkpoint) => checkpoint.trust === "unattested" || checkpoint.trust === "foreign"))
497
+ return { state: "unconfirmed", uri, file, sha256: digest, reason: "its recorded approval was not observed by this desk; confirm it at the gate" };
498
+ return { state: "awaiting", uri, file, sha256: digest, reason: `no approval checkpoint is scoped to ${uri}` };
499
+ }
500
+
501
+ function planReady(plan: PlanState): boolean {
502
+ return plan.state === "approved" || plan.state === "policy";
503
+ }
504
+
505
+ /** Why a section's manuscript may not be written now; empty when it may. */
506
+ function blockers(desk: Desk, section: SectionRow): string[] {
507
+ const reasons: string[] = [];
508
+ for (const gate of section.gates)
509
+ reasons.push(
510
+ gate.trust === "pending"
511
+ ? `the author has not answered "${gate.request}" (${gate.id})`
512
+ : `the recorded answer to ${gate.id} was not observed by this desk and must be confirmed`,
513
+ );
514
+ if (!planReady(section.plan)) reasons.push(`${section.plan.reason}`);
515
+ if (section.research.required && section.unsupported.length > 0)
516
+ reasons.push(`${section.unsupported.length} required ${section.unsupported.length === 1 ? "claim lacks" : "claims lack"} verified evidence (${section.unsupported.slice(0, 3).join(", ")}); run research-gap first`);
517
+ return reasons;
518
+ }
519
+
520
+ // --- loading -----------------------------------------------------------------
521
+
522
+ function loadDesk(workspace: string, key: Buffer | null = null): Desk {
257
523
  const manifest = readRecord(workspace, ".planning/project.json");
258
524
  const config = readRecord(workspace, ".planning/config.json");
259
525
  const state = readRecord(workspace, ".planning/state.json");
260
526
  const outline = readRecord(workspace, ".planning/structure/outline.json");
261
527
  const target = (manifest?.target ?? {}) as Json;
262
528
  const progress = (state?.progress ?? {}) as Json;
529
+ const projectId = typeof manifest?.id === "string" ? manifest.id : null;
530
+ const interactions = listJson(workspace, ".planning/interactions").flatMap((file) => {
531
+ const record = readRecord(workspace, file);
532
+ return record && record.schema === "wtfp.project.interaction/v1" ? [record] : [];
533
+ });
263
534
  const checkpoints: Checkpoint[] = listJson(workspace, ".planning/checkpoints").flatMap((file) => {
264
535
  const record = readRecord(workspace, file);
265
536
  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
- ];
537
+ const checkpoint = {
538
+ ...record,
539
+ file,
540
+ id: record.id,
541
+ kind: text(record.kind, "decision"),
542
+ status: text(record.status, "pending"),
543
+ blocking: record.blocking === true,
544
+ scope_uri: text(record.scope_uri),
545
+ request: text(record.request, record.id),
546
+ } as Checkpoint;
547
+ Object.assign(checkpoint, trustOf(checkpoint, interactions, key, projectId));
548
+ return [checkpoint];
278
549
  });
279
550
  checkpoints.sort((a, b) => text(a.created_at).localeCompare(text(b.created_at)) || a.id.localeCompare(b.id));
551
+ const gates = (config?.gates ?? {}) as Json;
552
+ const confirmPlan = gates.confirm_plan !== false;
553
+ const outputFormat = text(config?.output_format, "markdown");
554
+
555
+ // Only a record that passes its schema can support a claim, and an id carried by two records names neither.
556
+ const ignored: Array<{ file: string; reason: string }> = [];
557
+ const sources: Record<string, number> = {};
558
+ const indexed = (collection: string): Record<string, Json> => {
559
+ const entries: Array<{ file: string; record: Json }> = [];
560
+ for (const file of listJson(workspace, `.planning/${collection}`)) {
561
+ const record = readRecord(workspace, file);
562
+ if (!record) continue;
563
+ if (collection === "sources") sources[text(record.status, "unknown")] = (sources[text(record.status, "unknown")] ?? 0) + 1;
564
+ if (validateRecord(record).length > 0) ignored.push({ file, reason: "it fails its schema" });
565
+ else entries.push({ file, record });
566
+ }
567
+ const index = coverage.indexRecords(entries, collection, (id) => `.planning/${collection}/${id}.json`);
568
+ ignored.push(...index.ignored);
569
+ return index.byUri;
570
+ };
571
+ const sourceRecords = indexed("sources");
572
+ const evidenceRecords = indexed("evidence");
573
+
280
574
  const outlined = Array.isArray(outline?.sections) ? (outline.sections as Json[]) : [];
281
- const sections: SectionRow[] = outlined.map((entry) => {
575
+ const loaded = outlined.map((entry) => {
282
576
  const id = text(entry.id, "section");
283
- const base = `.planning/sections/${id}`;
284
- const record = readRecord(workspace, `${base}/section.json`);
577
+ // A section file holds the section its directory names; a record with another id is not this section's.
578
+ const file = `.planning/sections/${id}/section.json`;
579
+ const found = readRecord(workspace, file);
580
+ if (found && found.id !== id) ignored.push({ file, reason: `it holds section ${String(found.id)}, not ${id}` });
581
+ const record = found && found.id === id ? found : null;
285
582
  const artifacts = (record?.artifacts ?? {}) as Json;
286
- const manuscript = manuscriptFile(workspace, artifacts.manuscript ?? `project://paper/${id}`);
583
+ const manuscript = manuscriptFile(workspace, artifacts.manuscript ?? `project://paper/${id}`, outputFormat);
287
584
  const source = manuscript ? readText(workspace, manuscript) : null;
585
+ return { entry, id, record, artifacts, manuscript, source };
586
+ });
587
+ // A manuscript that exists but cannot be read safely, or that a drafted section lacks, leaves its citations unchecked.
588
+ const unread = loaded.flatMap((item) => {
589
+ if (item.source !== null) return [];
590
+ const drafted = ["writing", "reviewing", "complete"].includes(text(item.record?.status));
591
+ if (item.manuscript === null)
592
+ return drafted ? [{ section: item.id, file: text((item.artifacts as Json).manuscript), reason: "its manuscript link does not name a file under paper/" }] : [];
593
+ let present = false;
594
+ try {
595
+ lstatSync(path.join(workspace, item.manuscript));
596
+ present = true;
597
+ } catch {
598
+ present = false;
599
+ }
600
+ if (present) return [{ section: item.id, file: item.manuscript, reason: "it is a link, not a regular file, or too large" }];
601
+ const status = text(item.record?.status);
602
+ return ["writing", "reviewing", "complete"].includes(status) ? [{ section: item.id, file: item.manuscript, reason: `the section is ${status} but its manuscript does not exist` }] : [];
603
+ });
604
+ const report = coverage.analyzeCoverage({
605
+ projectId,
606
+ outline,
607
+ sections: loaded.filter((item) => item.record).map((item) => ({ uri: `project://sections/${item.id}`, record: item.record })),
608
+ evidence: evidenceRecords,
609
+ sources: sourceRecords,
610
+ manuscripts: loaded
611
+ .filter((item) => item.source !== null && item.manuscript !== null)
612
+ .map((item) => ({ section: item.id, file: item.manuscript, text: item.source })),
613
+ ignored,
614
+ unread,
615
+ });
616
+
617
+ const sections: SectionRow[] = loaded.map(({ entry, id, record, artifacts, manuscript, source }) => {
618
+ const base = `.planning/sections/${id}`;
288
619
  const words = source === null || manuscript === null ? 0 : bodyWords(source, manuscript);
289
620
  const status = text(record?.status, "not-started");
290
621
  const claims = Array.isArray(record?.claims) ? (record.claims as Json[]) : [];
291
622
  const plans = Array.isArray(artifacts.plans) ? artifacts.plans : [];
292
623
  const reviews = Array.isArray(artifacts.reviews) ? artifacts.reviews : [];
293
624
  const research = (entry.research ?? {}) as Json;
625
+ const unsupported = coverage.unsupportedRequired(report, id);
294
626
  return {
295
627
  id,
296
628
  title: text(entry.title, id),
@@ -298,32 +630,27 @@ function loadDesk(workspace: string): Desk {
298
630
  status,
299
631
  target: typeof entry.word_target === "number" ? entry.word_target : Number(record?.word_target ?? 0),
300
632
  words,
633
+ recorded: typeof record?.word_count === "number" ? record.word_count : null,
301
634
  manuscript,
302
635
  claims: {
303
636
  total: claims.length,
304
637
  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,
638
+ unsupported: unsupported.length,
310
639
  },
311
640
  stages: {
312
- discuss: existsSync(path.join(workspace, base, "context.md")),
641
+ discuss: readBytes(workspace, `${base}/context.md`) !== null,
313
642
  plan: plans.length > 0 || ["planned", "writing", "reviewing", "complete"].includes(status),
314
643
  write: words > 0 || ["reviewing", "complete"].includes(status),
315
644
  review: reviews.length > 0 || status === "complete",
316
645
  },
317
646
  gates: sectionGates(checkpoints, id, manuscript),
318
- research: { required: research.required === true, present: existsSync(path.join(workspace, base, "research.md")) },
647
+ research: { required: research.required === true, present: readBytes(workspace, `${base}/research.md`) !== null },
319
648
  dependsOn: Array.isArray(entry.depends_on) ? entry.depends_on.filter((dep): dep is string => typeof dep === "string") : [],
649
+ plan: planState(workspace, id, record, checkpoints, confirmPlan),
650
+ unsupported,
651
+ record,
320
652
  };
321
653
  });
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
654
  const issues = { blocker: 0, error: 0, warning: 0, info: 0 };
328
655
  for (const file of listJson(workspace, ".planning/validations")) {
329
656
  const record = readRecord(workspace, file);
@@ -332,10 +659,11 @@ function loadDesk(workspace: string): Desk {
332
659
  if (severity in issues) issues[severity] += 1;
333
660
  }
334
661
  }
335
- const gates = (config?.gates ?? {}) as Json;
662
+ const journal = contained(workspace, JOURNAL);
336
663
  return {
337
664
  workspace,
338
665
  present: manifest !== null,
666
+ projectId,
339
667
  title: text(manifest?.title, "Untitled paper"),
340
668
  documentType: text(manifest?.document_type, "paper"),
341
669
  venue: typeof target.venue === "string" ? target.venue : null,
@@ -343,11 +671,13 @@ function loadDesk(workspace: string): Desk {
343
671
  argument: text(manifest?.core_argument),
344
672
  phase: text(state?.phase, manifest ? "initialized" : "none"),
345
673
  status: text(state?.status, "active"),
346
- confirmPlan: gates.confirm_plan !== false,
674
+ confirmPlan,
675
+ outputFormat,
347
676
  sections,
348
677
  checkpoints,
678
+ interactions,
349
679
  sources,
350
- evidence: listJson(workspace, ".planning/evidence").length,
680
+ evidence: Object.keys(evidenceRecords).length,
351
681
  issues,
352
682
  invalid: [],
353
683
  targetWords:
@@ -358,141 +688,731 @@ function loadDesk(workspace: string): Desk {
358
688
  : typeof target.word_limit === "number"
359
689
  ? target.word_limit
360
690
  : sections.reduce((sum, section) => sum + section.target, 0),
361
- paperExists: existsSync(path.join(workspace, "paper")),
691
+ paperExists: contained(workspace, "paper") !== null && existsSync(path.join(workspace, "paper")),
692
+ journal: journal !== null && existsSync(journal),
693
+ coverage: report,
362
694
  served: null,
363
695
  };
364
696
  }
365
697
 
366
- // --- the rule ladder ---------------------------------------------------------
367
-
368
- interface Next {
369
- command: string | null;
370
- reason: string;
698
+ /**
699
+ * Disagreements between the records and the files they describe. Each one is
700
+ * a reason not to trust a count or a link until the action that owns it runs
701
+ * again; none is repaired here.
702
+ */
703
+ function reconcile(workspace: string, desk: Desk): Finding[] {
704
+ const out: Finding[] = [];
705
+ const add = (severity: Finding["severity"], code: string, subject: string, message: string): void => {
706
+ out.push({ severity, code, subject, message });
707
+ };
708
+ 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.");
709
+ if (!desk.present) return out;
710
+ const state = readRecord(workspace, ".planning/state.json");
711
+ const manifest = readRecord(workspace, ".planning/project.json");
712
+ const progress = (state?.progress ?? {}) as Json;
713
+ if (state) {
714
+ if (typeof progress.sections_total === "number" && progress.sections_total !== desk.sections.length)
715
+ add("warning", "state-sections-total", "project://state", `state counts ${progress.sections_total} sections; the outline has ${desk.sections.length}.`);
716
+ const complete = desk.sections.filter((section) => section.status === "complete").length;
717
+ if (typeof progress.sections_complete === "number" && progress.sections_complete !== complete)
718
+ add("warning", "state-sections-complete", "project://state", `state counts ${progress.sections_complete} complete sections; the section records say ${complete}.`);
719
+ const recorded = desk.sections.reduce((sum, section) => sum + (section.recorded ?? 0), 0);
720
+ if (typeof progress.word_count === "number" && progress.word_count !== recorded)
721
+ add("warning", "state-word-count", "project://state", `state records ${progress.word_count} words; the section records sum to ${recorded}.`);
722
+ const active = new Set(Array.isArray(state.active_checkpoint_uris) ? (state.active_checkpoint_uris as string[]) : []);
723
+ const pending = new Set(desk.checkpoints.filter((checkpoint) => checkpoint.status === "pending").map((checkpoint) => `project://checkpoints/${checkpoint.id}`));
724
+ for (const uri of active)
725
+ if (!pending.has(uri)) add("warning", "state-active-stale", uri, `state lists ${uri} as active, but it is not a pending checkpoint.`);
726
+ for (const uri of pending)
727
+ if (!active.has(uri)) add("info", "state-active-missing", uri, `${uri} is pending but state does not list it as active.`);
728
+ }
729
+ const manuscripts = new Set(Array.isArray((manifest?.artifacts as Json | undefined)?.manuscripts) ? ((manifest?.artifacts as Json).manuscripts as string[]) : []);
730
+ for (const section of desk.sections) {
731
+ const subject = `project://sections/${section.id}`;
732
+ if (!section.record) {
733
+ if (section.status !== "not-started") add("error", "section-missing", subject, `the outline names ${section.id}, but its section record is missing.`);
734
+ continue;
735
+ }
736
+ const artifacts = (section.record.artifacts ?? {}) as Json;
737
+ for (const uri of [
738
+ ...(Array.isArray(artifacts.plans) ? (artifacts.plans as string[]) : []),
739
+ ...(Array.isArray(artifacts.reviews) ? (artifacts.reviews as string[]) : []),
740
+ ...["context", "research", "summary", "handoff"].map((key) => artifacts[key]).filter((uri): uri is string => typeof uri === "string"),
741
+ ]) {
742
+ const file = artifactFile(workspace, uri, desk.outputFormat);
743
+ if (file === null || readBytes(workspace, file) === null) add("error", "artifact-dangling", subject, `${uri} is linked but does not resolve to a file.`);
744
+ }
745
+ for (const uri of Array.isArray(section.record.checkpoint_uris) ? (section.record.checkpoint_uris as string[]) : [])
746
+ if (!desk.checkpoints.some((checkpoint) => `project://checkpoints/${checkpoint.id}` === uri))
747
+ add("error", "checkpoint-dangling", subject, `${uri} is linked but no such checkpoint exists.`);
748
+ if (section.words > 0) {
749
+ if (section.recorded !== section.words)
750
+ 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.`);
751
+ const uri = typeof artifacts.manuscript === "string" ? artifacts.manuscript : `project://paper/${section.id}`;
752
+ if (!manuscripts.has(uri)) add("warning", "manuscript-unindexed", subject, `${uri} has text but is missing from the manifest's manuscripts index.`);
753
+ if (!planReady(section.plan))
754
+ 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.`);
755
+ }
756
+ }
757
+ for (const checkpoint of desk.checkpoints)
758
+ if (checkpoint.blocking && unconfirmed(checkpoint))
759
+ 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.`);
760
+ return out;
371
761
  }
372
762
 
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
- }
763
+ // --- the lock and the journal ------------------------------------------------
378
764
 
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);
765
+ const SLEEP = new Int32Array(new SharedArrayBuffer(4));
766
+
767
+ /** Runs `work` while this process holds the project's write lock. */
768
+ function withLock<T>(workspace: string, work: () => T): T {
769
+ const planning = contained(workspace, ".planning");
770
+ if (planning === null) throw new Error(".planning is a symbolic link or escapes the project; the desk writes only real project directories");
771
+ mkdirSync(planning, { recursive: true });
772
+ const lock = path.join(workspace, LOCK);
773
+ const deadline = performance.now() + LOCK_WAIT_MS;
774
+ for (;;) {
775
+ try {
776
+ const handle = openSync(lock, "wx", 0o600);
777
+ writeSync(handle, `${process.pid} ${new Date().toISOString()}\n`);
778
+ closeSync(handle);
779
+ break;
780
+ } catch (error) {
781
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
782
+ try {
783
+ if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS) {
784
+ unlinkSync(lock);
785
+ continue;
786
+ }
787
+ } catch {
788
+ continue;
789
+ }
790
+ if (performance.now() > deadline) throw new Error(`another writer holds ${LOCK}; nothing was written, try again`);
791
+ Atomics.wait(SLEEP, 0, 0, 20);
792
+ }
793
+ }
794
+ try {
795
+ return work();
796
+ } finally {
797
+ try {
798
+ unlinkSync(lock);
799
+ } catch {
800
+ // Already gone: a stale-lock sweep by another process is the only way, and it changes nothing here.
801
+ }
394
802
  }
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
803
  }
399
804
 
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.`);
805
+ /**
806
+ * Writes a new file and flushes it where the process may. Node's permission
807
+ * model, which Clio runs the desk under, refuses every flush (fsync,
808
+ * fdatasync, flush: true) with ERR_ACCESS_DENIED, so there a write is still
809
+ * all-or-nothing by its rename but not durable across power loss. A file that
810
+ * could not be written whole is removed.
811
+ */
812
+ function writeDurably(file: string, data: string): void {
813
+ const handle = openSync(file, "wx", 0o644);
814
+ try {
815
+ writeSync(handle, data);
816
+ try {
817
+ fsyncSync(handle);
818
+ } catch (error) {
819
+ if ((error as NodeJS.ErrnoException).code !== "ERR_ACCESS_DENIED") throw error;
820
+ }
821
+ } catch (error) {
822
+ closeSync(handle);
823
+ try {
824
+ unlinkSync(file);
825
+ } catch {
826
+ // Already removed.
827
+ }
828
+ throw error;
419
829
  }
830
+ closeSync(handle);
420
831
  }
421
832
 
422
- // --- views -------------------------------------------------------------------
833
+ /** Fault injection for the package tests; unset in every real session. */
834
+ function fault(point: string): void {
835
+ if (process.env.WTFP_DESK_TEST_FAULT === point) throw new Error(`injected fault at ${point}`);
836
+ }
423
837
 
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)}`;
838
+ interface PendingWrite {
839
+ uri: string;
840
+ file: string;
841
+ text: string;
842
+ sha256: string;
843
+ revision: number | null;
428
844
  }
429
845
 
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";
846
+ interface JournalEntry {
847
+ file: string;
848
+ staging: string;
849
+ sha256: string;
435
850
  }
436
851
 
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")}`;
852
+ const UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
853
+ const STAGING = new RegExp(`\\.${UUID}\\.partial$`, "u");
854
+
855
+ /** Whether a journal entry is one `commit` could have written: a record file and its own staged copy. */
856
+ function journaled(entry: unknown): entry is JournalEntry {
857
+ if (entry === null || typeof entry !== "object") return false;
858
+ const { file, staging, sha256: digest } = entry as Json;
859
+ return (
860
+ typeof file === "string" &&
861
+ RECORD_URIS.some((route) => route.filePattern.test(file)) &&
862
+ typeof staging === "string" &&
863
+ new RegExp(`^${file.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&")}\\.${UUID}\\.partial$`, "u").test(staging) &&
864
+ typeof digest === "string" &&
865
+ /^[a-f0-9]{64}$/u.test(digest)
866
+ );
445
867
  }
446
868
 
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}`;
869
+ /**
870
+ * A failure after the commit point. The write is in place, or the journal
871
+ * finishes it, so it must never be reported as not written. `pending` says
872
+ * recovery still has to finish it.
873
+ */
874
+ class AfterCommit extends Error {
875
+ readonly pending: boolean;
876
+ constructor(message: string, pending: boolean) {
877
+ super(message);
878
+ this.pending = pending;
879
+ }
453
880
  }
454
881
 
455
- function totalWords(desk: Desk): number {
456
- return desk.sections.reduce((sum, section) => sum + section.words, 0);
882
+ /** What a failed write tells the agent: before the commit point nothing changed; after it, the write stands. */
883
+ function failure(refused: string, error: unknown): string {
884
+ const message = error instanceof Error ? error.message : String(error);
885
+ if (error instanceof AfterCommit)
886
+ return error.pending
887
+ ? `Committed; recovery pending: ${message}. The next desk write or /ext:wtfp:validate completes it.`
888
+ : `Committed, but ${message}`;
889
+ return `${refused}: ${message}`;
457
890
  }
458
891
 
459
- function header(desk: Desk): View {
460
- if (!desk.present)
461
- return {
462
- t: "box",
463
- dir: "col",
464
- children: [
465
- { t: "art", lines: WORDMARK, tone: "brand" },
466
- { t: "text", text: "Write The F***ing Paper · no project here yet", tone: "muted" },
467
- ],
468
- };
469
- const facts = [desk.documentType.replaceAll("-", " "), desk.venue, daysLeft(desk.deadline)].filter(
470
- (fact): fact is string => typeof fact === "string",
471
- );
472
- const phaseIndex = PHASES.indexOf(desk.phase as (typeof PHASES)[number]);
473
- return {
474
- t: "box",
475
- dir: "col",
476
- children: [
477
- {
478
- t: "box",
479
- dir: "row",
480
- gap: 2,
481
- children: [
482
- { t: "box", dir: "col", width: 42, children: [{ t: "art", lines: WORDMARK, tone: "brand" }] },
483
- {
484
- t: "box",
485
- dir: "col",
486
- grow: 1,
487
- children: [
488
- { t: "text", text: desk.title, bold: true, wrap: "wrap" },
489
- { t: "text", text: facts.join(" · "), tone: "info" },
490
- ...(desk.argument ? [{ t: "text", text: desk.argument, tone: "muted", wrap: "wrap" } as View] : []),
491
- ],
492
- },
493
- ],
494
- },
495
- {
892
+ function stagingFiles(workspace: string, relative = ".planning"): string[] {
893
+ const directory = contained(workspace, relative);
894
+ if (directory === null || !existsSync(directory) || !lstatSync(directory).isDirectory()) return [];
895
+ const out: string[] = [];
896
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
897
+ const child = path.posix.join(relative, entry.name);
898
+ if (entry.isDirectory() && entry.name !== "archives") out.push(...stagingFiles(workspace, child));
899
+ else if (entry.isFile() && STAGING.test(entry.name)) out.push(child);
900
+ }
901
+ return out;
902
+ }
903
+
904
+ /**
905
+ * Finishes or discards an interrupted commit; call with the lock held. A
906
+ * journal exists only after every staged file was written whole, so finishing it is
907
+ * always safe. Staged files without a journal never became visible and are
908
+ * removed. Returns what it did, or null when there was nothing to do.
909
+ */
910
+ function recover(workspace: string): string | null {
911
+ const journal = path.join(workspace, JOURNAL);
912
+ if (!existsSync(journal)) {
913
+ const orphans = stagingFiles(workspace);
914
+ for (const orphan of orphans) unlinkSync(path.join(workspace, orphan));
915
+ return orphans.length > 0 ? `Removed ${orphans.length} staged file${orphans.length === 1 ? "" : "s"} from a write that never committed.` : null;
916
+ }
917
+ let entries: JournalEntry[];
918
+ try {
919
+ const parsed = JSON.parse(readFileSync(journal, "utf8")) as { entries?: JournalEntry[] };
920
+ entries = Array.isArray(parsed.entries) ? parsed.entries : [];
921
+ } catch {
922
+ const aside = `${JOURNAL}.unreadable-${randomUUID()}`;
923
+ renameSync(journal, path.join(workspace, aside));
924
+ return `Set aside an unreadable journal as ${aside}; check the records it may have touched before continuing.`;
925
+ }
926
+ // The desk journals only its own record writes, each staged beside its target; anything else did not come from a commit.
927
+ const foreign = entries.filter((entry) => !journaled(entry));
928
+ if (foreign.length > 0) {
929
+ const aside = `${JOURNAL}.untrusted-${randomUUID()}`;
930
+ renameSync(journal, path.join(workspace, aside));
931
+ 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.`;
932
+ }
933
+ const finished: string[] = [];
934
+ const drifted: string[] = [];
935
+ for (const entry of entries) {
936
+ const target = contained(workspace, entry.file);
937
+ const staging = contained(workspace, entry.staging);
938
+ if (target === null || staging === null) {
939
+ drifted.push(entry.file);
940
+ continue;
941
+ }
942
+ if (existsSync(staging)) {
943
+ renameSync(staging, target);
944
+ finished.push(entry.file);
945
+ }
946
+ const bytes = readBytes(workspace, entry.file);
947
+ if (bytes === null || sha256(bytes) !== entry.sha256) drifted.push(entry.file);
948
+ }
949
+ unlinkSync(journal);
950
+ for (const orphan of stagingFiles(workspace)) unlinkSync(path.join(workspace, orphan));
951
+ return [
952
+ `Completed an interrupted write of ${entries.map((entry) => entry.file).join(", ")}${finished.length === 0 ? " (every file had already landed)" : ""}.`,
953
+ ...(drifted.length > 0 ? [`These no longer hold what that write committed: ${drifted.join(", ")}; read them before relying on them.`] : []),
954
+ ].join(" ");
955
+ }
956
+
957
+ /**
958
+ * Makes every write visible or, before the commit point, none. One write is
959
+ * a staged file renamed over its target. Several are staged, then a journal
960
+ * naming all of them is written, which is the commit point, then each is
961
+ * renamed into place and the journal removed. Call with the lock held.
962
+ */
963
+ function commit(workspace: string, writes: PendingWrite[]): void {
964
+ const staged: JournalEntry[] = [];
965
+ try {
966
+ for (const write of writes) {
967
+ const target = contained(workspace, write.file);
968
+ if (target === null) throw new Error(`refusing to write ${write.file} through a symbolic link`);
969
+ mkdirSync(path.dirname(target), { recursive: true });
970
+ if (contained(workspace, write.file) === null) throw new Error(`refusing to write ${write.file} through a symbolic link`);
971
+ const staging = `${write.file}.${randomUUID()}.partial`;
972
+ writeDurably(path.join(workspace, staging), write.text);
973
+ staged.push({ file: write.file, staging, sha256: write.sha256 });
974
+ }
975
+ fault("before-commit");
976
+ if (staged.length > 1) {
977
+ const journal = `${JOURNAL}.${randomUUID()}.partial`;
978
+ writeDurably(path.join(workspace, journal), `${JSON.stringify({ schema: "wtfp.clio-journal/v1", at: timestamp(), entries: staged }, null, 2)}\n`);
979
+ renameSync(path.join(workspace, journal), path.join(workspace, JOURNAL));
980
+ }
981
+ } catch (error) {
982
+ for (const entry of staged) {
983
+ try {
984
+ unlinkSync(path.join(workspace, entry.staging));
985
+ } catch {
986
+ // Already removed.
987
+ }
988
+ }
989
+ throw error;
990
+ }
991
+ if (staged.length === 1) {
992
+ // One write commits by its rename; a failed rename changed nothing.
993
+ const [entry] = staged as [JournalEntry];
994
+ try {
995
+ renameSync(path.join(workspace, entry.staging), path.join(workspace, entry.file));
996
+ } catch (error) {
997
+ try {
998
+ unlinkSync(path.join(workspace, entry.staging));
999
+ } catch {
1000
+ // Already removed.
1001
+ }
1002
+ throw error;
1003
+ }
1004
+ } else {
1005
+ // Committed: a failure from here leaves the journal for recover() to finish.
1006
+ try {
1007
+ staged.forEach((entry, index) => {
1008
+ if (index > 0) fault("between-renames");
1009
+ renameSync(path.join(workspace, entry.staging), path.join(workspace, entry.file));
1010
+ });
1011
+ unlinkSync(path.join(workspace, JOURNAL));
1012
+ } catch (error) {
1013
+ throw new AfterCommit(error instanceof Error ? error.message : String(error), true);
1014
+ }
1015
+ }
1016
+ // Stands in for another process changing a file between the rename and the readback.
1017
+ if (process.env.WTFP_DESK_TEST_FAULT === "tamper-after-rename" && staged[0]) appendFileSync(path.join(workspace, staged[0].file), " ");
1018
+ for (const entry of staged) {
1019
+ const back = readBytes(workspace, entry.file);
1020
+ if (back === null || sha256(back) !== entry.sha256)
1021
+ 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);
1022
+ }
1023
+ }
1024
+
1025
+ // --- portable record writes --------------------------------------------------
1026
+
1027
+ const IDENTIFIER = "[a-z][a-z0-9]*(?:-[a-z0-9]+)*";
1028
+ /** The adapter mapping of project/README.md: logical URI to record type and project-relative file. */
1029
+ const RECORD_URIS: ReadonlyArray<{ pattern: RegExp; type: string; file: (id: string) => string; filePattern: RegExp }> = [
1030
+ { pattern: /^project:\/\/manifest$/u, type: "manifest", file: () => ".planning/project.json", filePattern: /^\.planning\/project\.json$/u },
1031
+ { pattern: /^project:\/\/config$/u, type: "config", file: () => ".planning/config.json", filePattern: /^\.planning\/config\.json$/u },
1032
+ { pattern: /^project:\/\/state$/u, type: "state", file: () => ".planning/state.json", filePattern: /^\.planning\/state\.json$/u },
1033
+ { pattern: /^project:\/\/decisions$/u, type: "decisions", file: () => ".planning/decisions.json", filePattern: /^\.planning\/decisions\.json$/u },
1034
+ {
1035
+ pattern: /^project:\/\/structure\/outline$/u,
1036
+ type: "outline",
1037
+ file: () => ".planning/structure/outline.json",
1038
+ filePattern: /^\.planning\/structure\/outline\.json$/u,
1039
+ },
1040
+ ...(
1041
+ [
1042
+ ["section", "sections", (id: string) => `.planning/sections/${id}/section.json`, `^\\.planning/sections/${IDENTIFIER}/section\\.json$`],
1043
+ ["source", "sources", (id: string) => `.planning/sources/${id}.json`, `^\\.planning/sources/${IDENTIFIER}\\.json$`],
1044
+ ["evidence", "evidence", (id: string) => `.planning/evidence/${id}.json`, `^\\.planning/evidence/${IDENTIFIER}\\.json$`],
1045
+ ["checkpoint", "checkpoints", (id: string) => `.planning/checkpoints/${id}.json`, `^\\.planning/checkpoints/${IDENTIFIER}\\.json$`],
1046
+ ["validation", "validations", (id: string) => `.planning/validations/${id}.json`, `^\\.planning/validations/${IDENTIFIER}\\.json$`],
1047
+ ["interaction", "interactions", (id: string) => `.planning/interactions/${id}.json`, `^\\.planning/interactions/${IDENTIFIER}\\.json$`],
1048
+ ] as const
1049
+ ).map(([type, collection, file, filePattern]) => ({
1050
+ pattern: new RegExp(`^project://${collection}/(${IDENTIFIER})$`, "u"),
1051
+ type,
1052
+ file,
1053
+ filePattern: new RegExp(filePattern, "u"),
1054
+ })),
1055
+ ];
1056
+ const REVISIONED = new Set(["state", "outline", "decisions"]);
1057
+ const STAMPED = new Set(["state", "outline", "decisions", "manifest", "section"]);
1058
+
1059
+ interface RecordWrite {
1060
+ uri: string;
1061
+ record: Json;
1062
+ expect_revision?: number;
1063
+ expect_sha256?: string;
1064
+ }
1065
+
1066
+ /** Interaction modes from the least to the most the workflow asks the author. */
1067
+ const MODES = ["autonomous", "standard", "guided"];
1068
+
1069
+ const list = (value: unknown): Json[] => (Array.isArray(value) ? (value as Json[]) : []);
1070
+
1071
+ /**
1072
+ * Changes that weaken an author's control or what the desk holds, each as the
1073
+ * line the author is shown before it may land: a gate, check or safeguard
1074
+ * turned off, a less interactive mode, a locked decision changed, a section
1075
+ * dropped from the outline or no longer researched, a manuscript re-pointed
1076
+ * away from the file its gates hold, plan history rewritten, or a claim
1077
+ * released from needing evidence.
1078
+ */
1079
+ function weakening(type: string, prior: Json | null, next: Json): string[] {
1080
+ const changes: string[] = [];
1081
+ if (type === "config") {
1082
+ for (const group of ["gates", "workflow", "safety"]) {
1083
+ const before = (prior?.[group] ?? {}) as Json;
1084
+ for (const [key, value] of Object.entries((next[group] ?? {}) as Json))
1085
+ if (value === false && before[key] !== false) changes.push(`${group}.${key}: on → off`);
1086
+ }
1087
+ const from = prior ? text(prior.interaction_mode, "standard") : null;
1088
+ const to = text(next.interaction_mode, "standard");
1089
+ if (from === null ? to === "autonomous" : MODES.indexOf(to) < MODES.indexOf(from)) changes.push(`interaction_mode: ${from ?? "unset"} → ${to}`);
1090
+ }
1091
+ if (type === "outline" && prior) {
1092
+ const after = new Map(list(next.sections).map((entry) => [entry.id, entry]));
1093
+ for (const entry of list(prior.sections)) {
1094
+ const kept = after.get(entry.id);
1095
+ if (!kept) changes.push(`removes ${String(entry.id)} from the outline, so the desk no longer holds its manuscript`);
1096
+ else if ((entry.research as Json | undefined)?.required === true && (kept.research as Json | undefined)?.required !== true)
1097
+ changes.push(`${String(entry.id)}: research.required on → off, so its claims may be drafted without verified evidence`);
1098
+ }
1099
+ }
1100
+ if (type === "section" && prior) {
1101
+ const id = text(next.id);
1102
+ const before = (prior.artifacts ?? {}) as Json;
1103
+ const after = (next.artifacts ?? {}) as Json;
1104
+ const mapped = (artifacts: Json): string => text(artifacts.manuscript, `project://paper/${id}`);
1105
+ if (mapped(before) !== mapped(after))
1106
+ changes.push(`${id}: manuscript ${mapped(before)} → ${mapped(after)}, so the desk no longer holds the old file`);
1107
+ const plansBefore = Array.isArray(before.plans) ? (before.plans as unknown[]) : [];
1108
+ const plansAfter = Array.isArray(after.plans) ? (after.plans as unknown[]) : [];
1109
+ if (plansBefore.some((uri, index) => plansAfter[index] !== uri))
1110
+ changes.push(`${id}: rewrites the plan history (${plansBefore.join(", ") || "none"} → ${plansAfter.join(", ") || "none"}); plans are only ever appended`);
1111
+ const claims = new Map(list(next.claims).map((claim) => [claim.id, claim]));
1112
+ for (const claim of list(prior.claims))
1113
+ if (claim.evidence_required === true && claims.get(claim.id)?.evidence_required !== true)
1114
+ changes.push(`${id}: claim ${String(claim.id)} no longer requires evidence`);
1115
+ }
1116
+ if (type === "decisions" && prior) {
1117
+ const after = new Map((Array.isArray(next.items) ? (next.items as Json[]) : []).map((item) => [item.id, item]));
1118
+ for (const item of Array.isArray(prior.items) ? (prior.items as Json[]) : []) {
1119
+ if (item.authority !== "author" || item.disposition !== "locked") continue;
1120
+ const changed = after.get(item.id);
1121
+ if (!changed) changes.push(`removes the author's locked decision ${String(item.id)}: ${text(item.statement)}`);
1122
+ else if (canonical(changed) !== canonical(item))
1123
+ changes.push(`changes the author's locked decision ${String(item.id)} (${text(item.disposition as string)} → ${text(changed.disposition as string)}): ${text(changed.statement)}`);
1124
+ }
1125
+ }
1126
+ return changes;
1127
+ }
1128
+
1129
+ /**
1130
+ * Why the agent may not make this checkpoint change; null when it may.
1131
+ * `superseded` says whether the checkpoint asks about a plan that is no longer
1132
+ * its section's current plan, so retiring it can authorize nothing.
1133
+ */
1134
+ function checkpointRefusal(prior: Json | null, next: Json, superseded: boolean): string | null {
1135
+ const snapshot = next.kind === "state-snapshot";
1136
+ const answered = (status: unknown): boolean => status === "resolved" || status === "waived";
1137
+ if (prior && prior.kind !== next.kind) return "a checkpoint's kind cannot change";
1138
+ if (snapshot) return null;
1139
+ if (prior && answered(prior.status)) return "it is answered, so its record is immutable; create a new checkpoint to ask again";
1140
+ if (next.status === "pending" && next.resolution !== undefined) return "a pending checkpoint carries no resolution";
1141
+ if (answered(next.status)) {
1142
+ if ((next.resolution as Json | undefined)?.resolved_by === "author")
1143
+ return "only the author's answer at the desk resolves it as the author's; call extension_wtfp__gate with its id";
1144
+ if (next.blocking === true) return "a blocking checkpoint is resolved only by the author; call extension_wtfp__gate with its id";
1145
+ }
1146
+ if (prior && prior.status === "pending" && prior.blocking === true) {
1147
+ if (next.blocking !== true) return "a pending blocking checkpoint cannot be made nonblocking";
1148
+ if (next.scope_uri !== prior.scope_uri) return "a pending blocking checkpoint cannot change scope";
1149
+ if (next.status === "expired" && !superseded)
1150
+ return "a pending blocking checkpoint cannot be expired by the agent; the author can waive it at the desk";
1151
+ }
1152
+ return null;
1153
+ }
1154
+
1155
+ /** Whether an armed action's contract declares this write. */
1156
+ function declares(armed: Armed, uri: string, mode: string): boolean {
1157
+ return armed.produces.some((output) => output.mode === mode && patternMatches(output.uri, uri, armed.section));
1158
+ }
1159
+
1160
+ function patternMatches(pattern: string, uri: string, section: string | null): boolean {
1161
+ const expression = pattern
1162
+ .split(/(\{[a-z]+\})/u)
1163
+ .map((part) => {
1164
+ if (part === "{section}" && section) return section.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
1165
+ if (part === "{artifact}") return "[A-Za-z0-9._~-]+(?:/[A-Za-z0-9._~-]+)*";
1166
+ if (/^\{[a-z]+\}$/u.test(part)) return IDENTIFIER;
1167
+ return part.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
1168
+ })
1169
+ .join("");
1170
+ return new RegExp(`^${expression}$`, "u").test(uri);
1171
+ }
1172
+
1173
+ interface Prepared {
1174
+ write: PendingWrite;
1175
+ type: string;
1176
+ prior: Json | null;
1177
+ priorSha: string | null;
1178
+ confirm: string[];
1179
+ }
1180
+
1181
+ /**
1182
+ * Checks one record write against everything the desk enforces and returns
1183
+ * the bytes to commit. Call with the lock held. `origin` is "agent" for a
1184
+ * model's tool call and "desk" for the desk's own writes of the author's
1185
+ * answers and its derived counts.
1186
+ */
1187
+ function prepare(workspace: string, input: RecordWrite, origin: "agent" | "desk", armed: Armed | null): Prepared {
1188
+ const { uri } = input;
1189
+ const record = input.record;
1190
+ if (record === null || typeof record !== "object" || Array.isArray(record)) throw new Error(`${uri}: record must be a JSON object`);
1191
+ const route = RECORD_URIS.find((entry) => entry.pattern.test(uri));
1192
+ if (!route) throw new Error(`${uri} is not a logical record URI this adapter maps`);
1193
+ if (route.type === "interaction" && origin === "agent")
1194
+ throw new Error(`${uri}: only the desk records an author's answer; ask with extension_wtfp__gate`);
1195
+ const id = route.pattern.exec(uri)?.[1] ?? "";
1196
+ if (record.schema !== `wtfp.project.${route.type}/v1`) throw new Error(`${uri} holds wtfp.project.${route.type}/v1 records`);
1197
+ if (id && record.id !== id) throw new Error(`${uri} must hold the record whose id is ${id}`);
1198
+ const file = route.file(id);
1199
+ if (contained(workspace, file) === null) throw new Error(`refusing to write ${uri} through a symbolic link or outside the project`);
1200
+ const manifest = readRecord(workspace, ".planning/project.json");
1201
+ const projectId = route.type === "manifest" ? record.id : record.project_id;
1202
+ if (manifest && typeof manifest.id === "string" && projectId !== manifest.id)
1203
+ throw new Error(`${uri} belongs to project ${String(projectId)}, not ${manifest.id}`);
1204
+ const bytes = readBytes(workspace, file);
1205
+ if (bytes === null && existsSync(path.join(workspace, file))) throw new Error(`${file} is not a regular file the desk can replace`);
1206
+ const priorSha = bytes === null ? null : sha256(bytes);
1207
+ let prior: Json | null = null;
1208
+ if (bytes !== null) {
1209
+ try {
1210
+ const parsed = JSON.parse(bytes.toString("utf8")) as unknown;
1211
+ prior = parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Json) : null;
1212
+ } catch {
1213
+ prior = null;
1214
+ }
1215
+ }
1216
+ const priorRevision = typeof prior?.revision === "number" ? prior.revision : null;
1217
+ const expectation = input.expect_revision !== undefined || input.expect_sha256 !== undefined;
1218
+ if (bytes === null) {
1219
+ if (expectation) throw new Error(`${uri} no longer exists; read the project again before writing`);
1220
+ } else if (!expectation) {
1221
+ throw new Error(
1222
+ `${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`,
1223
+ );
1224
+ } else {
1225
+ const byRevision = input.expect_revision !== undefined && REVISIONED.has(route.type) && input.expect_revision === priorRevision;
1226
+ const bySha = input.expect_sha256 !== undefined && input.expect_sha256 === priorSha;
1227
+ if (!byRevision && !bySha)
1228
+ throw new Error(
1229
+ REVISIONED.has(route.type) && input.expect_revision !== undefined
1230
+ ? `${uri} is at revision ${String(priorRevision)}, not ${input.expect_revision}; read it again before writing`
1231
+ : `${uri} changed since it was read; read it again before writing`,
1232
+ );
1233
+ }
1234
+ if (origin === "agent" && armed && !declares(armed, uri, bytes === null ? "create" : "update"))
1235
+ throw new Error(`${armed.action} does not declare ${bytes === null ? "creating" : "updating"} ${uri}; record what remains as a handoff instead`);
1236
+ if (origin === "agent" && route.type === "checkpoint") {
1237
+ const plan = new RegExp(`^project://sections/(${IDENTIFIER})/plans/${IDENTIFIER}$`, "u").exec(text(prior?.scope_uri));
1238
+ const owner = plan ? readRecord(workspace, `.planning/sections/${plan[1]}/section.json`) : null;
1239
+ const plans = plan && owner?.id === plan[1] ? ((owner.artifacts as Json | undefined)?.plans as unknown[] | undefined) : undefined;
1240
+ const superseded = plan !== null && Array.isArray(plans) && plans.length > 0 && plans[plans.length - 1] !== prior?.scope_uri;
1241
+ const refusal = checkpointRefusal(prior, record, superseded);
1242
+ if (refusal) throw new Error(`${uri}: ${refusal}`);
1243
+ }
1244
+ const next: Json = { ...record };
1245
+ let revision: number | null = null;
1246
+ if (REVISIONED.has(route.type)) {
1247
+ revision = priorRevision === null ? (typeof record.revision === "number" ? record.revision : 0) : priorRevision + 1;
1248
+ next.revision = revision;
1249
+ }
1250
+ if (STAMPED.has(route.type)) next.updated_at = timestamp();
1251
+ const errors = validateRecord(next);
1252
+ if (errors.length > 0) throw new Error(`${uri} would not validate: ${errors[0]}`);
1253
+ const serialized = `${JSON.stringify(next, null, 2)}\n`;
1254
+ return {
1255
+ write: { uri, file, text: serialized, sha256: sha256(serialized), revision },
1256
+ type: route.type,
1257
+ prior,
1258
+ priorSha,
1259
+ confirm: origin === "agent" ? weakening(route.type, prior, next) : [],
1260
+ };
1261
+ }
1262
+
1263
+ function normalizeWrites(input: Json): RecordWrite[] {
1264
+ if (Array.isArray(input.writes)) {
1265
+ if (input.uri !== undefined || input.record !== undefined) throw new Error("pass either uri and record or writes, not both");
1266
+ if (input.writes.length === 0 || input.writes.length > 16) throw new Error("writes holds one to sixteen records");
1267
+ return input.writes as RecordWrite[];
1268
+ }
1269
+ if (typeof input.uri !== "string") throw new Error("uri is required");
1270
+ 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 }];
1271
+ }
1272
+
1273
+ // --- views -------------------------------------------------------------------
1274
+
1275
+ interface Next {
1276
+ command: string | null;
1277
+ reason: string;
1278
+ }
1279
+
1280
+ /** One rung of the ladder; a step only the absent plugin can run says so instead of naming it. */
1281
+ function step(served: ServedPlugin, action: string, args: string, reason: string): Next {
1282
+ const command = commandFor(served, action, args);
1283
+ return command ? { command, reason } : { command: null, reason: `${reason} Its next step, ${action}, needs the WTF-P plugin.` };
1284
+ }
1285
+
1286
+ function openGates(desk: Desk): Checkpoint[] {
1287
+ return desk.checkpoints.filter((checkpoint) => holds(checkpoint));
1288
+ }
1289
+
1290
+ function nextAction(desk: Desk): Next {
1291
+ const served = desk.served;
1292
+ if (!desk.present)
1293
+ return desk.paperExists
1294
+ ? step(served, "map-project", "", "A manuscript exists but no WTF-P project records do.")
1295
+ : step(served, "new-paper", "", "Start a project: brief, decisions and outline.");
1296
+ if (desk.journal) return { command: "/ext:wtfp:validate", reason: "A record write was interrupted; validating completes it." };
1297
+ const gate = openGates(desk)[0];
1298
+ if (gate)
1299
+ return step(
1300
+ served,
1301
+ "check-todos",
1302
+ "",
1303
+ gate.trust === "pending" ? `Gate waiting on you: ${gate.request}` : `Confirm the recorded answer to ${gate.id}: ${gate.request}`,
1304
+ );
1305
+ if (desk.sections.length === 0) return step(served, "create-outline", "", "No outline yet.");
1306
+ const complete = new Set(desk.sections.filter((section) => section.status === "complete").map((section) => section.id));
1307
+ const ordered = [...desk.sections].sort((a, b) => a.wave - b.wave);
1308
+ for (const section of ordered) {
1309
+ if (section.status === "complete") continue;
1310
+ if (!section.dependsOn.every((dep) => complete.has(dep)) && section.status === "not-started") continue;
1311
+ return sectionNext(served, section);
1312
+ }
1313
+ if (desk.phase === "delivered") return { command: null, reason: "Delivered." };
1314
+ if (desk.phase === "ready") return step(served, "submit-milestone", "", "Every section is complete and audited.");
1315
+ return step(served, "audit-milestone", "", "Every section is complete; audit before delivery.");
1316
+ }
1317
+
1318
+ /** The next step for one section, by the same ladder the band follows. */
1319
+ function sectionNext(served: ServedPlugin, section: SectionRow): Next {
1320
+ const id = section.id;
1321
+ if (section.gates.length > 0) return step(served, "check-todos", "", `${section.title} waits on a gate.`);
1322
+ switch (section.status) {
1323
+ case "complete":
1324
+ return step(served, "review-section", id, `${section.title} is complete; review it again if it changed.`);
1325
+ case "blocked":
1326
+ return step(served, "check-todos", "", `${section.title} is blocked.`);
1327
+ case "reviewing":
1328
+ return step(served, "review-section", id, `${section.title} is drafted and waits for review.`);
1329
+ case "writing":
1330
+ case "planned":
1331
+ if (section.research.required && section.unsupported.length > 0)
1332
+ return step(served, "research-gap", id, `${section.title} has required claims without verified evidence.`);
1333
+ if (!planReady(section.plan))
1334
+ return step(served, "plan-section", id, `${section.title} cannot be drafted: ${section.plan.reason}.`);
1335
+ return step(served, "write-section", id, `${section.title} has an approved plan.`);
1336
+ default:
1337
+ if (!section.stages.discuss) return step(served, "discuss-section", id, `Settle what ${section.title} must argue.`);
1338
+ if (section.research.required && (!section.research.present || section.unsupported.length > 0))
1339
+ return step(served, "research-gap", id, `${section.title} needs verified evidence first.`);
1340
+ return step(served, "plan-section", id, `${section.title} is ready to plan.`);
1341
+ }
1342
+ }
1343
+
1344
+ function meter(words: number, target: number, cells = 8): string {
1345
+ if (target <= 0) return "";
1346
+ const filled = Math.max(0, Math.min(cells, Math.round((words / target) * cells)));
1347
+ return `${"▰".repeat(filled)}${"▱".repeat(cells - filled)}`;
1348
+ }
1349
+
1350
+ /** Within 15 percent of the target, by the same count the meter draws. */
1351
+ function tolerance(words: number, target: number): ViewTone {
1352
+ if (target <= 0 || words === 0) return "muted";
1353
+ const delta = Math.abs(words - target) / target;
1354
+ return delta <= 0.15 ? "positive" : words > target ? "warning" : "neutral";
1355
+ }
1356
+
1357
+ function stageStrip(section: SectionRow): string {
1358
+ const active = (stage: keyof SectionRow["stages"]): boolean =>
1359
+ (stage === "discuss" && section.status === "researching") ||
1360
+ (stage === "write" && section.status === "writing") ||
1361
+ (stage === "review" && section.status === "reviewing");
1362
+ const mark = (stage: keyof SectionRow["stages"], letter: string): string =>
1363
+ `${letter}${section.stages[stage] && !active(stage) ? "✓" : active(stage) ? "▸" : "·"}`;
1364
+ return `${mark("discuss", "D")} ${mark("plan", "P")} ${mark("write", "W")} ${mark("review", "R")}`;
1365
+ }
1366
+
1367
+ function daysLeft(deadline: string | null): string | null {
1368
+ if (!deadline) return null;
1369
+ const due = Date.parse(`${deadline}T23:59:59Z`);
1370
+ if (Number.isNaN(due)) return null;
1371
+ const days = Math.ceil((due - Date.now()) / 86_400_000);
1372
+ return days < 0 ? `${-days} days past ${deadline}` : days === 0 ? `due today (${deadline})` : `${days} days to ${deadline}`;
1373
+ }
1374
+
1375
+ function totalWords(desk: Desk): number {
1376
+ return desk.sections.reduce((sum, section) => sum + section.words, 0);
1377
+ }
1378
+
1379
+ function header(desk: Desk): View {
1380
+ if (!desk.present)
1381
+ return {
1382
+ t: "box",
1383
+ dir: "col",
1384
+ children: [
1385
+ { t: "art", lines: WORDMARK, tone: "brand" },
1386
+ { t: "text", text: "Write The F***ing Paper · no project here yet", tone: "muted" },
1387
+ ],
1388
+ };
1389
+ const facts = [desk.documentType.replaceAll("-", " "), desk.venue, daysLeft(desk.deadline)].filter(
1390
+ (fact): fact is string => typeof fact === "string",
1391
+ );
1392
+ const phaseIndex = PHASES.indexOf(desk.phase as (typeof PHASES)[number]);
1393
+ return {
1394
+ t: "box",
1395
+ dir: "col",
1396
+ children: [
1397
+ {
1398
+ t: "box",
1399
+ dir: "row",
1400
+ gap: 2,
1401
+ children: [
1402
+ { t: "box", dir: "col", width: 42, children: [{ t: "art", lines: WORDMARK, tone: "brand" }] },
1403
+ {
1404
+ t: "box",
1405
+ dir: "col",
1406
+ grow: 1,
1407
+ children: [
1408
+ { t: "text", text: desk.title, bold: true, wrap: "wrap" },
1409
+ { t: "text", text: facts.join(" · "), tone: "info" },
1410
+ ...(desk.argument ? [{ t: "text", text: desk.argument, tone: "muted", wrap: "wrap" } as View] : []),
1411
+ ],
1412
+ },
1413
+ ],
1414
+ },
1415
+ {
496
1416
  t: "steps",
497
1417
  items: PHASES.map((phase, index) => ({
498
1418
  label: phase,
@@ -510,6 +1430,27 @@ function header(desk: Desk): View {
510
1430
  };
511
1431
  }
512
1432
 
1433
+ function planBadge(section: SectionRow): { text: string; tone: ViewTone } | null {
1434
+ switch (section.plan.state) {
1435
+ case "approved":
1436
+ return { text: "plan ✓", tone: "positive" };
1437
+ case "policy":
1438
+ return { text: "plan", tone: "info" };
1439
+ case "changed":
1440
+ return { text: "plan changed", tone: "warning" };
1441
+ case "declined":
1442
+ return { text: "plan declined", tone: "warning" };
1443
+ case "unconfirmed":
1444
+ return { text: "plan unconfirmed", tone: "warning" };
1445
+ case "awaiting":
1446
+ return section.status === "not-started" ? null : { text: "plan awaits you", tone: "warning" };
1447
+ case "missing":
1448
+ return { text: "plan missing", tone: "error" };
1449
+ default:
1450
+ return null;
1451
+ }
1452
+ }
1453
+
513
1454
  function board(desk: Desk): View {
514
1455
  if (desk.sections.length === 0)
515
1456
  return { t: "text", text: `No outline yet. ${nextAction(desk).command ?? ""}`.trim(), tone: "muted" };
@@ -523,35 +1464,39 @@ function board(desk: Desk): View {
523
1464
  return {
524
1465
  title: `Wave ${wave} · ${done}/${cards.length}`,
525
1466
  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
- })),
1467
+ cards: cards.slice(0, 60).map((section) => {
1468
+ const plan = planBadge(section);
1469
+ return {
1470
+ key: section.id,
1471
+ title: section.title,
1472
+ detail: [
1473
+ stageStrip(section),
1474
+ section.target > 0 ? `${meter(section.words, section.target)} ${section.words}/${section.target}w` : `${section.words}w`,
1475
+ section.claims.total > 0
1476
+ ? `${section.claims.verified}/${section.claims.total} claims${section.claims.unsupported > 0 ? `, ${section.claims.unsupported} unsupported` : ""}`
1477
+ : "",
1478
+ ]
1479
+ .filter(Boolean)
1480
+ .join(" "),
1481
+ badges: [
1482
+ {
1483
+ text: section.status,
1484
+ tone: (section.status === "complete"
1485
+ ? "positive"
1486
+ : section.status === "blocked"
1487
+ ? "error"
1488
+ : section.status === "not-started"
1489
+ ? "muted"
1490
+ : "info") as ViewTone,
1491
+ },
1492
+ ...(plan ? [plan] : []),
1493
+ ...(section.gates.length > 0 ? [{ text: `GATE ×${section.gates.length}`, tone: "warning" as ViewTone }] : []),
1494
+ ...(section.words > 0 && section.target > 0
1495
+ ? [{ text: `${Math.round((section.words / section.target) * 100)}%`, tone: tolerance(section.words, section.target) }]
1496
+ : []),
1497
+ ],
1498
+ };
1499
+ }),
555
1500
  };
556
1501
  }),
557
1502
  };
@@ -564,12 +1509,12 @@ function agentLabel(agentId: string): string {
564
1509
 
565
1510
  function islands(desk: Desk, running: Record<string, { agentId: string; at: number }>): ExtensionIsland[] {
566
1511
  const out: ExtensionIsland[] = [];
567
- const gate = desk.checkpoints.find((checkpoint) => checkpoint.status === "pending" && checkpoint.blocking);
1512
+ const gate = openGates(desk)[0];
568
1513
  if (gate)
569
1514
  out.push({
570
1515
  key: "gate",
571
1516
  title: "⚑ Gate",
572
- meta: gate.kind,
1517
+ meta: gate.trust === "pending" ? gate.kind : "unconfirmed",
573
1518
  tone: "warning",
574
1519
  view: {
575
1520
  t: "box",
@@ -589,7 +1534,14 @@ function islands(desk: Desk, running: Record<string, { agentId: string; at: numb
589
1534
  } as View,
590
1535
  ]
591
1536
  : []),
592
- { t: "text", text: "Leader c answers it; only your answer resolves it.", tone: "muted" },
1537
+ {
1538
+ t: "text",
1539
+ text:
1540
+ gate.trust === "pending"
1541
+ ? "Leader c answers it; only your answer resolves it."
1542
+ : "Recorded as answered, but not by you at this desk. Leader c confirms it.",
1543
+ tone: "muted",
1544
+ },
593
1545
  ],
594
1546
  },
595
1547
  });
@@ -609,7 +1561,7 @@ function islands(desk: Desk, running: Record<string, { agentId: string; at: numb
609
1561
  { label: "provisional", value: String(provisional), tone: provisional > 0 ? "warning" : "muted" },
610
1562
  ...(lost > 0 ? [{ label: "unavailable or retracted", value: String(lost), tone: "error" as ViewTone }] : []),
611
1563
  { label: "evidence items", value: String(desk.evidence) },
612
- { label: "claims without evidence", value: String(unsupported), tone: unsupported > 0 ? "warning" : "positive" },
1564
+ { label: "required claims without support", value: String(unsupported), tone: unsupported > 0 ? "warning" : "positive" },
613
1565
  ],
614
1566
  },
615
1567
  });
@@ -704,7 +1656,7 @@ async function running(ctx: ExtensionContextV2): Promise<Running> {
704
1656
  }
705
1657
 
706
1658
  async function deskFor(ctx: ExtensionContextV2): Promise<Desk> {
707
- const desk = loadDesk(ctx.snapshot.workspace);
1659
+ const desk = loadDesk(ctx.snapshot.workspace, await storedKey(ctx, false));
708
1660
  desk.invalid = (await ctx.state.get<Desk["invalid"]>("invalid")).value ?? [];
709
1661
  desk.served = ctx.snapshot.plugin ?? null;
710
1662
  return desk;
@@ -721,7 +1673,7 @@ async function picture(
721
1673
  status: current.present
722
1674
  ? {
723
1675
  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",
1676
+ tone: openGates(current).length > 0 || current.journal ? "warning" : "neutral",
725
1677
  }
726
1678
  : null,
727
1679
  band: band(current),
@@ -762,35 +1714,93 @@ async function revalidate(ctx: ExtensionContextV2, files: string[]): Promise<Vie
762
1714
  // --- gates -------------------------------------------------------------------
763
1715
 
764
1716
  const KEEP = "__keep";
1717
+ const RESOLVE = "__resolve";
1718
+ const WAIVE = "__waive";
1719
+
1720
+ /** What the author was shown, kept until the answer arrives so a changed question cannot take an old answer. */
1721
+ interface Asked {
1722
+ checkpoint: string;
1723
+ workspace: string;
1724
+ project: string | null;
1725
+ content_sha256: string;
1726
+ options: string[];
1727
+ artifact: { uri: string; sha256: string } | null;
1728
+ asked_at: string;
1729
+ confirming: boolean;
1730
+ }
765
1731
 
766
- function pendingGates(desk: Desk, skip: readonly string[]): Checkpoint[] {
1732
+ /** The gates that want the author: pending ones, and blocking answers the desk never saw. */
1733
+ function askable(desk: Desk, skip: readonly string[]): Checkpoint[] {
767
1734
  return desk.checkpoints.filter(
768
- (checkpoint) => checkpoint.status === "pending" && checkpoint.kind !== "state-snapshot" && !skip.includes(checkpoint.id),
1735
+ (checkpoint) =>
1736
+ checkpoint.kind !== "state-snapshot" &&
1737
+ !skip.includes(checkpoint.id) &&
1738
+ (checkpoint.status === "pending" || (checkpoint.blocking && unconfirmed(checkpoint))),
769
1739
  );
770
1740
  }
771
1741
 
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
- ];
1742
+ function planGate(checkpoint: Checkpoint): boolean {
1743
+ return new RegExp(`^project://sections/${IDENTIFIER}/plans/${IDENTIFIER}$`, "u").test(checkpoint.scope_uri);
1744
+ }
1745
+
1746
+ /**
1747
+ * The words the author sees for an option. On a plan gate the desk owns them:
1748
+ * `approve` is what authorizes drafting, so it always reads as approval and
1749
+ * nothing else does, whatever the checkpoint's own labels say.
1750
+ */
1751
+ function shown(checkpoint: Checkpoint, option: { id: string; label: string; implication?: string }): { label: string; detail?: string } {
1752
+ if (planGate(checkpoint)) {
1753
+ 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." };
1754
+ 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." };
1755
+ }
1756
+ return { label: option.label, ...(option.implication ? { detail: option.implication } : {}) };
1757
+ }
1758
+
1759
+ function choices(checkpoint: Checkpoint): Array<{ value: string; label: string; detail?: string }> {
1760
+ return checkpoint.options && checkpoint.options.length > 0
1761
+ ? checkpoint.options.map((option) => ({ value: option.id, ...shown(checkpoint, option) }))
1762
+ : [
1763
+ { value: RESOLVE, label: checkpoint.kind === "human-verify" ? "Verified" : "Done", detail: "Mark it resolved by you." },
1764
+ { value: WAIVE, label: "Waive it", detail: "Record that you chose to skip it." },
1765
+ ];
1766
+ }
1767
+
1768
+ function subjectOf(workspace: string, desk: Desk, checkpoint: Checkpoint): { uri: string; sha256: string } | null {
1769
+ const file = artifactFile(workspace, checkpoint.scope_uri, desk.outputFormat);
1770
+ const bytes = file === null ? null : readBytes(workspace, file);
1771
+ return bytes === null ? null : { uri: checkpoint.scope_uri, sha256: sha256(bytes) };
1772
+ }
1773
+
1774
+ async function ask(ctx: ExtensionContextV2, desk: Desk, checkpoint: Checkpoint): Promise<InterviewStep> {
1775
+ const nonce = randomBytes(6).toString("hex");
1776
+ const artifact = subjectOf(ctx.snapshot.workspace, desk, checkpoint);
1777
+ const offered = [...choices(checkpoint), { value: KEEP, label: "Keep it pending", detail: "Answer later; its writes stay blocked." }];
1778
+ const confirming = checkpoint.status !== "pending";
1779
+ await ctx.state.set(`ask:${nonce}`, {
1780
+ checkpoint: checkpoint.id,
1781
+ workspace: ctx.snapshot.workspace,
1782
+ project: desk.projectId,
1783
+ content_sha256: checkpointDigest(checkpoint),
1784
+ options: offered.map((option) => option.value),
1785
+ artifact,
1786
+ asked_at: timestamp(),
1787
+ confirming,
1788
+ } satisfies Asked);
1789
+ const recorded = checkpoint.resolution?.selected_option ?? (checkpoint.status === "waived" ? "waived" : "done");
784
1790
  return {
785
- key: checkpoint.id,
786
- title: checkpoint.blocking ? "Blocking gate" : "Pending task",
1791
+ key: `gate.${nonce}`,
1792
+ title: confirming ? "Confirm a recorded answer" : checkpoint.blocking ? "Blocking gate" : "Pending task",
787
1793
  // The question carries the request; the intro adds only what it cannot.
788
1794
  intro: {
789
1795
  t: "box",
790
1796
  dir: "col",
791
1797
  children: [
792
1798
  ...(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" },
1799
+ ...(confirming
1800
+ ? [{ 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]
1801
+ : []),
1802
+ { t: "text", text: `${checkpoint.kind} · ${checkpoint.scope_uri.replace(/^project:\/\//u, "")} · ${checkpoint.id}`, tone: "muted" },
1803
+ ...(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
1804
  ],
795
1805
  },
796
1806
  questions: [
@@ -798,149 +1808,300 @@ function gateStep(checkpoint: Checkpoint): InterviewStep {
798
1808
  id: "choice",
799
1809
  label: checkpoint.request.length > 120 ? `${checkpoint.request.slice(0, 117)}...` : checkpoint.request,
800
1810
  kind: "single",
801
- options: [...choices, { value: KEEP, label: "Keep it pending", detail: "Answer later; its writes stay blocked." }],
1811
+ options: offered,
802
1812
  },
803
1813
  ],
804
1814
  };
805
1815
  }
806
1816
 
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
- },
1817
+ function interactionId(): string {
1818
+ return `interaction-${timestamp().replace(/[^0-9]/gu, "")}-${randomBytes(4).toString("hex")}`;
1819
+ }
1820
+
1821
+ type AnswerResult = { kind: "recorded" | "kept" | "stale" | "refused"; text: string; checkpoint?: string };
1822
+
1823
+ /**
1824
+ * Records one gate answer. The answer counts only if it names an option the
1825
+ * author was offered for this exact checkpoint, project and subject, and only
1826
+ * once: the binding is consumed before anything is written.
1827
+ */
1828
+ async function answer(ctx: ExtensionContextV2, stepKey: string, picked: unknown): Promise<AnswerResult> {
1829
+ const workspace = ctx.snapshot.workspace;
1830
+ const nonce = /^gate\.([a-f0-9]{12})$/u.exec(stepKey)?.[1];
1831
+ const asked = nonce ? (await ctx.state.get<Asked>(`ask:${nonce}`)).value : undefined;
1832
+ if (!nonce || !asked) return { kind: "refused", text: "That answer matches no open question; nothing was recorded." };
1833
+ await ctx.state.delete(`ask:${nonce}`);
1834
+ const key = await storedKey(ctx, true);
1835
+ if (key === null) return { kind: "refused", text: "The desk could not establish its seal key; nothing was recorded." };
1836
+ const desk = loadDesk(workspace, key);
1837
+ const checkpoint = desk.checkpoints.find((entry) => entry.id === asked.checkpoint);
1838
+ if (asked.workspace !== workspace || asked.project !== desk.projectId)
1839
+ return { kind: "refused", text: "That answer was given for another project; nothing was recorded." };
1840
+ if (typeof picked !== "string" || !asked.options.includes(picked))
1841
+ return { kind: "refused", text: "That answer is not one of the options offered; nothing was recorded." };
1842
+ if (!checkpoint) return { kind: "refused", text: `${asked.checkpoint} no longer exists; nothing was recorded.` };
1843
+ const stillAskable = checkpoint.status === "pending" || (asked.confirming && checkpoint.blocking && unconfirmed(checkpoint));
1844
+ if (!stillAskable) return { kind: "refused", text: `${checkpoint.id} is already ${checkpoint.status}; nothing was recorded.`, checkpoint: checkpoint.id };
1845
+ const now = timestamp();
1846
+ const artifact = subjectOf(workspace, desk, checkpoint);
1847
+ const base: Json = {
1848
+ schema: "wtfp.project.interaction/v1",
1849
+ id: interactionId(),
1850
+ project_id: desk.projectId,
1851
+ kind: "checkpoint-answer",
1852
+ subject_uri: `project://checkpoints/${checkpoint.id}`,
1853
+ channel: "attested-interview",
1854
+ presented: { content_sha256: asked.content_sha256, options: asked.options.filter((option) => option !== KEEP), ...(asked.artifact ? { artifact: asked.artifact } : {}) },
1855
+ asked_at: asked.asked_at,
1856
+ answered_at: now,
843
1857
  };
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,
1858
+ const stale = checkpointDigest(checkpoint) !== asked.content_sha256 || (artifact?.sha256 ?? null) !== (asked.artifact?.sha256 ?? null);
1859
+ const option = checkpoint.options?.find((entry) => entry.id === picked);
1860
+ const interaction = sealed(
1861
+ {
1862
+ ...base,
1863
+ outcome: stale ? "discarded-stale" : picked === KEEP ? "kept-pending" : picked === WAIVE ? "waived" : option ? "selected" : "done",
1864
+ ...(option && !stale ? { selected_option: option.id } : {}),
1865
+ },
1866
+ key,
1867
+ );
1868
+ const writes: Array<{ input: RecordWrite }> = [{ input: { uri: `project://interactions/${String(interaction.id)}`, record: interaction } }];
1869
+ if (!stale && picked !== KEEP) {
1870
+ const { file: _file, trust: _trust, answer: _answer, ...stored } = checkpoint;
1871
+ writes.push({
1872
+ input: {
1873
+ uri: `project://checkpoints/${checkpoint.id}`,
1874
+ expect_sha256: sha256(readBytes(workspace, checkpoint.file) ?? ""),
1875
+ record: {
1876
+ ...stored,
1877
+ status: picked === WAIVE ? "waived" : "resolved",
1878
+ resolution: {
1879
+ resolved_by: "author",
1880
+ ...(option ? { selected_option: option.id } : {}),
1881
+ summary: option
1882
+ ? `The author chose "${shown(checkpoint, option).label}" at the Clio WTF-P desk.`
1883
+ : picked === WAIVE
1884
+ ? "The author waived this gate at the Clio WTF-P desk."
1885
+ : "The author marked this done at the Clio WTF-P desk.",
1886
+ resolved_at: now,
1887
+ },
1888
+ },
1889
+ },
853
1890
  });
1891
+ const state = readRecord(workspace, ".planning/state.json");
1892
+ const uri = `project://checkpoints/${checkpoint.id}`;
1893
+ if (state && Array.isArray(state.active_checkpoint_uris) && state.active_checkpoint_uris.includes(uri))
1894
+ writes.push({
1895
+ input: {
1896
+ uri: "project://state",
1897
+ expect_revision: typeof state.revision === "number" ? state.revision : 0,
1898
+ record: { ...state, active_checkpoint_uris: (state.active_checkpoint_uris as string[]).filter((entry) => entry !== uri) },
1899
+ },
1900
+ });
854
1901
  }
855
- return option ? `${checkpoint.id}: ${option.label}` : `${checkpoint.id}: ${waived ? "waived" : "done"}`;
1902
+ withLock(workspace, () => {
1903
+ recover(workspace);
1904
+ commit(
1905
+ workspace,
1906
+ writes.map((entry) => prepare(workspace, entry.input, "desk", null).write),
1907
+ );
1908
+ });
1909
+ if (stale)
1910
+ return {
1911
+ kind: "stale",
1912
+ 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.`,
1913
+ checkpoint: checkpoint.id,
1914
+ };
1915
+ if (picked === KEEP) return { kind: "kept", text: `${checkpoint.id}: kept pending`, checkpoint: checkpoint.id };
1916
+ return {
1917
+ kind: "recorded",
1918
+ text: option ? `${checkpoint.id}: ${shown(checkpoint, option).label}` : `${checkpoint.id}: ${picked === WAIVE ? "waived" : "done"}`,
1919
+ checkpoint: checkpoint.id,
1920
+ };
856
1921
  }
857
1922
 
858
1923
  async function startGates(ctx: ExtensionContextV2): Promise<ExtensionOutputV2> {
859
1924
  const desk = await deskFor(ctx);
860
- const pending = pendingGates(desk, []);
1925
+ const pending = askable(desk, []);
861
1926
  await ctx.state.set("gate-kept", []);
1927
+ await ctx.state.set("gate-recorded", []);
862
1928
  if (pending.length === 0)
863
1929
  return {
864
1930
  text: "No pending gates or author tasks.",
865
1931
  card: { t: "text", text: "✓ No pending gates or author tasks.", tone: "positive" },
866
1932
  };
867
1933
  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) },
1934
+ text: `${pending.length} gate${pending.length === 1 ? "" : "s"} want${pending.length === 1 ? "s" : ""} your answer.`,
1935
+ interview: { id: "gate", title: "WTF-P gates", total: pending.length, step: await ask(ctx, desk, pending[0] as Checkpoint) },
870
1936
  };
871
1937
  }
872
1938
 
873
- // --- runtime tools -----------------------------------------------------------
1939
+ function choiceOf(answers: Record<string, string | string[]>): unknown {
1940
+ const choice = answers.choice;
1941
+ return Array.isArray(choice) ? (choice.length === 1 ? choice[0] : undefined) : choice;
1942
+ }
874
1943
 
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` },
888
- ];
889
- const REVISIONED = new Set(["state", "outline", "decisions"]);
890
- const STAMPED = new Set(["state", "outline", "decisions", "manifest", "section"]);
1944
+ // --- confirmations of weakening record writes --------------------------------
891
1945
 
892
- function timestamp(): string {
893
- return new Date().toISOString().replace(/\.\d{3}Z$/u, "Z");
1946
+ interface PendingConfirm {
1947
+ write: RecordWrite;
1948
+ workspace: string;
1949
+ project: string | null;
1950
+ base_sha256: string | null;
1951
+ content_sha256: string;
1952
+ changes: string[];
1953
+ asked_at: string;
894
1954
  }
895
1955
 
896
- /**
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.
901
- */
902
- function writePortableRecord(workspace: string, uri: string, input: Json, expectRevision?: number): { file: string; revision: number | null } {
1956
+ async function confirmStep(ctx: ExtensionContextV2, write: RecordWrite, prepared: Prepared): Promise<InterviewStep> {
1957
+ const nonce = randomBytes(6).toString("hex");
1958
+ await ctx.state.set(`confirm:${nonce}`, {
1959
+ write,
1960
+ workspace: ctx.snapshot.workspace,
1961
+ project: readRecord(ctx.snapshot.workspace, ".planning/project.json")?.id as string | null,
1962
+ base_sha256: prepared.priorSha,
1963
+ content_sha256: sha256(canonical(write.record)),
1964
+ changes: prepared.confirm,
1965
+ asked_at: timestamp(),
1966
+ } satisfies PendingConfirm);
1967
+ return {
1968
+ key: `confirm.${nonce}`,
1969
+ title: "Confirm a change to your controls",
1970
+ intro: {
1971
+ t: "box",
1972
+ dir: "col",
1973
+ children: [
1974
+ { 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" },
1975
+ ...prepared.confirm.slice(0, 8).map((change) => ({ t: "text", text: ` ${change}`, tone: "warning", wrap: "wrap" }) as View),
1976
+ ],
1977
+ },
1978
+ questions: [
1979
+ {
1980
+ id: "choice",
1981
+ label: "Apply this change?",
1982
+ kind: "single",
1983
+ options: [
1984
+ { value: "approve", label: "Apply it", detail: "Write the record exactly as shown." },
1985
+ { value: "decline", label: "Keep my current settings", detail: "Nothing is written." },
1986
+ ],
1987
+ },
1988
+ ],
1989
+ };
1990
+ }
1991
+
1992
+ // --- runtime tool handlers ---------------------------------------------------
1993
+
1994
+ async function armedFor(ctx: ExtensionContextV2): Promise<Armed | null> {
1995
+ const armed = (await ctx.state.get<Armed>("armed")).value;
1996
+ if (!armed) return null;
1997
+ // Arming belongs to the workspace and turn it was set in; anything else is stale.
1998
+ if (armed.workspace !== ctx.snapshot.workspace) return null;
1999
+ return armed;
2000
+ }
2001
+
2002
+ async function recordTool(ctx: ExtensionContextV2, input: Json): Promise<{ text: string; data?: unknown; isError?: boolean; interview?: { id: string; title: string; total: number; step: InterviewStep } }> {
2003
+ const workspace = ctx.snapshot.workspace;
2004
+ const armed = await armedFor(ctx);
2005
+ const writes = normalizeWrites(input);
2006
+ const uris = writes.map((write) => write.uri);
2007
+ if (new Set(uris).size !== uris.length) throw new Error("each record may appear once in writes");
2008
+ const outcome = withLock(workspace, (): { recovered: string | null; done: PendingWrite[]; confirm: Prepared | null } => {
2009
+ const recovered = recover(workspace);
2010
+ const prepared = writes.map((write) => prepare(workspace, write, "agent", armed));
2011
+ const weakening = prepared.filter((entry) => entry.confirm.length > 0);
2012
+ if (weakening.length > 0) {
2013
+ 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`);
2014
+ return { recovered, done: [], confirm: prepared[0] as Prepared };
2015
+ }
2016
+ commit(workspace, prepared.map((entry) => entry.write));
2017
+ return { recovered, done: prepared.map((entry) => entry.write), confirm: null };
2018
+ });
2019
+ const { recovered, done } = outcome;
2020
+ if (outcome.confirm) {
2021
+ const write = writes[0] as RecordWrite;
2022
+ return {
2023
+ text: `${write.uri} weakens the author's controls; asking the author.`,
2024
+ interview: { id: "confirm-write", title: "WTF-P · your controls", total: 1, step: await confirmStep(ctx, write, outcome.confirm) },
2025
+ };
2026
+ }
2027
+ return {
2028
+ text: [
2029
+ ...(recovered ? [recovered] : []),
2030
+ ...done.map((write) => `Wrote ${write.uri}${write.revision === null ? "" : ` at revision ${write.revision}`}; it validated and read back (sha256 ${write.sha256}).`),
2031
+ ...(done.length > 1 ? ["They committed together."] : []),
2032
+ ].join(" "),
2033
+ data:
2034
+ done.length === 1
2035
+ ? { uri: done[0]?.uri, file: done[0]?.file, revision: done[0]?.revision, sha256: done[0]?.sha256 }
2036
+ : { writes: done.map((write) => ({ uri: write.uri, file: write.file, revision: write.revision, sha256: write.sha256 })) },
2037
+ };
2038
+ }
2039
+
2040
+ function readTool(ctx: ExtensionContextV2, desk: Desk, uri: string): { text: string; data: unknown } {
2041
+ const workspace = ctx.snapshot.workspace;
903
2042
  const route = RECORD_URIS.find((entry) => entry.pattern.test(uri));
904
2043
  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;
2044
+ const file = route.file(route.pattern.exec(uri)?.[1] ?? "");
2045
+ const bytes = readBytes(workspace, file);
2046
+ if (bytes === null) {
2047
+ if (contained(workspace, file) === null) throw new Error(`${uri} is reached through a symbolic link; the desk does not follow links`);
2048
+ return { text: `${uri} does not exist yet; create it without expect_revision or expect_sha256.`, data: { uri, file, exists: false } };
2049
+ }
2050
+ let record: unknown;
2051
+ try {
2052
+ record = JSON.parse(bytes.toString("utf8"));
2053
+ } catch (error) {
2054
+ throw new Error(`${file} is not valid JSON (${error instanceof Error ? error.message : String(error)})`);
922
2055
  }
923
- if (STAMPED.has(route.type)) record.updated_at = timestamp();
924
- writeRecord(workspace, file, record);
925
- return { file, revision };
2056
+ const revision = typeof (record as Json).revision === "number" ? ((record as Json).revision as number) : null;
2057
+ const checkpoint = route.type === "checkpoint" ? desk.checkpoints.find((entry) => entry.file === file) : undefined;
2058
+ return {
2059
+ text: `${uri}${revision === null ? "" : ` at revision ${revision}`}, sha256 ${sha256(bytes)}${checkpoint ? `, ${checkpoint.status}, author answer ${checkpoint.trust}` : ""}.`,
2060
+ data: { uri, file, exists: true, revision, sha256: sha256(bytes), record, ...(checkpoint ? { trust: checkpoint.trust } : {}) },
2061
+ };
2062
+ }
2063
+
2064
+ function measureSection(workspace: string, sectionId: string, key: Buffer | null, armed: Armed | null): { words: number; target: number; file: string | null; total: number } {
2065
+ return withLock(workspace, () => {
2066
+ recover(workspace);
2067
+ const desk = loadDesk(workspace, key);
2068
+ const section = desk.sections.find((entry) => entry.id === sectionId);
2069
+ if (!section) throw new Error(`no section ${sectionId} in the outline`);
2070
+ const sectionFile = `.planning/sections/${sectionId}/section.json`;
2071
+ const record = readRecord(workspace, sectionFile);
2072
+ if (!record) throw new Error(`${sectionFile} does not exist yet`);
2073
+ const writes: RecordWrite[] = [
2074
+ { uri: `project://sections/${sectionId}`, expect_sha256: sha256(readBytes(workspace, sectionFile) ?? ""), record: { ...record, word_count: section.words } },
2075
+ ];
2076
+ const recorded = desk.sections.reduce((sum, entry) => sum + (entry.id === sectionId ? section.words : (entry.recorded ?? 0)), 0);
2077
+ const state = readRecord(workspace, ".planning/state.json");
2078
+ if (state && typeof state.progress === "object" && state.progress !== null)
2079
+ writes.push({
2080
+ uri: "project://state",
2081
+ expect_revision: typeof state.revision === "number" ? state.revision : 0,
2082
+ record: { ...state, progress: { ...(state.progress as Json), word_count: recorded } },
2083
+ });
2084
+ const prepared = writes.map((write) => prepare(workspace, write, "agent", armed));
2085
+ commit(workspace, prepared.map((entry) => entry.write));
2086
+ return { words: section.words, target: section.target, file: section.manuscript, total: recorded };
2087
+ });
926
2088
  }
927
2089
 
928
- function measureSection(workspace: string, sectionId: string): { words: number; target: number; file: string | null; total: number } {
929
- const desk = loadDesk(workspace);
2090
+ function readiness(desk: Desk, sectionId: string): Json {
930
2091
  const section = desk.sections.find((entry) => entry.id === sectionId);
931
2092
  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 };
2093
+ const reasons = blockers(desk, section);
2094
+ return {
2095
+ section: section.id,
2096
+ ready: reasons.length === 0,
2097
+ reasons,
2098
+ plan: { state: section.plan.state, uri: section.plan.uri, sha256: section.plan.sha256, reason: section.plan.reason },
2099
+ gates: section.gates.map((gate) => ({ id: gate.id, status: gate.status, trust: gate.trust, request: gate.request })),
2100
+ research_required: section.research.required,
2101
+ unsupported_required_claims: section.unsupported,
2102
+ findings: desk.coverage.findings.filter((entry) => entry.subject.startsWith(`project://sections/${section.id}`)),
2103
+ coverage_scope: desk.coverage.scope,
2104
+ };
944
2105
  }
945
2106
 
946
2107
  // --- commands ----------------------------------------------------------------
@@ -961,10 +2122,11 @@ function progressCard(desk: Desk): View {
961
2122
  { label: "words", value: `${totals.toLocaleString("en-US")} / ${desk.targetWords.toLocaleString("en-US")}`, tone: tolerance(totals, desk.targetWords) },
962
2123
  { label: "sections", value: `${desk.sections.filter((section) => section.status === "complete").length} of ${desk.sections.length} complete` },
963
2124
  {
964
- label: "pending gates and tasks",
965
- value: String(pendingGates(desk, []).length),
966
- tone: pendingGates(desk, []).length > 0 ? "warning" : "positive",
2125
+ label: "gates waiting on you",
2126
+ value: String(askable(desk, []).length),
2127
+ tone: askable(desk, []).length > 0 ? "warning" : "positive",
967
2128
  },
2129
+ ...(desk.journal ? [{ label: "interrupted write", value: "pending recovery", tone: "error" as ViewTone }] : []),
968
2130
  ...(daysLeft(desk.deadline) ? [{ label: "deadline", value: daysLeft(desk.deadline) as string }] : []),
969
2131
  { label: "next", value: next.command ? `${next.command} · ${next.reason}` : next.reason, tone: "info" },
970
2132
  ],
@@ -973,12 +2135,13 @@ function progressCard(desk: Desk): View {
973
2135
  ? [
974
2136
  {
975
2137
  t: "table",
976
- columns: ["wave", "section", "status", "stages", "words", "claims", "gates"],
2138
+ columns: ["wave", "section", "status", "stages", "plan", "words", "claims", "gates"],
977
2139
  rows: desk.sections.map((section) => [
978
2140
  String(section.wave),
979
2141
  section.title,
980
2142
  section.status,
981
2143
  stageStrip(section),
2144
+ section.plan.state,
982
2145
  section.target > 0 ? `${section.words}/${section.target}` : String(section.words),
983
2146
  `${section.claims.verified}/${section.claims.total}`,
984
2147
  String(section.gates.length),
@@ -997,7 +2160,8 @@ function progressText(desk: Desk): string {
997
2160
  return [
998
2161
  `${desk.title} · ${desk.phase}`,
999
2162
  `${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`),
2163
+ ...(desk.journal ? ["An interrupted record write awaits recovery."] : []),
2164
+ ...desk.sections.map((section) => ` w${section.wave} ${section.id}: ${section.status} ${stageStrip(section)} plan ${section.plan.state} ${section.words}/${section.target}w`),
1001
2165
  next.command ? `Next: ${next.command} (${next.reason})` : `Next: ${next.reason}`,
1002
2166
  ].join("\n");
1003
2167
  }
@@ -1015,7 +2179,6 @@ function helpCard(served: ServedPlugin): { text: string; card: View } {
1015
2179
  entry.status === "available" ? text(contract.description) : `unavailable: ${entry.unavailableCapabilities.join(", ")}`,
1016
2180
  ];
1017
2181
  });
1018
- const guarded = Object.keys(GUARD.actions).map((id) => actionName(served, id));
1019
2182
  const local = [...DESK_COMMANDS].map((id) => actionName(served, id));
1020
2183
  return {
1021
2184
  text: rows.map((row) => `${row[0]} ${row[1]}`).join("\n"),
@@ -1031,7 +2194,7 @@ function helpCard(served: ServedPlugin): { text: string; card: View } {
1031
2194
  t: "text",
1032
2195
  wrap: "wrap",
1033
2196
  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}`,
2197
+ 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
2198
  },
1036
2199
  ],
1037
2200
  },
@@ -1050,11 +2213,12 @@ function checkpointsCard(desk: Desk): View {
1050
2213
  children: [
1051
2214
  {
1052
2215
  t: "table",
1053
- columns: ["id", "kind", "status", "blocking", "scope"],
2216
+ columns: ["id", "kind", "status", "answer", "blocking", "scope"],
1054
2217
  rows: desk.checkpoints.slice(0, 100).map((checkpoint) => [
1055
2218
  checkpoint.id,
1056
2219
  checkpoint.kind,
1057
2220
  checkpoint.status,
2221
+ checkpoint.trust,
1058
2222
  checkpoint.blocking ? "yes" : "no",
1059
2223
  checkpoint.scope_uri.replace(/^project:\/\//u, ""),
1060
2224
  ]),
@@ -1064,98 +2228,579 @@ function checkpointsCard(desk: Desk): View {
1064
2228
  }
1065
2229
 
1066
2230
  async function validateAll(ctx: ExtensionContextV2): Promise<ExtensionOutputV2> {
1067
- const files = planningRecords(ctx.snapshot.workspace);
2231
+ const workspace = ctx.snapshot.workspace;
2232
+ let recovered: string | null = null;
2233
+ if (contained(workspace, JOURNAL) !== null && existsSync(path.join(workspace, JOURNAL)))
2234
+ recovered = withLock(workspace, () => recover(workspace));
2235
+ const files = planningRecords(workspace);
1068
2236
  const failures = files
1069
- .map((file) => ({ file, errors: validateFile(ctx.snapshot.workspace, file) }))
2237
+ .map((file) => ({ file, errors: validateFile(workspace, file) }))
1070
2238
  .filter((record) => record.errors.length > 0);
1071
2239
  await ctx.state.set(
1072
2240
  "invalid",
1073
2241
  failures.map((record) => ({ file: record.file, errors: record.errors.slice(0, 5) })),
1074
2242
  );
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)),
2243
+ const desk = await deskFor(ctx);
2244
+ const findings: Finding[] = [...reconcile(workspace, desk), ...desk.coverage.findings];
2245
+ const order = ["blocker", "error", "warning", "info"];
2246
+ findings.sort((a, b) => order.indexOf(a.severity) - order.indexOf(b.severity));
2247
+ const serious = findings.filter((finding) => finding.severity !== "info");
2248
+ const lines = [
2249
+ ...(recovered ? [recovered] : []),
2250
+ failures.length === 0 ? `${files.length} records valid against their schemas.` : failures.map((record) => `${record.file}: ${record.errors[0]}`).join("\n"),
2251
+ ...findings.map((finding) => `${finding.severity} ${finding.code} ${finding.subject}: ${finding.message}`),
2252
+ ...(desk.coverage.claims.length > 0 ? [desk.coverage.scope] : []),
2253
+ ];
2254
+ const view: View = {
2255
+ t: "box",
2256
+ dir: "col",
2257
+ border: "round",
2258
+ title: failures.length === 0 && serious.length === 0 ? "WTF-P · records consistent" : "WTF-P · findings",
2259
+ meta: `${files.length} records · ${failures.length} invalid · ${serious.length} findings`,
2260
+ children: [
2261
+ ...(recovered ? [{ t: "text", text: recovered, tone: "warning", wrap: "wrap" } as View] : []),
2262
+ failures.length === 0
2263
+ ? ({ t: "text", text: `✓ ${files.length} planning records valid against their schemas.`, tone: "positive" } as View)
2264
+ : ({ t: "text", text: `✗ ${failures.length} of ${files.length} records fail their schemas.`, tone: "error" } as View),
2265
+ ...failures.slice(0, 4).flatMap((record) => [
2266
+ { t: "text", text: record.file, bold: true, tone: "error" } as View,
2267
+ ...record.errors.slice(0, 2).map((error) => ({ t: "text", text: ` ${error}`, tone: "muted", wrap: "wrap" }) as View),
2268
+ ]),
2269
+ ...(findings.length > 0
2270
+ ? [
2271
+ {
2272
+ t: "table",
2273
+ columns: ["severity", "finding", "subject", "detail"],
2274
+ rows: findings.slice(0, 40).map((finding) => [finding.severity, finding.code, finding.subject.replace(/^project:\/\//u, ""), finding.message]),
2275
+ } as View,
2276
+ ]
2277
+ : []),
2278
+ ...(desk.coverage.claims.length > 0 ? [{ t: "text", text: desk.coverage.scope, tone: "muted", wrap: "wrap" } as View] : []),
2279
+ ],
1093
2280
  };
2281
+ return { text: lines.join("\n"), card: view, ...(await picture(ctx, desk)) };
1094
2282
  }
1095
2283
 
1096
2284
  // --- the write guard ---------------------------------------------------------
1097
2285
 
1098
2286
  interface Armed {
1099
2287
  action: string;
1100
- roots: string[];
2288
+ produces: GuardAction["produces"];
2289
+ section: string | null;
2290
+ workspace: string;
1101
2291
  }
1102
2292
 
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
- );
2293
+ /**
2294
+ * The project roots an armed action's file tools may write, from its declared
2295
+ * outputs. Author-selected materials are never one: a "." root would be the
2296
+ * whole workspace.
2297
+ */
2298
+ function writeRoots(desk: Desk, armed: Armed): string[] {
2299
+ const roots = new Set<string>();
2300
+ const section = armed.section;
2301
+ for (const output of armed.produces) {
2302
+ const uri = output.uri;
2303
+ if (uri.startsWith("project://paper/")) roots.add("paper");
2304
+ else if (uri.startsWith("project://deliverables/")) {
2305
+ const kind = uri.split("/")[3] ?? "";
2306
+ roots.add(kind.startsWith("{") ? "deliverables" : `deliverables/${kind}`);
2307
+ } else if (uri.startsWith("project://archives/")) {
2308
+ const kind = uri.split("/")[3] ?? "";
2309
+ roots.add(kind.startsWith("{") ? ".planning/archives" : `.planning/archives/${kind}`);
2310
+ } else {
2311
+ const match = /^project:\/\/sections\/\{section\}\/(context|research|summary|handoff|plans|reviews)/u.exec(uri);
2312
+ if (match && !section) roots.add(".planning/sections");
2313
+ else if (match) roots.add(match[1] === "plans" || match[1] === "reviews" ? `.planning/sections/${section}/${match[1]}` : `.planning/sections/${section}/${match[1]}.md`);
2314
+ }
2315
+ }
2316
+ if (roots.has("paper") && section) {
2317
+ roots.delete("paper");
2318
+ const row = desk.sections.find((entry) => entry.id === section);
2319
+ for (const root of manuscriptRoots(row)) roots.add(root);
2320
+ }
2321
+ return [...roots].sort();
2322
+ }
2323
+
2324
+ function manuscriptRoots(section: SectionRow | undefined): string[] {
2325
+ if (!section?.manuscript) return [];
2326
+ const stem = section.manuscript.replace(/\.(md|tex|typ)$/u, "");
2327
+ return [section.manuscript, `${stem}/`];
2328
+ }
2329
+
2330
+ /** Every section whose manuscript this file is: its own file, a variant of it, or a file nested under its stem. */
2331
+ function sectionsForPaper(desk: Desk, relative: string): SectionRow[] {
2332
+ return desk.sections.filter((section) => {
2333
+ if (section.manuscript === null) return false;
2334
+ const stem = section.manuscript.replace(/\.(md|tex|typ)$/u, "");
2335
+ return relative === section.manuscript || relative === stem || relative.startsWith(`${stem}.`) || relative.startsWith(`${stem}/`);
2336
+ });
2337
+ }
2338
+
2339
+ function under(root: string, relative: string): boolean {
2340
+ const trimmed = root.replace(/\/$/u, "");
2341
+ return trimmed === "." || relative === trimmed || relative.startsWith(`${trimmed}/`);
2342
+ }
2343
+
2344
+ /** Whether two project paths share a file: one is the other or lies under it. */
2345
+ function overlaps(left: string, right: string): boolean {
2346
+ const a = left.replace(/\/$/u, "");
2347
+ const b = right.replace(/\/$/u, "");
2348
+ return under(a, b) || under(b, a);
2349
+ }
2350
+
2351
+ function block(reason: string): ExtensionHookResult {
2352
+ return { effects: [{ kind: "block_tool", reason }] };
2353
+ }
2354
+
2355
+ /**
2356
+ * What Clio 0.6.3 and later resolve for a tool hook beside its `args`
2357
+ * (public-api-v2 ExtensionToolHookLanding): where a path-taking tool lands,
2358
+ * and a dispatch call's tasks as admission parsed them. The desk judges only
2359
+ * these, never its own reading of a call, so it cannot drift from Clio's
2360
+ * grammar. Clio 0.6.2 sends `args` alone; the desk then refuses writes and
2361
+ * dispatches inside a WTF-P project or action and leaves the rest alone.
2362
+ */
2363
+ interface HostTarget {
2364
+ path: string;
2365
+ resolved: boolean;
2366
+ /** The landing relative to the session's workspace, a worker's task worktree mapped back to the checkout; null outside it. */
2367
+ workspacePath?: string | null;
2368
+ }
2369
+
2370
+ interface HostDispatchTask {
2371
+ role?: string;
2372
+ agent: string;
2373
+ cwd: string;
2374
+ writeRoots: string[];
2375
+ writeBoundaries: string[];
2376
+ worktree: boolean;
2377
+ readOnly: boolean;
2378
+ }
2379
+
2380
+ type HostDispatch =
2381
+ | { kind: "tasks"; mode: string; tasks: HostDispatchTask[]; candidates?: number }
2382
+ | { kind: "list" }
2383
+ | { kind: "apply-winner"; branch: string; cwd: string };
2384
+
2385
+ interface HostLanding {
2386
+ target?: HostTarget;
2387
+ dispatch?: HostDispatch;
2388
+ }
2389
+
2390
+ /** Roles that only judge a dispatch's work; Clio runs them read-only with no write roots. */
2391
+ const GATE_ROLES = new Set(["reviewer", "judge", "member", "synthesis"]);
2392
+
2393
+ const strings = (value: unknown): value is string[] => Array.isArray(value) && value.every((entry) => typeof entry === "string");
2394
+
2395
+ /**
2396
+ * The host's facts for a hook event. A fact in a shape the desk cannot read,
2397
+ * or a dispatch kind it does not know, counts as no fact, and `malformed` says
2398
+ * so: the desk then refuses the call inside a WTF-P project or action and
2399
+ * leaves other folders alone, as for a host that sends none.
2400
+ */
2401
+ function hostLanding(event: unknown): HostLanding & { malformed?: string } {
2402
+ const fields = isObject(event) ? event : {};
2403
+ const landing: HostLanding & { malformed?: string } = {};
2404
+ if (fields.target !== undefined) {
2405
+ const target = fields.target;
2406
+ if (
2407
+ !isObject(target) ||
2408
+ typeof target.path !== "string" ||
2409
+ typeof target.resolved !== "boolean" ||
2410
+ (target.workspacePath !== undefined && target.workspacePath !== null && typeof target.workspacePath !== "string")
2411
+ )
2412
+ landing.malformed = "landing";
2413
+ else landing.target = { path: target.path, resolved: target.resolved, workspacePath: target.workspacePath as string | null | undefined };
2414
+ }
2415
+ if (fields.dispatch !== undefined) {
2416
+ const dispatch = fields.dispatch;
2417
+ const tasks = isObject(dispatch) && dispatch.kind === "tasks" && typeof dispatch.mode === "string" && Array.isArray(dispatch.tasks) ? dispatch.tasks : null;
2418
+ if (isObject(dispatch) && dispatch.kind === "list") landing.dispatch = { kind: "list" };
2419
+ else if (isObject(dispatch) && dispatch.kind === "apply-winner" && typeof dispatch.branch === "string" && typeof dispatch.cwd === "string")
2420
+ landing.dispatch = { kind: "apply-winner", branch: dispatch.branch, cwd: dispatch.cwd };
2421
+ else if (
2422
+ tasks !== null &&
2423
+ tasks.every(
2424
+ (task) =>
2425
+ isObject(task) &&
2426
+ typeof task.agent === "string" &&
2427
+ typeof task.cwd === "string" &&
2428
+ strings(task.writeRoots) &&
2429
+ strings(task.writeBoundaries) &&
2430
+ task.writeRoots.length === task.writeBoundaries.length &&
2431
+ typeof task.worktree === "boolean" &&
2432
+ typeof task.readOnly === "boolean" &&
2433
+ (task.role === undefined || typeof task.role === "string"),
2434
+ )
2435
+ )
2436
+ landing.dispatch = {
2437
+ kind: "tasks",
2438
+ mode: (dispatch as Json).mode as string,
2439
+ tasks: (tasks as Json[]).map((task) => ({
2440
+ ...(task.role === undefined ? {} : { role: task.role as string }),
2441
+ agent: task.agent as string,
2442
+ cwd: task.cwd as string,
2443
+ writeRoots: [...(task.writeRoots as string[])],
2444
+ writeBoundaries: [...(task.writeBoundaries as string[])],
2445
+ worktree: task.worktree as boolean,
2446
+ readOnly: task.readOnly as boolean,
2447
+ })),
2448
+ };
2449
+ else landing.malformed = "dispatch plan";
2450
+ }
2451
+ return landing;
2452
+ }
2453
+
2454
+ function deskOwned(relative: string): boolean {
2455
+ return DESK_OWNED.some((owned) => under(owned, relative)) || /^\.planning\/(?:.*\/)?\.wtfp-/u.test(relative);
2456
+ }
2457
+
2458
+ /** The manuscripts a write must not reach now: those of sections that are not ready to draft. */
2459
+ function heldManuscripts(desk: Desk): { roots: string[]; notes: string[] } {
2460
+ const roots: string[] = [];
2461
+ const notes: string[] = [];
2462
+ for (const section of desk.sections) {
2463
+ const reasons = blockers(desk, section);
2464
+ if (reasons.length === 0) continue;
2465
+ roots.push(...manuscriptRoots(section));
2466
+ notes.push(`${section.id}: ${reasons.join("; ")}`);
2467
+ }
2468
+ return { roots, notes };
2469
+ }
2470
+
2471
+ /**
2472
+ * The held manuscript a worker root would reach, judged like a direct write:
2473
+ * by every section the path belongs to, so a `.tex` or `.typ` spelling of a
2474
+ * section whose file does not exist yet is held too.
2475
+ */
2476
+ function heldBy(desk: Desk, held: string[], root: string): string | undefined {
2477
+ const hit = held.find((file) => overlaps(root, file));
2478
+ if (hit) return hit;
2479
+ const lexical = root.replace(/\/$/u, "");
2480
+ return sectionsForPaper(desk, lexical).some((section) => blockers(desk, section).length > 0) ? lexical : undefined;
2481
+ }
2482
+
2483
+ /** Whether the session is in a WTF-P project or inside a WTF-P action, where a call the desk cannot judge is refused. */
2484
+ async function projectOrArmed(ctx: ExtensionContextV2): Promise<boolean> {
2485
+ if (await armedFor(ctx)) return true;
2486
+ return loadDesk(ctx.snapshot.workspace, await storedKey(ctx, false)).present;
2487
+ }
2488
+
2489
+ /** Why a host that sends no landing or dispatch plan cannot be guarded. */
2490
+ 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.";
2491
+
2492
+ /** Why a call Clio sent no usable facts for is refused, once this Clio has shown it sends them. */
2493
+ async function missingFacts(ctx: ExtensionContextV2, malformed: string | undefined): Promise<string> {
2494
+ if (malformed) return `Clio's ${malformed} for this call is in a form the desk cannot read; refused.`;
2495
+ 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;
2496
+ }
2497
+
2498
+ /**
2499
+ * Where a write lands, relative to the project, or null outside it, as Clio
2500
+ * resolved it: the file the tool opens, which Clio refuses to change before
2501
+ * the tool runs, and for a worker in a task worktree the checkout path it
2502
+ * merges into.
2503
+ */
2504
+ function writeLanding(target: string, workspace: string, host: HostTarget): { relative: string | null } | { refused: string } {
2505
+ 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.` };
2506
+ if (host.workspacePath !== undefined) return { relative: host.workspacePath };
2507
+ const root = realWorkspace(workspace);
2508
+ return { relative: inside(root, host.path) ? posix(path.relative(root, host.path)) || "." : null };
1109
2509
  }
1110
2510
 
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 {};
2511
+ async function guardWrite(ctx: ExtensionContextV2, target: string, host?: HostTarget, malformed?: string): Promise<ExtensionHookResult> {
1114
2512
  const workspace = ctx.snapshot.workspace;
1115
2513
  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
- };
2514
+ if (!host) return (await projectOrArmed(ctx)) ? block(`WTF-P write guard: ${await missingFacts(ctx, malformed)}`) : {};
2515
+ const landed = writeLanding(target, workspace, host);
2516
+ if ("refused" in landed) return block(landed.refused);
2517
+ if (landed.relative === null) return {};
2518
+ const relative = landed.relative;
2519
+ if (deskOwned(relative)) return block(`WTF-P write guard: ${relative} is written only by the desk; nothing else may change it.`);
2520
+ if (under(".planning", relative) && relative.endsWith(".json") && !under(".planning/archives", relative))
2521
+ return block(
2522
+ `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.`,
2523
+ );
2524
+ const desk = loadDesk(workspace, await storedKey(ctx, false));
2525
+ const armed = await armedFor(ctx);
2526
+ // Clio's own artifact directory is no project file; a link that leads it into the project lands, and is judged, elsewhere.
2527
+ if (armed && !under(".clio-coder/artifacts", relative)) {
2528
+ const roots = writeRoots(desk, armed);
2529
+ if (!roots.some((allowed) => under(allowed, relative)))
2530
+ return block(
2531
+ `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.`,
2532
+ );
1129
2533
  }
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 {};
2534
+ for (const section of desk.sections) {
2535
+ const linked = Array.isArray((section.record?.artifacts as Json | undefined)?.plans) ? (((section.record?.artifacts as Json).plans as string[]) ?? []) : [];
2536
+ for (const uri of linked)
2537
+ if (artifactFile(workspace, uri) === relative)
2538
+ return block(`WTF-P write guard: ${relative} is a linked plan, and linked plans are immutable; write a revision plan instead.`);
2539
+ }
2540
+ if (!under("paper", relative) || !desk.present) return {};
2541
+ // A file can be the manuscript of more than one section (one nested under another's stem); every one must be ready.
2542
+ const held = sectionsForPaper(desk, relative)
2543
+ .map((section) => ({ section, reasons: blockers(desk, section) }))
2544
+ .find((entry) => entry.reasons.length > 0);
2545
+ if (!held) return {};
2546
+ const { section, reasons } = held;
1135
2547
  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 {};
2548
+ return block(
2549
+ `WTF-P gate: ${section.title} cannot be written yet: ${reasons.join("; ")}. ${
2550
+ gate
2551
+ ? `Answer it with ${actionName(served, "check-todos")}.`
2552
+ : !planReady(section.plan)
2553
+ ? commandFor(served, "plan-section", section.id) !== null
2554
+ ? `Run ${commandFor(served, "plan-section", section.id)} and approve its plan at the gate.`
2555
+ : "Planning it needs the WTF-P plugin; approve a plan at the gate."
2556
+ : `Run ${actionName(served, "research-gap")} for it first.`
2557
+ }`,
2558
+ );
2559
+ }
2560
+
2561
+ /** Narrows requested write roots to those inside the allowed ones; a broader request becomes the allowed roots inside it. */
2562
+ function narrow(requested: string[], allowed: string[]): string[] {
2563
+ const out = new Set<string>();
2564
+ for (const want of requested) {
2565
+ for (const root of allowed) {
2566
+ const bare = root.replace(/\/$/u, "");
2567
+ if (under(bare, want)) out.add(want);
2568
+ else if (under(want, bare)) out.add(root);
2569
+ }
2570
+ }
2571
+ return [...out].sort();
2572
+ }
2573
+
2574
+ const WTFP_AGENT = /^wtfp-[a-z-]+$/u;
2575
+
2576
+ /** One worker a dispatch names, as Clio parsed it. */
2577
+ interface DispatchTask {
2578
+ /** The agent Clio resolved, `auto` and an omitted agent included. */
2579
+ agent: string;
2580
+ /** Project-relative write roots, or null when the worker would have no boundary. */
2581
+ roots: string[] | null;
2582
+ /** True when Clio runs the worker read-only, as it does every read-only recipe's; it then has no write roots. */
2583
+ readOnly: boolean;
2584
+ }
2585
+
2586
+ function isObject(value: unknown): value is Json {
2587
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2588
+ }
2589
+
2590
+ /** A write root as a plain project path: no `./`, doubled or trailing slash. */
2591
+ function plainSpelling(root: string): string {
2592
+ return root.trim().replace(/\/{2,}/gu, "/").replace(/^(?:\.\/)+/u, "").replace(/\/$/u, "");
2593
+ }
2594
+
2595
+ /**
2596
+ * The workers a dispatch starts, from the plan Clio parsed. Gate roles only
2597
+ * judge, so they are left out. Every worker runs from the project root, no
2598
+ * writer works in a task worktree whose merge the desk would not see, and a
2599
+ * write root must land where it reads: Clio fixes a boundary at the root's
2600
+ * physical location, so a root through a link would let a worker write
2601
+ * wherever the link points. A root that lands on the whole project is no
2602
+ * boundary. Throws for any of these. Clio judges a rewritten call again, so
2603
+ * the roots the desk itself hands a worker are checked the same way.
2604
+ */
2605
+ function planTasks(plan: Extract<HostDispatch, { kind: "tasks" }>, workspace: string, present: boolean): DispatchTask[] {
2606
+ const root = realWorkspace(workspace);
2607
+ for (const task of plan.tasks)
2608
+ 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.");
2609
+ if (present && plan.tasks.some((task) => task.worktree && !task.readOnly))
2610
+ 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.");
2611
+ // With no role reported, every task is one the call named.
2612
+ return plan.tasks
2613
+ .filter((task) => task.role === undefined || !GATE_ROLES.has(task.role))
2614
+ .map((task) => {
2615
+ let unbounded = task.writeRoots.length === 0;
2616
+ const roots: string[] = [];
2617
+ task.writeRoots.forEach((spelled, index) => {
2618
+ const boundary = task.writeBoundaries[index] as string;
2619
+ const landed = inside(root, boundary) ? posix(path.relative(root, boundary)) || "." : null;
2620
+ if (landed === ".") {
2621
+ unbounded = true;
2622
+ return;
2623
+ }
2624
+ if (landed === null || landed !== plainSpelling(spelled))
2625
+ 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.`);
2626
+ roots.push(`${landed}${spelled.trim().endsWith("/") ? "/" : ""}`);
2627
+ });
2628
+ return { agent: task.agent, roots: unbounded ? null : roots, readOnly: task.readOnly };
2629
+ });
2630
+ }
2631
+
2632
+ /** The call's arguments without Clio's private admission keys, which Clio recomputes for any rewritten call. */
2633
+ function withoutHostKeys(args: Json): Json {
2634
+ return Object.fromEntries(Object.entries(args).filter(([key]) => !key.startsWith("__clio_")));
2635
+ }
2636
+
2637
+ /**
2638
+ * The call with each named worker held to its roots, in the shape Clio
2639
+ * prepares for hooks: `tasks` an array of task objects or task strings, one
2640
+ * per named worker, whose own intent overrides the shared one.
2641
+ */
2642
+ function confineCall(args: Json, narrowed: Array<string[] | null>): Json {
2643
+ const confine = (item: unknown, roots: string[] | null): unknown => {
2644
+ if (roots === null) return item;
2645
+ const task = typeof item === "string" ? { task: item } : (item as Json);
2646
+ return { ...task, intent: { ...(isObject(task.intent) ? task.intent : {}), write_roots: roots } };
2647
+ };
2648
+ const tasks = args.tasks;
2649
+ if (args.tasks === undefined && narrowed.length === 1) return { ...withoutHostKeys(args), intent: { ...(isObject(args.intent) ? args.intent : {}), write_roots: narrowed[0] } };
2650
+ if (Array.isArray(tasks) && tasks.length === narrowed.length && tasks.every((item) => isObject(item) || typeof item === "string"))
2651
+ return { ...withoutHostKeys(args), tasks: tasks.map((item, index) => confine(item, narrowed[index] ?? null)) };
2652
+ 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.");
2653
+ }
2654
+
2655
+ const sameRoots = (left: string[] | null, right: string[] | null): boolean =>
2656
+ left !== null && right !== null && left.length === right.length && [...left].sort().every((root, index) => root === [...right].sort()[index]);
2657
+
2658
+ async function guardDispatch(ctx: ExtensionContextV2, args: Json, host?: HostDispatch, malformed?: string): Promise<ExtensionHookResult> {
2659
+ if (args.list === true || host?.kind === "list") return {};
2660
+ // Clio could not prepare this call and refuses it itself, with its own reason; nothing of it runs.
2661
+ if (!host && typeof args.__clio_dispatch_plan_preparation_error === "string") return {};
2662
+ if (!host) return (await projectOrArmed(ctx)) ? block(`WTF-P dispatch guard: ${await missingFacts(ctx, malformed)}`) : {};
2663
+ const workspace = ctx.snapshot.workspace;
2664
+ const served = ctx.snapshot.plugin ?? null;
2665
+ const desk = loadDesk(workspace, await storedKey(ctx, false));
2666
+ const armed = await armedFor(ctx);
2667
+ if (!desk.present && !armed) {
2668
+ // Outside a WTF-P project and action, only the WTF-P recipes are the desk's business.
2669
+ const wtfp = host.kind === "tasks" ? host.tasks.filter((task) => WTFP_AGENT.test(task.agent)).map((task) => task.agent) : [];
2670
+ return wtfp.length > 0
2671
+ ? 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.`)
2672
+ : {};
2673
+ }
2674
+ if (desk.present && (args.from_scout !== undefined || host.kind === "apply-winner"))
2675
+ 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.");
2676
+ if (host.kind !== "tasks") return {};
2677
+ const entries = planTasks(host, workspace, desk.present);
2678
+ if (!armed) {
2679
+ const wtfp = entries.filter((entry) => WTFP_AGENT.test(entry.agent));
2680
+ if (wtfp.length > 0)
2681
+ return block(
2682
+ `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.`,
2683
+ );
2684
+ // Workers run no desk check, so outside an action each must be kept off the records and the manuscripts still held.
2685
+ const held = [".planning/", ...heldManuscripts(desk).roots];
2686
+ for (const entry of entries) {
2687
+ if (entry.readOnly) continue;
2688
+ if (entry.roots === null)
2689
+ return block(
2690
+ `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.`,
2691
+ );
2692
+ for (const root of entry.roots) {
2693
+ const hit = heldBy(desk, held, root);
2694
+ if (hit) return block(`WTF-P dispatch guard: write root ${root} reaches ${hit}, which a worker outside a WTF-P action may not change.`);
2695
+ }
2696
+ }
2697
+ return {};
2698
+ }
2699
+ const name = actionName(served, armed.action);
2700
+ // A worker never gets a root that holds records: the record tool is the only way records change.
2701
+ const base = writeRoots(desk, armed).filter((root) => ![".", ".planning", ".planning/sections"].includes(root.replace(/\/$/u, "")));
2702
+ const held = heldManuscripts(desk);
2703
+ let allowed = base;
2704
+ const notes: string[] = [];
2705
+ if (base.includes("paper")) {
2706
+ // Without a named section, a worker may reach only manuscripts whose sections are ready now.
2707
+ notes.push(...held.notes);
2708
+ allowed = [...base.filter((root) => root !== "paper"), ...desk.sections.filter((section) => blockers(desk, section).length === 0).flatMap((section) => manuscriptRoots(section))];
2709
+ } else if (armed.section) {
2710
+ const section = desk.sections.find((entry) => entry.id === armed.section);
2711
+ const reasons = section ? blockers(desk, section) : [];
2712
+ if (section && reasons.length > 0 && base.some((root) => root.startsWith("paper/"))) notes.push(`${section.id}: ${reasons.join("; ")}`);
2713
+ }
2714
+ // No worker root may cover a manuscript that is still held, even one nested under a ready section's stem.
2715
+ allowed = [...new Set(allowed.filter((root) => !held.roots.some((file) => overlaps(root, file))))].sort();
2716
+ const sectionScoped = armed.produces.some((output) => output.uri.includes("{section}"));
2717
+ const paperWriters = new Set(GUARD.paperWriters);
2718
+ const narrowed = entries.map((entry): string[] | null => {
2719
+ if (entry.readOnly) return null;
2720
+ const roots = entry.roots === null ? allowed : narrow(entry.roots, allowed);
2721
+ if (paperWriters.has(entry.agent) && !roots.some((root) => root.startsWith("paper/")))
2722
+ throw new Error(
2723
+ `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."}`,
2724
+ );
2725
+ if (roots.length > 0) return roots;
2726
+ // Clio reads an empty write_roots as no boundary at all, so an empty list is refused, never sent.
2727
+ if (entry.roots !== null && allowed.length > 0)
2728
+ throw new Error(`WTF-P dispatch guard: ${entry.roots.join(", ")} lie outside what ${armed.action} may write (${allowed.join(", ")}).`);
2729
+ throw new Error(
2730
+ sectionScoped && armed.section === null
2731
+ ? `WTF-P dispatch guard: ${name} names no section, so its workers would reach every section's records; name the section in the command.`
2732
+ : `WTF-P dispatch guard: ${name} declares no file outputs a worker may write; only its read-only reviewers may be dispatched.`,
2733
+ );
2734
+ });
2735
+ const writers = entries.filter((entry, index) => narrowed[index] !== null);
2736
+ if (writers.length > 1 && writers.some((entry) => entry.roots === null))
2737
+ return block(
2738
+ `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.`,
2739
+ );
2740
+ // A worker whose roots already are its confinement, in any order, needs no rewrite.
2741
+ const needed = narrowed.map((roots, index) => (roots === null || sameRoots(roots, entries[index]?.roots ?? null) ? null : roots));
2742
+ if (needed.every((roots) => roots === null)) return {};
2743
+ // Clio admits a rewritten call afresh, without the operator's approval of the original, so a call
2744
+ // that needs approval (more than one worker, a review loop, compete) is refused with the exact roots instead.
2745
+ if (host.tasks.length > 1)
2746
+ return block(
2747
+ `WTF-P dispatch guard: give each worker exactly these intent.write_roots, so the call you approve runs unchanged: ${entries
2748
+ .map((entry, index) => `task ${index + 1} (${entry.agent}): ${(narrowed[index] ?? []).join(", ") || "none, it only reads"}`)
2749
+ .join("; ")}.`,
2750
+ );
2751
+ const rewritten = confineCall(args, needed);
2752
+ return {
2753
+ effects: [
2754
+ {
2755
+ kind: "rewrite_tool_input",
2756
+ args: rewritten,
2757
+ reason: `WTF-P confines ${name} workers to ${[...new Set(narrowed.flatMap((roots) => roots ?? []))].join(", ") || "no writes"}.`,
2758
+ },
2759
+ ],
2760
+ };
2761
+ }
2762
+
2763
+ const BASH_DESK_PATHS = /\.planning\/(?:interactions\b|\.wtfp-)/u;
2764
+ /** Tools that run a command or script; the desk can only refuse ones that name its own records. */
2765
+ const COMMAND_TOOLS = new Set(["bash", "run_script", "job"]);
2766
+
2767
+ async function guard(ctx: ExtensionContextV2, tool: string, args: unknown, event: unknown = {}): Promise<ExtensionHookResult> {
2768
+ const input = args !== null && typeof args === "object" ? (args as Json) : {};
2769
+ const effects: ExtensionEffect[] = [];
2770
+ if (!(await ctx.state.get<boolean>("protected")).value) {
2771
+ // The host's protected-artifact guard then refuses bash rm, mv, cp and redirects into the desk's own records.
2772
+ effects.push({ kind: "protect_path", path: path.join(ctx.snapshot.workspace, ".planning", "interactions"), reason: "WTF-P author answers are written only by the desk." });
2773
+ await ctx.state.set("protected", true);
2774
+ }
2775
+ let result: ExtensionHookResult = {};
2776
+ try {
2777
+ const host = hostLanding(event);
2778
+ // A host that sends facts once sends them for every call it can resolve, so a later call without them failed in Clio.
2779
+ if ((host.target || host.dispatch) && !(await ctx.state.get<boolean>("host-facts")).value) await ctx.state.set("host-facts", true);
2780
+ if (tool === "dispatch") result = await guardDispatch(ctx, input, host.dispatch, host.malformed);
2781
+ else if (COMMAND_TOOLS.has(tool)) {
2782
+ 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.");
2783
+ } else {
2784
+ const raw = input.path ?? input.file_path ?? input.filePath;
2785
+ // The artifact tool trims its path; without one it writes under Clio's own artifact directory, where Clio's landing still says it lands.
2786
+ const target = typeof raw === "string" ? (tool === "artifact" ? raw.trim() : raw) : "";
2787
+ if (target.length > 0 || host.target) result = await guardWrite(ctx, target || "the artifact", host.target, host.malformed);
2788
+ }
2789
+ } catch (error) {
2790
+ result = block(error instanceof Error ? error.message : String(error));
2791
+ }
2792
+ return effects.length === 0 ? result : { ...result, effects: [...effects, ...(result.effects ?? [])] };
2793
+ }
2794
+
2795
+ function arm(text: string, desk: Desk, workspace: string): Armed | null {
2796
+ const match = /^\s*\/wtfp:([a-z][a-z0-9-]*)(?:\s+(\S+))?/u.exec(text);
2797
+ if (!match) return null;
2798
+ const action = GUARD.actions[match[1] as string];
2799
+ if (!action) return null;
2800
+ const candidate = match[2] ?? "";
2801
+ const sectionScoped = action.produces.some((output) => output.uri.includes("{section}"));
2802
+ const section = sectionScoped && desk.sections.some((entry) => entry.id === candidate) ? candidate : null;
2803
+ return { action: match[1] as string, produces: action.produces, section, workspace };
1159
2804
  }
1160
2805
 
1161
2806
  // --- registration ------------------------------------------------------------
@@ -1174,7 +2819,7 @@ export default function extension(api: ExtensionApiV2): void {
1174
2819
  api.handle("checkpoints", async (_args, ctx) => {
1175
2820
  const desk = await deskFor(ctx);
1176
2821
  return {
1177
- text: desk.checkpoints.map((checkpoint) => `${checkpoint.id} ${checkpoint.kind} ${checkpoint.status}`).join("\n") || "No checkpoints.",
2822
+ text: desk.checkpoints.map((checkpoint) => `${checkpoint.id} ${checkpoint.kind} ${checkpoint.status} ${checkpoint.trust}`).join("\n") || "No checkpoints.",
1178
2823
  card: checkpointsCard(desk),
1179
2824
  };
1180
2825
  });
@@ -1200,105 +2845,213 @@ export default function extension(api: ExtensionApiV2): void {
1200
2845
  });
1201
2846
 
1202
2847
  api.tool("record", async (input, ctx) => {
1203
- const { uri, record, expect_revision } = input as { uri: string; record: Json; expect_revision?: number };
1204
2848
  try {
1205
- const written = writePortableRecord(ctx.snapshot.workspace, uri, record, expect_revision);
2849
+ return await recordTool(ctx, (input ?? {}) as Json);
2850
+ } catch (error) {
2851
+ return { text: failure("Not written", error), isError: true };
2852
+ }
2853
+ });
2854
+ api.tool("read_record", async (input, ctx) => {
2855
+ try {
2856
+ return readTool(ctx, await deskFor(ctx), String((input as Json).uri ?? ""));
2857
+ } catch (error) {
2858
+ return { text: `Not read: ${error instanceof Error ? error.message : String(error)}`, isError: true };
2859
+ }
2860
+ });
2861
+ api.tool("readiness", async (input, ctx) => {
2862
+ try {
2863
+ const report = readiness(await deskFor(ctx), String((input as Json).section ?? ""));
1206
2864
  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 },
2865
+ text:
2866
+ report.ready === true
2867
+ ? `${String(report.section)} may be drafted: ${(report.plan as Json).reason as string}. ${coverage.STRUCTURAL_SCOPE}`
2868
+ : `${String(report.section)} may not be drafted yet: ${(report.reasons as string[]).join("; ")}.`,
2869
+ data: report,
1209
2870
  };
1210
2871
  } catch (error) {
1211
- return { text: `Not written: ${error instanceof Error ? error.message : String(error)}`, isError: true };
2872
+ return { text: `No readiness: ${error instanceof Error ? error.message : String(error)}`, isError: true };
1212
2873
  }
1213
2874
  });
1214
2875
  api.tool("measure_section", async (input, ctx) => {
1215
2876
  try {
1216
- const measured = measureSection(ctx.snapshot.workspace, (input as { section: string }).section);
2877
+ const measured = measureSection(ctx.snapshot.workspace, String((input as Json).section ?? ""), await storedKey(ctx, false), await armedFor(ctx));
1217
2878
  const share = measured.target > 0 ? Math.round((measured.words / measured.target) * 100) : null;
1218
2879
  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}`,
2880
+ 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, which committed together; the paper totals ${measured.total}. ${WORD_METHOD}`,
1220
2881
  data: measured,
1221
2882
  };
1222
2883
  } catch (error) {
1223
- return { text: `Not measured: ${error instanceof Error ? error.message : String(error)}`, isError: true };
2884
+ return { text: failure("Not measured", error), isError: true };
1224
2885
  }
1225
2886
  });
1226
2887
  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);
2888
+ const id = String((input as Json).checkpoint ?? "");
2889
+ const desk = await deskFor(ctx);
2890
+ const checkpoint = desk.checkpoints.find((entry) => entry.id === id);
1229
2891
  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) } };
2892
+ if (!askable(desk, []).includes(checkpoint)) return { text: `${id} is already ${checkpoint.status}${checkpoint.trust === "attested" ? " by the author at this desk" : ""}.` };
2893
+ return { text: `Asking the author: ${checkpoint.request}`, interview: { id: "gate-one", title: "WTF-P gate", total: 1, step: await ask(ctx, desk, checkpoint) } };
1232
2894
  });
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)) };
2895
+ api.interview("gate-one", async (event, ctx): Promise<InterviewNext> => {
2896
+ if (event.nav === "cancel")
2897
+ return {
2898
+ done: true,
2899
+ text:
2900
+ event.reason === "headless"
2901
+ ? "No author could be asked in this headless session; the gate stays pending and authorizes nothing."
2902
+ : "The author did not answer; the gate stays pending.",
2903
+ };
2904
+ try {
2905
+ const result = await answer(ctx, event.step, choiceOf(event.answers));
2906
+ if (result.kind === "stale" && result.checkpoint) {
2907
+ const desk = await deskFor(ctx);
2908
+ const current = desk.checkpoints.find((entry) => entry.id === result.checkpoint);
2909
+ if (current && askable(desk, []).includes(current)) return { step: await ask(ctx, desk, current), total: 1 };
2910
+ }
2911
+ if (result.kind === "recorded") return { done: true, text: `Recorded the author's answer: ${result.text}.`, ...(await picture(ctx)) };
2912
+ if (result.kind === "kept") return { done: true, text: `The author kept ${result.checkpoint} pending.`, ...(await picture(ctx)) };
2913
+ return { done: true, text: result.text };
2914
+ } catch (error) {
2915
+ return { done: true, text: failure("Nothing was recorded", error) };
2916
+ }
1243
2917
  });
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)) };
2918
+ api.interview("gate", async (event, ctx): Promise<InterviewNext> => {
2919
+ if (event.nav === "cancel")
2920
+ return {
2921
+ done: true,
2922
+ text: event.reason === "headless" ? "No author could be asked in this headless session; gates left as they were." : "Gates left as they were.",
2923
+ toast: { text: "WTF-P gates unchanged" },
2924
+ ...(await picture(ctx)),
2925
+ };
1247
2926
  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));
2927
+ const recorded = (await ctx.state.get<string[]>("gate-recorded")).value ?? [];
2928
+ let note = "";
2929
+ try {
2930
+ const result = await answer(ctx, event.step, choiceOf(event.answers));
2931
+ if (result.kind === "recorded") recorded.push(result.text);
2932
+ else if (result.kind === "kept" && result.checkpoint) kept.push(result.checkpoint);
2933
+ else if (result.kind === "refused") {
2934
+ note = result.text;
2935
+ if (result.checkpoint) kept.push(result.checkpoint);
2936
+ }
2937
+ } catch (error) {
2938
+ note = failure("Nothing was recorded", error);
1256
2939
  }
1257
2940
  await ctx.state.set("gate-kept", kept);
1258
2941
  await ctx.state.set("gate-recorded", recorded);
1259
- const remaining = pendingGates(loadDesk(ctx.snapshot.workspace), kept);
2942
+ const desk = await deskFor(ctx);
2943
+ const remaining = askable(desk, kept);
1260
2944
  const next = remaining[0];
1261
- if (next) return { step: gateStep(next), total: remaining.length + recorded.length + kept.length };
2945
+ if (next && !note.startsWith("Nothing was recorded")) return { step: await ask(ctx, desk, next), total: remaining.length + recorded.length + kept.length };
1262
2946
  await ctx.state.set("gate-recorded", []);
1263
- const summary = recorded.length > 0 ? `Recorded: ${recorded.join("; ")}.` : "Nothing recorded.";
2947
+ const summary = [recorded.length > 0 ? `Recorded: ${recorded.join("; ")}.` : "Nothing recorded.", note].filter(Boolean).join(" ");
1264
2948
  return {
1265
2949
  done: true,
1266
2950
  text: summary,
1267
- card: { t: "text", text: `✓ ${summary}`, tone: recorded.length > 0 ? "positive" : "muted", wrap: "wrap" },
1268
- ...(await picture(ctx)),
2951
+ card: { t: "text", text: `${recorded.length > 0 ? "✓" : "·"} ${summary}`, tone: recorded.length > 0 ? "positive" : "muted", wrap: "wrap" },
2952
+ ...(await picture(ctx, desk)),
1269
2953
  };
1270
2954
  });
2955
+ api.interview("confirm-write", async (event, ctx): Promise<InterviewNext> => {
2956
+ const nonce = /^confirm\.([a-f0-9]{12})$/u.exec(event.step)?.[1];
2957
+ const pending = nonce ? (await ctx.state.get<PendingConfirm>(`confirm:${nonce}`)).value : undefined;
2958
+ if (nonce) await ctx.state.delete(`confirm:${nonce}`);
2959
+ if (!pending) return { done: true, text: "That answer matches no open question; nothing was written." };
2960
+ if (event.nav === "cancel")
2961
+ 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." };
2962
+ const workspace = ctx.snapshot.workspace;
2963
+ const picked = choiceOf(event.answers);
2964
+ if (pending.workspace !== workspace) return { done: true, text: "That answer was given for another project; nothing was written." };
2965
+ if (picked !== "approve" && picked !== "decline") return { done: true, text: "That answer is not one of the options offered; nothing was written." };
2966
+ const key = await storedKey(ctx, true);
2967
+ if (key === null) return { done: true, text: "The desk could not establish its seal key; nothing was written." };
2968
+ try {
2969
+ const outcome = withLock(workspace, () => {
2970
+ recover(workspace);
2971
+ const file = artifactFile(workspace, pending.write.uri);
2972
+ const current = file === null ? null : readBytes(workspace, file);
2973
+ const stale = (current === null ? null : sha256(current)) !== pending.base_sha256 || sha256(canonical(pending.write.record)) !== pending.content_sha256;
2974
+ const prepared = stale || picked === "decline" ? null : prepare(workspace, pending.write, "desk", null);
2975
+ const interaction = sealed(
2976
+ {
2977
+ schema: "wtfp.project.interaction/v1",
2978
+ id: interactionId(),
2979
+ project_id: pending.project ?? readRecord(workspace, ".planning/project.json")?.id,
2980
+ kind: "record-change",
2981
+ subject_uri: pending.write.uri,
2982
+ channel: "attested-interview",
2983
+ outcome: stale ? "discarded-stale" : picked === "approve" ? "approved" : "declined",
2984
+ presented: { content_sha256: pending.content_sha256, options: ["approve", "decline"], ...(pending.base_sha256 ? { base_sha256: pending.base_sha256 } : {}) },
2985
+ asked_at: pending.asked_at,
2986
+ answered_at: timestamp(),
2987
+ },
2988
+ key,
2989
+ );
2990
+ const writes = [prepare(workspace, { uri: `project://interactions/${String(interaction.id)}`, record: interaction }, "desk", null).write];
2991
+ if (prepared) writes.push(prepared.write);
2992
+ commit(workspace, writes);
2993
+ return stale ? "stale" : picked;
2994
+ });
2995
+ return {
2996
+ done: true,
2997
+ text:
2998
+ outcome === "stale"
2999
+ ? `${pending.write.uri} changed while the author was asked; nothing was written. Read it again and propose the change anew.`
3000
+ : outcome === "approve"
3001
+ ? `The author approved the change; ${pending.write.uri} was written: ${pending.changes.join("; ")}.`
3002
+ : `The author kept the current settings; ${pending.write.uri} was not changed.`,
3003
+ ...(await picture(ctx)),
3004
+ };
3005
+ } catch (error) {
3006
+ return { done: true, text: failure("Nothing was written", error) };
3007
+ }
3008
+ });
1271
3009
 
1272
3010
  api.hook("prompt_submit", async (event, ctx) => {
1273
3011
  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) {
3012
+ const desk = loadDesk(ctx.snapshot.workspace);
3013
+ const armed = arm(typed, desk, ctx.snapshot.workspace);
3014
+ if (!armed) {
1277
3015
  await ctx.state.delete("armed");
1278
3016
  return {};
1279
3017
  }
1280
- await ctx.state.set("armed", { action: match[1], roots } satisfies Armed);
3018
+ await ctx.state.set("armed", armed);
3019
+ const roots = writeRoots(desk, armed);
1281
3020
  return {
1282
3021
  effects: [
1283
3022
  {
1284
3023
  kind: "notify_operator",
1285
3024
  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(", ")}.`,
3025
+ 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
3026
  },
1288
3027
  ],
1289
3028
  };
1290
3029
  });
1291
- api.hook("before_tool", async (event, ctx) =>
1292
- event.point === "before_tool" ? guard(ctx, event.args) : {},
1293
- );
3030
+ api.hook("before_tool", async (event, ctx) => (event.point === "before_tool" ? guard(ctx, event.tool, event.args, event) : {}));
1294
3031
 
1295
- api.on("session_open", async (_event, ctx) => ({ text: "", ...(await picture(ctx)) }));
3032
+ api.on("session_open", async (_event, ctx) => {
3033
+ const workspace = ctx.snapshot.workspace;
3034
+ let recovered: string | null = null;
3035
+ try {
3036
+ if (contained(workspace, JOURNAL) !== null && existsSync(path.join(workspace, JOURNAL))) recovered = withLock(workspace, () => recover(workspace));
3037
+ } catch (error) {
3038
+ recovered = `An interrupted write could not be completed: ${error instanceof Error ? error.message : String(error)}`;
3039
+ }
3040
+ return { text: recovered ?? "", ...(recovered ? { toast: { text: recovered, tone: "warning" as const } } : {}), ...(await picture(ctx)) };
3041
+ });
3042
+ api.on("turn_end", async (_event, ctx) => {
3043
+ // An action arms for the turn its command starts; nothing it allowed outlives that turn.
3044
+ await ctx.state.delete("armed");
3045
+ return undefined;
3046
+ });
1296
3047
  api.on("workspace_enter", async (_event, ctx) => ({ text: "", ...(await picture(ctx)) }));
1297
3048
  // Leaving means the desk no longer holds the screen, whatever the snapshot says yet.
1298
3049
  api.on("workspace_leave", async (_event, ctx) => ({ text: "", ...(await picture(ctx, undefined, null)) }));
1299
3050
  api.on("fs_changed", async (event, ctx) => {
1300
3051
  if (event.event !== "fs_changed") return undefined;
1301
- const records = event.paths.filter((file) => file.startsWith(".planning/") && file.endsWith(".json") && !file.includes("/archives/"));
3052
+ const records = event.paths.filter(
3053
+ (file) => file.startsWith(".planning/") && file.endsWith(".json") && !file.includes("/archives/") && !/(^|\/)\./u.test(file.slice(".planning/".length)),
3054
+ );
1302
3055
  const card = records.length > 0 ? await revalidate(ctx, records) : undefined;
1303
3056
  return { text: "", ...(card ? { card } : {}), ...(await picture(ctx)) };
1304
3057
  });