@crubal/engine 0.0.0-stage → 0.4.1

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 (114) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +97 -2
  3. package/dist/bin/crubal.d.ts +2 -0
  4. package/dist/bin/crubal.js +103 -0
  5. package/dist/bin/crubal.js.map +1 -0
  6. package/dist/src/access.d.ts +149 -0
  7. package/dist/src/access.js +584 -0
  8. package/dist/src/access.js.map +1 -0
  9. package/dist/src/acts.d.ts +531 -0
  10. package/dist/src/acts.js +1466 -0
  11. package/dist/src/acts.js.map +1 -0
  12. package/dist/src/address.d.ts +29 -0
  13. package/dist/src/address.js +59 -0
  14. package/dist/src/address.js.map +1 -0
  15. package/dist/src/arrival.d.ts +55 -0
  16. package/dist/src/arrival.js +127 -0
  17. package/dist/src/arrival.js.map +1 -0
  18. package/dist/src/browser.d.ts +10 -0
  19. package/dist/src/browser.js +13 -0
  20. package/dist/src/browser.js.map +1 -0
  21. package/dist/src/bundle.d.ts +74 -0
  22. package/dist/src/bundle.js +1118 -0
  23. package/dist/src/bundle.js.map +1 -0
  24. package/dist/src/canonical.d.ts +6 -0
  25. package/dist/src/canonical.js +47 -0
  26. package/dist/src/canonical.js.map +1 -0
  27. package/dist/src/carriers.d.ts +7 -0
  28. package/dist/src/carriers.js +33 -0
  29. package/dist/src/carriers.js.map +1 -0
  30. package/dist/src/conditions.d.ts +28 -0
  31. package/dist/src/conditions.js +227 -0
  32. package/dist/src/conditions.js.map +1 -0
  33. package/dist/src/corpus.d.ts +8 -0
  34. package/dist/src/corpus.js +1207 -0
  35. package/dist/src/corpus.js.map +1 -0
  36. package/dist/src/defs.d.ts +176 -0
  37. package/dist/src/defs.js +692 -0
  38. package/dist/src/defs.js.map +1 -0
  39. package/dist/src/dictionary.d.ts +77 -0
  40. package/dist/src/dictionary.js +629 -0
  41. package/dist/src/dictionary.js.map +1 -0
  42. package/dist/src/exchange.d.ts +259 -0
  43. package/dist/src/exchange.js +1088 -0
  44. package/dist/src/exchange.js.map +1 -0
  45. package/dist/src/forms.d.ts +16 -0
  46. package/dist/src/forms.js +181 -0
  47. package/dist/src/forms.js.map +1 -0
  48. package/dist/src/index.d.ts +32 -0
  49. package/dist/src/index.js +34 -0
  50. package/dist/src/index.js.map +1 -0
  51. package/dist/src/lex.d.ts +21 -0
  52. package/dist/src/lex.js +142 -0
  53. package/dist/src/lex.js.map +1 -0
  54. package/dist/src/lifecycle.d.ts +92 -0
  55. package/dist/src/lifecycle.js +451 -0
  56. package/dist/src/lifecycle.js.map +1 -0
  57. package/dist/src/log.d.ts +91 -0
  58. package/dist/src/log.js +629 -0
  59. package/dist/src/log.js.map +1 -0
  60. package/dist/src/migrate.d.ts +129 -0
  61. package/dist/src/migrate.js +415 -0
  62. package/dist/src/migrate.js.map +1 -0
  63. package/dist/src/model.d.ts +81 -0
  64. package/dist/src/model.js +188 -0
  65. package/dist/src/model.js.map +1 -0
  66. package/dist/src/packages.d.ts +386 -0
  67. package/dist/src/packages.js +1171 -0
  68. package/dist/src/packages.js.map +1 -0
  69. package/dist/src/print-text.d.ts +7 -0
  70. package/dist/src/print-text.js +223 -0
  71. package/dist/src/print-text.js.map +1 -0
  72. package/dist/src/publish.d.ts +27 -0
  73. package/dist/src/publish.js +279 -0
  74. package/dist/src/publish.js.map +1 -0
  75. package/dist/src/read-text.d.ts +10 -0
  76. package/dist/src/read-text.js +400 -0
  77. package/dist/src/read-text.js.map +1 -0
  78. package/dist/src/records.d.ts +32 -0
  79. package/dist/src/records.js +104 -0
  80. package/dist/src/records.js.map +1 -0
  81. package/dist/src/review.d.ts +22 -0
  82. package/dist/src/review.js +198 -0
  83. package/dist/src/review.js.map +1 -0
  84. package/dist/src/rules.d.ts +101 -0
  85. package/dist/src/rules.js +670 -0
  86. package/dist/src/rules.js.map +1 -0
  87. package/dist/src/schedule.d.ts +24 -0
  88. package/dist/src/schedule.js +126 -0
  89. package/dist/src/schedule.js.map +1 -0
  90. package/dist/src/std-packages.d.ts +9 -0
  91. package/dist/src/std-packages.js +268 -0
  92. package/dist/src/std-packages.js.map +1 -0
  93. package/dist/src/store.d.ts +191 -0
  94. package/dist/src/store.js +671 -0
  95. package/dist/src/store.js.map +1 -0
  96. package/dist/src/surface.d.ts +47 -0
  97. package/dist/src/surface.js +92 -0
  98. package/dist/src/surface.js.map +1 -0
  99. package/dist/src/tree.d.ts +35 -0
  100. package/dist/src/tree.js +159 -0
  101. package/dist/src/tree.js.map +1 -0
  102. package/dist/src/units-table.d.ts +1 -0
  103. package/dist/src/units-table.js +200 -0
  104. package/dist/src/units-table.js.map +1 -0
  105. package/dist/src/units.d.ts +42 -0
  106. package/dist/src/units.js +98 -0
  107. package/dist/src/units.js.map +1 -0
  108. package/dist/src/versions.d.ts +10 -0
  109. package/dist/src/versions.js +27 -0
  110. package/dist/src/versions.js.map +1 -0
  111. package/dist/src/views.d.ts +372 -0
  112. package/dist/src/views.js +1170 -0
  113. package/dist/src/views.js.map +1 -0
  114. package/package.json +60 -4
