daftari 3.17.0 → 3.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (318) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/README.md +3 -3
  3. package/dist/access/rbac.d.ts.map +1 -1
  4. package/dist/access/rbac.js +3 -1
  5. package/dist/access/rbac.js.map +1 -1
  6. package/dist/asof/git-read.d.ts.map +1 -1
  7. package/dist/asof/git-read.js +11 -9
  8. package/dist/asof/git-read.js.map +1 -1
  9. package/dist/asof/index.d.ts.map +1 -1
  10. package/dist/asof/index.js +3 -1
  11. package/dist/asof/index.js.map +1 -1
  12. package/dist/asof/report.d.ts.map +1 -1
  13. package/dist/asof/report.js +5 -3
  14. package/dist/asof/report.js.map +1 -1
  15. package/dist/asof/snapshot.d.ts +4 -3
  16. package/dist/asof/snapshot.d.ts.map +1 -1
  17. package/dist/asof/snapshot.js +44 -24
  18. package/dist/asof/snapshot.js.map +1 -1
  19. package/dist/board/ledger.d.ts.map +1 -1
  20. package/dist/board/ledger.js +1 -0
  21. package/dist/board/ledger.js.map +1 -1
  22. package/dist/board/sources/index.d.ts.map +1 -1
  23. package/dist/board/sources/index.js +2 -1
  24. package/dist/board/sources/index.js.map +1 -1
  25. package/dist/board/sources/lint.d.ts.map +1 -1
  26. package/dist/board/sources/lint.js +3 -1
  27. package/dist/board/sources/lint.js.map +1 -1
  28. package/dist/board/sources/staleness.d.ts +1 -0
  29. package/dist/board/sources/staleness.d.ts.map +1 -1
  30. package/dist/board/sources/staleness.js +101 -9
  31. package/dist/board/sources/staleness.js.map +1 -1
  32. package/dist/board/sources/staleness.test.js +27 -0
  33. package/dist/board/sources/staleness.test.js.map +1 -1
  34. package/dist/board/types.d.ts +7 -0
  35. package/dist/board/types.d.ts.map +1 -1
  36. package/dist/cli.d.ts.map +1 -1
  37. package/dist/cli.js +9 -2
  38. package/dist/cli.js.map +1 -1
  39. package/dist/consolidate/constants.d.ts.map +1 -1
  40. package/dist/consolidate/constants.js +6 -1
  41. package/dist/consolidate/constants.js.map +1 -1
  42. package/dist/consolidate/index.d.ts.map +1 -1
  43. package/dist/consolidate/index.js +1 -1
  44. package/dist/consolidate/index.js.map +1 -1
  45. package/dist/court/index.d.ts.map +1 -1
  46. package/dist/court/index.js +8 -1
  47. package/dist/court/index.js.map +1 -1
  48. package/dist/curation/chains.d.ts +21 -0
  49. package/dist/curation/chains.d.ts.map +1 -0
  50. package/dist/curation/chains.js +151 -0
  51. package/dist/curation/chains.js.map +1 -0
  52. package/dist/curation/governance-journals.d.ts +2 -0
  53. package/dist/curation/governance-journals.d.ts.map +1 -0
  54. package/dist/curation/governance-journals.js +36 -0
  55. package/dist/curation/governance-journals.js.map +1 -0
  56. package/dist/curation/grounding.d.ts +42 -0
  57. package/dist/curation/grounding.d.ts.map +1 -0
  58. package/dist/curation/grounding.js +247 -0
  59. package/dist/curation/grounding.js.map +1 -0
  60. package/dist/curation/lint-page.d.ts +22 -0
  61. package/dist/curation/lint-page.d.ts.map +1 -0
  62. package/dist/curation/lint-page.js +97 -0
  63. package/dist/curation/lint-page.js.map +1 -0
  64. package/dist/curation/lint-voice.d.ts.map +1 -1
  65. package/dist/curation/lint-voice.js +16 -11
  66. package/dist/curation/lint-voice.js.map +1 -1
  67. package/dist/curation/lint.d.ts +7 -1
  68. package/dist/curation/lint.d.ts.map +1 -1
  69. package/dist/curation/lint.js +85 -25
  70. package/dist/curation/lint.js.map +1 -1
  71. package/dist/curation/provenance.d.ts.map +1 -1
  72. package/dist/curation/provenance.js.map +1 -1
  73. package/dist/curation/question-candidates.d.ts +27 -0
  74. package/dist/curation/question-candidates.d.ts.map +1 -0
  75. package/dist/curation/question-candidates.js +151 -0
  76. package/dist/curation/question-candidates.js.map +1 -0
  77. package/dist/curation/questions.d.ts +9 -0
  78. package/dist/curation/questions.d.ts.map +1 -0
  79. package/dist/curation/questions.js +44 -0
  80. package/dist/curation/questions.js.map +1 -0
  81. package/dist/curation/review-log.d.ts +36 -0
  82. package/dist/curation/review-log.d.ts.map +1 -0
  83. package/dist/curation/review-log.js +195 -0
  84. package/dist/curation/review-log.js.map +1 -0
  85. package/dist/curation/review-stats.d.ts +39 -0
  86. package/dist/curation/review-stats.d.ts.map +1 -0
  87. package/dist/curation/review-stats.js +222 -0
  88. package/dist/curation/review-stats.js.map +1 -0
  89. package/dist/curation/review-throughput.d.ts +1 -0
  90. package/dist/curation/review-throughput.d.ts.map +1 -1
  91. package/dist/curation/review-throughput.js +1 -1
  92. package/dist/curation/review-throughput.js.map +1 -1
  93. package/dist/curation/shadow.d.ts.map +1 -1
  94. package/dist/curation/shadow.js +2 -0
  95. package/dist/curation/shadow.js.map +1 -1
  96. package/dist/curation/source-refs.d.ts +7 -0
  97. package/dist/curation/source-refs.d.ts.map +1 -1
  98. package/dist/curation/source-refs.js +46 -1
  99. package/dist/curation/source-refs.js.map +1 -1
  100. package/dist/curation/staged-actions.d.ts +12 -3
  101. package/dist/curation/staged-actions.d.ts.map +1 -1
  102. package/dist/curation/staged-actions.js +206 -46
  103. package/dist/curation/staged-actions.js.map +1 -1
  104. package/dist/curation/staleness.d.ts +6 -0
  105. package/dist/curation/staleness.d.ts.map +1 -1
  106. package/dist/curation/staleness.js +41 -0
  107. package/dist/curation/staleness.js.map +1 -1
  108. package/dist/curation/structural.d.ts.map +1 -1
  109. package/dist/curation/structural.js +6 -4
  110. package/dist/curation/structural.js.map +1 -1
  111. package/dist/curation/supersede-chains.d.ts +10 -0
  112. package/dist/curation/supersede-chains.d.ts.map +1 -0
  113. package/dist/curation/supersede-chains.js +95 -0
  114. package/dist/curation/supersede-chains.js.map +1 -0
  115. package/dist/curation/tension-blast.d.ts +5 -1
  116. package/dist/curation/tension-blast.d.ts.map +1 -1
  117. package/dist/curation/tension-blast.js +56 -9
  118. package/dist/curation/tension-blast.js.map +1 -1
  119. package/dist/curation/tension.d.ts +4 -1
  120. package/dist/curation/tension.d.ts.map +1 -1
  121. package/dist/curation/tension.js +48 -18
  122. package/dist/curation/tension.js.map +1 -1
  123. package/dist/curation/tier0.d.ts +3 -1
  124. package/dist/curation/tier0.d.ts.map +1 -1
  125. package/dist/curation/tier0.js +7 -3
  126. package/dist/curation/tier0.js.map +1 -1
  127. package/dist/curation/vault-docs.js +4 -4
  128. package/dist/curation/vault-docs.js.map +1 -1
  129. package/dist/distill/citation-check.d.ts +29 -0
  130. package/dist/distill/citation-check.d.ts.map +1 -0
  131. package/dist/distill/citation-check.js +109 -0
  132. package/dist/distill/citation-check.js.map +1 -0
  133. package/dist/distill/cli.d.ts +1 -1
  134. package/dist/distill/cli.d.ts.map +1 -1
  135. package/dist/distill/cli.js +127 -16
  136. package/dist/distill/cli.js.map +1 -1
  137. package/dist/distill/cost.d.ts +7 -3
  138. package/dist/distill/cost.d.ts.map +1 -1
  139. package/dist/distill/cost.js.map +1 -1
  140. package/dist/distill/extract.d.ts +38 -1
  141. package/dist/distill/extract.d.ts.map +1 -1
  142. package/dist/distill/extract.js +48 -6
  143. package/dist/distill/extract.js.map +1 -1
  144. package/dist/distill/index.d.ts +1 -1
  145. package/dist/distill/index.d.ts.map +1 -1
  146. package/dist/distill/index.js +1 -1
  147. package/dist/distill/index.js.map +1 -1
  148. package/dist/distill/propose.d.ts.map +1 -1
  149. package/dist/distill/propose.js +23 -0
  150. package/dist/distill/propose.js.map +1 -1
  151. package/dist/distill/receipt-store.d.ts.map +1 -1
  152. package/dist/distill/receipt-store.js +4 -3
  153. package/dist/distill/receipt-store.js.map +1 -1
  154. package/dist/distill/state.d.ts +39 -0
  155. package/dist/distill/state.d.ts.map +1 -1
  156. package/dist/distill/state.js +84 -7
  157. package/dist/distill/state.js.map +1 -1
  158. package/dist/eval/index.js.map +1 -1
  159. package/dist/eval/llm-openrouter.d.ts.map +1 -1
  160. package/dist/eval/llm-openrouter.js +6 -4
  161. package/dist/eval/llm-openrouter.js.map +1 -1
  162. package/dist/eval/llm.d.ts +2 -0
  163. package/dist/eval/llm.d.ts.map +1 -1
  164. package/dist/eval/llm.js +29 -4
  165. package/dist/eval/llm.js.map +1 -1
  166. package/dist/eval/tool-surface.d.ts.map +1 -1
  167. package/dist/eval/tool-surface.js +4 -1
  168. package/dist/eval/tool-surface.js.map +1 -1
  169. package/dist/federation/classification.d.ts.map +1 -1
  170. package/dist/federation/classification.js +4 -0
  171. package/dist/federation/classification.js.map +1 -1
  172. package/dist/federation/mounts.d.ts.map +1 -1
  173. package/dist/federation/mounts.js +3 -2
  174. package/dist/federation/mounts.js.map +1 -1
  175. package/dist/fence/detect.js +1 -1
  176. package/dist/fence/detect.js.map +1 -1
  177. package/dist/frontmatter/schema.d.ts.map +1 -1
  178. package/dist/frontmatter/schema.js +20 -0
  179. package/dist/frontmatter/schema.js.map +1 -1
  180. package/dist/frontmatter/types.d.ts +4 -1
  181. package/dist/frontmatter/types.d.ts.map +1 -1
  182. package/dist/frontmatter/types.js +3 -0
  183. package/dist/frontmatter/types.js.map +1 -1
  184. package/dist/import/langgraph-store.d.ts +2 -1
  185. package/dist/import/langgraph-store.d.ts.map +1 -1
  186. package/dist/import/langgraph-store.js +23 -4
  187. package/dist/import/langgraph-store.js.map +1 -1
  188. package/dist/index.d.ts +1 -1
  189. package/dist/index.d.ts.map +1 -1
  190. package/dist/index.js +27 -10
  191. package/dist/index.js.map +1 -1
  192. package/dist/integrations/distill.d.ts.map +1 -1
  193. package/dist/integrations/distill.js +5 -3
  194. package/dist/integrations/distill.js.map +1 -1
  195. package/dist/interview/index.d.ts.map +1 -1
  196. package/dist/interview/index.js +7 -1
  197. package/dist/interview/index.js.map +1 -1
  198. package/dist/interview/questions.d.ts +1 -1
  199. package/dist/interview/questions.d.ts.map +1 -1
  200. package/dist/interview/questions.js +6 -39
  201. package/dist/interview/questions.js.map +1 -1
  202. package/dist/interview/transcript.d.ts +2 -0
  203. package/dist/interview/transcript.d.ts.map +1 -1
  204. package/dist/interview/transcript.js +19 -5
  205. package/dist/interview/transcript.js.map +1 -1
  206. package/dist/lifecycle/lock.d.ts +19 -4
  207. package/dist/lifecycle/lock.d.ts.map +1 -1
  208. package/dist/lifecycle/lock.js +760 -171
  209. package/dist/lifecycle/lock.js.map +1 -1
  210. package/dist/okf/import.d.ts.map +1 -1
  211. package/dist/okf/import.js +15 -3
  212. package/dist/okf/import.js.map +1 -1
  213. package/dist/search/amended-by.d.ts +45 -0
  214. package/dist/search/amended-by.d.ts.map +1 -0
  215. package/dist/search/amended-by.js +62 -0
  216. package/dist/search/amended-by.js.map +1 -0
  217. package/dist/search/hybrid.d.ts +5 -0
  218. package/dist/search/hybrid.d.ts.map +1 -1
  219. package/dist/search/hybrid.js.map +1 -1
  220. package/dist/search/reindex.d.ts +2 -0
  221. package/dist/search/reindex.d.ts.map +1 -1
  222. package/dist/search/reindex.js +44 -12
  223. package/dist/search/reindex.js.map +1 -1
  224. package/dist/search/watcher.d.ts +2 -1
  225. package/dist/search/watcher.d.ts.map +1 -1
  226. package/dist/search/watcher.js +11 -19
  227. package/dist/search/watcher.js.map +1 -1
  228. package/dist/serve/index.d.ts.map +1 -1
  229. package/dist/serve/index.js +21 -10
  230. package/dist/serve/index.js.map +1 -1
  231. package/dist/serve/session.d.ts +3 -1
  232. package/dist/serve/session.d.ts.map +1 -1
  233. package/dist/serve/session.js +32 -4
  234. package/dist/serve/session.js.map +1 -1
  235. package/dist/server.d.ts.map +1 -1
  236. package/dist/server.js +10 -1
  237. package/dist/server.js.map +1 -1
  238. package/dist/sleep/cycle.d.ts +2 -0
  239. package/dist/sleep/cycle.d.ts.map +1 -1
  240. package/dist/sleep/cycle.js +65 -35
  241. package/dist/sleep/cycle.js.map +1 -1
  242. package/dist/sleep/index.d.ts.map +1 -1
  243. package/dist/sleep/index.js +1 -1
  244. package/dist/sleep/index.js.map +1 -1
  245. package/dist/sleep/report.d.ts.map +1 -1
  246. package/dist/sleep/report.js +3 -2
  247. package/dist/sleep/report.js.map +1 -1
  248. package/dist/storage/index-db.d.ts +28 -1
  249. package/dist/storage/index-db.d.ts.map +1 -1
  250. package/dist/storage/index-db.js +82 -23
  251. package/dist/storage/index-db.js.map +1 -1
  252. package/dist/storage/local.d.ts +6 -2
  253. package/dist/storage/local.d.ts.map +1 -1
  254. package/dist/storage/local.js +45 -7
  255. package/dist/storage/local.js.map +1 -1
  256. package/dist/storage/sync.d.ts +1 -0
  257. package/dist/storage/sync.d.ts.map +1 -1
  258. package/dist/storage/sync.js +31 -6
  259. package/dist/storage/sync.js.map +1 -1
  260. package/dist/tools/board.d.ts +1 -0
  261. package/dist/tools/board.d.ts.map +1 -1
  262. package/dist/tools/board.js +27 -2
  263. package/dist/tools/board.js.map +1 -1
  264. package/dist/tools/board.test.js +4 -2
  265. package/dist/tools/board.test.js.map +1 -1
  266. package/dist/tools/chains.d.ts +11 -0
  267. package/dist/tools/chains.d.ts.map +1 -0
  268. package/dist/tools/chains.js +133 -0
  269. package/dist/tools/chains.js.map +1 -0
  270. package/dist/tools/curation.d.ts +6 -1
  271. package/dist/tools/curation.d.ts.map +1 -1
  272. package/dist/tools/curation.js +114 -69
  273. package/dist/tools/curation.js.map +1 -1
  274. package/dist/tools/erase.d.ts.map +1 -1
  275. package/dist/tools/erase.js +14 -19
  276. package/dist/tools/erase.js.map +1 -1
  277. package/dist/tools/positions.d.ts.map +1 -1
  278. package/dist/tools/positions.js +4 -2
  279. package/dist/tools/positions.js.map +1 -1
  280. package/dist/tools/question-candidates.d.ts +11 -0
  281. package/dist/tools/question-candidates.d.ts.map +1 -0
  282. package/dist/tools/question-candidates.js +205 -0
  283. package/dist/tools/question-candidates.js.map +1 -0
  284. package/dist/tools/read.d.ts +5 -0
  285. package/dist/tools/read.d.ts.map +1 -1
  286. package/dist/tools/read.js +39 -12
  287. package/dist/tools/read.js.map +1 -1
  288. package/dist/tools/receipt.d.ts +4 -0
  289. package/dist/tools/receipt.d.ts.map +1 -1
  290. package/dist/tools/receipt.js +262 -22
  291. package/dist/tools/receipt.js.map +1 -1
  292. package/dist/tools/search.d.ts.map +1 -1
  293. package/dist/tools/search.js +53 -4
  294. package/dist/tools/search.js.map +1 -1
  295. package/dist/tools/staged-actions.d.ts +2 -1
  296. package/dist/tools/staged-actions.d.ts.map +1 -1
  297. package/dist/tools/staged-actions.js +152 -46
  298. package/dist/tools/staged-actions.js.map +1 -1
  299. package/dist/tools/write.d.ts +15 -2
  300. package/dist/tools/write.d.ts.map +1 -1
  301. package/dist/tools/write.js +747 -89
  302. package/dist/tools/write.js.map +1 -1
  303. package/dist/utils/config.d.ts +10 -2
  304. package/dist/utils/config.d.ts.map +1 -1
  305. package/dist/utils/config.js +61 -1
  306. package/dist/utils/config.js.map +1 -1
  307. package/dist/utils/git.d.ts +1 -0
  308. package/dist/utils/git.d.ts.map +1 -1
  309. package/dist/utils/git.js +18 -0
  310. package/dist/utils/git.js.map +1 -1
  311. package/dist/utils/vault-gitignore.d.ts +1 -1
  312. package/dist/utils/vault-gitignore.d.ts.map +1 -1
  313. package/dist/utils/vault-gitignore.js +25 -9
  314. package/dist/utils/vault-gitignore.js.map +1 -1
  315. package/dist/view/board-page.test.js +1 -1
  316. package/dist/view/board-page.test.js.map +1 -1
  317. package/package.json +3 -1
  318. package/templates/config.yaml +18 -3
