daftari 3.5.0 → 3.7.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 (151) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +39 -1
  3. package/dist/attest/bundle.d.ts +53 -0
  4. package/dist/attest/bundle.d.ts.map +1 -0
  5. package/dist/attest/bundle.js +141 -0
  6. package/dist/attest/bundle.js.map +1 -0
  7. package/dist/attest/index.d.ts +2 -0
  8. package/dist/attest/index.d.ts.map +1 -0
  9. package/dist/attest/index.js +139 -0
  10. package/dist/attest/index.js.map +1 -0
  11. package/dist/attest/sign.d.ts +16 -0
  12. package/dist/attest/sign.d.ts.map +1 -0
  13. package/dist/attest/sign.js +75 -0
  14. package/dist/attest/sign.js.map +1 -0
  15. package/dist/attest/verify.d.ts +21 -0
  16. package/dist/attest/verify.d.ts.map +1 -0
  17. package/dist/attest/verify.js +148 -0
  18. package/dist/attest/verify.js.map +1 -0
  19. package/dist/cli.d.ts.map +1 -1
  20. package/dist/cli.js +6 -0
  21. package/dist/cli.js.map +1 -1
  22. package/dist/consolidate/decorrelation.js +1 -1
  23. package/dist/consolidate/decorrelation.js.map +1 -1
  24. package/dist/consolidate/index.js +1 -1
  25. package/dist/court/index.d.ts.map +1 -1
  26. package/dist/court/index.js +5 -3
  27. package/dist/court/index.js.map +1 -1
  28. package/dist/curation/lint.d.ts.map +1 -1
  29. package/dist/curation/lint.js +68 -1
  30. package/dist/curation/lint.js.map +1 -1
  31. package/dist/curation/positions.d.ts +14 -0
  32. package/dist/curation/positions.d.ts.map +1 -1
  33. package/dist/curation/positions.js +74 -0
  34. package/dist/curation/positions.js.map +1 -1
  35. package/dist/curation/provenance.d.ts.map +1 -1
  36. package/dist/curation/provenance.js.map +1 -1
  37. package/dist/curation/staged-actions.d.ts +2 -0
  38. package/dist/curation/staged-actions.d.ts.map +1 -1
  39. package/dist/curation/staged-actions.js +5 -0
  40. package/dist/curation/staged-actions.js.map +1 -1
  41. package/dist/curation/tension.d.ts +9 -1
  42. package/dist/curation/tension.d.ts.map +1 -1
  43. package/dist/curation/tension.js +34 -1
  44. package/dist/curation/tension.js.map +1 -1
  45. package/dist/distill/adapters/claude-session.d.ts +6 -0
  46. package/dist/distill/adapters/claude-session.d.ts.map +1 -0
  47. package/dist/distill/adapters/claude-session.js +71 -0
  48. package/dist/distill/adapters/claude-session.js.map +1 -0
  49. package/dist/distill/cli.d.ts.map +1 -1
  50. package/dist/distill/cli.js +113 -9
  51. package/dist/distill/cli.js.map +1 -1
  52. package/dist/distill/index.d.ts +1 -0
  53. package/dist/distill/index.d.ts.map +1 -1
  54. package/dist/distill/index.js +3 -0
  55. package/dist/distill/index.js.map +1 -1
  56. package/dist/distill/propose.d.ts +23 -5
  57. package/dist/distill/propose.d.ts.map +1 -1
  58. package/dist/distill/propose.js +58 -30
  59. package/dist/distill/propose.js.map +1 -1
  60. package/dist/federation/classification.d.ts +9 -0
  61. package/dist/federation/classification.d.ts.map +1 -0
  62. package/dist/federation/classification.js +122 -0
  63. package/dist/federation/classification.js.map +1 -0
  64. package/dist/federation/index-location.d.ts +4 -0
  65. package/dist/federation/index-location.d.ts.map +1 -0
  66. package/dist/federation/index-location.js +30 -0
  67. package/dist/federation/index-location.js.map +1 -0
  68. package/dist/federation/mount-index.d.ts +8 -0
  69. package/dist/federation/mount-index.d.ts.map +1 -0
  70. package/dist/federation/mount-index.js +63 -0
  71. package/dist/federation/mount-index.js.map +1 -0
  72. package/dist/federation/mounts.d.ts +29 -0
  73. package/dist/federation/mounts.d.ts.map +1 -0
  74. package/dist/federation/mounts.js +215 -0
  75. package/dist/federation/mounts.js.map +1 -0
  76. package/dist/index.d.ts.map +1 -1
  77. package/dist/index.js +27 -0
  78. package/dist/index.js.map +1 -1
  79. package/dist/search/hybrid.d.ts +10 -0
  80. package/dist/search/hybrid.d.ts.map +1 -1
  81. package/dist/search/hybrid.js +28 -15
  82. package/dist/search/hybrid.js.map +1 -1
  83. package/dist/search/reindex.d.ts +2 -0
  84. package/dist/search/reindex.d.ts.map +1 -1
  85. package/dist/search/reindex.js +17 -9
  86. package/dist/search/reindex.js.map +1 -1
  87. package/dist/serve/auth-log.d.ts +16 -0
  88. package/dist/serve/auth-log.d.ts.map +1 -0
  89. package/dist/serve/auth-log.js +53 -0
  90. package/dist/serve/auth-log.js.map +1 -0
  91. package/dist/serve/index.d.ts +2 -0
  92. package/dist/serve/index.d.ts.map +1 -1
  93. package/dist/serve/index.js +141 -10
  94. package/dist/serve/index.js.map +1 -1
  95. package/dist/serve/limits.d.ts +37 -0
  96. package/dist/serve/limits.d.ts.map +1 -0
  97. package/dist/serve/limits.js +79 -0
  98. package/dist/serve/limits.js.map +1 -0
  99. package/dist/server.d.ts.map +1 -1
  100. package/dist/server.js +20 -0
  101. package/dist/server.js.map +1 -1
  102. package/dist/storage/index-db.d.ts +1 -0
  103. package/dist/storage/index-db.d.ts.map +1 -1
  104. package/dist/storage/index-db.js +9 -3
  105. package/dist/storage/index-db.js.map +1 -1
  106. package/dist/tools/curation.d.ts.map +1 -1
  107. package/dist/tools/curation.js +6 -5
  108. package/dist/tools/curation.js.map +1 -1
  109. package/dist/tools/positions.d.ts +8 -2
  110. package/dist/tools/positions.d.ts.map +1 -1
  111. package/dist/tools/positions.js +317 -173
  112. package/dist/tools/positions.js.map +1 -1
  113. package/dist/tools/read.d.ts +11 -0
  114. package/dist/tools/read.d.ts.map +1 -1
  115. package/dist/tools/read.js +188 -10
  116. package/dist/tools/read.js.map +1 -1
  117. package/dist/tools/receipt.d.ts +6 -0
  118. package/dist/tools/receipt.d.ts.map +1 -1
  119. package/dist/tools/receipt.js +47 -1
  120. package/dist/tools/receipt.js.map +1 -1
  121. package/dist/tools/search.d.ts +1 -1
  122. package/dist/tools/search.d.ts.map +1 -1
  123. package/dist/tools/search.js +455 -38
  124. package/dist/tools/search.js.map +1 -1
  125. package/dist/tools/staged-actions.d.ts.map +1 -1
  126. package/dist/tools/staged-actions.js +26 -2
  127. package/dist/tools/staged-actions.js.map +1 -1
  128. package/dist/tools/witness.d.ts.map +1 -1
  129. package/dist/tools/witness.js +78 -7
  130. package/dist/tools/witness.js.map +1 -1
  131. package/dist/tools/write.d.ts +9 -0
  132. package/dist/tools/write.d.ts.map +1 -1
  133. package/dist/tools/write.js +374 -234
  134. package/dist/tools/write.js.map +1 -1
  135. package/dist/utils/config.d.ts +34 -0
  136. package/dist/utils/config.d.ts.map +1 -1
  137. package/dist/utils/config.js +168 -6
  138. package/dist/utils/config.js.map +1 -1
  139. package/dist/utils/git.d.ts +18 -2
  140. package/dist/utils/git.d.ts.map +1 -1
  141. package/dist/utils/git.js +176 -34
  142. package/dist/utils/git.js.map +1 -1
  143. package/dist/utils/vault-gitignore.d.ts +1 -1
  144. package/dist/utils/vault-gitignore.d.ts.map +1 -1
  145. package/dist/utils/vault-gitignore.js +1 -0
  146. package/dist/utils/vault-gitignore.js.map +1 -1
  147. package/dist/witness/track-record.d.ts +23 -0
  148. package/dist/witness/track-record.d.ts.map +1 -1
  149. package/dist/witness/track-record.js +0 -0
  150. package/dist/witness/track-record.js.map +1 -1
  151. package/package.json +1 -1
