githolon 0.97.0 → 0.97.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.
@@ -0,0 +1,2829 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
11
+ // ../adapter/git-fs.ts
12
+ function fsErr(code, p) {
13
+ const e = new Error(`${code}: ${p}`);
14
+ e.code = code;
15
+ return e;
16
+ }
17
+ function makeGitFs(preopen, mount, { File: File2, Directory: Directory2 }) {
18
+ const root = preopen.dir;
19
+ const isDir = (n) => !!n && n.contents instanceof Map;
20
+ function parts(p) {
21
+ if (p === mount) return [];
22
+ if (!p.startsWith(mount + "/")) throw fsErr("ENOENT", p);
23
+ const rel = p.slice(mount.length + 1).replace(/\/+$/, "");
24
+ return rel === "" ? [] : rel.split("/");
25
+ }
26
+ function resolve(ps) {
27
+ let cur = root;
28
+ for (const part of ps) {
29
+ if (!isDir(cur)) return null;
30
+ const next = cur.contents.get(part);
31
+ if (next === void 0) return null;
32
+ cur = next;
33
+ }
34
+ return cur;
35
+ }
36
+ const parent = (ps) => resolve(ps.slice(0, -1));
37
+ const leaf = (ps) => ps[ps.length - 1];
38
+ const promises = {
39
+ async readFile(p, opts) {
40
+ const n = resolve(parts(p));
41
+ if (n === null) throw fsErr("ENOENT", p);
42
+ if (isDir(n)) throw fsErr("EISDIR", p);
43
+ const data = n.data ?? new Uint8Array(0);
44
+ const encoding = typeof opts === "string" ? opts : opts && opts.encoding;
45
+ return encoding ? new TextDecoder().decode(data) : new Uint8Array(data);
46
+ },
47
+ async writeFile(p, data) {
48
+ const ps = parts(p);
49
+ const par = parent(ps);
50
+ if (!isDir(par)) throw fsErr("ENOENT", p);
51
+ const bytes = typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data);
52
+ par.contents.set(leaf(ps), new File2(bytes));
53
+ },
54
+ async unlink(p) {
55
+ const ps = parts(p), par = parent(ps);
56
+ if (!isDir(par) || !par.contents.delete(leaf(ps))) throw fsErr("ENOENT", p);
57
+ },
58
+ async readdir(p) {
59
+ const n = resolve(parts(p));
60
+ if (n === null) throw fsErr("ENOENT", p);
61
+ if (!isDir(n)) throw fsErr("ENOTDIR", p);
62
+ return [...n.contents.keys()];
63
+ },
64
+ async mkdir(p) {
65
+ const ps = parts(p), par = parent(ps);
66
+ if (!isDir(par)) throw fsErr("ENOENT", p);
67
+ if (par.contents.has(leaf(ps))) throw fsErr("EEXIST", p);
68
+ par.contents.set(leaf(ps), new Directory2(/* @__PURE__ */ new Map()));
69
+ },
70
+ async rmdir(p) {
71
+ const ps = parts(p), par = parent(ps);
72
+ if (!isDir(par)) throw fsErr("ENOENT", p);
73
+ par.contents.delete(leaf(ps));
74
+ },
75
+ async stat(p) {
76
+ return promises.lstat(p);
77
+ },
78
+ async lstat(p) {
79
+ const n = resolve(parts(p));
80
+ if (n === null) throw fsErr("ENOENT", p);
81
+ const dir = isDir(n);
82
+ return {
83
+ type: dir ? "dir" : "file",
84
+ mode: dir ? 16384 : 33188,
85
+ size: dir ? 0 : n.data ? n.data.length : 0,
86
+ ino: 0,
87
+ mtimeMs: 0,
88
+ ctimeMs: 0,
89
+ uid: 1,
90
+ gid: 1,
91
+ dev: 1,
92
+ isFile: () => !dir,
93
+ isDirectory: () => dir,
94
+ isSymbolicLink: () => false
95
+ };
96
+ },
97
+ async readlink(p) {
98
+ throw fsErr("EINVAL", p);
99
+ },
100
+ async symlink() {
101
+ throw fsErr("EPERM", "symlink unsupported");
102
+ },
103
+ async chmod() {
104
+ }
105
+ };
106
+ return { promises };
107
+ }
108
+ var init_git_fs = __esm({
109
+ "../adapter/git-fs.ts"() {
110
+ "use strict";
111
+ }
112
+ });
113
+
114
+ // ../adapter/tree.ts
115
+ function flatten(dir, prefix, out) {
116
+ for (const [name, inode] of dir.contents ?? /* @__PURE__ */ new Map()) {
117
+ const path2 = prefix ? prefix + "/" + name : name;
118
+ if (inode.contents instanceof Map) {
119
+ out.push({ path: path2, dir: true });
120
+ flatten(inode, path2, out);
121
+ } else {
122
+ out.push({ path: path2, dir: false, bytes: inode.data ?? new Uint8Array(0) });
123
+ }
124
+ }
125
+ }
126
+ function serializeTree(workTree) {
127
+ const entries = [];
128
+ flatten(workTree, "", entries);
129
+ const chunks = [];
130
+ const header = new Uint8Array(4);
131
+ new DataView(header.buffer).setUint32(0, entries.length, true);
132
+ chunks.push(header);
133
+ for (const e of entries) {
134
+ const pathBytes = enc.encode(e.path);
135
+ const body = e.dir ? new Uint8Array(0) : e.bytes ?? new Uint8Array(0);
136
+ const meta = new Uint8Array(9);
137
+ const dv = new DataView(meta.buffer);
138
+ dv.setUint8(0, e.dir ? 1 : 0);
139
+ dv.setUint32(1, pathBytes.length, true);
140
+ dv.setUint32(5, body.length, true);
141
+ chunks.push(meta, pathBytes, body);
142
+ }
143
+ let total = 0;
144
+ for (const c of chunks) total += c.length;
145
+ const out = new Uint8Array(total);
146
+ let off = 0;
147
+ for (const c of chunks) {
148
+ out.set(c, off);
149
+ off += c.length;
150
+ }
151
+ return out;
152
+ }
153
+ var enc, dec;
154
+ var init_tree = __esm({
155
+ "../adapter/tree.ts"() {
156
+ "use strict";
157
+ enc = new TextEncoder();
158
+ dec = new TextDecoder();
159
+ }
160
+ });
161
+
162
+ // ../adapter/custody-transport.ts
163
+ function concatBytes(chunks) {
164
+ let n = 0;
165
+ for (const c of chunks) n += c.length;
166
+ const out = new Uint8Array(n);
167
+ let o = 0;
168
+ for (const c of chunks) {
169
+ out.set(c, o);
170
+ o += c.length;
171
+ }
172
+ return out;
173
+ }
174
+ function pkt(payload) {
175
+ const body = typeof payload === "string" ? enc2.encode(payload) : payload;
176
+ const len = (body.length + 4).toString(16).padStart(4, "0");
177
+ return concatBytes([enc2.encode(len), body]);
178
+ }
179
+ function readPktLines(buf, off = 0) {
180
+ const lines = [];
181
+ while (off + 4 <= buf.length) {
182
+ const hex = dec2.decode(buf.subarray(off, off + 4));
183
+ if (!/^[0-9a-f]{4}$/.test(hex)) break;
184
+ const len = parseInt(hex, 16);
185
+ if (len === 0) {
186
+ off += 4;
187
+ break;
188
+ }
189
+ if (len < 4 || off + len > buf.length) break;
190
+ lines.push(buf.subarray(off + 4, off + len));
191
+ off += len;
192
+ }
193
+ return { lines, rest: off };
194
+ }
195
+ async function lsRefs(remote, headers = {}, { service = "git-upload-pack", prefix = null } = {}) {
196
+ const r = await fetch(`${remote}/info/refs?service=${service}`, { headers });
197
+ if (!r.ok) {
198
+ if (r.status === 404) return {};
199
+ throw new Error(`info/refs ${r.status}: ${(await r.text()).slice(0, 180)}`);
200
+ }
201
+ const buf = new Uint8Array(await r.arrayBuffer());
202
+ const banner = readPktLines(buf, 0);
203
+ const { lines } = readPktLines(buf, banner.rest);
204
+ const refs = {};
205
+ for (const line of lines) {
206
+ let s = dec2.decode(line).replace(/\n$/, "");
207
+ if (s.startsWith("#")) continue;
208
+ const nul = s.indexOf("\0");
209
+ if (nul >= 0) s = s.slice(0, nul);
210
+ const sp = s.indexOf(" ");
211
+ if (sp !== 40) continue;
212
+ const oid = s.slice(0, 40), name = s.slice(41);
213
+ if (!/^[0-9a-f]{40}$/.test(oid)) continue;
214
+ if (prefix && !name.startsWith(prefix)) continue;
215
+ refs[name] = oid;
216
+ }
217
+ return refs;
218
+ }
219
+ async function fetchPack(remote, headers = {}, { wants = [], haves = [] } = {}) {
220
+ wants = wants.filter((w) => /^[0-9a-f]{40}$/.test(w) && w !== ZERO_OID);
221
+ if (!wants.length) return null;
222
+ const caps = "thin-pack ofs-delta agent=nomos-cloud";
223
+ const parts = [];
224
+ wants.forEach((w, i) => parts.push(pkt(`want ${w}${i === 0 ? " " + caps : ""}
225
+ `)));
226
+ parts.push(FLUSH);
227
+ for (const h of haves) if (/^[0-9a-f]{40}$/.test(h) && h !== ZERO_OID) parts.push(pkt(`have ${h}
228
+ `));
229
+ parts.push(pkt("done\n"));
230
+ const r = await fetch(`${remote}/git-upload-pack`, {
231
+ method: "POST",
232
+ headers: { "content-type": "application/x-git-upload-pack-request", "accept": "application/x-git-upload-pack-result", ...headers },
233
+ body: concatBytes(parts)
234
+ });
235
+ if (!r.ok) throw new Error(`upload-pack ${r.status}: ${(await r.text()).slice(0, 180)}`);
236
+ const buf = new Uint8Array(await r.arrayBuffer());
237
+ const { lines, rest } = readPktLines(buf, 0);
238
+ const packChunks = [];
239
+ let sideband = false;
240
+ for (const line of lines) {
241
+ if (line.length === 0) continue;
242
+ const head = dec2.decode(line.subarray(0, Math.min(line.length, 3)));
243
+ if (head === "NAK" || head === "ACK" || head === "ERR" || head.startsWith("sha")) continue;
244
+ const band = line[0];
245
+ if (band === 1) {
246
+ packChunks.push(line.subarray(1));
247
+ sideband = true;
248
+ } else if (band === 2) {
249
+ } else if (band === 3) {
250
+ throw new Error("upload-pack fatal: " + dec2.decode(line.subarray(1)).slice(0, 180));
251
+ }
252
+ }
253
+ const pack = sideband ? concatBytes(packChunks) : buf.subarray(rest);
254
+ if (pack.length < 12 || dec2.decode(pack.subarray(0, 4)) !== "PACK") {
255
+ throw new Error(`upload-pack: no pack in response (${pack.length}B, sideband=${sideband})`);
256
+ }
257
+ return pack;
258
+ }
259
+ async function pushPack(remote, headers = {}, { updates = [], pack = null } = {}) {
260
+ if (!updates.length) return { ok: true, noop: true };
261
+ const cmds = [];
262
+ updates.forEach((u, i) => {
263
+ const old = u.oldOid || ZERO_OID;
264
+ const neu = u.newOid || ZERO_OID;
265
+ const caps = i === 0 ? "\0report-status" : "";
266
+ cmds.push(pkt(`${old} ${neu} ${u.ref}${caps}
267
+ `));
268
+ });
269
+ cmds.push(FLUSH);
270
+ const body = concatBytes([...cmds, pack && pack.length ? pack : EMPTY_PACK]);
271
+ const r = await fetch(`${remote}/git-receive-pack`, {
272
+ method: "POST",
273
+ headers: { "content-type": "application/x-git-receive-pack-request", ...headers },
274
+ body
275
+ });
276
+ const txt = dec2.decode(new Uint8Array(await r.arrayBuffer()));
277
+ const unpacked = /unpack ok/.test(txt);
278
+ const everyRefOk = updates.every((u) => new RegExp(`ok ${u.ref.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`).test(txt));
279
+ if (!(r.ok && unpacked && everyRefOk && !/\bng /.test(txt))) {
280
+ throw new Error(`receive-pack ${r.status}: ${txt.replace(/[^\x20-\x7e]/g, " ").trim().slice(0, 200)}`);
281
+ }
282
+ return { ok: true };
283
+ }
284
+ var enc2, dec2, ZERO_OID, EMPTY_PACK, FLUSH;
285
+ var init_custody_transport = __esm({
286
+ "../adapter/custody-transport.ts"() {
287
+ "use strict";
288
+ enc2 = new TextEncoder();
289
+ dec2 = new TextDecoder();
290
+ ZERO_OID = "0".repeat(40);
291
+ EMPTY_PACK = new Uint8Array([
292
+ 80,
293
+ 65,
294
+ 67,
295
+ 75,
296
+ 0,
297
+ 0,
298
+ 0,
299
+ 2,
300
+ 0,
301
+ 0,
302
+ 0,
303
+ 0,
304
+ // "PACK", ver 2, 0 objects
305
+ 2,
306
+ 157,
307
+ 8,
308
+ 130,
309
+ 59,
310
+ 216,
311
+ 168,
312
+ 234,
313
+ 181,
314
+ 16,
315
+ 173,
316
+ 106,
317
+ // sha1(the 12 header bytes)
318
+ 199,
319
+ 92,
320
+ 130,
321
+ 60,
322
+ 253,
323
+ 62,
324
+ 211,
325
+ 30
326
+ ]);
327
+ FLUSH = enc2.encode("0000");
328
+ }
329
+ });
330
+
331
+ // ../adapter/engine.ts
332
+ import { WASI, File, Directory, OpenFile, ConsoleStdout, PreopenDirectory } from "@bjorn3/browser_wasi_shim";
333
+ function b64Bytes(bytes) {
334
+ let s = "";
335
+ for (let i = 0; i < bytes.length; i += 32768) {
336
+ s += String.fromCharCode(...bytes.subarray(i, i + 32768));
337
+ }
338
+ return btoa(s);
339
+ }
340
+ function b64Json(o) {
341
+ return b64Bytes(enc3.encode(JSON.stringify(o)));
342
+ }
343
+ async function sha256hex(t) {
344
+ const b = await crypto.subtle.digest("SHA-256", enc3.encode(t));
345
+ return [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
346
+ }
347
+ function osEntropyBuffer(n) {
348
+ const bytes = new Uint8Array(n * 8);
349
+ for (let o = 0; o < bytes.length; o += 65536) crypto.getRandomValues(bytes.subarray(o, Math.min(o + 65536, bytes.length)));
350
+ const out = new Array(n), T = 2 ** 53;
351
+ for (let i = 0; i < n; i++) {
352
+ let z = 0n;
353
+ for (let b = 7; b >= 0; b--) z = z << 8n | BigInt(bytes[i * 8 + b]);
354
+ out[i] = Number(z >> 11n) / T;
355
+ }
356
+ return out;
357
+ }
358
+ function stringifyBig(o) {
359
+ return JSON.stringify(o, (_k, v) => typeof v === "bigint" ? `@@B:${v}@@` : v).replace(/"@@B:(\d+)@@"/g, "$1");
360
+ }
361
+ function call(ex, mode, fields, STDERR) {
362
+ const req = enc3.encode(JSON.stringify({ mode, ...fields }));
363
+ const reqPtr = ex.git_holon_alloc(req.length);
364
+ try {
365
+ new Uint8Array(ex.memory.buffer, reqPtr, req.length).set(req);
366
+ let packed;
367
+ try {
368
+ packed = ex.git_holon_call(reqPtr, req.length);
369
+ } catch (e) {
370
+ const tail = STDERR.length ? ` | stderr: ${STDERR.slice(-8).join(" / ")}` : "";
371
+ throw new Error(`${String(e?.stack || e)}${tail}`);
372
+ }
373
+ const { ptr, len } = unpack(packed);
374
+ try {
375
+ const e = JSON.parse(dec3.decode(new Uint8Array(ex.memory.buffer, ptr, len).slice()));
376
+ if (!e.ok) throw new Error((e.error || "holon error") + (STDERR.length ? ` | ${STDERR.slice(-4).join(" / ")}` : ""));
377
+ return e.result;
378
+ } finally {
379
+ ex.git_holon_dealloc(ptr, len);
380
+ }
381
+ } finally {
382
+ ex.git_holon_dealloc(reqPtr, req.length);
383
+ }
384
+ }
385
+ async function createEngine({ wasmModule, bootstrapPkg, nomosPkg, replica, installedBy = "nomos-cloud" }) {
386
+ const hashes = { bootstrap: await sha256hex(bootstrapPkg), nomos: await sha256hex(nomosPkg) };
387
+ const root = /* @__PURE__ */ new Map();
388
+ root.set("domain.package.usda", new File(enc3.encode(bootstrapPkg)));
389
+ root.set("ws", new Directory(/* @__PURE__ */ new Map()));
390
+ const preopen = new PreopenDirectory("/work", root);
391
+ const STDERR = [];
392
+ const pushStderr = (l) => {
393
+ if (STDERR.length >= 500) STDERR.splice(0, STDERR.length - 499);
394
+ STDERR.push(l);
395
+ };
396
+ const fds = [new OpenFile(new File([])), ConsoleStdout.lineBuffered(() => {
397
+ }), ConsoleStdout.lineBuffered(pushStderr), preopen];
398
+ const wasi = new WASI(["wasm_git_holon", "reactor"], [], fds, { debug: false });
399
+ const inst = await WebAssembly.instantiate(wasmModule, { wasi_snapshot_preview1: wasi.wasiImport });
400
+ const code = wasi.start(inst);
401
+ if (code !== 0) throw new Error(`reactor init exited ${code}; stderr=${STDERR.join("\n")}`);
402
+ const instExports = inst.exports;
403
+ for (const n of ["memory", "git_holon_alloc", "git_holon_dealloc", "git_holon_call"]) if (!instExports[n]) throw new Error(`missing export ${n}`);
404
+ const eng = {
405
+ ex: instExports,
406
+ preopen,
407
+ STDERR,
408
+ seq: 0,
409
+ replica,
410
+ hashes,
411
+ bootstrapPkg,
412
+ nomosPkg,
413
+ installedBy,
414
+ fs: makeGitFs(preopen, "/work", { File, Directory }),
415
+ mounted: /* @__PURE__ */ new Map(),
416
+ // ws -> { restored, remoteMain, restoreError }
417
+ mainIntents: /* @__PURE__ */ new Map()
418
+ // ws -> { head, ids:Set, oids:Set } (admission idempotence)
419
+ };
420
+ return eng;
421
+ }
422
+ function directiveRoutes(eng) {
423
+ return /* @__PURE__ */ new Map();
424
+ }
425
+ function routeTagHexOfMintedId(id) {
426
+ const i = id.indexOf("_");
427
+ if (i <= 0) return void 0;
428
+ const body = id.slice(i + 1).replace(/-/g, "").toLowerCase();
429
+ return /^[0-9a-f]{32}$/.test(body) ? body.slice(0, 12) : void 0;
430
+ }
431
+ async function wrongHomeVerdict(shardRouting, route, payload) {
432
+ const value = payload ? payload[route.key] : void 0;
433
+ if (typeof value !== "string" || !value) return null;
434
+ const rows = await shardRouting.assignments() || [];
435
+ let assignment = null;
436
+ if (route.via === "axis") {
437
+ assignment = rows.find((a) => a.homeKey === value) || null;
438
+ } else {
439
+ const tag = routeTagHexOfMintedId(value);
440
+ if (tag !== void 0) {
441
+ for (const a of rows) {
442
+ if (await routeTagHexOfHomeKey(String(a.homeKey)) === tag) {
443
+ assignment = a;
444
+ break;
445
+ }
446
+ }
447
+ }
448
+ }
449
+ if (!assignment) {
450
+ return {
451
+ error: `no shard placement for this write's home ('${route.key}': ${value.slice(0, 80)}) \u2014 author the derived placement intent (birth<Type>) on the coordinator '${shardRouting.coordinatorWs}' first, then POST /dead-letters/retry`,
452
+ deadLettered: true
453
+ };
454
+ }
455
+ const movingTo = typeof assignment.status === "string" && assignment.status.startsWith("moving:") ? assignment.status.slice("moving:".length) : null;
456
+ if (movingTo) {
457
+ return {
458
+ error: `home-moving: home '${value.slice(0, 80)}' is migrating ${assignment.shard} -> ${movingTo} (shard map v${assignment.mapVersion ?? 1}) \u2014 parked; a routed client retries automatically after the handoff seals`,
459
+ homeMoving: { homeKey: value, from: assignment.shard, target: movingTo, workspace: `${shardRouting.coordinatorWs}--${movingTo}` },
460
+ deadLettered: true
461
+ };
462
+ }
463
+ if (shardRouting.selfLabel === assignment.shard) return null;
464
+ const correct = `${shardRouting.coordinatorWs}--${assignment.shard}`;
465
+ return {
466
+ error: `wrong-home: this write's home is assigned to '${correct}' (shard map v${assignment.mapVersion ?? 1}) \u2014 the client's shard map is stale; a routed client re-routes and retries automatically`,
467
+ wrongHome: { workspace: correct, ...assignment.mapVersion !== void 0 ? { mapVersion: assignment.mapVersion } : {} }
468
+ };
469
+ }
470
+ function tenantTypes(eng) {
471
+ return /* @__PURE__ */ new Set();
472
+ }
473
+ function placementDirectives(eng) {
474
+ return /* @__PURE__ */ new Map();
475
+ }
476
+ function scopedReads(eng) {
477
+ return [];
478
+ }
479
+ function globalAggregates(eng) {
480
+ return /* @__PURE__ */ new Set();
481
+ }
482
+ function parseIntentEvents(blob) {
483
+ let doc;
484
+ try {
485
+ doc = JSON.parse(dec3.decode(blob));
486
+ } catch {
487
+ return [];
488
+ }
489
+ const events = Array.isArray(doc && doc.events) ? doc.events : [];
490
+ return events.map((ev) => {
491
+ const sets = /* @__PURE__ */ new Map();
492
+ for (const op of ev.ops || []) {
493
+ const v = op && op.op && op.op.Set;
494
+ if (v === void 0) continue;
495
+ if (typeof v.Str === "string") sets.set(op.field, v.Str);
496
+ else if (typeof v.Int === "number") sets.set(op.field, v.Int);
497
+ }
498
+ return { aggregate: String(ev.aggregate || ""), sets };
499
+ });
500
+ }
501
+ function beginSummaryCapture(eng, ws, ctx, blob) {
502
+ const events = parseIntentEvents(blob);
503
+ if (events.length === 0) return null;
504
+ const pre = /* @__PURE__ */ new Map();
505
+ const candidates = /* @__PURE__ */ new Set();
506
+ for (const ev of events) {
507
+ if (!pre.has(ev.aggregate)) {
508
+ const rows = qById(eng, ws, ev.aggregate);
509
+ pre.set(ev.aggregate, rows.length ? { type: rows[0].type, data: rows[0].data || {} } : null);
510
+ }
511
+ const before = pre.get(ev.aggregate);
512
+ const evType = ev.sets.get("__type") ?? (before ? before.type : void 0);
513
+ for (const read of ctx.reads) {
514
+ if (read.of !== evType) continue;
515
+ const oldGroup = before ? groupOf(read, before.data) : void 0;
516
+ if (oldGroup !== void 0) candidates.add(summaryKey(read.id, oldGroup));
517
+ if (read.by === null) candidates.add(summaryKey(read.id, ""));
518
+ else if (ev.sets.has(read.by)) candidates.add(summaryKey(read.id, String(ev.sets.get(read.by))));
519
+ }
520
+ }
521
+ const preTallies = /* @__PURE__ */ new Map();
522
+ for (const key of candidates) {
523
+ const [readId, group] = splitSummaryKey(key);
524
+ const read = ctx.reads.find((r) => r.id === readId);
525
+ const v = tallyOf(eng, ws, read, group);
526
+ preTallies.set(key, v);
527
+ if (!ctx.prevs.has(key)) ctx.prevs.set(key, { read, group, value: v });
528
+ }
529
+ return { events, pre, candidates, preTallies };
530
+ }
531
+ function finishSummaryCapture(eng, ws, ctx, cap, oid, intentId) {
532
+ const deltas = [];
533
+ for (const key of cap.candidates) {
534
+ const [readId, group] = splitSummaryKey(key);
535
+ const read = ctx.reads.find((r) => r.id === readId);
536
+ const after = tallyOf(eng, ws, read, group);
537
+ if (isExtremumRead(read)) {
538
+ const before = cap.preTallies.has(key) ? cap.preTallies.get(key) : null;
539
+ if (after !== before) {
540
+ deltas.push({ readId, group, delta: after });
541
+ if (!extremumMonotone(read, before, after)) ctx.rederived.add(key);
542
+ }
543
+ } else {
544
+ const before = cap.preTallies.get(key) ?? 0;
545
+ if (after !== before) deltas.push({ readId, group, delta: after - before });
546
+ }
547
+ ctx.values.set(key, { read, group, value: after });
548
+ }
549
+ let rowsDelta = 0;
550
+ for (const [aggregateId, before] of cap.pre) {
551
+ const rows = qById(eng, ws, aggregateId);
552
+ const type = rows.length ? rows[0].type : before ? before.type : void 0;
553
+ if (type === void 0 || !tenantTypes(eng).has(type)) continue;
554
+ const existsAfter = rows.length > 0;
555
+ const flip = !before && existsAfter ? 1 : before && !existsAfter ? -1 : 0;
556
+ if (flip === 0) continue;
557
+ rowsDelta += flip;
558
+ const homeKey = ctx.homeKeySet && ctx.homeKeySet.has(aggregateId) ? aggregateId : ctx.homeTags ? ctx.homeTags.get(routeTagHexOfMintedId(aggregateId) ?? "") : void 0;
559
+ if (homeKey !== void 0) {
560
+ deltas.push({ readId: NOMOS_SHARD_ROWS_READ, group: homeKey, delta: flip });
561
+ ctx.rowsByHome.set(homeKey, (ctx.rowsByHome.get(homeKey) ?? 0) + flip);
562
+ }
563
+ }
564
+ if (rowsDelta !== 0) {
565
+ deltas.push({ readId: NOMOS_SHARD_ROWS_READ, group: "", delta: rowsDelta });
566
+ ctx.rowsDelta += rowsDelta;
567
+ }
568
+ if (deltas.length > 0) ctx.events.push({ oid, intentId: intentId || "", deltas });
569
+ }
570
+ function summaryOfCapture(ctx, fromOid, toOid) {
571
+ if (ctx.events.length === 0 || !toOid || fromOid === toOid) return null;
572
+ const touched = /* @__PURE__ */ new Set();
573
+ for (const ev of ctx.events) for (const d of ev.deltas) touched.add(summaryKey(d.readId, d.group));
574
+ const subtotals = [];
575
+ for (const [key, cur] of ctx.values) {
576
+ const extremum2 = isExtremumRead(cur.read);
577
+ const prev = ctx.prevs.get(key);
578
+ const prevValue = prev ? prev.value : extremum2 ? null : 0;
579
+ if (cur.value === prevValue && !touched.has(key)) continue;
580
+ subtotals.push({
581
+ readId: cur.read.id,
582
+ group: cur.group,
583
+ kind: cur.read.kind,
584
+ prev: prevValue,
585
+ value: cur.value,
586
+ ...extremum2 && ctx.rederived.has(key) ? { rederived: true } : {}
587
+ });
588
+ }
589
+ if (subtotals.length === 0 && ctx.rowsDelta === 0 && ctx.rowsByHome.size === 0) return null;
590
+ return {
591
+ fromOid: fromOid || "",
592
+ toOid,
593
+ subtotals: subtotals.sort((a, b) => summaryKey(a.readId, a.group) < summaryKey(b.readId, b.group) ? -1 : 1),
594
+ events: ctx.events,
595
+ rowsDelta: ctx.rowsDelta,
596
+ // SLICE 8: the exact per-home row deltas — the adapter closes each against the
597
+ // coordinator-held per-home subtotal exactly like the "" grand total.
598
+ rowsByHome: Object.fromEntries([...ctx.rowsByHome.entries()].sort((a, b) => a[0] < b[0] ? -1 : 1))
599
+ };
600
+ }
601
+ async function admitIntentOffers(eng, ws, ledger, offers, { receiptFence = null, shardRouting = null, clientBase = null, defer = false } = {}) {
602
+ const main = await mainIntentIds(eng, ws);
603
+ const sessions = /* @__PURE__ */ new Map();
604
+ const deadLetters = [];
605
+ let admittedTotal = 0;
606
+ const born = [];
607
+ const birthOutcomes = [];
608
+ const timings = { spans: [], intents: 0, sessions: 0 };
609
+ const summaryCtx = shardRouting && shardRouting.selfLabel && scopedReads(eng).length > 0 ? { reads: scopedReads(eng), prevs: /* @__PURE__ */ new Map(), values: /* @__PURE__ */ new Map(), events: [], rowsDelta: 0, rederived: /* @__PURE__ */ new Set(), rowsByHome: /* @__PURE__ */ new Map(), homeTags: /* @__PURE__ */ new Map(), homeKeySet: /* @__PURE__ */ new Set() } : null;
610
+ if (summaryCtx) {
611
+ try {
612
+ for (const r of query(eng, ws, "aggregatesByType", JSON.stringify({ __type: "NomosHomeReceipt" }))) {
613
+ const hk = r.data && typeof r.data.homeKey === "string" ? r.data.homeKey : null;
614
+ if (!hk) continue;
615
+ summaryCtx.homeKeySet.add(hk);
616
+ summaryCtx.homeTags.set(await routeTagHexOfHomeKey(hk), hk);
617
+ }
618
+ } catch (e) {
619
+ log("home-tag-table-error", { ws, error: String(e).slice(0, 200) });
620
+ }
621
+ }
622
+ const gitdir0 = gitdirOf(ws);
623
+ const headBefore = summaryCtx ? kgit.resolveRef(eng, gitdir0, BRANCH) : null;
624
+ const t0 = Date.now();
625
+ let seq = 0;
626
+ const span = (name, kind, depth = 1, extra = {}) => {
627
+ const s0 = Date.now();
628
+ return (end = {}) => timings.spans.push({ id: `intent-offer-${t0}-${seq++}`, track: "cloud", name, kind, depth, t0: s0, t1: Date.now(), ...extra, ...end });
629
+ };
630
+ for (const offer of Array.isArray(offers) ? offers : []) {
631
+ const cid = typeof offer?.session === "string" && offer.session ? offer.session : "direct";
632
+ const rec = sessions.get(cid) || { session: cid, admitted: [], rejected: [], skipped: [] };
633
+ sessions.set(cid, rec);
634
+ const done = span(`intent offer ${cid.slice(0, 14)}`, "cadmit", 1, { client: cid });
635
+ let blob = offer?.blob instanceof Uint8Array ? offer.blob : null;
636
+ try {
637
+ if (!blob && typeof offer?.intentB64 === "string") blob = Uint8Array.from(atob(offer.intentB64), (c) => c.charCodeAt(0));
638
+ const maxOfferBytes = offer?.staged ? 64 * 1024 * 1024 : 32 * 1024 * 1024;
639
+ if (!blob || blob.byteLength === 0 || blob.byteLength > maxOfferBytes) {
640
+ rec.rejected.push({ oid: String(offer?.oid || "").slice(0, 10), error: `intent offer must carry intentB64 <= ${maxOfferBytes / (1024 * 1024)} MiB` });
641
+ continue;
642
+ }
643
+ let doc = null;
644
+ try {
645
+ doc = JSON.parse(dec3.decode(blob));
646
+ } catch {
647
+ }
648
+ const intentId = typeof doc?.id === "string" ? doc.id : null;
649
+ const dom = typeof doc?.payload?.domain === "string" ? doc.payload.domain : null;
650
+ const dirId = typeof doc?.payload?.directiveId === "string" ? doc.payload.directiveId : null;
651
+ const oid = String(offer?.oid || intentId || "").slice(0, 10);
652
+ if (!dom) {
653
+ rec.rejected.push({ oid, error: "non-authored intent \u2014 governance enters its own admin lane" });
654
+ continue;
655
+ }
656
+ if (receiptFence && dirId && Array.isArray(receiptFence[dom]) && receiptFence[dom].includes(dirId)) {
657
+ const error = `'${dom}/${dirId}' is a capability RECEIPT \u2014 receipts are executor/owner writes, never open-session writes. Author it via POST /v1/workspaces/${ws}/author (owner Bearer), or \u2014 if this parked receipt is sanctioned \u2014 the owner unjams it: POST /v1/workspaces/${ws}/dead-letters/retry`;
658
+ rec.rejected.push({ oid, error, deadLettered: true });
659
+ deadLetters.push({ intentId, oid, session: cid, error, blob, domain: dom, directiveId: dirId });
660
+ continue;
661
+ }
662
+ if (intentId && main.ids.has(intentId)) {
663
+ rec.skipped.push({ oid, intent: intentId.slice(0, 12), alreadyOnMain: true });
664
+ continue;
665
+ }
666
+ const cap = summaryCtx ? beginSummaryCapture(eng, ws, summaryCtx, blob) : null;
667
+ const _tOffer = Date.now();
668
+ const res = offerAdmit(eng, ws, blob, { defer: !summaryCtx });
669
+ log("offer-admit-ms", { ws, ms: Date.now() - _tOffer, deferred: !summaryCtx, ok: res.ok });
670
+ if (res.ok) {
671
+ if (intentId) main.ids.add(intentId);
672
+ main.oids.add(res.head);
673
+ main.head = res.head;
674
+ rec.admitted.push({ oid, head: res.head });
675
+ admittedTotal += 1;
676
+ if (Array.isArray(res.born) && res.born.length) born.push(...res.born);
677
+ if (Array.isArray(res.birthOutcomes) && res.birthOutcomes.length) birthOutcomes.push(...res.birthOutcomes);
678
+ if (cap) finishSummaryCapture(eng, ws, summaryCtx, cap, res.head ?? "", intentId);
679
+ } else {
680
+ const error = `${String(res.error || "").slice(0, 300)} \u2014 dead-lettered; fix the law (or the payload), then POST /v1/workspaces/${ws}/dead-letters/retry`;
681
+ rec.rejected.push({ oid, error, deadLettered: true });
682
+ deadLetters.push({ intentId, oid, session: cid, error, blob, domain: dom, directiveId: dirId });
683
+ }
684
+ } catch (e) {
685
+ rec.rejected.push({ oid: String(offer?.oid || "").slice(0, 10), error: String(e).slice(0, 200) });
686
+ } finally {
687
+ done();
688
+ }
689
+ }
690
+ timings.sessions = sessions.size;
691
+ timings.intents = admittedTotal;
692
+ if (admittedTotal && !summaryCtx) (eng.pendingProjection ??= /* @__PURE__ */ new Set()).add(ws);
693
+ if (deadLetters.length) {
694
+ try {
695
+ await materializeRefused(eng, ws, ledger, deadLetters);
696
+ } catch (e) {
697
+ log("refused-materialize-failed", { ws, error: String(e).slice(0, 200) });
698
+ }
699
+ }
700
+ const deferDurability = defer && !summaryCtx;
701
+ if (admittedTotal && !deferDurability) {
702
+ const sealDone = span("seal offered intents", "cseal", 1, { admitted: admittedTotal });
703
+ await commitAndPush(eng, ws, ledger);
704
+ sealDone();
705
+ }
706
+ const gitdir = gitdirOf(ws);
707
+ const head = kgit.resolveRef(eng, gitdir, BRANCH) ?? main.head;
708
+ const summary = summaryCtx ? summaryOfCapture(summaryCtx, headBefore, head) : null;
709
+ let resultPackB64 = null;
710
+ if (admittedTotal && head && /^[0-9a-f]{40}$/i.test(clientBase || "") && clientBase !== head) {
711
+ try {
712
+ const p = servePack(eng, ws, clientBase ?? "");
713
+ if (p && p.packB64 && p.bytes && p.bytes <= RESULT_PACK_INLINE_MAX) resultPackB64 = p.packB64;
714
+ } catch {
715
+ }
716
+ }
717
+ log("admit-intent-offers", { ws, sessions: sessions.size, admitted: admittedTotal, rejected: [...sessions.values()].reduce((n, s) => n + s.rejected.length, 0), resultPack: resultPackB64 ? "inline" : "none" });
718
+ const bornPacked = born.length ? packBornChildren(eng, born) : born;
719
+ return { sessions: [...sessions.values()].map((s) => ({ ...s, ...s.skipped.length ? {} : { skipped: void 0 } })), main: head, deadLetters, timings, summary: summary ?? null, born: bornPacked, birthOutcomes, ...resultPackB64 ? { resultPackB64, resultBase: clientBase } : {}, ...deferDurability && admittedTotal && head ? { deferred: true, head } : {} };
720
+ }
721
+ async function authorOn(eng, ws, ledger, domain, directiveId, payload, lawHash, opts = {}) {
722
+ await mountWorkspace(eng, ws, ledger);
723
+ let res;
724
+ try {
725
+ res = author(eng, ws, domain, directiveId, payload, lawHash, opts);
726
+ } catch (e) {
727
+ return { ok: false, error: String(e?.message || e).slice(0, 500) };
728
+ }
729
+ if (res && res.ok === false) return { ok: false, error: String(res.error || "the law refused this intent").slice(0, 500) };
730
+ await commitAndPush(eng, ws, ledger);
731
+ const bornPacked = Array.isArray(res.born) && res.born.length ? packBornChildren(eng, res.born) : res.born;
732
+ return { ok: true, head: res.head, born: bornPacked ?? [], birthOutcomes: res.birthOutcomes ?? [] };
733
+ }
734
+ function stageWorkspaceDir(eng, ws) {
735
+ const wsContents = /* @__PURE__ */ new Map();
736
+ dirOf(eng.preopen.dir.contents.get("ws")).contents.set(ws, new Directory(wsContents));
737
+ }
738
+ async function mountWorkspace(eng, ws, ledger) {
739
+ if (eng.mounted.has(ws)) return eng.mounted.get(ws);
740
+ stageWorkspaceDir(eng, ws);
741
+ const gitdir = gitdirOf(ws);
742
+ let restored = false, remoteMain = null, restoreError = null;
743
+ try {
744
+ await custodySkeleton(eng, gitdir);
745
+ remoteMain = await custodyFetch(eng, ws, ledger, { remoteRef: "refs/heads/main" });
746
+ if (remoteMain) {
747
+ kgit.writeRef(eng, gitdir, "HEAD", "ref: refs/heads/main");
748
+ restored = true;
749
+ }
750
+ } catch (e) {
751
+ restoreError = String(e?.stack || e).split("\n").slice(0, 5).join(" | ");
752
+ }
753
+ const m = { restored, remoteMain, restoreError };
754
+ eng.mounted.set(ws, m);
755
+ return m;
756
+ }
757
+ function unmount(eng, ws) {
758
+ eng.mounted.delete(ws);
759
+ eng.mainIntents.delete(ws);
760
+ const wsRoot = dirOf(eng.preopen.dir.contents.get("ws"));
761
+ if (wsRoot) wsRoot.contents.delete(ws);
762
+ }
763
+ function writeWork(eng, name, bytes) {
764
+ eng.preopen.dir.contents.set(name, new File(bytes));
765
+ }
766
+ function currentLaw(eng, ws) {
767
+ const out = JSON.parse(call(eng.ex, "query", { repoArg: repoArgOf(ws), workspace: ws, queryBytes: b64Json({ op: "currentLaw" }), branch: BRANCH }, eng.STDERR));
768
+ return out.keyMap || {};
769
+ }
770
+ function installedLaw(eng, ws) {
771
+ return JSON.parse(call(eng.ex, "query", { repoArg: repoArgOf(ws), workspace: ws, queryBytes: b64Json({ op: "installedLaw" }), branch: BRANCH }, eng.STDERR));
772
+ }
773
+ function domainPackage(eng, ws, hash) {
774
+ return JSON.parse(call(eng.ex, "query", { repoArg: repoArgOf(ws), workspace: ws, queryBytes: b64Json({ op: "domainPackage", hash }), branch: BRANCH }, eng.STDERR));
775
+ }
776
+ function evolveDryRun(eng, ws, usda, domainHash, dispositions = null) {
777
+ const r = author(eng, ws, "nomos", "installDomain", installPayload(domainHash, usda, eng.installedBy, dispositions), eng.hashes.nomos, { dryRun: true, deferProjection: false });
778
+ return r.ok ? { admits: true } : { admits: false, detail: r.error };
779
+ }
780
+ function author(eng, ws, domain, directiveId, payload, controllerHash, opts = {}) {
781
+ const seq = eng.seq++;
782
+ const capPorts = { clock: { physical: Date.now(), logical: 0, replica: eng.replica }, rng: osEntropyBuffer(opts.rngDraws ?? 64) };
783
+ if (opts.validFromEpoch !== void 0) capPorts.valid_from_epoch = opts.validFromEpoch;
784
+ if (opts.principalVerified !== void 0) {
785
+ capPorts.principal = opts.actor ?? "";
786
+ capPorts.principal_verified = !!opts.principalVerified;
787
+ }
788
+ const envelope = { payload: { domain, directiveId, payload }, captured_ports: capPorts, policy_version: 1, policy_domain: "Nomos", policy_gas: 0, policy_memory: 0 };
789
+ if (opts.attestations !== void 0) envelope.attestations = opts.attestations;
790
+ writeWork(eng, `payload-${seq}.json`, enc3.encode(JSON.stringify(payload)));
791
+ writeWork(eng, `envelope-${seq}.json`, enc3.encode(stringifyBig(envelope)));
792
+ const genesis = !controllerHash;
793
+ const attestorSecretFor = (from) => {
794
+ const s = opts.attestorSecrets;
795
+ if (!s) return null;
796
+ if (typeof s === "string") return s;
797
+ return typeof s[from] === "string" ? s[from] : null;
798
+ };
799
+ const defer = opts.deferProjection !== false;
800
+ const offerOnce = () => JSON.parse(call(eng.ex, "offer", { repoArg: repoArgOf(ws), workspace: ws, domain, directiveId, payloadFile: `/work/payload-${seq}.json`, envelopeFile: `/work/envelope-${seq}.json`, seq, actor: opts.actor ?? "", ...opts.authToken ? { authToken: opts.authToken } : {}, domainFile: genesis ? "/work/domain.package.usda" : "", domainHash: genesis ? "" : controllerHash, branch: BRANCH, ...opts.authorSecret ? { authorSecret: opts.authorSecret } : {}, ...opts.spans ? { spans: true } : {}, ...opts.dryRun ? { dryRun: true } : defer ? { deferProjection: true } : {} }, eng.STDERR));
801
+ let v = offerOnce();
802
+ for (let pass = 0; pass < 8 && v.outcome === "refused"; pass++) {
803
+ const need = parseAttestedReadNeed(v.verdict?.reason ?? v.error);
804
+ if (!need || !eng.mounted.has(need.from)) break;
805
+ const secret = attestorSecretFor(need.from);
806
+ if (!secret) break;
807
+ const served = attestedRead(eng, need.from, {
808
+ queryId: need.queryId,
809
+ paramsJson: JSON.stringify(need.args),
810
+ attestorSecret: secret,
811
+ nowMs: opts.attestNowMs ?? Date.now(),
812
+ // K3 (§1.5.3): colocated custody is in-memory — always ask for the carried enrollment
813
+ // proof; the kernel produces-or-omits under its own bounds (the adapter decides nothing).
814
+ includeRosterProof: true
815
+ });
816
+ if (!served || served.ok !== true) break;
817
+ envelope.attestations = [...envelope.attestations ?? [], { queryId: need.queryId, result: served.rows, attestation: served.attestation }];
818
+ writeWork(eng, `envelope-${seq}.json`, enc3.encode(stringifyBig(envelope)));
819
+ v = offerOnce();
820
+ }
821
+ const res = v.outcome === "admitted" ? { ok: true, head: v.head, intentOut: v.intentOut, born: v.born ?? [], birthOutcomes: v.birthOutcomes ?? [], ...v.kernelSpans ? { kernelSpans: v.kernelSpans } : {} } : v.outcome === "refused" ? { ok: false, error: v.verdict?.reason ?? v.error } : v;
822
+ if (defer && res.ok) (eng.pendingProjection ??= /* @__PURE__ */ new Set()).add(ws);
823
+ return res;
824
+ }
825
+ function setTestKRoot(eng, kRootPublicB64) {
826
+ return JSON.parse(call(eng.ex, "set_test_k_root", { kRootPublicB64 }, eng.STDERR));
827
+ }
828
+ function refreshProjection(eng, ws) {
829
+ return JSON.parse(call(eng.ex, "query", { repoArg: repoArgOf(ws), workspace: ws, queryBytes: b64Json({ op: "refresh" }), branch: BRANCH }, eng.STDERR));
830
+ }
831
+ async function custodySkeleton(eng, gitdir) {
832
+ const p = eng.fs.promises;
833
+ for (const d of ["", "/objects", "/objects/pack", "/objects/info", "/refs", "/refs/heads"]) {
834
+ try {
835
+ await p.mkdir(`${gitdir}${d}`);
836
+ } catch (e) {
837
+ if (e?.code !== "EEXIST") throw e;
838
+ }
839
+ }
840
+ try {
841
+ await p.writeFile(`${gitdir}/HEAD`, `ref: refs/heads/${BRANCH}
842
+ `);
843
+ } catch {
844
+ }
845
+ try {
846
+ await p.writeFile(`${gitdir}/config`, "[core]\n repositoryformatversion = 0\n bare = true\n");
847
+ } catch {
848
+ }
849
+ }
850
+ async function custodyFetch(eng, ws, ledger, { remoteRef = "refs/heads/main", localRef = null, have = null } = {}) {
851
+ const remoteRefFull = fullRef(remoteRef);
852
+ const refs = await custodyLsRefs(ledger, remoteRefFull);
853
+ const tip = refs[remoteRefFull] || null;
854
+ if (!tip) return null;
855
+ if (tip !== have) {
856
+ const pk = await fetchPack(ledger.remote, ledger.headers || {}, { wants: [tip], haves: have ? [have] : [] });
857
+ if (pk) applyPackInto(eng, ws, pk);
858
+ }
859
+ kgit.writeRef(eng, gitdirOf(ws), fullRef(localRef || remoteRef), tip);
860
+ return tip;
861
+ }
862
+ async function custodyPush(eng, ws, ledger, { localRef = null, remoteRef, del = false, pointer = false, newOid = null }) {
863
+ const headers = ledger.headers || {};
864
+ const remoteRefFull = fullRef(remoteRef);
865
+ const remote = await lsRefs(ledger.remote, headers, { service: "git-receive-pack", prefix: remoteRefFull });
866
+ const oldOid = remote[remoteRefFull] || ZERO_OID;
867
+ if (del) {
868
+ if (oldOid === ZERO_OID) return;
869
+ return pushVia(ledger, () => pushPack(ledger.remote, headers, { updates: [{ ref: remoteRefFull, oldOid, newOid: ZERO_OID }] }));
870
+ }
871
+ const tgt = newOid || kgit.resolveRef(eng, gitdirOf(ws), fullRef(localRef || remoteRef));
872
+ if (!tgt) throw new Error(`custodyPush: local ref ${localRef || remoteRef} unresolved`);
873
+ if (tgt === oldOid) return;
874
+ let pack = null;
875
+ if (!pointer) {
876
+ pack = oldOid !== ZERO_OID ? packDelta(eng, ws, oldOid, tgt) : null;
877
+ if (!pack) pack = packDelta(eng, ws, "", tgt);
878
+ }
879
+ return pushVia(ledger, () => pushPack(ledger.remote, headers, { updates: [{ ref: remoteRefFull, oldOid, newOid: tgt }], pack }));
880
+ }
881
+ async function commitAndPush(eng, ws, ledger) {
882
+ try {
883
+ await custodyPush(eng, ws, ledger, { remoteRef: "refs/heads/main" });
884
+ } catch (e) {
885
+ unmount(eng, ws);
886
+ throw new Error(`ledger push failed \u2014 write NOT durable, rolled back to ledger: ${e}`);
887
+ }
888
+ }
889
+ function describe(eng, ws) {
890
+ return JSON.parse(call(eng.ex, "query", { repoArg: repoArgOf(ws), workspace: ws, queryBytes: b64Json({ op: "describe", workspace: ws }), branch: BRANCH }, eng.STDERR));
891
+ }
892
+ function parseAttestedReadNeed(error) {
893
+ const m = /attested-read-unreachable: read\('([^']+)', \{from: '([^']+)'\}\) args=(.*?) has no injected attestation/.exec(String(error || ""));
894
+ if (!m) return null;
895
+ let blob = m[3];
896
+ for (let i = 0; i < 4; i++) {
897
+ try {
898
+ return { queryId: m[1], from: m[2], args: JSON.parse(blob) };
899
+ } catch {
900
+ blob = blob.replace(/\\(["\\])/g, "$1");
901
+ }
902
+ }
903
+ return null;
904
+ }
905
+ function packDelta(eng, ws, base, head) {
906
+ try {
907
+ const r = JSON.parse(call(eng.ex, "pack_delta", { repoArg: repoArgOf(ws), base, head }, eng.STDERR));
908
+ if (!r || r.ok !== true || typeof r.packB64 !== "string") return null;
909
+ return Uint8Array.from(atob(r.packB64), (c) => c.charCodeAt(0));
910
+ } catch {
911
+ return null;
912
+ }
913
+ }
914
+ function servePack(eng, ws, base = "") {
915
+ let head = null;
916
+ try {
917
+ head = kgit.resolveRef(eng, gitdirOf(ws), BRANCH);
918
+ } catch {
919
+ }
920
+ let r;
921
+ try {
922
+ r = JSON.parse(call(eng.ex, "pack_delta", { repoArg: repoArgOf(ws), workspace: ws, base, branch: BRANCH }, eng.STDERR));
923
+ } catch (e) {
924
+ const msg = String(e);
925
+ if (/nothing to pack|head == base/.test(msg)) return { packB64: "", bytes: 0, upToDate: true, ...head ? { head } : {} };
926
+ if (base && /reached root|before base|not found|unknown|no (?:merge )?base|missing|invalid/i.test(msg)) {
927
+ try {
928
+ const full = JSON.parse(call(eng.ex, "pack_delta", { repoArg: repoArgOf(ws), workspace: ws, base: "", branch: BRANCH }, eng.STDERR));
929
+ if (full && full.ok === true && typeof full.packB64 === "string") {
930
+ return { packB64: full.packB64, bytes: full.bytes, divergent: true, ...head ? { head } : {} };
931
+ }
932
+ } catch {
933
+ }
934
+ }
935
+ throw e;
936
+ }
937
+ if (!r || r.ok !== true || typeof r.packB64 !== "string") throw new Error("servePack: kernel produced no pack");
938
+ return { packB64: r.packB64, bytes: r.bytes, ...head ? { head } : {} };
939
+ }
940
+ function packBornChildren(eng, born) {
941
+ if (!Array.isArray(born) || !born.length) return born;
942
+ return born.map((b) => {
943
+ const child = b && typeof b.workspace === "string" ? b.workspace : null;
944
+ const head = b && typeof b.head === "string" ? b.head : null;
945
+ if (!child || !/^[0-9a-f]{40}$/i.test(head || "")) {
946
+ log("born-pack-skipped", { workspace: child, head, reason: "malformed born entry" });
947
+ return b;
948
+ }
949
+ try {
950
+ const pack = packDelta(eng, child, "", head);
951
+ if (!pack || !pack.length) {
952
+ log("born-pack-empty", { workspace: child, head });
953
+ return b;
954
+ }
955
+ return { ...b, packB64: b64Bytes(pack), packBytes: pack.length };
956
+ } catch (e) {
957
+ log("born-pack-failed", { workspace: child, head, error: String(e).slice(0, 200) });
958
+ return b;
959
+ }
960
+ });
961
+ }
962
+ function offerIntent(eng, ws, bytes, opts = {}) {
963
+ const name = `offer-in-${eng.seq++}.json`;
964
+ writeWork(eng, name, bytes);
965
+ const deferProjection = !!(opts && opts.defer);
966
+ const branch = opts && opts.branch || BRANCH;
967
+ return JSON.parse(call(eng.ex, "offer", { repoArg: repoArgOf(ws), workspace: ws, intentFile: `/work/${name}`, branch, deferProjection }, eng.STDERR));
968
+ }
969
+ function offerAdmit(eng, ws, bytes, opts = {}) {
970
+ const v = offerIntent(eng, ws, bytes, opts);
971
+ return v.outcome === "admitted" ? { ok: true, head: v.head, ...v.born ? { born: v.born } : {} } : { ok: false, error: v.verdict?.reason ?? v.error ?? "the offer was refused" };
972
+ }
973
+ async function mainIntentIds(eng, ws) {
974
+ const gitdir = gitdirOf(ws);
975
+ const head = kgit.resolveRef(eng, gitdir, BRANCH);
976
+ if (!head) return { head: null, ids: /* @__PURE__ */ new Set(), oids: /* @__PURE__ */ new Set() };
977
+ const cached = eng.mainIntents.get(ws);
978
+ if (cached && cached.head === head) return cached;
979
+ const ids = /* @__PURE__ */ new Set(), oids = /* @__PURE__ */ new Set();
980
+ for (const c of kgit.intentsAbove(eng, gitdir, head, "", 500)) {
981
+ oids.add(c.oid);
982
+ try {
983
+ const id = JSON.parse(dec3.decode(bytesFromB64(c.intentB64))).id;
984
+ if (typeof id === "string" && id) ids.add(id);
985
+ } catch {
986
+ }
987
+ }
988
+ const m = { head, ids, oids };
989
+ eng.mainIntents.set(ws, m);
990
+ return m;
991
+ }
992
+ async function admitAll(eng, ws, ledger, { receiptFence = null, shardRouting = null, defer = false } = {}) {
993
+ const routes = shardRouting ? directiveRoutes(eng) : null;
994
+ const gitdir = gitdirOf(ws);
995
+ const H = () => ({ ...ledger.headers || {} });
996
+ const _t0 = Date.now();
997
+ let _fetchMs = 0, _sealMs = 0, _intents = 0;
998
+ const _spans = [];
999
+ let _traceSeq = 0;
1000
+ const _span = (name, kind, depth = 1, extra = {}) => {
1001
+ const t0 = Date.now();
1002
+ return (end = {}) => {
1003
+ const t1 = Date.now();
1004
+ _spans.push({ id: `admit-${_t0}-${_traceSeq++}`, track: "cloud", name, kind, depth, t0, t1, ...extra, ...end });
1005
+ };
1006
+ };
1007
+ const sessionRefPrefix = "refs/heads/session/";
1008
+ const sessions = {};
1009
+ const _scanDone = _span("scan session refs", "cscan", 1);
1010
+ for (const [ref, oid] of Object.entries(await custodyLsRefs(ledger, sessionRefPrefix))) {
1011
+ if (ref.startsWith(sessionRefPrefix) && oid) sessions[ref.slice(sessionRefPrefix.length)] = oid;
1012
+ }
1013
+ _scanDone({ sessions: Object.keys(sessions).length });
1014
+ const _scanMs = Date.now() - _t0;
1015
+ const results = [], deadLetters = [], placements = [], splits = [], globalsOut = [];
1016
+ const consumed = [];
1017
+ let totalAdmitted = 0;
1018
+ const globalsDeclared = shardRouting && !shardRouting.selfLabel ? globalAggregates(eng) : null;
1019
+ const summaryCtx = shardRouting && shardRouting.selfLabel && scopedReads(eng).length > 0 ? { reads: scopedReads(eng), prevs: /* @__PURE__ */ new Map(), values: /* @__PURE__ */ new Map(), events: [], rowsDelta: 0, rederived: /* @__PURE__ */ new Set(), rowsByHome: /* @__PURE__ */ new Map(), homeTags: /* @__PURE__ */ new Map(), homeKeySet: /* @__PURE__ */ new Set() } : null;
1020
+ const canDeferProjection = !summaryCtx && !(globalsDeclared && globalsDeclared.size > 0);
1021
+ if (summaryCtx) {
1022
+ try {
1023
+ for (const r of query(eng, ws, "aggregatesByType", JSON.stringify({ __type: "NomosHomeReceipt" }))) {
1024
+ const hk = r.data && typeof r.data.homeKey === "string" ? r.data.homeKey : null;
1025
+ if (!hk) continue;
1026
+ summaryCtx.homeKeySet.add(hk);
1027
+ summaryCtx.homeTags.set(await routeTagHexOfHomeKey(hk), hk);
1028
+ }
1029
+ } catch (e) {
1030
+ log("home-tag-table-error", { ws, error: String(e).slice(0, 200) });
1031
+ }
1032
+ }
1033
+ const headBefore = summaryCtx ? kgit.resolveRef(eng, gitdir, BRANCH) : null;
1034
+ for (const [cid, head] of Object.entries(sessions)) {
1035
+ const ref = `refs/heads/session/${cid}`;
1036
+ const shortCid = cid.length > 14 ? `${cid.slice(0, 14)}...` : cid;
1037
+ const _sessionDone = _span(`session ${shortCid}`, "csession", 1, { client: cid });
1038
+ try {
1039
+ const _fetchDone = _span(`fetch ${shortCid}`, "cfetch", 2, { client: cid });
1040
+ const _f = Date.now();
1041
+ try {
1042
+ const localMain = kgit.resolveRef(eng, gitdir, BRANCH);
1043
+ try {
1044
+ await custodyFetch(eng, ws, ledger, { remoteRef: ref, have: localMain });
1045
+ } catch (thinErr) {
1046
+ log("thin-fetch-fallback", { ws, cid, error: String(thinErr?.message || thinErr).slice(0, 160) });
1047
+ await custodyFetch(eng, ws, ledger, { remoteRef: ref, have: null });
1048
+ }
1049
+ } finally {
1050
+ _fetchMs += Date.now() - _f;
1051
+ _fetchDone();
1052
+ }
1053
+ const _walkDone = _span(`walk ${shortCid}`, "cwalk", 2, { client: cid });
1054
+ const main = await mainIntentIds(eng, ws);
1055
+ const recent = kgit.intentsAbove(eng, gitdir, head ?? "", "", 100);
1056
+ const chain = [];
1057
+ for (let i = recent.length - 1; i >= 0; i--) {
1058
+ if (main.oids.has(recent[i].oid)) break;
1059
+ chain.push(recent[i]);
1060
+ }
1061
+ chain.reverse();
1062
+ _walkDone({ intents: chain.length });
1063
+ const admitted = [], rejected = [], skipped = [];
1064
+ const _gateDone = _span(`gate+fold ${shortCid}`, "cgate", 2, { client: cid, intents: chain.length });
1065
+ for (const c of chain) {
1066
+ const oid = c.oid;
1067
+ try {
1068
+ const blob = bytesFromB64(c.intentB64);
1069
+ let dom = null, intentId = null, dirId = null;
1070
+ try {
1071
+ const doc = JSON.parse(dec3.decode(blob));
1072
+ intentId = typeof doc.id === "string" ? doc.id : null;
1073
+ dom = doc && doc.payload && typeof doc.payload.domain === "string" ? doc.payload.domain : null;
1074
+ dirId = doc && doc.payload && typeof doc.payload.directiveId === "string" ? doc.payload.directiveId : null;
1075
+ } catch {
1076
+ }
1077
+ if (!dom) {
1078
+ rejected.push({ oid: oid.slice(0, 10), error: "non-authored intent \u2014 governance enters its own admin lane" });
1079
+ continue;
1080
+ }
1081
+ if (receiptFence && dirId && Array.isArray(receiptFence[dom]) && receiptFence[dom].includes(dirId)) {
1082
+ const error = `'${dom}/${dirId}' is a capability RECEIPT \u2014 receipts are executor/owner writes, never open-session writes. Author it via POST /v1/workspaces/${ws}/author (owner Bearer), or \u2014 if this parked receipt is sanctioned \u2014 the owner unjams it: POST /v1/workspaces/${ws}/dead-letters/retry`;
1083
+ rejected.push({ oid: oid.slice(0, 10), error, deadLettered: true });
1084
+ deadLetters.push({ intentId, oid: oid.slice(0, 10), session: cid, error, blob, domain: dom, directiveId: dirId });
1085
+ continue;
1086
+ }
1087
+ if (routes && dom && dirId) {
1088
+ if (dirId === "nomosSealHome" || dirId === "nomosSealHandoff") {
1089
+ rejected.push({ oid: oid.slice(0, 10), error: `session lane refuses '${dirId}' \u2014 the \xA76 handoff seals are authored by the adapter after migration verifies (begin a move with nomosSplitShard, or POST /v1/workspaces/<coordinator>/split)` });
1090
+ continue;
1091
+ }
1092
+ const route = routes.get(`${dom} ${dirId}`);
1093
+ if (route) {
1094
+ let payloadObj = null;
1095
+ try {
1096
+ payloadObj = JSON.parse(dec3.decode(blob)).payload?.payload ?? null;
1097
+ } catch {
1098
+ }
1099
+ const verdict2 = await wrongHomeVerdict(shardRouting, route, payloadObj);
1100
+ if (verdict2) {
1101
+ rejected.push({ oid: oid.slice(0, 10), error: verdict2.error, ...verdict2.wrongHome ? { wrongHome: verdict2.wrongHome } : {}, ...verdict2.homeMoving ? { homeMoving: verdict2.homeMoving } : {}, ...verdict2.deadLettered ? { deadLettered: true } : {} });
1102
+ if (verdict2.deadLettered) deadLetters.push({ intentId, oid: oid.slice(0, 10), session: cid, error: verdict2.error, blob, domain: dom, directiveId: dirId });
1103
+ continue;
1104
+ }
1105
+ }
1106
+ if (dirId === "nomosReceiveAssignment" && shardRouting) {
1107
+ let p = null;
1108
+ try {
1109
+ p = JSON.parse(dec3.decode(blob)).payload?.payload ?? null;
1110
+ } catch {
1111
+ }
1112
+ const homeKey = p && typeof p.homeKey === "string" ? p.homeKey : null;
1113
+ const rows = homeKey ? await shardRouting.assignments() || [] : [];
1114
+ const a = homeKey ? rows.find((x) => x.homeKey === homeKey) : null;
1115
+ if (!a) {
1116
+ const error = `assignment receipt for home '${String(homeKey).slice(0, 80)}' has NO placement on the coordinator '${shardRouting.coordinatorWs}' \u2014 author the derived placement intent (birth<Type>) first, then POST /dead-letters/retry`;
1117
+ rejected.push({ oid: oid.slice(0, 10), error, deadLettered: true });
1118
+ deadLetters.push({ intentId, oid: oid.slice(0, 10), session: cid, error, blob, domain: dom, directiveId: dirId });
1119
+ continue;
1120
+ }
1121
+ if (a.shard !== shardRouting.selfLabel || p && p.shard !== shardRouting.selfLabel) {
1122
+ const correct = `${shardRouting.coordinatorWs}--${a.shard}`;
1123
+ rejected.push({
1124
+ oid: oid.slice(0, 10),
1125
+ error: `wrong-home: the coordinator's shard map assigns home '${homeKey.slice(0, 80)}' to '${correct}' (not this workspace) \u2014 a routed client re-routes and retries automatically`,
1126
+ wrongHome: { workspace: correct, ...a.mapVersion !== void 0 ? { mapVersion: a.mapVersion } : {} }
1127
+ });
1128
+ continue;
1129
+ }
1130
+ }
1131
+ }
1132
+ if (intentId && main.ids.has(intentId)) {
1133
+ skipped.push({ oid: oid.slice(0, 10), intent: intentId.slice(0, 12), alreadyOnMain: true });
1134
+ continue;
1135
+ }
1136
+ const cap = summaryCtx ? beginSummaryCapture(eng, ws, summaryCtx, blob) : null;
1137
+ const verdict = offerIntent(eng, ws, blob, { defer: canDeferProjection });
1138
+ const res = verdict.outcome === "admitted" ? { ok: true, head: verdict.head } : { ok: false, error: verdict.verdict?.reason ?? verdict.error ?? "the offer was refused" };
1139
+ if (res.ok) {
1140
+ main.ids.add(intentId);
1141
+ main.oids.add(res.head);
1142
+ main.head = res.head;
1143
+ admitted.push({ oid: oid.slice(0, 10), head: res.head });
1144
+ if (cap) finishSummaryCapture(eng, ws, summaryCtx, cap, res.head ?? "", intentId);
1145
+ if (shardRouting && dirId) {
1146
+ const placement = placementDirectives(eng).get(dirId);
1147
+ if (placement) {
1148
+ let p = null;
1149
+ try {
1150
+ p = JSON.parse(dec3.decode(blob)).payload?.payload ?? null;
1151
+ } catch {
1152
+ }
1153
+ const homeKey = p ? p[String(placement.keyField)] : void 0;
1154
+ if (typeof homeKey === "string" && typeof p?.shard === "string") {
1155
+ placements.push({ directive: dirId, homeKey, shard: p.shard, mapVersion: 1 });
1156
+ }
1157
+ }
1158
+ if (dirId === "nomosSplitShard" && !shardRouting.selfLabel) {
1159
+ let p = null;
1160
+ try {
1161
+ p = JSON.parse(dec3.decode(blob)).payload?.payload ?? null;
1162
+ } catch {
1163
+ }
1164
+ if (p && typeof p.fromShard === "string" && typeof p.toShard === "string" && Array.isArray(p.homeKeys)) {
1165
+ splits.push({ fromShard: p.fromShard, toShard: p.toShard, homeKeys: p.homeKeys.filter((k) => typeof k === "string") });
1166
+ }
1167
+ }
1168
+ }
1169
+ if (globalsDeclared && globalsDeclared.size > 0) {
1170
+ let touchesGlobal = false;
1171
+ for (const ev of parseIntentEvents(blob)) {
1172
+ const rows = qById(eng, ws, ev.aggregate);
1173
+ const t = ev.sets.get("__type") ?? (rows.length ? rows[0].type : void 0);
1174
+ if (t !== void 0 && globalsDeclared.has(t)) {
1175
+ touchesGlobal = true;
1176
+ break;
1177
+ }
1178
+ }
1179
+ if (touchesGlobal) globalsOut.push({ intentId: intentId || "", oid: oid.slice(0, 10), blob });
1180
+ }
1181
+ } else {
1182
+ const wh = String(res.error || "").match(/wrong-home:(s\d+)/);
1183
+ if (wh) {
1184
+ const coordinator = shardRouting && shardRouting.coordinatorWs || (ws.match(/^(.*)--s\d+$/) || [])[1] || ws;
1185
+ rejected.push({
1186
+ oid: oid.slice(0, 10),
1187
+ error: `wrong-home: this write's home is assigned to '${coordinator}--${wh[1]}' \u2014 the chain gate's homing invariant refused it; a routed client re-routes and retries automatically`,
1188
+ wrongHome: { workspace: `${coordinator}--${wh[1]}` }
1189
+ });
1190
+ continue;
1191
+ }
1192
+ const error = `${String(res.error || "").slice(0, 300)} \u2014 dead-lettered; fix the law (or the payload), then POST /v1/workspaces/${ws}/dead-letters/retry`;
1193
+ rejected.push({ oid: oid.slice(0, 10), error, deadLettered: true });
1194
+ deadLetters.push({ intentId, oid: oid.slice(0, 10), session: cid, error, blob, domain: dom, directiveId: dirId });
1195
+ }
1196
+ } catch (e) {
1197
+ rejected.push({ oid: oid.slice(0, 10), error: String(e).slice(0, 200) });
1198
+ }
1199
+ }
1200
+ _gateDone({ admitted: admitted.length, rejected: rejected.length, skipped: skipped.length });
1201
+ _intents += admitted.length;
1202
+ totalAdmitted += admitted.length;
1203
+ consumed.push({ cid, ref });
1204
+ results.push({ session: cid, admitted, rejected, ...skipped.length ? { skipped } : {} });
1205
+ } catch (e) {
1206
+ results.push({ session: cid, error: String(e).slice(0, 200) });
1207
+ } finally {
1208
+ _sessionDone();
1209
+ }
1210
+ }
1211
+ if (canDeferProjection && totalAdmitted) {
1212
+ const _projDone = _span("projection flush (batch)", "cproject", 1, { admitted: totalAdmitted });
1213
+ try {
1214
+ refreshProjection(eng, ws);
1215
+ } catch (e) {
1216
+ log("admit-projection-flush-failed", { ws, error: String(e).slice(0, 200) });
1217
+ } finally {
1218
+ _projDone();
1219
+ }
1220
+ }
1221
+ let unparkedSessions = /* @__PURE__ */ new Set();
1222
+ if (deadLetters.length) {
1223
+ try {
1224
+ unparkedSessions = (await materializeRefused(eng, ws, ledger, deadLetters)).unparkedSessions;
1225
+ } catch (e) {
1226
+ unparkedSessions = new Set(deadLetters.map((dl) => dl.session).filter(Boolean));
1227
+ log("refused-materialize-failed", { ws, error: String(e).slice(0, 200) });
1228
+ }
1229
+ }
1230
+ const prunable = unparkedSessions.size ? consumed.filter((c) => !unparkedSessions.has(c.cid)) : consumed;
1231
+ const hasCoordination = !!(summaryCtx || placements.length || splits.length || globalsOut.length);
1232
+ const deferDurability = defer && !hasCoordination;
1233
+ let _sealed = true;
1234
+ if (totalAdmitted && !deferDurability) {
1235
+ const _sealDone = _span(`seal (batch)`, "cseal", 1, { sessions: consumed.length, admitted: totalAdmitted });
1236
+ const _s = Date.now();
1237
+ try {
1238
+ await commitAndPush(eng, ws, ledger);
1239
+ } catch (e) {
1240
+ _sealed = false;
1241
+ log("admit-batch-push-failed", { ws, sessions: consumed.length, admitted: totalAdmitted, error: String(e).slice(0, 200) });
1242
+ } finally {
1243
+ _sealMs += Date.now() - _s;
1244
+ _sealDone();
1245
+ }
1246
+ }
1247
+ if (_sealed && !deferDurability) {
1248
+ for (const { ref } of prunable) {
1249
+ try {
1250
+ await custodyPush(eng, ws, ledger, { remoteRef: ref, del: true });
1251
+ } catch {
1252
+ }
1253
+ }
1254
+ }
1255
+ const newMain = kgit.resolveRef(eng, gitdir, BRANCH);
1256
+ log("admit", { ws, sessions: results.length, main: newMain });
1257
+ const summary = summaryCtx ? summaryOfCapture(summaryCtx, headBefore, newMain) : null;
1258
+ const _total = Date.now() - _t0;
1259
+ const timings = { totalMs: _total, scanMs: _scanMs, fetchMs: _fetchMs, sealMs: _sealMs, gateFoldMs: Math.max(0, _total - _scanMs - _fetchMs - _sealMs), intents: _intents, sessions: results.length, spans: _spans };
1260
+ return {
1261
+ sessions: results,
1262
+ main: newMain,
1263
+ deadLetters,
1264
+ timings,
1265
+ ...summary ? { summary } : {},
1266
+ ...placements.length ? { placements } : {},
1267
+ ...splits.length ? { splits } : {},
1268
+ ...globalsOut.length ? { globals: globalsOut } : {},
1269
+ // The adapter's backup lane consumes these: `deferred` ⇒ resident main carries totalAdmitted
1270
+ // un-backed-up commits and `consumed` are the session branches to delete AFTER the push lands.
1271
+ ...deferDurability && totalAdmitted ? { deferred: true, consumed: prunable, admitted: totalAdmitted } : {}
1272
+ };
1273
+ }
1274
+ async function writeRefusedRef(eng, ws, dl) {
1275
+ const gitdir = gitdirOf(ws);
1276
+ const blob = dl.blob instanceof Uint8Array ? dl.blob : enc3.encode(String(dl.blob || ""));
1277
+ const refForStamp = refusedRefName(dl.intentId || dl.oid);
1278
+ let parkedAt = (/* @__PURE__ */ new Date()).toISOString();
1279
+ try {
1280
+ const prevOid = kgit.resolveRef(eng, gitdir, refForStamp);
1281
+ if (prevOid) {
1282
+ const prev = JSON.parse(dec3.decode(kgit.readBlob(eng, gitdir, prevOid, "verdict.json") ?? new Uint8Array()));
1283
+ if (prev && typeof prev.parkedAt === "string") parkedAt = prev.parkedAt;
1284
+ }
1285
+ } catch {
1286
+ }
1287
+ const verdict = enc3.encode(JSON.stringify({
1288
+ offerId: dl.intentId || null,
1289
+ oid: dl.oid || null,
1290
+ domain: dl.domain || null,
1291
+ directiveId: dl.directiveId || null,
1292
+ session: dl.session || null,
1293
+ parkedAt,
1294
+ verdict: { reason: String(dl.error || "refused") }
1295
+ }));
1296
+ const ref = refusedRefName(dl.intentId || dl.oid);
1297
+ kgit.writeMetaCommit(eng, gitdir, {
1298
+ parents: [],
1299
+ files: [{ path: "intent.json", bytes: blob }, { path: "verdict.json", bytes: verdict }],
1300
+ message: `refused: ${dl.domain || "?"}/${dl.directiveId || "?"} \u2014 ${String(dl.error || "").slice(0, 120)}`,
1301
+ timeSecs: 0,
1302
+ ref
1303
+ });
1304
+ return ref;
1305
+ }
1306
+ async function listRefusedRefs(eng, ws) {
1307
+ const gitdir = gitdirOf(ws);
1308
+ const refs = kgit.listRefs(eng, gitdir, "refs/heads/refused/");
1309
+ const out = [];
1310
+ for (const { ref, oid } of refs) {
1311
+ try {
1312
+ const vb = kgit.readBlob(eng, gitdir, oid, "verdict.json") ?? new Uint8Array();
1313
+ const ib = kgit.readBlob(eng, gitdir, oid, "intent.json") ?? new Uint8Array();
1314
+ const v = JSON.parse(dec3.decode(vb));
1315
+ out.push({ ref, ...v, intentB64: b64Bytes(ib) });
1316
+ } catch {
1317
+ }
1318
+ }
1319
+ return out;
1320
+ }
1321
+ async function refusedSummary(eng, ws) {
1322
+ const gitdir = gitdirOf(ws);
1323
+ const refs = kgit.listRefs(eng, gitdir, "refs/heads/refused/");
1324
+ let count2 = 0, latestParkedAt = null;
1325
+ for (const { oid } of refs) {
1326
+ try {
1327
+ const v = JSON.parse(dec3.decode(kgit.readBlob(eng, gitdir, oid, "verdict.json") ?? new Uint8Array()));
1328
+ count2++;
1329
+ if (v && typeof v.parkedAt === "string" && (!latestParkedAt || v.parkedAt > latestParkedAt)) latestParkedAt = v.parkedAt;
1330
+ } catch {
1331
+ }
1332
+ }
1333
+ return { count: count2, latestParkedAt };
1334
+ }
1335
+ async function materializeRefused(eng, ws, ledger, deadLetters) {
1336
+ const refs = [];
1337
+ const unparkedSessions = /* @__PURE__ */ new Set();
1338
+ for (const dl of deadLetters || []) {
1339
+ try {
1340
+ const ref = await writeRefusedRef(eng, ws, dl);
1341
+ await custodyPush(eng, ws, ledger, { remoteRef: ref });
1342
+ refs.push(ref);
1343
+ } catch (e) {
1344
+ if (dl && dl.session) unparkedSessions.add(dl.session);
1345
+ log("refused-ref-materialize-failed", { ws, intentId: dl?.intentId, error: String(e).slice(0, 200) });
1346
+ }
1347
+ }
1348
+ return { refs, unparkedSessions };
1349
+ }
1350
+ async function deleteRefusedRef(eng, ws, ledger, offerId) {
1351
+ const gitdir = gitdirOf(ws);
1352
+ const ref = refusedRefName(offerId);
1353
+ try {
1354
+ kgit.deleteRef(eng, gitdir, ref);
1355
+ } catch {
1356
+ }
1357
+ try {
1358
+ await custodyPush(eng, ws, ledger, { remoteRef: ref, del: true });
1359
+ } catch (e) {
1360
+ log("refused-ref-delete-push-failed", { ws, ref, error: String(e).slice(0, 200) });
1361
+ }
1362
+ return ref;
1363
+ }
1364
+ async function boot(eng, ws, ledger) {
1365
+ const m = await mountWorkspace(eng, ws, ledger);
1366
+ if (nomosActive(eng, ws)) {
1367
+ if (ws !== "root" && !isWarranted(eng, ws)) {
1368
+ throw new Error(
1369
+ `unwarranted-workspace: '${ws}' is booted but its genesis never landed a GenesisWarrant \u2014 an era-0 workspace is born ONLY by its parent's warranted+attested birth. This is a host-authored/legacy orphan and will not serve (author its birth on its parent to bring it into the holarchy lawfully).`
1370
+ );
1371
+ }
1372
+ return { status: "already-initialized", head: m.remoteMain ?? void 0, controllerHash: eng.hashes.nomos, rows: qById(eng, ws, `domain-installation:${eng.hashes.nomos}`), mount: m };
1373
+ }
1374
+ throw new Error(
1375
+ `unborn-workspace: '${ws}' has no genesis and the host does not create workspaces \u2014 author its birth on its PARENT (birthChild/birthHome/an estate .births()); the parent's offer-effect materializes it in custody, then it serves from here. (root self-adopts via _ensureRootGenesis; this is not that path.)`
1376
+ );
1377
+ }
1378
+ async function deploy(eng, ws, ledger, usda, domainHash, dispositions, opts = {}) {
1379
+ const result = author(eng, ws, "nomos", "installDomain", installPayload(domainHash, usda, eng.installedBy, dispositions), eng.hashes.nomos, { actor: opts.actor ?? "", ...opts.authToken ? { authToken: opts.authToken } : {} });
1380
+ const installation = qById(eng, ws, `domain-installation:${domainHash}`);
1381
+ const keys = installation[0]?.data?.domainKeys ?? installation[0]?.domainKeys ?? [];
1382
+ if (keys.length > 0) {
1383
+ const law = installedLaw(eng, ws);
1384
+ const currentLaw2 = law?.currentLaw ?? {};
1385
+ const stale = keys.filter((k) => currentLaw2[k] !== void 0 && currentLaw2[k] !== domainHash);
1386
+ if (stale.length > 0) {
1387
+ throw new Error(
1388
+ `deploy-did-not-advance: the install of ${domainHash.slice(0, 12)}\u2026 ADMITTED but the workspace's current law still serves ${stale.map((k) => `'${k}' from ${String(currentLaw2[k]).slice(0, 12)}\u2026`).join(", ")} \u2014 refusing (custody unchanged) instead of a silent no-op. This usually means the existing installation's era/lineage prevents supersession: run \`githolon deploy --dry-run=evolve\` for the gate's verdict, supply #58 dispositions for a true removal/retype, or re-forge the workspace onto the current lineage.`
1389
+ );
1390
+ }
1391
+ }
1392
+ await commitAndPush(eng, ws, ledger);
1393
+ return { head: result.head, installation };
1394
+ }
1395
+ function snapshot(eng, ws) {
1396
+ const wsDir = dirOf(eng.preopen.dir.contents.get("ws")).contents.get(ws);
1397
+ return serializeTree(wsDir);
1398
+ }
1399
+ async function ledgerStats(eng, ws, ledger = null) {
1400
+ const gitdir = gitdirOf(ws);
1401
+ let head = kgit.resolveRef(eng, gitdir, BRANCH);
1402
+ if (!head && ledger?.remote) {
1403
+ try {
1404
+ await custodySkeleton(eng, gitdir);
1405
+ const remoteMain = await custodyFetch(eng, ws, ledger, { remoteRef: "refs/heads/main" });
1406
+ if (!remoteMain) return { head: null, commits: 0 };
1407
+ kgit.writeRef(eng, gitdir, "HEAD", `ref: refs/heads/${BRANCH}`);
1408
+ head = kgit.resolveRef(eng, gitdir, BRANCH);
1409
+ const mounted2 = eng.mounted.get(ws);
1410
+ if (mounted2) {
1411
+ mounted2.restored = true;
1412
+ mounted2.remoteMain = remoteMain;
1413
+ mounted2.restoreError = null;
1414
+ }
1415
+ } catch {
1416
+ }
1417
+ }
1418
+ if (!head) return { head: null, commits: 0 };
1419
+ const mounted = eng.mounted.get(ws);
1420
+ if (mounted && mounted.ledgerStats?.head === head) return mounted.ledgerStats;
1421
+ const commits = kgit.intentsAbove(eng, gitdir, head).length;
1422
+ const out = { head, commits };
1423
+ if (mounted) mounted.ledgerStats = out;
1424
+ return out;
1425
+ }
1426
+ var enc3, dec3, BRANCH, RESULT_PACK_INLINE_MAX, dirOf, repoArgOf, gitdirOf, unpack, log, repoArgOfGitdir, bytesFromB64, kgit, installPayload, routeTagHexOfHomeKey, SUMMARY_SEP, summaryKey, splitSummaryKey, NOMOS_SHARD_ROWS_READ, groupOf, tallyOf, isExtremumRead, extremumMonotone, pushVia, fullRef, applyPackInto, custodyLsRefs, qById, query, authorKeygen, attestedRead, certSign, readPosture, count, sum, pendingConflicts, spatialBboxParams, spatialWithin, extremum, nomosActive, refusedRefName, GENESIS_WARRANT_ID, isWarranted;
1427
+ var init_engine = __esm({
1428
+ "../adapter/engine.ts"() {
1429
+ "use strict";
1430
+ init_git_fs();
1431
+ init_tree();
1432
+ init_custody_transport();
1433
+ enc3 = new TextEncoder();
1434
+ dec3 = new TextDecoder();
1435
+ BRANCH = "main";
1436
+ RESULT_PACK_INLINE_MAX = 256 * 1024;
1437
+ dirOf = (n) => n;
1438
+ repoArgOf = (ws) => `/work/ws/${ws}`;
1439
+ gitdirOf = (ws) => `/work/ws/${ws}/nomos.git`;
1440
+ unpack = (p) => {
1441
+ const v = typeof p === "bigint" ? p : BigInt(p);
1442
+ return { ptr: Number(v >> 32n), len: Number(v & 0xffffffffn) };
1443
+ };
1444
+ log = (evt, fields = {}) => console.log(JSON.stringify({ evt, t: Date.now(), ...fields }));
1445
+ repoArgOfGitdir = (gitdir) => gitdir.replace(/\/nomos\.git$/, "");
1446
+ bytesFromB64 = (b64) => Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
1447
+ kgit = {
1448
+ // resolveRef → tip oid hex, or null if the ref is absent (replaces git.resolveRef(...).catch(()=>null)).
1449
+ resolveRef: (eng, gitdir, ref) => JSON.parse(call(eng.ex, "resolve_ref", { repoArg: repoArgOfGitdir(gitdir), ref }, eng.STDERR)).oid,
1450
+ // readBlob → the blob bytes at `path` inside commit `oid`, or null if not found (no throw).
1451
+ readBlob: (eng, gitdir, oid, path2) => {
1452
+ const r = JSON.parse(call(eng.ex, "read_blob", { repoArg: repoArgOfGitdir(gitdir), oid, path: path2 }, eng.STDERR));
1453
+ return r.ok ? bytesFromB64(r.blobB64) : null;
1454
+ },
1455
+ // intentsAbove → [{ oid, intentB64 }] oldest→newest over (base, head] (replaces log + readBlob intent.json).
1456
+ // `limit` (0 = all) caps to the most-recent N intent commits (replaces git.log depth).
1457
+ intentsAbove: (eng, gitdir, head, base = "", limit = 0) => JSON.parse(call(eng.ex, "intents_above", { repoArg: repoArgOfGitdir(gitdir), head, base, limit }, eng.STDERR)).intents,
1458
+ // listRefs → [{ ref, oid }] under prefix (replaces git.listRefs for LOCAL refs).
1459
+ listRefs: (eng, gitdir, prefix) => JSON.parse(call(eng.ex, "list_refs", { repoArg: repoArgOfGitdir(gitdir), prefix }, eng.STDERR)).refs,
1460
+ // writeRef → force-point a ref (plain oid or `ref:`-symbolic) (replaces git.writeRef).
1461
+ writeRef: (eng, gitdir, ref, value) => JSON.parse(call(eng.ex, "write_ref", { repoArg: repoArgOfGitdir(gitdir), ref, value }, eng.STDERR)),
1462
+ // deleteRef → remove a local ref, idempotent (replaces git.deleteRef).
1463
+ deleteRef: (eng, gitdir, ref) => JSON.parse(call(eng.ex, "delete_ref", { repoArg: repoArgOfGitdir(gitdir), ref }, eng.STDERR)),
1464
+ // applyPack → ingest a pack's objects into ws's repo (kernel apply_pack; refs are the caller's job).
1465
+ applyPack: (eng, ws, packBytes) => applyPackInto(eng, ws, packBytes),
1466
+ // writeMetaCommit → blobs→tree→commit→ref for a CUSTODY-META fact (checkpoint/refused/outbox/shape).
1467
+ // `files`: [{ path, bytes:Uint8Array }]; returns the commit oid (replaces writeBlob+writeTree+writeCommit[+writeRef]).
1468
+ writeMetaCommit: (eng, gitdir, { parents = [], files, message = "nomos custody meta", timeSecs = 0, ref = "" }) => JSON.parse(call(eng.ex, "write_meta_commit", {
1469
+ repoArg: repoArgOfGitdir(gitdir),
1470
+ parents,
1471
+ files: files.map((f) => ({ path: f.path, blobB64: b64Bytes(f.bytes) })),
1472
+ message,
1473
+ timeSecs,
1474
+ ref
1475
+ }, eng.STDERR)).oid
1476
+ };
1477
+ installPayload = (hash, usda, installedBy, dispositions) => ({ domainHash: hash, packageUsda: usda, installedBy, dependencies: [], finalizers: [], ...dispositions ? { dispositions } : {} });
1478
+ routeTagHexOfHomeKey = async (homeKey) => (await sha256hex(`nomos-route:${homeKey}`)).slice(0, 12);
1479
+ SUMMARY_SEP = "";
1480
+ summaryKey = (readId, group) => `${readId}${SUMMARY_SEP}${group}`;
1481
+ splitSummaryKey = (key) => {
1482
+ const i = key.indexOf(SUMMARY_SEP);
1483
+ return [key.slice(0, i), key.slice(i + 1)];
1484
+ };
1485
+ NOMOS_SHARD_ROWS_READ = "nomosShardRows";
1486
+ groupOf = (read, data) => {
1487
+ if (read.by === null) return "";
1488
+ const v = data ? data[read.by] : void 0;
1489
+ return v === void 0 || v === null ? void 0 : String(v);
1490
+ };
1491
+ tallyOf = (eng, ws, read, group) => read.kind === "count" ? count(eng, ws, read.id, group).count : read.kind === "sum" ? sum(eng, ws, read.id, group).sum : extremum(eng, ws, read.id, read.kind, group).value;
1492
+ isExtremumRead = (read) => read.kind === "min" || read.kind === "max";
1493
+ extremumMonotone = (read, prev, next) => next === null && prev === null || next !== null && (prev === null || (read.kind === "min" ? next <= prev : next >= prev));
1494
+ pushVia = (ledger, fn) => ledger && ledger.pushLane ? ledger.pushLane(fn) : fn();
1495
+ fullRef = (r) => r === "HEAD" || r.startsWith("refs/") ? r : `refs/heads/${r}`;
1496
+ applyPackInto = (eng, ws, pack) => {
1497
+ if (!pack || !pack.length) return;
1498
+ const r = JSON.parse(call(eng.ex, "apply_pack", { repoArg: repoArgOf(ws), packB64: b64Bytes(pack) }, eng.STDERR));
1499
+ if (!r || r.ok !== true) throw new Error(`apply_pack: ${r && r.error}`);
1500
+ };
1501
+ custodyLsRefs = (ledger, prefix = null) => lsRefs(ledger.remote, ledger.headers || {}, { service: "git-upload-pack", prefix });
1502
+ qById = (eng, ws, id, principal = "", keys = []) => JSON.parse(call(eng.ex, "query", { repoArg: repoArgOf(ws), workspace: ws, queryBytes: b64Json({ op: "byId", aggregateId: id }), principal, keys, branch: BRANCH }, eng.STDERR));
1503
+ query = (eng, ws, queryId, paramsJson, principal = "", keys = []) => JSON.parse(call(eng.ex, "query", { repoArg: repoArgOf(ws), workspace: ws, queryBytes: b64Json({ kind: "query", queryId, paramsJson }), principal, keys, branch: BRANCH }, eng.STDERR));
1504
+ authorKeygen = (eng) => JSON.parse(call(eng.ex, "query", { queryBytes: b64Json({ op: "authorKeygen" }) }, eng.STDERR));
1505
+ attestedRead = (eng, ws, { queryId, paramsJson, attestorSecret, nowMs, includeRosterProof }) => JSON.parse(call(eng.ex, "query", {
1506
+ repoArg: repoArgOf(ws),
1507
+ workspace: ws,
1508
+ branch: BRANCH,
1509
+ queryBytes: b64Json({ op: "attestedRead", queryId, paramsJson: paramsJson || "{}", attestorSecret, nowMs: nowMs ?? Date.now(), sourceWorkspace: ws, ...includeRosterProof ? { includeRosterProof: true } : {} })
1510
+ }, eng.STDERR));
1511
+ certSign = (eng, {
1512
+ child,
1513
+ founder,
1514
+ verified,
1515
+ parentKey,
1516
+ parentId,
1517
+ epoch,
1518
+ secret,
1519
+ verifiedVia,
1520
+ idpToken,
1521
+ capturedClock,
1522
+ authProviderIssuer,
1523
+ authProviderJwks,
1524
+ authProviderAudience
1525
+ }) => JSON.parse(call(eng.ex, "query", { queryBytes: b64Json({
1526
+ op: "certSign",
1527
+ child,
1528
+ founder,
1529
+ verified,
1530
+ parentKey,
1531
+ parentId,
1532
+ epoch,
1533
+ secret,
1534
+ // forwarded only when present (the op reads them optionally; absent ⇒ classic cert bytes).
1535
+ ...verifiedVia !== void 0 ? { verifiedVia } : {},
1536
+ ...idpToken !== void 0 ? { idpToken } : {},
1537
+ ...capturedClock !== void 0 ? { capturedClock } : {},
1538
+ ...authProviderIssuer !== void 0 ? { authProviderIssuer } : {},
1539
+ ...authProviderJwks !== void 0 ? { authProviderJwks } : {},
1540
+ ...authProviderAudience !== void 0 ? { authProviderAudience } : {}
1541
+ }) }, eng.STDERR)).cert;
1542
+ readPosture = (eng, ws, principal = "", authToken = "", nowUnix = 0) => JSON.parse(call(eng.ex, "query", { repoArg: repoArgOf(ws), workspace: ws, queryBytes: b64Json({ op: "readPosture", authToken, nowUnix }), principal, branch: BRANCH }, eng.STDERR));
1543
+ count = (eng, ws, countId, groupKey, principal = "") => JSON.parse(call(eng.ex, "query", { repoArg: repoArgOf(ws), workspace: ws, queryBytes: b64Json({ op: "count", countId, groupKey }), principal, branch: BRANCH }, eng.STDERR));
1544
+ sum = (eng, ws, sumId, groupKey, principal = "") => JSON.parse(call(eng.ex, "query", { repoArg: repoArgOf(ws), workspace: ws, queryBytes: b64Json({ op: "sum", sumId, groupKey }), principal, branch: BRANCH }, eng.STDERR));
1545
+ pendingConflicts = (eng, ws, principal = "") => JSON.parse(call(eng.ex, "query", { repoArg: repoArgOf(ws), workspace: ws, queryBytes: b64Json({ op: "pendingConflicts" }), principal, branch: BRANCH }, eng.STDERR));
1546
+ spatialBboxParams = (bbox) => {
1547
+ const minX = bbox.minX ?? bbox.minLng, minY = bbox.minY ?? bbox.minLat, maxX = bbox.maxX ?? bbox.maxLng, maxY = bbox.maxY ?? bbox.maxLat;
1548
+ return { minX, minY, maxX, maxY, minLng: minX, minLat: minY, maxLng: maxX, maxLat: maxY };
1549
+ };
1550
+ spatialWithin = (eng, ws, spatialId, bbox, principal = "") => JSON.parse(call(eng.ex, "query", { repoArg: repoArgOf(ws), workspace: ws, queryBytes: b64Json({ op: "spatial", spatialId, ...spatialBboxParams(bbox) }), principal, branch: BRANCH }, eng.STDERR));
1551
+ extremum = (eng, ws, extremumId, kind, groupKey, principal = "") => JSON.parse(call(eng.ex, "query", { repoArg: repoArgOf(ws), workspace: ws, queryBytes: b64Json({ op: "extremum", extremumId, kind, groupKey: groupKey ?? "" }), principal, branch: BRANCH }, eng.STDERR));
1552
+ nomosActive = (eng, ws) => qById(eng, ws, `domain-installation:${eng.hashes.nomos}`).length > 0;
1553
+ refusedRefName = (offerId) => `refs/heads/refused/${String(offerId || "unknown").replace(/[^A-Za-z0-9._-]/g, "_")}`;
1554
+ GENESIS_WARRANT_ID = "genesis-warrant:self";
1555
+ isWarranted = (eng, ws) => qById(eng, ws, GENESIS_WARRANT_ID).length > 0;
1556
+ }
1557
+ });
1558
+
1559
+ // ../cloud/dev-server/types.ts
1560
+ function errMsg(e) {
1561
+ return String(e && e.message || e);
1562
+ }
1563
+ function errStack(e) {
1564
+ const x = e;
1565
+ return String(x && x.stack || x && x.message || e);
1566
+ }
1567
+ var init_types = __esm({
1568
+ "../cloud/dev-server/types.ts"() {
1569
+ "use strict";
1570
+ }
1571
+ });
1572
+
1573
+ // ../cloud/dev-server/bootstrap.ts
1574
+ var bootstrap_exports = {};
1575
+ __export(bootstrap_exports, {
1576
+ bootstrapPlatform: () => bootstrapPlatform,
1577
+ homeDomainOf: () => homeDomainOf,
1578
+ isTestMint: () => isTestMint
1579
+ });
1580
+ import { readFileSync } from "node:fs";
1581
+ import { createHash } from "node:crypto";
1582
+ function isTestMint(eng) {
1583
+ try {
1584
+ setTestKRoot(eng, "");
1585
+ return true;
1586
+ } catch (e) {
1587
+ return !/poisoned|unknown|adapter-visible API/.test(errMsg(e));
1588
+ }
1589
+ }
1590
+ function homeDomainOf(opts) {
1591
+ if (!opts || !opts.deploy) return null;
1592
+ try {
1593
+ const body = JSON.parse(readFileSync(opts.deploy, "utf8"));
1594
+ const domains = body.summary && body.summary.domains || [];
1595
+ const hit = domains.find((d) => Array.isArray(d.directives) && d.directives.includes("seedBirthAttestation"));
1596
+ return hit ? hit.domain : null;
1597
+ } catch {
1598
+ return null;
1599
+ }
1600
+ }
1601
+ async function bootstrapPlatform(dev, opts) {
1602
+ const { eng, custody, ledgerFor, serialize, origin } = dev;
1603
+ const platform = opts.platform || "co2-platform-local";
1604
+ log2(`standing up platform '${platform}' on ${origin}`);
1605
+ await serialize(async () => {
1606
+ custody.create(`holon-${platform}`);
1607
+ await mountWorkspace(eng, platform, ledgerFor(platform));
1608
+ if (!nomosActive(eng, platform)) {
1609
+ const r = author(
1610
+ eng,
1611
+ platform,
1612
+ "bootstrap",
1613
+ "installDomain",
1614
+ installPayload(eng.hashes.nomos, eng.nomosPkg, "dev-bootstrap"),
1615
+ "",
1616
+ {}
1617
+ );
1618
+ if (r && r.ok === false) throw new Error(`platform genesis (framework install) REFUSED: ${String(r.error).slice(0, 300)}`);
1619
+ }
1620
+ log2(`platform '${platform}' genesis'd via the operator anchor lane (framework ${eng.hashes.nomos.slice(0, 12)})`);
1621
+ });
1622
+ if (opts.deploy) {
1623
+ const body = JSON.parse(readFileSync(opts.deploy, "utf8"));
1624
+ const usda = body.packageUsda || body.usda;
1625
+ if (!usda) throw new Error(`--deploy ${opts.deploy} has no packageUsda (nothing to install)`);
1626
+ const deployErr = await serialize(async () => {
1627
+ const ledger = ledgerFor(platform);
1628
+ const domainHash = await sha256hex(usda);
1629
+ try {
1630
+ const out = await deploy(eng, platform, ledger, usda, domainHash, body.dispositions || null, { actor: "user:dev-admin" });
1631
+ if (out && out.ok === false) return String(out.error || "the law refused the platform package");
1632
+ log2(`platform law deployed: ${domainHash.slice(0, 12)} (head ${String(out.head).slice(0, 12)})`);
1633
+ return null;
1634
+ } catch (e) {
1635
+ return errMsg(e);
1636
+ }
1637
+ });
1638
+ if (deployErr) throw new Error(`platform law deploy REFUSED: ${deployErr.slice(0, 400)}`);
1639
+ } else {
1640
+ log2("no --deploy given; platform runs framework law only (deploy your platform package to enable births)");
1641
+ }
1642
+ const testMint = isTestMint(eng);
1643
+ if (!testMint) {
1644
+ throw new Error(
1645
+ "dev bootstrap: `--platform` needs the test-mint kernel (set_test_k_root is poisoned in this one). The bundled cloud/dev-server/kernel-testmint.wasm is used automatically when reachable; otherwise build one (./git-holon/build_wasm.sh --release --features test-mint --bin wasm_git_holon) and set NOMOS_LOCAL_WASM."
1646
+ );
1647
+ } else {
1648
+ const OPERATOR = opts.operator || "user:dev-operator";
1649
+ const kRoot = authorKeygen(eng);
1650
+ setTestKRoot(eng, kRoot.public);
1651
+ log2(`K_root ceremony: pinned LOCAL test K_root ${kRoot.public.slice(0, 16)}\u2026`);
1652
+ const sP = authorKeygen(eng);
1653
+ const platformCert = certSign(eng, {
1654
+ child: platform,
1655
+ founder: OPERATOR,
1656
+ verified: true,
1657
+ parentKey: sP.public,
1658
+ // P_P — the onboarding signer the platform vouches for
1659
+ parentId: "root",
1660
+ epoch: 0,
1661
+ secret: kRoot.secret
1662
+ // signed by S_root
1663
+ });
1664
+ const certChain = JSON.stringify({ links: [platformCert] });
1665
+ const homeDomain = homeDomainOf(opts) || "home";
1666
+ const lawKeys = await serialize(async () => {
1667
+ await mountWorkspace(eng, platform, ledgerFor(platform));
1668
+ return currentLaw(eng, platform);
1669
+ });
1670
+ const lawHash = (lawKeys || {})[homeDomain] || "";
1671
+ if (!lawHash) {
1672
+ throw new Error(
1673
+ `dev bootstrap: the deployed platform law declares no '${homeDomain}' framework domain (seedBirthAttestation/enrollSigner/seedGenesis absent) \u2014 an era-0 platform must be born WARRANTED. Deploy a law that composes the home framework (export the birth machinery from @githolon/dsl) via --deploy.`
1674
+ );
1675
+ } else {
1676
+ let devIdP;
1677
+ {
1678
+ const { generateKeyPairSync, sign: nodeSign } = await import("node:crypto");
1679
+ const { privateKey, publicKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });
1680
+ const jwk = publicKey.export({ format: "jwk" });
1681
+ const ISS = `https://dev-idp.local/${platform}`;
1682
+ const AUD = `${platform}-app`;
1683
+ const JWKS = JSON.stringify({ keys: [{ kty: "EC", crv: "P-256", kid: "dev-idp", alg: "ES256", use: "sig", x: jwk.x, y: jwk.y }] });
1684
+ const b64url = (b) => Buffer.from(b).toString("base64url");
1685
+ const mint = (claims) => {
1686
+ const header = b64url(JSON.stringify({ alg: "ES256", typ: "JWT", kid: "dev-idp" }));
1687
+ const payload = b64url(JSON.stringify({ iss: ISS, aud: AUD, nbf: 0, exp: 4102444800, ...claims }));
1688
+ const si = `${header}.${payload}`;
1689
+ return `${si}.${b64url(nodeSign("sha256", Buffer.from(si), { key: privateKey, dsaEncoding: "ieee-p1363" }))}`;
1690
+ };
1691
+ const ap = await serialize(async () => authorOn(
1692
+ eng,
1693
+ platform,
1694
+ ledgerFor(platform),
1695
+ homeDomain,
1696
+ "setAuthProvider",
1697
+ { issuer: ISS, keys: JWKS, audience: AUD, principalClaim: "sub", deviceBindingClaim: "nonce" },
1698
+ lawHash,
1699
+ { actor: OPERATOR, principalVerified: true }
1700
+ ));
1701
+ if (ap.ok) {
1702
+ devIdP = { issuer: ISS, audience: AUD, jwks: JWKS, mint };
1703
+ log2(`dev test IdP registered (setAuthProvider ${ISS}, aud ${AUD}) \u2014 mint tokens via POST /dev/mint-token`);
1704
+ } else {
1705
+ log2(`dev test IdP NOT registered \u2014 the law composes no setAuthProvider (${String(ap.error).slice(0, 120)}); /dev/mint-token will refuse`);
1706
+ }
1707
+ }
1708
+ const sOp = authorKeygen(eng);
1709
+ const opKeyHash = createHash("sha256").update(Buffer.from(sOp.public, "base64")).digest("hex");
1710
+ const A = (directiveId, payload) => serialize(async () => authorOn(
1711
+ eng,
1712
+ platform,
1713
+ ledgerFor(platform),
1714
+ homeDomain,
1715
+ directiveId,
1716
+ payload,
1717
+ lawHash,
1718
+ { actor: OPERATOR, principalVerified: true }
1719
+ ));
1720
+ const en = await A("enrollSigner", { keyHash: opKeyHash, grantedBy: OPERATOR, grantedAt: 1 });
1721
+ if (!en.ok) throw new Error(`platform founding enrollSigner REFUSED: ${String(en.error).slice(0, 400)}`);
1722
+ const seed = await A("seedBirthAttestation", {
1723
+ child: platform,
1724
+ founder: OPERATOR,
1725
+ verified: "true",
1726
+ parentId: "root",
1727
+ parentKey: sP.public,
1728
+ epoch: 0,
1729
+ certChain
1730
+ });
1731
+ if (!seed.ok) throw new Error(`platform BirthAttestation seed REFUSED: ${String(seed.error).slice(0, 400)}`);
1732
+ const warrant = await A("seedGenesis", {
1733
+ principal: OPERATOR,
1734
+ workspaceId: platform,
1735
+ bornAt: (/* @__PURE__ */ new Date()).toISOString()
1736
+ });
1737
+ if (!warrant.ok) throw new Error(`platform WARRANT (seedGenesis) REFUSED: ${String(warrant.error).slice(0, 400)}`);
1738
+ dev.operatorDevice = sOp;
1739
+ dev.testIdP = devIdP;
1740
+ log2(`root-attested platform: enrolled founding device ${opKeyHash.slice(0, 12)}\u2026, seeded BirthAttestation (platform_cert signed by K_root, P_P=${sP.public.slice(0, 12)}\u2026), WARRANTED (self-id ${platform})`);
1741
+ log2(" a birthHome under this platform now assembles [home_cert, u_delegation(S_P), platform_cert(K_root)] \u2014 no unwarranted-cert.");
1742
+ log2(" ENROLL each user via the warranted lane: enrollFirstDevice (AuthProvider) or enrollDelegation (S_P-signed cert).");
1743
+ dev.testKRoot = kRoot;
1744
+ dev.onboardingSigner = sP;
1745
+ dev.platformCert = platformCert;
1746
+ dev.platformBirthAttestation = { child: platform, parentKey: sP.public, certChain };
1747
+ dev.homeDomain = homeDomain;
1748
+ }
1749
+ }
1750
+ if (opts.authProvider || opts.firebaseProject) {
1751
+ log2(`AuthProvider: ${opts.authProvider || `firebase:${opts.firebaseProject}`} \u2014 register it via the platform's setAuthProvider governance offer;`);
1752
+ log2(" the kernel verifies x-nomos-auth JWTs against the law-declared key (host stays blind).");
1753
+ }
1754
+ const attested = testMint && !!dev.platformBirthAttestation;
1755
+ log2(attested ? "bootstrap complete \u2014 platform law deployed + ROOT-ATTESTED (BirthAttestation certChain seeded; birthHome assembles a valid travelling cert)." : "bootstrap complete (platform law deployed; attested-birth legs gated as noted above \u2014 need the test-mint wasm).");
1756
+ return { platform, testMint, attested };
1757
+ }
1758
+ var log2;
1759
+ var init_bootstrap = __esm({
1760
+ "../cloud/dev-server/bootstrap.ts"() {
1761
+ "use strict";
1762
+ init_engine();
1763
+ init_types();
1764
+ log2 = (m) => console.log(`[bootstrap] ${m}`);
1765
+ }
1766
+ });
1767
+
1768
+ // ../cloud/dev-server/server.ts
1769
+ init_engine();
1770
+ init_custody_transport();
1771
+ import http from "node:http";
1772
+ import { createHash as createHash2, randomBytes } from "node:crypto";
1773
+ import { readFileSync as readFileSync2, writeFileSync, existsSync as existsSync2, mkdirSync as mkdirSync2, mkdtempSync } from "node:fs";
1774
+ import { fileURLToPath } from "node:url";
1775
+ import path from "node:path";
1776
+ import os from "node:os";
1777
+
1778
+ // ../adapter/pack_auth_contract.ts
1779
+ var HDR = Object.freeze({
1780
+ /** The verified PROOF: an IdP access token (JWT), kernel-verified against the workspace's AuthProvider. */
1781
+ AUTH: "x-nomos-auth",
1782
+ /** The bare CLAIM (transitional / unverified fallback when no token is presented). */
1783
+ PRINCIPAL: "x-nomos-principal"
1784
+ });
1785
+ function bulkReadForbidden(ws, kind, verdict) {
1786
+ const v = verdict || {};
1787
+ const caps = v.requiredRelationAnyOf || v.caps || [];
1788
+ const premise = v.tokenError ? `token-verification-failed:${v.tokenError}` : v.resolvedPrincipal ? "principal-lacks-workspace-read-cap" : "no-principal-presented";
1789
+ const why = v.tokenError ? `the presented ${HDR.AUTH} token did NOT verify (${v.tokenError}) against the workspace's declared issuer ${v.issuer || "?"}${v.audience ? ` / audience ${v.audience}` : ""}.` : v.resolvedPrincipal ? `resolved principal '${v.resolvedPrincipal}'${v.principalVerified ? " (token-verified)" : ` (unverified bare ${HDR.PRINCIPAL} claim)`} holds none of the required read capabilities.` : `no principal was presented \u2014 send a verified ${HDR.AUTH} token for a principal the owner granted a read capability.`;
1790
+ return {
1791
+ ok: false,
1792
+ ws,
1793
+ error: `${kind}-forbidden`,
1794
+ forbidden: {
1795
+ premise,
1796
+ workspace: ws,
1797
+ resolvedPrincipal: v.resolvedPrincipal || null,
1798
+ principalVerified: !!v.principalVerified,
1799
+ tokenError: v.tokenError || null,
1800
+ requiredObject: v.requiredObject || "workspace:self",
1801
+ requiredRelationAnyOf: caps,
1802
+ issuer: v.issuer || null,
1803
+ audience: v.audience || null
1804
+ },
1805
+ hint: `this workspace is private (read visibility) \u2014 a ${kind} reads the whole ledger, so it requires a principal granted ANY of its read capabilities (${caps.join(", ") || "a read cap"}) on ${v.requiredObject || "workspace:self"}: ${why}`
1806
+ };
1807
+ }
1808
+
1809
+ // ../cloud/cloudflare-shell/src/gateway-route-resolver.ts
1810
+ function aliasIdsFor(x, path2) {
1811
+ const ids = [];
1812
+ for (const key of ["directiveId", "queryId", "countId", "sumId", "extremumId", "spatialId"]) {
1813
+ const value = x && x[key];
1814
+ if (typeof value === "string" && value) ids.push(value);
1815
+ }
1816
+ const leaf = String(path2 || "").replace(/^\/+/, "").split("/").filter(Boolean).at(-1);
1817
+ if (leaf) ids.push(leaf);
1818
+ return new Set(ids);
1819
+ }
1820
+ function resolveGatewayOperation(spec, opName, method) {
1821
+ if (!spec || !spec.paths || !opName || !method) return { op: null };
1822
+ const normalizedMethod = String(method).toLowerCase();
1823
+ const exactPath = `/${String(opName).replace(/^\/+/, "")}`;
1824
+ const exact = spec.paths[exactPath]?.[normalizedMethod];
1825
+ if (exact) return { op: exact, path: exactPath, ambiguous: null };
1826
+ if (String(opName).includes("/")) return { op: null };
1827
+ const matches = [];
1828
+ for (const [path2, methods] of Object.entries(spec.paths)) {
1829
+ const op = methods?.[normalizedMethod];
1830
+ const x = op?.["x-nomos"];
1831
+ if (!op || !x) continue;
1832
+ if (aliasIdsFor(x, path2).has(opName)) matches.push({ op, path: path2 });
1833
+ }
1834
+ if (matches.length === 1) return { ...matches[0], ambiguous: null };
1835
+ if (matches.length > 1) {
1836
+ return { op: null, ambiguous: matches.map((m) => m.path).sort() };
1837
+ }
1838
+ return { op: null, ambiguous: null };
1839
+ }
1840
+
1841
+ // ../cloud/cloudflare-shell/src/staged-intents.ts
1842
+ var STAGE_THRESHOLD_CHARS = 4 * 1024 * 1024;
1843
+ var MAX_INLINE_INTENT_CHARS = 8 * 1024 * 1024;
1844
+ var MAX_STAGED_INTENT_BYTES = 64 * 1024 * 1024;
1845
+ var stagedIntentKey = (sha256) => typeof sha256 === "string" && /^[0-9a-f]{64}$/.test(sha256) ? `staged-intents/${sha256}` : null;
1846
+ async function sha256hexBytes(bytes) {
1847
+ const d = await crypto.subtle.digest("SHA-256", bytes);
1848
+ return [...new Uint8Array(d)].map((x) => x.toString(16).padStart(2, "0")).join("");
1849
+ }
1850
+ var b64OfBytes = (bytes) => {
1851
+ let s = "";
1852
+ for (let i = 0; i < bytes.length; i += 32768) s += String.fromCharCode.apply(null, bytes.subarray(i, i + 32768));
1853
+ return btoa(s);
1854
+ };
1855
+ async function stagePut(bucket, sha256, bytes) {
1856
+ const key = stagedIntentKey(sha256);
1857
+ if (key === null) return { status: 400, body: { ok: false, error: "stage-bad-ref: the path must name sha256 as 64 lowercase hex" } };
1858
+ if (!(bytes instanceof Uint8Array) || bytes.length === 0) return { status: 400, body: { ok: false, error: "stage-empty: PUT a non-empty raw body (the sealed intent bytes)" } };
1859
+ if (bytes.length > MAX_STAGED_INTENT_BYTES) return { status: 413, body: { ok: false, error: `stage-too-large: staged bytes are capped at ${MAX_STAGED_INTENT_BYTES} bytes` } };
1860
+ const got = await sha256hexBytes(bytes);
1861
+ if (got !== sha256) return { status: 400, body: { ok: false, error: `stage-hash-mismatch: sha256(body) is ${got}, not the named ${sha256} \u2014 stage bytes under their own hash` } };
1862
+ const existing = typeof bucket.head === "function" ? await bucket.head(key) : await bucket.get(key);
1863
+ if (existing) return { status: 200, body: { ok: true, sha256, size: bytes.length, alreadyStaged: true } };
1864
+ await bucket.put(key, bytes);
1865
+ return { status: 200, body: { ok: true, sha256, size: bytes.length, staged: true } };
1866
+ }
1867
+ async function resolveStagedIntent(bucket, ref) {
1868
+ const sha256 = ref && typeof ref === "object" && typeof ref.sha256 === "string" ? ref.sha256 : "";
1869
+ const key = stagedIntentKey(sha256);
1870
+ if (key === null) return { ok: false, status: 400, error: "staged-intent-bad-ref: intentRef must be { sha256: <64 lowercase hex>, size? }" };
1871
+ const obj = await bucket.get(key);
1872
+ if (!obj) return { ok: false, status: 422, error: `staged-intent-missing: no staged bytes for sha256 ${sha256} \u2014 PUT /v2/stage/${sha256} (raw sealed intent bytes) first, then re-offer { intentRef }` };
1873
+ const bytes = new Uint8Array(await obj.arrayBuffer());
1874
+ if (bytes.length > MAX_STAGED_INTENT_BYTES) return { ok: false, status: 413, error: `staged-intent-too-large: staged bytes exceed the ${MAX_STAGED_INTENT_BYTES}-byte cap` };
1875
+ if (typeof ref?.size === "number" && ref.size !== bytes.length) return { ok: false, status: 422, error: `staged-intent-size-mismatch: the ref names ${ref.size} bytes but ${bytes.length} are staged` };
1876
+ const got = await sha256hexBytes(bytes);
1877
+ if (got !== sha256) return { ok: false, status: 422, error: `staged-intent-hash-mismatch: staged bytes hash to ${got}, not the offered ${sha256} \u2014 the signed offer's hash is the binding; refuse` };
1878
+ return { ok: true, intentB64: b64OfBytes(bytes), sha256, size: bytes.length };
1879
+ }
1880
+
1881
+ // ../cloud/dev-server/custody.ts
1882
+ import { spawn, execFileSync } from "node:child_process";
1883
+ import { existsSync, mkdirSync, rmSync, readdirSync } from "node:fs";
1884
+ import { join } from "node:path";
1885
+ var GIT_HTTP_BACKEND = join(
1886
+ execFileSync("git", ["--exec-path"], { encoding: "utf8" }).trim(),
1887
+ "git-http-backend"
1888
+ );
1889
+ var FilesystemGitRepository = class {
1890
+ constructor(name, dir, origin) {
1891
+ this.name = name;
1892
+ this.dir = dir;
1893
+ this.remote = `${origin}/git/nomos/${name}.git`;
1894
+ }
1895
+ // Dev custody is open (git-http-backend export-all): a token is inert but we keep the
1896
+ // production SHAPE so callers that thread `createToken(...).plaintext` are unchanged.
1897
+ createToken(_scope = "read", ttlSec = 3600) {
1898
+ return { plaintext: "dev-inert-token", expiresAt: Date.now() + ttlSec * 1e3 };
1899
+ }
1900
+ };
1901
+ var FilesystemGitCustody = class {
1902
+ /** @param dataDir the --data root; repos live under <dataDir>/custody */
1903
+ constructor(dataDir, origin) {
1904
+ this.root = join(dataDir, "custody");
1905
+ this.origin = origin;
1906
+ mkdirSync(this.root, { recursive: true });
1907
+ }
1908
+ _dirOf(name) {
1909
+ return join(this.root, `${name}.git`);
1910
+ }
1911
+ get(name) {
1912
+ const dir = this._dirOf(name);
1913
+ return existsSync(dir) ? new FilesystemGitRepository(name, dir, this.origin) : null;
1914
+ }
1915
+ /** Idempotent: init a bare repo (with http.receivepack so the client can push). */
1916
+ create(name) {
1917
+ const dir = this._dirOf(name);
1918
+ if (!existsSync(dir)) {
1919
+ mkdirSync(dir, { recursive: true });
1920
+ execFileSync("git", ["init", "--bare", "--quiet", dir]);
1921
+ execFileSync("git", ["--git-dir", dir, "config", "http.receivepack", "true"]);
1922
+ execFileSync("git", ["--git-dir", dir, "config", "http.uploadpack", "true"]);
1923
+ }
1924
+ return new FilesystemGitRepository(name, dir, this.origin);
1925
+ }
1926
+ delete(name) {
1927
+ const dir = this._dirOf(name);
1928
+ if (existsSync(dir)) rmSync(dir, { recursive: true, force: true });
1929
+ }
1930
+ list() {
1931
+ if (!existsSync(this.root)) return [];
1932
+ return readdirSync(this.root).filter((f) => f.endsWith(".git")).map((f) => f.slice(0, -4));
1933
+ }
1934
+ };
1935
+ function runGitHttpBackend(projectRoot, { method, pathInfo, query: query2, contentType, body }) {
1936
+ return new Promise((resolve, reject) => {
1937
+ const env = {
1938
+ ...process.env,
1939
+ GIT_PROJECT_ROOT: projectRoot,
1940
+ GIT_HTTP_EXPORT_ALL: "1",
1941
+ PATH_INFO: pathInfo,
1942
+ REQUEST_METHOD: method,
1943
+ QUERY_STRING: query2 || "",
1944
+ CONTENT_TYPE: contentType || "",
1945
+ CONTENT_LENGTH: String(body ? body.length : 0),
1946
+ REMOTE_ADDR: "127.0.0.1",
1947
+ REMOTE_USER: "nomos-dev",
1948
+ GIT_HTTP_MAX_REQUEST_BUFFER: String(64 * 1024 * 1024)
1949
+ };
1950
+ const cgi = spawn(GIT_HTTP_BACKEND, [], { env });
1951
+ const chunks = [];
1952
+ cgi.stdout.on("data", (d) => chunks.push(d));
1953
+ cgi.stderr.on("data", () => {
1954
+ });
1955
+ cgi.on("error", reject);
1956
+ cgi.on("close", () => {
1957
+ const out = Buffer.concat(chunks);
1958
+ let sep = out.indexOf("\r\n\r\n");
1959
+ let sepLen = 4;
1960
+ if (sep < 0) {
1961
+ sep = out.indexOf("\n\n");
1962
+ sepLen = 2;
1963
+ }
1964
+ const headerText = sep >= 0 ? out.slice(0, sep).toString("utf8") : out.toString("utf8");
1965
+ const payload = sep >= 0 ? out.slice(sep + sepLen) : Buffer.alloc(0);
1966
+ const headers = {};
1967
+ let status = 200;
1968
+ for (const line of headerText.split(/\r?\n/)) {
1969
+ const i = line.indexOf(":");
1970
+ if (i < 0) continue;
1971
+ const k = line.slice(0, i).trim();
1972
+ const v = line.slice(i + 1).trim();
1973
+ if (/^status$/i.test(k)) {
1974
+ status = parseInt(v, 10) || 200;
1975
+ continue;
1976
+ }
1977
+ headers[k] = v;
1978
+ }
1979
+ resolve({ status, headers, body: payload });
1980
+ });
1981
+ if (body && body.length) cgi.stdin.write(body);
1982
+ cgi.stdin.end();
1983
+ });
1984
+ }
1985
+ function receivePackCommands(raw) {
1986
+ const cmds = [];
1987
+ let off = 0;
1988
+ const dec4 = new TextDecoder();
1989
+ while (off + 4 <= raw.length) {
1990
+ const hex = dec4.decode(raw.subarray(off, off + 4));
1991
+ if (!/^[0-9a-f]{4}$/.test(hex)) break;
1992
+ const len = parseInt(hex, 16);
1993
+ if (len === 0) {
1994
+ off += 4;
1995
+ break;
1996
+ }
1997
+ let line = dec4.decode(raw.subarray(off + 4, off + len));
1998
+ off += len;
1999
+ const nul = line.indexOf("\0");
2000
+ if (nul >= 0) line = line.slice(0, nul);
2001
+ const m = line.match(/^([0-9a-f]{40}) ([0-9a-f]{40}) (.+?)\s*$/);
2002
+ if (m) cmds.push({ oldOid: m[1], newOid: m[2], ref: m[3] });
2003
+ }
2004
+ return cmds;
2005
+ }
2006
+
2007
+ // ../cloud/dev-server/server.ts
2008
+ init_types();
2009
+ var DIR = path.dirname(fileURLToPath(import.meta.url));
2010
+ var REPO_ROOT = path.resolve(DIR, "../..");
2011
+ var RECOGNIZED_UNSUPPORTED = /* @__PURE__ */ new Set([
2012
+ "container-status",
2013
+ "recycle-container",
2014
+ "hostnames",
2015
+ "rebirth-custody",
2016
+ "upload-begin",
2017
+ "upload-gate",
2018
+ "upload-verify",
2019
+ "drain-reclaims",
2020
+ "drain-rebirths",
2021
+ "git-read-lease",
2022
+ "poke-admit",
2023
+ "clear-checkpoint",
2024
+ "domain-package",
2025
+ "capabilities"
2026
+ ]);
2027
+ var UNSUPPORTED_WHY = {
2028
+ "container-status": "the heavy container tier is Cloudflare-only (the dev cloud is one in-process engine)",
2029
+ "recycle-container": "the heavy container tier is Cloudflare-only (the dev cloud is one in-process engine)",
2030
+ "hostnames": "platform custom-hostname routing is a multi-tenant edge concern",
2031
+ "rebirth-custody": "the custodian rebirth lane is bound to Cloudflare Artifacts custody",
2032
+ "upload-begin": "the upload-birth lane is DELETED \u2014 there is no push-to-create; a workspace is born by its PARENT authoring its birth (birthHome/birthChild/your .births() directive) and syncing the parent",
2033
+ "upload-gate": "the upload-birth lane is DELETED \u2014 author the birth on its parent and sync the parent",
2034
+ "upload-verify": "the upload-birth lane is DELETED \u2014 author the birth on its parent and sync the parent",
2035
+ "drain-reclaims": "an operator lawful-recovery drain (multi-node lifecycle)",
2036
+ "drain-rebirths": "an operator lawful-recovery drain (multi-node lifecycle)",
2037
+ "capabilities": "retired everywhere \u2014 host-side capability storage is gone (capabilities are holon-offered obligations now)"
2038
+ };
2039
+ var _realFetch = globalThis.fetch;
2040
+ globalThis.fetch = (input, init) => {
2041
+ const u = typeof input === "string" ? input : input?.url || "";
2042
+ if (/artifacts\.cloudflare\.net|\.workers\.dev/i.test(u)) {
2043
+ throw new Error(`REMOTE CUSTODY FORBIDDEN in dev cloud: refused fetch to ${u}`);
2044
+ }
2045
+ return _realFetch(input, init);
2046
+ };
2047
+ var unb64 = (s) => new Uint8Array(Buffer.from(s, "base64"));
2048
+ function configDir() {
2049
+ return process.env.HOLON_CONFIG_DIR || path.join(os.homedir(), ".holon");
2050
+ }
2051
+ function firstExisting(...paths) {
2052
+ for (const p of paths) {
2053
+ if (p && existsSync2(p)) return p;
2054
+ }
2055
+ return null;
2056
+ }
2057
+ var TEST_MINT_MARKER = Buffer.from("set_test_k_root");
2058
+ var isTestMintBytes = (bytes) => bytes.includes(TEST_MINT_MARKER);
2059
+ var KERNEL_CAPABILITY_REGISTRY = [
2060
+ {
2061
+ prefix: "846c6bf8",
2062
+ version: "kernel-846c6bf8",
2063
+ note: "production (accepts compound-key law)",
2064
+ features: ["compoundKeys", "capturedReads", "invariantGate", "surfacedMerge", "fieldProvenance", "nullSemantics", "attestedReads"]
2065
+ },
2066
+ {
2067
+ prefix: "f6e44b3a",
2068
+ version: "kernel-f6e44b3a",
2069
+ note: "test-mint (DEV) \u2014 current, feature-equivalent to production",
2070
+ features: ["compoundKeys", "capturedReads", "invariantGate", "surfacedMerge", "fieldProvenance", "nullSemantics", "attestedReads"]
2071
+ },
2072
+ {
2073
+ prefix: "f81cb952",
2074
+ version: "kernel-f81cb952",
2075
+ note: "test-mint (DEV ONLY \u2014 STALE: predates compound-key read router; superseded by f6e44b3a)",
2076
+ features: ["capturedReads", "invariantGate", "surfacedMerge", "fieldProvenance", "nullSemantics", "attestedReads"]
2077
+ }
2078
+ ];
2079
+ function capabilitiesForKernelHash(hash) {
2080
+ const h = String(hash || "").toLowerCase();
2081
+ const hit = KERNEL_CAPABILITY_REGISTRY.find((e) => h.startsWith(e.prefix) || e.prefix.startsWith(h.slice(0, 8)));
2082
+ return hit ? { hash: h, version: hit.version, note: hit.note, features: hit.features, known: true } : { hash: h, version: null, note: "UNKNOWN kernel \u2014 not in the capability registry", features: [], known: false };
2083
+ }
2084
+ var DEFAULT_KERNEL_SOURCE = "https://nomos.captainapp.co.uk";
2085
+ async function resolveTestMintWasm(kernelSource) {
2086
+ const runtimeCache = path.join(configDir(), "runtime");
2087
+ const cachePath = path.join(runtimeCache, "holon-testmint.wasm");
2088
+ const local = process.env.NOMOS_LOCAL_WASM;
2089
+ if (local && existsSync2(local)) {
2090
+ const bytes = readFileSync2(local);
2091
+ if (isTestMintBytes(bytes)) return { wasmPath: local, wasmBytes: bytes, kernelKind: "test-mint", kernelSource: "NOMOS_LOCAL_WASM" };
2092
+ }
2093
+ const bundled = path.join(DIR, "kernel-testmint.wasm");
2094
+ if (existsSync2(bundled)) {
2095
+ const bytes = readFileSync2(bundled);
2096
+ if (isTestMintBytes(bytes)) return { wasmPath: bundled, wasmBytes: bytes, kernelKind: "test-mint", kernelSource: "bundled" };
2097
+ }
2098
+ if (existsSync2(cachePath)) {
2099
+ const bytes = readFileSync2(cachePath);
2100
+ if (isTestMintBytes(bytes)) return { wasmPath: cachePath, wasmBytes: bytes, kernelKind: "test-mint", kernelSource: "cache" };
2101
+ }
2102
+ const src = String(kernelSource || process.env.NOMOS_KERNEL_SOURCE || DEFAULT_KERNEL_SOURCE).replace(/\/+$/, "");
2103
+ const url = `${src}/v1/runtime/holon-testmint.wasm`;
2104
+ try {
2105
+ const resp = await _realFetch(url);
2106
+ if (resp.ok) {
2107
+ const bytes = Buffer.from(await resp.arrayBuffer());
2108
+ if (isTestMintBytes(bytes)) {
2109
+ mkdirSync2(runtimeCache, { recursive: true });
2110
+ writeFileSync(cachePath, bytes);
2111
+ return { wasmPath: cachePath, wasmBytes: bytes, kernelKind: "test-mint", kernelSource: `fetched ${url}` };
2112
+ }
2113
+ }
2114
+ } catch {
2115
+ }
2116
+ throw new Error(
2117
+ `attested births need the test-mint kernel; it couldn't be fetched from ${src} (offline?) \u2014 build one: git-holon/build_wasm.sh --release --features test-mint --bin wasm_git_holon and set NOMOS_LOCAL_WASM`
2118
+ );
2119
+ }
2120
+ async function loadRuntime(opts = {}) {
2121
+ const runtimeCache = path.join(configDir(), "runtime");
2122
+ const repoDomainsDir = path.join(REPO_ROOT, "cloud/cloudflare-shell/container/domains");
2123
+ const vendoredFrameworkDir = path.join(DIR, "framework");
2124
+ let wasmPath, wasmBytes, kernelKind, kernelSource;
2125
+ if (opts.attested) {
2126
+ ({ wasmPath, wasmBytes, kernelKind, kernelSource } = await resolveTestMintWasm(opts.kernelSource));
2127
+ } else {
2128
+ wasmPath = firstExisting(
2129
+ process.env.NOMOS_LOCAL_WASM,
2130
+ path.join(REPO_ROOT, "cloud/cloudflare-shell/container/vendor/wasm_git_holon.wasm"),
2131
+ path.join(runtimeCache, "holon.wasm")
2132
+ );
2133
+ if (!wasmPath) {
2134
+ throw new Error(
2135
+ "no kernel wasm found. Warm the kernel first:\n \u2022 set NOMOS_LOCAL_WASM=<path to holon.wasm>, OR\n \u2022 run any `githolon` cloud command once (e.g. `githolon ledger verify \u2026`) to cache ~/.holon/runtime/holon.wasm\n (attested births additionally require a test-mint wasm \u2014 pass --bootstrap or --attested)"
2136
+ );
2137
+ }
2138
+ wasmBytes = readFileSync2(wasmPath);
2139
+ kernelKind = isTestMintBytes(wasmBytes) ? "test-mint" : "production";
2140
+ kernelSource = wasmPath === process.env.NOMOS_LOCAL_WASM ? "NOMOS_LOCAL_WASM" : wasmPath.startsWith(runtimeCache) ? "cache" : "repo-vendor";
2141
+ }
2142
+ const repoBootstrap = firstExisting(path.join(repoDomainsDir, "domain_bootstrap.package.usda"));
2143
+ const repoNomos = firstExisting(path.join(repoDomainsDir, "domain_nomos.package.usda"));
2144
+ let bootstrapPkg, nomosPkg;
2145
+ if (repoBootstrap && repoNomos) {
2146
+ bootstrapPkg = readFileSync2(repoBootstrap, "utf8");
2147
+ nomosPkg = readFileSync2(repoNomos, "utf8");
2148
+ } else if (existsSync2(path.join(vendoredFrameworkDir, "domain_bootstrap.package.usda"))) {
2149
+ bootstrapPkg = readFileSync2(path.join(vendoredFrameworkDir, "domain_bootstrap.package.usda"), "utf8");
2150
+ nomosPkg = readFileSync2(path.join(vendoredFrameworkDir, "domain_nomos.package.usda"), "utf8");
2151
+ } else {
2152
+ const pkgsCache = path.join(runtimeCache, "packages.json");
2153
+ if (!existsSync2(pkgsCache)) {
2154
+ throw new Error(
2155
+ "no framework packages found (domain_bootstrap/domain_nomos). Warm the runtime cache by running any `githolon` cloud command once, or run from the monorepo checkout."
2156
+ );
2157
+ }
2158
+ const pkgs = JSON.parse(readFileSync2(pkgsCache, "utf8"));
2159
+ bootstrapPkg = pkgs.bootstrap;
2160
+ nomosPkg = pkgs.nomos;
2161
+ }
2162
+ return { wasmPath, wasmBytes, bootstrapPkg, nomosPkg, kernelKind, kernelSource };
2163
+ }
2164
+ async function startDevCloud(opts = {}) {
2165
+ let devSelf = null;
2166
+ const port = opts.port || 8787;
2167
+ const host = opts.host || "127.0.0.1";
2168
+ const origin = `http://${host}:${port}`;
2169
+ const ephemeral = !!opts.ephemeral;
2170
+ const dataDir = ephemeral ? mkdtempSync(path.join(os.tmpdir(), "nomos-dev-cloud-")) : path.resolve(opts.data || ".nomos/dev-cloud");
2171
+ mkdirSync2(dataDir, { recursive: true });
2172
+ const attested = !!(opts.attested || opts.bootstrap || opts.platform);
2173
+ const { wasmPath, wasmBytes, bootstrapPkg, nomosPkg, kernelKind, kernelSource } = await loadRuntime({ attested, kernelSource: opts.kernelSource });
2174
+ console.log(`[dev-cloud] kernel : ${kernelKind} (from ${kernelSource})`);
2175
+ const wasmModule = await WebAssembly.compile(wasmBytes);
2176
+ const kernelSha = createHash2("sha256").update(wasmBytes).digest("hex");
2177
+ const enc4 = new TextEncoder();
2178
+ const replicaDigest = new Uint8Array(await crypto.subtle.digest("SHA-256", enc4.encode(`dev:${randomBytes(8).toString("hex")}`)));
2179
+ let replica = 0n;
2180
+ for (let i = 0; i < 8; i++) replica = replica << 8n | BigInt(replicaDigest[i]);
2181
+ replica &= (1n << 63n) - 1n;
2182
+ const eng = await createEngine({ wasmModule, bootstrapPkg, nomosPkg, replica, installedBy: "nomos-cloud-dev" });
2183
+ const custody = new FilesystemGitCustody(dataDir, origin);
2184
+ const stagedBytes = /* @__PURE__ */ new Map();
2185
+ const stageBucket = {
2186
+ async get(k) {
2187
+ const b = stagedBytes.get(k);
2188
+ return b ? { arrayBuffer: async () => b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength) } : null;
2189
+ },
2190
+ async put(k, bytes) {
2191
+ stagedBytes.set(k, bytes);
2192
+ },
2193
+ async head(k) {
2194
+ const b = stagedBytes.get(k);
2195
+ return b ? { size: b.length } : null;
2196
+ }
2197
+ };
2198
+ let chain = Promise.resolve();
2199
+ const serialize = (fn) => {
2200
+ const r = chain.then(fn, fn);
2201
+ chain = r.then(() => {
2202
+ }, () => {
2203
+ });
2204
+ return r;
2205
+ };
2206
+ const pushChains = /* @__PURE__ */ new Map();
2207
+ const pushLaneFor = (ws) => (fn) => {
2208
+ const prev = pushChains.get(ws) || Promise.resolve();
2209
+ const r = prev.then(fn, fn);
2210
+ pushChains.set(ws, r.then(() => {
2211
+ }, () => {
2212
+ }));
2213
+ return r;
2214
+ };
2215
+ const ledgerFor = (ws) => ({
2216
+ remote: `${origin}/git/nomos/holon-${ws}.git`,
2217
+ headers: {},
2218
+ pushLane: pushLaneFor(ws)
2219
+ });
2220
+ async function persistBorn(born) {
2221
+ if (!Array.isArray(born)) return [];
2222
+ const out = [];
2223
+ for (const b of born) {
2224
+ const child = b && b.workspace;
2225
+ const head = b && b.head;
2226
+ out.push({ workspace: child, head });
2227
+ if (!child || !/^[0-9a-f]{40}$/i.test(head || "") || !b.packB64) continue;
2228
+ const repo = custody.create(`holon-${child}`);
2229
+ const refs = await lsRefs(repo.remote, {}, { service: "git-receive-pack", prefix: "refs/heads/main" }).catch(() => ({}));
2230
+ const oldOid = refs["refs/heads/main"] || ZERO_OID;
2231
+ if (oldOid === head) continue;
2232
+ await pushLaneFor(child)(
2233
+ () => pushPack(repo.remote, {}, { updates: [{ ref: "refs/heads/main", oldOid, newOid: head }], pack: unb64(b.packB64) })
2234
+ );
2235
+ }
2236
+ return out;
2237
+ }
2238
+ const CORS = {
2239
+ "access-control-allow-origin": "*",
2240
+ "access-control-allow-methods": "GET,POST,PUT,DELETE,OPTIONS",
2241
+ "access-control-allow-headers": "content-type,x-nomos-auth,x-nomos-principal,authorization"
2242
+ };
2243
+ const sendJson = (res, obj, status = 200) => {
2244
+ const body = JSON.stringify(obj, null, 2) + "\n";
2245
+ res.writeHead(status, { "content-type": "application/json", ...CORS });
2246
+ res.end(body);
2247
+ };
2248
+ const sendBytes = (res, bytes, status = 200, headers = {}) => {
2249
+ res.writeHead(status, { ...CORS, ...headers });
2250
+ res.end(Buffer.from(bytes));
2251
+ };
2252
+ const readBody = (req) => new Promise((resolve) => {
2253
+ const chunks = [];
2254
+ req.on("data", (c) => chunks.push(c));
2255
+ req.on("end", () => resolve(Buffer.concat(chunks)));
2256
+ });
2257
+ const principalOf = (req) => String(req.headers["x-nomos-principal"] || "").slice(0, 128);
2258
+ const authTokenOf = (req) => String(req.headers["x-nomos-auth"] || "").replace(/^Bearer\s+/i, "");
2259
+ const postureGate = (res, ws, req, kind) => {
2260
+ let posture;
2261
+ try {
2262
+ posture = readPosture(eng, ws, principalOf(req), authTokenOf(req), Math.floor(Date.now() / 1e3));
2263
+ } catch {
2264
+ return false;
2265
+ }
2266
+ if (posture && posture.private && !posture.allowedAny) {
2267
+ sendJson(res, bulkReadForbidden(ws, kind, posture), 403);
2268
+ return true;
2269
+ }
2270
+ return false;
2271
+ };
2272
+ function openapiFor(ws) {
2273
+ const merged = { openapi: "3.1.0", info: { title: `${ws} (nomos workspace)`, version: "0", "x-nomos-workspace": ws }, paths: {} };
2274
+ const domOf = (o) => {
2275
+ const x = o;
2276
+ return String(x && x["x-nomos"] && x["x-nomos"].domain ? x["x-nomos"].domain : "domain");
2277
+ };
2278
+ const mergeInto = (frag) => {
2279
+ for (const [p, methods] of Object.entries(frag.paths || {})) {
2280
+ for (const [m, op] of Object.entries(methods)) {
2281
+ const existing = merged.paths[p] && merged.paths[p][m];
2282
+ if (existing === void 0) {
2283
+ (merged.paths[p] ||= {})[m] = op;
2284
+ } else if (JSON.stringify(existing) !== JSON.stringify(op)) {
2285
+ (merged.paths[`/${domOf(existing)}${p}`] ||= {})[m] = existing;
2286
+ (merged.paths[`/${domOf(op)}${p}`] ||= {})[m] = op;
2287
+ delete merged.paths[p][m];
2288
+ if (Object.keys(merged.paths[p]).length === 0) delete merged.paths[p];
2289
+ }
2290
+ }
2291
+ }
2292
+ };
2293
+ try {
2294
+ const spec = describe(eng, ws);
2295
+ if (spec && spec.paths) mergeInto(spec);
2296
+ } catch {
2297
+ }
2298
+ merged.paths["/openapi.json"] = {
2299
+ get: { operationId: "nomos__openapi", summary: "this workspace's live OpenAPI", responses: { "200": { description: "ok" } } }
2300
+ };
2301
+ return merged;
2302
+ }
2303
+ const server = http.createServer(async (req, res) => {
2304
+ try {
2305
+ const url = new URL(req.url ?? "", origin);
2306
+ const seg = url.pathname.split("/").filter(Boolean);
2307
+ if (req.method === "OPTIONS") {
2308
+ res.writeHead(204, CORS);
2309
+ return res.end();
2310
+ }
2311
+ if (url.pathname === "/health") {
2312
+ return sendJson(res, {
2313
+ ok: true,
2314
+ kernelSha,
2315
+ dataDir,
2316
+ wasmPath,
2317
+ workspaces: custody.list(),
2318
+ ...devSelf?.platformReady !== void 0 ? { platformReady: devSelf.platformReady } : {}
2319
+ });
2320
+ }
2321
+ if (url.pathname === "/dev/mint-token" && req.method === "POST") {
2322
+ const idp = devSelf?.testIdP;
2323
+ if (!idp) {
2324
+ return sendJson(res, {
2325
+ ok: false,
2326
+ error: "no dev test IdP \u2014 start with `--platform` and deploy a law that composes setAuthProvider (the warranted-onboard surface)"
2327
+ }, 409);
2328
+ }
2329
+ const b = JSON.parse((await readBody(req)).toString("utf8") || "{}");
2330
+ if (!b.sub) return sendJson(res, { ok: false, error: "mint-token: 'sub' (the bare uid) is required" }, 400);
2331
+ const token = idp.mint({ sub: b.sub, ...b.nonce ? { nonce: b.nonce } : {} });
2332
+ return sendJson(res, { ok: true, token, issuer: idp.issuer, audience: idp.audience });
2333
+ }
2334
+ if (url.pathname === "/v1/runtime/holon.wasm" || url.pathname === "/v1/runtime/holon-testmint.wasm") {
2335
+ res.writeHead(200, { ...CORS, "content-type": "application/wasm", "cache-control": "no-store", "x-nomos-kernel": kernelKind, "x-nomos-kernel-sha": kernelSha });
2336
+ return res.end(Buffer.from(wasmBytes));
2337
+ }
2338
+ if (url.pathname === "/v1/runtime/capabilities") {
2339
+ const stamp = capabilitiesForKernelHash(kernelSha);
2340
+ return sendJson(res, {
2341
+ ok: true,
2342
+ prod: stamp,
2343
+ // the dev cloud serves ONE kernel; it is what holon.wasm returns
2344
+ testmint: kernelKind === "test-mint" ? stamp : null,
2345
+ kernelKind,
2346
+ expectedBundleVersion: 1,
2347
+ vocabulary: KERNEL_CAPABILITY_REGISTRY.flatMap((e) => e.features).filter((f, i, a) => a.indexOf(f) === i).sort()
2348
+ });
2349
+ }
2350
+ if (url.pathname === "/v1/runtime/packages") {
2351
+ return sendJson(res, { bootstrap: bootstrapPkg, nomos: nomosPkg });
2352
+ }
2353
+ {
2354
+ const m = url.pathname.match(/^\/v2\/stage\/([0-9a-f]{64})$/);
2355
+ if (m) {
2356
+ const sha = m[1];
2357
+ if (req.method === "PUT" || req.method === "POST") {
2358
+ const bytes = new Uint8Array(await readBody(req));
2359
+ const r = await stagePut(stageBucket, sha, bytes);
2360
+ return sendJson(res, r.body, r.status);
2361
+ }
2362
+ if (req.method === "GET" || req.method === "HEAD") {
2363
+ const head = await stageBucket.head(`staged-intents/${sha}`);
2364
+ if (!head) return sendJson(res, { ok: false, staged: false, sha256: sha }, 404);
2365
+ return sendJson(res, { ok: true, staged: true, sha256: sha, size: head.size }, 200);
2366
+ }
2367
+ }
2368
+ }
2369
+ if (seg[0] === "git" && seg[1] === "nomos") {
2370
+ return await gitBackend(req, res, seg.slice(2).join("/"), null);
2371
+ }
2372
+ if (seg[0] === "repositories" && seg[1]) {
2373
+ const name = decodeURIComponent(seg[1]);
2374
+ if (req.method === "PUT") {
2375
+ const r2 = custody.create(name);
2376
+ return sendJson(res, { ok: true, name, remote: r2.remote }, 201);
2377
+ }
2378
+ if (req.method === "DELETE") {
2379
+ custody.delete(name);
2380
+ return sendJson(res, { ok: true, name, deleted: true });
2381
+ }
2382
+ const r = custody.get(name);
2383
+ return r ? sendJson(res, { ok: true, name, remote: r.remote }) : sendJson(res, { ok: false, error: "no such repository" }, 404);
2384
+ }
2385
+ if (seg[0] === "v2" && seg[1] === "workspaces" && seg[2]) {
2386
+ const ws = decodeURIComponent(seg[2]);
2387
+ const sub = seg.slice(3);
2388
+ if (sub[0] === "git") {
2389
+ return await gitBackend(req, res, `holon-${ws}.git/${sub.slice(1).join("/")}`, ws);
2390
+ }
2391
+ if (sub.length === 0 && req.method === "POST") {
2392
+ return await serialize(async () => {
2393
+ if (!custody.get(`holon-${ws}`)) {
2394
+ sendJson(res, { ok: false, ws, error: `workspace '${ws}' is unborn \u2014 the host does not create workspaces; author its birth on its PARENT (birthChild/birthHome).` }, 409);
2395
+ return;
2396
+ }
2397
+ const ledger = ledgerFor(ws);
2398
+ const out = await boot(eng, ws, ledger);
2399
+ sendJson(res, { ok: true, ws, tier: "heavy", status: out.status, ledger: ledger.remote, head: out.head, controller: { domainHash: out.controllerHash, rows: out.rows } }, out.status === "already-initialized" ? 200 : 201);
2400
+ });
2401
+ }
2402
+ if (sub.length === 0 && req.method === "GET") {
2403
+ return await serialize(async () => {
2404
+ const ledger = ledgerFor(ws);
2405
+ let initialized = false, ledgerState = null;
2406
+ if (custody.get(`holon-${ws}`)) {
2407
+ await mountWorkspace(eng, ws, ledger);
2408
+ try {
2409
+ initialized = nomosActive(eng, ws);
2410
+ } catch {
2411
+ }
2412
+ ledgerState = await ledgerStats(eng, ws, ledger).catch(() => null);
2413
+ }
2414
+ sendJson(res, { ok: true, ws, tier: "heavy", initialized, ledger: ledger.remote, ledgerState, kernelSha });
2415
+ });
2416
+ }
2417
+ if (sub[0] === "domains" && sub.length === 1) {
2418
+ if (req.method === "GET") {
2419
+ return await serialize(async () => {
2420
+ await mountWorkspace(eng, ws, ledgerFor(ws));
2421
+ sendJson(res, { ok: true, ws, ...installedLaw(eng, ws) });
2422
+ });
2423
+ }
2424
+ if (req.method === "POST") {
2425
+ const raw = await readBody(req);
2426
+ return await serialize(async () => {
2427
+ const ledger = ledgerFor(ws);
2428
+ await mountWorkspace(eng, ws, ledger);
2429
+ if (!nomosActive(eng, ws)) return sendJson(res, { ok: false, error: `workspace '${ws}' is not initialized \u2014 POST /v2/workspaces/${ws} first` }, 409);
2430
+ let usda, dispositions = null;
2431
+ const text = raw.toString("utf8");
2432
+ if (text.trimStart().startsWith("#usda")) {
2433
+ usda = text;
2434
+ } else {
2435
+ const body = JSON.parse(text || "{}");
2436
+ usda = body.packageUsda || body.usda;
2437
+ dispositions = body.dispositions || null;
2438
+ }
2439
+ if (!usda) return sendJson(res, { ok: false, error: "deploy body must be raw #usda or JSON with packageUsda" }, 400);
2440
+ const domainHash = await sha256hex(usda);
2441
+ const dryRun = url.searchParams.get("dryRun");
2442
+ if (dryRun === "evolve") {
2443
+ const verdict = evolveDryRun(eng, ws, usda, domainHash, dispositions);
2444
+ return sendJson(res, { ok: true, dryRun: "evolve", verdict });
2445
+ }
2446
+ if (dryRun) return sendJson(res, { ok: true, dryRun: true, wouldInstall: domainHash, bytes: usda.length });
2447
+ const actor = principalOf(req);
2448
+ const authToken = authTokenOf(req);
2449
+ try {
2450
+ const out = await deploy(eng, ws, ledger, usda, domainHash, dispositions, { actor, ...authToken ? { authToken } : {} });
2451
+ sendJson(res, { ok: true, ws, domainHash, head: out.head, installation: out.installation }, 201);
2452
+ } catch (e) {
2453
+ const msg = errMsg(e);
2454
+ const status = /deploy-did-not-advance/.test(msg) ? 409 : 422;
2455
+ sendJson(res, { ok: false, refused: true, error: msg.slice(0, 600) }, status);
2456
+ }
2457
+ });
2458
+ }
2459
+ }
2460
+ if (sub[0] === "domains" && sub.length === 3 && sub[2] === "package.usda") {
2461
+ return await serialize(async () => {
2462
+ await mountWorkspace(eng, ws, ledgerFor(ws));
2463
+ const pkg = domainPackage(eng, ws, sub[1]);
2464
+ if (!pkg || !pkg.usda) return sendJson(res, { ok: false, error: "no such package" }, 404);
2465
+ res.writeHead(200, { "content-type": "text/plain", ...CORS });
2466
+ res.end(pkg.usda);
2467
+ });
2468
+ }
2469
+ if (sub[0] === "openapi.json" && req.method === "GET") {
2470
+ return await serialize(async () => {
2471
+ await mountWorkspace(eng, ws, ledgerFor(ws));
2472
+ sendJson(res, openapiFor(ws));
2473
+ });
2474
+ }
2475
+ if (sub[0] === "admit" && req.method === "POST") {
2476
+ return await serialize(async () => {
2477
+ const ledger = ledgerFor(ws);
2478
+ await mountWorkspace(eng, ws, ledger);
2479
+ const out = await admitAll(eng, ws, ledger, {});
2480
+ if (Array.isArray(out.born) && out.born.length) await persistBorn(packBornChildren(eng, out.born));
2481
+ sendJson(res, { ok: true, ws, sessions: out.sessions, main: out.main, ...out.timings ? { timings: out.timings } : {} });
2482
+ });
2483
+ }
2484
+ if (sub[0] === "intent-offers" && req.method === "POST") {
2485
+ return await serialize(async () => {
2486
+ const ledger = ledgerFor(ws);
2487
+ await mountWorkspace(eng, ws, ledger);
2488
+ const body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
2489
+ const offers = Array.isArray(body.offers) ? body.offers.slice(0, 100) : [];
2490
+ if (!offers.length) return sendJson(res, { ok: false, error: "body must be { offers:[{session, oid, intentB64}] }" }, 400);
2491
+ const clientBase = /^[0-9a-f]{40}$/i.test(body.base || "") ? body.base : null;
2492
+ const out = await admitIntentOffers(eng, ws, ledger, offers, { ...clientBase ? { clientBase } : {} });
2493
+ if (Array.isArray(out.born) && out.born.length) await persistBorn(out.born);
2494
+ const bornOut = Array.isArray(out.born) ? out.born.map(({ packB64, packBytes, ...b }) => b) : null;
2495
+ sendJson(res, {
2496
+ ok: true,
2497
+ ws,
2498
+ sessions: out.sessions,
2499
+ main: out.main,
2500
+ ...bornOut ? { born: bornOut } : {},
2501
+ ...out.birthOutcomes ? { birthOutcomes: out.birthOutcomes } : {},
2502
+ ...out.mainDelta ? { mainDelta: out.mainDelta } : {},
2503
+ ...out.resultPackB64 ? { resultPackB64: out.resultPackB64, resultBase: out.resultBase } : {},
2504
+ ...out.deadLetters && out.deadLetters.length ? { deadLetters: out.deadLetters.map(({ blob, ...m }) => m) } : {}
2505
+ });
2506
+ });
2507
+ }
2508
+ if (sub[0] === "dead-letters" && sub.length === 1 && req.method === "GET") {
2509
+ return await serialize(async () => {
2510
+ await mountWorkspace(eng, ws, ledgerFor(ws));
2511
+ sendJson(res, { ok: true, ws, deadLetters: await listRefusedRefs(eng, ws) });
2512
+ });
2513
+ }
2514
+ if (sub[0] === "dlq-summary" && req.method === "GET") {
2515
+ return await serialize(async () => {
2516
+ await mountWorkspace(eng, ws, ledgerFor(ws));
2517
+ sendJson(res, { ok: true, ws, ...await refusedSummary(eng, ws) });
2518
+ });
2519
+ }
2520
+ if (sub[0] === "dead-letters" && sub[1] === "retry" && req.method === "POST") {
2521
+ return await serialize(async () => {
2522
+ const ledger = ledgerFor(ws);
2523
+ await mountWorkspace(eng, ws, ledger);
2524
+ const body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
2525
+ const only = body.id || null;
2526
+ const refs = await listRefusedRefs(eng, ws);
2527
+ const retried = [], failed = [];
2528
+ for (const e of refs) {
2529
+ if (only && e.offerId !== only && e.oid !== only) continue;
2530
+ if (!e.intentB64) {
2531
+ failed.push({ intentId: e.offerId, error: "refused ref carries no intent bytes" });
2532
+ continue;
2533
+ }
2534
+ try {
2535
+ const r2 = offerAdmit(eng, ws, unb64(e.intentB64), {});
2536
+ if (r2.ok) retried.push({ intentId: e.offerId, head: r2.head });
2537
+ else failed.push({ intentId: e.offerId, error: String(r2.error || "").slice(0, 300) });
2538
+ } catch (err) {
2539
+ failed.push({ intentId: e.offerId, error: String(err).slice(0, 300) });
2540
+ }
2541
+ }
2542
+ if (retried.length) await commitAndPush(eng, ws, ledger);
2543
+ for (const r2 of retried) await deleteRefusedRef(eng, ws, ledger, r2.intentId);
2544
+ sendJson(res, { ok: true, ws, retried, failed, remaining: (await listRefusedRefs(eng, ws)).length });
2545
+ });
2546
+ }
2547
+ if (sub[0] === "dead-letters" && (sub[1] === "discard" || req.method === "DELETE")) {
2548
+ return await serialize(async () => {
2549
+ const ledger = ledgerFor(ws);
2550
+ await mountWorkspace(eng, ws, ledger);
2551
+ const body = req.method === "DELETE" ? {} : JSON.parse((await readBody(req)).toString("utf8") || "{}");
2552
+ const only = body.id || url.searchParams.get("id") || null;
2553
+ const targets = (await listRefusedRefs(eng, ws)).filter((e) => !only || e.offerId === only || e.oid === only);
2554
+ for (const e of targets) await deleteRefusedRef(eng, ws, ledger, e.offerId || e.oid);
2555
+ sendJson(res, { ok: true, ws, discarded: targets.length });
2556
+ });
2557
+ }
2558
+ if (sub[0] === "rotate-secret" && req.method === "POST") {
2559
+ return sendJson(res, { ok: false, retired: true, error: "rotate-secret is retired \u2014 ownership is a ledger fact (sha256 of the push password on the law record); re-own by re-birthing the workspace via its parent" }, 410);
2560
+ }
2561
+ if (sub[0] === "pack" && req.method === "GET") {
2562
+ return await serialize(async () => {
2563
+ await mountWorkspace(eng, ws, ledgerFor(ws));
2564
+ if (postureGate(res, ws, req, "pack")) return;
2565
+ const have = url.searchParams.get("have") || "";
2566
+ let r;
2567
+ try {
2568
+ r = servePack(eng, ws, have);
2569
+ } catch (e) {
2570
+ return sendJson(res, { ok: false, custodyBreak: true, error: errMsg(e).slice(0, 400), have }, 409);
2571
+ }
2572
+ if (!r.packB64) return sendBytes(res, Buffer.alloc(0), 204, r.head ? { "x-nomos-head": r.head } : {});
2573
+ const kind = r.divergent ? "full" : have ? "delta" : "full";
2574
+ sendBytes(res, unb64(r.packB64), 200, {
2575
+ "content-type": "application/x-git-packfile",
2576
+ "x-nomos-pack": kind,
2577
+ ...r.divergent ? { "x-nomos-divergent": "1" } : {},
2578
+ ...r.head ? { "x-nomos-head": r.head } : {}
2579
+ });
2580
+ });
2581
+ }
2582
+ if (sub[0] === "snapshot" && req.method === "GET") {
2583
+ return await serialize(async () => {
2584
+ await mountWorkspace(eng, ws, ledgerFor(ws));
2585
+ if (postureGate(res, ws, req, "snapshot")) return;
2586
+ const bytes = snapshot(eng, ws);
2587
+ sendBytes(res, bytes, 200, { "content-type": "application/octet-stream", "x-nomos-layout": "flat-manifest-v1" });
2588
+ });
2589
+ }
2590
+ if (sub[0] === "aggregates" && sub[1] || sub[0] === "qbyid" && req.method === "GET") {
2591
+ const id = sub[0] === "aggregates" ? decodeURIComponent(sub.slice(1).join("/")) : url.searchParams.get("id");
2592
+ return await serialize(async () => {
2593
+ await mountWorkspace(eng, ws, ledgerFor(ws));
2594
+ const rows = qById(eng, ws, id, principalOf(req));
2595
+ sendJson(res, { ok: true, ws, rows });
2596
+ });
2597
+ }
2598
+ if (sub[0] === "subscribe") {
2599
+ return sendJson(res, { ok: false, error: "subscribe requires a WebSocket upgrade" }, 426);
2600
+ }
2601
+ if ((sub.length === 1 || sub.length === 2) && (req.method === "POST" || req.method === "GET")) {
2602
+ const opName = sub.join("/");
2603
+ const method = req.method.toLowerCase();
2604
+ return await serialize(async () => {
2605
+ const ledger = ledgerFor(ws);
2606
+ await mountWorkspace(eng, ws, ledger);
2607
+ const spec = openapiFor(ws);
2608
+ const resolved = resolveGatewayOperation(spec, opName, method);
2609
+ if (resolved.ambiguous) return sendJson(res, { ok: false, error: "ambiguous operation", candidates: resolved.ambiguous }, 409);
2610
+ const x = resolved.op && resolved.op["x-nomos"];
2611
+ if (!x) {
2612
+ if (RECOGNIZED_UNSUPPORTED.has(opName)) {
2613
+ return sendJson(res, {
2614
+ ok: false,
2615
+ unsupported: true,
2616
+ route: opName,
2617
+ error: `'${opName}' is a recognized Nomos Cloud route that 'githolon cloud dev' (single-node local) does not serve \u2014 ${UNSUPPORTED_WHY[opName] || "a multi-node / Cloudflare-infra concern"}. This is NOT an app bug; if you need it locally, ask the Nomos devs.`
2618
+ }, 501);
2619
+ }
2620
+ return sendJson(res, { ok: false, error: "unknown operation", see: `GET /v2/workspaces/${ws}` }, 404);
2621
+ }
2622
+ const principal = principalOf(req);
2623
+ const authToken = authTokenOf(req);
2624
+ if (x.kind === "offer" && method === "post") {
2625
+ const body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
2626
+ if (body.intentRef && typeof body.intentRef === "object") {
2627
+ const resolved2 = await resolveStagedIntent(stageBucket, body.intentRef);
2628
+ if (!resolved2.ok) return sendJson(res, { ok: false, refused: true, error: resolved2.error }, resolved2.status);
2629
+ body.intentBytes = resolved2.intentB64;
2630
+ }
2631
+ try {
2632
+ let out;
2633
+ if (typeof body.intentBytes === "string" && body.intentBytes) {
2634
+ out = offerAdmit(eng, ws, unb64(body.intentBytes), {});
2635
+ if (out.ok) await commitAndPush(eng, ws, ledger);
2636
+ } else {
2637
+ const { actor, authorSecret, attestations, ...payload } = body;
2638
+ const effectiveActor = actor || principal || "";
2639
+ const lawHash = (currentLaw(eng, ws) || {})[x.domain] || "";
2640
+ out = await authorOn(eng, ws, ledger, x.domain, x.directiveId, payload, lawHash, {
2641
+ actor: effectiveActor,
2642
+ ...effectiveActor ? { principalVerified: true } : {},
2643
+ ...authToken ? { authToken } : {},
2644
+ ...authorSecret ? { authorSecret } : {},
2645
+ ...Array.isArray(attestations) ? { attestations } : {}
2646
+ });
2647
+ }
2648
+ if (!out.ok) return sendJson(res, { ok: false, refused: true, error: String(out.error).slice(0, 600) }, 422);
2649
+ const born = out.born ? await persistBorn(out.born) : void 0;
2650
+ sendJson(res, { ok: true, ws, head: out.head, ...born ? { born } : {}, ...out.birthOutcomes ? { birthOutcomes: out.birthOutcomes } : {} });
2651
+ } catch (e) {
2652
+ sendJson(res, { ok: false, refused: true, error: errMsg(e).slice(0, 600) }, 422);
2653
+ }
2654
+ return;
2655
+ }
2656
+ if (method === "get") {
2657
+ const group = url.searchParams.get("group") || "";
2658
+ try {
2659
+ if (x.kind === "query") {
2660
+ const params = {};
2661
+ for (const k of x.key || []) {
2662
+ const v = url.searchParams.get(k);
2663
+ if (v != null) params[k] = v;
2664
+ }
2665
+ const rows = query(eng, ws, x.queryId, JSON.stringify(params), principal);
2666
+ return sendJson(res, { ok: true, ws, rows });
2667
+ }
2668
+ if (x.kind === "count") return sendJson(res, { ok: true, ws, ...count(eng, ws, x.countId, group, principal) });
2669
+ if (x.kind === "sum") return sendJson(res, { ok: true, ws, ...sum(eng, ws, x.sumId, group, principal) });
2670
+ if (x.kind === "extremum") return sendJson(res, { ok: true, ws, ...extremum(eng, ws, x.extremumId, x.extremumKind || url.searchParams.get("kind") || "", group, principal) });
2671
+ if (x.kind === "spatial") return sendJson(res, { ok: true, ws, ...spatialWithin(eng, ws, x.spatialId, url.searchParams.get("bbox") || {}, principal) });
2672
+ if (x.kind === "pendingConflicts") return sendJson(res, { ok: true, ws, rows: pendingConflicts(eng, ws, principal) });
2673
+ } catch (e) {
2674
+ return sendJson(res, { ok: false, error: errMsg(e).slice(0, 600) }, 403);
2675
+ }
2676
+ }
2677
+ sendJson(res, { ok: false, error: "unroutable operation" }, 404);
2678
+ });
2679
+ }
2680
+ }
2681
+ sendJson(res, { ok: false, error: "not found", path: url.pathname }, 404);
2682
+ } catch (e) {
2683
+ sendJson(res, { ok: false, error: errMsg(e).slice(0, 600) }, 500);
2684
+ }
2685
+ });
2686
+ async function gitBackend(req, res, repoPathInfo, ws) {
2687
+ const body = await readBody(req);
2688
+ let sessionPush = false;
2689
+ if (ws && req.method === "POST" && /git-receive-pack/.test(repoPathInfo)) {
2690
+ try {
2691
+ const cmds = receivePackCommands(body);
2692
+ if (cmds.some((c) => c.ref === "refs/heads/main")) {
2693
+ res.writeHead(403, { "content-type": "text/plain", ...CORS });
2694
+ res.end("refs/heads/main is not writable \u2014 there is no push-to-create; a workspace is born by its PARENT (birthHome/birthChild/your .births() directive) and synced. Push work to refs/heads/session/<client-id>.");
2695
+ return;
2696
+ }
2697
+ sessionPush = cmds.some((c) => c.ref.startsWith("refs/heads/session/"));
2698
+ } catch {
2699
+ }
2700
+ }
2701
+ const out = await runGitHttpBackend(custody.root, {
2702
+ method: req.method ?? "",
2703
+ pathInfo: "/" + repoPathInfo,
2704
+ query: new URL(req.url ?? "", origin).search.replace(/^\?/, ""),
2705
+ contentType: req.headers["content-type"],
2706
+ body
2707
+ });
2708
+ res.writeHead(out.status, { ...out.headers, ...CORS });
2709
+ res.end(out.body);
2710
+ if (sessionPush && ws) scheduleAdmit(ws);
2711
+ }
2712
+ const admitTimers = /* @__PURE__ */ new Map();
2713
+ function scheduleAdmit(ws) {
2714
+ const existing = admitTimers.get(ws);
2715
+ if (existing) clearTimeout(existing);
2716
+ admitTimers.set(ws, setTimeout(() => {
2717
+ admitTimers.delete(ws);
2718
+ serialize(async () => {
2719
+ try {
2720
+ const ledger = ledgerFor(ws);
2721
+ await mountWorkspace(eng, ws, ledger);
2722
+ const out = await admitAll(eng, ws, ledger, {});
2723
+ if (Array.isArray(out.born) && out.born.length) await persistBorn(packBornChildren(eng, out.born));
2724
+ } catch (e) {
2725
+ console.error(`[dev-cloud] admit ${ws} failed:`, errMsg(e));
2726
+ }
2727
+ });
2728
+ }, 350));
2729
+ }
2730
+ server.on("upgrade", (req, socket) => {
2731
+ const key = req.headers["sec-websocket-key"];
2732
+ if (!key) return socket.destroy();
2733
+ const accept = createHash2("sha1").update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64");
2734
+ socket.write(
2735
+ `HTTP/1.1 101 Switching Protocols\r
2736
+ Upgrade: websocket\r
2737
+ Connection: Upgrade\r
2738
+ Sec-WebSocket-Accept: ${accept}\r
2739
+ \r
2740
+ `
2741
+ );
2742
+ socket.on("data", () => {
2743
+ });
2744
+ socket.on("error", () => {
2745
+ });
2746
+ });
2747
+ if (!globalThis.__nomosDevGuards) {
2748
+ globalThis.__nomosDevGuards = true;
2749
+ process.on("unhandledRejection", (e) => {
2750
+ console.error("[dev-cloud] unhandledRejection (kept alive):", errStack(e).slice(0, 500));
2751
+ });
2752
+ process.on("uncaughtException", (e) => {
2753
+ console.error("[dev-cloud] uncaughtException (kept alive):", errStack(e).slice(0, 500));
2754
+ });
2755
+ }
2756
+ await new Promise((resolve) => server.listen(port, host, () => resolve()));
2757
+ devSelf = {
2758
+ server,
2759
+ origin,
2760
+ dataDir,
2761
+ kernelSha,
2762
+ eng,
2763
+ custody,
2764
+ ledgerFor,
2765
+ serialize,
2766
+ persistBorn,
2767
+ // `--platform` requested ⇒ NOT ready until the boot-time ceremony completes (main flips it true).
2768
+ ...opts.platform ? { platformReady: false } : {},
2769
+ close: () => new Promise((resolve) => server.close(() => resolve()))
2770
+ };
2771
+ return devSelf;
2772
+ }
2773
+ function parseArgs(argv) {
2774
+ const o = {};
2775
+ for (let i = 0; i < argv.length; i++) {
2776
+ const a = argv[i];
2777
+ if (a === "--ephemeral") o.ephemeral = true;
2778
+ else if (a === "--port") o.port = parseInt(argv[++i], 10);
2779
+ else if (a === "--data") o.data = argv[++i];
2780
+ else if (a === "--firebase-project") o.firebaseProject = argv[++i];
2781
+ else if (a === "--platform") o.platform = argv[++i];
2782
+ else if (a === "--deploy") o.deploy = argv[++i];
2783
+ else if (a === "--auth-provider") o.authProvider = argv[++i];
2784
+ else if (a === "--bootstrap") o.bootstrap = true;
2785
+ else if (a === "--attested") o.attested = true;
2786
+ else if (a === "--kernel-source") o.kernelSource = argv[++i];
2787
+ }
2788
+ return o;
2789
+ }
2790
+ if (import.meta.url === `file://${process.argv[1]}`) {
2791
+ const opts = parseArgs(process.argv.slice(2));
2792
+ const dev = await startDevCloud(opts);
2793
+ console.log(`[dev-cloud] Nomos dev cloud listening on ${dev.origin}`);
2794
+ console.log(`[dev-cloud] data dir : ${dev.dataDir}`);
2795
+ console.log(`[dev-cloud] kernel : ${dev.kernelSha.slice(0, 16)}\u2026`);
2796
+ {
2797
+ const stamp = capabilitiesForKernelHash(dev.kernelSha);
2798
+ if (stamp.known) {
2799
+ console.log(`[dev-cloud] caps : ${stamp.version} \u2014 [${stamp.features.join(", ")}]`);
2800
+ if (/STALE/.test(stamp.note || "")) {
2801
+ console.log(`[dev-cloud] \u26A0 STALE KERNEL: ${stamp.note}. Law using compound-key queries will be REFUSED here.`);
2802
+ console.log(`[dev-cloud] Update the dev kernel (holon-testmint.wasm) to a build coherent with your compiler/release.`);
2803
+ }
2804
+ } else {
2805
+ console.log(`[dev-cloud] \u26A0 caps : kernel ${dev.kernelSha.slice(0, 8)} is UNKNOWN to the capability registry \u2014 coherence cannot be verified.`);
2806
+ }
2807
+ console.log(`[dev-cloud] coherence: GET ${dev.origin}/v1/runtime/capabilities`);
2808
+ }
2809
+ console.log(`[dev-cloud] point your Flutter app's cloud: base URL at ${dev.origin}`);
2810
+ if (opts.bootstrap || opts.platform) {
2811
+ const { bootstrapPlatform: bootstrapPlatform2 } = await Promise.resolve().then(() => (init_bootstrap(), bootstrap_exports));
2812
+ try {
2813
+ await bootstrapPlatform2(dev, opts);
2814
+ dev.platformReady = true;
2815
+ } catch (e) {
2816
+ console.error("[dev-cloud] bootstrap FAILED:", errMsg(e));
2817
+ await dev.close().catch(() => {
2818
+ });
2819
+ process.exit(1);
2820
+ }
2821
+ }
2822
+ process.on("SIGINT", async () => {
2823
+ await dev.close();
2824
+ process.exit(0);
2825
+ });
2826
+ }
2827
+ export {
2828
+ startDevCloud
2829
+ };