@@ -1,4 +1,5 @@
1
- // Write-path tools: vault_write, vault_append, vault_promote, vault_deprecate.
1
+ // Write-path tools: vault_write, vault_patch, vault_append, vault_promote,
2
+ // vault_deprecate, vault_unsupersede.
2
3
  //
3
4
  // Every write follows the same shape: validate inputs, acquire a file-level
4
5
  // lock, mutate the markdown file on disk, refresh the search index, auto-commit
@@ -11,16 +12,18 @@ import { mkdir, writeFile } from "node:fs/promises";
11
12
  import { dirname, relative, resolve, sep } from "node:path";
12
13
  import matter from "gray-matter";
13
14
  import { acquireLock, mintLeaseHolder, openLockDb, releaseLock } from "../access/locks.js";
14
- import { canPromote, canWrite, isProposeOnly } from "../access/rbac.js";
15
+ import { canPromote, canRead, canWrite, isProposeOnly, } from "../access/rbac.js";
15
16
  import { mintConsumesEdges } from "../curation/consumes.js";
16
17
  import { leakLedgerPath, privateReadsForRun, privateReadsForRunStrict, } from "../curation/leak-ledger.js";
17
18
  import { foreignPositionViolation } from "../curation/positions.js";
18
19
  import { frontmatterDiff, recordProvenance } from "../curation/provenance.js";
20
+ import { appendReviewEvents, docReviewItem, principalKindForVault, } from "../curation/review-log.js";
19
21
  import { recordShadowAction } from "../curation/shadow.js";
20
22
  import { resolveVaultSourceRef } from "../curation/source-refs.js";
21
23
  import { stageActionWithConflictCheck } from "../curation/staged-actions.js";
22
- import { sourceReadable } from "../curation/tension-access.js";
23
- import { bucketHiddenDownstream, buildReverseLinkMap, buildReverseSourceMap, computeBlast, } from "../curation/tension-blast.js";
24
+ import { closesSupersedeLoop } from "../curation/supersede-chains.js";
25
+ import { sourceReadable, sourceVerifiable } from "../curation/tension-access.js";
26
+ import { buildReverseLinkMap, buildReverseSourceMap, computeBlastForReader, } from "../curation/tension-blast.js";
24
27
  import { buildPathIndexes, extractLinks, loadDocuments, outgoingLinkTargets, } from "../curation/vault-docs.js";
25
28
  import { encodeLineageEntry, readersFromLineage, unionLineage, } from "../distill/reader-fingerprint.js";
26
29
  import { parseDocument } from "../frontmatter/parser.js";
@@ -33,11 +36,12 @@ import { getIndexStatus, indexingBusyMessage } from "../search/index-state.js";
33
36
  import { indexDocument } from "../search/reindex.js";
34
37
  import { noteSelfWrite } from "../search/self-write.js";
35
38
  import { allDocumentPaths, getDocumentsByPaths } from "../storage/index-db.js";
36
- import { readFile, resolveVaultPath } from "../storage/local.js";
39
+ import { collectionOfPath, matchesIgnoreList, readFile, resolveVaultPath, } from "../storage/local.js";
37
40
  import { loadConfig, } from "../utils/config.js";