@@ -3,15 +3,15 @@
3
3
  // principal. Pure logic lives in curation/positions.ts; write plumbing is
4
4
  // reused from write.ts (LD-9) — no duplicated lock/commit/provenance code.
5
5
  import { canRatify, canRead, hasAnyRead, isProposeOnly, } from "../access/rbac.js";
6
- import { applyAssert, comparePositions, conflictPairs, dissentIds, isContested, legacySnapshot, unsuperseded, } from "../curation/positions.js";
6
+ import { applyAssert, comparePositions, conflictPairs, dissentIds, isContested, legacySnapshot, qualifyingDissentTensions, unsuperseded, } from "../curation/positions.js";
7
7
  import { stageActionWithConflictCheck } from "../curation/staged-actions.js";
8
- import { addTension, listTensions, resolveTension, } from "../curation/tension.js";
8
+ import { addTension, listTensions, resolveTension, retryOnTensionLease, } from "../curation/tension.js";
9
9
  import { loadDocuments } from "../curation/vault-docs.js";
10
10
  import { parseDocument } from "../frontmatter/parser.js";
11
11
  import { CONFIDENCES, err, ok, PROVENANCES, STANCES, } from "../frontmatter/types.js";
12
12
  import { readFile, resolveVaultPath } from "../storage/local.js";
