daftari 3.0.0 → 3.1.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 (88) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +11 -5
  3. package/dist/access/locks.d.ts +1 -0
  4. package/dist/access/locks.d.ts.map +1 -1
  5. package/dist/access/locks.js +13 -0
  6. package/dist/access/locks.js.map +1 -1
  7. package/dist/access/rbac.js +3 -3
  8. package/dist/access/rbac.js.map +1 -1
  9. package/dist/asof/git-read.d.ts.map +1 -1
  10. package/dist/asof/git-read.js +4 -0
  11. package/dist/asof/git-read.js.map +1 -1
  12. package/dist/backfill/derive.d.ts.map +1 -1
  13. package/dist/backfill/derive.js +3 -0
  14. package/dist/backfill/derive.js.map +1 -1
  15. package/dist/curation/lint-voice.d.ts.map +1 -1
  16. package/dist/curation/lint-voice.js +1 -0
  17. package/dist/curation/lint-voice.js.map +1 -1
  18. package/dist/curation/lint.d.ts +1 -1
  19. package/dist/curation/lint.d.ts.map +1 -1
  20. package/dist/curation/lint.js +80 -0
  21. package/dist/curation/lint.js.map +1 -1
  22. package/dist/curation/positions.d.ts +29 -0
  23. package/dist/curation/positions.d.ts.map +1 -0
  24. package/dist/curation/positions.js +164 -0
  25. package/dist/curation/positions.js.map +1 -0
  26. package/dist/curation/staleness.d.ts +0 -7
  27. package/dist/curation/staleness.d.ts.map +1 -1
  28. package/dist/curation/staleness.js +0 -30
  29. package/dist/curation/staleness.js.map +1 -1
  30. package/dist/curation/tension.d.ts +5 -2
  31. package/dist/curation/tension.d.ts.map +1 -1
  32. package/dist/curation/tension.js +169 -103
  33. package/dist/curation/tension.js.map +1 -1
  34. package/dist/curation/vault-docs.d.ts +10 -0
  35. package/dist/curation/vault-docs.d.ts.map +1 -1
  36. package/dist/curation/vault-docs.js +101 -10
  37. package/dist/curation/vault-docs.js.map +1 -1
  38. package/dist/eval/llm-openrouter.d.ts.map +1 -1
  39. package/dist/eval/llm-openrouter.js +8 -0
  40. package/dist/eval/llm-openrouter.js.map +1 -1
  41. package/dist/frontmatter/schema.d.ts.map +1 -1
  42. package/dist/frontmatter/schema.js +118 -1
  43. package/dist/frontmatter/schema.js.map +1 -1
  44. package/dist/frontmatter/types.d.ts +26 -2
  45. package/dist/frontmatter/types.d.ts.map +1 -1
  46. package/dist/frontmatter/types.js +7 -0
  47. package/dist/frontmatter/types.js.map +1 -1
  48. package/dist/lifecycle/lock.d.ts +2 -0
  49. package/dist/lifecycle/lock.d.ts.map +1 -1
  50. package/dist/lifecycle/lock.js +98 -18
  51. package/dist/lifecycle/lock.js.map +1 -1
  52. package/dist/search/providers/openai-3-small.d.ts.map +1 -1
  53. package/dist/search/providers/openai-3-small.js +8 -0
  54. package/dist/search/providers/openai-3-small.js.map +1 -1
  55. package/dist/search/reindex.d.ts.map +1 -1
  56. package/dist/search/reindex.js +39 -13
  57. package/dist/search/reindex.js.map +1 -1
  58. package/dist/serve/index.d.ts +4 -1
  59. package/dist/serve/index.d.ts.map +1 -1
  60. package/dist/serve/index.js +28 -12
  61. package/dist/serve/index.js.map +1 -1
  62. package/dist/server.d.ts.map +1 -1
  63. package/dist/server.js +2 -0
  64. package/dist/server.js.map +1 -1
  65. package/dist/storage/index-db.d.ts +1 -0
  66. package/dist/storage/index-db.d.ts.map +1 -1
  67. package/dist/storage/index-db.js +17 -2
  68. package/dist/storage/index-db.js.map +1 -1
  69. package/dist/tools/positions.d.ts +42 -0
  70. package/dist/tools/positions.d.ts.map +1 -0
  71. package/dist/tools/positions.js +711 -0
  72. package/dist/tools/positions.js.map +1 -0
  73. package/dist/tools/read.d.ts +24 -1
  74. package/dist/tools/read.d.ts.map +1 -1
  75. package/dist/tools/read.js +186 -2
  76. package/dist/tools/read.js.map +1 -1
  77. package/dist/tools/write.d.ts +25 -2
  78. package/dist/tools/write.d.ts.map +1 -1
  79. package/dist/tools/write.js +63 -10
  80. package/dist/tools/write.js.map +1 -1
  81. package/dist/utils/concurrency.d.ts +2 -0
  82. package/dist/utils/concurrency.d.ts.map +1 -0
  83. package/dist/utils/concurrency.js +39 -0
  84. package/dist/utils/concurrency.js.map +1 -0
  85. package/dist/utils/git.d.ts.map +1 -1
  86. package/dist/utils/git.js +5 -1
  87. package/dist/utils/git.js.map +1 -1
  88. package/package.json +2 -2
