daftari 3.6.0 → 3.8.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 (289) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +4 -0
  3. package/dist/access/rbac.d.ts +1 -0
  4. package/dist/access/rbac.d.ts.map +1 -1
  5. package/dist/access/rbac.js +8 -0
  6. package/dist/access/rbac.js.map +1 -1
  7. package/dist/attest/bundle.d.ts +53 -0
  8. package/dist/attest/bundle.d.ts.map +1 -0
  9. package/dist/attest/bundle.js +141 -0
  10. package/dist/attest/bundle.js.map +1 -0
  11. package/dist/attest/index.d.ts +2 -0
  12. package/dist/attest/index.d.ts.map +1 -0
  13. package/dist/attest/index.js +139 -0
  14. package/dist/attest/index.js.map +1 -0
  15. package/dist/attest/sign.d.ts +16 -0
  16. package/dist/attest/sign.d.ts.map +1 -0
  17. package/dist/attest/sign.js +75 -0
  18. package/dist/attest/sign.js.map +1 -0
  19. package/dist/attest/verify.d.ts +21 -0
  20. package/dist/attest/verify.d.ts.map +1 -0
  21. package/dist/attest/verify.js +148 -0
  22. package/dist/attest/verify.js.map +1 -0
  23. package/dist/board/board.d.ts +37 -0
  24. package/dist/board/board.d.ts.map +1 -0
  25. package/dist/board/board.js +233 -0
  26. package/dist/board/board.js.map +1 -0
  27. package/dist/board/board.test.d.ts +2 -0
  28. package/dist/board/board.test.d.ts.map +1 -0
  29. package/dist/board/board.test.js +753 -0
  30. package/dist/board/board.test.js.map +1 -0
  31. package/dist/board/dormancy.test.d.ts +2 -0
  32. package/dist/board/dormancy.test.d.ts.map +1 -0
  33. package/dist/board/dormancy.test.js +79 -0
  34. package/dist/board/dormancy.test.js.map +1 -0
  35. package/dist/board/identity.d.ts +5 -0
  36. package/dist/board/identity.d.ts.map +1 -0
  37. package/dist/board/identity.js +146 -0
  38. package/dist/board/identity.js.map +1 -0
  39. package/dist/board/identity.test.d.ts +2 -0
  40. package/dist/board/identity.test.d.ts.map +1 -0
  41. package/dist/board/identity.test.js +291 -0
  42. package/dist/board/identity.test.js.map +1 -0
  43. package/dist/board/ledger.d.ts +41 -0
  44. package/dist/board/ledger.d.ts.map +1 -0
  45. package/dist/board/ledger.js +197 -0
  46. package/dist/board/ledger.js.map +1 -0
  47. package/dist/board/ledger.test.d.ts +2 -0
  48. package/dist/board/ledger.test.d.ts.map +1 -0
  49. package/dist/board/ledger.test.js +873 -0
  50. package/dist/board/ledger.test.js.map +1 -0
  51. package/dist/board/principals.d.ts +4 -0
  52. package/dist/board/principals.d.ts.map +1 -0
  53. package/dist/board/principals.js +37 -0
  54. package/dist/board/principals.js.map +1 -0
  55. package/dist/board/principals.test.d.ts +2 -0
  56. package/dist/board/principals.test.d.ts.map +1 -0
  57. package/dist/board/principals.test.js +296 -0
  58. package/dist/board/principals.test.js.map +1 -0
  59. package/dist/board/reconcile.d.ts +12 -0
  60. package/dist/board/reconcile.d.ts.map +1 -0
  61. package/dist/board/reconcile.js +293 -0
  62. package/dist/board/reconcile.js.map +1 -0
  63. package/dist/board/reconcile.test.d.ts +2 -0
  64. package/dist/board/reconcile.test.d.ts.map +1 -0
  65. package/dist/board/reconcile.test.js +788 -0
  66. package/dist/board/reconcile.test.js.map +1 -0
  67. package/dist/board/sources/index.d.ts +24 -0
  68. package/dist/board/sources/index.d.ts.map +1 -0
  69. package/dist/board/sources/index.js +64 -0
  70. package/dist/board/sources/index.js.map +1 -0
  71. package/dist/board/sources/lint.d.ts +3 -0
  72. package/dist/board/sources/lint.d.ts.map +1 -0
  73. package/dist/board/sources/lint.js +218 -0
  74. package/dist/board/sources/lint.js.map +1 -0
  75. package/dist/board/sources/lint.test.d.ts +2 -0
  76. package/dist/board/sources/lint.test.d.ts.map +1 -0
  77. package/dist/board/sources/lint.test.js +616 -0
  78. package/dist/board/sources/lint.test.js.map +1 -0
  79. package/dist/board/sources/staged.d.ts +3 -0
  80. package/dist/board/sources/staged.d.ts.map +1 -0
  81. package/dist/board/sources/staged.js +116 -0
  82. package/dist/board/sources/staged.js.map +1 -0
  83. package/dist/board/sources/staged.test.d.ts +2 -0
  84. package/dist/board/sources/staged.test.d.ts.map +1 -0
  85. package/dist/board/sources/staged.test.js +418 -0
  86. package/dist/board/sources/staged.test.js.map +1 -0
  87. package/dist/board/sources/staleness.d.ts +43 -0
  88. package/dist/board/sources/staleness.d.ts.map +1 -0
  89. package/dist/board/sources/staleness.js +346 -0
  90. package/dist/board/sources/staleness.js.map +1 -0
  91. package/dist/board/sources/staleness.test.d.ts +2 -0
  92. package/dist/board/sources/staleness.test.d.ts.map +1 -0
  93. package/dist/board/sources/staleness.test.js +923 -0
  94. package/dist/board/sources/staleness.test.js.map +1 -0
  95. package/dist/board/sources/tension.d.ts +3 -0
  96. package/dist/board/sources/tension.d.ts.map +1 -0
  97. package/dist/board/sources/tension.js +152 -0
  98. package/dist/board/sources/tension.js.map +1 -0
  99. package/dist/board/sources/tension.test.d.ts +2 -0
  100. package/dist/board/sources/tension.test.d.ts.map +1 -0
  101. package/dist/board/sources/tension.test.js +440 -0
  102. package/dist/board/sources/tension.test.js.map +1 -0
  103. package/dist/board/sources/tier2.d.ts +17 -0
  104. package/dist/board/sources/tier2.d.ts.map +1 -0
  105. package/dist/board/sources/tier2.js +233 -0
  106. package/dist/board/sources/tier2.js.map +1 -0
  107. package/dist/board/sources/tier2.test.d.ts +2 -0
  108. package/dist/board/sources/tier2.test.d.ts.map +1 -0
  109. package/dist/board/sources/tier2.test.js +480 -0
  110. package/dist/board/sources/tier2.test.js.map +1 -0
  111. package/dist/board/types.d.ts +161 -0
  112. package/dist/board/types.d.ts.map +1 -0
  113. package/dist/board/types.js +37 -0
  114. package/dist/board/types.js.map +1 -0
  115. package/dist/canon/index.d.ts +3 -1
  116. package/dist/canon/index.d.ts.map +1 -1
  117. package/dist/canon/index.js +35 -8
  118. package/dist/canon/index.js.map +1 -1
  119. package/dist/canon/types.d.ts +3 -0
  120. package/dist/canon/types.d.ts.map +1 -1
  121. package/dist/cli.d.ts.map +1 -1
  122. package/dist/cli.js +15 -0
  123. package/dist/cli.js.map +1 -1
  124. package/dist/consolidate/birth.d.ts +1 -1
  125. package/dist/consolidate/birth.d.ts.map +1 -1
  126. package/dist/consolidate/birth.js +22 -0
  127. package/dist/consolidate/birth.js.map +1 -1
  128. package/dist/consolidate/edge-write.d.ts +11 -0
  129. package/dist/consolidate/edge-write.d.ts.map +1 -1
  130. package/dist/consolidate/edge-write.js +41 -0
  131. package/dist/consolidate/edge-write.js.map +1 -1
  132. package/dist/consolidate/index.js +5 -2
  133. package/dist/consolidate/index.js.map +1 -1
  134. package/dist/consolidate/revision.d.ts +4 -2
  135. package/dist/consolidate/revision.d.ts.map +1 -1
  136. package/dist/consolidate/revision.js +23 -0
  137. package/dist/consolidate/revision.js.map +1 -1
  138. package/dist/curation/edge-staleness.d.ts +4 -2
  139. package/dist/curation/edge-staleness.d.ts.map +1 -1
  140. package/dist/curation/edge-staleness.js +36 -3
  141. package/dist/curation/edge-staleness.js.map +1 -1
  142. package/dist/curation/edges.d.ts +7 -0
  143. package/dist/curation/edges.d.ts.map +1 -1
  144. package/dist/curation/edges.js +13 -7
  145. package/dist/curation/edges.js.map +1 -1
  146. package/dist/curation/staged-actions.d.ts +2 -0
  147. package/dist/curation/staged-actions.d.ts.map +1 -1
  148. package/dist/curation/staged-actions.js +5 -0
  149. package/dist/curation/staged-actions.js.map +1 -1
  150. package/dist/curation/tension-access.d.ts +1 -0
  151. package/dist/curation/tension-access.d.ts.map +1 -1
  152. package/dist/curation/tension-access.js +18 -1
  153. package/dist/curation/tension-access.js.map +1 -1
  154. package/dist/curation/tension.d.ts +3 -0
  155. package/dist/curation/tension.d.ts.map +1 -1
  156. package/dist/curation/tension.js +36 -0
  157. package/dist/curation/tension.js.map +1 -1
  158. package/dist/curation/vault-docs.d.ts +1 -0
  159. package/dist/curation/vault-docs.d.ts.map +1 -1
  160. package/dist/curation/vault-docs.js +1 -0
  161. package/dist/curation/vault-docs.js.map +1 -1
  162. package/dist/distill/adapters/claude-session.d.ts +6 -0
  163. package/dist/distill/adapters/claude-session.d.ts.map +1 -0
  164. package/dist/distill/adapters/claude-session.js +71 -0
  165. package/dist/distill/adapters/claude-session.js.map +1 -0
  166. package/dist/distill/cli.d.ts.map +1 -1
  167. package/dist/distill/cli.js +119 -9
  168. package/dist/distill/cli.js.map +1 -1
  169. package/dist/distill/cost.d.ts +6 -0
  170. package/dist/distill/cost.d.ts.map +1 -1
  171. package/dist/distill/cost.js +2 -3
  172. package/dist/distill/cost.js.map +1 -1
  173. package/dist/distill/extract.d.ts +52 -0
  174. package/dist/distill/extract.d.ts.map +1 -1
  175. package/dist/distill/extract.js +24 -2
  176. package/dist/distill/extract.js.map +1 -1
  177. package/dist/distill/index.d.ts +1 -0
  178. package/dist/distill/index.d.ts.map +1 -1
  179. package/dist/distill/index.js +3 -0
  180. package/dist/distill/index.js.map +1 -1
  181. package/dist/distill/propose.d.ts +67 -6
  182. package/dist/distill/propose.d.ts.map +1 -1
  183. package/dist/distill/propose.js +142 -32
  184. package/dist/distill/propose.js.map +1 -1
  185. package/dist/distill/reader-fingerprint.d.ts +69 -0
  186. package/dist/distill/reader-fingerprint.d.ts.map +1 -0
  187. package/dist/distill/reader-fingerprint.js +145 -0
  188. package/dist/distill/reader-fingerprint.js.map +1 -0
  189. package/dist/distill/receipt-store.d.ts +5 -0
  190. package/dist/distill/receipt-store.d.ts.map +1 -0
  191. package/dist/distill/receipt-store.js +24 -0
  192. package/dist/distill/receipt-store.js.map +1 -0
  193. package/dist/eval/llm-openrouter.d.ts.map +1 -1
  194. package/dist/eval/llm-openrouter.js +4 -0
  195. package/dist/eval/llm-openrouter.js.map +1 -1
  196. package/dist/eval/llm.d.ts +22 -0
  197. package/dist/eval/llm.d.ts.map +1 -1
  198. package/dist/eval/llm.js +94 -24
  199. package/dist/eval/llm.js.map +1 -1
  200. package/dist/federation/classification.d.ts.map +1 -1
  201. package/dist/federation/classification.js +3 -0
  202. package/dist/federation/classification.js.map +1 -1
  203. package/dist/index.d.ts.map +1 -1
  204. package/dist/index.js +31 -0
  205. package/dist/index.js.map +1 -1
  206. package/dist/search/coverage.d.ts +5 -1
  207. package/dist/search/coverage.d.ts.map +1 -1
  208. package/dist/search/coverage.js +47 -15
  209. package/dist/search/coverage.js.map +1 -1
  210. package/dist/search/hybrid.d.ts +7 -1
  211. package/dist/search/hybrid.d.ts.map +1 -1
  212. package/dist/search/hybrid.js +31 -8
  213. package/dist/search/hybrid.js.map +1 -1
  214. package/dist/search/retrieval-metrics.d.ts +5 -0
  215. package/dist/search/retrieval-metrics.d.ts.map +1 -0
  216. package/dist/search/retrieval-metrics.js +60 -0
  217. package/dist/search/retrieval-metrics.js.map +1 -0
  218. package/dist/search/suppression.d.ts +9 -0
  219. package/dist/search/suppression.d.ts.map +1 -0
  220. package/dist/search/suppression.js +107 -0
  221. package/dist/search/suppression.js.map +1 -0
  222. package/dist/serve/index.d.ts.map +1 -1
  223. package/dist/serve/index.js +286 -4
  224. package/dist/serve/index.js.map +1 -1
  225. package/dist/server.d.ts.map +1 -1
  226. package/dist/server.js +4 -6
  227. package/dist/server.js.map +1 -1
  228. package/dist/storage/index-db.d.ts +1 -0
  229. package/dist/storage/index-db.d.ts.map +1 -1
  230. package/dist/storage/index-db.js.map +1 -1
  231. package/dist/tools/board.d.ts +32 -0
  232. package/dist/tools/board.d.ts.map +1 -0
  233. package/dist/tools/board.js +615 -0
  234. package/dist/tools/board.js.map +1 -0
  235. package/dist/tools/board.test.d.ts +2 -0
  236. package/dist/tools/board.test.d.ts.map +1 -0
  237. package/dist/tools/board.test.js +964 -0
  238. package/dist/tools/board.test.js.map +1 -0
  239. package/dist/tools/edge-staleness.d.ts.map +1 -1
  240. package/dist/tools/edge-staleness.js +18 -4
  241. package/dist/tools/edge-staleness.js.map +1 -1
  242. package/dist/tools/positions.d.ts.map +1 -1
  243. package/dist/tools/positions.js +6 -0
  244. package/dist/tools/positions.js.map +1 -1
  245. package/dist/tools/read.d.ts +2 -0
  246. package/dist/tools/read.d.ts.map +1 -1
  247. package/dist/tools/read.js +43 -13
  248. package/dist/tools/read.js.map +1 -1
  249. package/dist/tools/receipt.d.ts +6 -0
  250. package/dist/tools/receipt.d.ts.map +1 -1
  251. package/dist/tools/receipt.js +47 -1
  252. package/dist/tools/receipt.js.map +1 -1
  253. package/dist/tools/search.d.ts.map +1 -1
  254. package/dist/tools/search.js +79 -17
  255. package/dist/tools/search.js.map +1 -1
  256. package/dist/tools/staged-actions.d.ts.map +1 -1
  257. package/dist/tools/staged-actions.js +26 -2
  258. package/dist/tools/staged-actions.js.map +1 -1
  259. package/dist/tools/write.d.ts +1 -0
  260. package/dist/tools/write.d.ts.map +1 -1
  261. package/dist/tools/write.js +475 -227
  262. package/dist/tools/write.js.map +1 -1
  263. package/dist/utils/config.d.ts +21 -0
  264. package/dist/utils/config.d.ts.map +1 -1
  265. package/dist/utils/config.js +104 -1
  266. package/dist/utils/config.js.map +1 -1
  267. package/dist/utils/git.d.ts +18 -2
  268. package/dist/utils/git.d.ts.map +1 -1
  269. package/dist/utils/git.js +116 -13
  270. package/dist/utils/git.js.map +1 -1
  271. package/dist/version.d.ts +2 -0
  272. package/dist/version.d.ts.map +1 -0
  273. package/dist/version.js +8 -0
  274. package/dist/version.js.map +1 -0
  275. package/dist/view/board-page.d.ts +4 -0
  276. package/dist/view/board-page.d.ts.map +1 -0
  277. package/dist/view/board-page.js +278 -0
  278. package/dist/view/board-page.js.map +1 -0
  279. package/dist/view/board-page.test.d.ts +2 -0
  280. package/dist/view/board-page.test.d.ts.map +1 -0
  281. package/dist/view/board-page.test.js +548 -0
  282. package/dist/view/board-page.test.js.map +1 -0
  283. package/dist/view/pages.d.ts.map +1 -1
  284. package/dist/view/pages.js +13 -2
  285. package/dist/view/pages.js.map +1 -1
  286. package/dist/view/render.d.ts.map +1 -1
  287. package/dist/view/render.js +2 -1
  288. package/dist/view/render.js.map +1 -1
  289. package/package.json +2 -2