38
41
  import { normalizeIsoDate } from "../utils/dates.js";
39
42
  import { commit } from "../utils/git.js";
40
43
  import { sha256Hex } from "../utils/hash.js";
44
+ import { canonicalRel } from "../utils/paths.js";
41
45
  import { readRunId } from "../utils/run-id.js";
42
46
  import { mintDescribesPins } from "./pin-mint.js";
43
47
  import { openIndexForAccessOrNull } from "./search.js";
@@ -121,7 +125,14 @@ export function requireIndexReady() {
121
125
  // A document's RBAC collection: its frontmatter `collection`, falling back to
122
126
  // the top-level directory of its vault-relative path.
123
127
  function collectionOf(relPath, fm) {
124
- return fm.collection || (relPath.split("/")[0] ?? "");
128
+ return fm.collection || collectionOfPath(relPath);
129
+ }
130
+ // An ignored path is not a vault document (#646). A write there would commit a
131
+ // file that no search, status or lint can see, so it is refused instead.
132
+ export function refuseIgnoredPath(relPath, ignore) {
133
+ if (!matchesIgnoreList(relPath, ignore))
134
+ return ok(undefined);
135
+ return err(new Error(`${relPath} is excluded by the vault's 'ignore' config`));
125
136
  }
126
137
  // The collection the write gate for a *new* write must key off: the top-level
127
138
  // directory the bytes physically land in, i.e. the resolved target path's first
@@ -138,7 +149,7 @@ function collectionOf(relPath, fm) {
138
149
  // write; `resolveVaultPath` rejects it properly downstream.
139
150
  export function targetCollection(vaultRoot, relPath) {
140
151
  const rel = relative(resolve(vaultRoot), resolve(vaultRoot, relPath));
141
- return rel.split(sep)[0] ?? "";
152
+ return collectionOfPath(rel.split(sep).join("/"));
142
153
  }
143
154
  // Resolves an extension field's serializable value from the raw frontmatter:
144
155
  // the value as written, with a js-yaml Date normalized to a YYYY-MM-DD string.
@@ -191,12 +202,21 @@ export function serializeDocument(fm, body, extensions = [], raw = {}) {
191
202
  sources: fm.sources,
192
203
  superseded_by: fm.superseded_by,
193
204
  ttl_days: fm.ttl_days,
205
+ // Emitted only when set (the positions convention) so documents outside a
206
+ // series stay byte-stable.
207
+ ...(fm.series != null ? { series: fm.series } : {}),
194
208
  // `?? null` for the same reason as tier: a hand-built Frontmatter that
195
209
  // predates these fields carries undefined, which js-yaml refuses to dump.
196
210
  valid_from: fm.valid_from ?? null,
197
211
  valid_until: fm.valid_until ?? null,
212
+ // Emitted only when set (the positions convention) so documents without a
213
+ // source time stay byte-stable.
214
+ ...(fm.said_at != null ? { said_at: fm.said_at } : {}),
198
215
  tags: fm.tags,
199
216
  describes: fm.describes,
217
+ // Emitted only when non-empty (the said_at convention), so documents that
218
+ // amend nothing stay byte-stable.
219
+ ...(fm.amends != null && fm.amends.length > 0 ? { amends: fm.amends } : {}),
200
220
  questions_answered: fm.questions_answered,
201
221
  questions_raised: fm.questions_raised,
202
222
  subjects: fm.subjects,
@@ -244,6 +264,23 @@ export function serializeDocument(fm, body, extensions = [], raw = {}) {
244
264
  function shortHash(h) {
245
265
  return h.length === 64 ? h.slice(0, 12) : h;
246
266
  }
267
+ // Refuses a write whose base_version no longer matches the document: logs the
268
+ // "rejected_stale" provenance entry and returns the error isStaleWriteError
269
+ // classifies. The one place both shapes are defined, so the check inside
270
+ // performWrite's lock and vault_patch's pre-edit check cannot drift apart.
271
+ async function rejectStale(params) {
272
+ await recordProvenance(params.vaultRoot, {
273
+ tool: params.tool,
274
+ file: params.relPath,
275
+ agent: params.agent,
276
+ ...(params.principal ? { principal: params.principal } : {}),
277
+ ...(params.runId ? { run_id: params.runId } : {}),
278
+ action: "rejected_stale",
279
+ reason: `stale: base_version ${shortHash(params.baseVersion)} != ` +
280
+ `current ${params.currentHash ? shortHash(params.currentHash) : "<absent>"}`,
281
+ });
282
+ return err(new Error(`${STALE_WRITE_PREFIX} ${params.relPath} changed since base_version`));
283
+ }
247
284
  // Runs the durable part of a write under an exclusive file lock: write the
248
285
  // file, refresh the index, commit, log provenance. The lock is released in a
249
286
  // finally block so a failure mid-write never wedges the file.
@@ -263,6 +300,14 @@ function shortHash(h) {
263
300
  // entry is logged. When `baseVersion` is omitted the check is skipped entirely
264
301
  // and last-write-wins behavior is preserved.
265
302
  async function performWrite(params) {
303
+ // Loaded here, not threaded from callers like the fields above: this gate has
304
+ // to hold for every write tool, including ones added later.
305
+ const config = loadConfig(params.vaultRoot);
306
+ if (!config.ok)
307
+ return config;
308
+ const ignored = refuseIgnoredPath(params.relPath, config.value.ignore);
309
+ if (!ignored.ok)
310
+ return ignored;
266
311
  // Shadow mode (spec §11.5): everything up to here ran exactly as live —
267
312
  // validation, RBAC, frontmatter assembly, diff — so the logged do() is one
268
313
  // that WOULD have executed. Log it with its impact/budget verdict and stop:
@@ -312,17 +357,16 @@ async function performWrite(params) {
312
357
  const onDisk = await readFile(params.absPath);
313
358
  const currentHash = onDisk.ok ? sha256Hex(onDisk.value) : null;
314
359
  if (currentHash !== params.baseVersion) {
315
- await recordProvenance(params.vaultRoot, {
360
+ return await rejectStale({
361
+ vaultRoot: params.vaultRoot,
362
+ relPath: params.relPath,
316
363
  tool: params.tool,
317
- file: params.relPath,
318
364
  agent: params.agent,
365
+ baseVersion: params.baseVersion,
366
+ currentHash,
319
367
  ...(params.principal ? { principal: params.principal } : {}),
320
- ...(params.runId ? { run_id: params.runId } : {}),
321
- action: "rejected_stale",
322
- reason: `stale: base_version ${shortHash(params.baseVersion)} != ` +
323
- `current ${currentHash ? shortHash(currentHash) : "<absent>"}`,
368
+ ...(params.runId ? { runId: params.runId } : {}),
324
369
  });
325
- return err(new Error(`${STALE_WRITE_PREFIX} ${params.relPath} changed since base_version`));
326
370
  }
327
371
  }
328
372
  // Cross-vault leak gate (U3): the write-time refusal. Runs AFTER the
@@ -374,6 +418,12 @@ async function performWrite(params) {
374
418
  else
375
419
  commitError = committed.error;
376
420
  }
421
+ const provenanceReason = [
422
+ params.reason,
423
+ commitError ? `commit failed: ${commitError.message}` : undefined,
424
+ ]
425
+ .filter((part) => part !== undefined)
426
+ .join("; ");
377
427
  await recordProvenance(params.vaultRoot, {
378
428
  tool: params.tool,
379
429
  file: params.relPath,
@@ -383,7 +433,7 @@ async function performWrite(params) {
383
433
  ...(params.bodyChanged !== undefined ? { body_changed: params.bodyChanged } : {}),
384
434
  action: params.action,
385
435
  frontmatter_diff: frontmatterDiff(params.oldFrontmatter, params.newFrontmatter),
386
- ...(commitError ? { reason: `commit failed: ${commitError.message}` } : {}),
436
+ ...(provenanceReason ? { reason: provenanceReason } : {}),
387
437
  });
388
438
  // #233: a run-correlated write compiles its input set — every path the
389
439
  // run read beforehand becomes a consumes edge. Best-effort like the
@@ -457,7 +507,7 @@ function denyIfProposeOnly(access, tool) {
457
507
  return err(new Error(`${tool}: role '${access.roleName}' is propose-only — direct writes are ` +
458
508
  `disabled. Propose the change instead: vault_write stages a 'write' ` +
459
509
  `proposal, and vault_stage_action stages lifecycle actions ` +
460
- `(promote, deprecate, supersede, merge, confidence-up) for ratification.`));
510
+ `(promote, deprecate, supersede, unsupersede, merge, confidence-up) for ratification.`));
461
511
  }
462
512
  return ok(undefined);
463
513
  }
@@ -470,6 +520,22 @@ export function requireWriteAccess(access, collection) {
470
520
  }
471
521
  return ok(undefined);
472
522
  }
523
+ // `canonical` is the vault vouching for a document, and the `promote` grant is
524
+ // what authorizes that (docs/file-format.md). A write whose post-state is
525
+ // canonical while the prior state was not (or there was no prior doc) is a
526
+ // promote by another name, so it needs the grant on every write path, not only
527
+ // vault_promote. Callers judge the MERGED post-state, so an inherited status
528
+ // counts. Editing an already-canonical doc without changing its status is not
529
+ // a transition and stays open to writers. No access context (operator) passes.
530
+ // Under vault_ratify, `access` is the ratifier's, so the ratifier needs it.
531
+ function requireCanonicalAuthority(access, oldStatus, newStatus, tool) {
532
+ if (!access || newStatus !== "canonical" || oldStatus === "canonical")
533
+ return ok(undefined);
534
+ if (canPromote(access.role))
535
+ return ok(undefined);
536
+ return err(new Error(`access denied: role '${access.roleName}' cannot promote documents — ` +
537
+ `${tool} cannot set status 'canonical'; write it as draft and use vault_promote`));
538
+ }
473
539
  // Git history is the attribution layer, and the caller-supplied `agent`
474
540
  // string is advisory — any authenticated principal could claim any agent.
475
541
  // When an AccessContext exists the commit author is the AUTHENTICATED
@@ -626,6 +692,7 @@ export async function loadTargetDocument(vaultRoot, rawPath, tool) {
626
692
  parsed: parsed.value,
627
693
  config: config.value,
628
694
  contentHash: sha256Hex(existing.value),
695
+ text: existing.value,
629
696
  });
630
697
  }
631
698
  // The shared performWrite tail for frontmatter-only mutations: body preserved
@@ -655,8 +722,33 @@ export function performFrontmatterWrite(opts) {
655
722
  leakGate: target.config.leakGate,
656
723
  hasAccessContext: opts.access !== undefined,
657
724
  ...(opts.runId !== undefined ? { runId: opts.runId } : {}),
725
+ ...(opts.reason !== undefined ? { reason: opts.reason } : {}),
658
726
  });
659
727
  }
728
+ // #643: advisory for `amends` targets that resolve to no document the caller
729
+ // can read. Best-effort like generativeDomainRefs: index unavailability
730
+ // degrades to silence.
731
+ function unresolvedAmends(vaultRoot, amends, relPath, access) {
732
+ if (amends.length === 0)
733
+ return null;
734
+ const db = openIndexForAccessOrNull(vaultRoot);
735
+ if (!db)
736
+ return null;
737
+ try {
738
+ const warnings = amends.flatMap((target) => {
739
+ if (canonicalRel(target) === relPath) {
740
+ return [`amends '${target}' is this document; it will not surface anywhere`];
741
+ }
742
+ if (sourceVerifiable(db, access, target))
743
+ return [];
744
+ return [`amends '${target}' does not resolve to a document you can read`];
745
+ });
746
+ return warnings.length > 0 ? warnings : null;
747
+ }
748
+ finally {
749
+ db.close();
750
+ }
751
+ }
660
752
  // ---------------------------------------------------------------------------
661
753
  // vault_write
662
754
  // ---------------------------------------------------------------------------
@@ -681,6 +773,14 @@ function sameBody(a, b) {
681
773
  const norm = (s) => s.replace(/^\n+/, "").replace(/\s+$/, "");
682
774
  return norm(a) === norm(b);
683
775
  }
776
+ // Frontmatter equality minus the server stamps, which every write moves.
777
+ function sameFields(a, b) {
778
+ const unstamped = ({ updated: _u, updated_by: _b, ...rest }) => rest;
779
+ return JSON.stringify(unstamped(a)) === JSON.stringify(unstamped(b));
780
+ }
781
+ function patchChangesNothing(path) {
782
+ return new Error(`vault_patch: this patch changes nothing in ${path}`);
783
+ }
684
784
  function checkTierGuard(args) {
685
785
  const { tool, path, tier, oldBody, newBody, agent } = args;
686
786
  if (tier !== "source" && tier !== "manual")
@@ -761,27 +861,34 @@ const SUPERSEDE_HINT = "This write replaced an existing document in place. If it
761
861
  "superseded_by edge instead of erasing lineage. Advisory only — this write " +
762
862
  "has already landed.";
763
863
  export async function vaultWrite(vaultRoot, args, access) {
864
+ return writeDocument(vaultRoot, args, access);
865
+ }
866
+ // The one path for a full-document write. vault_patch runs through it too, so
867
+ // the merge, tier guards, hooks, pin minting, validation, foreign-position
868
+ // check, propose-only coercion, and leak gate exist exactly once.
869
+ async function writeDocument(vaultRoot, args, access, patch) {
870
+ const tool = patch ? "vault_patch" : "vault_write";
764
871
  const ready = requireIndexReady();
765
872
  if (!ready.ok)
766
873
  return ready;
767
- const path = requireString(args, "path", "vault_write");
874
+ const path = requireString(args, "path", tool);
768
875
  if (!path.ok)
769
876
  return path;
770
- const agent = requireString(args, "agent", "vault_write");
877
+ const agent = requireString(args, "agent", tool);
771
878
  if (!agent.ok)
772
879
  return agent;
773
- const baseVersion = readBaseVersion(args, "vault_write");
880
+ const baseVersion = readBaseVersion(args, tool);
774
881
  if (!baseVersion.ok)
775
882
  return baseVersion;
776
- const runId = readRunId(args, "vault_write");
883
+ const runId = readRunId(args, tool);
777
884
  if (!runId.ok)
778
885
  return runId;
779
886
  const body = args.body;
780
887
  if (typeof body !== "string") {
781
- return err(new Error("vault_write requires a string 'body' argument"));
888
+ return err(new Error(`${tool} requires a string 'body' argument`));
782
889
  }
783
890
  if (args.frontmatter === null || typeof args.frontmatter !== "object") {
784
- return err(new Error("vault_write requires a 'frontmatter' object argument"));
891
+ return err(new Error(`${tool} requires a 'frontmatter' object argument`));
785
892
  }
786
893
  const rawFrontmatter = args.frontmatter;
787
894
  // RBAC is checked before any file I/O or frontmatter validation: an
@@ -799,6 +906,8 @@ export async function vaultWrite(vaultRoot, args, access) {
799
906
  const resolved = resolveVaultPath(vaultRoot, path.value);
800
907
  if (!resolved.ok)
801
908
  return resolved;
909
+ const absPath = resolved.value.absPath;
910
+ const readCurrent = async () => patch ? ok(patch.loadedText) : readFile(absPath);
802
911
  // #235: a propose-only role's write lands as a staged `write` proposal, not
803
912
  // a mutation. Coerced EARLY — before file I/O, tier guards, hooks, or
804
913
  // validation — because all of that runs for real at ratify time when
@@ -822,7 +931,7 @@ export async function vaultWrite(vaultRoot, args, access) {
822
931
  return proposeConfig;
823
932
  let previewRaw = { ...rawFrontmatter };
824
933
  let existingPositions = null;
825
- const onDisk = await readFile(resolved.value.absPath);
934
+ const onDisk = await readCurrent();
826
935
  if (onDisk.ok) {
827
936
  const parsedExisting = parseDocument(onDisk.value);
828
937
  if (parsedExisting.ok) {
@@ -835,6 +944,11 @@ export async function vaultWrite(vaultRoot, args, access) {
835
944
  merged[key] = value;
836
945
  }
837
946
  previewRaw = merged;
947
+ if (patch &&
948
+ body === parsedExisting.value.content &&
949
+ sameFields(parsedExisting.value.raw, merged)) {
950
+ return err(patchChangesNothing(path.value));
951
+ }
838
952
  }
839
953
  }
840
954
  if (previewRaw.updated === undefined || previewRaw.updated === null) {
@@ -850,7 +964,7 @@ export async function vaultWrite(vaultRoot, args, access) {
850
964
  if (existingPositions != null) {
851
965
  const previewViolation = foreignPositionViolation(existingPositions, preview.frontmatter.positions, access.user);
852
966
  if (previewViolation) {
853
- return err(new Error(`vault_write (stage preview): ${previewViolation} — another principal's ` +
967
+ return err(new Error(`${tool} (stage preview): ${previewViolation} — another principal's ` +
854
968
  `position entries can only be superseded by their own new position ` +
855
969
  `(vault_assert) or edited by their holder`));
856
970
  }
@@ -862,7 +976,13 @@ export async function vaultWrite(vaultRoot, args, access) {
862
976
  rationale: typeof args.reason === "string" && args.reason.trim().length > 0
863
977
  ? args.reason.trim()
864
978
  : `propose-only role '${access.roleName}': write staged for ratification`,
865
- proposedDiff: { frontmatter: rawFrontmatter, body },
979
+ // body_edits is display-only for the ratifier, like repin's replacements;
980
+ // ratify dispatches the full computed body.
981
+ proposedDiff: {
982
+ frontmatter: rawFrontmatter,
983
+ body,
984
+ ...(patch ? { body_edits: patch.bodyEdits } : {}),
985
+ },
866
986
  // LD-13 ratify staleness guard (same one-line capture as vault_assert's
867
987
  // propose-only branch): anchor to the bytes `onDisk` was read from above,
868
988
  // so a ratify replay against a document that changed since staging fails
@@ -890,7 +1010,7 @@ export async function vaultWrite(vaultRoot, args, access) {
890
1010
  ...(staged.value.tension_error ? { tension_error: staged.value.tension_error } : {}),
891
1011
  });
892
1012
  }
893
- const existing = await readFile(resolved.value.absPath);
1013
+ const existing = await readCurrent();
894
1014
  let oldFrontmatter = null;
895
1015
  let oldRaw = null;
896
1016
  let oldContent = "";
@@ -902,7 +1022,7 @@ export async function vaultWrite(vaultRoot, args, access) {
902
1022
  // already holds, the exact field-loss class #113 is about. Refuse loudly
903
1023
  // instead: the caller must repair or remove the file before a write can
904
1024
  // proceed.
905
- return err(new Error(`vault_write: ${path.value} exists but its frontmatter could not be ` +
1025
+ return err(new Error(`${tool}: ${path.value} exists but its frontmatter could not be ` +
906
1026
  `parsed (${parsed.error.message}); refusing to overwrite it. ` +
907
1027
  `Fix or remove the file first.`));
908
1028
  }
@@ -914,7 +1034,7 @@ export async function vaultWrite(vaultRoot, args, access) {
914
1034
  const hookOperation = isUpdate ? "update" : "create";
915
1035
  if (isUpdate && oldFrontmatter) {
916
1036
  const guard = checkTierGuard({
917
- tool: "vault_write",
1037
+ tool,
918
1038
  path: path.value,
919
1039
  tier: oldFrontmatter.tier,
920
1040
  oldBody: oldContent,
@@ -1040,7 +1160,7 @@ export async function vaultWrite(vaultRoot, args, access) {
1040
1160
  oldFrontmatter &&
1041
1161
  (oldFrontmatter.tier === "source" || oldFrontmatter.tier === "manual")) {
1042
1162
  if (rawFrontmatter.tier !== oldFrontmatter.tier) {
1043
- return err(new Error(`vault_write: ${path.value} is tier '${oldFrontmatter.tier}' — changing ` +
1163
+ return err(new Error(`${tool}: ${path.value} is tier '${oldFrontmatter.tier}' — changing ` +
1044
1164
  `its tier requires vault_set_tier (a reason is required` +
1045
1165
  `${oldFrontmatter.tier === "manual" ? ", and a human:* identity" : ""}).`));
1046
1166
  }
@@ -1068,6 +1188,12 @@ export async function vaultWrite(vaultRoot, args, access) {
1068
1188
  operation: hookOperation,
1069
1189
  });
1070
1190
  Object.assign(rawFrontmatter, transformResult.merged);
1191
+ // Judged here — after the #113 merge (an omitted status is inherited) and
1192
+ // the transform hooks (which may set status) — so it sees the status that
1193
+ // will actually land.
1194
+ const canonicalGate = requireCanonicalAuthority(access, oldFrontmatter?.status ?? null, rawFrontmatter.status, tool);
1195
+ if (!canonicalGate.ok)
1196
+ return canonicalGate;
1071
1197
  // `updated` and `updated_by` are server-managed: performWrite re-stamps them
1072
1198
  // unconditionally after validation. Fill them in here too, so a caller who
1073
1199
  // (reasonably) omits them does not trip validateFrontmatter's required-field
@@ -1144,7 +1270,7 @@ export async function vaultWrite(vaultRoot, args, access) {
1144
1270
  const violation = foreignPositionViolation(oldFrontmatter.positions, frontmatter.positions, access.user);
1145
1271
  if (violation) {
1146
1272
  await recordProvenance(vaultRoot, {
1147
- tool: "vault_write",
1273
+ tool,
1148
1274
  file: resolved.value.relPath,
1149
1275
  agent: agent.value,
1150
1276
  principal: access.user,
@@ -1152,11 +1278,16 @@ export async function vaultWrite(vaultRoot, args, access) {
1152
1278
  action: "rejected_foreign_position",
1153
1279
  reason: violation,
1154
1280
  });
1155
- return err(new Error(`vault_write: ${violation} — another principal's position entries can ` +
1281
+ return err(new Error(`${tool}: ${violation} — another principal's position entries can ` +
1156
1282
  `only be superseded by their own new position (vault_assert) or ` +
1157
1283
  `edited by their holder`));
1158
1284
  }
1159
1285
  }
1286
+ // Compared on the raw merged fields: the validated Frontmatter drops
1287
+ // undeclared custom keys, and those are patchable too.
1288
+ if (patch && oldRaw !== null && body === oldContent && sameFields(oldRaw, rawFrontmatter)) {
1289
+ return err(patchChangesNothing(path.value));
1290
+ }
1160
1291
  const stamped = {
1161
1292
  ...frontmatter,
1162
1293
  created: isUpdate ? oldFrontmatter.created : frontmatter.created,
@@ -1171,13 +1302,15 @@ export async function vaultWrite(vaultRoot, args, access) {
1171
1302
  relPath: resolved.value.relPath,
1172
1303
  absPath: resolved.value.absPath,
1173
1304
  agent: agent.value,
1174
- tool: "vault_write",
1175
- action: isUpdate ? "update" : "create",
1305
+ tool,
1306
+ action: patch ? "patch" : isUpdate ? "update" : "create",
1176
1307
  fileText: serializeDocument(stamped, body, extensions, applyExtensionDefaults(rawFrontmatter, extensions)),
1177
1308
  newFrontmatter: stamped,
1178
1309
  oldFrontmatter,
1179
1310
  validation: mergedReport,
1180
- commitMessage: `vault_write: ${isUpdate ? "update" : "create"} ${path.value} ` + `by ${agent.value}`,
1311
+ commitMessage: patch
1312
+ ? `vault_patch: ${path.value} by ${agent.value} — ${patch.reason}`
1313
+ : `vault_write: ${isUpdate ? "update" : "create"} ${path.value} ` + `by ${agent.value}`,
1181
1314
  autoCommit: config.value.autoCommit,
1182
1315
  gitDir: config.value.gitDir,
1183
1316
  baseVersion: baseVersion.value,
@@ -1188,6 +1321,7 @@ export async function vaultWrite(vaultRoot, args, access) {
1188
1321
  visibility: config.value.visibility,
1189
1322
  leakGate: config.value.leakGate,
1190
1323
  hasAccessContext: access !== undefined,
1324
+ ...(patch ? { reason: patch.reason } : {}),
1191
1325
  });
1192
1326
  // #169: an in-place overwrite destroys the prior version's lineage, and
1193
1327
  // daftari HAS the preserve-not-overwrite primitive — steer toward it at
@@ -1201,21 +1335,204 @@ export async function vaultWrite(vaultRoot, args, access) {
1201
1335
  // would point at a write that never happened (same logic as supersede_hint).
1202
1336
  if (!written.ok || written.value.shadow)
1203
1337
  return written;
1338
+ // A patch warns only about what it added, for the reason vault_append does:
1339
+ // re-warning on every unrelated field change would drown the signal.
1204
1340
  const warnings = generativeDomainRefs(vaultRoot, {
1205
1341
  domain: stamped.domain,
1206
- sources: stamped.sources ?? [],
1207
- body,
1342
+ sources: patch && !patch.patchesSources ? [] : (stamped.sources ?? []),
1343
+ body: patch ? patch.bodyEdits.map((e) => e.new).join("\n") : body,
1208
1344
  relPath: resolved.value.relPath,
1209
1345
  }, access);
1210
- if (!isUpdate && warnings === null && pinMintOutcome === undefined)
1346
+ // A frontmatter-only patch replaces no fact, so there is no lineage to steer.
1347
+ const replacedContent = isUpdate && (!patch || patch.bodyEdits.length > 0);
1348
+ const amendsWarnings = unresolvedAmends(vaultRoot, patch && !patch.patchesAmends ? [] : (stamped.amends ?? []), resolved.value.relPath, access);
1349
+ if (!replacedContent &&
1350
+ warnings === null &&
1351
+ amendsWarnings === null &&
1352
+ pinMintOutcome === undefined) {
1211
1353
  return written;
1354
+ }
1212
1355
  return ok({
1213
1356
  ...written.value,
1214
- ...(isUpdate ? { supersede_hint: SUPERSEDE_HINT } : {}),
1357
+ ...(replacedContent ? { supersede_hint: SUPERSEDE_HINT } : {}),
1215
1358
  ...(warnings ? { domain_warnings: warnings } : {}),
1359
+ ...(amendsWarnings ? { amends_warnings: amendsWarnings } : {}),
1216
1360
  ...(pinMintOutcome !== undefined ? { pin_mint: pinMintOutcome } : {}),
1217
1361
  });
1218
1362
  }
1363
+ const MAX_BODY_EDITS = 50;
1364
+ // Fields a patch refuses, each with where the change belongs. Lifecycle state
1365
+ // and write protection stay with the tools that gate them, so a cheap field
1366
+ // edit cannot become a promote, an unsupersede, or a tier demotion by another
1367
+ // name. `collection` picks the RBAC scope every lifecycle gate keys on, which
1368
+ // makes changing it a relocation rather than a correction.
1369
+ const PATCH_RESERVED_FIELDS = new Map([
1370
+ ["status", "use vault_promote, vault_deprecate, vault_supersede, or vault_unsupersede"],
1371
+ ["superseded_by", "use vault_supersede, or vault_unsupersede to reverse one"],
1372
+ ["tier", "use vault_set_tier"],
1373
+ ["collection", "it is the document's access scope; use vault_write to relocate"],
1374
+ ["positions", "use vault_assert"],
1375
+ ["org_position", "use vault_assert or vault_consolidate"],
1376
+ ["contested", "use vault_assert or vault_consolidate"],
1377
+ ["created", "it is server-managed"],
1378
+ ["updated", "it is server-managed"],
1379
+ ["updated_by", "it is server-managed"],
1380
+ ]);
1381
+ function readPatchFields(args) {
1382
+ const v = args.frontmatter;
1383
+ if (v === undefined || v === null)
1384
+ return ok({});
1385
+ if (typeof v !== "object" || Array.isArray(v)) {
1386
+ return err(new Error("vault_patch: 'frontmatter' must be an object of fields to change"));
1387
+ }
1388
+ const fields = v;
1389
+ for (const key of Object.keys(fields)) {
1390
+ const owner = PATCH_RESERVED_FIELDS.get(key);
1391
+ if (owner !== undefined) {
1392
+ return err(new Error(`vault_patch: '${key}' cannot be patched — ${owner}`));
1393
+ }
1394
+ }
1395
+ return ok(fields);
1396
+ }
1397
+ function readBodyEdits(args) {
1398
+ const v = args.body_edits;
1399
+ if (v === undefined || v === null)
1400
+ return ok([]);
1401
+ if (!Array.isArray(v))
1402
+ return err(new Error("vault_patch: 'body_edits' must be an array"));
1403
+ if (v.length > MAX_BODY_EDITS) {
1404
+ return err(new Error(`vault_patch: 'body_edits' holds at most ${MAX_BODY_EDITS} edits`));
1405
+ }
1406
+ const edits = [];
1407
+ for (const [i, entry] of v.entries()) {
1408
+ const edit = entry;
1409
+ if (typeof edit?.old !== "string" || typeof edit.new !== "string") {
1410
+ return err(new Error(`vault_patch: body_edits[${i}] needs string 'old' and 'new'`));
1411
+ }
1412
+ if (edit.old.length === 0) {
1413
+ return err(new Error(`vault_patch: body_edits[${i}] has an empty 'old'`));
1414
+ }
1415
+ if (edit.old === edit.new) {
1416
+ return err(new Error(`vault_patch: body_edits[${i}] has identical 'old' and 'new'`));
1417
+ }
1418
+ edits.push({ old: edit.old, new: edit.new });
1419
+ }
1420
+ return ok(edits);
1421
+ }
1422
+ // Applies each edit to the running body, all or nothing. Errors name only the
1423
+ // index and match count, never body text.
1424
+ function applyBodyEdits(body, edits) {
1425
+ let out = body;
1426
+ for (const [i, edit] of edits.entries()) {
1427
+ const matches = out.split(edit.old).length - 1;
1428
+ if (matches !== 1) {
1429
+ return err(new Error(`vault_patch: body_edits[${i}] matched ${matches} times; 'old' must match ` +
1430
+ "exactly once. Re-read the document, or widen 'old' with surrounding text."));
1431
+ }
1432
+ const at = out.indexOf(edit.old);
1433
+ out = out.slice(0, at) + edit.new + out.slice(at + edit.old.length);
1434
+ }
1435
+ return ok(out);
1436
+ }
1437
+ // A patch is composed against content the caller read, so it needs read as
1438
+ // well as write. role.read and role.write are independent, and without this a
1439
+ // write-only role could use 'old' matching as a content oracle.
1440
+ function requirePatchAccess(access, collection) {
1441
+ const writable = requireWriteAccess(access, collection);
1442
+ if (!writable.ok)
1443
+ return writable;
1444
+ if (access && !canRead(access.role, collection)) {
1445
+ return err(new Error(`access denied: role '${access.roleName}' cannot read collection '${collection}'`));
1446
+ }
1447
+ return ok(undefined);
1448
+ }
1449
+ // Changes named frontmatter fields and exact-match body spans, leaving the rest
1450
+ // of the document as it is. Update-only: the target must already exist. The
1451
+ // caller sends the change, not the document; everything past the edit runs
1452
+ // through writeDocument.
1453
+ export async function vaultPatch(vaultRoot, args, access) {
1454
+ const ready = requireIndexReady();
1455
+ if (!ready.ok)
1456
+ return ready;
1457
+ const path = requireString(args, "path", "vault_patch");
1458
+ if (!path.ok)
1459
+ return path;
1460
+ const agent = requireString(args, "agent", "vault_patch");
1461
+ if (!agent.ok)
1462
+ return agent;
1463
+ const reason = requireString(args, "reason", "vault_patch");
1464
+ if (!reason.ok)
1465
+ return reason;
1466
+ const baseVersion = readBaseVersion(args, "vault_patch");
1467
+ if (!baseVersion.ok)
1468
+ return baseVersion;
1469
+ const runId = readRunId(args, "vault_patch");
1470
+ if (!runId.ok)
1471
+ return runId;
1472
+ const fields = readPatchFields(args);
1473
+ if (!fields.ok)
1474
+ return fields;
1475
+ const edits = readBodyEdits(args);
1476
+ if (!edits.ok)
1477
+ return edits;
1478
+ if (Object.keys(fields.value).length === 0 && edits.value.length === 0) {
1479
+ return err(new Error("vault_patch requires 'frontmatter' fields or 'body_edits' to change"));
1480
+ }
1481
+ // Path math only, so denial reveals nothing about the target. The declared
1482
+ // collection is gated after load, the convention every read filter honors.
1483
+ const physicalGate = requirePatchAccess(access, targetCollection(vaultRoot, path.value));
1484
+ if (!physicalGate.ok)
1485
+ return physicalGate;
1486
+ // The edits are anchored on content, not offsets: after a reload each one
1487
+ // still matches exactly once or fails loudly, so the one transparent retry
1488
+ // of an omitted base_version recomputes safely.
1489
+ const attemptPatch = async () => {
1490
+ const target = await loadTargetDocument(vaultRoot, path.value, "vault_patch");
1491
+ if (!target.ok)
1492
+ return target;
1493
+ const { parsed, relPath, contentHash, config, text } = target.value;
1494
+ const declaredGate = requirePatchAccess(access, collectionOf(relPath, parsed.frontmatter));
1495
+ if (!declaredGate.ok)
1496
+ return declaredGate;
1497
+ // Checked before the edits: against moved content an 'old' may simply fail
1498
+ // to match, which would hide the real cause. Shadow mode has no mutation
1499
+ // to guard, same as performWrite.
1500
+ if (baseVersion.value !== undefined &&
1501
+ baseVersion.value !== contentHash &&
1502
+ !config.shadowMode) {
1503
+ return rejectStale({
1504
+ vaultRoot,
1505
+ relPath,
1506
+ tool: "vault_patch",
1507
+ agent: agent.value,
1508
+ baseVersion: baseVersion.value,
1509
+ currentHash: contentHash,
1510
+ ...(access ? { principal: access.user } : {}),
1511
+ ...(runId.value !== undefined ? { runId: runId.value } : {}),
1512
+ });
1513
+ }
1514
+ const body = applyBodyEdits(parsed.content, edits.value);
1515
+ if (!body.ok)
1516
+ return body;
1517
+ return writeDocument(vaultRoot, {
1518
+ path: path.value,
1519
+ agent: agent.value,
1520
+ reason: reason.value,
1521
+ // Copied per attempt: the core merges into this object in place.
1522
+ frontmatter: { ...fields.value },
1523
+ body: body.value,
1524
+ base_version: baseVersion.value ?? contentHash,
1525
+ ...(runId.value !== undefined ? { run_id: runId.value } : {}),
1526
+ }, access, {
1527
+ loadedText: text,
1528
+ reason: reason.value,
1529
+ bodyEdits: edits.value,
1530
+ patchesSources: "sources" in fields.value,
1531
+ patchesAmends: "amends" in fields.value,
1532
+ });
1533
+ };
1534
+ return retryOnStaleIfDefaulted(baseVersion.value, attemptPatch);
1535
+ }
1219
1536
  // ---------------------------------------------------------------------------
1220
1537
  // vault_append
1221
1538
  // ---------------------------------------------------------------------------
@@ -1414,8 +1731,8 @@ export async function vaultPromote(vaultRoot, args, access) {
1414
1731
  // or superseded). Best-effort: returns null when docs can't be loaded so the
1415
1732
  // caller can omit `dependents` without failing the write.
1416
1733
  //
1417
- // When `access` is provided, filters the downstream set to docs the role can
1418
- // read and coarsens the hidden remainder via bucketHiddenDownstream. Without
1734
+ // When `access` is provided, the blast is computed over the docs the role can
1735
+ // read (computeBlastForReader) and the hidden remainder is coarsened. Without
1419
1736
  // access, all downstream docs are returned and hidden_downstream is "none".
1420
1737
  async function buildDependentsAdvisory(vaultRoot, retractedPath, access) {
1421
1738
  const docsResult = await loadDocuments(vaultRoot);
@@ -1424,37 +1741,46 @@ async function buildDependentsAdvisory(vaultRoot, retractedPath, access) {
1424
1741
  const docs = docsResult.value;
1425
1742
  const reverseSource = buildReverseSourceMap(docs);
1426
1743
  const reverseLink = buildReverseLinkMap(docs);
1427
- const blast = computeBlast({ seeds: [retractedPath], reverseSource, reverseLink });
1744
+ // #217 / #84q6: the shared reader filter — distances over the readable
1745
+ // subgraph, hidden remainder coarsened. No access ⇒ nothing hidden.
1746
+ const db = access ? openIndexForAccessOrNull(vaultRoot) : null;
1747
+ try {
1748
+ const blast = computeBlastForReader({ seeds: [retractedPath], reverseSource, reverseLink }, access ? (p) => sourceReadable(db, access, p) : undefined);
1749
+ return {
1750
+ downstream: blast.downstream,
1751
+ primary_blast: blast.primary_blast,
1752
+ advisory_blast: blast.advisory_blast,
1753
+ hidden_downstream: blast.hidden_downstream,
1754
+ };
1755
+ }
1756
+ finally {
1757
+ db?.close();
1758
+ }
1759
+ }
1760
+ // ---------------------------------------------------------------------------
1761
+ // superseded_by loop guard (#639)
1762
+ // ---------------------------------------------------------------------------
1763
+ // Refuses a write that would close a superseded_by loop, which leaves a topic
1764
+ // with no current entry. A precondition of the edge, like "the successor must
1765
+ // exist", not a curation verdict. Walks only what the caller can read: this
1766
+ // answers any writer, per pair of documents, so a refusal driven by a hidden
1767
+ // hop would be an exact oracle for edges behind the ACL (2026-07-14 spec). A
1768
+ // loop through a hidden hop is left to a vault_lint run that can see the hop.
1769
+ async function refuseSupersedeLoop(vaultRoot, edits, message, access) {
1770
+ const docs = await loadDocuments(vaultRoot);
1771
+ if (!docs.ok)
1772
+ return docs;
1773
+ let visible = docs.value;
1428
1774
  if (access) {
1429
1775
  const db = openIndexForAccessOrNull(vaultRoot);
1430
1776
  try {
1431
- const kept = blast.downstream.filter((e) => sourceReadable(db, access, e.path));
1432
- const hidden = blast.downstream.length - kept.length;
1433
- let primary_blast = 0;
1434
- let advisory_blast = 0;
1435
- for (const e of kept) {
1436
- if (e.dependency_type === "source")
1437
- primary_blast += 1;
1438
- else
1439
- advisory_blast += 1;
1440
- }
1441
- return {
1442
- downstream: kept,
1443
- primary_blast,
1444
- advisory_blast,
1445
- hidden_downstream: bucketHiddenDownstream(hidden),
1446
- };
1777
+ visible = visible.filter((d) => sourceReadable(db, access, d.path));
1447
1778
  }
1448
1779
  finally {
1449
1780
  db?.close();
1450
1781
  }
1451
1782
  }
1452
- return {
1453
- downstream: blast.downstream,
1454
- primary_blast: blast.primary_blast,
1455
- advisory_blast: blast.advisory_blast,
1456
- hidden_downstream: "none",
1457
- };
1783
+ return closesSupersedeLoop(visible, edits) ? err(new Error(message)) : ok(undefined);
1458
1784
  }
1459
1785
  // ---------------------------------------------------------------------------
1460
1786
  // vault_deprecate
@@ -1517,6 +1843,13 @@ export async function vaultDeprecate(vaultRoot, args, access) {
1517
1843
  return closing;
1518
1844
  validUntil = closing.value;
1519
1845
  }
1846
+ if (supersededBy !== null) {
1847
+ const successor = resolveVaultPath(vaultRoot, supersededBy);
1848
+ const loop = await refuseSupersedeLoop(vaultRoot, [[target.value.relPath, successor.ok ? successor.value.relPath : supersededBy]], `vault_deprecate: refused: ${path.value} is already on the superseded_by chain of ` +
1849
+ `${supersededBy}, so this would close a loop. Nothing was written.`, access);
1850
+ if (!loop.ok)
1851
+ return loop;
1852
+ }
1520
1853
  return performFrontmatterWrite({
1521
1854
  vaultRoot,
1522
1855
  target: target.value,
@@ -1791,6 +2124,11 @@ export async function vaultSupersede(vaultRoot, args, access) {
1791
2124
  const config = loadConfig(vaultRoot);
1792
2125
  if (!config.ok)
1793
2126
  return config;
2127
+ // The old document's write refuses in performWrite; the successor is only
2128
+ // pointed at, and superseded_by must not name a non-document.
2129
+ const successorIgnored = refuseIgnoredPath(resolvedNew.value.relPath, config.value.ignore);
2130
+ if (!successorIgnored.ok)
2131
+ return successorIgnored;
1794
2132
  const oldFrontmatter = parsed.value.frontmatter;
1795
2133
  const rbac = requireWriteAccess(access, collectionOf(oldPath.value, oldFrontmatter));
1796
2134
  if (!rbac.ok)
@@ -1803,6 +2141,10 @@ export async function vaultSupersede(vaultRoot, args, access) {
1803
2141
  return closing;
1804
2142
  validUntil = closing.value;
1805
2143
  }
2144
+ const loop = await refuseSupersedeLoop(vaultRoot, [[resolvedOld.value.relPath, resolvedNew.value.relPath]], `vault_supersede: refused: ${oldPath.value} is already on the superseded_by chain of ` +
2145
+ `${newPath.value}, so this would close a loop. Nothing was written.`, access);
2146
+ if (!loop.ok)
2147
+ return loop;
1806
2148
  const written = await performFrontmatterWrite({
1807
2149
  vaultRoot,
1808
2150
  // Canonical relPath keys the lock/provenance/commit (#127/#128).
@@ -1834,10 +2176,127 @@ export async function vaultSupersede(vaultRoot, args, access) {
1834
2176
  return written;
1835
2177
  // Build the downstream dependents advisory (best-effort, never fails the write).
1836
2178
  const dependents = await buildDependentsAdvisory(vaultRoot, oldPath.value, access);
1837
- if (boundary.value === null) {
1838
- return ok({ ...written.value, dependents });
2179
+ const successorWarning = retiredSuccessorWarning(vaultRoot, resolvedNew.value.relPath, successor.value, access);
2180
+ return ok({
2181
+ ...written.value,
2182
+ ...(boundary.value !== null ? { hint: boundaryHint(newPath.value, boundary.value) } : {}),
2183
+ dependents,
2184
+ ...(successorWarning !== null ? { successor_warning: successorWarning } : {}),
2185
+ });
2186
+ }
2187
+ // Advisory for a successor that is itself retired. Silent when the caller
2188
+ // cannot read the successor: its status is that document's content.
2189
+ function retiredSuccessorWarning(vaultRoot, successorPath, successorText, access) {
2190
+ const parsed = parseDocument(successorText);
2191
+ if (!parsed.ok)
2192
+ return null;
2193
+ const { status } = parsed.value.frontmatter;
2194
+ if (status !== "superseded" && status !== "deprecated")
2195
+ return null;
2196
+ if (access) {
2197
+ const db = openIndexForAccessOrNull(vaultRoot);
2198
+ try {
2199
+ if (!sourceReadable(db, access, successorPath))
2200
+ return null;
2201
+ }
2202
+ finally {
2203
+ db?.close();
2204
+ }
2205
+ }
2206
+ return (`Successor ${successorPath} is itself ${status}, so the chain does not end there. ` +
2207
+ `Point at the current entry, or check vault_lint's supersedeChains.`);
2208
+ }
2209
+ // ---------------------------------------------------------------------------
2210
+ // vault_unsupersede (#640)
2211
+ // ---------------------------------------------------------------------------
2212
+ // Reverses a supersession: clears superseded_by and returns the document to
2213
+ // draft, recorded as its own provenance action with a mandatory reason. Always
2214
+ // draft because the prior status is not stored on the document and the
2215
+ // provenance log is advisory; returning to canonical is a separate vault_promote
2216
+ // with that tool's preconditions. It rewires which document readers treat as
2217
+ // current, so it carries the promote grant, and propose-only roles go through
2218
+ // a staged `unsupersede`. The successor is never touched.
2219
+ export async function vaultUnsupersede(vaultRoot, args, access) {
2220
+ const ready = requireIndexReady();
2221
+ if (!ready.ok)
2222
+ return ready;
2223
+ const proposeGate = denyIfProposeOnly(access, "vault_unsupersede");
2224
+ if (!proposeGate.ok)
2225
+ return proposeGate;
2226
+ const path = requireString(args, "path", "vault_unsupersede");
2227
+ if (!path.ok)
2228
+ return path;
2229
+ const agent = requireString(args, "agent", "vault_unsupersede");
2230
+ if (!agent.ok)
2231
+ return agent;
2232
+ const reason = requireString(args, "reason", "vault_unsupersede");
2233
+ if (!reason.ok)
2234
+ return reason;
2235
+ const runId = readRunId(args, "vault_unsupersede");
2236
+ if (!runId.ok)
2237
+ return runId;
2238
+ const baseVersion = readBaseVersion(args, "vault_unsupersede");
2239
+ if (!baseVersion.ok)
2240
+ return baseVersion;
2241
+ if (access && !canPromote(access.role)) {
2242
+ return err(new Error(`access denied: role '${access.roleName}' cannot reverse a supersede`));
1839
2243
  }
1840
- return ok({ ...written.value, hint: boundaryHint(newPath.value, boundary.value), dependents });
2244
+ // Read-modify-write over the loaded frontmatter — see
2245
+ // retryOnStaleIfDefaulted above.
2246
+ const attemptUnsupersede = async () => {
2247
+ const target = await loadTargetDocument(vaultRoot, path.value, "vault_unsupersede");
2248
+ if (!target.ok)
2249
+ return target;
2250
+ const oldFrontmatter = target.value.parsed.frontmatter;
2251
+ const rbac = requireWriteAccess(access, collectionOf(path.value, oldFrontmatter));
2252
+ if (!rbac.ok)
2253
+ return rbac;
2254
+ if (oldFrontmatter.status !== "superseded") {
2255
+ return err(new Error(`vault_unsupersede: only superseded documents can be reversed ` +
2256
+ `(${path.value} is '${oldFrontmatter.status}')`));
2257
+ }
2258
+ const written = await performFrontmatterWrite({
2259
+ vaultRoot,
2260
+ target: target.value,
2261
+ agent: agent.value,
2262
+ tool: "vault_unsupersede",
2263
+ action: "unsupersede",
2264
+ newFrontmatter: {
2265
+ ...oldFrontmatter,
2266
+ status: "draft",
2267
+ superseded_by: null,
2268
+ updated: todayISO(),
2269
+ updated_by: agent.value,
2270
+ },
2271
+ commitMessage: `vault_unsupersede: ${path.value} superseded→draft by ${agent.value} — ` +
2272
+ `${reason.value}` +
2273
+ (oldFrontmatter.superseded_by
2274
+ ? ` (was superseded by ${oldFrontmatter.superseded_by})`
2275
+ : ""),
2276
+ baseVersion: baseVersion.value ?? target.value.contentHash,
2277
+ access,
2278
+ reason: reason.value,
2279
+ ...(runId.value !== undefined ? { runId: runId.value } : {}),
2280
+ });
2281
+ if (!written.ok)
2282
+ return written;
2283
+ // A reversed supersession does not prove the validity end wrong, and an
2284
+ // authored window is never rewritten by a convenience path.
2285
+ const validUntil = oldFrontmatter.valid_until ?? null;
2286
+ if (validUntil === null)
2287
+ return written;
2288
+ return ok({
2289
+ ...written.value,
2290
+ hint: `valid_until ${validUntil} was left in place. If closing the window was part of ` +
2291
+ "the mistake, clear it with vault_patch (frontmatter: { valid_until: null }).",
2292
+ });
2293
+ };
2294
+ const written = await retryOnStaleIfDefaulted(baseVersion.value, attemptUnsupersede);
2295
+ if (!written.ok)
2296
+ return written;
2297
+ // Build the downstream dependents advisory (best-effort, never fails the write).
2298
+ const dependents = await buildDependentsAdvisory(vaultRoot, written.value.path, access);
2299
+ return ok({ ...written.value, dependents });
1841
2300
  }
1842
2301
  // Combines two source documents into a target and supersedes both sources to
1843
2302
  // point at it. Mechanical, not generative: the merged body is supplied by the
@@ -1926,6 +2385,12 @@ export async function vaultMerge(vaultRoot, args, access) {
1926
2385
  if (!config.ok)
1927
2386
  return config;
1928
2387
  const extensions = config.value.schemaExtensions;
2388
+ // Merge does not go through performWrite, so its gate is applied here.
2389
+ for (const resolved of [resolvedA, resolvedB, resolvedTarget]) {
2390
+ const ignored = refuseIgnoredPath(resolved.value.relPath, config.value.ignore);
2391
+ if (!ignored.ok)
2392
+ return ignored;
2393
+ }
1929
2394
  // RBAC: a merge writes/mutates all three docs, so the caller needs write on
1930
2395
  // each one's collection.
1931
2396
  if (access) {
@@ -2008,6 +2473,13 @@ export async function vaultMerge(vaultRoot, args, access) {
2008
2473
  updated: todayISO(),
2009
2474
  updated_by: agent.value,
2010
2475
  };
2476
+ // A canonical result needs the promote grant when the target was not already
2477
+ // canonical — whether the status comes from an override or is inherited from
2478
+ // path_a into a new target. Merging into an already-canonical target is
2479
+ // allowed, matching vault_write: a writer may already edit canonical content.
2480
+ const canonicalGate = requireCanonicalAuthority(access, targetOldFrontmatter?.status ?? null, targetRaw.status, "vault_merge");
2481
+ if (!canonicalGate.ok)
2482
+ return canonicalGate;
2011
2483
  // Reader parentage fusion (6mf.1). targetRaw inherits path_a's raw, so it
2012
2484
  // currently carries ONLY path_a's `readers` set and path_a's scalar reader_*
2013
2485
  // fields — a false single-parent claim that silently drops path_b's reader.
@@ -2163,6 +2635,16 @@ export async function vaultMerge(vaultRoot, args, access) {
2163
2635
  action: "supersede",
2164
2636
  });
2165
2637
  }
2638
+ // The target inherits path_a's superseded_by, which can point back at a
2639
+ // source that is about to point at the target.
2640
+ const loop = await refuseSupersedeLoop(vaultRoot, writes.map((w) => [
2641
+ w.relPath,
2642
+ w.action === "supersede" ? resolvedTarget.value.relPath : w.newFrontmatter.superseded_by,
2643
+ ]), `vault_merge: refused: ${targetPath.value} would land on a superseded_by loop through ` +
2644
+ `its sources. Clear its inherited superseded_by with a frontmatter override. ` +
2645
+ `Nothing was written.`, access);
2646
+ if (!loop.ok)
2647
+ return loop;
2166
2648
  // Shadow mode (spec §11.5): the full write set is assembled and validated —
2167
2649
  // the do() that WOULD have executed. Log one merge record whose blast seeds
2168
2650
  // every touched path, write nothing.
@@ -2343,8 +2825,8 @@ const agentProperty = {
2343
2825
  const shadowNote = " If the vault runs shadow_mode, the write is computed and logged to the " +
2344
2826
  "shadow store but NOT applied; the result carries shadow: true.";
2345
2827
  // Appended to the description of every read-modify-write tool whose
2346
- // base_version defaults internally (append, promote, deprecate,
2347
- // set_confidence, set_tier): unlike vault_write, an omitted base_version here
2828
+ // base_version defaults internally (patch, append, promote, deprecate,
2829
+ // set_confidence, set_tier, unsupersede): unlike vault_write, an omitted base_version here
2348
2830
  // is NOT last-write-wins — it defaults to the version this call itself read,
2349
2831
  // and a race is retried once before failing loudly.
2350
2832
  const staleRetryNote = " If base_version is omitted, a concurrent change is retried once " +
@@ -2442,6 +2924,12 @@ const frontmatterProperty = {
2442
2924
  description: "Number of days after which this document is considered stale and " +
2443
2925
  "should be reviewed. null = no TTL.",
2444
2926
  },
2927
+ series: {
2928
+ type: ["string", "null"],
2929
+ description: "Name of the run of dated snapshots this document belongs to (e.g. " +
2930
+ "weekly reviews). Staleness is judged on the newest member by `created`: " +
2931
+ "the TTL fires when no new snapshot has been written, not on each old one.",
2932
+ },
2445
2933
  valid_from: {
2446
2934
  type: ["string", "null"],
2447
2935
  description: "First date (YYYY-MM-DD) on which this document's claim was true IN " +
@@ -2475,6 +2963,15 @@ const frontmatterProperty = {
2475
2963
  description: "Open questions this document raises (mirrors ## Questions Raised). " +
2476
2964
  "Surfaced by vault_lint's `unanswered-questions` check.",
2477
2965
  },
2966
+ amends: {
2967
+ type: "array",
2968
+ items: { type: "string" },
2969
+ description: "Vault-relative paths of earlier documents this one amends or fulfils " +
2970
+ "without replacing them: use this instead of vault_supersede when the " +
2971
+ "earlier claim stays true as written. The earlier files are not touched; " +
2972
+ "search hits and vault_read on them show this document as `amendedBy`. " +
2973
+ "Set to null to clear.",
2974
+ },
2478
2975
  describes: {
2479
2976
  type: "array",
2480
2977
  items: { type: "string" },
@@ -2532,6 +3029,13 @@ const domainWarningsProperty = {
2532
3029
  "references generative-domain documents the caller can read. Absent when " +
2533
3030
  "there is nothing to warn about. The write has already landed.",
2534
3031
  };
3032
+ const amendsWarningsProperty = {
3033
+ type: "array",
3034
+ items: { type: "string" },
3035
+ description: "Advisory: `amends` entries that resolve to no document the caller can " +
3036
+ "read, or that name this document, so they will surface on nothing. Absent " +
3037
+ "when every target resolves. The write has already landed.",
3038
+ };
2535
3039
  const pinMintProperty = {
2536
3040
  type: "object",
2537
3041
  description: "JIT anchor-pin minting outcome (U2). Present only when at least one " +
@@ -2570,6 +3074,35 @@ const pinMintProperty = {
2570
3074
  },
2571
3075
  required: ["minted", "unresolved"],
2572
3076
  };
3077
+ // The staged-proposal fields of a write a propose-only role is coerced into.
3078
+ const stagedResultProperties = {
3079
+ staged_id: {
3080
+ type: "string",
3081
+ description: "Staged-action id of the recorded proposal. Present only when " + "action is 'staged'.",
3082
+ },
3083
+ expires_at: {
3084
+ type: "string",
3085
+ description: "ISO timestamp after which the staged proposal expires unratified. " +
3086
+ "Present only when action is 'staged'.",
3087
+ },
3088
+ conflicts_with: {
3089
+ type: "array",
3090
+ items: { type: "string" },
3091
+ description: "Ids of other pending proposals contesting the same target. " +
3092
+ "Present only when action is 'staged'; empty when uncontested.",
3093
+ },
3094
+ tension_id: {
3095
+ type: ["string", "null"],
3096
+ description: "Id of the inter-proposal tension logged for the conflicting " +
3097
+ "proposals, or null when none was needed. Present only when " +
3098
+ "action is 'staged'.",
3099
+ },
3100
+ tension_error: {
3101
+ type: "string",
3102
+ description: "Why the conflict tension could not be written. The proposal is " +
3103
+ "still staged and conflicts_with still names the contenders.",
3104
+ },
3105
+ };
2573
3106
  // The shared WriteResult shape. `actions` and `statuses` are the closed
2574
3107
  // vocabularies the specific tool can emit; `properties` adds the tool's own
2575
3108
  // optional fields.
@@ -2682,36 +3215,89 @@ export const writeTools = [
2682
3215
  "and its lineage instead. The write has already landed.",
2683
3216
  },
2684
3217
  domain_warnings: domainWarningsProperty,
3218
+ amends_warnings: amendsWarningsProperty,
2685
3219
  pin_mint: pinMintProperty,
2686
- staged_id: {
3220
+ ...stagedResultProperties,
3221
+ },
3222
+ }),
3223
+ handler: (vaultRoot, args, access) => vaultWrite(vaultRoot, args, access),
3224
+ },
3225
+ {
3226
+ name: "vault_patch",
3227
+ title: "Patch fields or text in a document",
3228
+ annotations: { destructiveHint: true },
3229
+ description: "Change named frontmatter fields and exact-match body spans in an existing " +
3230
+ "document without resending it. Same validation, hooks, tier guards, " +
3231
+ "provenance log, and auto-commit as vault_write; the server stamps " +
3232
+ "'updated' and 'updated_by'. Supply 'frontmatter', 'body_edits', or both. " +
3233
+ "A field set to null is deleted; 'readers' and 'reader_lineage' union with " +
3234
+ "the existing values as they do in vault_write. Lifecycle and protected " +
3235
+ "fields (status, superseded_by, tier, collection, positions, org_position, " +
3236
+ "contested, created, updated, updated_by) are refused with a pointer to " +
3237
+ "the tool that owns them. Requires read as well as write access. If the " +
3238
+ "caller's role is propose-only, nothing is written: the patch lands as a " +
3239
+ "staged 'write' proposal awaiting vault_ratify." +
3240
+ staleRetryNote +
3241
+ shadowNote,
3242
+ inputSchema: {
3243
+ type: "object",
3244
+ properties: {
3245
+ path: {
2687
3246
  type: "string",
2688
- description: "Staged-action id of the recorded proposal. Present only when " + "action is 'staged'.",
3247
+ description: "Vault-relative path of the existing document to patch",
2689
3248
  },
2690
- expires_at: {
2691
- type: "string",
2692
- description: "ISO timestamp after which the staged proposal expires unratified. " +
2693
- "Present only when action is 'staged'.",
3249
+ frontmatter: {
3250
+ type: "object",
3251
+ description: "Fields to change, each replacing the whole field value; null deletes " +
3252
+ "the field. Fields not named are left as they are.",
3253
+ additionalProperties: true,
2694
3254
  },
2695
- conflicts_with: {
3255
+ body_edits: {
2696
3256
  type: "array",
2697
- items: { type: "string" },
2698
- description: "Ids of other pending proposals contesting the same target. " +
2699
- "Present only when action is 'staged'; empty when uncontested.",
3257
+ maxItems: MAX_BODY_EDITS,
3258
+ description: "Exact-text replacements, applied in order to the running body, all " +
3259
+ "or nothing. Each 'old' must match exactly once, so include enough " +
3260
+ "surrounding text to be unique.",
3261
+ items: {
3262
+ type: "object",
3263
+ properties: {
3264
+ old: { type: "string", description: "Exact text to replace; must match once" },
3265
+ new: { type: "string", description: "Replacement text; empty deletes the span" },
3266
+ },
3267
+ required: ["old", "new"],
3268
+ additionalProperties: false,
3269
+ },
2700
3270
  },
2701
- tension_id: {
2702
- type: ["string", "null"],
2703
- description: "Id of the inter-proposal tension logged for the conflicting " +
2704
- "proposals, or null when none was needed. Present only when " +
2705
- "action is 'staged'.",
3271
+ reason: {
3272
+ type: "string",
3273
+ description: "Why this change is being made (recorded in the commit and provenance)",
2706
3274
  },
2707
- tension_error: {
3275
+ agent: agentProperty,
3276
+ base_version: baseVersionProperty,
3277
+ run_id: runIdProperty,
3278
+ },
3279
+ required: ["path", "reason", "agent"],
3280
+ additionalProperties: false,
3281
+ },
3282
+ outputSchema: writeResultSchema({
3283
+ description: "The applied patch, or — for a propose-only role — the staged proposal " +
3284
+ "that was recorded instead ('staged', nothing written).",
3285
+ actions: ["patch", "staged"],
3286
+ // "pending" is the staged-proposal status, as on vault_write.
3287
+ statuses: [...STATUSES, "pending"],
3288
+ properties: {
3289
+ supersede_hint: {
2708
3290
  type: "string",
2709
- description: "Why the conflict tension could not be written. The proposal is " +
2710
- "still staged and conflicts_with still names the contenders.",
3291
+ description: "#169 advisory nudge, present only when this patch changed the body: " +
3292
+ "vault_supersede preserves the prior version and its lineage " +
3293
+ "instead. The write has already landed.",
2711
3294
  },
3295
+ domain_warnings: domainWarningsProperty,
3296
+ pin_mint: pinMintProperty,
3297
+ ...stagedResultProperties,
2712
3298
  },
2713
3299
  }),
2714
- handler: (vaultRoot, args, access) => vaultWrite(vaultRoot, args, access),
3300
+ handler: (vaultRoot, args, access) => vaultPatch(vaultRoot, args, access),
2715
3301
  },
2716
3302
  {
2717
3303
  name: "vault_append",
@@ -2778,7 +3364,26 @@ export const writeTools = [
2778
3364
  actions: ["promote"],
2779
3365
  statuses: ["canonical"],
2780
3366
  }),
2781
- handler: (vaultRoot, args, access) => vaultPromote(vaultRoot, args, access),
3367
+ // The review-journal decision is recorded here, at the tool entry point,
3368
+ // not inside vaultPromote: vault_ratify dispatches vaultPromote directly
3369
+ // and records its own staged decision, so a ratified promote counts once.
3370
+ handler: async (vaultRoot, args, access) => {
3371
+ const result = await vaultPromote(vaultRoot, args, access);
3372
+ if (result.ok) {
3373
+ appendReviewEvents(vaultRoot, [
3374
+ {
3375
+ ev: "decision",
3376
+ surface: "promote",
3377
+ item: docReviewItem(result.value.path),
3378
+ action: "promote",
3379
+ decided_by_kind: principalKindForVault(vaultRoot, access?.user),
3380
+ changed_anything: result.value.shadow !== true,
3381
+ at: new Date().toISOString(),
3382
+ },
3383
+ ]);
3384
+ }
3385
+ return result;
3386
+ },
2782
3387
  },
2783
3388
  {
2784
3389
  name: "vault_deprecate",
@@ -2906,7 +3511,9 @@ export const writeTools = [
2906
3511
  title: "Supersede a document",
2907
3512
  annotations: { destructiveHint: true },
2908
3513
  description: "Mark a document superseded by a named successor. Sets status=superseded " +
2909
- "and superseded_by; the successor must already exist. Distinct from " +
3514
+ "and superseded_by; the successor must already exist. Refuses a write " +
3515
+ "that would close a superseded_by loop; a successor that is itself " +
3516
+ "superseded or deprecated returns a successor_warning. Distinct from " +
2910
3517
  "vault_deprecate (which sets status=deprecated with an optional " +
2911
3518
  "successor). Auto-commits." +
2912
3519
  shadowNote,
@@ -2938,9 +3545,60 @@ export const writeTools = [
2938
3545
  "old_path). Status is always 'superseded' on success.",
2939
3546
  actions: ["supersede"],
2940
3547
  statuses: ["superseded"],
3548
+ properties: {
3549
+ successor_warning: {
3550
+ type: "string",
3551
+ description: "Advisory, present when the successor is itself superseded or " +
3552
+ "deprecated. The write landed.",
3553
+ },
3554
+ },
2941
3555
  }),
2942
3556
  handler: (vaultRoot, args, access) => vaultSupersede(vaultRoot, args, access),
2943
3557
  },
3558
+ {
3559
+ name: "vault_unsupersede",
3560
+ title: "Reverse a supersede",
3561
+ annotations: { destructiveHint: true },
3562
+ description: "Reverse a supersession: clear superseded_by and return a superseded " +
3563
+ "document to draft, logged as its own provenance action. A reason is " +
3564
+ "required. Always lands on draft; use vault_promote afterwards to return " +
3565
+ "it to canonical. Requires the promote grant; a propose-only role stages " +
3566
+ "an 'unsupersede' action for vault_ratify. The successor is not modified, " +
3567
+ "and an existing valid_until is left in place with a hint. Auto-commits." +
3568
+ staleRetryNote +
3569
+ shadowNote,
3570
+ inputSchema: {
3571
+ type: "object",
3572
+ properties: {
3573
+ path: {
3574
+ type: "string",
3575
+ description: "Vault-relative path of the superseded document",
3576
+ },
3577
+ reason: {
3578
+ type: "string",
3579
+ description: "Why the supersession is being reversed (recorded in commit and provenance)",
3580
+ },
3581
+ agent: agentProperty,
3582
+ run_id: runIdProperty,
3583
+ base_version: baseVersionProperty,
3584
+ },
3585
+ required: ["path", "reason", "agent"],
3586
+ additionalProperties: false,
3587
+ },
3588
+ outputSchema: writeResultSchema({
3589
+ description: "The applied reversal. Status is always 'draft' on success.",
3590
+ actions: ["unsupersede"],
3591
+ statuses: ["draft"],
3592
+ properties: {
3593
+ hint: {
3594
+ type: "string",
3595
+ description: "Present only when the document still declares a valid_until: how " +
3596
+ "to clear it if closing the window was part of the mistake.",
3597
+ },
3598
+ },
3599
+ }),
3600
+ handler: (vaultRoot, args, access) => vaultUnsupersede(vaultRoot, args, access),
3601
+ },
2944
3602
  {
2945
3603
  name: "vault_merge",
2946
3604
  title: "Merge two documents into one",