daftari 3.4.0 → 3.6.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 (129) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +59 -5
  3. package/dist/consolidate/decorrelation.js +1 -1
  4. package/dist/consolidate/decorrelation.js.map +1 -1
  5. package/dist/consolidate/index.js +1 -1
  6. package/dist/court/index.d.ts.map +1 -1
  7. package/dist/court/index.js +5 -3
  8. package/dist/court/index.js.map +1 -1
  9. package/dist/curation/lint.d.ts.map +1 -1
  10. package/dist/curation/lint.js +68 -1
  11. package/dist/curation/lint.js.map +1 -1
  12. package/dist/curation/positions.d.ts +14 -0
  13. package/dist/curation/positions.d.ts.map +1 -1
  14. package/dist/curation/positions.js +74 -0
  15. package/dist/curation/positions.js.map +1 -1
  16. package/dist/curation/provenance.d.ts.map +1 -1
  17. package/dist/curation/provenance.js.map +1 -1
  18. package/dist/curation/tension.d.ts +9 -1
  19. package/dist/curation/tension.d.ts.map +1 -1
  20. package/dist/curation/tension.js +34 -1
  21. package/dist/curation/tension.js.map +1 -1
  22. package/dist/federation/classification.d.ts +9 -0
  23. package/dist/federation/classification.d.ts.map +1 -0
  24. package/dist/federation/classification.js +122 -0
  25. package/dist/federation/classification.js.map +1 -0
  26. package/dist/federation/index-location.d.ts +4 -0
  27. package/dist/federation/index-location.d.ts.map +1 -0
  28. package/dist/federation/index-location.js +30 -0
  29. package/dist/federation/index-location.js.map +1 -0
  30. package/dist/federation/mount-index.d.ts +8 -0
  31. package/dist/federation/mount-index.d.ts.map +1 -0
  32. package/dist/federation/mount-index.js +63 -0
  33. package/dist/federation/mount-index.js.map +1 -0
  34. package/dist/federation/mounts.d.ts +29 -0
  35. package/dist/federation/mounts.d.ts.map +1 -0
  36. package/dist/federation/mounts.js +215 -0
  37. package/dist/federation/mounts.js.map +1 -0
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +27 -0
  40. package/dist/index.js.map +1 -1
  41. package/dist/search/hybrid.d.ts +10 -0
  42. package/dist/search/hybrid.d.ts.map +1 -1
  43. package/dist/search/hybrid.js +28 -15
  44. package/dist/search/hybrid.js.map +1 -1
  45. package/dist/search/reindex.d.ts +2 -0
  46. package/dist/search/reindex.d.ts.map +1 -1
  47. package/dist/search/reindex.js +17 -9
  48. package/dist/search/reindex.js.map +1 -1
  49. package/dist/serve/auth-log.d.ts +16 -0
  50. package/dist/serve/auth-log.d.ts.map +1 -0
  51. package/dist/serve/auth-log.js +53 -0
  52. package/dist/serve/auth-log.js.map +1 -0
  53. package/dist/serve/index.d.ts +2 -0
  54. package/dist/serve/index.d.ts.map +1 -1
  55. package/dist/serve/index.js +128 -10
  56. package/dist/serve/index.js.map +1 -1
  57. package/dist/serve/limits.d.ts +37 -0
  58. package/dist/serve/limits.d.ts.map +1 -0
  59. package/dist/serve/limits.js +79 -0
  60. package/dist/serve/limits.js.map +1 -0
  61. package/dist/server.d.ts.map +1 -1
  62. package/dist/server.js +20 -0
  63. package/dist/server.js.map +1 -1
  64. package/dist/storage/index-db.d.ts.map +1 -1
  65. package/dist/storage/index-db.js +9 -3
  66. package/dist/storage/index-db.js.map +1 -1
  67. package/dist/tools/curation.d.ts.map +1 -1
  68. package/dist/tools/curation.js +6 -5
  69. package/dist/tools/curation.js.map +1 -1
  70. package/dist/tools/positions.d.ts +8 -2
  71. package/dist/tools/positions.d.ts.map +1 -1
  72. package/dist/tools/positions.js +311 -173
  73. package/dist/tools/positions.js.map +1 -1
  74. package/dist/tools/read.d.ts +11 -0
  75. package/dist/tools/read.d.ts.map +1 -1
  76. package/dist/tools/read.js +188 -10
  77. package/dist/tools/read.js.map +1 -1
  78. package/dist/tools/search.d.ts +1 -1
  79. package/dist/tools/search.d.ts.map +1 -1
  80. package/dist/tools/search.js +455 -38
  81. package/dist/tools/search.js.map +1 -1
  82. package/dist/tools/witness.d.ts.map +1 -1
  83. package/dist/tools/witness.js +78 -7
  84. package/dist/tools/witness.js.map +1 -1
  85. package/dist/tools/write.d.ts +8 -0
  86. package/dist/tools/write.d.ts.map +1 -1
  87. package/dist/tools/write.js +71 -9
  88. package/dist/tools/write.js.map +1 -1
  89. package/dist/utils/config.d.ts +26 -0
  90. package/dist/utils/config.d.ts.map +1 -1
  91. package/dist/utils/config.js +152 -5
  92. package/dist/utils/config.js.map +1 -1
  93. package/dist/utils/git.d.ts.map +1 -1
  94. package/dist/utils/git.js +65 -26
  95. package/dist/utils/git.js.map +1 -1
  96. package/dist/utils/vault-gitignore.d.ts +1 -1
  97. package/dist/utils/vault-gitignore.d.ts.map +1 -1
  98. package/dist/utils/vault-gitignore.js +1 -0
  99. package/dist/utils/vault-gitignore.js.map +1 -1
  100. package/dist/view/doc-view.d.ts +21 -0
  101. package/dist/view/doc-view.d.ts.map +1 -0
  102. package/dist/view/doc-view.js +53 -0
  103. package/dist/view/doc-view.js.map +1 -0
  104. package/dist/view/graph.d.ts +52 -0
  105. package/dist/view/graph.d.ts.map +1 -0
  106. package/dist/view/graph.js +133 -0
  107. package/dist/view/graph.js.map +1 -0
  108. package/dist/view/pages.d.ts +34 -16
  109. package/dist/view/pages.d.ts.map +1 -1
  110. package/dist/view/pages.js +435 -83
  111. package/dist/view/pages.js.map +1 -1
  112. package/dist/view/render.d.ts +11 -0
  113. package/dist/view/render.d.ts.map +1 -1
  114. package/dist/view/render.js +77 -0
  115. package/dist/view/render.js.map +1 -1
  116. package/dist/view/server.d.ts +1 -0
  117. package/dist/view/server.d.ts.map +1 -1
  118. package/dist/view/server.js +214 -48
  119. package/dist/view/server.js.map +1 -1
  120. package/dist/view/status-view.d.ts +32 -0
  121. package/dist/view/status-view.d.ts.map +1 -0
  122. package/dist/view/status-view.js +39 -0
  123. package/dist/view/status-view.js.map +1 -0
  124. package/dist/witness/track-record.d.ts +23 -0
  125. package/dist/witness/track-record.d.ts.map +1 -1
  126. package/dist/witness/track-record.js +0 -0
  127. package/dist/witness/track-record.js.map +1 -1
  128. package/package.json +1 -1
  129. package/templates/view/cytoscape.min.js +31 -0