@@ -21,6 +21,7 @@ import { sourceReadable } from "../curation/tension-access.js";
21
21
  import { bucketHiddenDownstream, buildReverseLinkMap, buildReverseSourceMap, computeBlast, } from "../curation/tension-blast.js";
22
22
  import { EXTERNAL_REF } from "../curation/tier0.js";
23
23
  import { buildPathIndexes, extractLinks, loadDocuments, outgoingLinkTargets, resolveLink, } from "../curation/vault-docs.js";
24
+ import { encodeLineageEntry, readersFromLineage, unionLineage, } from "../distill/reader-fingerprint.js";
24
25
  import { parseDocument } from "../frontmatter/parser.js";
25
26
  import { validateFrontmatter } from "../frontmatter/schema.js";
26
27
  import { CONFIDENCES, DOMAINS, err, ok, PROVENANCES, STATUSES, TIERS, } from "../frontmatter/types.js";
@@ -473,6 +474,27 @@ export async function retryOnStale(attempt) {
473
474
  return first;
474
475
  return attempt();
475
476
  }
477
+ // The dispatcher for the other frontmatter-only lifecycle tools (promote,
478
+ // deprecate, set_confidence, set_tier, append): each accepts an OPTIONAL
479
+ // caller-supplied base_version, unlike assert/consolidate above which never
480
+ // expose one. The two cases behave differently on purpose:
481
+ //
482
+ // - explicit base_version: this is the CALLER's optimistic-concurrency
483
+ // token, composed against content the caller itself read. A stale
484
+ // rejection here is the caller's own mistake — it must fail loudly
485
+ // WITHOUT a hidden retry, so the caller re-reads and resubmits against
486
+ // the winner's content (retrying transparently would silently discard
487
+ // work the caller may have composed by hand).
488
+ // - omitted base_version: `attempt` fills it in internally from the
489
+ // load-time contentHash (TargetDocument.contentHash), and because these
490
+ // tools' new frontmatter is a pure function of that load, one transparent
491
+ // retry via retryOnStale is sound — the same guarantee assert/consolidate
492
+ // rely on above.
493
+ export async function retryOnStaleIfDefaulted(explicitBaseVersion, attempt) {
494
+ if (explicitBaseVersion !== undefined)
495
+ return attempt();
496
+ return retryOnStale(attempt);
497
+ }
476
498
  export async function loadTargetDocument(vaultRoot, rawPath, tool) {
477
499
  const resolved = resolveVaultPath(vaultRoot, rawPath);
478
500
  if (!resolved.ok)
@@ -726,6 +748,13 @@ export async function vaultWrite(vaultRoot, args, access) {
726
748
  ? args.reason.trim()
727
749
  : `propose-only role '${access.roleName}': write staged for ratification`,
728
750
  proposedDiff: { frontmatter: rawFrontmatter, body },
751
+ // LD-13 ratify staleness guard (same one-line capture as vault_assert's
752
+ // propose-only branch): anchor to the bytes `onDisk` was read from above,
753
+ // so a ratify replay against a document that changed since staging fails
754
+ // loudly as a stale write instead of silently overwriting the change.
755
+ // Undefined for a create (onDisk not ok — no prior version to anchor to;
756
+ // create-vs-create races are out of scope here, same as today).
757
+ ...(onDisk.ok ? { baseVersion: sha256Hex(onDisk.value) } : {}),
729
758
  ...(runId.value !== undefined ? { runId: runId.value } : {}),
730
759
  });