@@ -0,0 +1,711 @@
1
+ // Position tools (Slice 1, U-4/U-5): vault_assert writes the calling
2
+ // principal's position on a claim doc; vault_positions queries by doc or by
3
+ // principal. Pure logic lives in curation/positions.ts; write plumbing is
4
+ // reused from write.ts (LD-9) — no duplicated lock/commit/provenance code.
5
+ import { canRatify, canRead, hasAnyRead, isProposeOnly, } from "../access/rbac.js";
6
+ import { applyAssert, comparePositions, conflictPairs, dissentIds, isContested, legacySnapshot, unsuperseded, } from "../curation/positions.js";
7
+ import { stageActionWithConflictCheck } from "../curation/staged-actions.js";
8
+ import { addTension, listTensions, resolveTension, } from "../curation/tension.js";
9
+ import { loadDocuments } from "../curation/vault-docs.js";
10
+ import { parseDocument } from "../frontmatter/parser.js";
11
+ import { CONFIDENCES, err, ok, PROVENANCES, STANCES, } from "../frontmatter/types.js";
12
+ import { readFile, resolveVaultPath } from "../storage/local.js";
13
+ import { collectionOf } from "./read.js";
14
+ import { loadTargetDocument, performFrontmatterWrite, requireIndexReady, requireWriteAccess, targetCollection, } from "./write.js";
15
+ function todayISO() {
16
+ return new Date().toISOString().slice(0, 10);
17
+ }
18
+ function str(args, field, tool) {
19
+ const v = args[field];
20
+ if (typeof v !== "string" || v.trim().length === 0) {
21
+ return err(new Error(`${tool} requires a non-empty '${field}' argument`));
22
+ }
23
+ return ok(v);
24
+ }
25
+ function optStr(args, field, tool) {
26
+ const v = args[field];
27
+ if (v === undefined || v === null)
28
+ return ok(null);
29
+ if (typeof v !== "string")
30
+ return err(new Error(`${tool}: '${field}' must be a string`));
31
+ return ok(v);
32
+ }
33
+ export async function vaultAssert(vaultRoot, args, access) {
34
+ const ready = requireIndexReady();
35
+ if (!ready.ok)
36
+ return ready;
37
+ const path = str(args, "path", "vault_assert");
38
+ if (!path.ok)
39
+ return path;
40
+ const agent = str(args, "agent", "vault_assert");
41
+ if (!agent.ok)
42
+ return agent;
43
+ const stanceRaw = str(args, "stance", "vault_assert");
44
+ if (!stanceRaw.ok)
45
+ return stanceRaw;
46
+ if (!STANCES.includes(stanceRaw.value)) {
47
+ return err(new Error(`vault_assert 'stance' must be one of: ${STANCES.join(", ")}`));
48
+ }
49
+ const confidenceRaw = str(args, "confidence", "vault_assert");
50
+ if (!confidenceRaw.ok)
51
+ return confidenceRaw;
52
+ if (!CONFIDENCES.includes(confidenceRaw.value)) {
53
+ return err(new Error(`vault_assert 'confidence' must be one of: ${CONFIDENCES.join(", ")}`));
54
+ }
55
+ const provenanceRaw = optStr(args, "provenance", "vault_assert");
56
+ if (!provenanceRaw.ok)
57
+ return provenanceRaw;
58
+ const provenance = (provenanceRaw.value ?? "direct");
59
+ if (!PROVENANCES.includes(provenance)) {
60
+ return err(new Error(`vault_assert 'provenance' must be one of: ${PROVENANCES.join(", ")}`));
61
+ }
62
+ const statement = optStr(args, "statement", "vault_assert");
63
+ if (!statement.ok)
64
+ return statement;
65
+ const validFrom = optStr(args, "valid_from", "vault_assert");
66
+ if (!validFrom.ok)
67
+ return validFrom;
68
+ const runIdArg = optStr(args, "run_id", "vault_assert");
69
+ if (!runIdArg.ok)
70
+ return runIdArg;
71
+ const sources = Array.isArray(args.sources)
72
+ ? args.sources.filter((s) => typeof s === "string")
73
+ : [];
74
+ // R-3: the position's principal is the AUTHENTICATED user. With access, an
75
+ // explicit differing 'principal' argument is impersonation → reject. With
76
+ // no access context (operator server), an explicit principal is REQUIRED
77
+ // and recorded as unverified.
78
+ const principalArg = optStr(args, "principal", "vault_assert");
79
+ if (!principalArg.ok)
80
+ return principalArg;
81
+ let principal;
82
+ if (access) {
83
+ if (principalArg.value !== null && principalArg.value !== access.user) {
84
+ return err(new Error(`vault_assert: cannot assert a position for another principal ` +
85
+ `(authenticated as '${access.user}')`));
86
+ }
87
+ principal = access.user;
88
+ }
89
+ else {
90
+ if (principalArg.value === null) {
91
+ return err(new Error("vault_assert: no access context — an explicit 'principal' argument is " +
92
+ "required (recorded as unverified)"));
93
+ }
94
+ principal = principalArg.value;
95
+ }
96
+ // C-2 guard 1: "unknown" is reserved for the pos-000 legacy-snapshot
97
+ // principal (LD-22) — no live caller, authenticated or operator, may
98
+ // assert AS it. One check on the resolved value covers both paths.
99
+ if (principal === "unknown") {
100
+ return err(new Error("vault_assert: 'unknown' is reserved for the legacy snapshot principal (pos-000)"));
101
+ }
102
+ // RBAC before any file I/O, keyed off the physical target dir (S1 rule).
103
+ const writeGate = requireWriteAccess(access, targetCollection(vaultRoot, path.value));
104
+ if (!writeGate.ok)
105
+ 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,
153
+ contested,
154
+ ...(capConfidence ? { confidence: "low" } : {}),
155
+ },
156
+ body: target.value.parsed.content,
157
+ },
158
+ ...(runIdArg.value !== null ? { runId: runIdArg.value } : {}),
159
+ });
160
+ if (!staged.ok)
161
+ return staged;
162
+ return ok({
163
+ path: target.value.relPath,
164
+ action: "staged",
165
+ position: applied.newPosition,
166
+ superseded_position_id: applied.superseded?.id ?? null,
167
+ 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,
174
+ });
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;
190
+ // R-5 + locked R-3: one binary tension per NEW conflicting pair, skipped
191
+ // when an OPEN positional tension already names the same two ids on this
192
+ // doc. loggedBy = the asserting principal (DN-3) — the loop-authored
193
+ // ratify gate (CONSOLIDATE_AGENT) never fires on these.
194
+ const tensionIds = [];
195
+ let tensionError;
196
+ 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
+ }
226
+ }
227
+ return ok({
228
+ path: target.value.relPath,
229
+ action: "assert",
230
+ position: applied.newPosition,
231
+ superseded_position_id: applied.superseded?.id ?? null,
232
+ contested,
233
+ tension_ids: tensionIds,
234
+ ...(tensionError !== undefined ? { tension_error: tensionError } : {}),
235
+ commit: written.value.commit,
236
+ committed: written.value.committed,
237
+ });
238
+ }
239
+ // The subset of RESOLUTION_KINDS vault_consolidate accepts for its in-call
240
+ // resolve_tension (LD-19). "invalid" is a legitimate tension-resolution kind
241
+ // generally, but not a consolidation verdict — consolidate is not a backdoor
242
+ // generic resolver.
243
+ const CONSOLIDATABLE_RESOLUTION_KINDS = ["superseded", "corrected", "accepted"];
244
+ // U-10 / R-16: ratify-gated consolidation. Writes the org's ratified stance
245
+ // (org_position), mirrors its confidence onto the doc (clearing the R-9
246
+ // low-confidence cap — C-1's "the mirror moves only by re-consolidating"),
247
+ // and carries dissent — computed server-side, never caller-supplied (LD-18).
248
+ // Optionally resolves one open positional tension on this doc in the same
249
+ // call (LD-19): validated BEFORE the write; the write commits first, and a
250
+ // resolve failure afterward is reported as resolve_error, never rolled back.
251
+ export async function vaultConsolidate(vaultRoot, args, access) {
252
+ const ready = requireIndexReady();
253
+ if (!ready.ok)
254
+ return ready;
255
+ const path = str(args, "path", "vault_consolidate");
256
+ if (!path.ok)
257
+ return path;
258
+ const agent = str(args, "agent", "vault_consolidate");
259
+ if (!agent.ok)
260
+ return agent;
261
+ const stanceRaw = str(args, "stance", "vault_consolidate");
262
+ if (!stanceRaw.ok)
263
+ return stanceRaw;
264
+ if (!STANCES.includes(stanceRaw.value)) {
265
+ return err(new Error(`vault_consolidate 'stance' must be one of: ${STANCES.join(", ")}`));
266
+ }
267
+ const confidenceRaw = str(args, "confidence", "vault_consolidate");
268
+ if (!confidenceRaw.ok)
269
+ return confidenceRaw;
270
+ if (!CONFIDENCES.includes(confidenceRaw.value)) {
271
+ return err(new Error(`vault_consolidate 'confidence' must be one of: ${CONFIDENCES.join(", ")}`));
272
+ }
273
+ const runIdArg = optStr(args, "run_id", "vault_consolidate");
274
+ if (!runIdArg.ok)
275
+ return runIdArg;
276
+ let resolveTensionArg = null;
277
+ if (args.resolve_tension !== undefined && args.resolve_tension !== null) {
278
+ const rt = args.resolve_tension;
279
+ if (typeof rt !== "object" || Array.isArray(rt)) {
280
+ return err(new Error("vault_consolidate: 'resolve_tension' must be an object"));
281
+ }
282
+ const rtObj = rt;
283
+ const idRes = str(rtObj, "id", "vault_consolidate resolve_tension");
284
+ if (!idRes.ok)
285
+ return idRes;
286
+ const kindRes = str(rtObj, "kind", "vault_consolidate resolve_tension");
287
+ if (!kindRes.ok)
288
+ return kindRes;
289
+ if (!CONSOLIDATABLE_RESOLUTION_KINDS.includes(kindRes.value)) {
290
+ return err(new Error(`vault_consolidate resolve_tension 'kind' must be one of: ` +
291
+ `${CONSOLIDATABLE_RESOLUTION_KINDS.join(", ")}`));
292
+ }
293
+ const rationaleRes = optStr(rtObj, "rationale", "vault_consolidate resolve_tension");
294
+ if (!rationaleRes.ok)
295
+ return rationaleRes;
296
+ resolveTensionArg = {
297
+ id: idRes.value,
298
+ kind: kindRes.value,
299
+ ...(rationaleRes.value !== null ? { rationale: rationaleRes.value } : {}),
300
+ };
301
+ }
302
+ // LD-25: same identity shape as vault_assert's R-3 operator rule, but the
303
+ // resolved identity here is the RATIFIER, not a position's principal.
304
+ const principalArg = optStr(args, "principal", "vault_consolidate");
305
+ if (!principalArg.ok)
306
+ return principalArg;
307
+ let ratifier;
308
+ if (access) {
309
+ if (principalArg.value !== null && principalArg.value !== access.user) {
310
+ return err(new Error(`vault_consolidate: cannot ratify as another principal ` +
311
+ `(authenticated as '${access.user}')`));
312
+ }
313
+ ratifier = access.user;
314
+ }
315
+ else {
316
+ if (principalArg.value === null) {
317
+ return err(new Error("vault_consolidate: no access context — an explicit 'principal' argument is " +
318
+ "required (recorded as unverified)"));
319
+ }
320
+ ratifier = principalArg.value;
321
+ }
322
+ // C-2 guard 5: "unknown" is reserved for the pos-000 legacy-snapshot
323
+ // principal — no live ratifier, authenticated or operator, may ratify AS it.
324
+ if (ratifier === "unknown") {
325
+ return err(new Error("vault_consolidate: 'unknown' is reserved for the legacy snapshot principal (pos-000)"));
326
+ }
327
+ // LD-20: a propose-only role is denied even if `ratify` is (mis)granted —
328
+ // a proposer is not a ratifier, and there is no propose-only path for
329
+ // consolidate (unlike vault_write/vault_assert, which coerce into staged
330
+ // proposals).
331
+ if (access && isProposeOnly(access.role)) {
332
+ return err(new Error(`access denied: role '${access.roleName}' is propose-only — it cannot consolidate`));
333
+ }
334
+ if (access && !canRatify(access.role)) {
335
+ return err(new Error(`access denied: role '${access.roleName}' cannot consolidate`));
336
+ }
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"));
356
+ }
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,
375
+ };
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;
390
+ // The doc write commits FIRST; a resolve failure afterward is reported as
391
+ // resolve_error, not rolled back (LD-19 — mirror of Slice 1's tension_error
392
+ // channel).
393
+ let resolvedTensionId = null;
394
+ let resolveError;
395
+ if (resolveTensionArg) {
396
+ const resolution = {
397
+ resolved_at: new Date().toISOString(),
398
+ resolved_by: ratifier,
399
+ kind: resolveTensionArg.kind,
400
+ ...(resolveTensionArg.rationale !== undefined
401
+ ? { rationale: resolveTensionArg.rationale }
402
+ : {}),
403
+ };
404
+ const resolved = await resolveTension(vaultRoot, resolveTensionArg.id, resolution);
405
+ if (resolved.ok)
406
+ resolvedTensionId = resolveTensionArg.id;
407
+ else
408
+ resolveError = resolved.error.message;
409
+ }
410
+ return ok({
411
+ path: target.value.relPath,
412
+ action: "consolidate",
413
+ org_position: orgPosition,
414
+ confidence: confidenceRaw.value,
415
+ dissent,
416
+ contested,
417
+ resolved_tension_id: resolvedTensionId,
418
+ ...(resolveError !== undefined ? { resolve_error: resolveError } : {}),
419
+ commit: written.value.commit,
420
+ committed: written.value.committed,
421
+ });
422
+ }
423
+ export async function vaultPositions(vaultRoot, args, access) {
424
+ const path = optStr(args, "path", "vault_positions");
425
+ if (!path.ok)
426
+ return path;
427
+ const principal = optStr(args, "principal", "vault_positions");
428
+ if (!principal.ok)
429
+ return principal;
430
+ const includeSuperseded = args.include_superseded === true;
431
+ if ((path.value === null) === (principal.value === null)) {
432
+ return err(new Error("vault_positions requires exactly one of 'path' or 'principal'"));
433
+ }
434
+ if (path.value !== null) {
435
+ const resolved = resolveVaultPath(vaultRoot, path.value);
436
+ if (!resolved.ok)
437
+ return resolved;
438
+ // #212 discipline: the message never echoes the path — an unreadable doc
439
+ // must be byte-indistinguishable from a missing one, and the collection
440
+ // is the first path segment, so even echoing the caller's own string
441
+ // would leak it back through this channel.
442
+ const notFound = () => err(new Error("vault_positions: document not found"));
443
+ const file = await readFile(resolved.value.absPath);
444
+ if (!file.ok)
445
+ return notFound();
446
+ const parsed = parseDocument(file.value);
447
+ if (!parsed.ok)
448
+ return parsed;
449
+ if (access &&
450
+ !canRead(access.role, collectionOf(resolved.value.relPath, parsed.value.frontmatter))) {
451
+ return notFound();
452
+ }
453
+ const set = parsed.value.frontmatter.positions ?? [];
454
+ const chosen = (includeSuperseded ? set : unsuperseded(set)).slice().sort(comparePositions);
455
+ return ok({
456
+ count: chosen.length,
457
+ positions: chosen.map((p) => ({
458
+ path: resolved.value.relPath,
459
+ position: p,
460
+ contested: isContested(set),
461
+ })),
462
+ });
463
+ }
464
+ // By principal: whole-vault scan via the lint loader (LD-10). Unreadable
465
+ // docs are silently omitted — no count, no hint (#217 omission rule).
466
+ if (access && !hasAnyRead(access.role)) {
467
+ return err(new Error(`access denied: role '${access.roleName}' cannot use vault_positions`));
468
+ }
469
+ const loaded = await loadDocuments(vaultRoot);
470
+ if (!loaded.ok)
471
+ return loaded;
472
+ const out = [];
473
+ for (const doc of loaded.value) {
474
+ if (access && !canRead(access.role, collectionOf(doc.path, doc.frontmatter)))
475
+ continue;
476
+ const set = doc.frontmatter.positions;
477
+ if (set == null)
478
+ continue;
479
+ const pool = includeSuperseded ? set : unsuperseded(set);
480
+ for (const p of pool.filter((x) => x.principal === principal.value).sort(comparePositions)) {
481
+ out.push({ path: doc.path, position: p, contested: isContested(set) });
482
+ }
483
+ }
484
+ out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
485
+ return ok({ count: out.length, positions: out });
486
+ }
487
+ const POSITION_SCHEMA = {
488
+ type: "object",
489
+ properties: {
490
+ id: { type: "string" },
491
+ principal: { type: "string" },
492
+ stance: { type: "string", enum: [...STANCES] },
493
+ statement: { type: ["string", "null"] },
494
+ confidence: { type: "string", enum: [...CONFIDENCES] },
495
+ provenance: { type: "string", enum: [...PROVENANCES] },
496
+ valid_from: { type: ["string", "null"] },
497
+ superseded_by: { type: ["string", "null"] },
498
+ created: { type: "string" },
499
+ sources: { type: "array", items: { type: "string" } },
500
+ },
501
+ required: [
502
+ "id",
503
+ "principal",
504
+ "stance",
505
+ "statement",
506
+ "confidence",
507
+ "provenance",
508
+ "valid_from",
509
+ "superseded_by",
510
+ "created",
511
+ "sources",
512
+ ],
513
+ };
514
+ const ORG_POSITION_SCHEMA = {
515
+ type: "object",
516
+ properties: {
517
+ stance: { type: "string", enum: [...STANCES] },
518
+ confidence: { type: "string", enum: [...CONFIDENCES] },
519
+ ratified_by: { type: "string" },
520
+ ratified_at: { type: "string" },
521
+ dissent: { type: "array", items: { type: "string" } },
522
+ },
523
+ required: ["stance", "confidence", "ratified_by", "ratified_at", "dissent"],
524
+ };
525
+ const assertToolDefinition = {
526
+ name: "vault_assert",
527
+ title: "Assert a position on a claim document",
528
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
529
+ description: "Assert, dispute, or qualify the calling principal's position on an " +
530
+ "existing claim document. The position's principal is the authenticated " +
531
+ "--user; a prior live position by the same principal is superseded, never " +
532
+ "edited. A second conflicting live stance (assert vs dispute) marks the " +
533
+ "document contested, caps its confidence at low until an org position is " +
534
+ "ratified (see vault_consolidate), and auto-logs a 'positional' tension (never " +
535
+ "caller-loggable via vault_tension_log; resolve through " +
536
+ "vault_tension_resolve). Propose-only roles: the assert lands as a staged " +
537
+ "'write' proposal for ratification — nothing is written and no positional " +
538
+ "tension is logged until the ratified write lands. The first assert on a " +
539
+ "legacy doc (typed positions null) snapshots the doc's prior belief as " +
540
+ "pos-000 (principal 'unknown', system-authored, unforgeable).",
541
+ inputSchema: {
542
+ type: "object",
543
+ properties: {
544
+ path: { type: "string", description: "Vault-relative path of the existing claim doc" },
545
+ stance: { type: "string", enum: [...STANCES] },
546
+ statement: { type: "string", description: "Optional refinement of the title claim" },
547
+ confidence: { type: "string", enum: [...CONFIDENCES] },
548
+ provenance: { type: "string", enum: [...PROVENANCES], description: "Default: direct" },
549
+ valid_from: { type: "string", description: "YYYY-MM-DD" },
550
+ sources: { type: "array", items: { type: "string" } },
551
+ agent: { type: "string", description: "Free-text acting identity (advisory)" },
552
+ principal: {
553
+ type: "string",
554
+ description: "Only honored (and required) when the server runs without an access " +
555
+ "context; recorded as unverified. With an access context it must " +
556
+ "match the authenticated user.",
557
+ },
558
+ run_id: { type: "string" },
559
+ },
560
+ required: ["path", "stance", "confidence", "agent"],
561
+ additionalProperties: false,
562
+ },
563
+ outputSchema: {
564
+ type: "object",
565
+ properties: {
566
+ path: { type: "string" },
567
+ action: { type: "string", enum: ["assert", "staged"] },
568
+ position: { ...POSITION_SCHEMA, type: ["object", "null"] },
569
+ superseded_position_id: { type: ["string", "null"] },
570
+ contested: { type: "boolean" },
571
+ tension_ids: { type: "array", items: { type: "string" } },
572
+ tension_error: { type: "string" },
573
+ commit: { type: ["string", "null"] },
574
+ committed: { type: "boolean" },
575
+ staged_id: { type: "string" },
576
+ expires_at: { type: "string" },
577
+ conflicts_with: { type: "array", items: { type: "string" } },
578
+ },
579
+ required: [
580
+ "path",
581
+ "action",
582
+ "position",
583
+ "superseded_position_id",
584
+ "contested",
585
+ "tension_ids",
586
+ "commit",
587
+ "committed",
588
+ ],
589
+ },
590
+ docLinks: (value) => [value.path],
591
+ handler: (vaultRoot, args, access) => vaultAssert(vaultRoot, args, access),
592
+ };
593
+ const positionsToolDefinition = {
594
+ name: "vault_positions",
595
+ title: "Query principals' positions",
596
+ annotations: { readOnlyHint: true },
597
+ description: "Query positions: all positions on one doc ('path'), or all live " +
598
+ "positions held by a principal across the vault ('principal'). Exactly " +
599
+ "one selector. Results are limited to docs the caller can read; " +
600
+ "include_superseded (default false) adds superseded entries.",
601
+ inputSchema: {
602
+ type: "object",
603
+ properties: {
604
+ path: { type: "string" },
605
+ principal: { type: "string" },
606
+ include_superseded: { type: "boolean" },
607
+ },
608
+ additionalProperties: false,
609
+ },
610
+ outputSchema: {
611
+ type: "object",
612
+ properties: {
613
+ count: { type: "integer", minimum: 0 },
614
+ positions: {
615
+ type: "array",
616
+ items: {
617
+ type: "object",
618
+ properties: {
619
+ path: { type: "string" },
620
+ position: POSITION_SCHEMA,
621
+ contested: { type: "boolean" },
622
+ },
623
+ required: ["path", "position", "contested"],
624
+ },
625
+ },
626
+ },
627
+ required: ["count", "positions"],
628
+ },
629
+ docLinks: (value) => [...new Set(value.positions.map((p) => p.path))],
630
+ handler: (vaultRoot, args, access) => vaultPositions(vaultRoot, args, access),
631
+ };
632
+ const consolidateToolDefinition = {
633
+ name: "vault_consolidate",
634
+ title: "Ratify an org position on a contested claim",
635
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
636
+ description: "Ratify the org's consolidated stance on a claim document (ratify-gated: " +
637
+ "requires a role with ratify: true; propose-only roles are denied outright " +
638
+ "— there is no staged-proposal path for consolidation). Writes org_position " +
639
+ "and mirrors its confidence onto the doc, clearing the R-9 low-confidence " +
640
+ "cap; the mirror holds through re-contest and moves only by " +
641
+ "re-consolidating. dissent is computed server-side from the live position " +
642
+ "set at ratify time (assert<->dispute; qualify opposes nothing) — never " +
643
+ "caller-supplied. Allowed on uncontested or fully legacy docs (dissent: " +
644
+ "[]). Optionally resolves one open positional tension on this doc in the " +
645
+ "same call via resolve_tension: validated before any write (must name an " +
646
+ "open 'positional' tension whose sourceA is this doc; kind 'accepted' " +
647
+ "requires standing dissent); the doc write commits first, and a resolve " +
648
+ "failure afterward is reported as resolve_error, never rolled back.",
649
+ inputSchema: {
650
+ type: "object",
651
+ properties: {
652
+ path: { type: "string", description: "Vault-relative path of the existing claim doc" },
653
+ stance: { type: "string", enum: [...STANCES] },
654
+ confidence: { type: "string", enum: [...CONFIDENCES] },
655
+ agent: { type: "string", description: "Free-text acting identity (advisory)" },
656
+ principal: {
657
+ type: "string",
658
+ description: "Only honored (and required) when the server runs without an access " +
659
+ "context; recorded as unverified as the ratifier. With an access " +
660
+ "context it must match the authenticated user.",
661
+ },
662
+ run_id: { type: "string" },
663
+ resolve_tension: {
664
+ type: "object",
665
+ properties: {
666
+ id: { type: "string" },
667
+ kind: { type: "string", enum: [...CONSOLIDATABLE_RESOLUTION_KINDS] },
668
+ rationale: { type: "string" },
669
+ },
670
+ required: ["id", "kind"],
671
+ additionalProperties: false,
672
+ },
673
+ },
674
+ required: ["path", "stance", "confidence", "agent"],
675
+ additionalProperties: false,
676
+ },
677
+ outputSchema: {
678
+ type: "object",
679
+ properties: {
680
+ path: { type: "string" },
681
+ action: { type: "string", enum: ["consolidate"] },
682
+ org_position: ORG_POSITION_SCHEMA,
683
+ confidence: { type: "string", enum: [...CONFIDENCES] },
684
+ dissent: { type: "array", items: { type: "string" } },
685
+ contested: { type: ["boolean", "null"] },
686
+ resolved_tension_id: { type: ["string", "null"] },
687
+ resolve_error: { type: "string" },
688
+ commit: { type: ["string", "null"] },
689
+ committed: { type: "boolean" },
690
+ },
691
+ required: [
692
+ "path",
693
+ "action",
694
+ "org_position",
695
+ "confidence",
696
+ "dissent",
697
+ "contested",
698
+ "resolved_tension_id",
699
+ "commit",
700
+ "committed",
701
+ ],
702
+ },
703
+ docLinks: (value) => [value.path],
704
+ handler: (vaultRoot, args, access) => vaultConsolidate(vaultRoot, args, access),
705
+ };
706
+ export const positionsTools = [
707
+ assertToolDefinition,
708
+ positionsToolDefinition,
709
+ consolidateToolDefinition,
710
+ ];
711
+ //# sourceMappingURL=positions.js.map