@@ -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,160 @@ 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
+ ...(runIdArg.value !== null ? { runId: runIdArg.value } : {}),
163
+ });
164
+ if (!staged.ok)
165
+ return staged;
166
+ return ok({
167
+ kind: "staged",
168
+ result: {
169
+ path: target.value.relPath,
170
+ action: "staged",
171
+ position: applied.newPosition,
172
+ superseded_position_id: applied.superseded?.id ?? null,
153
173
  contested,
154
- ...(capConfidence ? { confidence: "low" } : {}),
174
+ tension_ids: [],
175
+ commit: null,
176
+ committed: false,
177
+ staged_id: staged.value.id,
178
+ expires_at: staged.value.expires_at,
179
+ conflicts_with: staged.value.conflicts_with,
155
180
  },
156
- body: target.value.parsed.content,
157
- },
181
+ });
182
+ }
183
+ const written = await performFrontmatterWrite({
184
+ vaultRoot,
185
+ target: target.value,
186
+ agent: agent.value,
187
+ tool: "vault_assert",
188
+ action: "assert",
189
+ newFrontmatter,
190
+ commitMessage: `vault_assert: ${stanceRaw.value} on ${target.value.relPath} by ${principal}`,
191
+ baseVersion: target.value.contentHash,
192
+ access,
158
193
  ...(runIdArg.value !== null ? { runId: runIdArg.value } : {}),
159
194
  });
