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