@@ -0,0 +1,671 @@
1
+ // store.ts: the Store level (spec chapters 8 and 9). Hash-linked logs (8.5), intake through a receive
2
+ // contract with raw bytes kept (9.1–9.4), landing values by the trust order with alternatives (8.4),
3
+ // matching parts before minting rows (9.2), and evidence validation with independence and vetoes (9.7).
4
+ import { createHash, createPublicKey, verify } from "node:crypto";
5
+ import { serialize } from "./canonical.js";
6
+ import { readClassLine, unquote } from "./defs.js";
7
+ import { checkScalar, foldKey, foldValue } from "./dictionary.js";
8
+ import { splitTop } from "./lex.js";
9
+ import { readUnder } from "./read-text.js";
10
+ import { CrubalError, readTree } from "./tree.js";
11
+ const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
12
+ // ─── Logs (8.5) ──────────────────────────────────────────────────────────────
13
+ export function sha256(text) {
14
+ return createHash("sha256").update(text, "utf8").digest("hex");
15
+ }
16
+ /** A write's hash: SHA-256 of its canonical form; a redacted write's hash is what it carries (8.5.2). */
17
+ export function writeHash(w) {
18
+ if (isObj(w) && typeof w.redacted === "string")
19
+ return w.redacted.replace(/^sha256:/, "");
20
+ return sha256(serialize(w));
21
+ }
22
+ /**
23
+ * An entry's hash (8.5): SHA-256 of its canonical form without `sig`, each write replaced by `sha256:` and
24
+ * its own hash, so a redacted write leaves the entry's hash where it was. A redacted entry's hash is what it
25
+ * carries.
26
+ */
27
+ export function entryHash(entry) {
28
+ if (typeof entry.redacted === "string")
29
+ return entry.redacted.replace(/^sha256:/, "");
30
+ const { sig: _sig, ...rest } = entry;
31
+ if (Array.isArray(rest.writes))
32
+ rest.writes = rest.writes.map((w) => `sha256:${writeHash(w)}`);
33
+ return sha256(serialize(rest));
34
+ }
35
+ /** The owner's key in force at a moment: the one whose span holds `at`, else an undated one, else the latest. */
36
+ export function keyFor(keys, owner, at) {
37
+ const k = keys[owner];
38
+ if (!k)
39
+ return undefined;
40
+ const list = Array.isArray(k) ? k : [k];
41
+ if (at) {
42
+ const spans = list.filter((x) => (!x.from || x.from <= at) && (!x.until || at < x.until));
43
+ if (spans.length)
44
+ return spans.at(-1);
45
+ }
46
+ return list.find((x) => !x.from && !x.until) ?? list.at(-1);
47
+ }
48
+ /** Does `sig` (base64url) verify over the entry's hash bytes with the owner's Ed25519 key? */
49
+ export function verifySig(entry, owner, keys) {
50
+ const k = keyFor(keys, owner, typeof entry.at === "string" ? entry.at : undefined);
51
+ if (!k || k.alg !== "Ed25519" || typeof entry.sig !== "string")
52
+ return false;
53
+ const key = createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: k.public }, format: "jwk" });
54
+ return verify(null, Buffer.from(entryHash(entry), "hex"), key, Buffer.from(entry.sig, "base64url"));
55
+ }
56
+ /** Check a chain's links, and, when the owner's key is known, every entry's signature (8.5). */
57
+ export function verifyChain(entries, keys) {
58
+ let owner = "";
59
+ for (let i = 0; i < entries.length; i++) {
60
+ const e = entries[i];
61
+ if (i > 0 && e.prev !== `sha256:${entryHash(entries[i - 1])}`)
62
+ return { valid: false, "breaks-at": String(e.log), reason: "link" };
63
+ if (typeof e.owner === "string")
64
+ owner = e.owner;
65
+ if (keys?.[owner] && !verifySig(e, owner, keys))
66
+ return { valid: false, "breaks-at": String(e.log), reason: "signature" };
67
+ }
68
+ return { valid: true };
69
+ }
70
+ function readMap(lines) {
71
+ return lines.map((l) => {
72
+ const [from, to] = splitArrow(l.text, l.line);
73
+ const values = l.children.map((c) => splitArrow(c.text, c.line).map(unq));
74
+ return { from, to, values, line: l.line, valueLines: l.children.map((c) => c.line) };
75
+ });
76
+ }
77
+ function splitArrow(text, line) {
78
+ const at = text.indexOf(" -> ");
79
+ if (at < 0)
80
+ throw new CrubalError(`a map line is "from -> to": ${text}`, line);
81
+ return [text.slice(0, at).trim(), text.slice(at + 4).trim()];
82
+ }
83
+ const unq = (s) => (s.startsWith('"') ? JSON.parse(s) : s);
84
+ /** Read `contract:` blocks. */
85
+ export function readContracts(source) {
86
+ const out = [];
87
+ for (const node of readTree(source)) {
88
+ if (node.kind !== "pair" || node.key !== "contract")
89
+ continue;
90
+ const c = {
91
+ name: node.value.trim(),
92
+ kind: "receive",
93
+ origin: "",
94
+ reads: [],
95
+ writes: [],
96
+ stores: [],
97
+ terms: {},
98
+ ignore: [],
99
+ keepRaw: [],
100
+ absorb: true,
101
+ lands: "value",
102
+ line: node.line,
103
+ needs: [],
104
+ gives: [],
105
+ stream: [],
106
+ parts: {},
107
+ partLines: {},
108
+ };
109
+ for (const p of node.children) {
110
+ if (!p.key)
111
+ continue;
112
+ c.partLines[p.key] = p.line;
113
+ const list = () => splitTop(p.value, ",", p.line).filter(Boolean);
114
+ if (p.key === "needs") {
115
+ // Needs are an unnamed class (5.8): its lines, placed by the same sections (5.3.3, 7.7).
116
+ if (p.value)
117
+ c.needs = splitTop(p.value, ",", p.line).map((t) => readClassLine(t, p.line));
118
+ else {
119
+ let section;
120
+ for (const l of p.children) {
121
+ if (l.kind === "pair" && l.key === "section") {
122
+ section = unq(l.value);
123
+ continue;
124
+ }
125
+ c.needs.push(readClassLine(l.text, l.line, section));
126
+ }
127
+ }
128
+ continue;
129
+ }
130
+ if (p.key === "gives")
131
+ c.gives = list();
132
+ else if (p.key === "who")
133
+ c.who = p.value;
134
+ else if (p.key === "when")
135
+ c.when = p.value;
136
+ else if (p.key === "from")
137
+ c.from = p.value;
138
+ else if (p.key === "to")
139
+ c.to = p.value;
140
+ else if (p.key === "mode")
141
+ c.mode = p.value;
142
+ else if (p.key === "undo")
143
+ c.undo = p.value;
144
+ else if (p.key === "ref")
145
+ c.ref = p.value;
146
+ else if (p.key === "quorum")
147
+ c.quorum = p.value.trim();
148
+ else if (p.key === "role") {
149
+ const r = p.value.trim();
150
+ if (r !== "make" && r !== "keep" && r !== "act")
151
+ throw new CrubalError(`${c.name}: role is make, keep or act, not ${r || "nothing"}`, p.line);
152
+ c.role = r;
153
+ }
154
+ else if (p.key === "stream")
155
+ c.stream = list();
156
+ else if (p.key === "terms") {
157
+ // `terms:` with one term per line, or `terms: reshare no, expires 2027-01-01` on the line.
158
+ for (const t of p.children)
159
+ if (t.key)
160
+ c.terms[t.key] = t.value.trim();
161
+ for (const t of list()) {
162
+ const [k, ...v] = t.trim().split(/[:\s]+/);
163
+ if (k && v.length)
164
+ c.terms[k] = v.join(" ");
165
+ }
166
+ }
167
+ if (p.key === "kind")
168
+ c.kind = p.value;
169
+ else if (p.key === "origin")
170
+ c.origin = p.value;
171
+ else if (p.key === "prefix")
172
+ c.prefix = p.value;
173
+ else if (p.key === "reads")
174
+ c.reads = readMap(p.children);
175
+ else if (p.key === "writes")
176
+ c.writes = readMap(p.children);
177
+ else if (p.key === "stores") {
178
+ // Written, ourAddress -> theirField; read, the same lines the other way, value maps too.
179
+ c.stores = readMap(p.children);
180
+ c.writes = c.stores.map((m) => ({ ...m, values: [...m.values] }));
181
+ c.reads = c.stores.map((m) => ({ from: m.to, to: m.from, values: m.values.map(([ours, theirs]) => [theirs, ours]), line: m.line, valueLines: m.valueLines }));
182
+ }
183
+ else if (p.key === "ignore")
184
+ c.ignore = list();
185
+ else if (p.key === "keep-raw")
186
+ c.keepRaw = list();
187
+ else if (p.key === "absorb")
188
+ c.absorb = p.value !== "no";
189
+ else if (p.key === "lands")
190
+ c.lands = p.value;
191
+ // Free text the printer may have quoted (2.5) reads back as text; every other part is kept as written.
192
+ if (!["kind", "origin", "prefix", "reads", "writes", "stores", "ignore", "keep-raw", "absorb", "lands", "gives", "who", "when", "from", "mode", "undo", "ref", "stream", "terms", "role"].includes(p.key))
193
+ c.parts[p.key] = p.key === "label" || p.key === "describe" ? unquote(p.value) : p.value;
194
+ }
195
+ if (!c.origin)
196
+ c.origin = c.kind === "form" ? "declared" : "reported";
197
+ if (c.role && c.kind !== "form")
198
+ throw new CrubalError(`${c.name}: only a form has a role`, c.partLines.role ?? c.line);
199
+ // A form's utility and act (7.7, revision 16): only a form names them; an act needs a utility and an act role.
200
+ for (const k of ["utility", "act"]) {
201
+ const v = c.parts[k];
202
+ if (v === undefined)
203
+ continue;
204
+ if (c.kind !== "form")
205
+ throw new CrubalError(`${c.name}: only a form names ${k === "act" ? "an act" : "a utility"}`, c.partLines[k] ?? c.line);
206
+ if (!/^[a-z][\w-]*$/.test(v.trim()))
207
+ throw new CrubalError(`${c.name}: ${k} is a lower-case word, not ${v || "nothing"}`, c.partLines[k] ?? c.line);
208
+ c.parts[k] = v.trim();
209
+ }
210
+ if (c.parts.act !== undefined && c.parts.utility === undefined)
211
+ throw new CrubalError(`${c.name}: a form names an act of its utility; it names no utility`, c.partLines.act ?? c.line);
212
+ if (c.parts.act !== undefined && (c.role ?? "keep") !== "act")
213
+ throw new CrubalError(`${c.name}: only an act form names an act; its role is ${c.role ?? "keep"}`, c.partLines.act ?? c.line);
214
+ if (c.keepRaw.length && !c.prefix)
215
+ throw new CrubalError(`${c.name} keeps raw fields, so it needs a prefix`, c.line);
216
+ // A form's fields are its needs (7.7): with no reads of its own, each answer lands on its facet by name.
217
+ if (c.kind === "form" && !c.reads.length && c.needs.length)
218
+ c.reads = c.needs.map((l) => ({ from: l.facet, to: l.facet, values: [], line: l.line, valueLines: [] }));
219
+ out.push(c);
220
+ }
221
+ return out;
222
+ }
223
+ /** Split a field path into names: `aspects."Run Time"` → ["aspects", "Run Time"]. */
224
+ export function fieldPath(path) {
225
+ const out = [];
226
+ let cur = "";
227
+ let quoted = false;
228
+ for (let i = 0; i < path.length; i++) {
229
+ const ch = path[i];
230
+ if (ch === '"') {
231
+ quoted = !quoted;
232
+ continue;
233
+ }
234
+ if (ch === "." && !quoted) {
235
+ out.push(cur);
236
+ cur = "";
237
+ continue;
238
+ }
239
+ cur += ch;
240
+ }
241
+ out.push(cur);
242
+ return out;
243
+ }
244
+ /** Write a payload's field name as a path segment, quoted when it isn't a plain name. */
245
+ function segment(name) {
246
+ return /^[A-Za-z_]\w*$/.test(name) ? name : JSON.stringify(name);
247
+ }
248
+ /** A value in one of chapter 3's object forms (`$link`, `$image`, `$color`, `$qty`, `$money`, `$value`, `$empty`): a leaf, not a nesting. */
249
+ const valueObject = (v) => isObj(v) && Object.keys(v).some((k) => k.startsWith("$"));
250
+ function leaves(obj, prefix = "", whole = () => false) {
251
+ if (!isObj(obj) || valueObject(obj))
252
+ return [[prefix, obj]];
253
+ return Object.entries(obj).flatMap(([k, v]) => {
254
+ const p = prefix ? `${prefix}.${segment(k)}` : segment(k);
255
+ // An object at a path the contract maps as one field (a compound answer, chapter 3) is one leaf.
256
+ return isObj(v) && !valueObject(v) && !whole(p) ? leaves(v, p, whole) : [[p, v]];
257
+ });
258
+ }
259
+ function samePath(a, b) {
260
+ return serialize(fieldPath(a)) === serialize(fieldPath(b));
261
+ }
262
+ /** Fold one raw value through the map's value map, the aliases and the shapes, then check it (9.2). */
263
+ function foldIn(f, raw, map, dict) {
264
+ // Chapter 3's forms arrive as values: a boolean for a yes-no, an object with a `$` key, and a list read item
265
+ // by item. Anything else is text, read under the facet (chapter 2) after the map's value map and the aliases.
266
+ let childProblem;
267
+ const one = (r) => {
268
+ if (valueObject(r) || (typeof r === "boolean" && f.type === "yes-no"))
269
+ return r;
270
+ // A compound answer as an object (chapter 3): each child folded under its own facet; a child that
271
+ // contradicts its facet contradicts the whole answer, and the outcome names the child.
272
+ if (f.type === "compound" && isObj(r)) {
273
+ const out = {};
274
+ for (const [k, v] of Object.entries(r)) {
275
+ const child = f.children?.get(k);
276
+ if (!child) {
277
+ out[k] = v;
278
+ continue;
279
+ }
280
+ const folded = foldIn(child, v, undefined, dict);
281
+ if (folded.outcome === "contradiction")
282
+ childProblem = childProblem ?? child.key;
283
+ out[k] = folded.value;
284
+ }
285
+ return out;
286
+ }
287
+ let text = typeof r === "string" ? r : serialize(r);
288
+ const vm = map?.values.find(([theirs]) => theirs === text);
289
+ if (vm)
290
+ text = vm[1];
291
+ return readUnder(f, text, dict) ?? text;
292
+ };
293
+ const read = Array.isArray(raw)
294
+ ? raw.flatMap((r) => {
295
+ const x = one(r);
296
+ return Array.isArray(x) ? x : [x];
297
+ })
298
+ : one(raw);
299
+ const value = foldValue(f, read, dict);
300
+ const items = Array.isArray(value) ? value : [value];
301
+ const checks = items.map((i) => checkScalar(f, i));
302
+ if (childProblem)
303
+ return { value, outcome: "contradiction", cites: { type: childProblem } };
304
+ const outcome = checks.some((c) => c.outcome === "contradiction") ? "contradiction" : checks.some((c) => c.outcome === "new") ? "new" : "absorbed";
305
+ const unit = checks.find((c) => c.cites?.unit)?.cites;
306
+ return { value, outcome, ...(unit ? { cites: unit } : {}) };
307
+ }
308
+ /** Keep a payload's exact bytes (3.8): as text when they are valid UTF-8, otherwise as base64. */
309
+ export function rawOf(bytes, type) {
310
+ const hash = createHash("sha256").update(bytes).digest("hex");
311
+ try {
312
+ return { type, sha256: hash, body: new TextDecoder("utf-8", { fatal: true }).decode(bytes) };
313
+ }
314
+ catch {
315
+ return { type, sha256: hash, base64: Buffer.from(bytes).toString("base64") };
316
+ }
317
+ }
318
+ /** Replay an intake record from its kept bytes under the current contract (9.6); earlier outcomes stay. */
319
+ export function replay(intake, c, dict) {
320
+ const again = receive(c, intake.raw.body, intake.for, dict, intake.intake);
321
+ const replays = [...(intake.replays ?? []), { outcomes: again.outcomes, contract: c.name }];
322
+ return { ...intake, replays };
323
+ }
324
+ /** Review by key across every intake record (9.5), and candidate facets proposed by recurrence. */
325
+ export function reviewByKey(intakes, recur = 5) {
326
+ const groups = new Map();
327
+ for (const i of intakes) {
328
+ for (const o of i.outcomes) {
329
+ if (o.outcome !== "unknown" && o.outcome !== "new")
330
+ continue;
331
+ // A unit question (11.9) is reviewed by spelling, across every facet it reached.
332
+ const key = o.cites?.unit ? `unit:${String(o.cites.unit)}` : (o.to ?? o.from);
333
+ const g = groups.get(key) ?? { objects: new Set(), values: new Set(), outcome: o.outcome };
334
+ g.objects.add(i.for);
335
+ if (o.value !== undefined)
336
+ g.values.add(serialize(o.value));
337
+ groups.set(key, g);
338
+ }
339
+ }
340
+ const rows = [...groups.entries()].sort((a, b) => b[1].objects.size - a[1].objects.size || a[0].localeCompare(b[0]));
341
+ return {
342
+ "by-key": rows.map(([key, g]) => ({ key, objects: g.objects.size, values: g.values.size, outcome: g.outcome })),
343
+ // Only keys no facet holds become candidate facets; a facet's new values go to vocabulary review.
344
+ proposals: rows.filter(([, g]) => g.outcome === "unknown" && g.objects.size >= recur).map(([key, g]) => ({ key, objects: g.objects.size, state: "candidate" })),
345
+ };
346
+ }
347
+ /** Receive a raw payload through a contract: every field gets exactly one outcome. The bytes are kept. */
348
+ export function receive(c, body, forRecord, dict, intakeId = "I-1") {
349
+ const payload = JSON.parse(body);
350
+ const outcomes = [];
351
+ // Parts (5.6, 9.2): the body's `parts` list, each `{ slot, row?, ...values }`; a value is read under its facet
352
+ // and lands on the part the slot and row name (the record's classes decide the slot; the row binds or mints).
353
+ const partList = isObj(payload) && Array.isArray(payload.parts) ? payload.parts : [];
354
+ partList.forEach((p, at) => {
355
+ if (!isObj(p) || typeof p.slot !== "string" || !p.slot) {
356
+ outcomes.push({ from: `parts[${at}]`, outcome: "unknown" });
357
+ return;
358
+ }
359
+ const row = typeof p.row === "string" && p.row ? p.row : undefined;
360
+ for (const [key, raw] of Object.entries(p)) {
361
+ if (key === "slot" || key === "row")
362
+ continue;
363
+ const from = `parts[${at}].${key}`;
364
+ const part = { slot: p.slot, at, ...(row ? { row } : {}), key };
365
+ if (raw === "" || raw === null) {
366
+ outcomes.push({ from, outcome: "ignored", part });
367
+ continue;
368
+ }
369
+ if (key === "crubal:count") {
370
+ outcomes.push({ from, to: key, outcome: "absorbed", value: raw, part });
371
+ continue;
372
+ }
373
+ const f = dict.facets.get(key);
374
+ if (!f) {
375
+ outcomes.push({ from, to: key, outcome: "unknown", value: raw, part });
376
+ continue;
377
+ }
378
+ const { value, outcome, cites } = foldIn(f, raw, undefined, dict);
379
+ outcomes.push({ from, to: key, outcome, value, part, ...(outcome === "contradiction" ? { cites: cites ?? { type: f.key } } : cites ? { cites } : {}) });
380
+ }
381
+ });
382
+ for (const [path, raw] of leaves(isObj(payload) ? Object.fromEntries(Object.entries(payload).filter(([k]) => k !== "parts")) : payload, "", (p) => c.reads.some((m) => samePath(m.from, p)))) {
383
+ // An empty string is no answer (chapter 3: what is absent stays absent); an empty is written as `$empty`.
384
+ if (raw === "") {
385
+ outcomes.push({ from: path, outcome: "ignored" });
386
+ continue;
387
+ }
388
+ if (!c.absorb || c.ignore.some((i) => samePath(i, path))) {
389
+ outcomes.push({ from: path, outcome: "ignored" });
390
+ continue;
391
+ }
392
+ const map = c.reads.find((m) => samePath(m.from, path));
393
+ if (map) {
394
+ const f = dict.facets.get(map.to);
395
+ if (!f) {
396
+ outcomes.push({ from: path, to: map.to, outcome: "unknown", value: raw });
397
+ continue;
398
+ }
399
+ const { value, outcome, cites } = foldIn(f, raw, map, dict);
400
+ outcomes.push({ from: path, to: map.to, outcome, value, ...(outcome === "contradiction" ? { cites: cites ?? { type: f.key } } : cites ? { cites } : {}) });
401
+ continue;
402
+ }
403
+ if (c.keepRaw.some((k) => samePath(k, path))) {
404
+ const name = fieldPath(path).at(-1);
405
+ if (!/^[A-Za-z_]\w*$/.test(name))
406
+ throw new CrubalError(`the raw field ${path} needs a map line: ${name} isn't a key name`, c.line);
407
+ outcomes.push({ from: path, to: `${c.prefix}:${name}`, outcome: "unknown", value: raw });
408
+ continue;
409
+ }
410
+ outcomes.push({ from: path, outcome: "unknown" });
411
+ }
412
+ return {
413
+ intake: intakeId,
414
+ contract: c.name,
415
+ for: forRecord,
416
+ raw: { type: "application/json", sha256: sha256(body), body },
417
+ outcomes,
418
+ };
419
+ }
420
+ // ─── Landing values: trust and alternatives (8.4, 9.3) ───────────────────────
421
+ const DEFAULT_TRUST = ["person", "observed", "declared", "reported", "derived"];
422
+ function matchAt(who, order) {
423
+ const hits = [who.person ? "person" : "", who.contract ?? "", who.source.owner ?? "", who.source.origin].filter(Boolean);
424
+ const at = order.findIndex((e) => hits.includes(e));
425
+ return at;
426
+ }
427
+ /** A source's rank under a facet's order then the package's (lower wins). */
428
+ function rank(who, trust, facetOrder = []) {
429
+ const f = matchAt(who, facetOrder);
430
+ if (f >= 0)
431
+ return f;
432
+ const p = matchAt(who, trust);
433
+ return facetOrder.length + (p >= 0 ? p : trust.length);
434
+ }
435
+ function sourceAt(r, address) {
436
+ return r.sources?.[address] ?? r.sources?.["*"];
437
+ }
438
+ /**
439
+ * Land an intake record's outcomes on a record. Absorbed and conflicting values go through the trust
440
+ * order: the winner is current, the loser is kept as an alternative. Equal values are agreement.
441
+ */
442
+ export function land(r, intake, source, trust = DEFAULT_TRUST, facetTrust = new Map(),
443
+ /** The facets declared `transitions: yes` (4.2): a later value of equal or higher trust replaces, never conflicts. */
444
+ transitions = new Set(),
445
+ /** The dictionary, for landing parts (5.6): which class a slot's parts wear, and the match child that binds a row. */
446
+ dict) {
447
+ const order = trust.length ? trust : DEFAULT_TRUST;
448
+ const incoming = { source, ...(intake.contract ? { contract: intake.contract } : {}), ...(intake.person ? { person: true } : {}) };
449
+ const out = {
450
+ ...r,
451
+ values: { ...r.values },
452
+ sources: { ...(r.sources ?? {}) },
453
+ };
454
+ // One value landing at an address: new, agreed, moved (a transition), or decided by the trust order with
455
+ // the loser kept as an alternative (9.3). The same for a record's values and a part's.
456
+ const settle = (address, facet, current, value) => {
457
+ if (current === undefined || (isObj(current) && current.$empty === "unknown")) {
458
+ out.sources[address] = source;
459
+ return value;
460
+ }
461
+ if (serialize(current) === serialize(value))
462
+ return undefined; // agreement: the current source stays
463
+ const was = sourceAt(out, address);
464
+ const fo = facetTrust.get(facet) ?? [];
465
+ const incomingRank = rank(incoming, order, fo);
466
+ const currentRank = rank({ source: was }, order, fo);
467
+ // A state facet moves: a later value of equal or higher trust is the transition, not a dispute (4.2).
468
+ if (transitions.has(facet) && incomingRank <= currentRank) {
469
+ out.sources[address] = source;
470
+ return value;
471
+ }
472
+ const incomingWins = incomingRank < currentRank;
473
+ const loser = incomingWins ? { value: current, origin: was.origin, via: was.via } : { value, origin: source.origin, via: source.via };
474
+ if (incomingWins)
475
+ out.sources[address] = source;
476
+ out.alternatives = { ...(out.alternatives ?? {}) };
477
+ out.alternatives[address] = [...(out.alternatives[address] ?? []), loser];
478
+ return incomingWins ? value : undefined;
479
+ };
480
+ for (const o of intake.outcomes) {
481
+ if (o.part || !o.to || o.value === undefined || !["absorbed", "conflict", "new"].includes(o.outcome))
482
+ continue;
483
+ const v = settle(o.to, o.to, out.values[o.to], o.value);
484
+ if (v !== undefined)
485
+ out.values[o.to] = v;
486
+ }
487
+ // Parts (5.6): the incoming parts bind to the record's rows (a named row binds by its key; else the slot's
488
+ // match child, else review, else a new row, 9.2), then each value lands on its part at `parts[row].key`.
489
+ const partOutcomes = intake.outcomes.filter((o) => o.part && o.to && o.value !== undefined && ["absorbed", "conflict", "new"].includes(o.outcome));
490
+ if (partOutcomes.length && dict) {
491
+ const byAt = new Map();
492
+ for (const o of partOutcomes) {
493
+ const p = o.part;
494
+ const have = byAt.get(p.at) ?? { slot: p.slot, ...(p.row ? { row: p.row } : {}), values: {} };
495
+ have.values[o.to] = o.value;
496
+ byAt.set(p.at, have);
497
+ }
498
+ const parts = [...(r.parts ?? [])].filter(isObj).map((p) => ({ ...p }));
499
+ const slotsWorn = (r.wears ?? []).flatMap((w) => dict.classes.get(w)?.parts ?? []);
500
+ const review = [];
501
+ const landOn = (row, slot, values) => {
502
+ const wears = slotsWorn.find((s) => s.slot === slot)?.wears ?? parts.find((p) => String(p.$row) === row)?.wears?.[0];
503
+ let part = parts.find((p) => String(p.$row) === row);
504
+ if (!part) {
505
+ part = { $row: row, ...(wears ? { wears: [wears] } : {}), values: {} };
506
+ parts.push(part);
507
+ }
508
+ const pv = { ...(isObj(part.values) ? part.values : {}) };
509
+ for (const [k, v] of Object.entries(values)) {
510
+ const landed = settle(`parts[${row}].${k}`, k, pv[k], v);
511
+ if (landed !== undefined)
512
+ pv[k] = landed;
513
+ }
514
+ part.values = pv;
515
+ };
516
+ // Every incoming part is bound in one pass (a named row by its key, the rest by the slot's match child),
517
+ // then each lands on its row; one the match left to review is not landed, and the review item says why.
518
+ const incoming = [...byAt.values()];
519
+ const { match, bound } = bindParts({ ...r, parts }, incoming.map((p) => ({ slot: p.slot, ...(p.row ? { row: p.row } : {}), ...p.values })), dict);
520
+ review.push(...match.review);
521
+ incoming.forEach((p, i) => {
522
+ const row = bound[i];
523
+ if (row)
524
+ landOn(row, p.slot, p.values);
525
+ });
526
+ if (parts.length)
527
+ out.parts = parts;
528
+ if (review.length)
529
+ out.review = [...((out.review) ?? []), ...review];
530
+ }
531
+ return out;
532
+ }
533
+ /** Bind incoming parts to existing ones: by the slot's match child, else review, else a new row. */
534
+ export function matchParts(r, incoming, dict) {
535
+ return bindParts(r, incoming, dict).match;
536
+ }
537
+ /**
538
+ * The binding with each incoming part's row beside it (5.6, 9.2): a part that names a `row` binds to the
539
+ * record's row of that key, or makes it; else the slot's match child; else, with an unmatched row of the
540
+ * slot still standing, review (no row); else a new row. `bound[i]` is the row the i-th incoming part
541
+ * landed on, or nothing when it went to review.
542
+ */
543
+ export function bindParts(r, incoming, dict) {
544
+ const slots = (r.wears ?? []).flatMap((w) => dict.classes.get(w)?.parts ?? []);
545
+ const existing = (r.parts ?? []).filter(isObj).map((p) => ({ p, matched: false }));
546
+ const result = new Map(existing.map(({ p }) => [String(p.$row), { $row: p.$row }]));
547
+ const review = [];
548
+ const minted = [];
549
+ const bound = [];
550
+ const keys = existing.map(({ p }) => String(p.$row));
551
+ const mint = () => {
552
+ const m = keys.map((k) => k.match(/^(\D+)(\d+)$/)).find(Boolean);
553
+ const prefix = m?.[1] ?? "r";
554
+ let n = Math.max(0, ...keys.map((k) => Number(k.match(/(\d+)$/)?.[1] ?? 0))) + 1;
555
+ while (keys.includes(`${prefix}${n}`))
556
+ n++;
557
+ keys.push(`${prefix}${n}`);
558
+ return `${prefix}${n}`;
559
+ };
560
+ for (const inc of incoming) {
561
+ const slot = slots.find((s) => s.slot === inc.slot);
562
+ const inSlot = existing.filter(({ p }) => Array.isArray(p.wears) && slot && p.wears.includes(slot.wears));
563
+ const by = slot?.match;
564
+ // A named row binds by its key (1.6): the row the record holds under it, else a new row under that key.
565
+ if (typeof inc.row === "string" && inc.row) {
566
+ const named = existing.find(({ p }) => String(p.$row) === inc.row);
567
+ if (named) {
568
+ named.matched = true;
569
+ result.set(inc.row, { $row: inc.row, matched: "row", from: inc.row });
570
+ }
571
+ else if (!keys.includes(inc.row)) {
572
+ keys.push(inc.row);
573
+ minted.push({ $row: inc.row, new: true, from: inc.row });
574
+ }
575
+ bound.push(inc.row);
576
+ continue;
577
+ }
578
+ const want = by && typeof inc[by] === "string" ? foldKey(inc[by]) : null;
579
+ const hit = want ? inSlot.find(({ p, matched }) => !matched && isObj(p.values) && foldKey(String(p.values[by] ?? "")) === want) : undefined;
580
+ const label = String(by ? inc[by] : inc.slot);
581
+ if (hit) {
582
+ hit.matched = true;
583
+ result.set(String(hit.p.$row), { $row: hit.p.$row, matched: by, from: label });
584
+ bound.push(String(hit.p.$row));
585
+ continue;
586
+ }
587
+ const could = inSlot.filter((x) => !x.matched);
588
+ if (could.length) {
589
+ const names = could.map(({ p }) => String(p.$row)).join(", ");
590
+ review.push({ address: "parts", from: label, reason: `could be the same part as ${names} (${inc.slot}); not matched by ${by ?? "identity"}` });
591
+ bound.push(undefined);
592
+ continue;
593
+ }
594
+ const row = mint();
595
+ minted.push({ $row: row, new: true, from: label });
596
+ bound.push(row);
597
+ }
598
+ return { match: { parts: [...result.values(), ...minted], review }, bound };
599
+ }
600
+ /** Validate a value from observations: independent witnesses for and against, vetoes, and the state. */
601
+ export function validate(r, address, observations, confirmAt = 2, splitAt = 3) {
602
+ const current = serialize(r.values[address] ?? "");
603
+ const mine = observations.filter((o) => o.supports === r.id && o.address === address);
604
+ const witness = (o) => `${o.on}|${o["evidence-type"] ?? ""}`;
605
+ const forW = new Set();
606
+ const againstW = new Set();
607
+ const vetoes = [];
608
+ const against = new Map();
609
+ for (const o of mine) {
610
+ if (o.veto !== undefined) {
611
+ if (serialize(o.veto) === current)
612
+ vetoes.push(o);
613
+ continue;
614
+ }
615
+ if (serialize(o.value) === current)
616
+ forW.add(witness(o));
617
+ else {
618
+ againstW.add(witness(o));
619
+ const k = serialize(o.value);
620
+ const g = against.get(k) ?? { value: o.value, instances: new Set() };
621
+ g.instances.add(o.on);
622
+ against.set(k, g);
623
+ }
624
+ }
625
+ const out = {
626
+ record: r.id,
627
+ address,
628
+ "witnesses-for": forW.size,
629
+ "witnesses-against": againstW.size,
630
+ vetoes: vetoes.length,
631
+ };
632
+ if (vetoes.length) {
633
+ out.state = "contradicted";
634
+ out.cites = { veto: vetoes[0].obs };
635
+ }
636
+ else if (againstW.size)
637
+ out.state = "contradicted";
638
+ else if (forW.size >= confirmAt)
639
+ out.state = "confirmed";
640
+ else
641
+ out.state = "unobserved";
642
+ out.alternatives = [...against.values()].map((g) => ({ value: g.value, origin: "observed" }));
643
+ out["split-proposed"] = [...against.values()].some((g) => g.instances.size >= splitAt);
644
+ out.clusters = [...against.values()].map((g) => ({ value: g.value, instances: [...g.instances].sort() }));
645
+ return out;
646
+ }
647
+ /**
648
+ * Version splits proposed (9.7.3): for each value an address's observations contradict, a cluster of at
649
+ * least `splitAt` instances agreeing with each other is a review item `split:<record>`; nothing splits
650
+ * on its own.
651
+ */
652
+ export function proposeSplit(records, observations, splitAt = 3) {
653
+ const out = [];
654
+ const seen = new Set();
655
+ for (const o of observations) {
656
+ const key = `${o.supports}|${o.address}`;
657
+ if (seen.has(key))
658
+ continue;
659
+ seen.add(key);
660
+ const r = records.find((x) => x.id === o.supports);
661
+ if (!r)
662
+ continue;
663
+ const v = validate(r, o.address, observations, 2, splitAt);
664
+ for (const c of v.clusters ?? []) {
665
+ if (c.instances.length >= splitAt)
666
+ out.push({ key: `split:${r.id}`, record: r.id, address: o.address, value: c.value, instances: c.instances });
667
+ }
668
+ }
669
+ return out;
670
+ }
671
+ //# sourceMappingURL=store.js.map