13
13
  import { collectionOf } from "./read.js";
14
- import { loadTargetDocument, performFrontmatterWrite, requireIndexReady, requireWriteAccess, targetCollection, } from "./write.js";
14
+ import { loadTargetDocument, performFrontmatterWrite, requireIndexReady, requireWriteAccess, retryOnStale, targetCollection, } from "./write.js";
15
15
  function todayISO() {
16
16
  return new Date().toISOString().slice(0, 10);
17
17
  }
@@ -30,7 +30,10 @@ function optStr(args, field, tool) {
30
30
  return err(new Error(`${tool}: '${field}' must be a string`));
31
31
  return ok(v);
32
32
  }
33
- export async function vaultAssert(vaultRoot, args, access) {
33
+ export async function vaultAssert(vaultRoot, args, access,
34
+ // Test-injectable retry timing for the §3.5 tension-lease retry; invisible
35
+ // to the MCP surface (the tool handler never passes it).
36
+ leaseDeps) {
34
37
  const ready = requireIndexReady();
35
38
  if (!ready.ok)
36
39
  return ready;
@@ -103,137 +106,166 @@ export async function vaultAssert(vaultRoot, args, access) {
103
106
  const writeGate = requireWriteAccess(access, targetCollection(vaultRoot, path.value));
104
107
  if (!writeGate.ok)
105
108
  return writeGate;
106
- // Assert targets an EXISTING claim doc; creating the doc is vault_write's
107
- // job. loadTargetDocument canonicalizes (#127/#128) — one lock, one
108
- // position set per file, however the path is spelled.
109
- const target = await loadTargetDocument(vaultRoot, path.value, "vault_assert");
110
- if (!target.ok)
111
- return target;
112
- const fm = target.value.parsed.frontmatter;
113
- // U-12 / DN-2 / LD-22: the first assert on a legacy doc (typed positions
114
- // null — an explicit `positions: []` means already opted in, no snapshot)
115
- // snapshots the prior authored belief as pos-000 before the caller's own
116
- // position is applied. Guard 2 (applyAssert never self-supersedes across
117
- // principals) means the snapshot is never touched by a live caller's assert.
118
- const basePositions = fm.positions ?? [legacySnapshot(fm)];
119
- const applied = applyAssert(basePositions, {
120
- principal,
121
- stance: stanceRaw.value,
122
- statement: statement.value,
123
- confidence: confidenceRaw.value,
124
- provenance,
125
- valid_from: validFrom.value,
126
- sources,
127
- created: todayISO(),
128
- });
129
- const contested = isContested(applied.positions);
130
- const capConfidence = contested && fm.org_position == null; // R-9
131
- const newFrontmatter = {
132
- ...fm,
133
- positions: applied.positions,
134
- contested, // R-8: recomputed on every assert; hand-set values overwritten
135
- ...(capConfidence ? { confidence: "low" } : {}),
136
- updated: todayISO(),
137
- updated_by: agent.value,
138
- };
139
- // R-13: a propose-only role's assert lands as a staged `write` proposal —
140
- // no file write, no positional tension yet (it fires when the ratified
141
- // write lands). Contention with other pending proposals is surfaced by
142
- // stageActionWithConflictCheck's inter-proposal tension.
143
- if (access && isProposeOnly(access.role)) {
144
- const staged = await stageActionWithConflictCheck(vaultRoot, {
145
- actionType: "write",
146
- targetPath: target.value.relPath,
147
- proposedBy: agent.value,
148
- rationale: `propose-only role '${access.roleName}': position ${stanceRaw.value} by ` +
149
- `'${principal}' staged for ratification`,
150
- proposedDiff: {
151
- frontmatter: {
152
- positions: applied.positions,
109
+ const attemptAssert = async () => {
110
+ // Assert targets an EXISTING claim doc; creating the doc is vault_write's
111
+ // job. loadTargetDocument canonicalizes (#127/#128) — one lock, one
112
+ // position set per file, however the path is spelled.
113
+ const target = await loadTargetDocument(vaultRoot, path.value, "vault_assert");
114
+ if (!target.ok)
115
+ return target;
116
+ const fm = target.value.parsed.frontmatter;
117
+ // U-12 / DN-2 / LD-22: the first assert on a legacy doc (typed positions
118
+ // null — an explicit `positions: []` means already opted in, no snapshot)
119
+ // snapshots the prior authored belief as pos-000 before the caller's own
120
+ // position is applied. Guard 2 (applyAssert never self-supersedes across
121
+ // principals) means the snapshot is never touched by a live caller's assert.
122
+ const basePositions = fm.positions ?? [legacySnapshot(fm)];
123
+ const applied = applyAssert(basePositions, {
124
+ principal,
125
+ stance: stanceRaw.value,
126
+ statement: statement.value,
127
+ confidence: confidenceRaw.value,
128
+ provenance,
129
+ valid_from: validFrom.value,
130
+ sources,
131
+ created: todayISO(),
132
+ });
133
+ const contested = isContested(applied.positions);
134
+ const capConfidence = contested && fm.org_position == null; // R-9
135
+ const newFrontmatter = {
136
+ ...fm,
137
+ positions: applied.positions,
138
+ contested, // R-8: recomputed on every assert; hand-set values overwritten
139
+ ...(capConfidence ? { confidence: "low" } : {}),
140
+ updated: todayISO(),
141
+ updated_by: agent.value,
142
+ };
143
+ // R-13: a propose-only role's assert lands as a staged `write` proposal —
144
+ // no file write, no positional tension yet (it fires when the ratified
145
+ // write lands). Contention with other pending proposals is surfaced by
146
+ // stageActionWithConflictCheck's inter-proposal tension.
147
+ if (access && isProposeOnly(access.role)) {
148
+ const staged = await stageActionWithConflictCheck(vaultRoot, {
149
+ actionType: "write",
150
+ targetPath: target.value.relPath,
151
+ proposedBy: agent.value,
152
+ rationale: `propose-only role '${access.roleName}': position ${stanceRaw.value} by ` +
153
+ `'${principal}' staged for ratification`,
154
+ proposedDiff: {
155
+ frontmatter: {
156
+ positions: applied.positions,
157
+ contested,
158
+ ...(capConfidence ? { confidence: "low" } : {}),
159
+ },
160
+ body: target.value.parsed.content,
161
+ },
162
+ // LD-13 ratify staleness guard: proposedDiff.frontmatter.positions is a
163
+ // FULL array snapshotted from `target` above. Anchor the proposal to
164
+ // the exact bytes it was computed from so a ratify replay against a
165
+ // document that changed since staging fails loudly (stale write)
166
+ // instead of silently overwriting whatever landed in between.
167
+ baseVersion: target.value.contentHash,
168
+ ...(runIdArg.value !== null ? { runId: runIdArg.value } : {}),
169
+ });
170
+ if (!staged.ok)
171
+ return staged;
172
+ return ok({
173
+ kind: "staged",
174
+ result: {
175
+ path: target.value.relPath,
176
+ action: "staged",
177
+ position: applied.newPosition,
178
+ superseded_position_id: applied.superseded?.id ?? null,
153
179
  contested,
154
- ...(capConfidence ? { confidence: "low" } : {}),
180
+ tension_ids: [],
181
+ commit: null,
182
+ committed: false,
183
+ staged_id: staged.value.id,
184
+ expires_at: staged.value.expires_at,
185
+ conflicts_with: staged.value.conflicts_with,
155
186
  },
156
- body: target.value.parsed.content,
157
- },
187
+ });
188
+ }
189
+ const written = await performFrontmatterWrite({
190
+ vaultRoot,
191
+ target: target.value,
192
+ agent: agent.value,
193
+ tool: "vault_assert",
194
+ action: "assert",
195
+ newFrontmatter,
196
+ commitMessage: `vault_assert: ${stanceRaw.value} on ${target.value.relPath} by ${principal}`,
197
+ baseVersion: target.value.contentHash,
198
+ access,
158
199
  ...(runIdArg.value !== null ? { runId: runIdArg.value } : {}),
159
200
  });
160
- if (!staged.ok)
161
- return staged;
201
+ if (!written.ok)
202
+ return written;
162
203
  return ok({
163
- path: target.value.relPath,
164
- action: "staged",
165
- position: applied.newPosition,
166
- superseded_position_id: applied.superseded?.id ?? null,
204
+ kind: "written",
205
+ relPath: target.value.relPath,
206
+ title: fm.title,
207
+ applied,
167
208
  contested,
168
- tension_ids: [],
169
- commit: null,
170
- committed: false,
171
- staged_id: staged.value.id,
172
- expires_at: staged.value.expires_at,
173
- conflicts_with: staged.value.conflicts_with,
209
+ written: written.value,
174
210
  });
175
- }
176
- const written = await performFrontmatterWrite({
177
- vaultRoot,
178
- target: target.value,
179
- agent: agent.value,
180
- tool: "vault_assert",
181
- action: "assert",
182
- newFrontmatter,
183
- commitMessage: `vault_assert: ${stanceRaw.value} on ${target.value.relPath} by ${principal}`,
184
- baseVersion: undefined,
185
- access,
186
- ...(runIdArg.value !== null ? { runId: runIdArg.value } : {}),
187
- });
188
- if (!written.ok)
189
- return written;
211
+ };
212
+ const attempt = await retryOnStale(attemptAssert);
213
+ if (!attempt.ok)
214
+ return attempt;
215
+ if (attempt.value.kind === "staged")
216
+ return ok(attempt.value.result);
217
+ const { relPath, title, applied, contested, written } = attempt.value;
190
218
  // R-5 + locked R-3: one binary tension per NEW conflicting pair, skipped
191
219
  // when an OPEN positional tension already names the same two ids on this
192
220
  // doc. loggedBy = the asserting principal (DN-3) — the loop-authored
193
- // ratify gate (CONSOLIDATE_AGENT) never fires on these.
221
+ // ratify gate (CONSOLIDATE_AGENT) never fires on these. Each pair's
222
+ // list→covered→mint runs as one retryOnTensionLease attempt (slice-3
223
+ // §3.5's bounded jittered retry — this contention is system-generated,
224
+ // never caller-visible), with the coverage re-check INSIDE the attempt so
225
+ // a retry never double-mints.
194
226
  const tensionIds = [];
195
227
  let tensionError;
196
228
  const pairs = conflictPairs(applied.newPosition, applied.positions);
197
- if (pairs.length > 0) {
198
- const existing = await listTensions(vaultRoot);
199
- if (!existing.ok) {
200
- tensionError = existing.error.message;
201
- }
202
- else {
203
- const open = existing.value.filter((t) => t.kind === "positional" && !t.resolved && t.sourceA === target.value.relPath);
204
- const covered = (a, b) => open.some((t) => (t.positionA === a && t.positionB === b) || (t.positionA === b && t.positionB === a));
205
- const claim = (p) => p.statement ?? `${fm.title} — ${p.stance} (${p.confidence})`;
206
- for (const pair of pairs) {
207
- if (covered(pair.a.id, pair.b.id))
208
- continue;
209
- const minted = await addTension(vaultRoot, {
210
- kind: "positional",
211
- title: `Positional: ${pair.a.principal} vs ${pair.b.principal} on ${fm.title}`,
212
- sourceA: target.value.relPath,
213
- claimA: claim(pair.a),
214
- sourceB: target.value.relPath,
215
- claimB: claim(pair.b),
216
- positionA: pair.a.id,
217
- positionB: pair.b.id,
218
- loggedBy: principal,
219
- });
220
- if (minted.ok)
221
- tensionIds.push(minted.value.id);
222
- else
223
- tensionError = minted.error.message;
224
- }
225
- }
229
+ const claim = (p) => p.statement ?? `${title} — ${p.stance} (${p.confidence})`;
230
+ for (const pair of pairs) {
231
+ const minted = await retryOnTensionLease(async () => {
232
+ const existing = await listTensions(vaultRoot);
233
+ if (!existing.ok)
234
+ return existing;
235
+ const covered = existing.value.some((t) => t.kind === "positional" &&
236
+ !t.resolved &&
237
+ t.sourceA === relPath &&
238
+ ((t.positionA === pair.a.id && t.positionB === pair.b.id) ||
239
+ (t.positionA === pair.b.id && t.positionB === pair.a.id)));
240
+ if (covered)
241
+ return ok(null);
242
+ return addTension(vaultRoot, {
243
+ kind: "positional",
244
+ title: `Positional: ${pair.a.principal} vs ${pair.b.principal} on ${title}`,
245
+ sourceA: relPath,
246
+ claimA: claim(pair.a),
247
+ sourceB: relPath,
248
+ claimB: claim(pair.b),
249
+ positionA: pair.a.id,
250
+ positionB: pair.b.id,
251
+ loggedBy: principal,
252
+ });
253
+ }, leaseDeps);
254
+ if (!minted.ok)
255
+ tensionError = minted.error.message;
256
+ else if (minted.value)
257
+ tensionIds.push(minted.value.id);
226
258
  }
227
259
  return ok({
228
- path: target.value.relPath,
260
+ path: relPath,
229
261
  action: "assert",
230
262
  position: applied.newPosition,
231
263
  superseded_position_id: applied.superseded?.id ?? null,
232
264
  contested,
233
265
  tension_ids: tensionIds,
234
266
  ...(tensionError !== undefined ? { tension_error: tensionError } : {}),
235
- commit: written.value.commit,
236
- committed: written.value.committed,
267
+ commit: written.commit,
268
+ committed: written.committed,
237
269
  });
238
270
  }
239
271
  // The subset of RESOLUTION_KINDS vault_consolidate accepts for its in-call
@@ -248,7 +280,9 @@ const CONSOLIDATABLE_RESOLUTION_KINDS = ["superseded", "corrected", "accepted"];
248
280
  // Optionally resolves one open positional tension on this doc in the same
249
281
  // call (LD-19): validated BEFORE the write; the write commits first, and a
250
282
  // resolve failure afterward is reported as resolve_error, never rolled back.
251
- export async function vaultConsolidate(vaultRoot, args, access) {
283
+ export async function vaultConsolidate(vaultRoot, args, access,
284
+ // Test-injectable retry timing for the §3.5 tension-lease retry.
285
+ leaseDeps) {
252
286
  const ready = requireIndexReady();
253
287
  if (!ready.ok)
254
288
  return ready;
@@ -299,6 +333,22 @@ export async function vaultConsolidate(vaultRoot, args, access) {
299
333
  ...(rationaleRes.value !== null ? { rationale: rationaleRes.value } : {}),
300
334
  };
301
335
  }
336
+ // Batch resolve: no ids, no kind — both server-derived from the
337
+ // ratification itself, which is why this is not LD-19's "backdoor generic
338
+ // resolver": a resolver you cannot aim at an arbitrary tension is not a
339
+ // backdoor. A `qualify` ratification carries no dissent, so there is
340
+ // nothing for the batch to adjudicate — rejected loudly.
341
+ let batchDissent = false;
342
+ if (args.resolve_tensions !== undefined && args.resolve_tensions !== null) {
343
+ if (args.resolve_tensions !== "dissent") {
344
+ return err(new Error(`vault_consolidate: 'resolve_tensions' must be "dissent"`));
345
+ }
346
+ if (stanceRaw.value === "qualify") {
347
+ return err(new Error("vault_consolidate: resolve_tensions with stance 'qualify' — qualify opposes " +
348
+ "nothing, so there is no dissent to adjudicate"));
349
+ }
350
+ batchDissent = true;
351
+ }
302
352
  // LD-25: same identity shape as vault_assert's R-3 operator rule, but the
303
353
  // resolved identity here is the RATIFIER, not a position's principal.
304
354
  const principalArg = optStr(args, "principal", "vault_consolidate");
@@ -334,62 +384,98 @@ export async function vaultConsolidate(vaultRoot, args, access) {
334
384
  if (access && !canRatify(access.role)) {
335
385
  return err(new Error(`access denied: role '${access.roleName}' cannot consolidate`));
336
386
  }
337
- const target = await loadTargetDocument(vaultRoot, path.value, "vault_consolidate");
338
- if (!target.ok)
339
- return target;
340
- const fm = target.value.parsed.frontmatter;
341
- const dissent = dissentIds(fm.positions ?? [], stanceRaw.value);
342
- // LD-19: resolve_tension is validated BEFORE any write. The id must name
343
- // an OPEN tension with kind "positional" and sourceA === this doc — never
344
- // a backdoor generic resolver.
345
- if (resolveTensionArg) {
346
- const all = await listTensions(vaultRoot);
347
- if (!all.ok)
348
- return all;
349
- const t = all.value.find((x) => x.id === resolveTensionArg?.id);
350
- if (!t || t.resolved || t.kind !== "positional" || t.sourceA !== target.value.relPath) {
351
- return err(new Error("vault_consolidate: resolve_tension does not name an open positional tension " +
352
- "on this document"));
353
- }
354
- if (resolveTensionArg.kind === "accepted" && dissent.length === 0) {
355
- return err(new Error("vault_consolidate: resolve_tension kind 'accepted' requires standing dissent"));
387
+ const attemptConsolidate = async () => {
388
+ const target = await loadTargetDocument(vaultRoot, path.value, "vault_consolidate");
389
+ if (!target.ok)
390
+ return target;
391
+ const fm = target.value.parsed.frontmatter;
392
+ const dissent = dissentIds(fm.positions ?? [], stanceRaw.value);
393
+ // LD-19: resolve_tension is validated BEFORE any write. The id must name
394
+ // an OPEN tension with kind "positional" and sourceA === this doc — never
395
+ // a backdoor generic resolver.
396
+ let batchIds = [];
397
+ if (resolveTensionArg || batchDissent) {
398
+ const all = await listTensions(vaultRoot);
399
+ if (!all.ok)
400
+ return all;
401
+ if (resolveTensionArg) {
402
+ const t = all.value.find((x) => x.id === resolveTensionArg?.id);
403
+ if (!t || t.resolved || t.kind !== "positional" || t.sourceA !== target.value.relPath) {
404
+ return err(new Error("vault_consolidate: resolve_tension does not name an open positional tension " +
405
+ "on this document"));
406
+ }
407
+ if (resolveTensionArg.kind === "accepted" && dissent.length === 0) {
408
+ return err(new Error("vault_consolidate: resolve_tension kind 'accepted' requires standing dissent"));
409
+ }
410
+ }
411
+ // The batch's qualifying set, computed from the SAME snapshot that
412
+ // computes dissent (so retryOnStale recomputes both together): open
413
+ // positional tensions on this doc whose chain-resolved losing end is
414
+ // in the dissent this ratification carries. The single resolve_tension
415
+ // id keeps its deliberate kind — the batch skips it.
416
+ if (batchDissent) {
417
+ const open = all.value.filter((t) => t.kind === "positional" &&
418
+ !t.resolved &&
419
+ t.sourceA === target.value.relPath &&
420
+ t.positionA !== undefined &&
421
+ t.positionB !== undefined &&
422
+ t.id !== resolveTensionArg?.id);
423
+ batchIds = qualifyingDissentTensions(fm.positions ?? [], stanceRaw.value, dissent, open.map((t) => ({
424
+ id: t.id,
425
+ resolved: t.resolved,
426
+ positionA: t.positionA,
427
+ positionB: t.positionB,
428
+ })));
429
+ }
356
430
  }
357
- }
358
- const orgPosition = {
359
- stance: stanceRaw.value,
360
- confidence: confidenceRaw.value,
361
- ratified_by: ratifier,
362
- ratified_at: todayISO(),
363
- dissent,
364
- };
365
- // LD-21: contested is re-derived from the live set, never touched by
366
- // consolidate itself; a fully legacy doc (positions null) stays null.
367
- const contested = fm.positions != null ? isContested(fm.positions) : null;
368
- const newFrontmatter = {
369
- ...fm,
370
- org_position: orgPosition,
371
- confidence: confidenceRaw.value, // the mirror — clears the R-9 cap
372
- contested,
373
- updated: todayISO(),
374
- updated_by: agent.value,
431
+ const orgPosition = {
432
+ stance: stanceRaw.value,
433
+ confidence: confidenceRaw.value,
434
+ ratified_by: ratifier,
435
+ ratified_at: todayISO(),
436
+ dissent,
437
+ };
438
+ // LD-21: contested is re-derived from the live set, never touched by
439
+ // consolidate itself; a fully legacy doc (positions null) stays null.
440
+ const contested = fm.positions != null ? isContested(fm.positions) : null;
441
+ const newFrontmatter = {
442
+ ...fm,
443
+ org_position: orgPosition,
444
+ confidence: confidenceRaw.value, // the mirror — clears the R-9 cap
445
+ contested,
446
+ updated: todayISO(),
447
+ updated_by: agent.value,
448
+ };
449
+ const written = await performFrontmatterWrite({
450
+ vaultRoot,
451
+ target: target.value,
452
+ agent: agent.value,
453
+ tool: "vault_consolidate",
454
+ action: "consolidate",
455
+ newFrontmatter,
456
+ commitMessage: `vault_consolidate: ${stanceRaw.value} on ${target.value.relPath} ratified by ${ratifier}`,
457
+ baseVersion: target.value.contentHash,
458
+ access,
459
+ ...(runIdArg.value !== null ? { runId: runIdArg.value } : {}),
460
+ });
461
+ if (!written.ok)
462
+ return written;
463
+ return ok({
464
+ relPath: target.value.relPath,
465
+ orgPosition,
466
+ dissent,
467
+ contested,
468
+ batchIds,
469
+ written: written.value,
470
+ });
375
471
  };
376
- const written = await performFrontmatterWrite({
377
- vaultRoot,
378
- target: target.value,
379
- agent: agent.value,
380
- tool: "vault_consolidate",
381
- action: "consolidate",
382
- newFrontmatter,
383
- commitMessage: `vault_consolidate: ${stanceRaw.value} on ${target.value.relPath} ratified by ${ratifier}`,
384
- baseVersion: undefined,
385
- access,
386
- ...(runIdArg.value !== null ? { runId: runIdArg.value } : {}),
387
- });
388
- if (!written.ok)
389
- return written;
472
+ const attempt = await retryOnStale(attemptConsolidate);
473
+ if (!attempt.ok)
474
+ return attempt;
475
+ const { relPath, orgPosition, dissent, contested, batchIds, written } = attempt.value;
390
476
  // The doc write commits FIRST; a resolve failure afterward is reported as
391
477
  // resolve_error, not rolled back (LD-19 — mirror of Slice 1's tension_error
392
- // channel).
478
+ // channel). Resolutions ride the §3.5 bounded tension-lease retry.
393
479
  let resolvedTensionId = null;
394
480
  let resolveError;
395
481
  if (resolveTensionArg) {
@@ -401,14 +487,35 @@ export async function vaultConsolidate(vaultRoot, args, access) {
401
487
  ? { rationale: resolveTensionArg.rationale }
402
488
  : {}),
403
489
  };
404
- const resolved = await resolveTension(vaultRoot, resolveTensionArg.id, resolution);
490
+ const resolved = await retryOnTensionLease(() => resolveTension(vaultRoot, resolveTensionArg.id, resolution), leaseDeps);
405
491
  if (resolved.ok)
406
492
  resolvedTensionId = resolveTensionArg.id;
407
493
  else
408
494
  resolveError = resolved.error.message;
409
495
  }
496
+ // The batch: each qualifying tension resolves `consolidated` — the honest
497
+ // record that the pairwise conflict is subsumed by this ratification, the
498
+ // dissent carried in org_position (never `superseded`: the disagreement
499
+ // persists; never blanket `accepted`: standing immunity stays a deliberate
500
+ // per-pair grant). Per-id failures never unwind the ratification.
501
+ const resolvedTensionIds = [];
502
+ const resolveErrors = [];
503
+ for (const id of batchIds) {
504
+ const resolved = await retryOnTensionLease(() => resolveTension(vaultRoot, id, {
505
+ resolved_at: new Date().toISOString(),
506
+ resolved_by: ratifier,
507
+ kind: "consolidated",
508
+ rationale: `org_position ratified ${stanceRaw.value} by ${ratifier} ${todayISO()}; ` +
509
+ `dissent carried: ${dissent.join(", ")}`,
510
+ references: [relPath],
511
+ }), leaseDeps);
512
+ if (resolved.ok)
513
+ resolvedTensionIds.push(id);
514
+ else
515
+ resolveErrors.push({ id, error: resolved.error.message });
516
+ }
410
517
  return ok({
411
- path: target.value.relPath,
518
+ path: relPath,
412
519
  action: "consolidate",
413
520
  org_position: orgPosition,
414
521
  confidence: confidenceRaw.value,
@@ -416,8 +523,10 @@ export async function vaultConsolidate(vaultRoot, args, access) {
416
523
  contested,
417
524
  resolved_tension_id: resolvedTensionId,
418
525
  ...(resolveError !== undefined ? { resolve_error: resolveError } : {}),
419
- commit: written.value.commit,
420
- committed: written.value.committed,
526
+ resolved_tension_ids: resolvedTensionIds,
527
+ resolve_errors: resolveErrors,
528
+ commit: written.commit,
529
+ committed: written.committed,
421
530
  });
422
531
  }
423
532
  export async function vaultPositions(vaultRoot, args, access) {
@@ -537,7 +646,10 @@ const assertToolDefinition = {
537
646
  "'write' proposal for ratification — nothing is written and no positional " +
538
647
  "tension is logged until the ratified write lands. The first assert on a " +
539
648
  "legacy doc (typed positions null) snapshots the doc's prior belief as " +
540
- "pos-000 (principal 'unknown', system-authored, unforgeable).",
649
+ "pos-000 (principal 'unknown', system-authored, unforgeable). Under " +
650
+ "concurrent writes to the same doc the call retries once against the " +
651
+ "fresh state, then fails loudly ('locked' or 'stale write') — safe to " +
652
+ "re-call; no position is ever silently overwritten.",
541
653
  inputSchema: {
542
654
  type: "object",
543
655
  properties: {
@@ -645,7 +757,17 @@ const consolidateToolDefinition = {
645
757
  "same call via resolve_tension: validated before any write (must name an " +
646
758
  "open 'positional' tension whose sourceA is this doc; kind 'accepted' " +
647
759
  "requires standing dissent); the doc write commits first, and a resolve " +
648
- "failure afterward is reported as resolve_error, never rolled back.",
760
+ "failure afterward is reported as resolve_error, never rolled back. " +
761
+ "resolve_tensions: 'dissent' batch-resolves EVERY open positional tension " +
762
+ "this ratification adjudicates — chain-following superseded dissent — " +
763
+ "with the system-only kind 'consolidated' (the disagreement persists, " +
764
+ "carried as dissent in org_position; standing 'accepted' immunity stays " +
765
+ "a deliberate per-pair grant via resolve_tension, which composes and is " +
766
+ "skipped by the batch). Rejected when ratifying 'qualify' (no dissent to " +
767
+ "adjudicate); moot pairs (a stance flip) stay open for lint. Under " +
768
+ "concurrent writes to the same doc the call retries once against the " +
769
+ "fresh state (dissent and the batch set recomputed), then fails loudly " +
770
+ "('locked' or 'stale write') — safe to re-call.",
649
771
  inputSchema: {
650
772
  type: "object",
651
773
  properties: {
@@ -670,6 +792,12 @@ const consolidateToolDefinition = {
670
792
  required: ["id", "kind"],
671
793
  additionalProperties: false,
672
794
  },
795
+ resolve_tensions: {
796
+ type: "string",
797
+ enum: ["dissent"],
798
+ description: "Batch-resolve every open positional tension adjudicated by this " +
799
+ "ratification's dissent, recorded as kind 'consolidated'.",
800
+ },
673
801
  },
674
802
  required: ["path", "stance", "confidence", "agent"],
675
803
  additionalProperties: false,
@@ -685,6 +813,20 @@ const consolidateToolDefinition = {
685
813
  contested: { type: ["boolean", "null"] },
686
814
  resolved_tension_id: { type: ["string", "null"] },
687
815
  resolve_error: { type: "string" },
816
+ resolved_tension_ids: {
817
+ type: "array",
818
+ items: { type: "string" },
819
+ description: "Batch-resolved tension ids; [] when resolve_tensions not requested",
820
+ },
821
+ resolve_errors: {
822
+ type: "array",
823
+ items: {
824
+ type: "object",
825
+ properties: { id: { type: "string" }, error: { type: "string" } },
826
+ required: ["id", "error"],
827
+ additionalProperties: false,
828
+ },
829
+ },
688
830
  commit: { type: ["string", "null"] },
689
831
  committed: { type: "boolean" },
690
832
  },
@@ -696,6 +838,8 @@ const consolidateToolDefinition = {
696
838
  "dissent",
697
839
  "contested",
698
840
  "resolved_tension_id",
841
+ "resolved_tension_ids",
842
+ "resolve_errors",
699
843
  "commit",
700
844
  "committed",
701
845
  ],