wtf-p 0.7.4 → 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 (516) hide show
  1. package/README.md +10 -10
  2. package/bin/commands/install-logic.js +1 -1
  3. package/bin/lib/adapter-compiler.js +305 -78
  4. package/bin/lib/clio-registration.js +159 -41
  5. package/bin/lib/manifest.js +11 -3
  6. package/bin/uninstall.js +22 -6
  7. package/package.json +3 -3
  8. package/protocol/actions/checkpoint.json +10 -1
  9. package/protocol/actions/execute-outline.json +10 -2
  10. package/protocol/actions/export-latex.json +15 -2
  11. package/protocol/actions/plan-revision.json +17 -4
  12. package/protocol/actions/polish-prose.json +13 -3
  13. package/protocol/actions/research-gap.json +16 -3
  14. package/protocol/actions/verify-work.json +7 -2
  15. package/protocol/project/README.md +37 -0
  16. package/protocol/project/schemas/interaction.schema.json +100 -0
  17. package/protocol/project/templates/interaction.json +16 -0
  18. package/protocol/skills/wtfp-deliver-research/SKILL.md +1 -1
  19. package/protocol/skills/wtfp-deliver-research/references/actions.md +2 -2
  20. package/protocol/skills/wtfp-plan-section/SKILL.md +1 -1
  21. package/protocol/skills/wtfp-plan-section/references/actions.md +4 -3
  22. package/protocol/skills/wtfp-research-literature/SKILL.md +1 -1
  23. package/protocol/skills/wtfp-review-manuscript/SKILL.md +1 -1
  24. package/protocol/skills/wtfp-write-section/SKILL.md +1 -1
  25. package/protocol/skills/wtfp-write-section/references/actions.md +1 -1
  26. package/protocol/workflows/checkpoint.md +2 -2
  27. package/protocol/workflows/execute-outline.md +2 -2
  28. package/protocol/workflows/export-latex.md +4 -4
  29. package/protocol/workflows/plan-revision.md +4 -3
  30. package/protocol/workflows/plan-section.md +2 -2
  31. package/protocol/workflows/polish-prose.md +3 -3
  32. package/protocol/workflows/research-gap.md +2 -2
  33. package/protocol/workflows/verify-work.md +3 -3
  34. package/protocol/workflows/write-section.md +2 -2
  35. package/vendors/antigravity/.wtfp-generated.json +172 -172
  36. package/vendors/antigravity/actions/checkpoint.json +10 -1
  37. package/vendors/antigravity/actions/execute-outline.json +10 -2
  38. package/vendors/antigravity/actions/export-latex.json +15 -2
  39. package/vendors/antigravity/actions/plan-revision.json +17 -4
  40. package/vendors/antigravity/actions/polish-prose.json +13 -3
  41. package/vendors/antigravity/actions/research-gap.json +16 -3
  42. package/vendors/antigravity/actions/verify-work.json +7 -2
  43. package/vendors/antigravity/plugin.json +2 -1
  44. package/vendors/antigravity/project/README.md +37 -0
  45. package/vendors/antigravity/project/schemas/interaction.schema.json +100 -0
  46. package/vendors/antigravity/project/templates/interaction.json +16 -0
  47. package/vendors/antigravity/rules/wtfp-project-state.md +41 -1
  48. package/vendors/antigravity/{commands/wtfp-add-todo.md → skills/wtfp-add-todo/SKILL.md} +2 -1
  49. package/vendors/antigravity/{commands/wtfp-analyze-bib.md → skills/wtfp-analyze-bib/SKILL.md} +2 -1
  50. package/vendors/antigravity/{commands/wtfp-audit-milestone.md → skills/wtfp-audit-milestone/SKILL.md} +2 -1
  51. package/vendors/antigravity/{commands/wtfp-check-refs.md → skills/wtfp-check-refs/SKILL.md} +2 -1
  52. package/vendors/antigravity/{commands/wtfp-check-todos.md → skills/wtfp-check-todos/SKILL.md} +2 -1
  53. package/vendors/antigravity/{commands/wtfp-checkpoint.md → skills/wtfp-checkpoint/SKILL.md} +4 -3
  54. package/vendors/antigravity/{commands/wtfp-contribute.md → skills/wtfp-contribute/SKILL.md} +2 -1
  55. package/vendors/antigravity/{commands/wtfp-create-outline.md → skills/wtfp-create-outline/SKILL.md} +2 -1
  56. package/vendors/antigravity/{commands/wtfp-create-poster.md → skills/wtfp-create-poster/SKILL.md} +2 -1
  57. package/vendors/antigravity/{commands/wtfp-create-slides.md → skills/wtfp-create-slides/SKILL.md} +2 -1
  58. package/vendors/antigravity/skills/wtfp-deliver-research/SKILL.md +1 -1
  59. package/vendors/antigravity/skills/wtfp-deliver-research/references/actions.md +2 -2
  60. package/vendors/antigravity/{commands/wtfp-discuss-section.md → skills/wtfp-discuss-section/SKILL.md} +2 -1
  61. package/vendors/antigravity/{commands/wtfp-execute-outline.md → skills/wtfp-execute-outline/SKILL.md} +4 -3
  62. package/vendors/antigravity/{commands/wtfp-export-latex.md → skills/wtfp-export-latex/SKILL.md} +2 -1
  63. package/vendors/antigravity/{commands/wtfp-help.md → skills/wtfp-help/SKILL.md} +3 -2
  64. package/vendors/antigravity/{commands/wtfp-insert-section.md → skills/wtfp-insert-section/SKILL.md} +2 -1
  65. package/vendors/antigravity/{commands/wtfp-list-assumptions.md → skills/wtfp-list-assumptions/SKILL.md} +2 -1
  66. package/vendors/antigravity/{commands/wtfp-map-project.md → skills/wtfp-map-project/SKILL.md} +2 -1
  67. package/vendors/antigravity/{commands/wtfp-new-paper.md → skills/wtfp-new-paper/SKILL.md} +2 -1
  68. package/vendors/antigravity/{commands/wtfp-pause-writing.md → skills/wtfp-pause-writing/SKILL.md} +2 -1
  69. package/vendors/antigravity/{commands/wtfp-plan-milestone-gaps.md → skills/wtfp-plan-milestone-gaps/SKILL.md} +2 -1
  70. package/vendors/antigravity/{commands/wtfp-plan-revision.md → skills/wtfp-plan-revision/SKILL.md} +10 -4
  71. package/vendors/antigravity/skills/wtfp-plan-section/SKILL.md +1 -1
  72. package/vendors/antigravity/skills/wtfp-plan-section/references/actions.md +4 -3
  73. package/vendors/antigravity/{commands/wtfp-polish-prose.md → skills/wtfp-polish-prose/SKILL.md} +9 -4
  74. package/vendors/antigravity/{commands/wtfp-progress.md → skills/wtfp-progress/SKILL.md} +2 -1
  75. package/vendors/antigravity/{commands/wtfp-quick.md → skills/wtfp-quick/SKILL.md} +2 -1
  76. package/vendors/antigravity/{commands/wtfp-remove-section.md → skills/wtfp-remove-section/SKILL.md} +2 -1
  77. package/vendors/antigravity/{commands/wtfp-report-bug.md → skills/wtfp-report-bug/SKILL.md} +2 -1
  78. package/vendors/antigravity/{commands/wtfp-request-feature.md → skills/wtfp-request-feature/SKILL.md} +2 -1
  79. package/vendors/antigravity/{commands/wtfp-research-gap.md → skills/wtfp-research-gap/SKILL.md} +2 -1
  80. package/vendors/antigravity/skills/wtfp-research-literature/SKILL.md +1 -1
  81. package/vendors/antigravity/{commands/wtfp-resume-writing.md → skills/wtfp-resume-writing/SKILL.md} +2 -1
  82. package/vendors/antigravity/skills/wtfp-review-manuscript/SKILL.md +1 -1
  83. package/vendors/antigravity/{commands/wtfp-review-section.md → skills/wtfp-review-section/SKILL.md} +2 -1
  84. package/vendors/antigravity/{commands/wtfp-settings.md → skills/wtfp-settings/SKILL.md} +2 -1
  85. package/vendors/antigravity/{commands/wtfp-submit-milestone.md → skills/wtfp-submit-milestone/SKILL.md} +2 -1
  86. package/vendors/antigravity/{commands/wtfp-update.md → skills/wtfp-update/SKILL.md} +2 -1
  87. package/vendors/antigravity/{commands/wtfp-verify-work.md → skills/wtfp-verify-work/SKILL.md} +5 -4
  88. package/vendors/antigravity/skills/wtfp-write-section/SKILL.md +1 -1
  89. package/vendors/antigravity/skills/wtfp-write-section/references/actions.md +1 -1
  90. package/vendors/antigravity/workflows/checkpoint.md +2 -2
  91. package/vendors/antigravity/workflows/execute-outline.md +2 -2
  92. package/vendors/antigravity/workflows/export-latex.md +4 -4
  93. package/vendors/antigravity/workflows/plan-revision.md +4 -3
  94. package/vendors/antigravity/workflows/plan-section.md +2 -2
  95. package/vendors/antigravity/workflows/polish-prose.md +3 -3
  96. package/vendors/antigravity/workflows/research-gap.md +2 -2
  97. package/vendors/antigravity/workflows/verify-work.md +3 -3
  98. package/vendors/antigravity/workflows/write-section.md +2 -2
  99. package/vendors/claude/.claude-plugin/marketplace.json +2 -2
  100. package/vendors/claude/.claude-plugin/plugin.json +1 -1
  101. package/vendors/claude/.wtfp-generated.json +84 -76
  102. package/vendors/claude/actions/checkpoint.json +10 -1
  103. package/vendors/claude/actions/execute-outline.json +10 -2
  104. package/vendors/claude/actions/export-latex.json +15 -2
  105. package/vendors/claude/actions/plan-revision.json +17 -4
  106. package/vendors/claude/actions/polish-prose.json +13 -3
  107. package/vendors/claude/actions/research-gap.json +16 -3
  108. package/vendors/claude/actions/verify-work.json +7 -2
  109. package/vendors/claude/ai.iowarp.clio/agents/wtfp-argument-verifier.md +3 -3
  110. package/vendors/claude/ai.iowarp.clio/agents/wtfp-coherence-checker.md +3 -3
  111. package/vendors/claude/ai.iowarp.clio/agents/wtfp-plan-checker.md +3 -3
  112. package/vendors/claude/ai.iowarp.clio/agents/wtfp-section-reviewer.md +3 -3
  113. package/vendors/claude/ai.iowarp.clio/fleets/wtfp-draft-review.md +1 -1
  114. package/vendors/claude/ai.iowarp.clio/fleets/wtfp-plan-section.md +1 -1
  115. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/add-todo.md +8 -0
  116. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/analyze-bib.md +22 -0
  117. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/audit-milestone.md +10 -0
  118. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/check-refs.md +22 -0
  119. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/check-todos.md +9 -0
  120. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/checkpoint.md +11 -2
  121. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/create-outline.md +21 -0
  122. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/create-poster.md +9 -0
  123. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/create-slides.md +9 -0
  124. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/discuss-section.md +9 -0
  125. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/execute-outline.md +24 -3
  126. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/export-latex.md +14 -4
  127. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/help.md +1 -1
  128. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/insert-section.md +9 -0
  129. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/list-assumptions.md +6 -0
  130. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/map-project.md +8 -0
  131. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/new-paper.md +9 -0
  132. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/pause-writing.md +8 -0
  133. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/plan-milestone-gaps.md +9 -0
  134. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/plan-revision.md +17 -3
  135. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/plan-section.md +24 -3
  136. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/polish-prose.md +28 -3
  137. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/progress.md +7 -0
  138. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/quick.md +21 -0
  139. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/research-gap.md +25 -2
  140. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/resume-writing.md +9 -0
  141. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/review-section.md +19 -1
  142. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/settings.md +9 -0
  143. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/submit-milestone.md +9 -0
  144. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/verify-work.md +12 -3
  145. package/vendors/claude/ai.iowarp.clio/prompts/wtfp/write-section.md +24 -3
  146. package/vendors/claude/commands/checkpoint.md +2 -2
  147. package/vendors/claude/commands/execute-outline.md +2 -2
  148. package/vendors/claude/commands/export-latex.md +4 -4
  149. package/vendors/claude/commands/plan-revision.md +8 -3
  150. package/vendors/claude/commands/plan-section.md +2 -2
  151. package/vendors/claude/commands/polish-prose.md +7 -3
  152. package/vendors/claude/commands/research-gap.md +2 -2
  153. package/vendors/claude/commands/verify-work.md +3 -3
  154. package/vendors/claude/commands/write-section.md +2 -2
  155. package/vendors/claude/output-styles/wtfp-academic-writing.md +5 -5
  156. package/vendors/claude/plugin.json +1 -1
  157. package/vendors/claude/project/README.md +37 -0
  158. package/vendors/claude/project/schemas/interaction.schema.json +100 -0
  159. package/vendors/claude/project/templates/interaction.json +16 -0
  160. package/vendors/claude/skills/wtfp-deliver-research/SKILL.md +1 -1
  161. package/vendors/claude/skills/wtfp-deliver-research/references/actions.md +2 -2
  162. package/vendors/claude/skills/wtfp-plan-section/SKILL.md +1 -1
  163. package/vendors/claude/skills/wtfp-plan-section/references/actions.md +4 -3
  164. package/vendors/claude/skills/wtfp-research-literature/SKILL.md +1 -1
  165. package/vendors/claude/skills/wtfp-review-manuscript/SKILL.md +1 -1
  166. package/vendors/claude/skills/wtfp-write-section/SKILL.md +1 -1
  167. package/vendors/claude/skills/wtfp-write-section/references/actions.md +1 -1
  168. package/vendors/claude/workflows/checkpoint.md +2 -2
  169. package/vendors/claude/workflows/execute-outline.md +2 -2
  170. package/vendors/claude/workflows/export-latex.md +4 -4
  171. package/vendors/claude/workflows/plan-revision.md +4 -3
  172. package/vendors/claude/workflows/plan-section.md +2 -2
  173. package/vendors/claude/workflows/polish-prose.md +3 -3
  174. package/vendors/claude/workflows/research-gap.md +2 -2
  175. package/vendors/claude/workflows/verify-work.md +3 -3
  176. package/vendors/claude/workflows/write-section.md +2 -2
  177. package/vendors/clio-extension/.wtfp-generated.json +240 -0
  178. package/vendors/clio-extension/actions/add-todo.json +52 -0
  179. package/vendors/clio-extension/actions/analyze-bib.json +97 -0
  180. package/vendors/clio-extension/actions/audit-milestone.json +63 -0
  181. package/vendors/clio-extension/actions/check-refs.json +80 -0
  182. package/vendors/clio-extension/actions/check-todos.json +52 -0
  183. package/vendors/clio-extension/actions/checkpoint.json +85 -0
  184. package/vendors/clio-extension/actions/contribute.json +57 -0
  185. package/vendors/clio-extension/actions/create-outline.json +84 -0
  186. package/vendors/clio-extension/actions/create-poster.json +54 -0
  187. package/vendors/clio-extension/actions/create-slides.json +54 -0
  188. package/vendors/clio-extension/actions/discuss-section.json +76 -0
  189. package/vendors/clio-extension/actions/execute-outline.json +124 -0
  190. package/vendors/clio-extension/actions/export-latex.json +78 -0
  191. package/vendors/clio-extension/actions/help.json +30 -0
  192. package/vendors/clio-extension/actions/insert-section.json +61 -0
  193. package/vendors/clio-extension/actions/list-assumptions.json +35 -0
  194. package/vendors/clio-extension/actions/map-project.json +71 -0
  195. package/vendors/clio-extension/actions/new-paper.json +70 -0
  196. package/vendors/clio-extension/actions/pause-writing.json +71 -0
  197. package/vendors/clio-extension/actions/plan-milestone-gaps.json +57 -0
  198. package/vendors/clio-extension/actions/plan-revision.json +71 -0
  199. package/vendors/clio-extension/actions/plan-section.json +100 -0
  200. package/vendors/clio-extension/actions/polish-prose.json +79 -0
  201. package/vendors/clio-extension/actions/progress.json +51 -0
  202. package/vendors/clio-extension/actions/quick.json +70 -0
  203. package/vendors/clio-extension/actions/remove-section.json +63 -0
  204. package/vendors/clio-extension/actions/report-bug.json +47 -0
  205. package/vendors/clio-extension/actions/request-feature.json +47 -0
  206. package/vendors/clio-extension/actions/research-gap.json +115 -0
  207. package/vendors/clio-extension/actions/resume-writing.json +65 -0
  208. package/vendors/clio-extension/actions/review-section.json +83 -0
  209. package/vendors/clio-extension/actions/settings.json +47 -0
  210. package/vendors/clio-extension/actions/submit-milestone.json +77 -0
  211. package/vendors/clio-extension/actions/update.json +42 -0
  212. package/vendors/clio-extension/actions/verify-work.json +68 -0
  213. package/vendors/clio-extension/actions/write-section.json +115 -0
  214. package/vendors/clio-extension/clio-coder-extension.yaml +76 -0
  215. package/vendors/clio-extension/compatibility/action-availability.json +295 -0
  216. package/vendors/clio-extension/project/schemas/checkpoint.schema.json +102 -0
  217. package/vendors/clio-extension/project/schemas/common.schema.json +33 -0
  218. package/vendors/clio-extension/project/schemas/config.schema.json +69 -0
  219. package/vendors/clio-extension/project/schemas/decisions.schema.json +31 -0
  220. package/vendors/clio-extension/project/schemas/evidence.schema.json +48 -0
  221. package/vendors/clio-extension/project/schemas/interaction.schema.json +100 -0
  222. package/vendors/clio-extension/project/schemas/manifest.schema.json +102 -0
  223. package/vendors/clio-extension/project/schemas/outline.schema.json +67 -0
  224. package/vendors/clio-extension/project/schemas/section.schema.json +95 -0
  225. package/vendors/clio-extension/project/schemas/source.schema.json +73 -0
  226. package/vendors/clio-extension/project/schemas/state.schema.json +58 -0
  227. package/vendors/clio-extension/project/schemas/validation.schema.json +74 -0
  228. package/vendors/clio-extension/runtime/claim-coverage.cjs +332 -0
  229. package/vendors/clio-extension/runtime/desk-trust.cjs +112 -0
  230. package/vendors/clio-extension/runtime/extension.test.ts +1567 -0
  231. package/vendors/clio-extension/runtime/extension.ts +3074 -0
  232. package/vendors/clio-extension/runtime/json-schema.cjs +304 -0
  233. package/vendors/clio-extension/runtime/package.json +3 -0
  234. package/vendors/clio-extension/runtime/write-guard.json +566 -0
  235. package/vendors/clio-extension/skins/wtfp.json +20 -0
  236. package/vendors/codex/plugins/wtfp/.codex-plugin/plugin.json +1 -1
  237. package/vendors/codex/plugins/wtfp/.wtfp-generated.json +36 -28
  238. package/vendors/codex/plugins/wtfp/actions/checkpoint.json +10 -1
  239. package/vendors/codex/plugins/wtfp/actions/execute-outline.json +10 -2
  240. package/vendors/codex/plugins/wtfp/actions/export-latex.json +15 -2
  241. package/vendors/codex/plugins/wtfp/actions/plan-revision.json +17 -4
  242. package/vendors/codex/plugins/wtfp/actions/polish-prose.json +13 -3
  243. package/vendors/codex/plugins/wtfp/actions/research-gap.json +16 -3
  244. package/vendors/codex/plugins/wtfp/actions/verify-work.json +7 -2
  245. package/vendors/codex/plugins/wtfp/plugin.json +1 -1
  246. package/vendors/codex/plugins/wtfp/project/README.md +37 -0
  247. package/vendors/codex/plugins/wtfp/project/schemas/interaction.schema.json +100 -0
  248. package/vendors/codex/plugins/wtfp/project/templates/interaction.json +16 -0
  249. package/vendors/codex/plugins/wtfp/skills/wtfp-deliver-research/SKILL.md +1 -1
  250. package/vendors/codex/plugins/wtfp/skills/wtfp-deliver-research/references/actions.md +2 -2
  251. package/vendors/codex/plugins/wtfp/skills/wtfp-plan-section/SKILL.md +1 -1
  252. package/vendors/codex/plugins/wtfp/skills/wtfp-plan-section/references/actions.md +4 -3
  253. package/vendors/codex/plugins/wtfp/skills/wtfp-research-literature/SKILL.md +1 -1
  254. package/vendors/codex/plugins/wtfp/skills/wtfp-review-manuscript/SKILL.md +1 -1
  255. package/vendors/codex/plugins/wtfp/skills/wtfp-write-section/SKILL.md +1 -1
  256. package/vendors/codex/plugins/wtfp/skills/wtfp-write-section/references/actions.md +1 -1
  257. package/vendors/codex/plugins/wtfp/workflows/checkpoint.md +2 -2
  258. package/vendors/codex/plugins/wtfp/workflows/execute-outline.md +2 -2
  259. package/vendors/codex/plugins/wtfp/workflows/export-latex.md +4 -4
  260. package/vendors/codex/plugins/wtfp/workflows/plan-revision.md +4 -3
  261. package/vendors/codex/plugins/wtfp/workflows/plan-section.md +2 -2
  262. package/vendors/codex/plugins/wtfp/workflows/polish-prose.md +3 -3
  263. package/vendors/codex/plugins/wtfp/workflows/research-gap.md +2 -2
  264. package/vendors/codex/plugins/wtfp/workflows/verify-work.md +3 -3
  265. package/vendors/codex/plugins/wtfp/workflows/write-section.md +2 -2
  266. package/vendors/copilot/.wtfp-generated.json +43 -35
  267. package/vendors/copilot/marketplace.json +2 -2
  268. package/vendors/copilot/plugins/wtfp/.claude-plugin/plugin.json +1 -1
  269. package/vendors/copilot/plugins/wtfp/.wtfp-generated.json +42 -34
  270. package/vendors/copilot/plugins/wtfp/actions/checkpoint.json +10 -1
  271. package/vendors/copilot/plugins/wtfp/actions/execute-outline.json +10 -2
  272. package/vendors/copilot/plugins/wtfp/actions/export-latex.json +15 -2
  273. package/vendors/copilot/plugins/wtfp/actions/plan-revision.json +17 -4
  274. package/vendors/copilot/plugins/wtfp/actions/polish-prose.json +13 -3
  275. package/vendors/copilot/plugins/wtfp/actions/research-gap.json +16 -3
  276. package/vendors/copilot/plugins/wtfp/actions/verify-work.json +7 -2
  277. package/vendors/copilot/plugins/wtfp/commands/wtfp-checkpoint.md +2 -2
  278. package/vendors/copilot/plugins/wtfp/commands/wtfp-execute-outline.md +2 -2
  279. package/vendors/copilot/plugins/wtfp/commands/wtfp-plan-revision.md +8 -3
  280. package/vendors/copilot/plugins/wtfp/commands/wtfp-plan-section.md +2 -2
  281. package/vendors/copilot/plugins/wtfp/commands/wtfp-polish-prose.md +7 -3
  282. package/vendors/copilot/plugins/wtfp/commands/wtfp-verify-work.md +3 -3
  283. package/vendors/copilot/plugins/wtfp/commands/wtfp-write-section.md +2 -2
  284. package/vendors/copilot/plugins/wtfp/project/README.md +37 -0
  285. package/vendors/copilot/plugins/wtfp/project/schemas/interaction.schema.json +100 -0
  286. package/vendors/copilot/plugins/wtfp/project/templates/interaction.json +16 -0
  287. package/vendors/copilot/plugins/wtfp/skills/wtfp-deliver-research/SKILL.md +1 -1
  288. package/vendors/copilot/plugins/wtfp/skills/wtfp-deliver-research/references/actions.md +2 -2
  289. package/vendors/copilot/plugins/wtfp/skills/wtfp-plan-section/SKILL.md +1 -1
  290. package/vendors/copilot/plugins/wtfp/skills/wtfp-plan-section/references/actions.md +4 -3
  291. package/vendors/copilot/plugins/wtfp/skills/wtfp-research-literature/SKILL.md +1 -1
  292. package/vendors/copilot/plugins/wtfp/skills/wtfp-review-manuscript/SKILL.md +1 -1
  293. package/vendors/copilot/plugins/wtfp/skills/wtfp-write-section/SKILL.md +1 -1
  294. package/vendors/copilot/plugins/wtfp/skills/wtfp-write-section/references/actions.md +1 -1
  295. package/vendors/copilot/plugins/wtfp/workflows/checkpoint.md +2 -2
  296. package/vendors/copilot/plugins/wtfp/workflows/execute-outline.md +2 -2
  297. package/vendors/copilot/plugins/wtfp/workflows/export-latex.md +4 -4
  298. package/vendors/copilot/plugins/wtfp/workflows/plan-revision.md +4 -3
  299. package/vendors/copilot/plugins/wtfp/workflows/plan-section.md +2 -2
  300. package/vendors/copilot/plugins/wtfp/workflows/polish-prose.md +3 -3
  301. package/vendors/copilot/plugins/wtfp/workflows/research-gap.md +2 -2
  302. package/vendors/copilot/plugins/wtfp/workflows/verify-work.md +3 -3
  303. package/vendors/copilot/plugins/wtfp/workflows/write-section.md +2 -2
  304. package/vendors/copilot/project/.github/skills/wtfp-deliver-research/SKILL.md +1 -1
  305. package/vendors/copilot/project/.github/skills/wtfp-deliver-research/references/actions.md +2 -2
  306. package/vendors/copilot/project/.github/skills/wtfp-plan-section/SKILL.md +1 -1
  307. package/vendors/copilot/project/.github/skills/wtfp-plan-section/references/actions.md +4 -3
  308. package/vendors/copilot/project/.github/skills/wtfp-research-literature/SKILL.md +1 -1
  309. package/vendors/copilot/project/.github/skills/wtfp-review-manuscript/SKILL.md +1 -1
  310. package/vendors/copilot/project/.github/skills/wtfp-write-section/SKILL.md +1 -1
  311. package/vendors/copilot/project/.github/skills/wtfp-write-section/references/actions.md +1 -1
  312. package/vendors/copilot/project/.github/wtfp/actions/checkpoint.json +10 -1
  313. package/vendors/copilot/project/.github/wtfp/actions/execute-outline.json +10 -2
  314. package/vendors/copilot/project/.github/wtfp/actions/export-latex.json +15 -2
  315. package/vendors/copilot/project/.github/wtfp/actions/plan-revision.json +17 -4
  316. package/vendors/copilot/project/.github/wtfp/actions/polish-prose.json +13 -3
  317. package/vendors/copilot/project/.github/wtfp/actions/research-gap.json +16 -3
  318. package/vendors/copilot/project/.github/wtfp/actions/verify-work.json +7 -2
  319. package/vendors/copilot/project/.github/wtfp/project/README.md +37 -0
  320. package/vendors/copilot/project/.github/wtfp/project/schemas/interaction.schema.json +100 -0
  321. package/vendors/copilot/project/.github/wtfp/project/templates/interaction.json +16 -0
  322. package/vendors/copilot/project/.github/wtfp/skills/wtfp-deliver-research/SKILL.md +1 -1
  323. package/vendors/copilot/project/.github/wtfp/skills/wtfp-deliver-research/references/actions.md +2 -2
  324. package/vendors/copilot/project/.github/wtfp/skills/wtfp-plan-section/SKILL.md +1 -1
  325. package/vendors/copilot/project/.github/wtfp/skills/wtfp-plan-section/references/actions.md +4 -3
  326. package/vendors/copilot/project/.github/wtfp/skills/wtfp-research-literature/SKILL.md +1 -1
  327. package/vendors/copilot/project/.github/wtfp/skills/wtfp-review-manuscript/SKILL.md +1 -1
  328. package/vendors/copilot/project/.github/wtfp/skills/wtfp-write-section/SKILL.md +1 -1
  329. package/vendors/copilot/project/.github/wtfp/skills/wtfp-write-section/references/actions.md +1 -1
  330. package/vendors/copilot/project/.github/wtfp/workflows/checkpoint.md +2 -2
  331. package/vendors/copilot/project/.github/wtfp/workflows/execute-outline.md +2 -2
  332. package/vendors/copilot/project/.github/wtfp/workflows/export-latex.md +4 -4
  333. package/vendors/copilot/project/.github/wtfp/workflows/plan-revision.md +4 -3
  334. package/vendors/copilot/project/.github/wtfp/workflows/plan-section.md +2 -2
  335. package/vendors/copilot/project/.github/wtfp/workflows/polish-prose.md +3 -3
  336. package/vendors/copilot/project/.github/wtfp/workflows/research-gap.md +2 -2
  337. package/vendors/copilot/project/.github/wtfp/workflows/verify-work.md +3 -3
  338. package/vendors/copilot/project/.github/wtfp/workflows/write-section.md +2 -2
  339. package/vendors/gemini/.wtfp-generated.json +61 -53
  340. package/vendors/gemini/actions/checkpoint.json +10 -1
  341. package/vendors/gemini/actions/execute-outline.json +10 -2
  342. package/vendors/gemini/actions/export-latex.json +15 -2
  343. package/vendors/gemini/actions/plan-revision.json +17 -4
  344. package/vendors/gemini/actions/polish-prose.json +13 -3
  345. package/vendors/gemini/actions/research-gap.json +16 -3
  346. package/vendors/gemini/actions/verify-work.json +7 -2
  347. package/vendors/gemini/commands/wtfp/add-todo.toml +37 -0
  348. package/vendors/gemini/commands/wtfp/check-todos.toml +37 -0
  349. package/vendors/gemini/commands/wtfp/checkpoint.toml +49 -3
  350. package/vendors/gemini/commands/wtfp/create-outline.toml +37 -0
  351. package/vendors/gemini/commands/wtfp/create-poster.toml +40 -3
  352. package/vendors/gemini/commands/wtfp/create-slides.toml +40 -3
  353. package/vendors/gemini/commands/wtfp/discuss-section.toml +42 -4
  354. package/vendors/gemini/commands/wtfp/execute-outline.toml +51 -6
  355. package/vendors/gemini/commands/wtfp/help.toml +37 -0
  356. package/vendors/gemini/commands/wtfp/insert-section.toml +42 -4
  357. package/vendors/gemini/commands/wtfp/list-assumptions.toml +42 -4
  358. package/vendors/gemini/commands/wtfp/map-project.toml +37 -0
  359. package/vendors/gemini/commands/wtfp/new-paper.toml +37 -0
  360. package/vendors/gemini/commands/wtfp/pause-writing.toml +37 -0
  361. package/vendors/gemini/commands/wtfp/plan-milestone-gaps.toml +38 -1
  362. package/vendors/gemini/commands/wtfp/plan-revision.toml +310 -11
  363. package/vendors/gemini/commands/wtfp/plan-section.toml +44 -6
  364. package/vendors/gemini/commands/wtfp/polish-prose.toml +281 -7
  365. package/vendors/gemini/commands/wtfp/progress.toml +37 -0
  366. package/vendors/gemini/commands/wtfp/quick.toml +39 -2
  367. package/vendors/gemini/commands/wtfp/resume-writing.toml +37 -0
  368. package/vendors/gemini/commands/wtfp/review-section.toml +38 -1
  369. package/vendors/gemini/commands/wtfp/settings.toml +37 -0
  370. package/vendors/gemini/commands/wtfp/submit-milestone.toml +40 -3
  371. package/vendors/gemini/commands/wtfp/verify-work.toml +48 -6
  372. package/vendors/gemini/commands/wtfp/write-section.toml +41 -4
  373. package/vendors/gemini/gemini-extension.json +1 -1
  374. package/vendors/gemini/project/README.md +37 -0
  375. package/vendors/gemini/project/schemas/interaction.schema.json +100 -0
  376. package/vendors/gemini/project/templates/interaction.json +16 -0
  377. package/vendors/gemini/skills/wtfp-deliver-research/SKILL.md +1 -1
  378. package/vendors/gemini/skills/wtfp-deliver-research/references/actions.md +2 -2
  379. package/vendors/gemini/skills/wtfp-plan-section/SKILL.md +1 -1
  380. package/vendors/gemini/skills/wtfp-plan-section/references/actions.md +4 -3
  381. package/vendors/gemini/skills/wtfp-research-literature/SKILL.md +1 -1
  382. package/vendors/gemini/skills/wtfp-review-manuscript/SKILL.md +1 -1
  383. package/vendors/gemini/skills/wtfp-write-section/SKILL.md +1 -1
  384. package/vendors/gemini/skills/wtfp-write-section/references/actions.md +1 -1
  385. package/vendors/gemini/workflows/checkpoint.md +2 -2
  386. package/vendors/gemini/workflows/execute-outline.md +2 -2
  387. package/vendors/gemini/workflows/export-latex.md +4 -4
  388. package/vendors/gemini/workflows/plan-revision.md +4 -3
  389. package/vendors/gemini/workflows/plan-section.md +2 -2
  390. package/vendors/gemini/workflows/polish-prose.md +3 -3
  391. package/vendors/gemini/workflows/research-gap.md +2 -2
  392. package/vendors/gemini/workflows/verify-work.md +3 -3
  393. package/vendors/gemini/workflows/write-section.md +2 -2
  394. package/vendors/opencode/.wtfp-generated.json +60 -52
  395. package/vendors/opencode/actions/checkpoint.json +10 -1
  396. package/vendors/opencode/actions/execute-outline.json +10 -2
  397. package/vendors/opencode/actions/export-latex.json +15 -2
  398. package/vendors/opencode/actions/plan-revision.json +17 -4
  399. package/vendors/opencode/actions/polish-prose.json +13 -3
  400. package/vendors/opencode/actions/research-gap.json +16 -3
  401. package/vendors/opencode/actions/verify-work.json +7 -2
  402. package/vendors/opencode/commands/wtfp/add-todo.md +37 -0
  403. package/vendors/opencode/commands/wtfp/check-todos.md +37 -0
  404. package/vendors/opencode/commands/wtfp/checkpoint.md +49 -3
  405. package/vendors/opencode/commands/wtfp/create-outline.md +37 -0
  406. package/vendors/opencode/commands/wtfp/create-poster.md +40 -3
  407. package/vendors/opencode/commands/wtfp/create-slides.md +40 -3
  408. package/vendors/opencode/commands/wtfp/discuss-section.md +42 -4
  409. package/vendors/opencode/commands/wtfp/execute-outline.md +51 -6
  410. package/vendors/opencode/commands/wtfp/help.md +37 -0
  411. package/vendors/opencode/commands/wtfp/insert-section.md +42 -4
  412. package/vendors/opencode/commands/wtfp/list-assumptions.md +42 -4
  413. package/vendors/opencode/commands/wtfp/map-project.md +37 -0
  414. package/vendors/opencode/commands/wtfp/new-paper.md +37 -0
  415. package/vendors/opencode/commands/wtfp/pause-writing.md +37 -0
  416. package/vendors/opencode/commands/wtfp/plan-milestone-gaps.md +38 -1
  417. package/vendors/opencode/commands/wtfp/plan-revision.md +310 -11
  418. package/vendors/opencode/commands/wtfp/plan-section.md +44 -6
  419. package/vendors/opencode/commands/wtfp/polish-prose.md +281 -7
  420. package/vendors/opencode/commands/wtfp/progress.md +37 -0
  421. package/vendors/opencode/commands/wtfp/quick.md +39 -2
  422. package/vendors/opencode/commands/wtfp/resume-writing.md +37 -0
  423. package/vendors/opencode/commands/wtfp/review-section.md +38 -1
  424. package/vendors/opencode/commands/wtfp/settings.md +37 -0
  425. package/vendors/opencode/commands/wtfp/submit-milestone.md +40 -3
  426. package/vendors/opencode/commands/wtfp/verify-work.md +48 -6
  427. package/vendors/opencode/commands/wtfp/write-section.md +41 -4
  428. package/vendors/opencode/project/README.md +37 -0
  429. package/vendors/opencode/project/schemas/interaction.schema.json +100 -0
  430. package/vendors/opencode/project/templates/interaction.json +16 -0
  431. package/vendors/opencode/skills/wtfp-deliver-research/SKILL.md +1 -1
  432. package/vendors/opencode/skills/wtfp-deliver-research/references/actions.md +2 -2
  433. package/vendors/opencode/skills/wtfp-plan-section/SKILL.md +1 -1
  434. package/vendors/opencode/skills/wtfp-plan-section/references/actions.md +4 -3
  435. package/vendors/opencode/skills/wtfp-research-literature/SKILL.md +1 -1
  436. package/vendors/opencode/skills/wtfp-review-manuscript/SKILL.md +1 -1
  437. package/vendors/opencode/skills/wtfp-write-section/SKILL.md +1 -1
  438. package/vendors/opencode/skills/wtfp-write-section/references/actions.md +1 -1
  439. package/vendors/opencode/workflows/checkpoint.md +2 -2
  440. package/vendors/opencode/workflows/execute-outline.md +2 -2
  441. package/vendors/opencode/workflows/export-latex.md +4 -4
  442. package/vendors/opencode/workflows/plan-revision.md +4 -3
  443. package/vendors/opencode/workflows/plan-section.md +2 -2
  444. package/vendors/opencode/workflows/polish-prose.md +3 -3
  445. package/vendors/opencode/workflows/research-gap.md +2 -2
  446. package/vendors/opencode/workflows/verify-work.md +3 -3
  447. package/vendors/opencode/workflows/write-section.md +2 -2
  448. package/vendors/plugin/.wtfp-generated.json +75 -67
  449. package/vendors/plugin/actions/checkpoint.json +10 -1
  450. package/vendors/plugin/actions/execute-outline.json +10 -2
  451. package/vendors/plugin/actions/export-latex.json +15 -2
  452. package/vendors/plugin/actions/plan-revision.json +17 -4
  453. package/vendors/plugin/actions/polish-prose.json +13 -3
  454. package/vendors/plugin/actions/research-gap.json +16 -3
  455. package/vendors/plugin/actions/verify-work.json +7 -2
  456. package/vendors/plugin/ai.iowarp.clio/agents/wtfp-argument-verifier.md +3 -3
  457. package/vendors/plugin/ai.iowarp.clio/agents/wtfp-coherence-checker.md +3 -3
  458. package/vendors/plugin/ai.iowarp.clio/agents/wtfp-plan-checker.md +3 -3
  459. package/vendors/plugin/ai.iowarp.clio/agents/wtfp-section-reviewer.md +3 -3
  460. package/vendors/plugin/ai.iowarp.clio/{fleets → playbooks}/wtfp-draft-review.md +1 -1
  461. package/vendors/plugin/ai.iowarp.clio/{fleets → playbooks}/wtfp-plan-section.md +1 -1
  462. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/add-todo.md +19 -12
  463. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/analyze-bib.md +34 -19
  464. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/audit-milestone.md +22 -25
  465. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/check-refs.md +34 -15
  466. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/check-todos.md +23 -13
  467. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/checkpoint.md +23 -29
  468. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/create-outline.md +33 -25
  469. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/create-poster.md +9 -0
  470. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/create-slides.md +9 -0
  471. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/discuss-section.md +21 -17
  472. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/execute-outline.md +38 -30
  473. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/export-latex.md +26 -21
  474. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/help.md +2 -2
  475. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/insert-section.md +21 -13
  476. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/list-assumptions.md +6 -0
  477. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/map-project.md +19 -14
  478. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/new-paper.md +21 -17
  479. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/pause-writing.md +19 -18
  480. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/plan-milestone-gaps.md +21 -15
  481. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/plan-revision.md +25 -18
  482. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/plan-section.md +36 -30
  483. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/polish-prose.md +38 -18
  484. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/progress.md +7 -0
  485. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/quick.md +35 -15
  486. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/research-gap.md +37 -23
  487. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/resume-writing.md +21 -23
  488. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/review-section.md +31 -20
  489. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/settings.md +21 -9
  490. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/submit-milestone.md +21 -25
  491. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/verify-work.md +24 -18
  492. package/vendors/plugin/ai.iowarp.clio/prompts/wtfp/write-section.md +38 -31
  493. package/vendors/plugin/compatibility/action-availability.json +18 -3
  494. package/vendors/plugin/plugin.json +7 -7
  495. package/vendors/plugin/project/README.md +37 -0
  496. package/vendors/plugin/project/schemas/interaction.schema.json +100 -0
  497. package/vendors/plugin/project/templates/interaction.json +16 -0
  498. package/vendors/plugin/skills/wtfp-deliver-research/SKILL.md +1 -1
  499. package/vendors/plugin/skills/wtfp-deliver-research/references/actions.md +2 -2
  500. package/vendors/plugin/skills/wtfp-plan-section/SKILL.md +1 -1
  501. package/vendors/plugin/skills/wtfp-plan-section/references/actions.md +4 -3
  502. package/vendors/plugin/skills/wtfp-research-literature/SKILL.md +1 -1
  503. package/vendors/plugin/skills/wtfp-review-manuscript/SKILL.md +1 -1
  504. package/vendors/plugin/skills/wtfp-write-section/SKILL.md +1 -1
  505. package/vendors/plugin/skills/wtfp-write-section/references/actions.md +1 -1
  506. package/vendors/plugin/workflows/checkpoint.md +2 -2
  507. package/vendors/plugin/workflows/execute-outline.md +2 -2
  508. package/vendors/plugin/workflows/export-latex.md +4 -4
  509. package/vendors/plugin/workflows/plan-revision.md +4 -3
  510. package/vendors/plugin/workflows/plan-section.md +2 -2
  511. package/vendors/plugin/workflows/polish-prose.md +3 -3
  512. package/vendors/plugin/workflows/research-gap.md +2 -2
  513. package/vendors/plugin/workflows/verify-work.md +3 -3
  514. package/vendors/plugin/workflows/write-section.md +2 -2
  515. package/vendors/antigravity/commands/wtfp-plan-section.md +0 -78
  516. package/vendors/antigravity/commands/wtfp-write-section.md +0 -77