160
- if (!staged.ok)
161
- return staged;
195
+ if (!written.ok)
196
+ return written;
162
197
  return ok({
163
- path: target.value.relPath,
164
- action: "staged",
165
- position: applied.newPosition,
166
- superseded_position_id: applied.superseded?.id ?? null,
198
+ kind: "written",
199
+ relPath: target.value.relPath,
200
+ title: fm.title,
201
+ applied,
167
202
  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,
203
+ written: written.value,
174
204
  });
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;
205
+ };
206
+ const attempt = await retryOnStale(attemptAssert);
207
+ if (!attempt.ok)
208
+ return attempt;
209
+ if (attempt.value.kind === "staged")
210
+ return ok(attempt.value.result);
211
+ const { relPath, title, applied, contested, written } = attempt.value;
190
212
  // R-5 + locked R-3: one binary tension per NEW conflicting pair, skipped
191
213
  // when an OPEN positional tension already names the same two ids on this
192
214
  // doc. loggedBy = the asserting principal (DN-3) — the loop-authored
193
- // ratify gate (CONSOLIDATE_AGENT) never fires on these.
215
+ // ratify gate (CONSOLIDATE_AGENT) never fires on these. Each pair's
216
+ // list→covered→mint runs as one retryOnTensionLease attempt (slice-3
217
+ // §3.5's bounded jittered retry — this contention is system-generated,
218
+ // never caller-visible), with the coverage re-check INSIDE the attempt so
219
+ // a retry never double-mints.
194
220
  const tensionIds = [];
195
221
  let tensionError;
196
222
  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
- }
223
+ const claim = (p) => p.statement ?? `${title} — ${p.stance} (${p.confidence})`;
224
+ for (const pair of pairs) {
225
+ const minted = await retryOnTensionLease(async () => {
226
+ const existing = await listTensions(vaultRoot);
227
+ if (!existing.ok)
228
+ return existing;
229
+ const covered = existing.value.some((t) => t.kind === "positional" &&
230
+ !t.resolved &&
231
+ t.sourceA === relPath &&
232
+ ((t.positionA === pair.a.id && t.positionB === pair.b.id) ||
233
+ (t.positionA === pair.b.id && t.positionB === pair.a.id)));
234
+ if (covered)
235
+ return ok(null);
236
+ return addTension(vaultRoot, {
237
+ kind: "positional",
238
+ title: `Positional: ${pair.a.principal} vs ${pair.b.principal} on ${title}`,
239
+ sourceA: relPath,
240
+ claimA: claim(pair.a),
241
+ sourceB: relPath,
242
+ claimB: claim(pair.b),
243
+ positionA: pair.a.id,
244
+ positionB: pair.b.id,
245
+ loggedBy: principal,
246
+ });
247
+ }, leaseDeps);
248
+ if (!minted.ok)
249
+ tensionError = minted.error.message;
250
+ else if (minted.value)
251
+ tensionIds.push(minted.value.id);
226
252
  }
227
253
  return ok({
228
- path: target.value.relPath,
254
+ path: relPath,
229
255
  action: "assert",
230
256
  position: applied.newPosition,
231
257
  superseded_position_id: applied.superseded?.id ?? null,
232
258
  contested,
233
259
  tension_ids: tensionIds,
234
260
  ...(tensionError !== undefined ? { tension_error: tensionError } : {}),
235
- commit: written.value.commit,
236
- committed: written.value.committed,
261
+ commit: written.commit,
262
+ committed: written.committed,
237
263
  });
238
264
  }
239
265
  // The subset of RESOLUTION_KINDS vault_consolidate accepts for its in-call
@@ -248,7 +274,9 @@ const CONSOLIDATABLE_RESOLUTION_KINDS = ["superseded", "corrected", "accepted"];
248
274
  // Optionally resolves one open positional tension on this doc in the same
249
275
  // call (LD-19): validated BEFORE the write; the write commits first, and a
250
276
  // resolve failure afterward is reported as resolve_error, never rolled back.
