githolon 0.102.5 → 0.103.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -113,13 +113,14 @@ var init_git_fs = __esm({
113
113
 
114
114
  // ../adapter/tree.ts
115
115
  function flatten(dir, prefix, out) {
116
- for (const [name, inode] of dir.contents ?? /* @__PURE__ */ new Map()) {
117
- const path2 = prefix ? prefix + "/" + name : name;
116
+ const children = [...(dir.contents ?? /* @__PURE__ */ new Map()).entries()].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
117
+ for (const [name, inode] of children) {
118
+ const path3 = prefix ? prefix + "/" + name : name;
118
119
  if (inode.contents instanceof Map) {
119
- out.push({ path: path2, dir: true });
120
- flatten(inode, path2, out);
120
+ out.push({ path: path3, dir: true });
121
+ flatten(inode, path3, out);
121
122
  } else {
122
- out.push({ path: path2, dir: false, bytes: inode.data ?? new Uint8Array(0) });
123
+ out.push({ path: path3, dir: false, bytes: inode.data ?? new Uint8Array(0) });
123
124
  }
124
125
  }
125
126
  }
@@ -192,8 +193,8 @@ function readPktLines(buf, off = 0) {
192
193
  }
193
194
  return { lines, rest: off };
194
195
  }
195
- async function lsRefs(remote, headers = {}, { service = "git-upload-pack", prefix = null } = {}) {
196
- const r = await fetch(`${remote}/info/refs?service=${service}`, { headers });
196
+ async function lsRefs(remote, headers = {}, { service = "git-upload-pack", prefix = null } = {}, fetchImpl = fetch) {
197
+ const r = await fetchImpl(`${remote}/info/refs?service=${service}`, { headers });
197
198
  if (!r.ok) {
198
199
  if (r.status === 404) return {};
199
200
  throw new Error(`info/refs ${r.status}: ${(await r.text()).slice(0, 180)}`);
@@ -219,7 +220,7 @@ async function lsRefs(remote, headers = {}, { service = "git-upload-pack", prefi
219
220
  async function fetchPack(remote, headers = {}, { wants = [], haves = [] } = {}) {
220
221
  wants = wants.filter((w) => /^[0-9a-f]{40}$/.test(w) && w !== ZERO_OID);
221
222
  if (!wants.length) return null;
222
- const caps = "thin-pack ofs-delta agent=nomos-cloud";
223
+ const caps = "ofs-delta agent=nomos-cloud";
223
224
  const parts = [];
224
225
  wants.forEach((w, i) => parts.push(pkt(`want ${w}${i === 0 ? " " + caps : ""}
225
226
  `)));
@@ -256,7 +257,7 @@ async function fetchPack(remote, headers = {}, { wants = [], haves = [] } = {})
256
257
  }
257
258
  return pack;
258
259
  }
259
- async function pushPack(remote, headers = {}, { updates = [], pack = null } = {}) {
260
+ async function pushPack(remote, headers = {}, { updates = [], pack = null } = {}, fetchImpl = fetch) {
260
261
  if (!updates.length) return { ok: true, noop: true };
261
262
  const cmds = [];
262
263
  updates.forEach((u, i) => {
@@ -270,7 +271,7 @@ async function pushPack(remote, headers = {}, { updates = [], pack = null } = {}
270
271
  const body = concatBytes([...cmds, pack && pack.length ? pack : EMPTY_PACK]);
271
272
  let r;
272
273
  try {
273
- r = await fetch(`${remote}/git-receive-pack`, {
274
+ r = await fetchImpl(`${remote}/git-receive-pack`, {
274
275
  method: "POST",
275
276
  headers: { "content-type": "application/x-git-receive-pack-request", ...headers },
276
277
  body
@@ -340,8 +341,56 @@ var init_managed_promotion = __esm({
340
341
  }
341
342
  });
342
343
 
344
+ // ../adapter/proto/nomos/kernel/v1/kernel_pb.js
345
+ import { enumDesc, fileDesc, messageDesc, serviceDesc, tsEnum } from "@bufbuild/protobuf/codegenv2";
346
+ var file_nomos_kernel_v1_kernel, CallRequestSchema, CallResponseSchema, WorkspaceTargetSchema, DirectiveCallSchema, AuthoringOptionsSchema, CapturedClockSchema, OfferRequestSchema, QueryRequestSchema, QueryAuthoritySchema, InjectedKeySchema, RowsQuerySchema, ByIdQuerySchema, TallyQuerySchema, SpatialQuerySchema, NamedQuerySchema, TestRequestSchema, SetTestRootRequestSchema, CustodyRequestSchema, PackDeltaRequestSchema, ApplyPackRequestSchema, RepoStatsRequestSchema, IntentsAboveRequestSchema, InspectChangeRequestSchema, EncodeDocumentRequestSchema, InspectDocumentRequestSchema, ReadBlobRequestSchema, ResolveRefRequestSchema, ListRefsRequestSchema, WriteRefRequestSchema, DeleteRefRequestSchema, WriteMetaCommitRequestSchema, LawClosureInfoRequestSchema, RestoreMainRequestSchema, NomosValueSchema, NomosStructSchema, QueryOperationSchema, QueryOperation;
347
+ var init_kernel_pb = __esm({
348
+ "../adapter/proto/nomos/kernel/v1/kernel_pb.js"() {
349
+ "use strict";
350
+ file_nomos_kernel_v1_kernel = /* @__PURE__ */ fileDesc("Chxub21vcy9rZXJuZWwvdjEva2VybmVsLnByb3RvEg9ub21vcy5rZXJuZWwudjEimAMKC0NhbGxSZXF1ZXN0EhgKEHByb3RvY29sX3ZlcnNpb24YASABKA0SEgoKcmVxdWVzdF9pZBgCIAEoCRIsCgRvcGVuGAogASgLMhwubm9tb3Mua2VybmVsLnYxLk9wZW5SZXF1ZXN0SAASLgoFb2ZmZXIYCyABKAsyHS5ub21vcy5rZXJuZWwudjEuT2ZmZXJSZXF1ZXN0SAASLgoFcXVlcnkYDCABKAsyHS5ub21vcy5rZXJuZWwudjEuUXVlcnlSZXF1ZXN0SAASMAoGb3V0Ym94GA0gASgLMh4ubm9tb3Mua2VybmVsLnYxLk91dGJveFJlcXVlc3RIABIsCgRzeW5jGA4gASgLMhwubm9tb3Mua2VybmVsLnYxLlN5bmNSZXF1ZXN0SAASMgoHY3VzdG9keRgPIAEoCzIfLm5vbW9zLmtlcm5lbC52MS5DdXN0b2R5UmVxdWVzdEgAEiwKBHRlc3QYECABKAsyHC5ub21vcy5rZXJuZWwudjEuVGVzdFJlcXVlc3RIAEILCglvcGVyYXRpb24iywMKDENhbGxSZXNwb25zZRIYChBwcm90b2NvbF92ZXJzaW9uGAEgASgNEhIKCnJlcXVlc3RfaWQYAiABKAkSKwoHZmFpbHVyZRgKIAEoCzIYLm5vbW9zLmtlcm5lbC52MS5GYWlsdXJlSAASLQoEb3BlbhgLIAEoCzIdLm5vbW9zLmtlcm5lbC52MS5PcGVuUmVzcG9uc2VIABIvCgVvZmZlchgMIAEoCzIeLm5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MlkKEk5vbW9zS2VybmVsU2VydmljZRJDCgRDYWxsEhwubm9tb3Mua2VybmVsLnYxLkNhbGxSZXF1ZXN0Gh0ubm9tb3Mua2VybmVsLnYxLkNhbGxSZXNwb25zZWIGcHJvdG8z");
351
+ CallRequestSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 0);
352
+ CallResponseSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 1);
353
+ WorkspaceTargetSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 15);
354
+ DirectiveCallSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 17);
355
+ AuthoringOptionsSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 18);
356
+ CapturedClockSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 19);
357
+ OfferRequestSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 20);
358
+ QueryRequestSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 23);
359
+ QueryAuthoritySchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 24);
360
+ InjectedKeySchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 25);
361
+ RowsQuerySchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 26);
362
+ ByIdQuerySchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 28);
363
+ TallyQuerySchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 33);
364
+ SpatialQuerySchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 34);
365
+ NamedQuerySchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 35);
366
+ TestRequestSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 50);
367
+ SetTestRootRequestSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 51);
368
+ CustodyRequestSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 53);
369
+ PackDeltaRequestSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 54);
370
+ ApplyPackRequestSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 55);
371
+ RepoStatsRequestSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 56);
372
+ IntentsAboveRequestSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 57);
373
+ InspectChangeRequestSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 58);
374
+ EncodeDocumentRequestSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 59);
375
+ InspectDocumentRequestSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 60);
376
+ ReadBlobRequestSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 61);
377
+ ResolveRefRequestSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 62);
378
+ ListRefsRequestSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 63);
379
+ WriteRefRequestSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 64);
380
+ DeleteRefRequestSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 65);
381
+ WriteMetaCommitRequestSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 67);
382
+ LawClosureInfoRequestSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 68);
383
+ RestoreMainRequestSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 72);
384
+ NomosValueSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 93);
385
+ NomosStructSchema = /* @__PURE__ */ messageDesc(file_nomos_kernel_v1_kernel, 96);
386
+ QueryOperationSchema = /* @__PURE__ */ enumDesc(file_nomos_kernel_v1_kernel, 1);
387
+ QueryOperation = /* @__PURE__ */ tsEnum(QueryOperationSchema);
388
+ }
389
+ });
390
+
343
391
  // ../adapter/engine.ts
344
392
  import { WASI, File, Directory, OpenFile, ConsoleStdout, PreopenDirectory } from "@bjorn3/browser_wasi_shim";