731
760
  if (!staged.ok)
@@ -790,13 +819,99 @@ export async function vaultWrite(vaultRoot, args, access) {
790
819
  // object is written back into `rawFrontmatter` in place, so transform hooks,
791
820
  // validation, and serialization all operate on it. The create path is
792
821
  // unchanged — there is no existing frontmatter to preserve.
822
+ //
823
+ // Field-aware special cases (6mf.4 R2, R6, R7):
824
+ // `readers` and `reader_lineage` are append-only provenance fields; instead
825
+ // of letting the payload win, we union existing ∪ payload at land time.
826
+ // This fixes the clobber without any writer having to read the doc first.
827
+ // Null-delete is evaluated BEFORE the union (R7 escape hatch preserved).
828
+ // Non-array on-disk lineage is filtered as absent, never bricks a write.
829
+ // After the union, the 6mf.1 rule applies: >1 distinct reader ⇒ drop all
830
+ // scalar reader_* fields from the merged raw.
793
831
  if (isUpdate && oldRaw !== null) {
794
832
  const merged = { ...oldRaw };
833
+ // Step 1: apply null-delete and regular payload keys (null-delete first).
795
834
  for (const [key, value] of Object.entries(rawFrontmatter)) {
796
- if (value === null)
835
+ if (value === null) {
797
836
  delete merged[key];
798
- else
837
+ }
838
+ else if (key === "readers" || key === "reader_lineage") {
839
+ // Defer these — handled below as append-only union.
840
+ // (We do NOT write them here yet; we'll union after the loop.)
841
+ }
842
+ else {
799
843
  merged[key] = value;
844
+ }
845
+ }
846
+ // Step 2: field-aware union for readers / reader_lineage.
847
+ // Only runs when NOT null-deleted (null case handled above).
848
+ const readersNulled = rawFrontmatter.readers === null;
849
+ const lineageNulled = rawFrontmatter.reader_lineage === null;
850
+ if (!readersNulled && !lineageNulled) {
851
+ // Union readers[]
852
+ const existingReaders = Array.isArray(merged.readers)
853
+ ? merged.readers.filter((r) => typeof r === "string")
854
+ : [];
855
+ const payloadReaders = "readers" in rawFrontmatter && Array.isArray(rawFrontmatter.readers)
856
+ ? rawFrontmatter.readers.filter((r) => typeof r === "string")
857
+ : null;
858
+ if (payloadReaders !== null) {
859
+ const unioned = [...existingReaders];
860
+ for (const r of payloadReaders) {
861
+ if (!unioned.includes(r))
862
+ unioned.push(r);
863
+ }
864
+ merged.readers = unioned;
865
+ }
866
+ // Union reader_lineage[]
867
+ let existingLineage = Array.isArray(merged.reader_lineage)
868
+ ? merged.reader_lineage.filter((e) => typeof e === "string")
869
+ : []; // malformed (non-array) treated as absent (R7)
870
+ // Lazy backfill (6mf.4 R8): if the existing doc has readers[] but NO
871
+ // reader_lineage yet, synthesize one `ingest` entry per reader at
872
+ // doc.created so the lineage history isn't blank. Only when lineage is
873
+ // absent — docs that already have lineage are not re-synthesized. Docs
874
+ // with no readers at all (human/legacy) get no fabricated ingest entries.
875
+ if (existingLineage.length === 0 && existingReaders.length > 0) {
876
+ const createdTs = typeof merged.created === "string" && merged.created.length >= 10
877
+ ? `${merged.created.slice(0, 10)}T00:00:00Z`
878
+ : new Date().toISOString();
879
+ existingLineage = existingReaders.map((r) => encodeLineageEntry(createdTs, "ingest", r));
880
+ }
881
+ const payloadLineage = "reader_lineage" in rawFrontmatter && Array.isArray(rawFrontmatter.reader_lineage)
882
+ ? rawFrontmatter.reader_lineage.filter((e) => typeof e === "string")
883
+ : null;
884
+ if (payloadLineage !== null) {
885
+ merged.reader_lineage = unionLineage(existingLineage, payloadLineage);
886
+ // Recompute readers[] from the unioned lineage to keep the invariant:
887
+ // readers[] == dedupe(reader-part of reader_lineage). Only when a
888
+ // lineage is being written — if neither source has a lineage, readers[]
889
+ // stays as the simpler union computed above.
890
+ const lineageDerivedReaders = readersFromLineage(merged.reader_lineage);
891
+ if (lineageDerivedReaders.length > 0) {
892
+ // Lineage-derived readers may include readers that aren't in lineage
893
+ // entries yet (e.g. readers[] added without a lineage entry). Merge:
894
+ // start from lineage-derived, then add any extras from merged.readers.
895
+ const lineageSet = new Set(lineageDerivedReaders);
896
+ const extras = (Array.isArray(merged.readers) ? merged.readers : []).filter((r) => !lineageSet.has(r));
897
+ merged.readers = [...lineageDerivedReaders, ...extras];
898
+ }
899
+ }
900
+ // Step 3: 6mf.1 scalar-drop rule — if unioned readers > 1, drop scalars.
901
+ const finalReaders = Array.isArray(merged.readers) ? merged.readers : [];
902
+ if (finalReaders.length > 1) {
903
+ const READER_SCALAR_FIELDS = [
904
+ "reader_model",
905
+ "reader_served_model",
906
+ "reader_temperature",
907
+ "reader_via_retry",
908
+ "reader_prompt_version",
909
+ "reader_chunk_window",
910
+ "reader_input_cap",
911
+ ];
912
+ for (const field of READER_SCALAR_FIELDS)
913
+ delete merged[field];
914
+ }
800
915
  }
801
916
  for (const key of Object.keys(rawFrontmatter))
802
917
  delete rawFrontmatter[key];
@@ -1010,91 +1125,90 @@ export async function vaultAppend(vaultRoot, args, access) {
1010
1125
  const proposeGate = denyIfProposeOnly(access, "vault_append");
1011
1126
  if (!proposeGate.ok)
1012
1127
  return proposeGate;
1013
- const resolved = resolveVaultPath(vaultRoot, path.value);
1014
- if (!resolved.ok)
1015
- return resolved;
1016
- const existing = await readFile(resolved.value.absPath);
1017
- if (!existing.ok) {
1018
- return err(new Error(`vault_append: document not found: ${path.value}`));
1019
- }
1020
- const parsed = parseDocument(existing.value);
1021
- if (!parsed.ok)
1022
- return parsed;
1023
- const config = loadConfig(vaultRoot);
1024
- if (!config.ok)
1025
- return config;
1026
- const extensions = config.value.schemaExtensions;
1027
- const oldFrontmatter = parsed.value.frontmatter;
1028
- const rbac = requireWriteAccess(access, collectionOf(path.value, oldFrontmatter));
1029
- if (!rbac.ok)
1030
- return rbac;
1031
- const newFrontmatter = {
1032
- ...oldFrontmatter,
1033
- updated: todayISO(),
1034
- updated_by: agent.value,
1128
+ const attemptAppend = async () => {
1129
+ const target = await loadTargetDocument(vaultRoot, path.value, "vault_append");
1130
+ if (!target.ok)
1131
+ return target;
1132
+ const extensions = target.value.config.schemaExtensions;
1133
+ const oldFrontmatter = target.value.parsed.frontmatter;
1134
+ const rbac = requireWriteAccess(access, collectionOf(path.value, oldFrontmatter));
1135
+ if (!rbac.ok)
1136
+ return rbac;
1137
+ const newFrontmatter = {
1138
+ ...oldFrontmatter,
1139
+ updated: todayISO(),
1140
+ updated_by: agent.value,
1141
+ };
1142
+ const newBody = `${target.value.parsed.content.replace(/\s+$/, "")}\n\n${section.value.trim()}\n`;
1143
+ // Pre-write transform hooks run before the pre_write validators; their
1144
+ // Partial<Frontmatter> patch is merged Object.assign-style into the
1145
+ // post-stamp frontmatter so the validators below see the transformed
1146
+ // values. A transform throw or non-object return blocks the append.
1147
+ const loadedTransformHooks = await loadPreWriteTransformHooks(vaultRoot, target.value.config.hooks.preWriteTransform);
1148
+ if (!loadedTransformHooks.ok)
1149
+ return loadedTransformHooks;
1150
+ const transformResult = runPreWriteTransformHooks(loadedTransformHooks.value, newFrontmatter, { path: path.value, operation: "append" });
1151
+ Object.assign(newFrontmatter, transformResult.merged);
1152
+ // Pre-write hooks see the post-stamp, post-transform frontmatter (the
1153
+ // same shape a subsequent vault_read would return). Issues block the
1154
+ // append, same as for vault_write.
1155
+ const loadedHooks = await loadHooks(vaultRoot, target.value.config.hooks.preWrite);
1156
+ if (!loadedHooks.ok)
1157
+ return loadedHooks;
1158
+ const hookIssues = runPreWriteHooks(loadedHooks.value, newFrontmatter, { path: path.value, operation: "append" });
1159
+ const appendIssues = [...transformResult.issues, ...hookIssues];
1160
+ if (appendIssues.length > 0) {
1161
+ const summary = appendIssues.map((i) => `${i.field}: ${i.message}`).join("; ");
1162
+ return err(new Error(`invalid frontmatter: ${summary}`));
1163
+ }
1164
+ const written = await performWrite({
1165
+ vaultRoot,
1166
+ // Lock key, provenance, and commit path are all keyed on the CANONICAL
1167
+ // relPath, never the raw caller string: aliased spellings of one file
1168
+ // must contend on one lock (#127/#128).
1169
+ relPath: target.value.relPath,
1170
+ absPath: target.value.absPath,
1171
+ agent: agent.value,
1172
+ tool: "vault_append",
1173
+ action: "append",
1174
+ fileText: serializeDocument(newFrontmatter, newBody, extensions, target.value.parsed.raw),
1175
+ newFrontmatter,
1176
+ oldFrontmatter,
1177
+ validation: target.value.parsed.validation,
1178
+ commitMessage: `vault_append: ${path.value} by ${agent.value}`,
1179
+ autoCommit: target.value.config.autoCommit,
1180
+ gitDir: target.value.config.gitDir,
1181
+ baseVersion: baseVersion.value ?? target.value.contentHash,
1182
+ shadowMode: target.value.config.shadowMode,
1183
+ principal: access?.user,
1184
+ ...(runId.value !== undefined ? { runId: runId.value } : {}),
1185
+ bodyChanged: true,
1186
+ });
1187
+ if (!written.ok)
1188
+ return written;
1189
+ return ok({ written: written.value, domain: newFrontmatter.domain });
1035
1190
  };
1036
- const newBody = `${parsed.value.content.replace(/\s+$/, "")}\n\n${section.value.trim()}\n`;
1037
- // Pre-write transform hooks run before the pre_write validators; their
1038
- // Partial<Frontmatter> patch is merged Object.assign-style into the
1039
- // post-stamp frontmatter so the validators below see the transformed
1040
- // values. A transform throw or non-object return blocks the append.
1041
- const loadedTransformHooks = await loadPreWriteTransformHooks(vaultRoot, config.value.hooks.preWriteTransform);
1042
- if (!loadedTransformHooks.ok)
1043
- return loadedTransformHooks;
1044
- const transformResult = runPreWriteTransformHooks(loadedTransformHooks.value, newFrontmatter, { path: path.value, operation: "append" });
1045
- Object.assign(newFrontmatter, transformResult.merged);
1046
- // Pre-write hooks see the post-stamp, post-transform frontmatter (the same
1047
- // shape a subsequent vault_read would return). Issues block the append,
1048
- // same as for vault_write.
1049
- const loadedHooks = await loadHooks(vaultRoot, config.value.hooks.preWrite);
1050
- if (!loadedHooks.ok)
1051
- return loadedHooks;
1052
- const hookIssues = runPreWriteHooks(loadedHooks.value, newFrontmatter, { path: path.value, operation: "append" });
1053
- const appendIssues = [...transformResult.issues, ...hookIssues];
1054
- if (appendIssues.length > 0) {
1055
- const summary = appendIssues.map((i) => `${i.field}: ${i.message}`).join("; ");
1056
- return err(new Error(`invalid frontmatter: ${summary}`));
1057
- }
1058
- const appended = await performWrite({
1059
- vaultRoot,
1060
- // Lock key, provenance, and commit path are all keyed on the CANONICAL
1061
- // relPath (resolved.value.relPath), never the raw caller string: aliased
1062
- // spellings of one file must contend on one lock (#127/#128).
1063
- relPath: resolved.value.relPath,
1064
- absPath: resolved.value.absPath,
1065
- agent: agent.value,
1066
- tool: "vault_append",
1067
- action: "append",
1068
- fileText: serializeDocument(newFrontmatter, newBody, extensions, parsed.value.raw),
1069
- newFrontmatter,
1070
- oldFrontmatter,
1071
- validation: parsed.value.validation,
1072
- commitMessage: `vault_append: ${path.value} by ${agent.value}`,
1073
- autoCommit: config.value.autoCommit,
1074
- gitDir: config.value.gitDir,
1075
- baseVersion: baseVersion.value,
1076
- shadowMode: config.value.shadowMode,
1077
- principal: access?.user,
1078
- ...(runId.value !== undefined ? { runId: runId.value } : {}),
1079
- bodyChanged: true,
1080
- });
1191
+ const attempt = await retryOnStaleIfDefaulted(baseVersion.value, attemptAppend);
1192
+ if (!attempt.ok)
1193
+ return attempt;
1194
+ const { written, domain } = attempt.value;
1081
1195
  // #4: an appended section can introduce body links into generative-domain
1082
1196
  // docs — same advisory channel as vault_write, scoped to what THIS append
1083
1197
  // added: only the new section is scanned (a doc that already leaned on
1084
1198
  // generative material warned at write time; re-warning on every later,
1085
1199
  // unrelated append would drown the signal), and sources are skipped
1086
1200
  // entirely because an append cannot change frontmatter.
1087
- if (!appended.ok || appended.value.shadow)
1088
- return appended;
1201
+ if (written.shadow)
1202
+ return ok(written);
1089
1203
  const appendWarnings = generativeDomainRefs(vaultRoot, {
1090
- domain: newFrontmatter.domain,
1204
+ domain,
1091
1205
  sources: [],
1092
1206
  body: section.value,
1093
- relPath: resolved.value.relPath,
1207
+ relPath: written.path,
1094
1208
  }, access);
1095
1209
  if (appendWarnings === null)
1096
- return appended;
1097
- return ok({ ...appended.value, domain_warnings: appendWarnings });
1210
+ return ok(written);
1211
+ return ok({ ...written, domain_warnings: appendWarnings });
1098
1212
  }
1099
1213
  // ---------------------------------------------------------------------------
1100
1214
  // vault_promote
@@ -1121,43 +1235,52 @@ export async function vaultPromote(vaultRoot, args, access) {
1121
1235
  if (access && !canPromote(access.role)) {
1122
1236
  return err(new Error(`access denied: role '${access.roleName}' cannot promote documents`));
1123
1237
  }
1124
- const target = await loadTargetDocument(vaultRoot, path.value, "vault_promote");
1125
- if (!target.ok)
1126
- return target;
1127
- const oldFrontmatter = target.value.parsed.frontmatter;
1128
- if (oldFrontmatter.status !== "draft") {
1129
- return err(new Error(`vault_promote: only draft documents can be promoted ` +
1130
- `(${path.value} is '${oldFrontmatter.status}')`));
1131
- }
1132
- if (!target.value.parsed.validation.valid) {
1133
- const summary = target.value.parsed.validation.issues
1134
- .map((i) => `${i.field}: ${i.message}`)
1135
- .join("; ");
1136
- return err(new Error(`vault_promote: frontmatter is incomplete: ${summary}`));
1137
- }
1138
- // `confidence set` — the document must declare a confidence explicitly, not
1139
- // ride on the validator's default.
1140
- const rawConfidence = target.value.parsed.raw.confidence;
1141
- if (typeof rawConfidence !== "string" ||
1142
- !CONFIDENCES.includes(rawConfidence)) {
1143
- return err(new Error("vault_promote: confidence must be set before promotion"));
1144
- }
1145
- return performFrontmatterWrite({
1146
- vaultRoot,
1147
- target: target.value,
1148
- agent: agent.value,
1149
- tool: "vault_promote",
1150
- action: "promote",
1151
- newFrontmatter: {
1152
- ...oldFrontmatter,
1153
- status: "canonical",
1154
- updated: todayISO(),
1155
- updated_by: agent.value,
1156
- },
1157
- commitMessage: `vault_promote: ${path.value} draft→canonical by ${agent.value}`,
1158
- baseVersion: baseVersion.value,
1159
- access,
1160
- });
1238
+ // Read-modify-write over the loaded frontmatter — see
1239
+ // retryOnStaleIfDefaulted above. An explicit base_version passes straight
1240
+ // through (one attempt, loud stale rejection); an omitted one defaults to
1241
+ // the load-time contentHash and gets one transparent retry, so a concurrent
1242
+ // vault_assert's positions array is never silently erased by a clean
1243
+ // promote commit.
1244
+ const attemptPromote = async () => {
1245
+ const target = await loadTargetDocument(vaultRoot, path.value, "vault_promote");
1246
+ if (!target.ok)
1247
+ return target;
1248
+ const oldFrontmatter = target.value.parsed.frontmatter;
1249
+ if (oldFrontmatter.status !== "draft") {
1250
+ return err(new Error(`vault_promote: only draft documents can be promoted ` +
1251
+ `(${path.value} is '${oldFrontmatter.status}')`));
1252
+ }
1253
+ if (!target.value.parsed.validation.valid) {
1254
+ const summary = target.value.parsed.validation.issues
1255
+ .map((i) => `${i.field}: ${i.message}`)
1256
+ .join("; ");
1257
+ return err(new Error(`vault_promote: frontmatter is incomplete: ${summary}`));
1258
+ }
1259
+ // `confidence set` — the document must declare a confidence explicitly, not
1260
+ // ride on the validator's default.
1261
+ const rawConfidence = target.value.parsed.raw.confidence;
1262
+ if (typeof rawConfidence !== "string" ||
1263
+ !CONFIDENCES.includes(rawConfidence)) {
1264
+ return err(new Error("vault_promote: confidence must be set before promotion"));
1265
+ }
1266
+ return performFrontmatterWrite({
1267
+ vaultRoot,
1268
+ target: target.value,
1269
+ agent: agent.value,
1270
+ tool: "vault_promote",
1271
+ action: "promote",
1272
+ newFrontmatter: {
1273
+ ...oldFrontmatter,
1274
+ status: "canonical",
1275
+ updated: todayISO(),
1276
+ updated_by: agent.value,
1277
+ },
1278
+ commitMessage: `vault_promote: ${path.value} draft→canonical by ${agent.value}`,
1279
+ baseVersion: baseVersion.value ?? target.value.contentHash,
1280
+ access,
1281
+ });
1282
+ };
1283
+ return retryOnStaleIfDefaulted(baseVersion.value, attemptPromote);
1161
1284
  }
1162
1285
  // ---------------------------------------------------------------------------
1163
1286
  // downstream dependents advisory helper
@@ -1243,41 +1366,50 @@ export async function vaultDeprecate(vaultRoot, args, access) {
1243
1366
  }
1244
1367
  supersededBy = args.superseded_by;
1245
1368
  }
1246
- const target = await loadTargetDocument(vaultRoot, path.value, "vault_deprecate");
1247
- if (!target.ok)
1248
- return target;
1249
- const oldFrontmatter = target.value.parsed.frontmatter;
1250
- const rbac = requireWriteAccess(access, collectionOf(path.value, oldFrontmatter));
1251
- if (!rbac.ok)
1252
- return rbac;
1253
- // Same predecessor-only handoff as vault_supersede: this writes exactly the
1254
- // document being deprecated, which it already locks and commits.
1255
- let validUntil = null;
1256
- if (boundary.value !== null) {
1257
- const closing = closingUntil(oldFrontmatter, boundary.value, "vault_deprecate", path.value);
1258
- if (!closing.ok)
1259
- return closing;
1260
- validUntil = closing.value;
1261
- }
1262
- const written = await performFrontmatterWrite({
1263
- vaultRoot,
1264
- target: target.value,
1265
- agent: agent.value,
1266
- tool: "vault_deprecate",
1267
- action: "deprecate",
1268
- newFrontmatter: {
1269
- ...oldFrontmatter,
1270
- status: "deprecated",
1271
- superseded_by: supersededBy,
1272
- ...(validUntil !== null ? { valid_until: validUntil } : {}),
1273
- updated: todayISO(),
1274
- updated_by: agent.value,
1275
- },
1276
- commitMessage: `vault_deprecate: ${path.value} by ${agent.value} — ${reason.value}` +
1277
- (supersededBy ? ` (superseded by ${supersededBy})` : ""),
1278
- baseVersion: baseVersion.value,
1279
- access,
1280
- });
1369
+ // Read-modify-write over the loaded frontmatter — see
1370
+ // retryOnStaleIfDefaulted above. An explicit base_version passes straight
1371
+ // through (one attempt, loud stale rejection); an omitted one defaults to
1372
+ // the load-time contentHash and gets one transparent retry, so a concurrent
1373
+ // vault_assert's positions array is never silently erased by a clean
1374
+ // deprecate commit.
1375
+ const attemptDeprecate = async () => {
1376
+ const target = await loadTargetDocument(vaultRoot, path.value, "vault_deprecate");
1377
+ if (!target.ok)
1378
+ return target;
1379
+ const oldFrontmatter = target.value.parsed.frontmatter;
1380
+ const rbac = requireWriteAccess(access, collectionOf(path.value, oldFrontmatter));
1381
+ if (!rbac.ok)
1382
+ return rbac;
1383
+ // Same predecessor-only handoff as vault_supersede: this writes exactly
1384
+ // the document being deprecated, which it already locks and commits.
1385
+ let validUntil = null;
1386
+ if (boundary.value !== null) {
1387
+ const closing = closingUntil(oldFrontmatter, boundary.value, "vault_deprecate", path.value);
1388
+ if (!closing.ok)
1389
+ return closing;
1390
+ validUntil = closing.value;
1391
+ }
1392
+ return performFrontmatterWrite({
1393
+ vaultRoot,
1394
+ target: target.value,
1395
+ agent: agent.value,
1396
+ tool: "vault_deprecate",
1397
+ action: "deprecate",
1398
+ newFrontmatter: {
1399
+ ...oldFrontmatter,
1400
+ status: "deprecated",
1401
+ superseded_by: supersededBy,
1402
+ ...(validUntil !== null ? { valid_until: validUntil } : {}),
1403
+ updated: todayISO(),
1404
+ updated_by: agent.value,
1405
+ },
1406
+ commitMessage: `vault_deprecate: ${path.value} by ${agent.value} — ${reason.value}` +
1407
+ (supersededBy ? ` (superseded by ${supersededBy})` : ""),
1408
+ baseVersion: baseVersion.value ?? target.value.contentHash,
1409
+ access,
1410
+ });
1411
+ };
1412
+ const written = await retryOnStaleIfDefaulted(baseVersion.value, attemptDeprecate);
1281
1413
  if (!written.ok)
1282
1414
  return written;
1283
1415
  // Build the downstream dependents advisory (best-effort, never fails the write).
@@ -1320,45 +1452,55 @@ export async function vaultSetConfidence(vaultRoot, args, access) {
1320
1452
  const baseVersion = readBaseVersion(args, "vault_set_confidence");
1321
1453
  if (!baseVersion.ok)
1322
1454
  return baseVersion;
1323
- const target = await loadTargetDocument(vaultRoot, path.value, "vault_set_confidence");
1324
- if (!target.ok)
1325
- return target;
1326
- const oldFrontmatter = target.value.parsed.frontmatter;
1327
- const rbac = requireWriteAccess(access, collectionOf(path.value, oldFrontmatter));
1328
- if (!rbac.ok)
1329
- return rbac;
1330
- // No-op guard: a confidence already at the target would churn a commit for no
1331
- // change. Surface it as an error so a redundant staged confidence-up does not
1332
- // silently no-op (and a caller learns the value was already set). Compare
1333
- // against the *raw* on-disk value, not the validated frontmatter — the
1334
- // validator defaults a missing confidence to "low", so comparing the
1335
- // validated value would wrongly reject set_confidence(…, "low") on a doc that
1336
- // never declared one and never write the field (the trap vault_promote dodges
1337
- // the same way, via parsed.value.raw.confidence).
1338
- const rawConfidence = target.value.parsed.raw.confidence;
1339
- const currentConfidence = typeof rawConfidence === "string" && CONFIDENCES.includes(rawConfidence)
1340
- ? rawConfidence
1341
- : undefined;
1342
- if (currentConfidence === confidence.value) {
1343
- return err(new Error(`vault_set_confidence: ${path.value} confidence is already '${confidence.value}'`));
1344
- }
1345
- return performFrontmatterWrite({
1346
- vaultRoot,
1347
- target: target.value,
1348
- agent: agent.value,
1349
- tool: "vault_set_confidence",
1350
- action: "confidence-set",
1351
- newFrontmatter: {
1352
- ...oldFrontmatter,
1353
- confidence: confidence.value,
1354
- updated: todayISO(),
1355
- updated_by: agent.value,
1356
- },
1357
- commitMessage: `vault_set_confidence: ${path.value} ${oldFrontmatter.confidence}→${confidence.value} ` +
1358
- `by ${agent.value} — ${reason.value}`,
1359
- baseVersion: baseVersion.value,
1360
- access,
1361
- });
1455
+ // Read-modify-write over the loaded frontmatter — see
1456
+ // retryOnStaleIfDefaulted above. An explicit base_version passes straight
1457
+ // through (one attempt, loud stale rejection); an omitted one defaults to
1458
+ // the load-time contentHash and gets one transparent retry, so a concurrent
1459
+ // vault_assert's positions array is never silently erased by a clean
1460
+ // confidence-set commit.
1461
+ const attemptSetConfidence = async () => {
1462
+ const target = await loadTargetDocument(vaultRoot, path.value, "vault_set_confidence");
1463
+ if (!target.ok)
1464
+ return target;
1465
+ const oldFrontmatter = target.value.parsed.frontmatter;
1466
+ const rbac = requireWriteAccess(access, collectionOf(path.value, oldFrontmatter));
1467
+ if (!rbac.ok)
1468
+ return rbac;
1469
+ // No-op guard: a confidence already at the target would churn a commit for
1470
+ // no change. Surface it as an error so a redundant staged confidence-up
1471
+ // does not silently no-op (and a caller learns the value was already
1472
+ // set). Compare against the *raw* on-disk value, not the validated
1473
+ // frontmatter — the validator defaults a missing confidence to "low", so
1474
+ // comparing the validated value would wrongly reject set_confidence(…,
1475
+ // "low") on a doc that never declared one and never write the field (the
1476
+ // trap vault_promote dodges the same way, via parsed.value.raw.confidence).
1477
+ const rawConfidence = target.value.parsed.raw.confidence;
1478
+ const currentConfidence = typeof rawConfidence === "string" &&
1479
+ CONFIDENCES.includes(rawConfidence)
1480
+ ? rawConfidence
1481
+ : undefined;
1482
+ if (currentConfidence === confidence.value) {
1483
+ return err(new Error(`vault_set_confidence: ${path.value} confidence is already '${confidence.value}'`));
1484
+ }
1485
+ return performFrontmatterWrite({
1486
+ vaultRoot,
1487
+ target: target.value,
1488
+ agent: agent.value,
1489
+ tool: "vault_set_confidence",
1490
+ action: "confidence-set",
1491
+ newFrontmatter: {
1492
+ ...oldFrontmatter,
1493
+ confidence: confidence.value,
1494
+ updated: todayISO(),
1495
+ updated_by: agent.value,
1496
+ },
1497
+ commitMessage: `vault_set_confidence: ${path.value} ${oldFrontmatter.confidence}→${confidence.value} ` +
1498
+ `by ${agent.value} — ${reason.value}`,
1499
+ baseVersion: baseVersion.value ?? target.value.contentHash,
1500
+ access,
1501
+ });
1502
+ };
1503
+ return retryOnStaleIfDefaulted(baseVersion.value, attemptSetConfidence);
1362
1504
  }
1363
1505
  // ---------------------------------------------------------------------------
1364
1506
  // vault_set_tier (#141)
@@ -1396,47 +1538,56 @@ export async function vaultSetTier(vaultRoot, args, access) {
1396
1538
  const baseVersion = readBaseVersion(args, "vault_set_tier");
1397
1539
  if (!baseVersion.ok)
1398
1540
  return baseVersion;
1399
- const target = await loadTargetDocument(vaultRoot, path.value, "vault_set_tier");
1400
- if (!target.ok)
1401
- return target;
1402
- const oldFrontmatter = target.value.parsed.frontmatter;
1403
- const rbac = requireWriteAccess(access, collectionOf(path.value, oldFrontmatter));
1404
- if (!rbac.ok)
1405
- return rbac;
1406
- // The manual consent boundary: only a human identity may lift `manual`.
1407
- if (oldFrontmatter.tier === "manual" &&
1408
- newTier !== "manual" &&
1409
- !agent.value.startsWith("human:")) {
1410
- return err(new Error(`vault_set_tier: ${path.value} is tier 'manual' — moving it away from ` +
1411
- `'manual' requires a human:* identity (got '${agent.value}').`));
1412
- }
1413
- // No-op guard, same shape as vault_set_confidence: compare against the raw
1414
- // on-disk value so an invalid raw tier (validated down to null) can still be
1415
- // set to any member.
1416
- const rawTier = target.value.parsed.raw.tier;
1417
- const currentTier = typeof rawTier === "string" && TIERS.includes(rawTier)
1418
- ? rawTier
1419
- : undefined;
1420
- if (currentTier === newTier) {
1421
- return err(new Error(`vault_set_tier: ${path.value} tier is already '${newTier}'`));
1422
- }
1423
- return performFrontmatterWrite({
1424
- vaultRoot,
1425
- target: target.value,
1426
- agent: agent.value,
1427
- tool: "vault_set_tier",
1428
- action: "tier-set",
1429
- newFrontmatter: {
1430
- ...oldFrontmatter,
1431
- tier: newTier,
1432
- updated: todayISO(),
1433
- updated_by: agent.value,
1434
- },
1435
- commitMessage: `vault_set_tier: ${path.value} ${oldFrontmatter.tier ?? "unset"}→${newTier} ` +
1436
- `by ${agent.value} — ${reason.value}`,
1437
- baseVersion: baseVersion.value,
1438
- access,
1439
- });
1541
+ // Read-modify-write over the loaded frontmatter — see
1542
+ // retryOnStaleIfDefaulted above. An explicit base_version passes straight
1543
+ // through (one attempt, loud stale rejection); an omitted one defaults to
1544
+ // the load-time contentHash and gets one transparent retry, so a concurrent
1545
+ // vault_assert's positions array is never silently erased by a clean
1546
+ // tier-set commit.
1547
+ const attemptSetTier = async () => {
1548
+ const target = await loadTargetDocument(vaultRoot, path.value, "vault_set_tier");
1549
+ if (!target.ok)
1550
+ return target;
1551
+ const oldFrontmatter = target.value.parsed.frontmatter;
1552
+ const rbac = requireWriteAccess(access, collectionOf(path.value, oldFrontmatter));
1553
+ if (!rbac.ok)
1554
+ return rbac;
1555
+ // The manual consent boundary: only a human identity may lift `manual`.
1556
+ if (oldFrontmatter.tier === "manual" &&
1557
+ newTier !== "manual" &&
1558
+ !agent.value.startsWith("human:")) {
1559
+ return err(new Error(`vault_set_tier: ${path.value} is tier 'manual' — moving it away from ` +
1560
+ `'manual' requires a human:* identity (got '${agent.value}').`));
1561
+ }
1562
+ // No-op guard, same shape as vault_set_confidence: compare against the
1563
+ // raw on-disk value so an invalid raw tier (validated down to null) can
1564
+ // still be set to any member.
1565
+ const rawTier = target.value.parsed.raw.tier;
1566
+ const currentTier = typeof rawTier === "string" && TIERS.includes(rawTier)
1567
+ ? rawTier
1568
+ : undefined;
1569
+ if (currentTier === newTier) {
1570
+ return err(new Error(`vault_set_tier: ${path.value} tier is already '${newTier}'`));
1571
+ }
1572
+ return performFrontmatterWrite({
1573
+ vaultRoot,
1574
+ target: target.value,
1575
+ agent: agent.value,
1576
+ tool: "vault_set_tier",
1577
+ action: "tier-set",
1578
+ newFrontmatter: {
1579
+ ...oldFrontmatter,
1580
+ tier: newTier,
1581
+ updated: todayISO(),
1582
+ updated_by: agent.value,
1583
+ },
1584
+ commitMessage: `vault_set_tier: ${path.value} ${oldFrontmatter.tier ?? "unset"}→${newTier} ` +
1585
+ `by ${agent.value} — ${reason.value}`,
1586
+ baseVersion: baseVersion.value ?? target.value.contentHash,
1587
+ access,
1588
+ });
1589
+ };
1590
+ return retryOnStaleIfDefaulted(baseVersion.value, attemptSetTier);
1440
1591
  }
1441
1592
  // ---------------------------------------------------------------------------
1442
1593
  // vault_supersede (§11.4)
@@ -1685,6 +1836,89 @@ export async function vaultMerge(vaultRoot, args, access) {
1685
1836
  updated: todayISO(),
1686
1837
  updated_by: agent.value,
1687
1838
  };
1839
+ // Reader parentage fusion (6mf.1). targetRaw inherits path_a's raw, so it
1840
+ // currently carries ONLY path_a's `readers` set and path_a's scalar reader_*
1841
+ // fields — a false single-parent claim that silently drops path_b's reader.
1842
+ // Fuse instead: the merged `readers` is the DEDUPED UNION of both sources'
1843
+ // sets (A's entries first, then B's new ones — order-stable). Entries are
1844
+ // already-encoded opaque strings (reader-fingerprint.ts#encodeReader); we
1845
+ // union the strings, we never re-encode. Then:
1846
+ // - union has exactly ONE distinct reader ⇒ keep path_a's scalar reader_*
1847
+ // fields (already inherited into targetRaw — nothing to do).
1848
+ // - union has MORE THAN ONE ⇒ the merged belief must not claim single
1849
+ // parentage: DROP every scalar reader_* from targetRaw and keep only the
1850
+ // unioned `readers` set as the authoritative parentage. Dropping = delete
1851
+ // the key from targetRaw; since serializeDocument reads reader_* only from
1852
+ // this raw record, omission here removes them from the written frontmatter.
1853
+ // - neither source has a `readers` set (legacy) ⇒ no `readers` key at all,
1854
+ // no scalar changes, no empty-array placeholder.
1855
+ // This block only touches reader provenance — RBAC, body, and the superseded
1856
+ // source writes below are untouched.
1857
+ const readersA = Array.isArray(parsedA.value.raw.readers)
1858
+ ? parsedA.value.raw.readers.filter((r) => typeof r === "string")
1859
+ : [];
1860
+ const readersB = Array.isArray(parsedB.value.raw.readers)
1861
+ ? parsedB.value.raw.readers.filter((r) => typeof r === "string")
1862
+ : [];
1863
+ const unionReaders = [];
1864
+ for (const r of [...readersA, ...readersB]) {
1865
+ if (!unionReaders.includes(r))
1866
+ unionReaders.push(r);
1867
+ }
1868
+ const READER_SCALAR_FIELDS = [
1869
+ "reader_model",
1870
+ "reader_served_model",
1871
+ "reader_temperature",
1872
+ "reader_via_retry",
1873
+ "reader_prompt_version",
1874
+ "reader_chunk_window",
1875
+ "reader_input_cap",
1876
+ ];
1877
+ if (unionReaders.length === 0) {
1878
+ // Legacy on both sides: carry no parentage set (avoid an empty placeholder).
1879
+ delete targetRaw.readers;
1880
+ }
1881
+ else {
1882
+ targetRaw.readers = unionReaders;
1883
+ if (unionReaders.length > 1) {
1884
+ // Mixed parentage: drop every single-parent scalar claim.
1885
+ for (const field of READER_SCALAR_FIELDS)
1886
+ delete targetRaw[field];
1887
+ }
1888
+ }
1889
+ // reader_lineage fusion (6mf.4 R4). Mirror the readers fusion above:
1890
+ // union A's lineage entries then B's not-already-present (dedup key =
1891
+ // (op, reader) — same as the Task 2 land-time union). Neither source having
1892
+ // a lineage ⇒ no key at all (avoids an empty-array placeholder).
1893
+ const lineageA = Array.isArray(parsedA.value.raw.reader_lineage)
1894
+ ? parsedA.value.raw.reader_lineage.filter((e) => typeof e === "string")
1895
+ : [];
1896
+ const lineageB = Array.isArray(parsedB.value.raw.reader_lineage)
1897
+ ? parsedB.value.raw.reader_lineage.filter((e) => typeof e === "string")
1898
+ : [];
1899
+ if (lineageA.length > 0 || lineageB.length > 0) {
1900
+ targetRaw.reader_lineage = unionLineage(lineageA, lineageB);
1901
+ // Keep readers[] consistent with the fused lineage (invariant: readers[] ==
1902
+ // dedupe(reader-part of lineage)). Only overwrite if we actually have lineage.
1903
+ const lineageDerivedReaders = readersFromLineage(targetRaw.reader_lineage);
1904
+ if (lineageDerivedReaders.length > 0) {
1905
+ // Union any readers already in targetRaw that aren't in the lineage
1906
+ // (e.g., from the readers-only path above) to avoid narrowing the set.
1907
+ const combined = [...lineageDerivedReaders];
1908
+ for (const r of unionReaders) {
1909
+ if (!combined.includes(r))
1910
+ combined.push(r);
1911
+ }
1912
+ targetRaw.readers = combined;
1913
+ if (combined.length > 1) {
1914
+ for (const field of READER_SCALAR_FIELDS)
1915
+ delete targetRaw[field];
1916
+ }
1917
+ }
1918
+ }
1919
+ else {
1920
+ delete targetRaw.reader_lineage;
1921
+ }
1688
1922
  const { frontmatter: targetFm, report: targetReport } = validateFrontmatter(targetRaw, extensions);
1689
1923
  if (!targetReport.valid) {
1690
1924
  const summary = targetReport.issues.map((i) => `${i.field}: ${i.message}`).join("; ");
@@ -1894,6 +2128,15 @@ const agentProperty = {
1894
2128
  // surface a caller reads before invoking.
1895
2129
  const shadowNote = " If the vault runs shadow_mode, the write is computed and logged to the " +
1896
2130
  "shadow store but NOT applied; the result carries shadow: true.";
2131
+ // Appended to the description of every read-modify-write tool whose
2132
+ // base_version defaults internally (append, promote, deprecate,
2133
+ // set_confidence, set_tier): unlike vault_write, an omitted base_version here
2134
+ // is NOT last-write-wins — it defaults to the version this call itself read,
2135
+ // and a race is retried once before failing loudly.
2136
+ const staleRetryNote = " If base_version is omitted, a concurrent change is retried once " +
2137
+ "automatically before this fails loudly as stale; an explicitly supplied " +
2138
+ "base_version that is stale is rejected immediately, with no retry — " +
2139
+ "re-read and resubmit.";
1897
2140
  const baseVersionProperty = {
1898
2141
  type: "string",
1899
2142
  description: "Optional optimistic-concurrency token: the 'version' that vault_read " +
@@ -2265,6 +2508,7 @@ export const writeTools = [
2265
2508
  "Appending links to generative-domain docs onto an accumulation-domain " +
2266
2509
  "doc returns advisory domain_warnings naming them; the append still " +
2267
2510
  "lands." +
2511
+ staleRetryNote +
2268
2512
  shadowNote,
2269
2513
  inputSchema: {
2270
2514
  type: "object",
@@ -2299,6 +2543,7 @@ export const writeTools = [
2299
2543
  description: "Promote a draft document to canonical status. Refuses unless the " +
2300
2544
  "document is currently a draft, its frontmatter is complete, and a " +
2301
2545
  "confidence level has been explicitly set. Auto-commits." +
2546
+ staleRetryNote +
2302
2547
  shadowNote,
2303
2548
  inputSchema: {
2304
2549
  type: "object",
@@ -2326,6 +2571,7 @@ export const writeTools = [
2326
2571
  annotations: { destructiveHint: true },
2327
2572
  description: "Mark a document deprecated. A reason is required; optionally record " +
2328
2573
  "the document that supersedes it. Auto-commits." +
2574
+ staleRetryNote +
2329
2575
  shadowNote,
2330
2576
  inputSchema: {
2331
2577
  type: "object",
@@ -2363,6 +2609,7 @@ export const writeTools = [
2363
2609
  description: "Change only a document's confidence level (low | medium | high), leaving " +
2364
2610
  "its status and body untouched. A reason is required and recorded. Rejects " +
2365
2611
  "if the confidence is already at the target. Auto-commits." +
2612
+ staleRetryNote +
2366
2613
  shadowNote,
2367
2614
  inputSchema: {
2368
2615
  type: "object",
@@ -2405,6 +2652,7 @@ export const writeTools = [
2405
2652
  "logged for lint review), then write. Moving a doc away from 'manual' " +
2406
2653
  "requires a human:* identity. Rejects if the tier is already at the " +
2407
2654
  "target. Auto-commits." +
2655
+ staleRetryNote +
2408
2656
  shadowNote,
2409
2657
  inputSchema: {
2410
2658
  type: "object",