251
- export async function vaultConsolidate(vaultRoot, args, access) {
277
+ export async function vaultConsolidate(vaultRoot, args, access,
278
+ // Test-injectable retry timing for the §3.5 tension-lease retry.
279
+ leaseDeps) {
252
280
  const ready = requireIndexReady();
253
281
  if (!ready.ok)
254
282
  return ready;
@@ -299,6 +327,22 @@ export async function vaultConsolidate(vaultRoot, args, access) {
299
327
  ...(rationaleRes.value !== null ? { rationale: rationaleRes.value } : {}),
300
328
  };
301
329
  }
330
+ // Batch resolve: no ids, no kind — both server-derived from the
331
+ // ratification itself, which is why this is not LD-19's "backdoor generic
332
+ // resolver": a resolver you cannot aim at an arbitrary tension is not a
333
+ // backdoor. A `qualify` ratification carries no dissent, so there is
334
+ // nothing for the batch to adjudicate — rejected loudly.
335
+ let batchDissent = false;
336
+ if (args.resolve_tensions !== undefined && args.resolve_tensions !== null) {
337
+ if (args.resolve_tensions !== "dissent") {
338
+ return err(new Error(`vault_consolidate: 'resolve_tensions' must be "dissent"`));
339
+ }
340
+ if (stanceRaw.value === "qualify") {
341
+ return err(new Error("vault_consolidate: resolve_tensions with stance 'qualify' — qualify opposes " +
342
+ "nothing, so there is no dissent to adjudicate"));
343
+ }
344
+ batchDissent = true;
345
+ }
302
346
  // LD-25: same identity shape as vault_assert's R-3 operator rule, but the
303
347
  // resolved identity here is the RATIFIER, not a position's principal.
304
348
  const principalArg = optStr(args, "principal", "vault_consolidate");
@@ -334,62 +378,98 @@ export async function vaultConsolidate(vaultRoot, args, access) {
334
378
  if (access && !canRatify(access.role)) {
335
379
  return err(new Error(`access denied: role '${access.roleName}' cannot consolidate`));
336
380
  }
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"));
381
+ const attemptConsolidate = async () => {
382
+ const target = await loadTargetDocument(vaultRoot, path.value, "vault_consolidate");
383
+ if (!target.ok)
384
+ return target;
385
+ const fm = target.value.parsed.frontmatter;
386
+ const dissent = dissentIds(fm.positions ?? [], stanceRaw.value);
387
+ // LD-19: resolve_tension is validated BEFORE any write. The id must name
388
+ // an OPEN tension with kind "positional" and sourceA === this doc — never
389
+ // a backdoor generic resolver.
390
+ let batchIds = [];
391
+ if (resolveTensionArg || batchDissent) {
392
+ const all = await listTensions(vaultRoot);
393
+ if (!all.ok)
394
+ return all;
395
+ if (resolveTensionArg) {
396
+ const t = all.value.find((x) => x.id === resolveTensionArg?.id);
397
+ if (!t || t.resolved || t.kind !== "positional" || t.sourceA !== target.value.relPath) {
398
+ return err(new Error("vault_consolidate: resolve_tension does not name an open positional tension " +
399
+ "on this document"));
400
+ }
401
+ if (resolveTensionArg.kind === "accepted" && dissent.length === 0) {
402
+ return err(new Error("vault_consolidate: resolve_tension kind 'accepted' requires standing dissent"));
403
+ }
404
+ }
405
+ // The batch's qualifying set, computed from the SAME snapshot that
406
+ // computes dissent (so retryOnStale recomputes both together): open
407
+ // positional tensions on this doc whose chain-resolved losing end is
408
+ // in the dissent this ratification carries. The single resolve_tension
409
+ // id keeps its deliberate kind — the batch skips it.
410
+ if (batchDissent) {
411
+ const open = all.value.filter((t) => t.kind === "positional" &&
412
+ !t.resolved &&
413
+ t.sourceA === target.value.relPath &&
414
+ t.positionA !== undefined &&
415
+ t.positionB !== undefined &&
416
+ t.id !== resolveTensionArg?.id);
417
+ batchIds = qualifyingDissentTensions(fm.positions ?? [], stanceRaw.value, dissent, open.map((t) => ({
418
+ id: t.id,
419
+ resolved: t.resolved,
420
+ positionA: t.positionA,
421
+ positionB: t.positionB,
422
+ })));
423
+ }
356
424
  }
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,
425
+ const orgPosition = {
426
+ stance: stanceRaw.value,
427
+ confidence: confidenceRaw.value,
428
+ ratified_by: ratifier,
429
+ ratified_at: todayISO(),
430
+ dissent,
431
+ };
432
+ // LD-21: contested is re-derived from the live set, never touched by
433
+ // consolidate itself; a fully legacy doc (positions null) stays null.
434
+ const contested = fm.positions != null ? isContested(fm.positions) : null;
435
+ const newFrontmatter = {
436
+ ...fm,
437
+ org_position: orgPosition,
438
+ confidence: confidenceRaw.value, // the mirror — clears the R-9 cap
439
+ contested,
440
+ updated: todayISO(),
441
+ updated_by: agent.value,
442
+ };
443
+ const written = await performFrontmatterWrite({
444
+ vaultRoot,
445
+ target: target.value,
446
+ agent: agent.value,
447
+ tool: "vault_consolidate",
448
+ action: "consolidate",
449
+ newFrontmatter,
450
+ commitMessage: `vault_consolidate: ${stanceRaw.value} on ${target.value.relPath} ratified by ${ratifier}`,
451
+ baseVersion: target.value.contentHash,
452
+ access,
453
+ ...(runIdArg.value !== null ? { runId: runIdArg.value } : {}),
454
+ });
455
+ if (!written.ok)
456
+ return written;
457
+ return ok({
458
+ relPath: target.value.relPath,
459
+ orgPosition,
460
+ dissent,
461
+ contested,
462
+ batchIds,
463
+ written: written.value,
464
+ });
375
465
  };
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;
466
+ const attempt = await retryOnStale(attemptConsolidate);
467
+ if (!attempt.ok)
468
+ return attempt;
469
+ const { relPath, orgPosition, dissent, contested, batchIds, written } = attempt.value;
390
470
  // The doc write commits FIRST; a resolve failure afterward is reported as
391
471
  // resolve_error, not rolled back (LD-19 — mirror of Slice 1's tension_error
392
- // channel).
472
+ // channel). Resolutions ride the §3.5 bounded tension-lease retry.
393
473
  let resolvedTensionId = null;
394
474
  let resolveError;
395
475
  if (resolveTensionArg) {
@@ -401,14 +481,35 @@ export async function vaultConsolidate(vaultRoot, args, access) {
401
481
  ? { rationale: resolveTensionArg.rationale }
402
482
  : {}),
403
483
  };
404
- const resolved = await resolveTension(vaultRoot, resolveTensionArg.id, resolution);
484
+ const resolved = await retryOnTensionLease(() => resolveTension(vaultRoot, resolveTensionArg.id, resolution), leaseDeps);
405
485
  if (resolved.ok)
406
486
  resolvedTensionId = resolveTensionArg.id;
407
487
  else
408
488
  resolveError = resolved.error.message;
409
489
  }
490
+ // The batch: each qualifying tension resolves `consolidated` — the honest
491
+ // record that the pairwise conflict is subsumed by this ratification, the
492
+ // dissent carried in org_position (never `superseded`: the disagreement
493
+ // persists; never blanket `accepted`: standing immunity stays a deliberate
494
+ // per-pair grant). Per-id failures never unwind the ratification.
495
+ const resolvedTensionIds = [];
496
+ const resolveErrors = [];
497
+ for (const id of batchIds) {
498
+ const resolved = await retryOnTensionLease(() => resolveTension(vaultRoot, id, {
499
+ resolved_at: new Date().toISOString(),
500
+ resolved_by: ratifier,
501
+ kind: "consolidated",
502
+ rationale: `org_position ratified ${stanceRaw.value} by ${ratifier} ${todayISO()}; ` +
503
+ `dissent carried: ${dissent.join(", ")}`,
504
+ references: [relPath],
505
+ }), leaseDeps);
506
+ if (resolved.ok)
507
+ resolvedTensionIds.push(id);
508
+ else
509
+ resolveErrors.push({ id, error: resolved.error.message });
510
+ }
410
511
  return ok({
411
- path: target.value.relPath,
512
+ path: relPath,
412
513
  action: "consolidate",
413
514
  org_position: orgPosition,
414
515
  confidence: confidenceRaw.value,
@@ -416,8 +517,10 @@ export async function vaultConsolidate(vaultRoot, args, access) {
416
517
  contested,
417
518
  resolved_tension_id: resolvedTensionId,
418
519
  ...(resolveError !== undefined ? { resolve_error: resolveError } : {}),
419
- commit: written.value.commit,
420
- committed: written.value.committed,
520
+ resolved_tension_ids: resolvedTensionIds,
521
+ resolve_errors: resolveErrors,
522
+ commit: written.commit,
523
+ committed: written.committed,
421
524
  });
422
525
  }
423
526
  export async function vaultPositions(vaultRoot, args, access) {
@@ -537,7 +640,10 @@ const assertToolDefinition = {
537
640
  "'write' proposal for ratification — nothing is written and no positional " +
538
641
  "tension is logged until the ratified write lands. The first assert on a " +
539
642
  "legacy doc (typed positions null) snapshots the doc's prior belief as " +
540
- "pos-000 (principal 'unknown', system-authored, unforgeable).",
643
+ "pos-000 (principal 'unknown', system-authored, unforgeable). Under " +
644
+ "concurrent writes to the same doc the call retries once against the " +
645
+ "fresh state, then fails loudly ('locked' or 'stale write') — safe to " +
646
+ "re-call; no position is ever silently overwritten.",
541
647
  inputSchema: {
542
648
  type: "object",
543
649
  properties: {
@@ -645,7 +751,17 @@ const consolidateToolDefinition = {
645
751
  "same call via resolve_tension: validated before any write (must name an " +
646
752
  "open 'positional' tension whose sourceA is this doc; kind 'accepted' " +
647
753
  "requires standing dissent); the doc write commits first, and a resolve " +
648
- "failure afterward is reported as resolve_error, never rolled back.",
754
+ "failure afterward is reported as resolve_error, never rolled back. " +
755
+ "resolve_tensions: 'dissent' batch-resolves EVERY open positional tension " +
756
+ "this ratification adjudicates — chain-following superseded dissent — " +
757
+ "with the system-only kind 'consolidated' (the disagreement persists, " +
758
+ "carried as dissent in org_position; standing 'accepted' immunity stays " +
759
+ "a deliberate per-pair grant via resolve_tension, which composes and is " +
760
+ "skipped by the batch). Rejected when ratifying 'qualify' (no dissent to " +
761
+ "adjudicate); moot pairs (a stance flip) stay open for lint. Under " +
762
+ "concurrent writes to the same doc the call retries once against the " +
763
+ "fresh state (dissent and the batch set recomputed), then fails loudly " +
764
+ "('locked' or 'stale write') — safe to re-call.",
649
765
  inputSchema: {
650
766
  type: "object",
651
767
  properties: {
@@ -670,6 +786,12 @@ const consolidateToolDefinition = {
670
786
  required: ["id", "kind"],
671
787
  additionalProperties: false,
672
788
  },
789
+ resolve_tensions: {
790
+ type: "string",
791
+ enum: ["dissent"],
792
+ description: "Batch-resolve every open positional tension adjudicated by this " +
793
+ "ratification's dissent, recorded as kind 'consolidated'.",
794
+ },
673
795
  },
674
796
  required: ["path", "stance", "confidence", "agent"],
675
797
  additionalProperties: false,
@@ -685,6 +807,20 @@ const consolidateToolDefinition = {
685
807
  contested: { type: ["boolean", "null"] },
686
808
  resolved_tension_id: { type: ["string", "null"] },
687
809
  resolve_error: { type: "string" },
810
+ resolved_tension_ids: {
811
+ type: "array",
812
+ items: { type: "string" },
813
+ description: "Batch-resolved tension ids; [] when resolve_tensions not requested",
814
+ },
815
+ resolve_errors: {
816
+ type: "array",
817
+ items: {
818
+ type: "object",
819
+ properties: { id: { type: "string" }, error: { type: "string" } },
820
+ required: ["id", "error"],
821
+ additionalProperties: false,
822
+ },
823
+ },
688
824
  commit: { type: ["string", "null"] },
689
825
  committed: { type: "boolean" },
690
826
  },
@@ -696,6 +832,8 @@ const consolidateToolDefinition = {
696
832
  "dissent",
697
833
  "contested",
698
834
  "resolved_tension_id",
835
+ "resolved_tension_ids",
836
+ "resolve_errors",
699
837
  "commit",
700
838
  "committed",
701
839
  ],