@@ -0,0 +1,3074 @@
1
+ // Generated by WTF-P adapter compiler v5 from clio/runtime/extension.ts; do not edit.
2
+ /**
3
+ * WTF-P writing desk for Clio Coder. Human-edited source; the adapter
4
+ * compiler copies it to vendors/clio-extension/runtime/ beside the
5
+ * generated write-guard.json, json-schema.cjs and claim-coverage.cjs.
6
+ *
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.
14
+ */
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";
32
+ import { createRequire } from "node:module";
33
+ import path from "node:path";
34
+ import { performance } from "node:perf_hooks";
35
+ import { fileURLToPath } from "node:url";
36
+ import type {
37
+ ExtensionApiV2,
38
+ ExtensionContextV2,
39
+ ExtensionEffect,
40
+ ExtensionHookResult,
41
+ ExtensionIsland,
42
+ ExtensionOutputV2,
43
+ ExtensionSkin,
44
+ InterviewNext,
45
+ InterviewStep,
46
+ View,
47
+ ViewTone,
48
+ } from "@iowarp/clio-coder/extensions";
49
+
50
+ const require = createRequire(import.meta.url);
51
+ const { SchemaRegistry, validateInstance } = require("./json-schema.cjs") as {
52
+ SchemaRegistry: new (files: string[]) => { get(file: string): unknown };
53
+ validateInstance: (value: unknown, schema: unknown, file: string, registry: unknown) => string[];
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
+ }
84
+
85
+ const PACKAGE_ROOT = fileURLToPath(new URL("../", import.meta.url));
86
+ const SCHEMAS = path.join(PACKAGE_ROOT, "project", "schemas");
87
+ interface GuardAction {
88
+ produces: Array<{ uri: string; mode: string }>;
89
+ }
90
+ const GUARD = JSON.parse(readFileSync(new URL("./write-guard.json", import.meta.url), "utf8")) as {
91
+ schema: string;
92
+ actions: Record<string, GuardAction>;
93
+ paperWriters: string[];
94
+ };
95
+ const SKIN = JSON.parse(readFileSync(new URL("../skins/wtfp.json", import.meta.url), "utf8")) as ExtensionSkin;
96
+ const RECORD_LIMIT = 1024 * 1024;
97
+ const PHASES = ["initialized", "mapped", "outlining", "planning", "writing", "reviewing", "ready", "delivered"] as const;
98
+ const WORDMARK = [
99
+ "██╗ ██╗████████╗███████╗ ██████╗ ",
100
+ "██║ ██║╚══██╔══╝██╔════╝ ██╔══██╗",
101
+ "██║ █╗ ██║ ██║ █████╗ █████╗██████╔╝",
102
+ "██║███╗██║ ██║ ██╔══╝ ╚════╝██╔═══╝ ",
103
+ "╚███╔███╔╝ ██║ ██║ ██║ ",
104
+ " ╚══╝╚══╝ ╚═╝ ╚═╝ ╚═╝ ",
105
+ ];
106
+ const WORD_METHOD =
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";
117
+
118
+ // --- records -----------------------------------------------------------------
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
+
131
+ interface Checkpoint {
132
+ file: string;
133
+ id: string;
134
+ kind: string;
135
+ status: string;
136
+ blocking: boolean;
137
+ scope_uri: string;
138
+ request: string;
139
+ context?: string;
140
+ options?: Array<{ id: string; label: string; implication?: string }>;
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;
146
+ [key: string]: unknown;
147
+ }
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
+
157
+ interface SectionRow {
158
+ id: string;
159
+ title: string;
160
+ wave: number;
161
+ status: string;
162
+ target: number;
163
+ words: number;
164
+ recorded: number | null;
165
+ manuscript: string | null;
166
+ claims: { total: number; verified: number; unsupported: number };
167
+ stages: { discuss: boolean; plan: boolean; write: boolean; review: boolean };
168
+ gates: Checkpoint[];
169
+ research: { required: boolean; present: boolean };
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;
181
+ }
182
+
183
+ interface Desk {
184
+ workspace: string;
185
+ present: boolean;
186
+ projectId: string | null;
187
+ title: string;
188
+ documentType: string;
189
+ venue: string | null;
190
+ deadline: string | null;
191
+ argument: string;
192
+ phase: string;
193
+ status: string;
194
+ confirmPlan: boolean;
195
+ outputFormat: string;
196
+ sections: SectionRow[];
197
+ checkpoints: Checkpoint[];
198
+ interactions: Json[];
199
+ sources: Record<string, number>;
200
+ evidence: number;
201
+ issues: Record<"blocker" | "error" | "warning" | "info", number>;
202
+ invalid: Array<{ file: string; errors: string[] }>;
203
+ targetWords: number;
204
+ paperExists: boolean;
205
+ journal: boolean;
206
+ coverage: CoverageReport;
207
+ /** The WTF-P plugin while Clio serves it; null when it is not installed and enabled. */
208
+ served: ServedPlugin;
209
+ }
210
+
211
+ /** Actions the desk answers itself; they stay reachable as `/ext:wtfp:<name>` without the plugin. */
212
+ const DESK_COMMANDS = new Set(["progress", "help", "check-todos"]);
213
+
214
+ /**
215
+ * How the desk names an action: the plugin's `/wtfp:` prompt while the plugin
216
+ * serves it, else the desk's own `/ext:wtfp:` command, else null because only
217
+ * the plugin can run it.
218
+ */
219
+ function commandFor(served: ServedPlugin, action: string, args = ""): string | null {
220
+ const tail = args ? ` ${args}` : "";
221
+ if (served?.prompts.includes(`wtfp:${action}`)) return `/wtfp:${action}${tail}`;
222
+ if (DESK_COMMANDS.has(action)) return `/ext:wtfp:${action}${tail}`;
223
+ return null;
224
+ }
225
+
226
+ /** An action's command, or its bare name where no command runs it here. */
227
+ function actionName(served: ServedPlugin, action: string): string {
228
+ return commandFor(served, action) ?? action;
229
+ }
230
+
231
+ function inside(root: string, candidate: string): boolean {
232
+ const relative = path.relative(root, candidate);
233
+ return relative === "" || (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
234
+ }
235
+
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 {
246
+ const file = path.resolve(workspace, relative);
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;
274
+ const stat = lstatSync(file);
275
+ if (!stat.isFile() || stat.size > RECORD_LIMIT) return null;
276
+ return readFileSync(file);
277
+ }
278
+
279
+ function readText(workspace: string, relative: string): string | null {
280
+ return readBytes(workspace, relative)?.toString("utf8") ?? null;
281
+ }
282
+
283
+ function readRecord(workspace: string, relative: string): Json | null {
284
+ const source = readText(workspace, relative);
285
+ if (source === null) return null;
286
+ try {
287
+ const value = JSON.parse(source) as unknown;
288
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Json) : null;
289
+ } catch {
290
+ // An unreadable record shows up as a schema problem from validation, not here.
291
+ return null;
292
+ }
293
+ }
294
+
295
+ function listJson(workspace: string, relative: string): string[] {
296
+ const directory = contained(workspace, relative);
297
+ if (directory === null || !existsSync(directory) || !lstatSync(directory).isDirectory()) return [];
298
+ return readdirSync(directory, { withFileTypes: true })
299
+ .filter((entry) => entry.isFile() && entry.name.endsWith(".json") && !entry.name.startsWith("."))
300
+ .map((entry) => path.posix.join(relative, entry.name))
301
+ .sort();
302
+ }
303
+
304
+ function text(value: unknown, fallback = ""): string {
305
+ return typeof value === "string" && value.length > 0 ? value : fallback;
306
+ }
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
+
328
+ /** `project://paper/{artifact}` to a manuscript file, trying the authored formats in order. */
329
+ function manuscriptFile(workspace: string, uri: unknown, format = "markdown"): string | null {
330
+ if (typeof uri !== "string" || !uri.startsWith("project://paper/")) return null;
331
+ const artifact = uri.slice("project://paper/".length);
332
+ if (artifact.length === 0 || artifact.split("/").some((part) => part === ".." || part === "." || part === "")) return null;
333
+ for (const candidate of [artifact, `${artifact}.md`, `${artifact}.tex`, `${artifact}.typ`]) {
334
+ const relative = path.posix.join("paper", candidate);
335
+ const file = contained(workspace, relative);
336
+ if (file !== null && existsSync(file) && lstatSync(file).isFile()) return relative;
337
+ }
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;
350
+ }
351
+
352
+ /** The one counting method every meter and tolerance uses (see WORD_METHOD). */
353
+ export function bodyWords(source: string, file: string): number {
354
+ let body = source.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/u, "");
355
+ body = body.replace(/```[\s\S]*?```/gu, " ").replace(/`[^`\n]*`/gu, " ");
356
+ body = body.replace(/<!--[\s\S]*?-->/gu, " ");
357
+ body = body.replace(/\$\$[\s\S]*?\$\$/gu, " ").replace(/\$[^$\n]*\$/gu, " ");
358
+ if (file.endsWith(".tex")) {
359
+ body = body.replace(/(^|[^\\])%.*$/gmu, "$1");
360
+ body = body.replace(/\\(?:begin|end)\{[^}]*\}/gu, " ");
361
+ body = body.replace(/\\(?:cite[a-z]*|ref|eqref|autoref|label|input|include|bibliography\w*)\*?(?:\[[^\]]*\])*\{[^}]*\}/gu, " ");
362
+ body = body.replace(/\\(?:section|subsection|subsubsection|chapter|paragraph)\*?\{[^}]*\}/gu, " ");
363
+ body = body.replace(/\\[a-zA-Z@]+\*?/gu, " ");
364
+ }
365
+ if (file.endsWith(".typ")) body = body.replace(/^\s*=+\s.*$/gmu, " ").replace(/\/\/.*$/gmu, " ").replace(/#[a-z-]+(?:\([^)]*\))?/gu, " ");
366
+ body = body.replace(/^\s{0,3}#{1,6}\s.*$/gmu, " ");
367
+ body = body.replace(/\[@[^\]]+\]|@[A-Za-z][\w:-]+/gu, " ");
368
+ body = body.replace(/!\[[^\]]*\]\([^)]*\)/gu, " ").replace(/\[([^\]]*)\]\([^)]*\)/gu, "$1");
369
+ return (body.match(/[\p{L}\p{N}]+(?:['’-][\p{L}\p{N}]+)*/gu) ?? []).length;
370
+ }
371
+
372
+ let registry: InstanceType<typeof SchemaRegistry> | undefined;
373
+ function schemaRegistry(): InstanceType<typeof SchemaRegistry> {
374
+ registry ??= new SchemaRegistry(
375
+ readdirSync(SCHEMAS)
376
+ .filter((name) => name.endsWith(".schema.json"))
377
+ .map((name) => path.join(SCHEMAS, name)),
378
+ );
379
+ return registry;
380
+ }
381
+
382
+ /** Schema errors for one record, as the canonical validator reports them. */
383
+ function validateRecord(value: unknown): string[] {
384
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return ["$: planning record must be a JSON object"];
385
+ const match = /^wtfp\.project\.([a-z][a-z0-9-]*)\/v1$/u.exec(text((value as Json).schema));
386
+ if (!match) return ["$: missing or unsupported wtfp.project.<record>/v1 schema discriminator"];
387
+ const schemaFile = path.join(SCHEMAS, `${match[1]}.schema.json`);
388
+ if (!existsSync(schemaFile)) return [`$: no canonical schema for record type ${match[1]}`];
389
+ const schemas = schemaRegistry();
390
+ return validateInstance(value, schemas.get(schemaFile), schemaFile, schemas);
391
+ }
392
+
393
+ function validateFile(workspace: string, relative: string): string[] {
394
+ const source = readText(workspace, relative);
395
+ if (source === null) return contained(workspace, relative) === null ? ["$: reached through a symbolic link; the desk does not follow links"] : [];
396
+ try {
397
+ return validateRecord(JSON.parse(source));
398
+ } catch (error) {
399
+ return [`$: invalid JSON (${error instanceof Error ? error.message : String(error)})`];
400
+ }
401
+ }
402
+
403
+ function planningRecords(workspace: string, relative = ".planning"): string[] {
404
+ const directory = contained(workspace, relative);
405
+ if (directory === null || !existsSync(directory) || !lstatSync(directory).isDirectory()) return [];
406
+ const out: string[] = [];
407
+ for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
408
+ if (entry.name.startsWith(".")) continue;
409
+ const child = path.posix.join(relative, entry.name);
410
+ if (entry.isDirectory() && entry.name !== "archives") out.push(...planningRecords(workspace, child));
411
+ else if (entry.isFile() && entry.name.endsWith(".json")) out.push(child);
412
+ }
413
+ return out;
414
+ }
415
+
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 {
523
+ const manifest = readRecord(workspace, ".planning/project.json");
524
+ const config = readRecord(workspace, ".planning/config.json");
525
+ const state = readRecord(workspace, ".planning/state.json");
526
+ const outline = readRecord(workspace, ".planning/structure/outline.json");
527
+ const target = (manifest?.target ?? {}) as Json;
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
+ });
534
+ const checkpoints: Checkpoint[] = listJson(workspace, ".planning/checkpoints").flatMap((file) => {
535
+ const record = readRecord(workspace, file);
536
+ if (!record || typeof record.id !== "string") return [];
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];
549
+ });
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
+
574
+ const outlined = Array.isArray(outline?.sections) ? (outline.sections as Json[]) : [];
575
+ const loaded = outlined.map((entry) => {
576
+ const id = text(entry.id, "section");
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;
582
+ const artifacts = (record?.artifacts ?? {}) as Json;
583
+ const manuscript = manuscriptFile(workspace, artifacts.manuscript ?? `project://paper/${id}`, outputFormat);
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}`;
619
+ const words = source === null || manuscript === null ? 0 : bodyWords(source, manuscript);
620
+ const status = text(record?.status, "not-started");
621
+ const claims = Array.isArray(record?.claims) ? (record.claims as Json[]) : [];
622
+ const plans = Array.isArray(artifacts.plans) ? artifacts.plans : [];
623
+ const reviews = Array.isArray(artifacts.reviews) ? artifacts.reviews : [];
624
+ const research = (entry.research ?? {}) as Json;
625
+ const unsupported = coverage.unsupportedRequired(report, id);
626
+ return {
627
+ id,
628
+ title: text(entry.title, id),
629
+ wave: typeof entry.wave === "number" ? entry.wave : 1,
630
+ status,
631
+ target: typeof entry.word_target === "number" ? entry.word_target : Number(record?.word_target ?? 0),
632
+ words,
633
+ recorded: typeof record?.word_count === "number" ? record.word_count : null,
634
+ manuscript,
635
+ claims: {
636
+ total: claims.length,
637
+ verified: claims.filter((claim) => claim.status === "verified").length,
638
+ unsupported: unsupported.length,
639
+ },
640
+ stages: {
641
+ discuss: readBytes(workspace, `${base}/context.md`) !== null,
642
+ plan: plans.length > 0 || ["planned", "writing", "reviewing", "complete"].includes(status),
643
+ write: words > 0 || ["reviewing", "complete"].includes(status),
644
+ review: reviews.length > 0 || status === "complete",
645
+ },
646
+ gates: sectionGates(checkpoints, id, manuscript),
647
+ research: { required: research.required === true, present: readBytes(workspace, `${base}/research.md`) !== null },
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,
652
+ };
653
+ });
654
+ const issues = { blocker: 0, error: 0, warning: 0, info: 0 };
655
+ for (const file of listJson(workspace, ".planning/validations")) {
656
+ const record = readRecord(workspace, file);
657
+ for (const issue of Array.isArray(record?.issues) ? (record.issues as Json[]) : []) {
658
+ const severity = text(issue.severity) as keyof typeof issues;
659
+ if (severity in issues) issues[severity] += 1;
660
+ }
661
+ }
662
+ const journal = contained(workspace, JOURNAL);
663
+ return {
664
+ workspace,
665
+ present: manifest !== null,
666
+ projectId,
667
+ title: text(manifest?.title, "Untitled paper"),
668
+ documentType: text(manifest?.document_type, "paper"),
669
+ venue: typeof target.venue === "string" ? target.venue : null,
670
+ deadline: typeof target.deadline === "string" ? target.deadline : null,
671
+ argument: text(manifest?.core_argument),
672
+ phase: text(state?.phase, manifest ? "initialized" : "none"),
673
+ status: text(state?.status, "active"),
674
+ confirmPlan,
675
+ outputFormat,
676
+ sections,
677
+ checkpoints,
678
+ interactions,
679
+ sources,
680
+ evidence: Object.keys(evidenceRecords).length,
681
+ issues,
682
+ invalid: [],
683
+ targetWords:
684
+ typeof outline?.target_words === "number"
685
+ ? outline.target_words
686
+ : typeof progress.word_target === "number"
687
+ ? progress.word_target
688
+ : typeof target.word_limit === "number"
689
+ ? target.word_limit
690
+ : sections.reduce((sum, section) => sum + section.target, 0),
691
+ paperExists: contained(workspace, "paper") !== null && existsSync(path.join(workspace, "paper")),
692
+ journal: journal !== null && existsSync(journal),
693
+ coverage: report,
694
+ served: null,
695
+ };
696
+ }
697
+
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;
761
+ }
762
+
763
+ // --- the lock and the journal ------------------------------------------------
764
+
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
+ }
802
+ }
803
+ }
804
+
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;
829
+ }
830
+ closeSync(handle);
831
+ }
832
+
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
+ }
837
+
838
+ interface PendingWrite {
839
+ uri: string;
840
+ file: string;
841
+ text: string;
842
+ sha256: string;
843
+ revision: number | null;
844
+ }
845
+
846
+ interface JournalEntry {
847
+ file: string;
848
+ staging: string;
849
+ sha256: string;
850
+ }
851
+
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
+ );
867
+ }
868
+
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
+ }
880
+ }
881
+
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}`;
890
+ }
891
+
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
+ {
1416
+ t: "steps",
1417
+ items: PHASES.map((phase, index) => ({
1418
+ label: phase,
1419
+ state:
1420
+ desk.status === "blocked" && index === phaseIndex
1421
+ ? "blocked"
1422
+ : index < phaseIndex || desk.phase === "delivered"
1423
+ ? "done"
1424
+ : index === phaseIndex
1425
+ ? "active"
1426
+ : "todo",
1427
+ })),
1428
+ },
1429
+ ],
1430
+ };
1431
+ }
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
+
1454
+ function board(desk: Desk): View {
1455
+ if (desk.sections.length === 0)
1456
+ return { t: "text", text: `No outline yet. ${nextAction(desk).command ?? ""}`.trim(), tone: "muted" };
1457
+ const waves = [...new Set(desk.sections.map((section) => section.wave))].sort((a, b) => a - b).slice(0, 8);
1458
+ return {
1459
+ t: "board",
1460
+ action: "section",
1461
+ columns: waves.map((wave) => {
1462
+ const cards = desk.sections.filter((section) => section.wave === wave);
1463
+ const done = cards.filter((section) => section.status === "complete").length;
1464
+ return {
1465
+ title: `Wave ${wave} · ${done}/${cards.length}`,
1466
+ tone: done === cards.length ? "positive" : "info",
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
+ }),
1500
+ };
1501
+ }),
1502
+ };
1503
+ }
1504
+
1505
+ function agentLabel(agentId: string): string {
1506
+ const agent = SKIN.agents?.[agentId];
1507
+ return agent ? `${agent.glyph ?? ""} ${agent.label ?? agentId}`.trim() : agentId;
1508
+ }
1509
+
1510
+ function islands(desk: Desk, running: Record<string, { agentId: string; at: number }>): ExtensionIsland[] {
1511
+ const out: ExtensionIsland[] = [];
1512
+ const gate = openGates(desk)[0];
1513
+ if (gate)
1514
+ out.push({
1515
+ key: "gate",
1516
+ title: "⚑ Gate",
1517
+ meta: gate.trust === "pending" ? gate.kind : "unconfirmed",
1518
+ tone: "warning",
1519
+ view: {
1520
+ t: "box",
1521
+ dir: "col",
1522
+ children: [
1523
+ { t: "text", text: gate.request, wrap: "wrap", bold: true },
1524
+ ...(gate.options && gate.options.length > 0
1525
+ ? [
1526
+ {
1527
+ t: "list",
1528
+ items: gate.options.slice(0, 6).map((option) => ({
1529
+ key: option.id,
1530
+ label: option.label,
1531
+ ...(option.implication ? { detail: option.implication } : {}),
1532
+ mark: "◇",
1533
+ })),
1534
+ } as View,
1535
+ ]
1536
+ : []),
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
+ },
1545
+ ],
1546
+ },
1547
+ });
1548
+ const verified = desk.sources.verified ?? 0;
1549
+ const provisional = desk.sources.provisional ?? 0;
1550
+ const lost = (desk.sources.unavailable ?? 0) + (desk.sources.retracted ?? 0);
1551
+ const unsupported = desk.sections.reduce((sum, section) => sum + section.claims.unsupported, 0);
1552
+ if (desk.present)
1553
+ out.push({
1554
+ key: "evidence",
1555
+ title: "❝ Evidence ledger",
1556
+ tone: unsupported > 0 || lost > 0 ? "warning" : "info",
1557
+ view: {
1558
+ t: "kv",
1559
+ items: [
1560
+ { label: "sources verified", value: String(verified), tone: verified > 0 ? "positive" : "muted" },
1561
+ { label: "provisional", value: String(provisional), tone: provisional > 0 ? "warning" : "muted" },
1562
+ ...(lost > 0 ? [{ label: "unavailable or retracted", value: String(lost), tone: "error" as ViewTone }] : []),
1563
+ { label: "evidence items", value: String(desk.evidence) },
1564
+ { label: "required claims without support", value: String(unsupported), tone: unsupported > 0 ? "warning" : "positive" },
1565
+ ],
1566
+ },
1567
+ });
1568
+ for (const [runId, run] of Object.entries(running).slice(0, 2))
1569
+ out.push({
1570
+ key: `run-${runId}`,
1571
+ title: agentLabel(run.agentId),
1572
+ meta: `${Math.max(0, Math.round((Date.now() - run.at) / 1000))}s`,
1573
+ tone: "info",
1574
+ view: { t: "text", text: `working on ${desk.title}`, tone: "muted" },
1575
+ });
1576
+ if (desk.invalid.length > 0)
1577
+ out.push({
1578
+ key: "schema",
1579
+ title: "✗ Schema",
1580
+ meta: `${desk.invalid.length} record${desk.invalid.length === 1 ? "" : "s"}`,
1581
+ tone: "error",
1582
+ view: {
1583
+ t: "list",
1584
+ items: desk.invalid.slice(0, 4).map((record) => ({
1585
+ key: record.file,
1586
+ label: record.file.replace(/^\.planning\//u, ""),
1587
+ detail: record.errors[0] ?? "",
1588
+ tone: "error" as ViewTone,
1589
+ })),
1590
+ },
1591
+ });
1592
+ return out.slice(0, 4);
1593
+ }
1594
+
1595
+ function footer(desk: Desk): View {
1596
+ if (!desk.present) {
1597
+ const start = commandFor(desk.served, "new-paper");
1598
+ return {
1599
+ t: "text",
1600
+ text: `WTF-P · no .planning here · ${start ? `${start} starts one` : "the WTF-P plugin's new-paper starts one"}`,
1601
+ tone: "muted",
1602
+ };
1603
+ }
1604
+ const complete = desk.sections.filter((section) => section.status === "complete").length;
1605
+ const issues = (["blocker", "error", "warning"] as const)
1606
+ .filter((severity) => desk.issues[severity] > 0)
1607
+ .map((severity) => `${desk.issues[severity]} ${severity}${desk.issues[severity] === 1 ? "" : "s"}`);
1608
+ const next = nextAction(desk).command;
1609
+ return {
1610
+ t: "text",
1611
+ tone: "muted",
1612
+ text: [
1613
+ `${totalWords(desk).toLocaleString("en-US")}/${desk.targetWords.toLocaleString("en-US")} words`,
1614
+ `${complete}/${desk.sections.length} sections`,
1615
+ issues.length > 0 ? `issues ${issues.join(", ")}` : "no open issues",
1616
+ desk.invalid.length > 0 ? `schema ✗ ${desk.invalid.length}` : "schema ✓",
1617
+ next ? `next ${next}` : "",
1618
+ ]
1619
+ .filter(Boolean)
1620
+ .join(" · "),
1621
+ };
1622
+ }
1623
+
1624
+ function rail(desk: Desk): View {
1625
+ return {
1626
+ t: "text",
1627
+ text: desk.present
1628
+ ? `WTF-P ◆ ${desk.phase} ◆ ${totalWords(desk).toLocaleString("en-US")}/${desk.targetWords.toLocaleString("en-US")}`
1629
+ : "WTF-P ◆ no project",
1630
+ tone: "brand",
1631
+ bold: true,
1632
+ };
1633
+ }
1634
+
1635
+ function band(desk: Desk): View {
1636
+ const next = nextAction(desk);
1637
+ return {
1638
+ t: "box",
1639
+ dir: "row",
1640
+ gap: 2,
1641
+ children: [
1642
+ { t: "box", dir: "col", grow: 1, children: [{ t: "text", text: `✎ ${next.reason}`, tone: "info" }] },
1643
+ ...(next.command
1644
+ ? [{ t: "actions", items: [{ id: "next", label: `Fill ${next.command}`, hotkey: "f", primary: true }] } as View]
1645
+ : []),
1646
+ ],
1647
+ };
1648
+ }
1649
+
1650
+ // --- session state -----------------------------------------------------------
1651
+
1652
+ type Running = Record<string, { agentId: string; at: number }>;
1653
+
1654
+ async function running(ctx: ExtensionContextV2): Promise<Running> {
1655
+ return (await ctx.state.get<Running>("running")).value ?? {};
1656
+ }
1657
+
1658
+ async function deskFor(ctx: ExtensionContextV2): Promise<Desk> {
1659
+ const desk = loadDesk(ctx.snapshot.workspace, await storedKey(ctx, false));
1660
+ desk.invalid = (await ctx.state.get<Desk["invalid"]>("invalid")).value ?? [];
1661
+ desk.served = ctx.snapshot.plugin ?? null;
1662
+ return desk;
1663
+ }
1664
+
1665
+ async function picture(
1666
+ ctx: ExtensionContextV2,
1667
+ desk?: Desk,
1668
+ active: string | null = ctx.snapshot.activeWorkspace,
1669
+ ): Promise<Omit<ExtensionOutputV2, "text">> {
1670
+ const current = desk ?? (await deskFor(ctx));
1671
+ if (!current.present && !current.paperExists && active === null) return { status: null, band: null, islands: null };
1672
+ return {
1673
+ status: current.present
1674
+ ? {
1675
+ text: `WTF-P · ${current.phase} · ${totalWords(current).toLocaleString("en-US")}/${current.targetWords.toLocaleString("en-US")}w`,
1676
+ tone: openGates(current).length > 0 || current.journal ? "warning" : "neutral",
1677
+ }
1678
+ : null,
1679
+ band: band(current),
1680
+ regions: { header: header(current), board: board(current), rail: rail(current), footer: footer(current) },
1681
+ islands: islands(current, await running(ctx)),
1682
+ };
1683
+ }
1684
+
1685
+ /** Validate the named records; a newly invalid record gets one card naming it and the field. */
1686
+ async function revalidate(ctx: ExtensionContextV2, files: string[]): Promise<View | undefined> {
1687
+ const workspace = ctx.snapshot.workspace;
1688
+ const before = (await ctx.state.get<Desk["invalid"]>("invalid")).value ?? [];
1689
+ const current = new Map(before.map((record) => [record.file, record]));
1690
+ const fresh: Desk["invalid"] = [];
1691
+ for (const file of files) {
1692
+ const errors = existsSync(path.join(workspace, file)) ? validateFile(workspace, file) : [];
1693
+ const prior = current.get(file);
1694
+ if (errors.length === 0) current.delete(file);
1695
+ else {
1696
+ current.set(file, { file, errors: errors.slice(0, 5) });
1697
+ if (!prior || prior.errors[0] !== errors[0]) fresh.push({ file, errors });
1698
+ }
1699
+ }
1700
+ await ctx.state.set("invalid", [...current.values()]);
1701
+ if (fresh.length === 0) return undefined;
1702
+ return {
1703
+ t: "box",
1704
+ dir: "col",
1705
+ border: "round",
1706
+ title: "WTF-P · schema violation",
1707
+ children: fresh.slice(0, 4).flatMap((record) => [
1708
+ { t: "text", text: record.file, bold: true, tone: "error" } as View,
1709
+ ...record.errors.slice(0, 3).map((error) => ({ t: "text", text: ` ${error}`, tone: "muted", wrap: "wrap" }) as View),
1710
+ ]),
1711
+ };
1712
+ }
1713
+
1714
+ // --- gates -------------------------------------------------------------------
1715
+
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
+ }
1731
+
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[] {
1734
+ return desk.checkpoints.filter(
1735
+ (checkpoint) =>
1736
+ checkpoint.kind !== "state-snapshot" &&
1737
+ !skip.includes(checkpoint.id) &&
1738
+ (checkpoint.status === "pending" || (checkpoint.blocking && unconfirmed(checkpoint))),
1739
+ );
1740
+ }
1741
+
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");
1790
+ return {
1791
+ key: `gate.${nonce}`,
1792
+ title: confirming ? "Confirm a recorded answer" : checkpoint.blocking ? "Blocking gate" : "Pending task",
1793
+ // The question carries the request; the intro adds only what it cannot.
1794
+ intro: {
1795
+ t: "box",
1796
+ dir: "col",
1797
+ children: [
1798
+ ...(checkpoint.context ? [{ t: "text", text: checkpoint.context, wrap: "wrap" } as View] : []),
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] : []),
1804
+ ],
1805
+ },
1806
+ questions: [
1807
+ {
1808
+ id: "choice",
1809
+ label: checkpoint.request.length > 120 ? `${checkpoint.request.slice(0, 117)}...` : checkpoint.request,
1810
+ kind: "single",
1811
+ options: offered,
1812
+ },
1813
+ ],
1814
+ };
1815
+ }
1816
+
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,
1857
+ };
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
+ },
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
+ });
1901
+ }
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
+ };
1921
+ }
1922
+
1923
+ async function startGates(ctx: ExtensionContextV2): Promise<ExtensionOutputV2> {
1924
+ const desk = await deskFor(ctx);
1925
+ const pending = askable(desk, []);
1926
+ await ctx.state.set("gate-kept", []);
1927
+ await ctx.state.set("gate-recorded", []);
1928
+ if (pending.length === 0)
1929
+ return {
1930
+ text: "No pending gates or author tasks.",
1931
+ card: { t: "text", text: "✓ No pending gates or author tasks.", tone: "positive" },
1932
+ };
1933
+ return {
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) },
1936
+ };
1937
+ }
1938
+
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
+ }
1943
+
1944
+ // --- confirmations of weakening record writes --------------------------------
1945
+
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;
1954
+ }
1955
+
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;
2042
+ const route = RECORD_URIS.find((entry) => entry.pattern.test(uri));
2043
+ if (!route) throw new Error(`${uri} is not a logical record URI this adapter maps`);
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)})`);
2055
+ }
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
+ });
2088
+ }
2089
+
2090
+ function readiness(desk: Desk, sectionId: string): Json {
2091
+ const section = desk.sections.find((entry) => entry.id === sectionId);
2092
+ if (!section) throw new Error(`no section ${sectionId} in the outline`);
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
+ };
2105
+ }
2106
+
2107
+ // --- commands ----------------------------------------------------------------
2108
+
2109
+ function progressCard(desk: Desk): View {
2110
+ const next = nextAction(desk);
2111
+ const totals = totalWords(desk);
2112
+ return {
2113
+ t: "box",
2114
+ dir: "col",
2115
+ border: "round",
2116
+ title: `WTF-P · ${desk.title}`,
2117
+ meta: desk.phase,
2118
+ children: [
2119
+ {
2120
+ t: "kv",
2121
+ items: [
2122
+ { label: "words", value: `${totals.toLocaleString("en-US")} / ${desk.targetWords.toLocaleString("en-US")}`, tone: tolerance(totals, desk.targetWords) },
2123
+ { label: "sections", value: `${desk.sections.filter((section) => section.status === "complete").length} of ${desk.sections.length} complete` },
2124
+ {
2125
+ label: "gates waiting on you",
2126
+ value: String(askable(desk, []).length),
2127
+ tone: askable(desk, []).length > 0 ? "warning" : "positive",
2128
+ },
2129
+ ...(desk.journal ? [{ label: "interrupted write", value: "pending recovery", tone: "error" as ViewTone }] : []),
2130
+ ...(daysLeft(desk.deadline) ? [{ label: "deadline", value: daysLeft(desk.deadline) as string }] : []),
2131
+ { label: "next", value: next.command ? `${next.command} · ${next.reason}` : next.reason, tone: "info" },
2132
+ ],
2133
+ },
2134
+ ...(desk.sections.length > 0
2135
+ ? [
2136
+ {
2137
+ t: "table",
2138
+ columns: ["wave", "section", "status", "stages", "plan", "words", "claims", "gates"],
2139
+ rows: desk.sections.map((section) => [
2140
+ String(section.wave),
2141
+ section.title,
2142
+ section.status,
2143
+ stageStrip(section),
2144
+ section.plan.state,
2145
+ section.target > 0 ? `${section.words}/${section.target}` : String(section.words),
2146
+ `${section.claims.verified}/${section.claims.total}`,
2147
+ String(section.gates.length),
2148
+ ]),
2149
+ } as View,
2150
+ ]
2151
+ : []),
2152
+ { t: "text", text: WORD_METHOD, tone: "muted", wrap: "wrap" },
2153
+ ],
2154
+ };
2155
+ }
2156
+
2157
+ function progressText(desk: Desk): string {
2158
+ const next = nextAction(desk);
2159
+ if (!desk.present) return `No WTF-P project here. ${next.command ?? next.reason}`;
2160
+ return [
2161
+ `${desk.title} · ${desk.phase}`,
2162
+ `${totalWords(desk)}/${desk.targetWords} words; ${desk.sections.filter((section) => section.status === "complete").length}/${desk.sections.length} sections complete`,
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`),
2165
+ next.command ? `Next: ${next.command} (${next.reason})` : `Next: ${next.reason}`,
2166
+ ].join("\n");
2167
+ }
2168
+
2169
+ function helpCard(served: ServedPlugin): { text: string; card: View } {
2170
+ const availability = JSON.parse(
2171
+ readFileSync(path.join(PACKAGE_ROOT, "compatibility", "action-availability.json"), "utf8"),
2172
+ ) as { actions: Array<{ id: string; status: string; unavailableCapabilities: string[] }> };
2173
+ const rows = availability.actions.map((entry) => {
2174
+ const contract = JSON.parse(readFileSync(path.join(PACKAGE_ROOT, "actions", `${entry.id}.json`), "utf8")) as {
2175
+ description?: string;
2176
+ };
2177
+ return [
2178
+ actionName(served, entry.id),
2179
+ entry.status === "available" ? text(contract.description) : `unavailable: ${entry.unavailableCapabilities.join(", ")}`,
2180
+ ];
2181
+ });
2182
+ const local = [...DESK_COMMANDS].map((id) => actionName(served, id));
2183
+ return {
2184
+ text: rows.map((row) => `${row[0]} ${row[1]}`).join("\n"),
2185
+ card: {
2186
+ t: "box",
2187
+ dir: "col",
2188
+ border: "round",
2189
+ title: "WTF-P actions",
2190
+ meta: `${rows.length}`,
2191
+ children: [
2192
+ { t: "table", columns: ["action", "what it does"], rows },
2193
+ {
2194
+ t: "text",
2195
+ wrap: "wrap",
2196
+ tone: "muted",
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}`,
2198
+ },
2199
+ ],
2200
+ },
2201
+ };
2202
+ }
2203
+
2204
+ function checkpointsCard(desk: Desk): View {
2205
+ return desk.checkpoints.length === 0
2206
+ ? { t: "text", text: "No checkpoints recorded.", tone: "muted" }
2207
+ : {
2208
+ t: "box",
2209
+ dir: "col",
2210
+ border: "round",
2211
+ title: "WTF-P checkpoints",
2212
+ meta: String(desk.checkpoints.length),
2213
+ children: [
2214
+ {
2215
+ t: "table",
2216
+ columns: ["id", "kind", "status", "answer", "blocking", "scope"],
2217
+ rows: desk.checkpoints.slice(0, 100).map((checkpoint) => [
2218
+ checkpoint.id,
2219
+ checkpoint.kind,
2220
+ checkpoint.status,
2221
+ checkpoint.trust,
2222
+ checkpoint.blocking ? "yes" : "no",
2223
+ checkpoint.scope_uri.replace(/^project:\/\//u, ""),
2224
+ ]),
2225
+ },
2226
+ ],
2227
+ };
2228
+ }
2229
+
2230
+ async function validateAll(ctx: ExtensionContextV2): Promise<ExtensionOutputV2> {
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);
2236
+ const failures = files
2237
+ .map((file) => ({ file, errors: validateFile(workspace, file) }))
2238
+ .filter((record) => record.errors.length > 0);
2239
+ await ctx.state.set(
2240
+ "invalid",
2241
+ failures.map((record) => ({ file: record.file, errors: record.errors.slice(0, 5) })),
2242
+ );
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
+ ],
2280
+ };
2281
+ return { text: lines.join("\n"), card: view, ...(await picture(ctx, desk)) };
2282
+ }
2283
+
2284
+ // --- the write guard ---------------------------------------------------------
2285
+
2286
+ interface Armed {
2287
+ action: string;
2288
+ produces: GuardAction["produces"];
2289
+ section: string | null;
2290
+ workspace: string;
2291
+ }
2292
+
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 };
2509
+ }
2510
+
2511
+ async function guardWrite(ctx: ExtensionContextV2, target: string, host?: HostTarget, malformed?: string): Promise<ExtensionHookResult> {
2512
+ const workspace = ctx.snapshot.workspace;
2513
+ const served = ctx.snapshot.plugin ?? null;
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
+ );
2533
+ }
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;
2547
+ const gate = section.gates[0];
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 };
2804
+ }
2805
+
2806
+ // --- registration ------------------------------------------------------------
2807
+
2808
+ export default function extension(api: ExtensionApiV2): void {
2809
+ api.handle("desk", async (_args, ctx) => {
2810
+ const desk = await deskFor(ctx);
2811
+ return { text: progressText(desk), workspace: { enter: "desk" }, ...(await picture(ctx, desk, "desk")) };
2812
+ });
2813
+ api.handle("progress", async (_args, ctx) => {
2814
+ const desk = await deskFor(ctx);
2815
+ return { text: progressText(desk), card: progressCard(desk), ...(await picture(ctx, desk)) };
2816
+ });
2817
+ api.handle("help", async (_args, ctx) => helpCard(ctx.snapshot.plugin ?? null));
2818
+ api.handle("check-todos", async (_args, ctx) => startGates(ctx));
2819
+ api.handle("checkpoints", async (_args, ctx) => {
2820
+ const desk = await deskFor(ctx);
2821
+ return {
2822
+ text: desk.checkpoints.map((checkpoint) => `${checkpoint.id} ${checkpoint.kind} ${checkpoint.status} ${checkpoint.trust}`).join("\n") || "No checkpoints.",
2823
+ card: checkpointsCard(desk),
2824
+ };
2825
+ });
2826
+ api.handle("validate", async (_args, ctx) => validateAll(ctx));
2827
+
2828
+ api.action("next", async (_event, ctx) => {
2829
+ const next = nextAction(await deskFor(ctx));
2830
+ return next.command ? { text: next.command, prompt: { fill: next.command } } : { text: next.reason, toast: { text: next.reason } };
2831
+ });
2832
+ api.action("gates", async (_event, ctx) => startGates(ctx));
2833
+ api.action("validate", async (_event, ctx) => validateAll(ctx));
2834
+ api.action("help", async (_event, ctx) => helpCard(ctx.snapshot.plugin ?? null));
2835
+ api.action("section", async (event, ctx) => {
2836
+ const desk = await deskFor(ctx);
2837
+ const section = desk.sections.find((entry) => entry.id === event.key);
2838
+ if (!section) return { text: "Unknown section." };
2839
+ const next = sectionNext(desk.served, section);
2840
+ return {
2841
+ text: `${section.title}: ${next.reason}`,
2842
+ toast: { text: `${section.title}: ${next.reason}` },
2843
+ ...(next.command ? { prompt: { fill: next.command } } : {}),
2844
+ };
2845
+ });
2846
+
2847
+ api.tool("record", async (input, ctx) => {
2848
+ try {
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 ?? ""));
2864
+ return {
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,
2870
+ };
2871
+ } catch (error) {
2872
+ return { text: `No readiness: ${error instanceof Error ? error.message : String(error)}`, isError: true };
2873
+ }
2874
+ });
2875
+ api.tool("measure_section", async (input, ctx) => {
2876
+ try {
2877
+ const measured = measureSection(ctx.snapshot.workspace, String((input as Json).section ?? ""), await storedKey(ctx, false), await armedFor(ctx));
2878
+ const share = measured.target > 0 ? Math.round((measured.words / measured.target) * 100) : null;
2879
+ return {
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}`,
2881
+ data: measured,
2882
+ };
2883
+ } catch (error) {
2884
+ return { text: failure("Not measured", error), isError: true };
2885
+ }
2886
+ });
2887
+ api.tool("gate", async (input, ctx) => {
2888
+ const id = String((input as Json).checkpoint ?? "");
2889
+ const desk = await deskFor(ctx);
2890
+ const checkpoint = desk.checkpoints.find((entry) => entry.id === id);
2891
+ if (!checkpoint) return { text: `No checkpoint ${id}.`, isError: true };
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) } };
2894
+ });
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
+ }
2917
+ });
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
+ };
2926
+ const kept = (await ctx.state.get<string[]>("gate-kept")).value ?? [];
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);
2939
+ }
2940
+ await ctx.state.set("gate-kept", kept);
2941
+ await ctx.state.set("gate-recorded", recorded);
2942
+ const desk = await deskFor(ctx);
2943
+ const remaining = askable(desk, kept);
2944
+ const next = remaining[0];
2945
+ if (next && !note.startsWith("Nothing was recorded")) return { step: await ask(ctx, desk, next), total: remaining.length + recorded.length + kept.length };
2946
+ await ctx.state.set("gate-recorded", []);
2947
+ const summary = [recorded.length > 0 ? `Recorded: ${recorded.join("; ")}.` : "Nothing recorded.", note].filter(Boolean).join(" ");
2948
+ return {
2949
+ done: true,
2950
+ text: summary,
2951
+ card: { t: "text", text: `${recorded.length > 0 ? "✓" : "·"} ${summary}`, tone: recorded.length > 0 ? "positive" : "muted", wrap: "wrap" },
2952
+ ...(await picture(ctx, desk)),
2953
+ };
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
+ });
3009
+
3010
+ api.hook("prompt_submit", async (event, ctx) => {
3011
+ const typed = event.point === "prompt_submit" ? (event.text ?? "") : "";
3012
+ const desk = loadDesk(ctx.snapshot.workspace);
3013
+ const armed = arm(typed, desk, ctx.snapshot.workspace);
3014
+ if (!armed) {
3015
+ await ctx.state.delete("armed");
3016
+ return {};
3017
+ }
3018
+ await ctx.state.set("armed", armed);
3019
+ const roots = writeRoots(desk, armed);
3020
+ return {
3021
+ effects: [
3022
+ {
3023
+ kind: "notify_operator",
3024
+ key: "wtfp-guard",
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.`,
3026
+ },
3027
+ ],
3028
+ };
3029
+ });
3030
+ api.hook("before_tool", async (event, ctx) => (event.point === "before_tool" ? guard(ctx, event.tool, event.args, event) : {}));
3031
+
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
+ });
3047
+ api.on("workspace_enter", async (_event, ctx) => ({ text: "", ...(await picture(ctx)) }));
3048
+ // Leaving means the desk no longer holds the screen, whatever the snapshot says yet.
3049
+ api.on("workspace_leave", async (_event, ctx) => ({ text: "", ...(await picture(ctx, undefined, null)) }));
3050
+ api.on("fs_changed", async (event, ctx) => {
3051
+ if (event.event !== "fs_changed") return undefined;
3052
+ const records = event.paths.filter(
3053
+ (file) => file.startsWith(".planning/") && file.endsWith(".json") && !file.includes("/archives/") && !/(^|\/)\./u.test(file.slice(".planning/".length)),
3054
+ );
3055
+ const card = records.length > 0 ? await revalidate(ctx, records) : undefined;
3056
+ return { text: "", ...(card ? { card } : {}), ...(await picture(ctx)) };
3057
+ });
3058
+ api.on("dispatch_started", async (event, ctx) => {
3059
+ if (event.event !== "dispatch_started" || !event.agentId.startsWith("wtfp-")) return undefined;
3060
+ const runs = await running(ctx);
3061
+ runs[event.runId] = { agentId: event.agentId, at: Date.now() };
3062
+ await ctx.state.set("running", runs);
3063
+ return { text: "", ...(await picture(ctx)) };
3064
+ });
3065
+ const finished = async (runId: string, ctx: ExtensionContextV2): Promise<ExtensionOutputV2 | undefined> => {
3066
+ const runs = await running(ctx);
3067
+ if (!(runId in runs)) return undefined;
3068
+ delete runs[runId];
3069
+ await ctx.state.set("running", runs);
3070
+ return { text: "", ...(await picture(ctx)) };
3071
+ };
3072
+ api.on("dispatch_completed", async (event, ctx) => (event.event === "dispatch_completed" ? finished(event.runId, ctx) : undefined));
3073
+ api.on("dispatch_failed", async (event, ctx) => (event.event === "dispatch_failed" ? finished(event.runId, ctx) : undefined));
3074
+ }