393
+ import { create, fromBinary, toBinary } from "@bufbuild/protobuf";
345
394
  function b64Bytes(bytes) {
346
395
  let s = "";
347
396
  for (let i = 0; i < bytes.length; i += 32768) {
@@ -349,9 +398,6 @@ function b64Bytes(bytes) {
349
398
  }
350
399
  return btoa(s);
351
400
  }
352
- function b64Json(o) {
353
- return b64Bytes(enc3.encode(JSON.stringify(o)));
354
- }
355
401
  async function sha256hex(t) {
356
402
  const b = await crypto.subtle.digest("SHA-256", enc3.encode(t));
357
403
  return [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
@@ -367,61 +413,297 @@ function osEntropyBuffer(n) {
367
413
  }
368
414
  return out;
369
415
  }
370
- function stringifyBig(o) {
371
- return JSON.stringify(o, (_k, v) => typeof v === "bigint" ? `@@B:${v}@@` : v).replace(/"@@B:(\d+)@@"/g, "$1");
372
- }
373
- function call(ex, mode, fields, STDERR) {
374
- const req = enc3.encode(JSON.stringify({ mode, ...fields }));
375
- const reqPtr = ex.git_holon_alloc(req.length);
416
+ function callProto(ex, operation, STDERR) {
417
+ const requestId = `adapter-${++protoRequestSequence}`;
418
+ const request = create(CallRequestSchema, {
419
+ protocolVersion: PROTO_ABI_VERSION,
420
+ requestId,
421
+ operation
422
+ });
423
+ const bytes = toBinary(CallRequestSchema, request);
424
+ const requestPtr = ex.git_holon_alloc(bytes.length) >>> 0;
376
425
  try {
377
- new Uint8Array(ex.memory.buffer, reqPtr, req.length).set(req);
426
+ new Uint8Array(ex.memory.buffer, requestPtr, bytes.length).set(bytes);
378
427
  let packed;
379
428
  try {
380
- packed = ex.git_holon_call(reqPtr, req.length);
381
- } catch (e) {
429
+ packed = ex.git_holon_call_proto(requestPtr, bytes.length);
430
+ } catch (error) {
382
431
  const tail = STDERR.length ? ` | stderr: ${STDERR.slice(-8).join(" / ")}` : "";
383
- throw new Error(`${String(e?.stack || e)}${tail}`);
432
+ throw new Error(`${String(error?.stack || error)}${tail}`);
384
433
  }
385
434
  const { ptr, len } = unpack(packed);
386
435
  try {
387
- const e = JSON.parse(dec3.decode(new Uint8Array(ex.memory.buffer, ptr, len).slice()));
388
- if (!e.ok) throw new Error((e.error || "holon error") + (STDERR.length ? ` | ${STDERR.slice(-4).join(" / ")}` : ""));
389
- return e.result;
436
+ const responseBytes = new Uint8Array(ex.memory.buffer, ptr, len).slice();
437
+ const response = fromBinary(CallResponseSchema, responseBytes);
438
+ if (response.protocolVersion !== PROTO_ABI_VERSION) {
439
+ throw new Error(`kernel protobuf ABI ${response.protocolVersion}; expected ${PROTO_ABI_VERSION}`);
440
+ }
441
+ if (response.requestId !== requestId) {
442
+ throw new Error(`kernel protobuf response id ${response.requestId || "<empty>"}; expected ${requestId}`);
443
+ }
444
+ if (response.outcome.case === "failure") {
445
+ throw new Error(`${response.outcome.value.code}: ${response.outcome.value.message}`);
446
+ }
447
+ return response;
390
448
  } finally {
391
449
  ex.git_holon_dealloc(ptr, len);
392
450
  }
393
451
  } finally {
394
- ex.git_holon_dealloc(reqPtr, req.length);
452
+ ex.git_holon_dealloc(requestPtr, bytes.length);
395
453
  }
396
454
  }
397
- async function createEngine({ wasmModule, bootstrapPkg, nomosPkg, replica, installedBy = "nomos-cloud" }) {
398
- const hashes = { bootstrap: await sha256hex(bootstrapPkg), nomos: await sha256hex(nomosPkg) };
455
+ function protoValue(value) {
456
+ if (value === null || value === void 0) {
457
+ return create(NomosValueSchema, { kind: { case: "null", value: {} } });
458
+ }
459
+ if (typeof value === "boolean") {
460
+ return create(NomosValueSchema, { kind: { case: "boolean", value } });
461
+ }
462
+ if (typeof value === "bigint") {
463
+ return value < 0n ? create(NomosValueSchema, { kind: { case: "signedInteger", value } }) : create(NomosValueSchema, { kind: { case: "unsignedInteger", value } });
464
+ }
465
+ if (typeof value === "number") {
466
+ if (!Number.isFinite(value)) throw new Error("NomosValue numbers must be finite");
467
+ if (Number.isSafeInteger(value)) {
468
+ return value < 0 ? create(NomosValueSchema, { kind: { case: "signedInteger", value: BigInt(value) } }) : create(NomosValueSchema, { kind: { case: "unsignedInteger", value: BigInt(value) } });
469
+ }
470
+ return create(NomosValueSchema, { kind: { case: "floatingPoint", value } });
471
+ }
472
+ if (typeof value === "string") {
473
+ return create(NomosValueSchema, { kind: { case: "text", value } });
474
+ }
475
+ if (value instanceof Uint8Array) {
476
+ return create(NomosValueSchema, { kind: { case: "bytes", value } });
477
+ }
478
+ if (Array.isArray(value)) {
479
+ return create(NomosValueSchema, {
480
+ kind: { case: "list", value: { values: value.map(protoValue) } }
481
+ });
482
+ }
483
+ if (typeof value === "object") {
484
+ return create(NomosValueSchema, {
485
+ kind: { case: "object", value: protoStruct(value) }
486
+ });
487
+ }
488
+ throw new Error(`unsupported NomosValue type: ${typeof value}`);
489
+ }
490
+ function protoStruct(value) {
491
+ return create(NomosStructSchema, {
492
+ fields: Object.fromEntries(Object.entries(value).map(([key, field]) => [key, protoValue(field)]))
493
+ });
494
+ }
495
+ function jsValue(value) {
496
+ if (!value) return void 0;
497
+ switch (value.kind.case) {
498
+ case "null":
499
+ return null;
500
+ case "boolean":
501
+ case "floatingPoint":
502
+ case "text":
503
+ case "bytes":
504
+ return value.kind.value;
505
+ case "signedInteger":
506
+ case "unsignedInteger": {
507
+ const integer = value.kind.value;
508
+ return integer >= BigInt(Number.MIN_SAFE_INTEGER) && integer <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(integer) : integer;
509
+ }
510
+ case "list":
511
+ return value.kind.value.values.map(jsValue);
512
+ case "object":
513
+ return jsStruct(value.kind.value);
514
+ default:
515
+ return void 0;
516
+ }
517
+ }
518
+ function jsStruct(value) {
519
+ if (!value) return {};
520
+ return Object.fromEntries(Object.entries(value.fields).map(([key, field]) => [key, jsValue(field)]));
521
+ }
522
+ function unreachableOfferOutcome(value) {
523
+ throw new Error(`kernel returned an unsupported offer outcome: ${String(value)}`);
524
+ }
525
+ function offerResult(response) {
526
+ const outcome = response.outcome;
527
+ switch (outcome.case) {
528
+ case "admitted": {
529
+ const value = jsStruct(outcome.value.result);
530
+ return {
531
+ ok: true,
532
+ outcome: "admitted",
533
+ ...typeof value.head === "string" ? { head: value.head } : {},
534
+ ...value.intentOut !== void 0 ? { intentOut: value.intentOut } : {},
535
+ created: Array.isArray(value.created) ? value.created : [],
536
+ affected: Array.isArray(value.affected) ? value.affected : [],
537
+ born: Array.isArray(value.born) ? value.born : [],
538
+ birthOutcomes: Array.isArray(value.birthOutcomes) ? value.birthOutcomes : [],
539
+ ...value.kernelSpans !== void 0 ? { kernelSpans: value.kernelSpans } : {},
540
+ ...value.dryRun === true ? { dryRun: true } : {}
541
+ };
542
+ }
543
+ case "refused": {
544
+ const refusal = outcome.value.refusal;
545
+ if (!refusal) throw new Error("kernel returned an offer refusal without its typed refusal");
546
+ const diagnostics = jsStruct(outcome.value.diagnostics);
547
+ return {
548
+ ok: false,
549
+ outcome: "refused",
550
+ ...outcome.value.offerId !== void 0 ? { offerId: outcome.value.offerId } : {},
551
+ refusal: {
552
+ code: refusal.code,
553
+ message: refusal.message,
554
+ details: jsStruct(refusal.details)
555
+ },
556
+ error: refusal.message,
557
+ ...diagnostics.kernelSpans !== void 0 ? { kernelSpans: diagnostics.kernelSpans } : {}
558
+ };
559
+ }
560
+ case "deadLettered": {
561
+ const diagnostics = jsStruct(outcome.value.diagnostics);
562
+ return {
563
+ ok: false,
564
+ outcome: "deadLettered",
565
+ ...outcome.value.offerId !== void 0 ? { offerId: outcome.value.offerId } : {},
566
+ reason: outcome.value.reason,
567
+ error: outcome.value.reason,
568
+ ...diagnostics.kernelSpans !== void 0 ? { kernelSpans: diagnostics.kernelSpans } : {}
569
+ };
570
+ }
571
+ case "quarantined": {
572
+ const diagnostics = jsStruct(outcome.value.diagnostics);
573
+ return {
574
+ ok: false,
575
+ outcome: "quarantined",
576
+ ...outcome.value.offerId !== void 0 ? { offerId: outcome.value.offerId } : {},
577
+ authoredLawHash: outcome.value.authoredLawHash,
578
+ currentLawHash: outcome.value.currentLawHash,
579
+ reason: outcome.value.reason,
580
+ error: outcome.value.reason,
581
+ ...diagnostics.kernelSpans !== void 0 ? { kernelSpans: diagnostics.kernelSpans } : {}
582
+ };
583
+ }
584
+ case "blockedOnDependency": {
585
+ const diagnostics = jsStruct(outcome.value.diagnostics);
586
+ return {
587
+ ok: false,
588
+ outcome: "blockedOnDependency",
589
+ ...outcome.value.offerId !== void 0 ? { offerId: outcome.value.offerId } : {},
590
+ detail: outcome.value.detail,
591
+ error: outcome.value.detail,
592
+ ...diagnostics.kernelSpans !== void 0 ? { kernelSpans: diagnostics.kernelSpans } : {}
593
+ };
594
+ }
595
+ case void 0:
596
+ throw new Error("kernel returned an empty offer outcome");
597
+ default:
598
+ return unreachableOfferOutcome(outcome);
599
+ }
600
+ }
601
+ function applicationQueryProto(eng, ws, query2, options = {}) {
602
+ const response = callProto(eng.ex, {
603
+ case: "query",
604
+ value: create(QueryRequestSchema, {
605
+ target: protoTarget(ws, options.branch ?? BRANCH),
606
+ authority: protoAuthority(
607
+ options.principal,
608
+ options.keys,
609
+ options.authToken,
610
+ options.nowUnix,
611
+ options.authorSecret
612
+ ),
613
+ spans: options.spans ?? false,
614
+ query: query2
615
+ })
616
+ }, eng.STDERR);
617
+ if (response.outcome.case !== "query") {
618
+ throw new Error(`kernel returned ${response.outcome.case || "empty"} for application query`);
619
+ }
620
+ const result = response.outcome.value.result;
621
+ if (result.case === "applicationJson") {
622
+ return JSON.parse(dec3.decode(result.value.utf8));
623
+ }
624
+ if (result.case === "value") return jsValue(result.value);
625
+ throw new Error(`kernel returned ${result.case || "empty"} for application query`);
626
+ }
627
+ function namedQueryProto(eng, ws, operation, arguments_ = {}, options = {}) {
628
+ return applicationQueryProto(eng, ws, {
629
+ case: "named",
630
+ value: create(NamedQuerySchema, { operation, arguments: protoStruct(arguments_) })
631
+ }, options);
632
+ }
633
+ function custodyProto(eng, operation) {
634
+ return custodyProtoWith(eng.ex, operation, eng.STDERR);
635
+ }
636
+ function custodyProtoWith(ex, operation, STDERR) {
637
+ const response = callProto(ex, {
638
+ case: "custody",
639
+ value: create(CustodyRequestSchema, { operation })
640
+ }, STDERR);
641
+ if (response.outcome.case !== "custody" || !response.outcome.value.operation.case) {
642
+ throw new Error(`kernel returned ${response.outcome.case || "empty"} for custody request`);
643
+ }
644
+ return response.outcome.value.operation;
645
+ }
646
+ function custodyProtoCase(eng, operation, expected) {
647
+ const result = custodyProto(eng, operation);
648
+ if (result.case !== expected) {
649
+ throw new Error(`kernel returned custody.${result.case || "empty"}; expected custody.${expected}`);
650
+ }
651
+ return result.value;
652
+ }
653
+ async function createEngine({ wasmModule, bootstrapLawUsdz, nomosLawUsdz, replica, installedBy = "nomos-cloud" }) {
654
+ const assertUsdz = (name, bytes) => {
655
+ if (!(bytes instanceof Uint8Array) || bytes.length < 4 || bytes[0] !== 80 || bytes[1] !== 75 || bytes[2] !== 3 || bytes[3] !== 4) {
656
+ throw new Error(`${name} must be opaque USDZ bytes`);
657
+ }
658
+ };
659
+ assertUsdz("bootstrapLawUsdz", bootstrapLawUsdz);
660
+ assertUsdz("nomosLawUsdz", nomosLawUsdz);
399
661
  const root = /* @__PURE__ */ new Map();
400
- root.set("domain.package.usda", new File(enc3.encode(bootstrapPkg)));
662
+ root.set("bootstrap.law.usdz", new File(bootstrapLawUsdz));
663
+ root.set("nomos.law.usdz", new File(nomosLawUsdz));
401
664
  root.set("ws", new Directory(/* @__PURE__ */ new Map()));
402
665
  const preopen = new PreopenDirectory("/work", root);
403
666
  const STDERR = [];
667
+ const streamKernelStderr = globalThis.process?.env?.NOMOS_WASM_STDERR === "1";
404
668
  const pushStderr = (l) => {
405
669
  if (STDERR.length >= 500) STDERR.splice(0, STDERR.length - 499);
406
670
  STDERR.push(l);
671
+ if (streamKernelStderr) console.error(`[nomos-kernel-stderr] ${l}`);
407
672
  };
408
673
  const fds = [new OpenFile(new File([])), ConsoleStdout.lineBuffered(() => {
409
674
  }), ConsoleStdout.lineBuffered(pushStderr), preopen];
410
675
  const wasi = new WASI(["wasm_git_holon", "reactor"], [], fds, { debug: false });
411
- const inst = await WebAssembly.instantiate(wasmModule, { wasi_snapshot_preview1: wasi.wasiImport });
676
+ const wasiImports = unsignedWasiPointers(wasi.wasiImport);
677
+ const inst = await WebAssembly.instantiate(wasmModule, { wasi_snapshot_preview1: wasiImports });
412
678
  const code = wasi.start(inst);
413
679
  if (code !== 0) throw new Error(`reactor init exited ${code}; stderr=${STDERR.join("\n")}`);
414
680
  const instExports = inst.exports;
415
- for (const n of ["memory", "git_holon_alloc", "git_holon_dealloc", "git_holon_call"]) if (!instExports[n]) throw new Error(`missing export ${n}`);
681
+ for (const n of ["memory", "git_holon_alloc", "git_holon_dealloc", "git_holon_call_proto"]) if (!instExports[n]) throw new Error(`missing export ${n}`);
682
+ const ex = instExports;
683
+ const closureInfo = (closureFile) => {
684
+ const response = custodyProtoWith(ex, {
685
+ case: "lawClosureInfo",
686
+ value: create(LawClosureInfoRequestSchema, { closureFile })
687
+ }, STDERR);
688
+ if (response.case !== "lawClosureInfo") {
689
+ throw new Error(`kernel returned custody.${response.case || "empty"}; expected custody.lawClosureInfo`);
690
+ }
691
+ return response.value;
692
+ };
693
+ const bootstrapInfo = closureInfo("/work/bootstrap.law.usdz");
694
+ const nomosInfo = closureInfo("/work/nomos.law.usdz");
695
+ if (!bootstrapInfo.identity) throw new Error("bootstrap USDA closure refused: missing identity");
696
+ if (!nomosInfo.identity) throw new Error("Nomos USDA closure refused: missing identity");
697
+ const hashes = { bootstrap: bootstrapInfo.identity, nomos: nomosInfo.identity };
416
698
  const eng = {
417
- ex: instExports,
699
+ ex,
418
700
  preopen,
419
701
  STDERR,
420
702
  seq: 0,
421
703
  replica,
422
704
  hashes,
423
- bootstrapPkg,
424
- nomosPkg,
705
+ bootstrapLawUsdz,
706
+ nomosLawUsdz,
425
707
  installedBy,
426
708
  fs: makeGitFs(preopen, "/work", { File, Directory }),
427
709
  mounted: /* @__PURE__ */ new Map(),
@@ -491,14 +773,9 @@ function scopedReads(eng) {
491
773
  function globalAggregates(eng) {
492
774
  return /* @__PURE__ */ new Set();
493
775
  }
494
- function parseIntentEvents(blob) {
495
- let doc;
496
- try {
497
- doc = JSON.parse(dec3.decode(blob));
498
- } catch {
499
- return [];
500
- }
501
- const events = Array.isArray(doc && doc.events) ? doc.events : [];
776
+ function parseIntentEvents(doc) {
777
+ const rawEvents = doc?.events;
778
+ const events = Array.isArray(rawEvents) ? rawEvents : [];
502
779
  return events.map((ev) => {
503
780
  const sets = /* @__PURE__ */ new Map();
504
781
  for (const op of ev.ops || []) {
@@ -510,8 +787,8 @@ function parseIntentEvents(blob) {
510
787
  return { aggregate: String(ev.aggregate || ""), sets };
511
788
  });
512
789
  }
513
- function beginSummaryCapture(eng, ws, ctx, blob) {
514
- const events = parseIntentEvents(blob);
790
+ function beginSummaryCapture(eng, ws, ctx, doc) {
791
+ const events = parseIntentEvents(doc);
515
792
  if (events.length === 0) return null;
516
793
  const pre = /* @__PURE__ */ new Map();
517
794
  const candidates = /* @__PURE__ */ new Set();
@@ -646,17 +923,13 @@ async function admitIntentOffers(eng, ws, ledger, offers, { receiptFence = null,
646
923
  const done = span(`intent offer ${cid.slice(0, 14)}`, "cadmit", 1, { client: cid });
647
924
  let blob = offer?.blob instanceof Uint8Array ? offer.blob : null;
648
925
  try {
649
- if (!blob && typeof offer?.intentB64 === "string") blob = Uint8Array.from(atob(offer.intentB64), (c) => c.charCodeAt(0));
926
+ if (!blob && typeof offer?.changeB64 === "string") blob = Uint8Array.from(atob(offer.changeB64), (c) => c.charCodeAt(0));
650
927
  const maxOfferBytes = offer?.staged ? 64 * 1024 * 1024 : 32 * 1024 * 1024;
651
928
  if (!blob || blob.byteLength === 0 || blob.byteLength > maxOfferBytes) {
652
- rec.rejected.push({ oid: String(offer?.oid || "").slice(0, 10), error: `intent offer must carry intentB64 <= ${maxOfferBytes / (1024 * 1024)} MiB` });
929
+ rec.rejected.push({ oid: String(offer?.oid || "").slice(0, 10), error: `intent offer must carry changeB64 <= ${maxOfferBytes / (1024 * 1024)} MiB` });
653
930
  continue;
654
931
  }
655
- let doc = null;
656
- try {
657
- doc = JSON.parse(dec3.decode(blob));
658
- } catch {
659
- }
932
+ const doc = offer?.intent ?? kgit.inspectChange(eng, blob);
660
933
  const intentId = typeof doc?.id === "string" ? doc.id : null;
661
934
  const dom = typeof doc?.payload?.domain === "string" ? doc.payload.domain : null;
662
935
  const dirId = typeof doc?.payload?.directiveId === "string" ? doc.payload.directiveId : null;
@@ -675,7 +948,7 @@ async function admitIntentOffers(eng, ws, ledger, offers, { receiptFence = null,
675
948
  rec.skipped.push({ oid, intent: intentId.slice(0, 12), alreadyOnMain: true });
676
949
  continue;
677
950
  }
678
- const cap = summaryCtx ? beginSummaryCapture(eng, ws, summaryCtx, blob) : null;
951
+ const cap = summaryCtx ? beginSummaryCapture(eng, ws, summaryCtx, doc) : null;
679
952
  const _tOffer = Date.now();
680
953
  const res = offerAdmit(eng, ws, blob, { defer: false });
681
954
  log("offer-admit-ms", { ws, ms: Date.now() - _tOffer, deferred: false, ok: res.ok });
@@ -687,13 +960,30 @@ async function admitIntentOffers(eng, ws, ledger, offers, { receiptFence = null,
687
960
  admittedTotal += 1;
688
961
  if (Array.isArray(res.born) && res.born.length) born.push(...res.born);
689
962
  if (Array.isArray(res.birthOutcomes) && res.birthOutcomes.length) birthOutcomes.push(...res.birthOutcomes);
963
+ if (typeof process !== "undefined" && process.env?.NOMOS_TEST_DIAGNOSTICS === "1" && Array.isArray(res.birthOutcomes) && res.birthOutcomes.length) {
964
+ log("offer-birth-outcomes", { ws, outcomes: res.birthOutcomes });
965
+ }
690
966
  if (cap) finishSummaryCapture(eng, ws, summaryCtx, cap, res.head ?? "", intentId);
691
967
  } else {
968
+ if (typeof process !== "undefined" && process.env?.NOMOS_TEST_DIAGNOSTICS === "1") {
969
+ log("offer-admit-refused", {
970
+ ws,
971
+ domain: dom,
972
+ directiveId: dirId,
973
+ error: String(res.error || "").slice(0, 2e3)
974
+ });
975
+ }
692
976
  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`;
693
977
  rec.rejected.push({ oid, error, deadLettered: true });
694
978
  deadLetters.push({ intentId, oid, session: cid, error, blob, domain: dom, directiveId: dirId });
695
979
  }
696
980
  } catch (e) {
981
+ if (typeof process !== "undefined" && process.env?.NOMOS_TEST_DIAGNOSTICS === "1") {
982
+ log("offer-admit-threw", {
983
+ ws,
984
+ error: String(e).slice(0, 2e3)
985
+ });
986
+ }
697
987
  rec.rejected.push({ oid: String(offer?.oid || "").slice(0, 10), error: String(e).slice(0, 200) });
698
988
  } finally {
699
989
  done();
@@ -715,7 +1005,7 @@ async function admitIntentOffers(eng, ws, ledger, offers, { receiptFence = null,
715
1005
  }
716
1006
  const gitdir = gitdirOf(ws);
717
1007
  const head = kgit.resolveRef(eng, gitdir, BRANCH) ?? main.head;
718
- const summary = summaryCtx ? summaryOfCapture(summaryCtx, headBefore, head) : null;
1008
+ const summary = summaryCtx ? summaryOfCapture(summaryCtx, headBefore ?? "", head ?? "") : null;
719
1009
  let resultPackB64 = null;
720
1010
  if (admittedTotal && head && /^[0-9a-f]{40}$/i.test(clientBase || "") && clientBase !== head) {
721
1011
  try {
@@ -752,9 +1042,12 @@ async function mountWorkspace(eng, ws, ledger) {
752
1042
  let restored = false, remoteMain = null, restoreError = null;
753
1043
  try {
754
1044
  await custodySkeleton(eng, gitdir);
755
- remoteMain = await custodyFetch(eng, ws, ledger, { remoteRef: "refs/heads/main" });
1045
+ remoteMain = await custodyFetch(eng, ws, ledger, { remoteRef: "refs/heads/main", writeRef: false });
756
1046
  if (remoteMain) {
757
- kgit.writeRef(eng, gitdir, "HEAD", "ref: refs/heads/main");
1047
+ const mounted = kgit.restoreMain(eng, ws, remoteMain);
1048
+ if (!mounted.verified || mounted.head !== remoteMain) {
1049
+ throw new Error(`kernel refused restored main ${remoteMain}: ${JSON.stringify(mounted)}`);
1050
+ }
758
1051
  restored = true;
759
1052
  }
760
1053
  } catch (e) {
@@ -773,81 +1066,99 @@ function unmount(eng, ws) {
773
1066
  function writeWork(eng, name, bytes) {
774
1067
  eng.preopen.dir.contents.set(name, new File(bytes));
775
1068
  }
1069
+ function stageLawClosure(eng, lawUsdz, label = "candidate-law") {
1070
+ const name = `${label.replace(/[^A-Za-z0-9._-]/g, "_")}.law.usdz`;
1071
+ writeWork(eng, name, lawUsdz);
1072
+ return custodyProtoCase(eng, {
1073
+ case: "lawClosureInfo",
1074
+ value: create(LawClosureInfoRequestSchema, { closureFile: `/work/${name}` })
1075
+ }, "lawClosureInfo");
1076
+ }
776
1077
  function currentLaw(eng, ws) {
777
- const out = JSON.parse(call(eng.ex, "query", { repoArg: repoArgOf(ws), workspace: ws, queryBytes: b64Json({ op: "currentLaw" }), branch: BRANCH }, eng.STDERR));
1078
+ const out = namedQueryProto(eng, ws, QueryOperation.CURRENT_LAW);
778
1079
  return out.keyMap || {};
779
1080
  }
780
1081
  function installedLaw(eng, ws) {
781
- return JSON.parse(call(eng.ex, "query", { repoArg: repoArgOf(ws), workspace: ws, queryBytes: b64Json({ op: "installedLaw" }), branch: BRANCH }, eng.STDERR));
1082
+ return namedQueryProto(eng, ws, QueryOperation.INSTALLED_LAW);
782
1083
  }
783
1084
  function kernelStamp(eng, ws) {
784
- return JSON.parse(call(eng.ex, "query", {
785
- repoArg: repoArgOf(ws),
786
- workspace: ws,
787
- queryBytes: b64Json({ op: "kernelStamp" }),
788
- branch: BRANCH
789
- }, eng.STDERR));
790
- }
791
- function domainPackage(eng, ws, hash) {
792
- return JSON.parse(call(eng.ex, "query", { repoArg: repoArgOf(ws), workspace: ws, queryBytes: b64Json({ op: "domainPackage", hash }), branch: BRANCH }, eng.STDERR));
793
- }
794
- function evolveDryRun(eng, ws, usda, domainHash, dispositions = null) {
795
- const r = author(eng, ws, "nomos", "installDomain", installPayload(domainHash, usda, eng.installedBy, dispositions), eng.hashes.nomos, { dryRun: true, deferProjection: false });
796
- return r.ok ? { admits: true } : { admits: false, detail: r.error };
1085
+ return namedQueryProto(eng, ws, QueryOperation.KERNEL_STAMP);
797
1086
  }
798
1087
  function author(eng, ws, domain, directiveId, payload, controllerHash, opts = {}) {
799
1088
  const seq = eng.seq++;
800
1089
  const capPorts = { clock: { physical: Date.now(), logical: 0, replica: eng.replica }, rng: osEntropyBuffer(opts.rngDraws ?? 64) };
801
- if (opts.__nomosConflictSnapshots !== void 0 && opts.__nomosConflictSnapshots.length > 0) {
802
- capPorts.conflict_snapshots = opts.__nomosConflictSnapshots;
803
- }
804
- if (opts.validFromEpoch !== void 0) capPorts.valid_from_epoch = opts.validFromEpoch;
805
- if (opts.principalVerified !== void 0) {
806
- capPorts.principal = opts.actor ?? "";
807
- capPorts.principal_verified = !!opts.principalVerified;
808
- }
809
- const envelope = { payload: { domain, directiveId, payload }, captured_ports: capPorts, policy_version: 1, policy_domain: "Nomos", policy_gas: 0, policy_memory: 0 };
810
- if (opts.attestations !== void 0) envelope.attestations = opts.attestations;
811
- writeWork(eng, `payload-${seq}.json`, enc3.encode(JSON.stringify(payload)));
812
- writeWork(eng, `envelope-${seq}.json`, enc3.encode(stringifyBig(envelope)));
813
1090
  const genesis = !controllerHash;
814
- const attestorSecretFor = (from) => {
815
- const s = opts.attestorSecrets;
816
- if (!s) return null;
817
- if (typeof s === "string") return s;
818
- return typeof s[from] === "string" ? s[from] : null;
819
- };
820
- const defer = opts.deferProjection !== false;
821
- 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));
822
- let v = offerOnce();
823
- for (let pass = 0; pass < 8 && v.outcome === "refused"; pass++) {
824
- const need = parseAttestedReadNeed(v.verdict?.reason ?? v.error);
825
- if (!need || !eng.mounted.has(need.from)) break;
826
- const secret = attestorSecretFor(need.from);
827
- if (!secret) break;
828
- const served = attestedRead(eng, need.from, {
829
- queryId: need.queryId,
830
- paramsJson: JSON.stringify(need.args),
831
- attestorSecret: secret,
832
- nowMs: opts.attestNowMs ?? Date.now(),
833
- // K3 (§1.5.3): colocated custody is in-memory — always ask for the carried enrollment
834
- // proof; the kernel produces-or-omits under its own bounds (the adapter decides nothing).
835
- includeRosterProof: true
836
- });
837
- if (!served || served.ok !== true) break;
838
- envelope.attestations = [...envelope.attestations ?? [], { queryId: need.queryId, result: served.rows, attestation: served.attestation }];
839
- writeWork(eng, `envelope-${seq}.json`, enc3.encode(stringifyBig(envelope)));
840
- v = offerOnce();
1091
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
1092
+ throw new Error(`directive ${domain}/${directiveId} payload must be an object`);
841
1093
  }
842
- 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;
1094
+ const defer = opts.deferProjection !== false;
1095
+ const offerOnce = () => {
1096
+ const response = callProto(eng.ex, {
1097
+ case: "offer",
1098
+ value: create(OfferRequestSchema, {
1099
+ target: protoTarget(ws),
1100
+ intent: {
1101
+ case: "call",
1102
+ value: create(DirectiveCallSchema, {
1103
+ domain,
1104
+ directive: directiveId,
1105
+ payload: protoStruct(payload)
1106
+ })
1107
+ },
1108
+ authoring: create(AuthoringOptionsSchema, {
1109
+ actor: opts.actor ?? "",
1110
+ authToken: opts.authToken ? enc3.encode(opts.authToken) : new Uint8Array(),
1111
+ authorSecret: opts.authorSecret ? bytesFromB64(opts.authorSecret) : new Uint8Array(),
1112
+ validFromEpoch: opts.validFromEpoch === void 0 ? void 0 : BigInt(opts.validFromEpoch),
1113
+ rng: capPorts.rng,
1114
+ deferProjection: !opts.dryRun && defer,
1115
+ spans: opts.spans ?? false,
1116
+ dryRun: opts.dryRun ?? false,
1117
+ sequence: BigInt(seq),
1118
+ clock: create(CapturedClockSchema, {
1119
+ physicalMillis: BigInt(capPorts.clock.physical),
1120
+ logical: capPorts.clock.logical,
1121
+ replica: BigInt(capPorts.clock.replica)
1122
+ })
1123
+ }),
1124
+ lawUsdz: opts.lawUsdz ?? new Uint8Array(),
1125
+ executionLawUsdz: genesis && domain === "bootstrap" && directiveId === "installDomain" ? eng.bootstrapLawUsdz : new Uint8Array(),
1126
+ controllerLawHash: genesis ? "" : controllerHash,
1127
+ conflictSnapshots: (opts.__nomosConflictSnapshots ?? []).map((snapshot2) => ({
1128
+ aggregateType: snapshot2.aggregateType,
1129
+ aggregateId: snapshot2.aggregateId,
1130
+ field: snapshot2.field,
1131
+ targetSchema: snapshot2.targetSchema,
1132
+ token: snapshot2.token
1133
+ }))
1134
+ })
1135
+ }, eng.STDERR);
1136
+ if (response.outcome.case !== "offer") {
1137
+ throw new Error(`kernel returned ${response.outcome.case || "empty"} for offer request`);
1138
+ }
1139
+ return offerResult(response.outcome.value);
1140
+ };
1141
+ const res = offerOnce();
843
1142
  if (defer && res.ok) (eng.pendingProjection ??= /* @__PURE__ */ new Set()).add(ws);
844
1143
  return res;
845
1144
  }
846
1145
  function setTestKRoot(eng, kRootPublicB64) {
847
- return JSON.parse(call(eng.ex, "set_test_k_root", { kRootPublicB64 }, eng.STDERR));
1146
+ const response = callProto(eng.ex, {
1147
+ case: "test",
1148
+ value: create(TestRequestSchema, {
1149
+ operation: {
1150
+ case: "setRoot",
1151
+ value: create(SetTestRootRequestSchema, { publicKey: bytesFromB64(kRootPublicB64) })
1152
+ }
1153
+ })
1154
+ }, eng.STDERR);
1155
+ if (response.outcome.case !== "test") {
1156
+ throw new Error(`kernel returned ${response.outcome.case || "empty"} for test control`);
1157
+ }
1158
+ return { ok: true };
848
1159
  }
849
1160
  function refreshProjection(eng, ws) {
850
- return JSON.parse(call(eng.ex, "query", { repoArg: repoArgOf(ws), workspace: ws, queryBytes: b64Json({ op: "refresh" }), branch: BRANCH }, eng.STDERR));
1161
+ return namedQueryProto(eng, ws, QueryOperation.REFRESH, {}, { spans: true });
851
1162
  }
852
1163
  async function custodySkeleton(eng, gitdir) {
853
1164
  const p = eng.fs.promises;
@@ -868,16 +1179,16 @@ async function custodySkeleton(eng, gitdir) {
868
1179
  } catch {
869
1180
  }
870
1181
  }
871
- async function custodyFetch(eng, ws, ledger, { remoteRef = "refs/heads/main", localRef = null, have = null } = {}) {
1182
+ async function custodyFetch(eng, ws, ledger, { remoteRef = "refs/heads/main", localRef = null, have = null, writeRef = true } = {}) {
872
1183
  const remoteRefFull = fullRef(remoteRef);
873
1184
  const refs = await custodyLsRefs(ledger, remoteRefFull);
874
1185
  const tip = refs[remoteRefFull] || null;
875
1186
  if (!tip) return null;
876
1187
  if (tip !== have) {
877
1188
  const pk = await fetchPack(ledger.remote, ledger.headers || {}, { wants: [tip], haves: have ? [have] : [] });
878
- if (pk) applyPackInto(eng, ws, pk);
1189
+ if (pk) applyPackInto(eng, ws, pk, tip);
879
1190
  }
880
- kgit.writeRef(eng, gitdirOf(ws), fullRef(localRef || remoteRef), tip);
1191
+ if (writeRef) kgit.writeRef(eng, gitdirOf(ws), fullRef(localRef || remoteRef), tip);
881
1192
  return tip;
882
1193
  }
883
1194
  async function custodyPush(eng, ws, ledger, { localRef = null, remoteRef, del = false, pointer = false, newOid = null }) {
@@ -920,26 +1231,14 @@ async function commitAndPush(eng, ws, ledger) {
920
1231
  }
921
1232
  }
922
1233
  function describe(eng, ws) {
923
- return JSON.parse(call(eng.ex, "query", { repoArg: repoArgOf(ws), workspace: ws, queryBytes: b64Json({ op: "describe", workspace: ws }), branch: BRANCH }, eng.STDERR));
924
- }
925
- function parseAttestedReadNeed(error) {
926
- const m = /attested-read-unreachable: read\('([^']+)', \{from: '([^']+)'\}\) args=(.*?) has no injected attestation/.exec(String(error || ""));
927
- if (!m) return null;
928
- let blob = m[3];
929
- for (let i = 0; i < 4; i++) {
930
- try {
931
- return { queryId: m[1], from: m[2], args: JSON.parse(blob) };
932
- } catch {
933
- blob = blob.replace(/\\(["\\])/g, "$1");
934
- }
935
- }
936
- return null;
1234
+ return namedQueryProto(eng, ws, QueryOperation.DESCRIBE, { workspace: ws });
937
1235
  }
938
1236
  function packDelta(eng, ws, base, head) {
939
1237
  try {
940
- const r = JSON.parse(call(eng.ex, "pack_delta", { repoArg: repoArgOf(ws), base, head }, eng.STDERR));
941
- if (!r || r.ok !== true || typeof r.packB64 !== "string") return null;
942
- return Uint8Array.from(atob(r.packB64), (c) => c.charCodeAt(0));
1238
+ return custodyProtoCase(eng, {
1239
+ case: "packDelta",
1240
+ value: create(PackDeltaRequestSchema, { repo: repoArgOf(ws), base: base || void 0, head })
1241
+ }, "packDelta").pack;
943
1242
  } catch {
944
1243
  return null;
945
1244
  }
@@ -952,13 +1251,21 @@ function servePack(eng, ws, base = "") {
952
1251
  }
953
1252
  let r;
954
1253
  try {
955
- r = JSON.parse(call(eng.ex, "pack_delta", { repoArg: repoArgOf(ws), workspace: ws, base, branch: BRANCH }, eng.STDERR));
1254
+ const pack = custodyProtoCase(eng, {
1255
+ case: "packDelta",
1256
+ value: create(PackDeltaRequestSchema, { repo: repoArgOf(ws), base: base || void 0, branch: BRANCH })
1257
+ }, "packDelta").pack;
1258
+ r = { ok: true, packB64: b64Bytes(pack), bytes: pack.length };
956
1259
  } catch (e) {
957
1260
  const msg = String(e);
958
1261
  if (/nothing to pack|head == base/.test(msg)) return { packB64: "", bytes: 0, upToDate: true, ...head ? { head } : {} };
959
- if (base && /reached root|before base|not found|unknown|no (?:merge )?base|missing|invalid/i.test(msg)) {
1262
+ if (base && /reached root|before base|not an ancestor|request a full pack|not found|unknown|no (?:merge )?base|missing|invalid/i.test(msg)) {
960
1263
  try {
961
- const full = JSON.parse(call(eng.ex, "pack_delta", { repoArg: repoArgOf(ws), workspace: ws, base: "", branch: BRANCH }, eng.STDERR));
1264
+ const pack = custodyProtoCase(eng, {
1265
+ case: "packDelta",
1266
+ value: create(PackDeltaRequestSchema, { repo: repoArgOf(ws), branch: BRANCH })
1267
+ }, "packDelta").pack;
1268
+ const full = { ok: true, packB64: b64Bytes(pack), bytes: pack.length };
962
1269
  if (full && full.ok === true && typeof full.packB64 === "string") {
963
1270
  return { packB64: full.packB64, bytes: full.bytes, divergent: true, ...head ? { head } : {} };
964
1271
  }
@@ -993,15 +1300,29 @@ function packBornChildren(eng, born) {
993
1300
  });
994
1301
  }
995
1302
  function offerIntent(eng, ws, bytes, opts = {}) {
996
- const name = `offer-in-${eng.seq++}.json`;
997
- writeWork(eng, name, bytes);
1303
+ const seq = eng.seq++;
998
1304
  const deferProjection = !!(opts && opts.defer);
999
1305
  const branch = opts && opts.branch || BRANCH;
1000
- return JSON.parse(call(eng.ex, "offer", { repoArg: repoArgOf(ws), workspace: ws, intentFile: `/work/${name}`, branch, deferProjection }, eng.STDERR));
1306
+ const response = callProto(eng.ex, {
1307
+ case: "offer",
1308
+ value: create(OfferRequestSchema, {
1309
+ target: protoTarget(ws, String(branch)),
1310
+ intent: { case: "sealedChangeUsda", value: bytes },
1311
+ authoring: create(AuthoringOptionsSchema, {
1312
+ sequence: BigInt(seq),
1313
+ deferProjection,
1314
+ spans: !!opts?.spans
1315
+ }),
1316
+ candidateCommit: typeof opts?.candidateCommit === "string" ? opts.candidateCommit : void 0
1317
+ })
1318
+ }, eng.STDERR);
1319
+ if (response.outcome.case !== "offer") {
1320
+ throw new Error(`kernel returned ${response.outcome.case || "empty"} for sealed offer request`);
1321
+ }
1322
+ return offerResult(response.outcome.value);
1001
1323
  }
1002
1324
  function offerAdmit(eng, ws, bytes, opts = {}) {
1003
- const v = offerIntent(eng, ws, bytes, opts);
1004
- 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" };
1325
+ return offerIntent(eng, ws, bytes, opts);
1005
1326
  }
1006
1327
  async function mainIntentIds(eng, ws) {
1007
1328
  const gitdir = gitdirOf(ws);
@@ -1013,7 +1334,7 @@ async function mainIntentIds(eng, ws) {
1013
1334
  for (const c of kgit.intentsAbove(eng, gitdir, head, "", 500)) {
1014
1335
  oids.add(c.oid);
1015
1336
  try {
1016
- const id = JSON.parse(dec3.decode(bytesFromB64(c.intentB64))).id;
1337
+ const id = c.id;
1017
1338
  if (typeof id === "string" && id) ids.add(id);
1018
1339
  } catch {
1019
1340
  }
@@ -1098,15 +1419,11 @@ async function admitAll(eng, ws, ledger, { receiptFence = null, shardRouting = n
1098
1419
  for (const c of chain) {
1099
1420
  const oid = c.oid;
1100
1421
  try {
1101
- const blob = bytesFromB64(c.intentB64);
1102
- let dom = null, intentId = null, dirId = null;
1103
- try {
1104
- const doc = JSON.parse(dec3.decode(blob));
1105
- intentId = typeof doc.id === "string" ? doc.id : null;
1106
- dom = doc && doc.payload && typeof doc.payload.domain === "string" ? doc.payload.domain : null;
1107
- dirId = doc && doc.payload && typeof doc.payload.directiveId === "string" ? doc.payload.directiveId : null;
1108
- } catch {
1109
- }
1422
+ const blob = bytesFromB64(c.changeB64);
1423
+ const doc = c.intent;
1424
+ const intentId = typeof c.id === "string" ? c.id : null;
1425
+ const dom = typeof c.domain === "string" ? c.domain : null;
1426
+ const dirId = typeof c.directiveId === "string" ? c.directiveId : null;
1110
1427
  if (!dom) {
1111
1428
  rejected.push({ oid: oid.slice(0, 10), error: "non-authored intent \u2014 governance enters its own admin lane" });
1112
1429
  continue;
@@ -1124,11 +1441,7 @@ async function admitAll(eng, ws, ledger, { receiptFence = null, shardRouting = n
1124
1441
  }
1125
1442
  const route = routes.get(`${dom} ${dirId}`);
1126
1443
  if (route) {
1127
- let payloadObj = null;
1128
- try {
1129
- payloadObj = JSON.parse(dec3.decode(blob)).payload?.payload ?? null;
1130
- } catch {
1131
- }
1444
+ const payloadObj = doc?.payload?.payload ?? null;
1132
1445
  const verdict2 = await wrongHomeVerdict(shardRouting, route, payloadObj);
1133
1446
  if (verdict2) {
1134
1447
  rejected.push({ oid: oid.slice(0, 10), error: verdict2.error, ...verdict2.wrongHome ? { wrongHome: verdict2.wrongHome } : {}, ...verdict2.homeMoving ? { homeMoving: verdict2.homeMoving } : {}, ...verdict2.deadLettered ? { deadLettered: true } : {} });
@@ -1137,11 +1450,7 @@ async function admitAll(eng, ws, ledger, { receiptFence = null, shardRouting = n
1137
1450
  }
1138
1451
  }
1139
1452
  if (dirId === "nomosReceiveAssignment" && shardRouting) {
1140
- let p = null;
1141
- try {
1142
- p = JSON.parse(dec3.decode(blob)).payload?.payload ?? null;
1143
- } catch {
1144
- }
1453
+ const p = doc?.payload?.payload ?? null;
1145
1454
  const homeKey = p && typeof p.homeKey === "string" ? p.homeKey : null;
1146
1455
  const rows = homeKey ? await shardRouting.assignments() || [] : [];
1147
1456
  const a = homeKey ? rows.find((x) => x.homeKey === homeKey) : null;
@@ -1166,34 +1475,32 @@ async function admitAll(eng, ws, ledger, { receiptFence = null, shardRouting = n
1166
1475
  skipped.push({ oid: oid.slice(0, 10), intent: intentId.slice(0, 12), alreadyOnMain: true });
1167
1476
  continue;
1168
1477
  }
1169
- const cap = summaryCtx ? beginSummaryCapture(eng, ws, summaryCtx, blob) : null;
1170
- const verdict = offerIntent(eng, ws, blob, { defer: canDeferProjection });
1171
- const res = verdict.outcome === "admitted" ? { ok: true, head: verdict.head } : { ok: false, error: verdict.verdict?.reason ?? verdict.error ?? "the offer was refused" };
1478
+ const cap = summaryCtx ? beginSummaryCapture(eng, ws, summaryCtx, doc) : null;
1479
+ const verdict = offerIntent(eng, ws, blob, {
1480
+ defer: canDeferProjection,
1481
+ // The session commit is inert custody. Passing its content address lets the kernel recover
1482
+ // typed auxiliary assets (notably a USDA law closure) bound by the sealed intent. The kernel
1483
+ // authenticates the closure and runs the same offer gate; the adapter interprets nothing.
1484
+ candidateCommit: oid
1485
+ });
1486
+ const res = verdict.outcome === "admitted" ? { ok: true, head: verdict.head } : { ok: false, error: verdict.error };
1172
1487
  if (res.ok) {
1173
- main.ids.add(intentId);
1488
+ if (intentId) main.ids.add(intentId);
1174
1489
  main.oids.add(res.head);
1175
1490
  main.head = res.head;
1176
1491
  admitted.push({ oid: oid.slice(0, 10), head: res.head });
1177
- if (cap) finishSummaryCapture(eng, ws, summaryCtx, cap, res.head ?? "", intentId);
1492
+ if (cap) finishSummaryCapture(eng, ws, summaryCtx, cap, res.head ?? "", intentId ?? "");
1178
1493
  if (shardRouting && dirId) {
1179
1494
  const placement = placementDirectives(eng).get(dirId);
1180
1495
  if (placement) {
1181
- let p = null;
1182
- try {
1183
- p = JSON.parse(dec3.decode(blob)).payload?.payload ?? null;
1184
- } catch {
1185
- }
1496
+ const p = doc?.payload?.payload ?? null;
1186
1497
  const homeKey = p ? p[String(placement.keyField)] : void 0;
1187
1498
  if (typeof homeKey === "string" && typeof p?.shard === "string") {
1188
1499
  placements.push({ directive: dirId, homeKey, shard: p.shard, mapVersion: 1 });
1189
1500
  }
1190
1501
  }
1191
1502
  if (dirId === "nomosSplitShard" && !shardRouting.selfLabel) {
1192
- let p = null;
1193
- try {
1194
- p = JSON.parse(dec3.decode(blob)).payload?.payload ?? null;
1195
- } catch {
1196
- }
1503
+ const p = doc?.payload?.payload ?? null;
1197
1504
  if (p && typeof p.fromShard === "string" && typeof p.toShard === "string" && Array.isArray(p.homeKeys)) {
1198
1505
  splits.push({ fromShard: p.fromShard, toShard: p.toShard, homeKeys: p.homeKeys.filter((k) => typeof k === "string") });
1199
1506
  }
@@ -1201,7 +1508,7 @@ async function admitAll(eng, ws, ledger, { receiptFence = null, shardRouting = n
1201
1508
  }
1202
1509
  if (globalsDeclared && globalsDeclared.size > 0) {
1203
1510
  let touchesGlobal = false;
1204
- for (const ev of parseIntentEvents(blob)) {
1511
+ for (const ev of parseIntentEvents(doc)) {
1205
1512
  const rows = qById(eng, ws, ev.aggregate);
1206
1513
  const t = ev.sets.get("__type") ?? (rows.length ? rows[0].type : void 0);
1207
1514
  if (t !== void 0 && globalsDeclared.has(t)) {
@@ -1287,7 +1594,7 @@ async function admitAll(eng, ws, ledger, { receiptFence = null, shardRouting = n
1287
1594
  }
1288
1595
  const newMain = kgit.resolveRef(eng, gitdir, BRANCH);
1289
1596
  log("admit", { ws, sessions: results.length, main: newMain });
1290
- const summary = summaryCtx ? summaryOfCapture(summaryCtx, headBefore, newMain) : null;
1597
+ const summary = summaryCtx ? summaryOfCapture(summaryCtx, headBefore ?? "", newMain) : null;
1291
1598
  const _total = Date.now() - _t0;
1292
1599
  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 };
1293
1600
  return {
@@ -1312,12 +1619,13 @@ async function writeRefusedRef(eng, ws, dl) {
1312
1619
  try {
1313
1620
  const prevOid = kgit.resolveRef(eng, gitdir, refForStamp);
1314
1621
  if (prevOid) {
1315
- const prev = JSON.parse(dec3.decode(kgit.readBlob(eng, gitdir, prevOid, "verdict.json") ?? new Uint8Array()));
1622
+ const prevBytes = kgit.readBlob(eng, gitdir, prevOid, "verdict.usda");
1623
+ const prev = prevBytes ? kgit.inspectDocument(eng, prevBytes) : null;
1316
1624
  if (prev && typeof prev.parkedAt === "string") parkedAt = prev.parkedAt;
1317
1625
  }
1318
1626
  } catch {
1319
1627
  }
1320
- const verdict = enc3.encode(JSON.stringify({
1628
+ const verdict = kgit.encodeDocument(eng, {
1321
1629
  offerId: dl.intentId || null,
1322
1630
  oid: dl.oid || null,
1323
1631
  domain: dl.domain || null,
@@ -1325,11 +1633,11 @@ async function writeRefusedRef(eng, ws, dl) {
1325
1633
  session: dl.session || null,
1326
1634
  parkedAt,
1327
1635
  verdict: { reason: String(dl.error || "refused") }
1328
- }));
1636
+ });
1329
1637
  const ref = refusedRefName(dl.intentId || dl.oid);
1330
1638
  kgit.writeMetaCommit(eng, gitdir, {
1331
1639
  parents: [],
1332
- files: [{ path: "intent.json", bytes: blob }, { path: "verdict.json", bytes: verdict }],
1640
+ files: [{ path: "change.usda", bytes: blob }, { path: "verdict.usda", bytes: verdict }],
1333
1641
  message: `refused: ${dl.domain || "?"}/${dl.directiveId || "?"} \u2014 ${String(dl.error || "").slice(0, 120)}`,
1334
1642
  timeSecs: 0,
1335
1643
  ref
@@ -1342,10 +1650,10 @@ async function listRefusedRefs(eng, ws) {
1342
1650
  const out = [];
1343
1651
  for (const { ref, oid } of refs) {
1344
1652
  try {
1345
- const vb = kgit.readBlob(eng, gitdir, oid, "verdict.json") ?? new Uint8Array();
1346
- const ib = kgit.readBlob(eng, gitdir, oid, "intent.json") ?? new Uint8Array();
1347
- const v = JSON.parse(dec3.decode(vb));
1348
- out.push({ ref, ...v, intentB64: b64Bytes(ib) });
1653
+ const vb = kgit.readBlob(eng, gitdir, oid, "verdict.usda") ?? new Uint8Array();
1654
+ const ib = kgit.readBlob(eng, gitdir, oid, "change.usda") ?? new Uint8Array();
1655
+ const v = kgit.inspectDocument(eng, vb);
1656
+ out.push({ ref, ...v, changeB64: b64Bytes(ib) });
1349
1657
  } catch {
1350
1658
  }
1351
1659
  }
@@ -1357,7 +1665,9 @@ async function refusedSummary(eng, ws) {
1357
1665
  let count2 = 0, latestParkedAt = null;
1358
1666
  for (const { oid } of refs) {
1359
1667
  try {
1360
- const v = JSON.parse(dec3.decode(kgit.readBlob(eng, gitdir, oid, "verdict.json") ?? new Uint8Array()));
1668
+ const bytes = kgit.readBlob(eng, gitdir, oid, "verdict.usda");
1669
+ if (!bytes) continue;
1670
+ const v = kgit.inspectDocument(eng, bytes);
1361
1671
  count2++;
1362
1672
  if (v && typeof v.parkedAt === "string" && (!latestParkedAt || v.parkedAt > latestParkedAt)) latestParkedAt = v.parkedAt;
1363
1673
  } catch {
@@ -1408,92 +1718,6 @@ async function boot(eng, ws, ledger) {
1408
1718
  `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.)`
1409
1719
  );
1410
1720
  }
1411
- async function deploy(eng, ws, ledger, usda, domainHash, dispositions, opts = {}) {
1412
- const existing = qById(eng, ws, `domain-installation:${domainHash}`);
1413
- if (existing.length > 0) {
1414
- const phase = String(existing[0]?.data?.["status.phase"] ?? "");
1415
- return {
1416
- head: kgit.resolveRef(eng, gitdirOf(ws), BRANCH),
1417
- installation: existing,
1418
- staged: phase === "Pending",
1419
- alreadyInstalled: true
1420
- };
1421
- }
1422
- const before = currentLaw(eng, ws);
1423
- const tenantHashes = [...new Set(Object.values(before).filter(
1424
- (hash) => typeof hash === "string" && hash !== eng.hashes.bootstrap && hash !== eng.hashes.nomos
1425
- ))];
1426
- const upgrade = tenantHashes.length > 0;
1427
- let supersedes = opts.supersedes?.trim() || void 0;
1428
- if (supersedes !== void 0 && !tenantHashes.includes(supersedes)) {
1429
- throw new Error(
1430
- `deploy-predecessor-changed: the client named ${supersedes.slice(0, 12)}\u2026 as the current model, but this workspace no longer serves it. Refresh and deploy again; nothing was committed.`
1431
- );
1432
- }
1433
- if (upgrade && supersedes === void 0) {
1434
- if (tenantHashes.length === 1) supersedes = tenantHashes[0];
1435
- else {
1436
- throw new Error(
1437
- `deploy-predecessor-ambiguous: this workspace currently serves ${tenantHashes.length} business-model packages. Nomos will not guess which one this candidate follows; use the generated deploy client, which binds the candidate to the current model before staging. Nothing was committed.`
1438
- );
1439
- }
1440
- }
1441
- if (upgrade && dispositions && Object.keys(dispositions).length > 0) {
1442
- throw new Error(
1443
- "deploy-manual-evolution-refused: successor deployment no longer accepts caller-chosen schema dispositions. Schema evolution belongs to the candidate model's adoption proof; nothing was committed."
1444
- );
1445
- }
1446
- const directiveId = upgrade ? "stageDomain" : "installDomain";
1447
- const payload = upgrade ? stagePayload(domainHash, usda, eng.installedBy, supersedes) : installPayload(domainHash, usda, eng.installedBy, dispositions);
1448
- const result = author(eng, ws, "nomos", directiveId, payload, eng.hashes.nomos, {
1449
- actor: opts.actor ?? "",
1450
- ...opts.authToken ? { authToken: opts.authToken } : {},
1451
- ...opts.authorSecret ? { authorSecret: opts.authorSecret } : {}
1452
- });
1453
- if (result.ok === false) {
1454
- unmount(eng, ws);
1455
- throw new Error(
1456
- `deploy-refused: ${upgrade ? "staging" : "installing"} ${domainHash.slice(0, 12)}\u2026 was REFUSED by the one gate (custody unchanged): ${result.error ?? "unknown refusal"}`
1457
- );
1458
- }
1459
- try {
1460
- const installation = qById(eng, ws, `domain-installation:${domainHash}`);
1461
- if (upgrade) {
1462
- const phase = String(installation[0]?.data?.["status.phase"] ?? "");
1463
- if (phase !== "Pending") {
1464
- throw new Error(
1465
- `deploy-did-not-stage: candidate ${domainHash.slice(0, 12)}\u2026 admitted but its lifecycle phase is '${phase || "missing"}', not Pending. Custody was not pushed.`
1466
- );
1467
- }
1468
- const after = currentLaw(eng, ws);
1469
- const moved = Object.entries(before).filter(([key, hash]) => after[key] !== hash);
1470
- if (moved.length > 0 || Object.values(after).includes(domainHash)) {
1471
- throw new Error(
1472
- `deploy-activated-candidate: staging ${domainHash.slice(0, 12)}\u2026 changed served law (${moved.map(([key]) => key).join(", ") || "candidate became current"}). Nomos refuses to persist an upgrade that bypassed model.adopt().`
1473
- );
1474
- }
1475
- await commitAndPush(eng, ws, ledger);
1476
- return { head: result.head, installation, staged: true, supersedes };
1477
- }
1478
- const law = installedLaw(eng, ws);
1479
- const installed = (law?.domains ?? []).find((row) => row?.domainHash === domainHash);
1480
- const keys = installed?.domainKeys ?? installation[0]?.data?.domainKeys ?? installation[0]?.domainKeys ?? [];
1481
- if (keys.length > 0) {
1482
- const currentLaw2 = law?.currentLaw ?? {};
1483
- const stale = keys.filter((k) => currentLaw2[k] !== domainHash);
1484
- if (stale.length > 0) {
1485
- throw new Error(
1486
- `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.`
1487
- );
1488
- }
1489
- }
1490
- await commitAndPush(eng, ws, ledger);
1491
- return { head: result.head, installation, staged: false };
1492
- } catch (error) {
1493
- unmount(eng, ws);
1494
- throw error;
1495
- }
1496
- }
1497
1721
  function snapshot(eng, ws) {
1498
1722
  const wsDir = dirOf(eng.preopen.dir.contents.get("ws")).contents.get(ws);
1499
1723
  return serializeTree(wsDir);
@@ -1504,9 +1728,9 @@ async function ledgerStats(eng, ws, ledger = null) {
1504
1728
  if (!head && ledger?.remote) {
1505
1729
  try {
1506
1730
  await custodySkeleton(eng, gitdir);
1507
- const remoteMain = await custodyFetch(eng, ws, ledger, { remoteRef: "refs/heads/main" });
1731
+ const remoteMain = await custodyFetch(eng, ws, ledger, { remoteRef: "refs/heads/main", writeRef: false });
1508
1732
  if (!remoteMain) return { head: null, commits: 0 };
1509
- kgit.writeRef(eng, gitdir, "HEAD", `ref: refs/heads/${BRANCH}`);
1733
+ kgit.restoreMain(eng, ws, remoteMain);
1510
1734
  head = kgit.resolveRef(eng, gitdir, BRANCH);
1511
1735
  const mounted2 = eng.mounted.get(ws);
1512
1736
  if (mounted2) {
@@ -1525,7 +1749,7 @@ async function ledgerStats(eng, ws, ledger = null) {
1525
1749
  if (mounted) mounted.ledgerStats = out;
1526
1750
  return out;
1527
1751
  }
1528
- var enc3, dec3, BRANCH, RESULT_PACK_INLINE_MAX, dirOf, repoArgOf, gitdirOf, unpack, log, repoArgOfGitdir, bytesFromB64, kgit, installPayload, stagePayload, 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, pendingConflictSummary, spatialBboxParams, spatialWithin, extremum, nomosActive, refusedRefName, GENESIS_WARRANT_ID, isWarranted;
1752
+ var enc3, dec3, BRANCH, PROTO_ABI_VERSION, protoRequestSequence, RESULT_PACK_INLINE_MAX, dirOf, repoArgOf, gitdirOf, unpack, unsignedWasiPointers, log, protoTarget, protoAuthority, repoArgOfGitdir, bytesFromB64, kgit, closureInstallPayload, routeTagHexOfHomeKey, SUMMARY_SEP, summaryKey, splitSummaryKey, NOMOS_SHARD_ROWS_READ, groupOf, tallyOf, isExtremumRead, extremumMonotone, pushVia, fullRef, applyPackInto, custodyLsRefs, queryArguments, queryAuthorityOptions, qById, query, authorKeygen, certSign, readPosture, count, sum, pendingConflicts, pendingConflictSummary, spatialBboxParams, spatialWithin, extremum, nomosActive, refusedRefName, GENESIS_WARRANT_ID, isWarranted;
1529
1753
  var init_engine = __esm({
1530
1754
  "../adapter/engine.ts"() {
1531
1755
  "use strict";
@@ -1533,57 +1757,199 @@ var init_engine = __esm({
1533
1757
  init_tree();
1534
1758
  init_custody_transport();
1535
1759
  init_managed_promotion();
1760
+ init_kernel_pb();
1536
1761
  enc3 = new TextEncoder();
1537
1762
  dec3 = new TextDecoder();
1538
1763
  BRANCH = "main";
1764
+ PROTO_ABI_VERSION = 1;
1765
+ protoRequestSequence = 0;
1539
1766
  RESULT_PACK_INLINE_MAX = 256 * 1024;
1540
1767
  dirOf = (n) => n;
1541
1768
  repoArgOf = (ws) => `/work/ws/${ws}`;
1542
1769
  gitdirOf = (ws) => `/work/ws/${ws}/nomos.git`;
1543
1770
  unpack = (p) => {
1544
- const v = typeof p === "bigint" ? p : BigInt(p);
1545
- return { ptr: Number(v >> 32n), len: Number(v & 0xffffffffn) };
1771
+ const v = BigInt.asUintN(64, typeof p === "bigint" ? p : BigInt(p));
1772
+ return { ptr: Number(v >> 32n & 0xffffffffn), len: Number(v & 0xffffffffn) };
1773
+ };
1774
+ unsignedWasiPointers = (imports) => {
1775
+ const pointerArgs = {
1776
+ args_sizes_get: [0, 1],
1777
+ args_get: [0, 1],
1778
+ environ_sizes_get: [0, 1],
1779
+ environ_get: [0, 1],
1780
+ clock_res_get: [1],
1781
+ clock_time_get: [2],
1782
+ fd_fdstat_get: [1],
1783
+ fd_filestat_get: [1],
1784
+ fd_pread: [1, 4],
1785
+ fd_prestat_get: [1],
1786
+ fd_prestat_dir_name: [1],
1787
+ fd_pwrite: [1, 4],
1788
+ fd_read: [1, 3],
1789
+ fd_readdir: [1, 4],
1790
+ fd_seek: [3],
1791
+ fd_tell: [1],
1792
+ fd_write: [1, 3],
1793
+ path_create_directory: [1],
1794
+ path_filestat_get: [2, 4],
1795
+ path_filestat_set_times: [2],
1796
+ path_link: [2, 5],
1797
+ path_open: [2, 8],
1798
+ path_readlink: [1, 3, 5],
1799
+ path_remove_directory: [1],
1800
+ path_rename: [1, 4],
1801
+ path_symlink: [0, 3],
1802
+ path_unlink_file: [1],
1803
+ poll_oneoff: [0, 1],
1804
+ random_get: [0]
1805
+ };
1806
+ for (const [name, indexes] of Object.entries(pointerArgs)) {
1807
+ const original = imports[name];
1808
+ if (typeof original !== "function") continue;
1809
+ imports[name] = (...args) => {
1810
+ for (const index of indexes) args[index] = args[index] >>> 0;
1811
+ return original(...args);
1812
+ };
1813
+ }
1814
+ return imports;
1546
1815
  };
1547
1816
  log = (evt, fields = {}) => console.log(JSON.stringify({ evt, t: Date.now(), ...fields }));
1817
+ protoTarget = (ws = "root", branch = BRANCH) => create(WorkspaceTargetSchema, {
1818
+ repo: repoArgOf(ws),
1819
+ workspace: ws,
1820
+ branch
1821
+ });
1822
+ protoAuthority = (principal = "", keys = [], authToken = "", nowUnix = 0, authorSecret = "") => create(QueryAuthoritySchema, {
1823
+ principalClaim: principal,
1824
+ authToken: authToken ? enc3.encode(authToken) : new Uint8Array(),
1825
+ nowUnix: BigInt(nowUnix),
1826
+ authorSecret: authorSecret ? bytesFromB64(authorSecret) : new Uint8Array(),
1827
+ keys: keys.map((key) => create(InjectedKeySchema, {
1828
+ scope: key.scope,
1829
+ epoch: BigInt(key.epoch),
1830
+ key: bytesFromB64(key.key)
1831
+ }))
1832
+ });
1548
1833
  repoArgOfGitdir = (gitdir) => gitdir.replace(/\/nomos\.git$/, "");
1549
1834
  bytesFromB64 = (b64) => Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
1550
1835
  kgit = {
1551
1836
  // resolveRef → tip oid hex, or null if the ref is absent (replaces git.resolveRef(...).catch(()=>null)).
1552
- resolveRef: (eng, gitdir, ref) => JSON.parse(call(eng.ex, "resolve_ref", { repoArg: repoArgOfGitdir(gitdir), ref }, eng.STDERR)).oid,
1837
+ resolveRef: (eng, gitdir, ref) => custodyProtoCase(eng, {
1838
+ case: "resolveRef",
1839
+ value: create(ResolveRefRequestSchema, { repo: repoArgOfGitdir(gitdir), reference: ref })
1840
+ }, "resolveRef").oid ?? "",
1553
1841
  // readBlob → the blob bytes at `path` inside commit `oid`, or null if not found (no throw).
1554
- readBlob: (eng, gitdir, oid, path2) => {
1555
- const r = JSON.parse(call(eng.ex, "read_blob", { repoArg: repoArgOfGitdir(gitdir), oid, path: path2 }, eng.STDERR));
1556
- return r.ok ? bytesFromB64(r.blobB64) : null;
1842
+ readBlob: (eng, gitdir, oid, path3) => {
1843
+ const result = custodyProtoCase(eng, {
1844
+ case: "readBlob",
1845
+ value: create(ReadBlobRequestSchema, { repo: repoArgOfGitdir(gitdir), oid, path: path3 })
1846
+ }, "readBlob");
1847
+ return result.found ? result.blob : null;
1557
1848
  },
1558
- // intentsAbove → [{ oid, intentB64 }] oldest→newest over (base, head] (replaces log + readBlob intent.json).
1849
+ // intentsAbove → [{ oid, changeB64 }] oldest→newest over (base, head] (replaces log + readBlob intent.json).
1559
1850
  // `limit` (0 = all) caps to the most-recent N intent commits (replaces git.log depth).
1560
- intentsAbove: (eng, gitdir, head, base = "", limit = 0) => JSON.parse(call(eng.ex, "intents_above", { repoArg: repoArgOfGitdir(gitdir), head, base, limit }, eng.STDERR)).intents,
1851
+ intentsAbove: (eng, gitdir, head, base = "", limit = 0, completeLogical = false) => custodyProtoCase(eng, {
1852
+ case: "intentsAbove",
1853
+ value: create(IntentsAboveRequestSchema, {
1854
+ repo: repoArgOfGitdir(gitdir),
1855
+ head: head || void 0,
1856
+ base: base || void 0,
1857
+ branch: BRANCH,
1858
+ limit: BigInt(limit),
1859
+ completeLogical
1860
+ })
1861
+ }, "intentsAbove").intents.map((intent) => ({
1862
+ oid: intent.oid,
1863
+ id: intent.intentId,
1864
+ domain: intent.domain,
1865
+ directiveId: intent.directive,
1866
+ changeB64: b64Bytes(intent.changeUsda),
1867
+ intent: jsStruct(intent.semantic)
1868
+ })),
1869
+ // inspectChange → compact semantic view decoded by the kernel; the adapter never parses USDA.
1870
+ inspectChange: (eng, bytes) => jsStruct(custodyProtoCase(eng, {
1871
+ case: "inspectChange",
1872
+ value: create(InspectChangeRequestSchema, { changeUsda: bytes })
1873
+ }, "inspectChange").semantic),
1874
+ // Open structured custody sidecars are USDA too. The kernel owns their syntax and validation;
1875
+ // the adapter only relays transient values and opaque bytes.
1876
+ encodeDocument: (eng, value) => custodyProtoCase(eng, {
1877
+ case: "encodeDocument",
1878
+ value: create(EncodeDocumentRequestSchema, { document: protoValue(value) })
1879
+ }, "encodeDocument").documentUsda,
1880
+ inspectDocument: (eng, bytes) => jsValue(custodyProtoCase(eng, {
1881
+ case: "inspectDocument",
1882
+ value: create(InspectDocumentRequestSchema, { documentUsda: bytes })
1883
+ }, "inspectDocument").document),
1561
1884
  // listRefs → [{ ref, oid }] under prefix (replaces git.listRefs for LOCAL refs).
1562
- listRefs: (eng, gitdir, prefix) => JSON.parse(call(eng.ex, "list_refs", { repoArg: repoArgOfGitdir(gitdir), prefix }, eng.STDERR)).refs,
1885
+ listRefs: (eng, gitdir, prefix) => custodyProtoCase(eng, {
1886
+ case: "listRefs",
1887
+ value: create(ListRefsRequestSchema, { repo: repoArgOfGitdir(gitdir), prefix })
1888
+ }, "listRefs").refs.map(({ reference, oid }) => ({ ref: reference, oid })),
1563
1889
  // writeRef → force-point a ref (plain oid or `ref:`-symbolic) (replaces git.writeRef).
1564
- writeRef: (eng, gitdir, ref, value) => JSON.parse(call(eng.ex, "write_ref", { repoArg: repoArgOfGitdir(gitdir), ref, value }, eng.STDERR)),
1890
+ writeRef: (eng, gitdir, ref, value) => {
1891
+ custodyProtoCase(eng, {
1892
+ case: "writeRef",
1893
+ value: create(WriteRefRequestSchema, { repo: repoArgOfGitdir(gitdir), reference: ref, target: value })
1894
+ }, "writeRef");
1895
+ return { ok: true };
1896
+ },
1897
+ // restoreMain → promote already-imported custody only after the kernel re-admits the complete chain.
1898
+ // Unlike writeRef this is allowed to establish an absent main; it can never advance an existing one.
1899
+ restoreMain: (eng, ws, head) => custodyProtoCase(eng, {
1900
+ case: "restoreMain",
1901
+ value: create(RestoreMainRequestSchema, {
1902
+ target: create(WorkspaceTargetSchema, { repo: repoArgOf(ws), workspace: ws, branch: BRANCH }),
1903
+ head
1904
+ })
1905
+ }, "restoreMain"),
1565
1906
  // deleteRef → remove a local ref, idempotent (replaces git.deleteRef).
1566
- deleteRef: (eng, gitdir, ref) => JSON.parse(call(eng.ex, "delete_ref", { repoArg: repoArgOfGitdir(gitdir), ref }, eng.STDERR)),
1907
+ deleteRef: (eng, gitdir, ref) => {
1908
+ custodyProtoCase(eng, {
1909
+ case: "deleteRef",
1910
+ value: create(DeleteRefRequestSchema, { repo: repoArgOfGitdir(gitdir), reference: ref })
1911
+ }, "deleteRef");
1912
+ return { ok: true };
1913
+ },
1567
1914
  // applyPack → ingest a pack's objects into ws's repo (kernel apply_pack; refs are the caller's job).
1568
1915
  applyPack: (eng, ws, packBytes) => applyPackInto(eng, ws, packBytes),
1916
+ // repoStats → kernel-owned physical custody accounting (host never walks Git's loose/pack layout).
1917
+ repoStats: (eng, ws) => {
1918
+ const stats = custodyProtoCase(eng, {
1919
+ case: "repoStats",
1920
+ value: create(RepoStatsRequestSchema, { repo: repoArgOf(ws) })
1921
+ }, "repoStats");
1922
+ return {
1923
+ ok: true,
1924
+ totalBytes: Number(stats.totalBytes),
1925
+ objectBytes: Number(stats.objectBytes),
1926
+ looseObjects: Number(stats.looseObjects),
1927
+ looseBytes: Number(stats.looseBytes),
1928
+ packFiles: Number(stats.packFiles),
1929
+ packBytes: Number(stats.packBytes),
1930
+ indexBytes: Number(stats.indexBytes)
1931
+ };
1932
+ },
1569
1933
  // writeMetaCommit → blobs→tree→commit→ref for a CUSTODY-META fact (checkpoint/refused/outbox/shape).
1570
1934
  // `files`: [{ path, bytes:Uint8Array }]; returns the commit oid (replaces writeBlob+writeTree+writeCommit[+writeRef]).
1571
- writeMetaCommit: (eng, gitdir, { parents = [], files, message = "nomos custody meta", timeSecs = 0, ref = "" }) => JSON.parse(call(eng.ex, "write_meta_commit", {
1572
- repoArg: repoArgOfGitdir(gitdir),
1573
- parents,
1574
- files: files.map((f) => ({ path: f.path, blobB64: b64Bytes(f.bytes) })),
1575
- message,
1576
- timeSecs,
1577
- ref
1578
- }, eng.STDERR)).oid
1935
+ writeMetaCommit: (eng, gitdir, { parents = [], files, message = "nomos custody meta", timeSecs = 0, ref = "" }) => custodyProtoCase(eng, {
1936
+ case: "writeMetaCommit",
1937
+ value: create(WriteMetaCommitRequestSchema, {
1938
+ repo: repoArgOfGitdir(gitdir),
1939
+ parents,
1940
+ files: files.map((file) => ({ path: file.path, content: file.bytes })),
1941
+ message,
1942
+ timeSeconds: BigInt(timeSecs),
1943
+ reference: ref || void 0
1944
+ })
1945
+ }, "writeMetaCommit").oid
1579
1946
  };
1580
- installPayload = (hash, usda, installedBy, dispositions) => ({ domainHash: hash, packageUsda: usda, installedBy, dependencies: [], finalizers: [], ...dispositions ? { dispositions } : {} });
1581
- stagePayload = (hash, usda, installedBy, supersedes) => ({
1947
+ closureInstallPayload = (hash, installedBy, options = {}) => ({
1582
1948
  domainHash: hash,
1583
- packageUsda: usda,
1584
1949
  installedBy,
1585
1950
  dependencies: [],
1586
- ...supersedes ? { supersedes } : {},
1951
+ ...options.supersedes ? { supersedes: options.supersedes } : {},
1952
+ ...options.dispositions ? { dispositions: options.dispositions } : {},
1587
1953
  finalizers: []
1588
1954
  });
1589
1955
  routeTagHexOfHomeKey = async (homeKey) => (await sha256hex(`nomos-route:${homeKey}`)).slice(0, 12);
@@ -1604,21 +1970,35 @@ var init_engine = __esm({
1604
1970
  extremumMonotone = (read, prev, next) => next === null && prev === null || next !== null && (prev === null || (read.kind === "min" ? next <= prev : next >= prev));
1605
1971
  pushVia = (ledger, fn) => ledger && ledger.pushLane ? ledger.pushLane(fn) : fn();
1606
1972
  fullRef = (r) => r === "HEAD" || r.startsWith("refs/") ? r : `refs/heads/${r}`;
1607
- applyPackInto = (eng, ws, pack) => {
1973
+ applyPackInto = (eng, ws, pack, head = null) => {
1608
1974
  if (!pack || !pack.length) return;
1609
- const r = JSON.parse(call(eng.ex, "apply_pack", { repoArg: repoArgOf(ws), packB64: b64Bytes(pack) }, eng.STDERR));
1610
- if (!r || r.ok !== true) throw new Error(`apply_pack: ${r && r.error}`);
1975
+ custodyProtoCase(eng, {
1976
+ case: "applyPack",
1977
+ value: create(ApplyPackRequestSchema, {
1978
+ repo: repoArgOf(ws),
1979
+ source: { case: "pack", value: pack },
1980
+ head: head || void 0
1981
+ })
1982
+ }, "applyPack");
1611
1983
  };
1612
1984
  custodyLsRefs = (ledger, prefix = null) => lsRefs(ledger.remote, ledger.headers || {}, { service: "git-upload-pack", prefix });
1613
- 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));
1614
- 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));
1615
- authorKeygen = (eng) => JSON.parse(call(eng.ex, "query", { queryBytes: b64Json({ op: "authorKeygen" }) }, eng.STDERR));
1616
- attestedRead = (eng, ws, { queryId, paramsJson, attestorSecret, nowMs, includeRosterProof }) => JSON.parse(call(eng.ex, "query", {
1617
- repoArg: repoArgOf(ws),
1618
- workspace: ws,
1619
- branch: BRANCH,
1620
- queryBytes: b64Json({ op: "attestedRead", queryId, paramsJson: paramsJson || "{}", attestorSecret, nowMs: nowMs ?? Date.now(), sourceWorkspace: ws, ...includeRosterProof ? { includeRosterProof: true } : {} })
1621
- }, eng.STDERR));
1985
+ queryArguments = (paramsJson) => {
1986
+ const value = JSON.parse(paramsJson || "{}");
1987
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
1988
+ throw new Error("query arguments must be a JSON object");
1989
+ }
1990
+ return value;
1991
+ };
1992
+ queryAuthorityOptions = (principal, keys, authToken, nowUnix, authorSecret) => ({ principal, keys, authToken, nowUnix, authorSecret });
1993
+ qById = (eng, ws, id, principal = "", keys = [], authToken = "", nowUnix = 0, authorSecret = "") => applicationQueryProto(eng, ws, {
1994
+ case: "byId",
1995
+ value: create(ByIdQuerySchema, { aggregateId: id, principal })
1996
+ }, queryAuthorityOptions(principal, keys, authToken, nowUnix, authorSecret));
1997
+ query = (eng, ws, queryId, paramsJson, principal = "", keys = [], authToken = "", nowUnix = 0, authorSecret = "") => applicationQueryProto(eng, ws, {
1998
+ case: "rows",
1999
+ value: create(RowsQuerySchema, { id: queryId, arguments: protoStruct(queryArguments(paramsJson)), principal })
2000
+ }, queryAuthorityOptions(principal, keys, authToken, nowUnix, authorSecret));
2001
+ authorKeygen = (eng) => namedQueryProto(eng, "root", QueryOperation.AUTHOR_KEYGEN);
1622
2002
  certSign = (eng, {
1623
2003
  child,
1624
2004
  founder,
@@ -1633,8 +2013,7 @@ var init_engine = __esm({
1633
2013
  authProviderIssuer,
1634
2014
  authProviderJwks,
1635
2015
  authProviderAudience
1636
- }) => JSON.parse(call(eng.ex, "query", { queryBytes: b64Json({
1637
- op: "certSign",
2016
+ }) => namedQueryProto(eng, "root", QueryOperation.CERT_SIGN, {
1638
2017
  child,
1639
2018
  founder,
1640
2019
  verified,
@@ -1649,18 +2028,51 @@ var init_engine = __esm({
1649
2028
  ...authProviderIssuer !== void 0 ? { authProviderIssuer } : {},
1650
2029
  ...authProviderJwks !== void 0 ? { authProviderJwks } : {},
1651
2030
  ...authProviderAudience !== void 0 ? { authProviderAudience } : {}
1652
- }) }, eng.STDERR)).cert;
1653
- 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));
1654
- 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));
1655
- 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));
1656
- pendingConflicts = (eng, ws, principal = "", aggregateType = "") => JSON.parse(call(eng.ex, "query", { repoArg: repoArgOf(ws), workspace: ws, queryBytes: b64Json({ op: "pendingConflicts", aggregateType }), principal, branch: BRANCH }, eng.STDERR));
1657
- pendingConflictSummary = (eng, ws, principal = "") => JSON.parse(call(eng.ex, "query", { repoArg: repoArgOf(ws), workspace: ws, queryBytes: b64Json({ op: "pendingConflictSummary" }), principal, branch: BRANCH }, eng.STDERR));
2031
+ }).cert;
2032
+ readPosture = (eng, ws, principal = "", authToken = "", nowUnix = 0, authorSecret = "") => namedQueryProto(
2033
+ eng,
2034
+ ws,
2035
+ QueryOperation.READ_POSTURE,
2036
+ {},
2037
+ queryAuthorityOptions(principal, [], authToken, nowUnix, authorSecret)
2038
+ );
2039
+ count = (eng, ws, countId, groupKey, principal = "", authToken = "", nowUnix = 0, authorSecret = "") => applicationQueryProto(eng, ws, {
2040
+ case: "count",
2041
+ value: create(TallyQuerySchema, { id: countId, arguments: protoStruct({ groupKey: groupKey ?? null }), principal })
2042
+ }, queryAuthorityOptions(principal, [], authToken, nowUnix, authorSecret));
2043
+ sum = (eng, ws, sumId, groupKey, principal = "", authToken = "", nowUnix = 0, authorSecret = "") => applicationQueryProto(eng, ws, {
2044
+ case: "sum",
2045
+ value: create(TallyQuerySchema, { id: sumId, arguments: protoStruct({ groupKey: groupKey ?? null }), principal })
2046
+ }, queryAuthorityOptions(principal, [], authToken, nowUnix, authorSecret));
2047
+ pendingConflicts = (eng, ws, principal = "", aggregateType = "", authToken = "", nowUnix = 0, authorSecret = "") => namedQueryProto(
2048
+ eng,
2049
+ ws,
2050
+ QueryOperation.PENDING_CONFLICTS,
2051
+ { aggregateType },
2052
+ queryAuthorityOptions(principal, [], authToken, nowUnix, authorSecret)
2053
+ );
2054
+ pendingConflictSummary = (eng, ws, principal = "", authToken = "", nowUnix = 0, authorSecret = "") => namedQueryProto(
2055
+ eng,
2056
+ ws,
2057
+ QueryOperation.PENDING_CONFLICT_SUMMARY,
2058
+ {},
2059
+ queryAuthorityOptions(principal, [], authToken, nowUnix, authorSecret)
2060
+ );
1658
2061
  spatialBboxParams = (bbox) => {
1659
2062
  const minX = bbox.minX ?? bbox.minLng, minY = bbox.minY ?? bbox.minLat, maxX = bbox.maxX ?? bbox.maxLng, maxY = bbox.maxY ?? bbox.maxLat;
1660
2063
  return { minX, minY, maxX, maxY, minLng: minX, minLat: minY, maxLng: maxX, maxLat: maxY };
1661
2064
  };
1662
- 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));
1663
- 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));
2065
+ spatialWithin = (eng, ws, spatialId, bbox, principal = "", authToken = "", nowUnix = 0, authorSecret = "") => applicationQueryProto(eng, ws, {
2066
+ case: "spatial",
2067
+ value: create(SpatialQuerySchema, { id: spatialId, arguments: protoStruct(spatialBboxParams(bbox)), principal })
2068
+ }, queryAuthorityOptions(principal, [], authToken, nowUnix, authorSecret));
2069
+ extremum = (eng, ws, extremumId, kind, groupKey, principal = "", authToken = "", nowUnix = 0, authorSecret = "") => namedQueryProto(
2070
+ eng,
2071
+ ws,
2072
+ QueryOperation.EXTREMUM,
2073
+ { extremumId, kind, groupKey: groupKey ?? "" },
2074
+ queryAuthorityOptions(principal, [], authToken, nowUnix, authorSecret)
2075
+ );
1664
2076
  nomosActive = (eng, ws) => qById(eng, ws, `domain-installation:${eng.hashes.nomos}`).length > 0;
1665
2077
  refusedRefName = (offerId) => `refs/heads/refused/${String(offerId || "unknown").replace(/[^A-Za-z0-9._-]/g, "_")}`;
1666
2078
  GENESIS_WARRANT_ID = "genesis-warrant:self";
@@ -1686,12 +2098,12 @@ var init_types = __esm({
1686
2098
  var bootstrap_exports = {};
1687
2099
  __export(bootstrap_exports, {
1688
2100
  bootstrapPlatform: () => bootstrapPlatform,
1689
- completeDevAuthProviderPayload: () => completeDevAuthProviderPayload,
1690
- homeDomainOf: () => homeDomainOf,
2101
+ devAuthProviderPayload: () => devAuthProviderPayload,
1691
2102
  isTestMint: () => isTestMint
1692
2103
  });
1693
2104
  import { readFileSync } from "node:fs";
1694
2105
  import { createHash } from "node:crypto";
2106
+ import path from "node:path";
1695
2107
  function isTestMint(eng) {
1696
2108
  try {
1697
2109
  setTestKRoot(eng, "");
@@ -1700,54 +2112,21 @@ function isTestMint(eng) {
1700
2112
  return !/poisoned|unknown|adapter-visible API/.test(errMsg(e));
1701
2113
  }
1702
2114
  }
1703
- function completeDevAuthProviderPayload(deployBody, homeDomain, initial, nowMillis = Date.now(), operator = "user:dev-operator") {
1704
- const payload = { ...initial };
1705
- const iface = deployBody?.interface ?? {};
1706
- const legacy = iface.domains?.[homeDomain]?.directives?.setAuthProvider?.fields ?? iface[homeDomain]?.directives?.setAuthProvider?.fields ?? {};
1707
- const openapi = deployBody?.openapi;
1708
- const frameworkPaths = openapi?.["x-nomos-framework-routes"]?.paths ?? {};
1709
- const setAuthOperation = Object.values(frameworkPaths).map((pathItem) => pathItem.post).filter((operation) => operation?.["x-nomos"]?.directiveId === "setAuthProvider").sort((a, b) => Number(b?.["x-nomos"]?.domain === homeDomain) - Number(a?.["x-nomos"]?.domain === homeDomain))[0] ?? frameworkPaths["/setAuthProvider"]?.post;
1710
- const schema = setAuthOperation?.requestBody?.content?.["application/json"]?.schema;
1711
- const required = new Set(schema?.required ?? []);
1712
- const fields = { ...legacy };
1713
- for (const [name, spec] of Object.entries(schema?.properties ?? {})) {
1714
- fields[name] = {
1715
- kind: spec.type === "integer" ? "int" : spec.type,
1716
- optional: !required.has(name)
1717
- };
1718
- }
1719
- for (const [name, spec] of Object.entries(fields)) {
1720
- if (spec.optional === true || payload[name] !== void 0) continue;
1721
- if (spec.kind === "int" && /At$/.test(name)) payload[name] = nowMillis;
1722
- else if (spec.kind === "string" && /At$/.test(name)) payload[name] = new Date(nowMillis).toISOString();
1723
- else if (spec.kind === "string" && /By$/.test(name)) payload[name] = operator;
1724
- else if (spec.kind === "string" && /url$/i.test(name)) payload[name] = `${payload.issuer}/jwks.json`;
1725
- else if (spec.kind === "string") payload[name] = "dev";
1726
- else log2(`dev test IdP: required setAuthProvider field '${name}' (kind ${spec.kind}) is not synthesizable \u2014 the author below may refuse typed`);
1727
- }
1728
- return payload;
1729
- }
1730
- function homeDomainOf(opts) {
1731
- if (!opts) return null;
1732
- const deploy2 = homeDeployPathOf(opts);
1733
- if (!deploy2) return null;
1734
- try {
1735
- const body = JSON.parse(readFileSync(deploy2, "utf8"));
1736
- const frameworkPaths = body.openapi?.["x-nomos-framework-routes"]?.paths ?? {};
1737
- for (const pathItem of Object.values(frameworkPaths)) {
1738
- const route = pathItem.post?.["x-nomos"];
1739
- if (route?.directiveId === "birthHome" && typeof route.domain === "string") return route.domain;
1740
- }
1741
- const domains = body.summary && body.summary.domains || [];
1742
- const hit = domains.find((d) => Array.isArray(d.directives) && d.directives.includes("seedBirthAttestation"));
1743
- return hit ? hit.domain : null;
1744
- } catch {
1745
- return null;
1746
- }
2115
+ function devAuthProviderPayload(initial, nowMillis = Date.now(), operator = "user:dev-operator") {
2116
+ return {
2117
+ ...initial,
2118
+ jwksUrl: `${initial.issuer}/jwks.json`,
2119
+ principalClaim: "sub",
2120
+ deviceBindingClaim: "nonce",
2121
+ label: "dev",
2122
+ setBy: operator,
2123
+ setAt: nowMillis
2124
+ };
1747
2125
  }
1748
2126
  async function bootstrapPlatform(dev, opts) {
1749
2127
  const { eng, custody, ledgerFor, serialize, origin } = dev;
1750
2128
  const platform = opts.platform || "co2-platform-local";
2129
+ const lawInputs = lawInputsOf(opts);
1751
2130
  log2(`standing up platform '${platform}' on ${origin}`);
1752
2131
  await serialize(async () => {
1753
2132
  custody.create(`holon-${platform}`);
@@ -1758,25 +2137,54 @@ async function bootstrapPlatform(dev, opts) {
1758
2137
  platform,
1759
2138
  "bootstrap",
1760
2139
  "installDomain",
1761
- installPayload(eng.hashes.nomos, eng.nomosPkg, "dev-bootstrap"),
2140
+ closureInstallPayload(eng.hashes.nomos, "dev-bootstrap"),
1762
2141
  "",
1763
- {}
2142
+ { lawUsdz: eng.nomosLawUsdz }
1764
2143
  );
1765
2144
  if (r && r.ok === false) throw new Error(`platform genesis (framework install) REFUSED: ${String(r.error).slice(0, 300)}`);
1766
2145
  }
1767
2146
  log2(`platform '${platform}' genesis'd via the operator anchor lane (framework ${eng.hashes.nomos.slice(0, 12)})`);
1768
2147
  });
2148
+ const stageZeroLaw = lawInputs[0];
2149
+ if (stageZeroLaw) {
2150
+ if (!stageZeroLaw.endsWith(".law.usdz")) {
2151
+ throw new Error(`--law requires a canonical .law.usdz archive, received ${stageZeroLaw}`);
2152
+ }
2153
+ const lawUsdz = new Uint8Array(readFileSync(stageZeroLaw));
2154
+ const info = stageLawClosure(eng, lawUsdz, path.basename(stageZeroLaw));
2155
+ const domainHash = String(info.identity || "");
2156
+ if (!/^[0-9a-f]{64}$/.test(domainHash)) {
2157
+ throw new Error(`kernel did not derive a valid law identity for ${stageZeroLaw}`);
2158
+ }
2159
+ const installed = await serialize(async () => authorOn(
2160
+ eng,
2161
+ platform,
2162
+ ledgerFor(platform),
2163
+ "nomos",
2164
+ "installDomain",
2165
+ closureInstallPayload(domainHash, "dev-bootstrap"),
2166
+ eng.hashes.nomos,
2167
+ { lawUsdz }
2168
+ ));
2169
+ if (!installed.ok) {
2170
+ throw new Error(`stage-zero application law install REFUSED: ${String(installed.error).slice(0, 400)}`);
2171
+ }
2172
+ (dev.deployedLawIdentities ??= []).push(domainHash);
2173
+ log2(`application root law installed through stage zero: ${domainHash.slice(0, 12)}`);
2174
+ }
1769
2175
  const testMint = isTestMint(eng);
1770
2176
  if (!testMint) {
1771
2177
  throw new Error(
1772
2178
  "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."
1773
2179
  );
1774
2180
  } else {
1775
- const OPERATOR = opts.operator || "user:dev-operator";
1776
2181
  const kRoot = authorKeygen(eng);
1777
2182
  setTestKRoot(eng, kRoot.public);
1778
2183
  log2(`K_root ceremony: pinned LOCAL test K_root ${kRoot.public.slice(0, 16)}\u2026`);
1779
2184
  const sP = authorKeygen(eng);
2185
+ const sOp = authorKeygen(eng);
2186
+ const opKeyHash = createHash("sha256").update(Buffer.from(sOp.public, "base64")).digest("hex");
2187
+ const foundingPrincipal = `key:${opKeyHash}`;
1780
2188
  const { generateKeyPairSync, sign: nodeSign } = await import("node:crypto");
1781
2189
  const { privateKey: idpPrivateKey, publicKey: idpPublicKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });
1782
2190
  const idpJwk = idpPublicKey.export({ format: "jwk" });
@@ -1792,7 +2200,7 @@ async function bootstrapPlatform(dev, opts) {
1792
2200
  };
1793
2201
  const platformCert = certSign(eng, {
1794
2202
  child: platform,
1795
- founder: OPERATOR,
2203
+ founder: foundingPrincipal,
1796
2204
  verified: true,
1797
2205
  parentKey: sP.public,
1798
2206
  // P_P — the onboarding signer the platform vouches for
@@ -1813,25 +2221,30 @@ async function bootstrapPlatform(dev, opts) {
1813
2221
  const lawHash = (lawKeys || {})[homeDomain] || "";
1814
2222
  if (!lawHash) {
1815
2223
  throw new Error(
1816
- `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.`
2224
+ `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 --law.`
1817
2225
  );
1818
2226
  } else {
1819
2227
  let devIdP;
1820
2228
  let pendingIdP;
1821
2229
  {
1822
- let apPayload = { issuer: idpIssuer, keys: idpJwks, audience: idpAudience, principalClaim: "sub", deviceBindingClaim: "nonce" };
1823
- try {
1824
- const homeDeploy = homeDeployPathOf(opts);
1825
- const deployBody = homeDeploy ? JSON.parse(readFileSync(homeDeploy, "utf8")) : null;
1826
- apPayload = completeDevAuthProviderPayload(deployBody, homeDomain, apPayload, Date.now(), OPERATOR);
1827
- } catch (e) {
1828
- log2(`dev test IdP: BYO-shape fill failed (${errMsg(e).slice(0, 200)}) \u2014 the canonical payload stands`);
1829
- }
2230
+ const apPayload = devAuthProviderPayload(
2231
+ { issuer: idpIssuer, keys: idpJwks, audience: idpAudience },
2232
+ Date.now(),
2233
+ foundingPrincipal
2234
+ );
1830
2235
  pendingIdP = { ISS: idpIssuer, AUD: idpAudience, JWKS: idpJwks, mint: mintDevToken, apPayload };
1831
2236
  }
1832
- const sOp = authorKeygen(eng);
1833
- const opKeyHash = createHash("sha256").update(Buffer.from(sOp.public, "base64")).digest("hex");
1834
- const A = (directiveId, payload) => serialize(async () => authorOn(
2237
+ const preWarrant = (directiveId, payload) => serialize(async () => authorOn(
2238
+ eng,
2239
+ platform,
2240
+ ledgerFor(platform),
2241
+ homeDomain,
2242
+ directiveId,
2243
+ payload,
2244
+ lawHash,
2245
+ { actor: foundingPrincipal }
2246
+ ));
2247
+ const signed = (directiveId, payload) => serialize(async () => authorOn(
1835
2248
  eng,
1836
2249
  platform,
1837
2250
  ledgerFor(platform),
@@ -1839,13 +2252,11 @@ async function bootstrapPlatform(dev, opts) {
1839
2252
  directiveId,
1840
2253
  payload,
1841
2254
  lawHash,
1842
- { actor: OPERATOR, principalVerified: true }
2255
+ { actor: foundingPrincipal, authorSecret: sOp.secret }
1843
2256
  ));
1844
- const en = await A("enrollSigner", { keyHash: opKeyHash, grantedBy: OPERATOR, grantedAt: 1 });
1845
- if (!en.ok) throw new Error(`platform founding enrollSigner REFUSED: ${String(en.error).slice(0, 400)}`);
1846
- const seed = await A("seedBirthAttestation", {
2257
+ const seed = await preWarrant("seedBirthAttestation", {
1847
2258
  child: platform,
1848
- founder: OPERATOR,
2259
+ founder: foundingPrincipal,
1849
2260
  verified: "true",
1850
2261
  parentId: "root",
1851
2262
  parentKey: sP.public,
@@ -1853,13 +2264,21 @@ async function bootstrapPlatform(dev, opts) {
1853
2264
  certChain
1854
2265
  });
1855
2266
  if (!seed.ok) throw new Error(`platform BirthAttestation seed REFUSED: ${String(seed.error).slice(0, 400)}`);
1856
- const warrant = await A("seedGenesis", {
1857
- principal: OPERATOR,
2267
+ const enrolled = await preWarrant("enrollSigner", {
2268
+ principal: foundingPrincipal,
2269
+ keyHash: opKeyHash,
2270
+ grantedBy: "root",
2271
+ grantedAt: Date.now()
2272
+ });
2273
+ if (!enrolled.ok) throw new Error(`platform founding signer enrollment REFUSED: ${String(enrolled.error).slice(0, 400)}`);
2274
+ const warrant = await signed("seedGenesis", {
2275
+ principal: foundingPrincipal,
1858
2276
  workspaceId: platform,
1859
2277
  bornAt: (/* @__PURE__ */ new Date()).toISOString()
1860
2278
  });
1861
2279
  if (!warrant.ok) throw new Error(`platform WARRANT (seedGenesis) REFUSED: ${String(warrant.error).slice(0, 400)}`);
1862
2280
  dev.operatorDevice = sOp;
2281
+ dev.operatorPrincipal = foundingPrincipal;
1863
2282
  if (pendingIdP) {
1864
2283
  const ap = await serialize(async () => authorOn(
1865
2284
  eng,
@@ -1869,7 +2288,7 @@ async function bootstrapPlatform(dev, opts) {
1869
2288
  "setAuthProvider",
1870
2289
  pendingIdP.apPayload,
1871
2290
  lawHash,
1872
- { actor: OPERATOR, principalVerified: true, authorSecret: sOp.secret }
2291
+ { actor: foundingPrincipal, authorSecret: sOp.secret }
1873
2292
  ));
1874
2293
  if (ap.ok) {
1875
2294
  devIdP = { issuer: pendingIdP.ISS, audience: pendingIdP.AUD, jwks: pendingIdP.JWKS, mint: pendingIdP.mint };
@@ -1879,7 +2298,7 @@ async function bootstrapPlatform(dev, opts) {
1879
2298
  }
1880
2299
  }
1881
2300
  dev.testIdP = devIdP;
1882
- 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})`);
2301
+ log2(`root-attested platform: founding key ${opKeyHash.slice(0, 12)}\u2026 signed GenesisWarrant, seeded BirthAttestation (platform_cert signed by K_root, P_P=${sP.public.slice(0, 12)}\u2026), WARRANTED (self-id ${platform})`);
1883
2302
  log2(" a birthHome under this platform now assembles [home_cert, u_delegation(S_P), platform_cert(K_root)] \u2014 no unwarranted-cert.");
1884
2303
  log2(" ENROLL each user via the warranted lane: enrollFirstDevice (AuthProvider) or enrollDelegation (S_P-signed cert).");
1885
2304
  dev.testKRoot = kRoot;
@@ -1889,35 +2308,56 @@ async function bootstrapPlatform(dev, opts) {
1889
2308
  dev.homeDomain = homeDomain;
1890
2309
  }
1891
2310
  }
1892
- const deployPaths = deployPathsOf(opts);
1893
- if (deployPaths.length > 0) {
2311
+ const rolloutLaws = lawInputs.slice(1);
2312
+ if (rolloutLaws.length > 0) {
1894
2313
  const founderDevice = dev.operatorDevice;
1895
2314
  if (!founderDevice) throw new Error("platform law deploy needs the warranted founder device established by bootstrap");
1896
- for (const deployPath of deployPaths) {
1897
- const body = JSON.parse(readFileSync(deployPath, "utf8"));
1898
- const usda = body.packageUsda || body.usda;
1899
- if (!usda) throw new Error(`--deploy ${deployPath} has no packageUsda (nothing to install)`);
2315
+ for (const inputPath of rolloutLaws) {
2316
+ if (!inputPath.endsWith(".law.usdz")) {
2317
+ throw new Error(`--law requires a canonical .law.usdz archive, received ${inputPath}`);
2318
+ }
2319
+ const lawUsdz = new Uint8Array(readFileSync(inputPath));
2320
+ const info = stageLawClosure(eng, lawUsdz, path.basename(inputPath));
2321
+ const domainHash = String(info.identity || "");
2322
+ if (!/^[0-9a-f]{64}$/.test(domainHash)) {
2323
+ throw new Error(`kernel did not derive a valid law identity for ${inputPath}`);
2324
+ }
2325
+ (dev.deployedLawIdentities ??= []).push(domainHash);
1900
2326
  const deployErr = await serialize(async () => {
1901
2327
  const ledger = ledgerFor(platform);
1902
- const domainHash = await sha256hex(usda);
1903
2328
  try {
1904
- const out = await deploy(eng, platform, ledger, usda, domainHash, body.dispositions || null, {
1905
- actor: "user:dev-operator",
1906
- authorSecret: founderDevice.secret
1907
- });
2329
+ const current = currentLaw(eng, platform);
2330
+ const tenantPredecessors = [...new Set(Object.values(current).filter(
2331
+ (hash) => hash !== eng.hashes.bootstrap && hash !== eng.hashes.nomos
2332
+ ))];
2333
+ if (tenantPredecessors.length > 1) {
2334
+ throw new Error(`bootstrap fixture serves ${tenantPredecessors.length} tenant models; refusing to guess a lifecycle predecessor`);
2335
+ }
2336
+ const supersedes = tenantPredecessors[0];
2337
+ const directiveId = supersedes ? "stageDomain" : "installDomain";
2338
+ const out = await authorOn(
2339
+ eng,
2340
+ platform,
2341
+ ledger,
2342
+ "nomos",
2343
+ directiveId,
2344
+ closureInstallPayload(domainHash, "dev-bootstrap", supersedes ? { supersedes } : {}),
2345
+ eng.hashes.nomos,
2346
+ { actor: dev.operatorPrincipal || "", authorSecret: founderDevice.secret, lawUsdz }
2347
+ );
1908
2348
  if (out && out.ok === false) return String(out.error || "the law refused the platform package");
1909
2349
  log2(
1910
- out.staged === true ? `application payload staged for child birth: ${domainHash.slice(0, 12)} (head ${String(out.head).slice(0, 12)})` : `platform law deployed: ${domainHash.slice(0, 12)} (head ${String(out.head).slice(0, 12)})`
2350
+ supersedes !== void 0 ? `application payload staged for child birth: ${domainHash.slice(0, 12)} (head ${String(out.head).slice(0, 12)})` : `platform law deployed: ${domainHash.slice(0, 12)} (head ${String(out.head).slice(0, 12)})`
1911
2351
  );
1912
2352
  return null;
1913
2353
  } catch (e) {
1914
2354
  return errStack(e);
1915
2355
  }
1916
2356
  });
1917
- if (deployErr) throw new Error(`platform law deploy REFUSED (${deployPath}): ${deployErr.slice(0, 400)}`);
2357
+ if (deployErr) throw new Error(`platform law deploy REFUSED (${inputPath}): ${deployErr.slice(0, 400)}`);
1918
2358
  }
1919
- } else {
1920
- log2("no --deploy given; platform runs framework law only (deploy your platform package to enable births)");
2359
+ } else if (lawInputs.length === 0) {
2360
+ log2("no application root law was supplied; the framework-only platform cannot establish a private home authority");
1921
2361
  }
1922
2362
  if (opts.authProvider || opts.firebaseProject) {
1923
2363
  log2(`AuthProvider: ${opts.authProvider || `firebase:${opts.firebaseProject}`} \u2014 register it via the platform's setAuthProvider governance offer;`);
@@ -1927,7 +2367,7 @@ async function bootstrapPlatform(dev, opts) {
1927
2367
  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).");
1928
2368
  return { platform, testMint, attested };
1929
2369
  }
1930
- var log2, FRAMEWORK_HOME_DOMAIN, deployPathsOf, homeDeployPathOf;
2370
+ var log2, FRAMEWORK_HOME_DOMAIN, lawInputsOf;
1931
2371
  var init_bootstrap = __esm({
1932
2372
  "../cloud/dev-server/bootstrap.ts"() {
1933
2373
  "use strict";
@@ -1935,8 +2375,7 @@ var init_bootstrap = __esm({
1935
2375
  init_types();
1936
2376
  log2 = (m) => console.log(`[bootstrap] ${m}`);
1937
2377
  FRAMEWORK_HOME_DOMAIN = "__nomos_application_home_v1";
1938
- deployPathsOf = (opts) => opts.deploys && opts.deploys.length > 0 ? [...opts.deploys] : opts.deploy ? [opts.deploy] : [];
1939
- homeDeployPathOf = (opts) => deployPathsOf(opts).at(-1);
2378
+ lawInputsOf = (opts) => opts.lawUsdzs && opts.lawUsdzs.length > 0 ? [...opts.lawUsdzs] : opts.lawUsdz ? [opts.lawUsdz] : [];
1940
2379
  }
1941
2380
  });
1942
2381
 
@@ -1947,7 +2386,7 @@ import http from "node:http";
1947
2386
  import { createHash as createHash2, randomBytes } from "node:crypto";
1948
2387
  import { readFileSync as readFileSync2, writeFileSync, existsSync as existsSync2, mkdirSync as mkdirSync2, mkdtempSync } from "node:fs";
1949
2388
  import { fileURLToPath } from "node:url";
1950
- import path from "node:path";
2389
+ import path2 from "node:path";
1951
2390
  import os from "node:os";
1952
2391
 
1953
2392
  // ../adapter/pack_auth_contract.ts
@@ -1983,13 +2422,13 @@ function bulkReadForbidden(ws, kind, verdict) {
1983
2422
  }
1984
2423
 
1985
2424
  // ../cloud/cloudflare-shell/src/gateway-route-resolver.ts
1986
- function aliasIdsFor(x, path2) {
2425
+ function aliasIdsFor(x, path3) {
1987
2426
  const ids = [];
1988
2427
  for (const key of ["directiveId", "queryId", "countId", "sumId", "extremumId", "spatialId"]) {
1989
2428
  const value = x && x[key];
1990
2429
  if (typeof value === "string" && value) ids.push(value);
1991
2430
  }
1992
- const leaf = String(path2 || "").replace(/^\/+/, "").split("/").filter(Boolean).at(-1);
2431
+ const leaf = String(path3 || "").replace(/^\/+/, "").split("/").filter(Boolean).at(-1);
1993
2432
  if (leaf) ids.push(leaf);
1994
2433
  return new Set(ids);
1995
2434
  }
@@ -2011,11 +2450,11 @@ function resolveGatewayOperation(spec, opName, method) {
2011
2450
  const requestedAlias = String(opName).slice(slash + 1);
2012
2451
  const matches2 = [];
2013
2452
  for (const paths of routeTables) {
2014
- for (const [path2, methods] of Object.entries(paths)) {
2453
+ for (const [path3, methods] of Object.entries(paths)) {
2015
2454
  const op = methods?.[normalizedMethod];
2016
2455
  const x = op?.["x-nomos"];
2017
2456
  if (!op || !x || x.domain !== requestedDomain) continue;
2018
- if (aliasIdsFor(x, path2).has(requestedAlias)) matches2.push({ op, path: path2 });
2457
+ if (aliasIdsFor(x, path3).has(requestedAlias)) matches2.push({ op, path: path3 });
2019
2458
  }
2020
2459
  }
2021
2460
  if (matches2.length === 1) return { ...matches2[0], ambiguous: null };
@@ -2024,11 +2463,11 @@ function resolveGatewayOperation(spec, opName, method) {
2024
2463
  }
2025
2464
  const matches = [];
2026
2465
  for (const paths of routeTables) {
2027
- for (const [path2, methods] of Object.entries(paths)) {
2466
+ for (const [path3, methods] of Object.entries(paths)) {
2028
2467
  const op = methods?.[normalizedMethod];
2029
2468
  const x = op?.["x-nomos"];
2030
2469
  if (!op || !x) continue;
2031
- if (aliasIdsFor(x, path2).has(opName)) matches.push({ op, path: path2 });
2470
+ if (aliasIdsFor(x, path3).has(opName)) matches.push({ op, path: path3 });
2032
2471
  }
2033
2472
  }
2034
2473
  if (matches.length === 1) return { ...matches[0], ambiguous: null };
@@ -2040,8 +2479,8 @@ function resolveGatewayOperation(spec, opName, method) {
2040
2479
 
2041
2480
  // ../cloud/cloudflare-shell/src/kernel-registry.generated.ts
2042
2481
  var DEPLOYED_KERNELS = [
2043
- { prefix: "bc52f7eb", hash: "bc52f7eb630bc5a9a03b4c62b9b7ab58c4b6f25e687ecd51c72f9251763593fc", version: "kernel-bc52f7eb", note: "production (this candidate)", features: ["compoundKeys", "capturedReads", "invariantGate", "surfacedMerge", "fieldProvenance", "nullSemantics", "attestedReads", "conflictSnapshots", "ownedAudience"] },
2044
- { prefix: "17d8f91b", hash: "17d8f91b661dc8c3a6dea72d699f9f5759ab5e6b4e3e3e5e90afceb3a7034154", version: "kernel-17d8f91b", note: "test-mint (this candidate) \u2014 feature-equivalent to production", features: ["compoundKeys", "capturedReads", "invariantGate", "surfacedMerge", "fieldProvenance", "nullSemantics", "attestedReads", "conflictSnapshots", "ownedAudience"] }
2482
+ { prefix: "efe619cb", hash: "efe619cbabba8f5d9d1a1309e7ab60feb489ddb4794ce5a6a95f35c7e7ae5928", version: "kernel-efe619cb", note: "production (this candidate)", features: ["compoundKeys", "capturedReads", "invariantGate", "surfacedMerge", "fieldProvenance", "nullSemantics", "attestedReads", "conflictSnapshots", "ownedAudience"] },
2483
+ { prefix: "0a801b8f", hash: "0a801b8f40a17d3a1534d1452f0dc990f160299f6db55fe9c0c39d7aa726730b", version: "kernel-0a801b8f", note: "test-mint (this candidate) \u2014 feature-equivalent to production", features: ["compoundKeys", "capturedReads", "invariantGate", "surfacedMerge", "fieldProvenance", "nullSemantics", "attestedReads", "conflictSnapshots", "ownedAudience"] }
2045
2484
  ];
2046
2485
 
2047
2486
  // ../cloud/cloudflare-shell/src/staged-intents.ts
@@ -2081,7 +2520,7 @@ async function resolveStagedIntent(bucket, ref) {
2081
2520
  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` };
2082
2521
  const got = await sha256hexBytes(bytes);
2083
2522
  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` };
2084
- return { ok: true, intentB64: b64OfBytes(bytes), sha256, size: bytes.length };
2523
+ return { ok: true, changeB64: b64OfBytes(bytes), sha256, size: bytes.length };
2085
2524
  }
2086
2525
 
2087
2526
  // ../cloud/dev-server/custody.ts
@@ -2218,8 +2657,8 @@ function receivePackCommands(raw) {
2218
2657
 
2219
2658
  // ../cloud/dev-server/server.ts
2220
2659
  init_types();
2221
- var DIR = path.dirname(fileURLToPath(import.meta.url));
2222
- var REPO_ROOT = path.resolve(DIR, "../..");
2660
+ var DIR = path2.dirname(fileURLToPath(import.meta.url));
2661
+ var REPO_ROOT = path2.resolve(DIR, "../..");
2223
2662
  var RECOGNIZED_UNSUPPORTED = /* @__PURE__ */ new Set([
2224
2663
  "container-status",
2225
2664
  "recycle-container",
@@ -2233,7 +2672,6 @@ var RECOGNIZED_UNSUPPORTED = /* @__PURE__ */ new Set([
2233
2672
  "git-read-lease",
2234
2673
  "poke-admit",
2235
2674
  "clear-checkpoint",
2236
- "domain-package",
2237
2675
  "capabilities"
2238
2676
  ]);
2239
2677
  var UNSUPPORTED_WHY = {
@@ -2258,7 +2696,7 @@ globalThis.fetch = (input, init) => {
2258
2696
  };
2259
2697
  var unb64 = (s) => new Uint8Array(Buffer.from(s, "base64"));
2260
2698
  function configDir() {
2261
- return process.env.HOLON_CONFIG_DIR || path.join(os.homedir(), ".holon");
2699
+ return process.env.HOLON_CONFIG_DIR || path2.join(os.homedir(), ".holon");
2262
2700
  }
2263
2701
  function explicitRuntimeDir() {
2264
2702
  if (process.env.NOMOS_CANDIDATE_RUNTIME) {
@@ -2270,7 +2708,7 @@ function explicitRuntimeDir() {
2270
2708
  return null;
2271
2709
  }
2272
2710
  function selectedRuntimeDir() {
2273
- return explicitRuntimeDir()?.dir ?? path.join(configDir(), "runtime");
2711
+ return explicitRuntimeDir()?.dir ?? path2.join(configDir(), "runtime");
2274
2712
  }
2275
2713
  function firstExisting(...paths) {
2276
2714
  for (const p of paths) {
@@ -2279,7 +2717,11 @@ function firstExisting(...paths) {
2279
2717
  return null;
2280
2718
  }
2281
2719
  var TEST_MINT_MARKER = Buffer.from("set_test_k_root");
2282
- var isTestMintBytes = (bytes) => bytes.includes(TEST_MINT_MARKER);
2720
+ var isTestMintBytes = (bytes) => {
2721
+ if (bytes.includes(TEST_MINT_MARKER)) return true;
2722
+ const sha = createHash2("sha256").update(bytes).digest("hex");
2723
+ return DEPLOYED_KERNELS.some((entry) => entry.hash === sha && /test-mint/i.test(entry.note));
2724
+ };
2283
2725
  var HISTORICAL_KERNEL_CAPABILITY_REGISTRY = [
2284
2726
  {
2285
2727
  prefix: "f50d0cc5",
@@ -2315,11 +2757,11 @@ function capabilitiesForKernelHash(hash) {
2315
2757
  const hit = KERNEL_CAPABILITY_REGISTRY.find((e) => h.startsWith(e.prefix) || e.prefix.startsWith(h.slice(0, 8)));
2316
2758
  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 };
2317
2759
  }
2318
- var DEFAULT_KERNEL_SOURCE = "https://nomos.captainapp.co.uk";
2760
+ var DEFAULT_KERNEL_SOURCE = "https://nomos.cafe";
2319
2761
  async function resolveTestMintWasm(kernelSource) {
2320
2762
  const explicitRuntime = explicitRuntimeDir();
2321
2763
  const runtimeCache = selectedRuntimeDir();
2322
- const cachePath = path.join(runtimeCache, "holon-testmint.wasm");
2764
+ const cachePath = path2.join(runtimeCache, "holon-testmint.wasm");
2323
2765
  if (explicitRuntime) {
2324
2766
  if (existsSync2(cachePath)) {
2325
2767
  const bytes = readFileSync2(cachePath);
@@ -2338,7 +2780,7 @@ async function resolveTestMintWasm(kernelSource) {
2338
2780
  const bytes = readFileSync2(local);
2339
2781
  if (isTestMintBytes(bytes)) return { wasmPath: local, wasmBytes: bytes, kernelKind: "test-mint", kernelSource: "NOMOS_LOCAL_WASM" };
2340
2782
  }
2341
- const bundled = path.join(DIR, "kernel-testmint.wasm");
2783
+ const bundled = path2.join(DIR, "kernel-testmint.wasm");
2342
2784
  if (!explicitRuntime && existsSync2(bundled)) {
2343
2785
  const bytes = readFileSync2(bundled);
2344
2786
  if (isTestMintBytes(bytes)) return { wasmPath: bundled, wasmBytes: bytes, kernelKind: "test-mint", kernelSource: "bundled" };
@@ -2372,17 +2814,17 @@ async function resolveTestMintWasm(kernelSource) {
2372
2814
  async function loadRuntime(opts = {}) {
2373
2815
  const explicitRuntime = explicitRuntimeDir();
2374
2816
  const runtimeCache = selectedRuntimeDir();
2375
- const repoDomainsDir = path.join(REPO_ROOT, "cloud/cloudflare-shell/container/domains");
2376
- const vendoredFrameworkDir = path.join(DIR, "framework");
2817
+ const repoDomainsDir = path2.join(REPO_ROOT, "cloud/cloudflare-shell/domains");
2818
+ const vendoredFrameworkDir = path2.join(DIR, "framework");
2377
2819
  let wasmPath, wasmBytes, kernelKind, kernelSource;
2378
2820
  if (opts.attested) {
2379
2821
  ({ wasmPath, wasmBytes, kernelKind, kernelSource } = await resolveTestMintWasm(opts.kernelSource));
2380
2822
  } else {
2381
2823
  wasmPath = firstExisting(
2382
- explicitRuntime ? path.join(runtimeCache, "holon.wasm") : null,
2824
+ explicitRuntime ? path2.join(runtimeCache, "holon.wasm") : null,
2383
2825
  explicitRuntime ? null : process.env.NOMOS_LOCAL_WASM,
2384
- explicitRuntime ? null : path.join(REPO_ROOT, "cloud/cloudflare-shell/container/vendor/wasm_git_holon.wasm"),
2385
- explicitRuntime ? null : path.join(runtimeCache, "holon.wasm")
2826
+ explicitRuntime ? null : path2.join(REPO_ROOT, "cloud/cloudflare-shell/container/vendor/wasm_git_holon.wasm"),
2827
+ explicitRuntime ? null : path2.join(runtimeCache, "holon.wasm")
2386
2828
  );
2387
2829
  if (!wasmPath) {
2388
2830
  throw new Error(
@@ -2393,36 +2835,31 @@ async function loadRuntime(opts = {}) {
2393
2835
  kernelKind = isTestMintBytes(wasmBytes) ? "test-mint" : "production";
2394
2836
  kernelSource = wasmPath === process.env.NOMOS_LOCAL_WASM ? "NOMOS_LOCAL_WASM" : wasmPath.startsWith(runtimeCache) ? "cache" : "repo-vendor";
2395
2837
  }
2396
- const repoBootstrap = firstExisting(path.join(repoDomainsDir, "domain_bootstrap.package.usda"));
2397
- const repoNomos = firstExisting(path.join(repoDomainsDir, "domain_nomos.package.usda"));
2398
- let bootstrapPkg, nomosPkg;
2399
- const explicitPackages = explicitRuntime ? path.join(runtimeCache, "packages.json") : null;
2400
- if (explicitPackages && existsSync2(explicitPackages)) {
2401
- const pkgs = JSON.parse(readFileSync2(explicitPackages, "utf8"));
2402
- bootstrapPkg = pkgs.bootstrap;
2403
- nomosPkg = pkgs.nomos;
2838
+ const repoBootstrap = firstExisting(path2.join(repoDomainsDir, "build/bootstrap/domain_bootstrap.law.usdz"));
2839
+ const repoNomos = firstExisting(path2.join(repoDomainsDir, "build/nomos/nomos.law.usdz"));
2840
+ const explicitBootstrap = explicitRuntime ? path2.join(runtimeCache, "bootstrap.law.usdz") : null;
2841
+ const explicitNomos = explicitRuntime ? path2.join(runtimeCache, "nomos.law.usdz") : null;
2842
+ let bootstrapLawUsdz;
2843
+ let nomosLawUsdz;
2844
+ if (explicitBootstrap && explicitNomos && existsSync2(explicitBootstrap) && existsSync2(explicitNomos)) {
2845
+ bootstrapLawUsdz = new Uint8Array(readFileSync2(explicitBootstrap));
2846
+ nomosLawUsdz = new Uint8Array(readFileSync2(explicitNomos));
2404
2847
  } else if (explicitRuntime) {
2405
2848
  throw new Error(
2406
- `explicit runtime is missing framework packages at ${explicitPackages}; hydrate that exact runtime bundle before starting the local Nomos cloud`
2849
+ `explicit runtime is missing bootstrap.law.usdz or nomos.law.usdz in ${runtimeCache}; hydrate that exact runtime bundle before starting the local Nomos cloud`
2407
2850
  );
2408
2851
  } else if (repoBootstrap && repoNomos) {
2409
- bootstrapPkg = readFileSync2(repoBootstrap, "utf8");
2410
- nomosPkg = readFileSync2(repoNomos, "utf8");
2411
- } else if (existsSync2(path.join(vendoredFrameworkDir, "domain_bootstrap.package.usda"))) {
2412
- bootstrapPkg = readFileSync2(path.join(vendoredFrameworkDir, "domain_bootstrap.package.usda"), "utf8");
2413
- nomosPkg = readFileSync2(path.join(vendoredFrameworkDir, "domain_nomos.package.usda"), "utf8");
2852
+ bootstrapLawUsdz = new Uint8Array(readFileSync2(repoBootstrap));
2853
+ nomosLawUsdz = new Uint8Array(readFileSync2(repoNomos));
2854
+ } else if (existsSync2(path2.join(vendoredFrameworkDir, "bootstrap.law.usdz")) && existsSync2(path2.join(vendoredFrameworkDir, "nomos.law.usdz"))) {
2855
+ bootstrapLawUsdz = new Uint8Array(readFileSync2(path2.join(vendoredFrameworkDir, "bootstrap.law.usdz")));
2856
+ nomosLawUsdz = new Uint8Array(readFileSync2(path2.join(vendoredFrameworkDir, "nomos.law.usdz")));
2414
2857
  } else {
2415
- const pkgsCache = path.join(runtimeCache, "packages.json");
2416
- if (!existsSync2(pkgsCache)) {
2417
- throw new Error(
2418
- "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."
2419
- );
2420
- }
2421
- const pkgs = JSON.parse(readFileSync2(pkgsCache, "utf8"));
2422
- bootstrapPkg = pkgs.bootstrap;
2423
- nomosPkg = pkgs.nomos;
2858
+ throw new Error(
2859
+ "no framework USDA closures found (bootstrap.law.usdz and nomos.law.usdz); compile the framework law before starting the dev cloud"
2860
+ );
2424
2861
  }
2425
- return { wasmPath, wasmBytes, bootstrapPkg, nomosPkg, kernelKind, kernelSource };
2862
+ return { wasmPath, wasmBytes, bootstrapLawUsdz, nomosLawUsdz, kernelKind, kernelSource };
2426
2863
  }
2427
2864
  async function startDevCloud(opts = {}) {
2428
2865
  let devSelf = null;
@@ -2430,10 +2867,10 @@ async function startDevCloud(opts = {}) {
2430
2867
  const host = opts.host || "127.0.0.1";
2431
2868
  const origin = `http://${host}:${port}`;
2432
2869
  const ephemeral = !!opts.ephemeral;
2433
- const dataDir = ephemeral ? mkdtempSync(path.join(os.tmpdir(), "nomos-dev-cloud-")) : path.resolve(opts.data || ".nomos/dev-cloud");
2870
+ const dataDir = ephemeral ? mkdtempSync(path2.join(os.tmpdir(), "nomos-dev-cloud-")) : path2.resolve(opts.data || ".nomos/dev-cloud");
2434
2871
  mkdirSync2(dataDir, { recursive: true });
2435
2872
  const attested = !!(opts.attested || opts.bootstrap || opts.platform);
2436
- const { wasmPath, wasmBytes, bootstrapPkg, nomosPkg, kernelKind, kernelSource } = await loadRuntime({ attested, kernelSource: opts.kernelSource });
2873
+ const { wasmPath, wasmBytes, bootstrapLawUsdz, nomosLawUsdz, kernelKind, kernelSource } = await loadRuntime({ attested, kernelSource: opts.kernelSource });
2437
2874
  console.log(`[dev-cloud] kernel : ${kernelKind} (from ${kernelSource})`);
2438
2875
  const wasmModule = await WebAssembly.compile(wasmBytes);
2439
2876
  const kernelSha = createHash2("sha256").update(wasmBytes).digest("hex");
@@ -2442,7 +2879,7 @@ async function startDevCloud(opts = {}) {
2442
2879
  let replica = 0n;
2443
2880
  for (let i = 0; i < 8; i++) replica = replica << 8n | BigInt(replicaDigest[i]);
2444
2881
  replica &= (1n << 63n) - 1n;
2445
- const eng = await createEngine({ wasmModule, bootstrapPkg, nomosPkg, replica, installedBy: "nomos-cloud-dev" });
2882
+ const eng = await createEngine({ wasmModule, bootstrapLawUsdz, nomosLawUsdz, replica, installedBy: "nomos-cloud-dev" });
2446
2883
  const custody = new FilesystemGitCustody(dataDir, origin);
2447
2884
  const stagedBytes = /* @__PURE__ */ new Map();
2448
2885
  const stageBucket = {
@@ -2517,12 +2954,17 @@ async function startDevCloud(opts = {}) {
2517
2954
  req.on("data", (c) => chunks.push(c));
2518
2955
  req.on("end", () => resolve(Buffer.concat(chunks)));
2519
2956
  });
2520
- const principalOf = (req) => String(req.headers["x-nomos-principal"] || "").slice(0, 128);
2957
+ const claimedPrincipalOf = (req) => String(req.headers["x-nomos-principal"] || "").slice(0, 128);
2521
2958
  const authTokenOf = (req) => String(req.headers["x-nomos-auth"] || "").replace(/^Bearer\s+/i, "");
2522
2959
  const postureGate = (res, ws, req, kind) => {
2960
+ if (process.env.NOMOS_TEST_DIAGNOSTICS === "1") {
2961
+ console.error(
2962
+ `[dev-cloud] read-posture request ${ws} ${kind} auth-bytes=${authTokenOf(req).length} principal=${claimedPrincipalOf(req) || "(none)"}`
2963
+ );
2964
+ }
2523
2965
  let posture;
2524
2966
  try {
2525
- posture = readPosture(eng, ws, principalOf(req), authTokenOf(req), Math.floor(Date.now() / 1e3));
2967
+ posture = readPosture(eng, ws, claimedPrincipalOf(req), authTokenOf(req), Math.floor(Date.now() / 1e3));
2526
2968
  } catch {
2527
2969
  return false;
2528
2970
  }
@@ -2541,25 +2983,41 @@ async function startDevCloud(opts = {}) {
2541
2983
  const x = o;
2542
2984
  return String(x && x["x-nomos"] && x["x-nomos"].domain ? x["x-nomos"].domain : "domain");
2543
2985
  };
2544
- const mergeInto = (frag) => {
2986
+ const mergeInto = (frag, target = merged.paths) => {
2545
2987
  for (const [p, methods] of Object.entries(frag.paths || {})) {
2546
2988
  for (const [m, op] of Object.entries(methods)) {
2547
- const existing = merged.paths[p] && merged.paths[p][m];
2989
+ const existing = target[p] && target[p][m];
2548
2990
  if (existing === void 0) {
2549
- (merged.paths[p] ||= {})[m] = op;
2991
+ (target[p] ||= {})[m] = op;
2550
2992
  } else if (JSON.stringify(existing) !== JSON.stringify(op)) {
2551
- (merged.paths[`/${domOf(existing)}${p}`] ||= {})[m] = existing;
2552
- (merged.paths[`/${domOf(op)}${p}`] ||= {})[m] = op;
2553
- delete merged.paths[p][m];
2554
- if (Object.keys(merged.paths[p]).length === 0) delete merged.paths[p];
2993
+ (target[`/${domOf(existing)}${p}`] ||= {})[m] = existing;
2994
+ (target[`/${domOf(op)}${p}`] ||= {})[m] = op;
2995
+ delete target[p][m];
2996
+ if (Object.keys(target[p]).length === 0) delete target[p];
2555
2997
  }
2556
2998
  }
2557
2999
  }
2558
3000
  };
2559
3001
  try {
2560
3002
  const spec = describe(eng, ws);
3003
+ if (process.env.NOMOS_TEST_DIAGNOSTICS === "1") {
3004
+ console.error(
3005
+ `[dev-cloud] describe ${ws} paths=${JSON.stringify(Object.keys(spec?.paths ?? {}))} described=${JSON.stringify(spec?.["x-nomos-described"] ?? [])}`
3006
+ );
3007
+ }
2561
3008
  if (spec && spec.paths) mergeInto(spec);
2562
- } catch {
3009
+ const frameworkPaths = spec?.["x-nomos-framework-routes"]?.paths;
3010
+ if (frameworkPaths && Object.keys(frameworkPaths).length > 0) {
3011
+ const framework = merged["x-nomos-framework-routes"] ??= { paths: {} };
3012
+ mergeInto({ paths: frameworkPaths }, framework.paths);
3013
+ }
3014
+ if (Object.keys(spec?.paths ?? {}).length === 0 && Object.keys(frameworkPaths ?? {}).length === 0) {
3015
+ console.error(
3016
+ `[dev-cloud] describe '${ws}' returned no law routes; installed=${JSON.stringify(installedLaw(eng, ws)).slice(0, 2e3)}`
3017
+ );
3018
+ }
3019
+ } catch (error) {
3020
+ console.error(`[dev-cloud] describe '${ws}' failed: ${error instanceof Error ? error.message : String(error)}`);
2563
3021
  }
2564
3022
  merged.paths["/openapi.json"] = {
2565
3023
  get: { operationId: "nomos__openapi", summary: "this workspace's live OpenAPI", responses: { "200": { description: "ok" } } }
@@ -2645,8 +3103,15 @@ async function startDevCloud(opts = {}) {
2645
3103
  vocabulary: KERNEL_CAPABILITY_REGISTRY.flatMap((e) => e.features).filter((f, i, a) => a.indexOf(f) === i).sort()
2646
3104
  });
2647
3105
  }
2648
- if (url.pathname === "/v1/runtime/packages") {
2649
- return sendJson(res, { bootstrap: bootstrapPkg, nomos: nomosPkg });
3106
+ if (url.pathname === "/v1/runtime/bootstrap.law.usdz") {
3107
+ res.writeHead(200, { "content-type": "model/vnd.usdz+zip", "cache-control": "public, max-age=31536000, immutable" });
3108
+ res.end(bootstrapLawUsdz);
3109
+ return;
3110
+ }
3111
+ if (url.pathname === "/v1/runtime/nomos.law.usdz") {
3112
+ res.writeHead(200, { "content-type": "model/vnd.usdz+zip", "cache-control": "public, max-age=31536000, immutable" });
3113
+ res.end(nomosLawUsdz);
3114
+ return;
2650
3115
  }
2651
3116
  {
2652
3117
  const m = url.pathname.match(/^\/v2\/stage\/([0-9a-f]{64})$/);
@@ -2720,59 +3185,12 @@ async function startDevCloud(opts = {}) {
2720
3185
  });
2721
3186
  }
2722
3187
  if (req.method === "POST") {
2723
- const raw = await readBody(req);
2724
- return await serialize(async () => {
2725
- const ledger = ledgerFor(ws);
2726
- await mountWorkspace(eng, ws, ledger);
2727
- if (!nomosActive(eng, ws)) return sendJson(res, { ok: false, error: `workspace '${ws}' is not initialized \u2014 POST /v2/workspaces/${ws} first` }, 409);
2728
- let usda, dispositions = null;
2729
- const text = raw.toString("utf8");
2730
- if (text.trimStart().startsWith("#usda")) {
2731
- usda = text;
2732
- } else {
2733
- const body = JSON.parse(text || "{}");
2734
- usda = body.packageUsda || body.usda;
2735
- dispositions = body.dispositions || null;
2736
- }
2737
- if (!usda) return sendJson(res, { ok: false, error: "deploy body must be raw #usda or JSON with packageUsda" }, 400);
2738
- const domainHash = await sha256hex(usda);
2739
- const dryRun = url.searchParams.get("dryRun");
2740
- if (dryRun === "evolve") {
2741
- const verdict = evolveDryRun(eng, ws, usda, domainHash, dispositions);
2742
- return sendJson(res, { ok: true, dryRun: "evolve", verdict });
2743
- }
2744
- if (dryRun) return sendJson(res, { ok: true, dryRun: true, wouldInstall: domainHash, bytes: usda.length });
2745
- const actor = principalOf(req);
2746
- const authToken = authTokenOf(req);
2747
- try {
2748
- const out = await deploy(eng, ws, ledger, usda, domainHash, dispositions, { actor, ...authToken ? { authToken } : {} });
2749
- sendJson(res, {
2750
- ok: true,
2751
- ws,
2752
- domainHash,
2753
- head: out.head,
2754
- installation: out.installation,
2755
- staged: out.staged === true,
2756
- ...out.supersedes ? { supersedes: out.supersedes } : {},
2757
- ...out.alreadyInstalled ? { alreadyInstalled: true } : {}
2758
- }, 201);
2759
- } catch (e) {
2760
- const msg = errMsg(e);
2761
- const status = /deploy-did-not-advance|deploy-did-not-stage|deploy-predecessor|deploy-activated-candidate/.test(msg) ? 409 : 422;
2762
- sendJson(res, { ok: false, refused: true, error: msg.slice(0, 600) }, status);
2763
- }
2764
- });
3188
+ return sendJson(res, {
3189
+ ok: false,
3190
+ error: "raw law deployment is retired: author installDomain/stageDomain locally as an ordinary signed offer, push its opaque candidate custody, then request admission"
3191
+ }, 410);
2765
3192
  }
2766
3193
  }
2767
- if (sub[0] === "domains" && sub.length === 3 && sub[2] === "package.usda") {
2768
- return await serialize(async () => {
2769
- await mountWorkspace(eng, ws, ledgerFor(ws));
2770
- const pkg = domainPackage(eng, ws, sub[1]);
2771
- if (!pkg || !pkg.usda) return sendJson(res, { ok: false, error: "no such package" }, 404);
2772
- res.writeHead(200, { "content-type": "text/plain", ...CORS });
2773
- res.end(pkg.usda);
2774
- });
2775
- }
2776
3194
  if (sub[0] === "openapi.json" && req.method === "GET") {
2777
3195
  return await serialize(async () => {
2778
3196
  await mountWorkspace(eng, ws, ledgerFor(ws));
@@ -2803,7 +3221,7 @@ async function startDevCloud(opts = {}) {
2803
3221
  await mountWorkspace(eng, ws, ledger);
2804
3222
  const body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
2805
3223
  const offers = Array.isArray(body.offers) ? body.offers.slice(0, 100) : [];
2806
- if (!offers.length) return sendJson(res, { ok: false, error: "body must be { offers:[{session, oid, intentB64}] }" }, 400);
3224
+ if (!offers.length) return sendJson(res, { ok: false, error: "body must be { offers:[{session, oid, changeB64}] }" }, 400);
2807
3225
  const clientBase = /^[0-9a-f]{40}$/i.test(body.base || "") ? body.base : null;
2808
3226
  const out = await admitIntentOffers(eng, ws, ledger, offers, { ...clientBase ? { clientBase } : {} });
2809
3227
  if (Array.isArray(out.born) && out.born.length) await persistBorn(out.born);
@@ -2843,12 +3261,12 @@ async function startDevCloud(opts = {}) {
2843
3261
  const retried = [], failed = [];
2844
3262
  for (const e of refs) {
2845
3263
  if (only && e.offerId !== only && e.oid !== only) continue;
2846
- if (!e.intentB64) {
3264
+ if (!e.changeB64) {
2847
3265
  failed.push({ intentId: e.offerId, error: "refused ref carries no intent bytes" });
2848
3266
  continue;
2849
3267
  }
2850
3268
  try {
2851
- const r2 = offerAdmit(eng, ws, unb64(e.intentB64), {});
3269
+ const r2 = offerAdmit(eng, ws, unb64(e.changeB64), {});
2852
3270
  if (r2.ok) retried.push({ intentId: e.offerId, head: r2.head });
2853
3271
  else failed.push({ intentId: e.offerId, error: String(r2.error || "").slice(0, 300) });
2854
3272
  } catch (err) {
@@ -2856,7 +3274,7 @@ async function startDevCloud(opts = {}) {
2856
3274
  }
2857
3275
  }
2858
3276
  if (retried.length) await commitAndPush(eng, ws, ledger);
2859
- for (const r2 of retried) await deleteRefusedRef(eng, ws, ledger, r2.intentId);
3277
+ for (const r2 of retried) await deleteRefusedRef(eng, ws, ledger, String(r2.intentId || "unknown"));
2860
3278
  sendJson(res, { ok: true, ws, retried, failed, remaining: (await listRefusedRefs(eng, ws)).length });
2861
3279
  });
2862
3280
  }
@@ -2867,7 +3285,7 @@ async function startDevCloud(opts = {}) {
2867
3285
  const body = req.method === "DELETE" ? {} : JSON.parse((await readBody(req)).toString("utf8") || "{}");
2868
3286
  const only = body.id || url.searchParams.get("id") || null;
2869
3287
  const targets = (await listRefusedRefs(eng, ws)).filter((e) => !only || e.offerId === only || e.oid === only);
2870
- for (const e of targets) await deleteRefusedRef(eng, ws, ledger, e.offerId || e.oid);
3288
+ for (const e of targets) await deleteRefusedRef(eng, ws, ledger, String(e.offerId || e.oid || "unknown"));
2871
3289
  sendJson(res, { ok: true, ws, discarded: targets.length });
2872
3290
  });
2873
3291
  }
@@ -2907,7 +3325,7 @@ async function startDevCloud(opts = {}) {
2907
3325
  const id = sub[0] === "aggregates" ? decodeURIComponent(sub.slice(1).join("/")) : url.searchParams.get("id");
2908
3326
  return await serialize(async () => {
2909
3327
  await mountWorkspace(eng, ws, ledgerFor(ws));
2910
- const rows = qById(eng, ws, id, principalOf(req));
3328
+ const rows = qById(eng, ws, id, claimedPrincipalOf(req), [], authTokenOf(req), Math.floor(Date.now() / 1e3));
2911
3329
  sendJson(res, { ok: true, ws, rows });
2912
3330
  });
2913
3331
  }
@@ -2935,14 +3353,14 @@ async function startDevCloud(opts = {}) {
2935
3353
  }
2936
3354
  return sendJson(res, { ok: false, error: "unknown operation", see: `GET /v2/workspaces/${ws}` }, 404);
2937
3355
  }
2938
- const principal = principalOf(req);
3356
+ const principal = claimedPrincipalOf(req);
2939
3357
  const authToken = authTokenOf(req);
2940
3358
  if (x.kind === "offer" && method === "post") {
2941
3359
  const body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
2942
3360
  if (body.intentRef && typeof body.intentRef === "object") {
2943
3361
  const resolved2 = await resolveStagedIntent(stageBucket, body.intentRef);
2944
3362
  if (!resolved2.ok) return sendJson(res, { ok: false, refused: true, error: resolved2.error }, resolved2.status);
2945
- body.intentBytes = resolved2.intentB64;
3363
+ body.intentBytes = resolved2.changeB64;
2946
3364
  }
2947
3365
  try {
2948
3366
  let out;
@@ -2950,19 +3368,15 @@ async function startDevCloud(opts = {}) {
2950
3368
  out = offerAdmit(eng, ws, unb64(body.intentBytes), {});
2951
3369
  if (out.ok) await commitAndPush(eng, ws, ledger);
2952
3370
  } else {
2953
- const { actor, authorSecret, attestations, ...payload } = body;
2954
- const effectiveActor = actor || principal || "";
2955
- const lawHash = (currentLaw(eng, ws) || {})[x.domain] || "";
2956
- out = await authorOn(eng, ws, ledger, x.domain, x.directiveId, payload, lawHash, {
2957
- actor: effectiveActor,
2958
- ...effectiveActor ? { principalVerified: true } : {},
2959
- ...authToken ? { authToken } : {},
2960
- ...authorSecret ? { authorSecret } : {},
2961
- ...Array.isArray(attestations) ? { attestations } : {}
2962
- });
3371
+ return sendJson(res, {
3372
+ ok: false,
3373
+ refused: true,
3374
+ error: "offer requires sealed intentBytes or a content-addressed intentRef; the host cannot author raw payloads",
3375
+ code: "nomos.host_authority.raw_offer_refused"
3376
+ }, 400);
2963
3377
  }
2964
3378
  if (!out.ok) return sendJson(res, { ok: false, refused: true, error: String(out.error).slice(0, 600) }, 422);
2965
- const born = out.born ? await persistBorn(out.born) : void 0;
3379
+ const born = Array.isArray(out.born) && out.born.length ? await persistBorn(packBornChildren(eng, out.born)) : void 0;
2966
3380
  sendJson(res, { ok: true, ws, head: out.head, ...born ? { born } : {}, ...out.birthOutcomes ? { birthOutcomes: out.birthOutcomes } : {} });
2967
3381
  } catch (e) {
2968
3382
  sendJson(res, { ok: false, refused: true, error: errMsg(e).slice(0, 600) }, 422);
@@ -3062,7 +3476,14 @@ Sec-WebSocket-Accept: ${accept}\r
3062
3476
  \r
3063
3477
  `
3064
3478
  );
3065
- socket.on("data", () => {
3479
+ socket.on("data", (frame) => {
3480
+ if (frame.length > 0 && (frame[0] & 15) === 8) {
3481
+ try {
3482
+ socket.write(Buffer.from([136, 0]));
3483
+ } catch {
3484
+ }
3485
+ socket.end();
3486
+ }
3066
3487
  });
3067
3488
  socket.on("error", () => {
3068
3489
  });
@@ -3111,11 +3532,11 @@ async function startGeneratedApplicationProofCloud(opts) {
3111
3532
  ephemeral: true,
3112
3533
  attested: true,
3113
3534
  platform: opts.platform,
3114
- deploy: opts.deploy
3535
+ lawUsdz: opts.lawUsdz
3115
3536
  });
3116
3537
  try {
3117
3538
  const { bootstrapPlatform: bootstrapPlatform2 } = await Promise.resolve().then(() => (init_bootstrap(), bootstrap_exports));
3118
- await bootstrapPlatform2(dev, { platform: opts.platform, deploy: opts.deploy, attested: true });
3539
+ await bootstrapPlatform2(dev, { platform: opts.platform, lawUsdz: opts.lawUsdz, attested: true });
3119
3540
  dev.platformReady = true;
3120
3541
  if (dev.operatorDevice === void 0) {
3121
3542
  throw new Error("the local proof cloud did not establish its private founding device");
@@ -3144,10 +3565,10 @@ function parseArgs(argv) {
3144
3565
  else if (a === "--data") o.data = argv[++i];
3145
3566
  else if (a === "--firebase-project") o.firebaseProject = argv[++i];
3146
3567
  else if (a === "--platform") o.platform = argv[++i];
3147
- else if (a === "--deploy") {
3148
- const deploy2 = argv[++i];
3149
- o.deploy = deploy2;
3150
- (o.deploys ??= []).push(deploy2);
3568
+ else if (a === "--law") {
3569
+ const lawUsdz = argv[++i];
3570
+ o.lawUsdz = lawUsdz;
3571
+ (o.lawUsdzs ??= []).push(lawUsdz);
3151
3572
  } else if (a === "--auth-provider") o.authProvider = argv[++i];
3152
3573
  else if (a === "--bootstrap") o.bootstrap = true;
3153
3574
  else if (a === "--attested") o.attested = true;