githolon 0.112.8 → 0.112.12

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.
@@ -3878,10 +3878,10 @@ var init_node_custody_filesystem = __esm({
3878
3878
  // ../platform-shells/node/kernel_wasi_stdio.ts
3879
3879
  import { TextDecoder as TextDecoder2 } from "node:util";
3880
3880
  function kernelWasiStdio(memory, stderr, writeFile2, stderrPartial) {
3881
- const decoder4 = new TextDecoder2();
3881
+ const decoder5 = new TextDecoder2();
3882
3882
  let pending = "";
3883
3883
  const accept = (bytes) => {
3884
- pending += decoder4.decode(bytes, { stream: true });
3884
+ pending += decoder5.decode(bytes, { stream: true });
3885
3885
  for (; ; ) {
3886
3886
  const newline = pending.indexOf("\n");
3887
3887
  if (newline >= 0 && newline < 16384) {
@@ -5574,17 +5574,17 @@ function attributes(capability) {
5574
5574
  }
5575
5575
  return result;
5576
5576
  }
5577
- function capabilityByNamespace(capabilities, namespace) {
5578
- const matches = capabilities.filter((capability) => capability.namespace === namespace);
5577
+ function capabilityByNamespace(capabilities, namespace2) {
5578
+ const matches = capabilities.filter((capability) => capability.namespace === namespace2);
5579
5579
  if (matches.length !== 1) {
5580
- throw new Error(`OSGi resource needs exactly one ${namespace} capability`);
5580
+ throw new Error(`OSGi resource needs exactly one ${namespace2} capability`);
5581
5581
  }
5582
5582
  return matches[0];
5583
5583
  }
5584
- function optionalCapabilityByNamespace(capabilities, namespace) {
5585
- const matches = capabilities.filter((capability) => capability.namespace === namespace);
5584
+ function optionalCapabilityByNamespace(capabilities, namespace2) {
5585
+ const matches = capabilities.filter((capability) => capability.namespace === namespace2);
5586
5586
  if (matches.length > 1) {
5587
- throw new Error(`OSGi resource needs at most one ${namespace} capability`);
5587
+ throw new Error(`OSGi resource needs at most one ${namespace2} capability`);
5588
5588
  }
5589
5589
  return matches[0];
5590
5590
  }
@@ -6618,7 +6618,8 @@ var init_kernel_port = __esm({
6618
6618
  }
6619
6619
  }));
6620
6620
  if (response.outcome.case === "failure") {
6621
- throw new Error(`${response.outcome.value.code}: ${response.outcome.value.message}`);
6621
+ throwUnnamedHistoryRequirement(response.outcome.value, mount.workspace);
6622
+ throwKernelFailure(response.outcome.value);
6622
6623
  }
6623
6624
  if (response.outcome.case !== "outbox") {
6624
6625
  throw new Error(`kernel returned '${response.outcome.case || "empty"}' while reading correspondence`);
@@ -6647,7 +6648,8 @@ var init_kernel_port = __esm({
6647
6648
  }
6648
6649
  }));
6649
6650
  if (response.outcome.case === "failure") {
6650
- throw new Error(`${response.outcome.value.code}: ${response.outcome.value.message}`);
6651
+ throwUnnamedHistoryRequirement(response.outcome.value, mount.workspace);
6652
+ throwKernelFailure(response.outcome.value);
6651
6653
  }
6652
6654
  if (response.outcome.case !== "outbox") {
6653
6655
  throw new Error(
@@ -9844,11 +9846,11 @@ import { create as create19 } from "@bufbuild/protobuf";
9844
9846
  function resolveWorkspaceName(command) {
9845
9847
  switch (command.birth.case) {
9846
9848
  case "keyed": {
9847
- const { namespace, key: key2 } = command.birth.value;
9848
- if (namespace.length === 0 || key2.length === 0) {
9849
+ const { namespace: namespace2, key: key2 } = command.birth.value;
9850
+ if (namespace2.length === 0 || key2.length === 0) {
9849
9851
  throw new Error(`${WORKSPACE_NAME_REQUEST_INVALID}: a keyed birth name needs both its namespace and its key`);
9850
9852
  }
9851
- return create19(ResolvedWorkspaceNameSchema, { workspace: keyedBirthNameOf(namespace, key2) });
9853
+ return create19(ResolvedWorkspaceNameSchema, { workspace: keyedBirthNameOf(namespace2, key2) });
9852
9854
  }
9853
9855
  case "receivingGroup": {
9854
9856
  const { principal } = command.birth.value;
@@ -9872,10 +9874,10 @@ var init_workspace_naming = __esm({
9872
9874
  init_records_desk_pb();
9873
9875
  init_sha256();
9874
9876
  WORKSPACE_NAME_SEP = "";
9875
- keyedBirthNameOf = (namespace, key2) => `${namespace}-${sha256Hex(new TextEncoder().encode(namespace + WORKSPACE_NAME_SEP + key2)).slice(0, 40)}`;
9877
+ keyedBirthNameOf = (namespace2, key2) => `${namespace2}-${sha256Hex(new TextEncoder().encode(namespace2 + WORKSPACE_NAME_SEP + key2)).slice(0, 40)}`;
9876
9878
  RECEIVING_GROUP_NAME_PREFIX = "nomos-rg-";
9877
9879
  receivingGroupNameOf = (principal) => `${RECEIVING_GROUP_NAME_PREFIX}${sha256Hex(new TextEncoder().encode(principal)).slice(0, 40)}`;
9878
- isKeyedBirthOf = (namespace, workspace) => workspace.startsWith(`${namespace}-`);
9880
+ isKeyedBirthOf = (namespace2, workspace) => workspace.startsWith(`${namespace2}-`);
9879
9881
  WORKSPACE_NAME_REQUEST_INVALID = "nomos.runtime.workspace_name_request_invalid";
9880
9882
  }
9881
9883
  });
@@ -11975,8 +11977,150 @@ var init_model_adoption_desk = __esm({
11975
11977
  }
11976
11978
  });
11977
11979
 
11980
+ // ../peer-office/src/runtime/peer_desk_store.ts
11981
+ var recordId, copy2, MemoryPeerDeskStore;
11982
+ var init_peer_desk_store = __esm({
11983
+ "../peer-office/src/runtime/peer_desk_store.ts"() {
11984
+ "use strict";
11985
+ recordId = (namespace2, key2) => `${namespace2.length}:${namespace2}${key2}`;
11986
+ copy2 = (record) => ({
11987
+ ...record,
11988
+ value: record.value.slice()
11989
+ });
11990
+ MemoryPeerDeskStore = class {
11991
+ #records = /* @__PURE__ */ new Map();
11992
+ list(namespace2) {
11993
+ return [...this.#records.values()].filter((record) => record.namespace === namespace2).sort((left, right) => left.key.localeCompare(right.key)).map(copy2);
11994
+ }
11995
+ compareExchange(namespace2, key2, expectedRevision, value) {
11996
+ const id = recordId(namespace2, key2);
11997
+ const current = this.#records.get(id);
11998
+ if (current?.revision !== expectedRevision) {
11999
+ throw new Error(
12000
+ `peer desk record '${namespace2}/${key2}' changed at revision ${current?.revision ?? "absent"}`
12001
+ );
12002
+ }
12003
+ if (value === void 0) {
12004
+ this.#records.delete(id);
12005
+ return void 0;
12006
+ }
12007
+ const next = Object.freeze({
12008
+ namespace: namespace2,
12009
+ key: key2,
12010
+ revision: (current?.revision ?? 0n) + 1n,
12011
+ value: value.slice()
12012
+ });
12013
+ this.#records.set(id, next);
12014
+ return copy2(next);
12015
+ }
12016
+ };
12017
+ }
12018
+ });
12019
+
12020
+ // ../peer-office/src/runtime/custody_receipts.ts
12021
+ import { fromBinary as fromBinary15, toBinary as toBinary12 } from "@bufbuild/protobuf";
12022
+ var namespace, encoder, decoder, MAX_BASES, MAX_RECEIPTS, CustodyReceipts;
12023
+ var init_custody_receipts = __esm({
12024
+ "../peer-office/src/runtime/custody_receipts.ts"() {
12025
+ "use strict";
12026
+ init_correspondence_desk_pb();
12027
+ init_peer_desk_store();
12028
+ init_sha256();
12029
+ namespace = "nomos.peer-desk.custody-receipts/v1";
12030
+ encoder = new TextEncoder();
12031
+ decoder = new TextDecoder();
12032
+ MAX_BASES = 256;
12033
+ MAX_RECEIPTS = 4096;
12034
+ CustodyReceipts = class {
12035
+ #store;
12036
+ #records = /* @__PURE__ */ new Map();
12037
+ #journals = /* @__PURE__ */ new Map();
12038
+ #receipts = /* @__PURE__ */ new Map();
12039
+ constructor(store = new MemoryPeerDeskStore()) {
12040
+ this.#store = store;
12041
+ for (const record of store.list(namespace)) {
12042
+ this.#records.set(record.key, record);
12043
+ try {
12044
+ if (record.key.startsWith("receipt:")) {
12045
+ const newline = record.value.indexOf(10);
12046
+ if (newline < 0) continue;
12047
+ const receipt = fromBinary15(CustodyIntentAdmissionSchema, record.value.subarray(newline + 1));
12048
+ const header2 = JSON.parse(decoder.decode(record.value.subarray(0, newline)));
12049
+ if (receipt.outcome.case === "admitted" && typeof header2.generation === "string" && typeof header2.head === "string") this.#receipts.set(record.key, { ...header2, receipt });
12050
+ continue;
12051
+ }
12052
+ if (!record.key.startsWith("head:")) continue;
12053
+ const value = JSON.parse(decoder.decode(record.value));
12054
+ if (typeof value.head !== "string" || typeof value.generation !== "string" || !Array.isArray(value.bases) || !Array.isArray(value.keys) || value.bases.length > MAX_BASES || value.keys.length > MAX_RECEIPTS) continue;
12055
+ if (!value.bases.every((base) => typeof base === "string") || !value.keys.every((key2) => typeof key2 === "string")) continue;
12056
+ this.#journals.set(record.key.slice(5), value);
12057
+ } catch {
12058
+ }
12059
+ }
12060
+ }
12061
+ covers(workspace, current, base) {
12062
+ const value = this.#journals.get(workspace);
12063
+ return value?.head === current && value.bases.includes(base);
12064
+ }
12065
+ receipt(workspace, current, change) {
12066
+ const value = this.#journals.get(workspace);
12067
+ if (value?.head !== current) return void 0;
12068
+ const stored = this.#receipts.get(`receipt:${workspace}:${sha256Hex(change)}`);
12069
+ if (stored?.generation !== value.generation) return void 0;
12070
+ if (stored.head !== value.head && !value.bases.includes(stored.head)) return void 0;
12071
+ return fromBinary15(CustodyIntentAdmissionSchema, toBinary12(CustodyIntentAdmissionSchema, stored.receipt));
12072
+ }
12073
+ record(workspace, before, after, receipts) {
12074
+ const old = this.#journals.get(workspace);
12075
+ const journalKey = `head:${workspace}`;
12076
+ const value = old?.head === before ? { ...old, head: after, bases: [...old.bases], keys: [...old.keys] } : { head: after, bases: [], keys: [], generation: String((this.#records.get(journalKey)?.revision ?? 0n) + 1n) };
12077
+ if (before && before !== after) value.bases.push(before);
12078
+ value.bases = [...new Set(value.bases)].slice(-MAX_BASES);
12079
+ const keys = new Set(value.keys);
12080
+ const discarded = new Set(old?.generation !== value.generation ? old?.keys : []);
12081
+ for (const { change, receipt } of receipts) {
12082
+ if (receipt.outcome.case !== "admitted") continue;
12083
+ const key2 = `receipt:${workspace}:${sha256Hex(change)}`;
12084
+ keys.delete(key2);
12085
+ keys.add(key2);
12086
+ discarded.delete(key2);
12087
+ const header2 = encoder.encode(`${JSON.stringify({ generation: value.generation, head: after })}
12088
+ `);
12089
+ const body = toBinary12(CustodyIntentAdmissionSchema, receipt);
12090
+ const bytes = new Uint8Array(header2.length + body.length);
12091
+ bytes.set(header2);
12092
+ bytes.set(body, header2.length);
12093
+ const record2 = this.#store.compareExchange(namespace, key2, this.#records.get(key2)?.revision, bytes);
12094
+ if (record2) this.#records.set(key2, record2);
12095
+ this.#receipts.set(key2, {
12096
+ generation: value.generation,
12097
+ head: after,
12098
+ receipt: fromBinary15(CustodyIntentAdmissionSchema, body)
12099
+ });
12100
+ }
12101
+ const ordered = [...keys];
12102
+ for (const key2 of ordered.slice(0, -MAX_RECEIPTS)) discarded.add(key2);
12103
+ value.keys = ordered.slice(-MAX_RECEIPTS);
12104
+ for (const key2 of discarded) {
12105
+ this.#store.compareExchange(namespace, key2, this.#records.get(key2)?.revision, void 0);
12106
+ this.#records.delete(key2);
12107
+ this.#receipts.delete(key2);
12108
+ }
12109
+ const record = this.#store.compareExchange(
12110
+ namespace,
12111
+ journalKey,
12112
+ this.#records.get(journalKey)?.revision,
12113
+ encoder.encode(JSON.stringify(value))
12114
+ );
12115
+ if (record) this.#records.set(journalKey, record);
12116
+ this.#journals.set(workspace, value);
12117
+ }
12118
+ };
12119
+ }
12120
+ });
12121
+
11978
12122
  // ../peer-office/src/runtime/custodian_placement.ts
11979
- import { create as create25, fromBinary as fromBinary15, toBinary as toBinary12 } from "@bufbuild/protobuf";
12123
+ import { create as create25, fromBinary as fromBinary16, toBinary as toBinary13 } from "@bufbuild/protobuf";
11980
12124
  var CustodianPlacement;
11981
12125
  var init_custodian_placement = __esm({
11982
12126
  "../peer-office/src/runtime/custodian_placement.ts"() {
@@ -11990,7 +12134,7 @@ var init_custodian_placement = __esm({
11990
12134
  #clock;
11991
12135
  #template;
11992
12136
  constructor(kernel, clock, templateProtobuf) {
11993
- const template = fromBinary15(CustodyPlacementPolicySchema, templateProtobuf);
12137
+ const template = fromBinary16(CustodyPlacementPolicySchema, templateProtobuf);
11994
12138
  if (!template.declaration || !template.adoptedBy || template.rules.length === 0 || template.remotes.length === 0) {
11995
12139
  throw new Error("custodian placement template requires a declaration, adoptedBy, rules and remotes");
11996
12140
  }
@@ -12022,7 +12166,7 @@ var init_custodian_placement = __esm({
12022
12166
  });
12023
12167
  return create25(CustodyPlacementPolicySchema, {
12024
12168
  ...content,
12025
- packageSha256: sha256Hex(toBinary12(CustodyPlacementPolicySchema, content))
12169
+ packageSha256: sha256Hex(toBinary13(CustodyPlacementPolicySchema, content))
12026
12170
  });
12027
12171
  }
12028
12172
  /** Adopt this custodian's placement for an opened, born workspace that has none. True when it adopted. */
@@ -12087,6 +12231,7 @@ var init_custody_admission_desk = __esm({
12087
12231
  init_correspondence_desk_pb();
12088
12232
  init_session_directory();
12089
12233
  init_custody_return_delta();
12234
+ init_custody_receipts();
12090
12235
  CandidateCustodyRequiredError = class extends Error {
12091
12236
  workspace;
12092
12237
  reference;
@@ -12100,14 +12245,16 @@ var init_custody_admission_desk = __esm({
12100
12245
  CustodyAdmissionDesk = class {
12101
12246
  #kernel;
12102
12247
  #custody;
12103
- constructor(kernel, custody) {
12248
+ #receipts;
12249
+ constructor(kernel, custody, receipts = new CustodyReceipts()) {
12104
12250
  this.#kernel = kernel;
12105
12251
  this.#custody = custody;
12252
+ this.#receipts = receipts;
12106
12253
  }
12107
12254
  admit(request, command) {
12108
- const session = request.target?.session;
12109
- if (!session) throw new Error("custody admission requires an addressed runtime session");
12110
- const mount = this.#custody.mountForSession(session);
12255
+ const workspace = request.target?.workspace;
12256
+ if (!workspace) throw new Error("custody admission requires an addressed workspace");
12257
+ const mount = this.#custody.mountForWorkspace(workspace);
12111
12258
  if (command.evidencePack.byteLength > 0) {
12112
12259
  this.#kernel.applyPack(mount, request.requestId, command.evidencePack);
12113
12260
  }
@@ -12118,21 +12265,42 @@ var init_custody_admission_desk = __esm({
12118
12265
  const births = [];
12119
12266
  const admittedBase = this.#kernel.head(mount, request.requestId) ?? "";
12120
12267
  if (command.fastForwardOnly && offers.length > 0 && (command.baseHead ?? "") !== admittedBase) {
12268
+ for (const offer of offers) {
12269
+ const receipt = this.#receipts.receipt(mount.workspace, admittedBase, offer.changeUsda);
12270
+ if (!receipt) continue;
12271
+ receipt.commitOid = offer.commitOid;
12272
+ const records = sessions.get(offer.session) ?? [];
12273
+ records.push(receipt);
12274
+ sessions.set(offer.session, records);
12275
+ }
12276
+ let delta = custodyReturnDelta(
12277
+ this.#kernel,
12278
+ mount,
12279
+ request.requestId,
12280
+ command.baseHead,
12281
+ admittedBase,
12282
+ admittedBase,
12283
+ command.observedHead
12284
+ );
12285
+ if (command.baseHead && command.observedHead !== admittedBase && this.#receipts.covers(mount.workspace, admittedBase, command.baseHead)) {
12286
+ try {
12287
+ delta = {
12288
+ resultBase: command.baseHead,
12289
+ resultPack: this.#kernel.packDelta(mount, request.requestId, admittedBase, command.baseHead),
12290
+ recoveryRequired: false
12291
+ };
12292
+ } catch {
12293
+ }
12294
+ }
12121
12295
  return create26(CustodyAdmissionSchema, {
12122
12296
  main: admittedBase,
12123
- ...custodyReturnDelta(
12124
- this.#kernel,
12125
- mount,
12126
- request.requestId,
12127
- command.baseHead,
12128
- admittedBase,
12129
- admittedBase,
12130
- command.observedHead
12131
- )
12297
+ sessions: [...sessions].map(([session, intents]) => create26(CustodySessionAdmissionSchema, { session, intents })),
12298
+ ...delta
12132
12299
  });
12133
12300
  }
12134
12301
  let main = admittedBase;
12135
12302
  const heldSessions = /* @__PURE__ */ new Map();
12303
+ const receipts = [];
12136
12304
  for (const offer of offers) {
12137
12305
  const heldBehind = heldSessions.get(offer.session);
12138
12306
  const verdict = heldBehind === void 0 ? this.#offer(request, mount, offer) : create26(OfferResponseSchema, { outcome: { case: "blockedOnDependency", value: {
@@ -12142,7 +12310,9 @@ var init_custody_admission_desk = __esm({
12142
12310
  heldSessions.set(offer.session, verdict.outcome.value.offerId || offer.commitOid);
12143
12311
  }
12144
12312
  const records = sessions.get(offer.session) ?? [];
12145
- records.push(this.#record(offer, verdict));
12313
+ const receipt = this.#record(offer, verdict);
12314
+ records.push(receipt);
12315
+ receipts.push({ change: offer.changeUsda, receipt });
12146
12316
  sessions.set(offer.session, records);
12147
12317
  if (verdict.outcome.case === "admitted") {
12148
12318
  main = verdict.outcome.value.head;
@@ -12158,6 +12328,9 @@ var init_custody_admission_desk = __esm({
12158
12328
  }
12159
12329
  }
12160
12330
  }
12331
+ if (receipts.some((entry) => entry.receipt.outcome.case === "admitted")) {
12332
+ this.#receipts.record(mount.workspace, admittedBase, main, receipts);
12333
+ }
12161
12334
  return create26(CustodyAdmissionSchema, {
12162
12335
  main,
12163
12336
  sessions: [...sessions].map(
@@ -13176,7 +13349,7 @@ var init_application_readiness_desk = __esm({
13176
13349
  });
13177
13350
 
13178
13351
  // ../peer-office/src/runtime/authentication_readiness_desk.ts
13179
- import { create as create34, fromBinary as fromBinary16, toBinary as toBinary13 } from "@bufbuild/protobuf";
13352
+ import { create as create34, fromBinary as fromBinary17, toBinary as toBinary14 } from "@bufbuild/protobuf";
13180
13353
  var AuthenticationReadinessDesk;
13181
13354
  var init_authentication_readiness_desk = __esm({
13182
13355
  "../peer-office/src/runtime/authentication_readiness_desk.ts"() {
@@ -13199,7 +13372,7 @@ var init_authentication_readiness_desk = __esm({
13199
13372
  begin(request, input) {
13200
13373
  if (![AuthenticationReadinessCriterion.ENROLLED_DEVICE, AuthenticationReadinessCriterion.PROVIDER_TOKEN, AuthenticationReadinessCriterion.BIRTH_EVIDENCE].includes(input.criterion)) throw new Error("authentication readiness requires a criterion");
13201
13374
  if (!input.session) throw new Error("authentication readiness requires a session");
13202
- const command = fromBinary16(AwaitAuthenticationRequestSchema, toBinary13(AwaitAuthenticationRequestSchema, input));
13375
+ const command = fromBinary17(AwaitAuthenticationRequestSchema, toBinary14(AwaitAuthenticationRequestSchema, input));
13203
13376
  const now = this.#now();
13204
13377
  for (const [id2, work2] of this.#waiting) if (work2.expiresAt <= now) this.#waiting.delete(id2);
13205
13378
  const work = {
@@ -13989,7 +14162,7 @@ var init_residency_pins = __esm({
13989
14162
  });
13990
14163
 
13991
14164
  // ../peer-office/src/runtime/subscription_manager.ts
13992
- import { clone, create as create39, toBinary as toBinary14 } from "@bufbuild/protobuf";
14165
+ import { clone, create as create39, toBinary as toBinary15 } from "@bufbuild/protobuf";
13993
14166
  function createSyntheticRequest(requestId) {
13994
14167
  return create39(RuntimeRequestSchema, {
13995
14168
  protocolVersion: 2,
@@ -14133,7 +14306,7 @@ var init_subscription_manager = __esm({
14133
14306
  const groups = [];
14134
14307
  for (const subscription of this.#subscriptions.values()) {
14135
14308
  if (!matches(subscription) || !subscription.request.query) continue;
14136
- const declaration = toBinary14(QueryRequestSchema, subscription.request.query);
14309
+ const declaration = toBinary15(QueryRequestSchema, subscription.request.query);
14137
14310
  const session = subscription.request.session;
14138
14311
  const group = groups.find((group2) => group2.session === session && sameBytes(group2.declaration, declaration));
14139
14312
  if (group) group.watches.push(subscription);
@@ -15283,14 +15456,14 @@ var init_local_copy_drop = __esm({
15283
15456
 
15284
15457
  // ../peer-office/src/runtime/preserved_copies_desk.ts
15285
15458
  import { create as create41, fromJsonString, toJsonString } from "@bufbuild/protobuf";
15286
- var PRESERVED_COPIES_NAMESPACE, encoder, decoder, PreservedCopiesDesk;
15459
+ var PRESERVED_COPIES_NAMESPACE, encoder2, decoder2, PreservedCopiesDesk;
15287
15460
  var init_preserved_copies_desk = __esm({
15288
15461
  "../peer-office/src/runtime/preserved_copies_desk.ts"() {
15289
15462
  "use strict";
15290
15463
  init_custody_desk_pb();
15291
15464
  PRESERVED_COPIES_NAMESPACE = "nomos.peer-desk.preserved-local-copies/v1";
15292
- encoder = new TextEncoder();
15293
- decoder = new TextDecoder();
15465
+ encoder2 = new TextEncoder();
15466
+ decoder2 = new TextDecoder();
15294
15467
  PreservedCopiesDesk = class {
15295
15468
  #store;
15296
15469
  constructor(store) {
@@ -15299,7 +15472,7 @@ var init_preserved_copies_desk = __esm({
15299
15472
  list(workspace) {
15300
15473
  const record = this.#store.list(PRESERVED_COPIES_NAMESPACE).find((entry) => entry.key === workspace);
15301
15474
  if (!record) return [];
15302
- const values = JSON.parse(decoder.decode(record.value));
15475
+ const values = JSON.parse(decoder2.decode(record.value));
15303
15476
  if (!Array.isArray(values)) {
15304
15477
  throw new Error(`corrupt preserved-copy record for '${workspace}' at revision ${record.revision}`);
15305
15478
  }
@@ -15313,7 +15486,7 @@ var init_preserved_copies_desk = __esm({
15313
15486
  PRESERVED_COPIES_NAMESPACE,
15314
15487
  copy3.workspace,
15315
15488
  current?.revision,
15316
- encoder.encode(`[${next.map((entry) => toJsonString(PreservedLocalCopySchema, entry)).join(",")}]`)
15489
+ encoder2.encode(`[${next.map((entry) => toJsonString(PreservedLocalCopySchema, entry)).join(",")}]`)
15317
15490
  );
15318
15491
  if (!stored) throw new Error(`preserved copy of '${copy3.workspace}' was not recorded`);
15319
15492
  }
@@ -15322,7 +15495,7 @@ var init_preserved_copies_desk = __esm({
15322
15495
  });
15323
15496
 
15324
15497
  // ../peer-office/src/runtime/office_seat.ts
15325
- import { fromBinary as fromBinary17 } from "@bufbuild/protobuf";
15498
+ import { fromBinary as fromBinary18 } from "@bufbuild/protobuf";
15326
15499
  function officeSeat(profile) {
15327
15500
  const origins = /* @__PURE__ */ new Set();
15328
15501
  const add = (url) => {
@@ -15332,7 +15505,7 @@ function officeSeat(profile) {
15332
15505
  add(profile.liveRelayOrigin);
15333
15506
  if (profile.custodianPlacement !== void 0 && profile.custodianPlacement.byteLength > 0) {
15334
15507
  try {
15335
- for (const remote of fromBinary17(CustodyPlacementPolicySchema, profile.custodianPlacement).remotes) {
15508
+ for (const remote of fromBinary18(CustodyPlacementPolicySchema, profile.custodianPlacement).remotes) {
15336
15509
  add(remote.url);
15337
15510
  }
15338
15511
  } catch {
@@ -15362,7 +15535,7 @@ import { create as create42 } from "@bufbuild/protobuf";
15362
15535
  function readSeal(value) {
15363
15536
  const headerLength = SEAT_PREFIX.length + SEAT_DIGEST_HEX + 1;
15364
15537
  if (value.byteLength < headerLength) return void 0;
15365
- const text = decoder2.decode(value.subarray(0, headerLength));
15538
+ const text = decoder3.decode(value.subarray(0, headerLength));
15366
15539
  if (!text.startsWith(SEAT_PREFIX) || !text.endsWith("\n")) return void 0;
15367
15540
  const seat = text.slice(SEAT_PREFIX.length, headerLength - 1);
15368
15541
  if (!/^[0-9a-f]{64}$/.test(seat)) return void 0;
@@ -15375,7 +15548,7 @@ function seal(digest, value) {
15375
15548
  sealed.set(value, prefix.byteLength);
15376
15549
  return sealed;
15377
15550
  }
15378
- var QUARANTINED_BINDINGS_NAMESPACE, LOCAL_ONLY_NAMESPACES, SEAT_PREFIX, SEAT_DIGEST_HEX, encoder2, decoder2, header, QuarantineReason, SeatedPeerDeskStore;
15551
+ var QUARANTINED_BINDINGS_NAMESPACE, LOCAL_ONLY_NAMESPACES, SEAT_PREFIX, SEAT_DIGEST_HEX, encoder3, decoder3, header, QuarantineReason, SeatedPeerDeskStore;
15379
15552
  var init_seated_peer_desk_store = __esm({
15380
15553
  "../peer-office/src/runtime/seated_peer_desk_store.ts"() {
15381
15554
  "use strict";
@@ -15388,9 +15561,9 @@ var init_seated_peer_desk_store = __esm({
15388
15561
  ]);
15389
15562
  SEAT_PREFIX = "nomos-office-seat/v1:";
15390
15563
  SEAT_DIGEST_HEX = 64;
15391
- encoder2 = new TextEncoder();
15392
- decoder2 = new TextDecoder();
15393
- header = (digest) => encoder2.encode(`${SEAT_PREFIX}${digest}
15564
+ encoder3 = new TextEncoder();
15565
+ decoder3 = new TextDecoder();
15566
+ header = (digest) => encoder3.encode(`${SEAT_PREFIX}${digest}
15394
15567
  `);
15395
15568
  QuarantineReason = Object.freeze({
15396
15569
  /** Another office's seat: a copied state directory, or a store lifted from another peer. */
@@ -15409,44 +15582,44 @@ var init_seated_peer_desk_store = __esm({
15409
15582
  this.#seat = seat;
15410
15583
  this.#report = report;
15411
15584
  }
15412
- list(namespace) {
15413
- if (LOCAL_ONLY_NAMESPACES.has(namespace)) return this.#inner.list(namespace);
15585
+ list(namespace2) {
15586
+ if (LOCAL_ONLY_NAMESPACES.has(namespace2)) return this.#inner.list(namespace2);
15414
15587
  const kept = [];
15415
- for (const record of this.#inner.list(namespace)) {
15588
+ for (const record of this.#inner.list(namespace2)) {
15416
15589
  const sealed = readSeal(record.value);
15417
15590
  if (sealed?.seat === this.#seat.digest) {
15418
15591
  kept.push({ ...record, value: sealed.value.slice() });
15419
15592
  continue;
15420
15593
  }
15421
- this.#quarantine(namespace, record, sealed?.seat);
15594
+ this.#quarantine(namespace2, record, sealed?.seat);
15422
15595
  }
15423
15596
  return kept;
15424
15597
  }
15425
- compareExchange(namespace, key2, expectedRevision, value) {
15426
- if (LOCAL_ONLY_NAMESPACES.has(namespace)) {
15427
- return this.#inner.compareExchange(namespace, key2, expectedRevision, value);
15598
+ compareExchange(namespace2, key2, expectedRevision, value) {
15599
+ if (LOCAL_ONLY_NAMESPACES.has(namespace2)) {
15600
+ return this.#inner.compareExchange(namespace2, key2, expectedRevision, value);
15428
15601
  }
15429
15602
  const stored = this.#inner.compareExchange(
15430
- namespace,
15603
+ namespace2,
15431
15604
  key2,
15432
15605
  expectedRevision,
15433
15606
  value === void 0 ? void 0 : seal(this.#seat.digest, value)
15434
15607
  );
15435
15608
  if (stored === void 0) return void 0;
15436
15609
  const sealed = readSeal(stored.value);
15437
- if (!sealed) throw new Error(`peer desk record '${namespace}/${key2}' lost its office seat`);
15610
+ if (!sealed) throw new Error(`peer desk record '${namespace2}/${key2}' lost its office seat`);
15438
15611
  return { ...stored, value: sealed.value.slice() };
15439
15612
  }
15440
15613
  /** Preserve the foreign record under the quarantine namespace, then free the slot. */
15441
- #quarantine(namespace, record, recordedSeat) {
15442
- const key2 = `${namespace}\0${record.key}\0${record.revision}`;
15614
+ #quarantine(namespace2, record, recordedSeat) {
15615
+ const key2 = `${namespace2}\0${record.key}\0${record.revision}`;
15443
15616
  try {
15444
15617
  this.#inner.compareExchange(QUARANTINED_BINDINGS_NAMESPACE, key2, void 0, record.value);
15445
15618
  } catch {
15446
15619
  }
15447
- this.#inner.compareExchange(namespace, record.key, record.revision, void 0);
15620
+ this.#inner.compareExchange(namespace2, record.key, record.revision, void 0);
15448
15621
  this.#report(create42(QuarantinedBindingSchema, {
15449
- namespace,
15622
+ namespace: namespace2,
15450
15623
  key: record.key,
15451
15624
  reason: recordedSeat === void 0 ? QuarantineReason.Unseated : QuarantineReason.ForeignSeat,
15452
15625
  recordedSeat: recordedSeat ?? "",
@@ -15505,6 +15678,7 @@ var init_replica_inventory_desk = __esm({
15505
15678
  const undiscovered = /* @__PURE__ */ new Set();
15506
15679
  for (const restored of this.#follows.recover()) {
15507
15680
  following.set(restored.workspace, restored.delayMillis);
15681
+ followed.add(restored.workspace);
15508
15682
  }
15509
15683
  if (!this.#bootstrapped) {
15510
15684
  this.#bootstrapped = true;
@@ -15542,6 +15716,7 @@ var init_replica_inventory_desk = __esm({
15542
15716
  stopped.delete(workspace);
15543
15717
  } else if (reconciliation.changed) {
15544
15718
  following.delete(workspace);
15719
+ followed.delete(workspace);
15545
15720
  stopped.add(workspace);
15546
15721
  }
15547
15722
  } catch (error) {
@@ -15685,7 +15860,7 @@ var init_correspondence_work_registry = __esm({
15685
15860
  });
15686
15861
 
15687
15862
  // ../peer-office/src/runtime/placement_discovery_desk.ts
15688
- import { create as create43, toBinary as toBinary15 } from "@bufbuild/protobuf";
15863
+ import { create as create43, toBinary as toBinary16 } from "@bufbuild/protobuf";
15689
15864
  var DiscoveryPhase, PlacementDiscoveryDesk;
15690
15865
  var init_placement_discovery_desk = __esm({
15691
15866
  "../peer-office/src/runtime/placement_discovery_desk.ts"() {
@@ -15746,7 +15921,7 @@ var init_placement_discovery_desk = __esm({
15746
15921
  return {
15747
15922
  workspace: next.workspace,
15748
15923
  nextAfterMillis: 0,
15749
- frame: toBinary15(RuntimeRequestSchema, create43(RuntimeRequestSchema, {
15924
+ frame: toBinary16(RuntimeRequestSchema, create43(RuntimeRequestSchema, {
15750
15925
  protocolVersion: 2,
15751
15926
  requestId,
15752
15927
  command: { case: "workspacePlacement", value: {
@@ -15833,7 +16008,7 @@ var init_placement_discovery_desk = __esm({
15833
16008
  });
15834
16009
 
15835
16010
  // ../peer-office/src/runtime/live_correspondence_desk.ts
15836
- import { create as create44, fromBinary as fromBinary18, toBinary as toBinary16 } from "@bufbuild/protobuf";
16011
+ import { create as create44, fromBinary as fromBinary19, toBinary as toBinary17 } from "@bufbuild/protobuf";
15837
16012
  function presencePeerToken(replicaId2) {
15838
16013
  return sha256Hex(new TextEncoder().encode(`nomos-presence-peer:${replicaId2}`)).slice(0, PRESENCE_PEER_TOKEN_HEX);
15839
16014
  }
@@ -15897,7 +16072,7 @@ var init_live_correspondence_desk = __esm({
15897
16072
  wasResident: this.kernel.isResident(binding.workspace) !== false
15898
16073
  };
15899
16074
  this.#links.set(binding.workspace, link);
15900
- if (link.wasResident) this.#open(link);
16075
+ if (!link.publisher || link.wasResident) this.#open(link);
15901
16076
  }
15902
16077
  changed(workspace) {
15903
16078
  const link = this.#links.get(workspace);
@@ -15919,11 +16094,14 @@ var init_live_correspondence_desk = __esm({
15919
16094
  this.#effect(link, { case: "openUrl", value: `${endpoint}/v2/workspaces/${encodeURIComponent(link.binding.workspace)}/subscribe?${subscribeQuery(link)}` });
15920
16095
  }
15921
16096
  #send(link, message) {
15922
- const bytes = toBinary16(LiveOfferFrameSchema, create44(LiveOfferFrameSchema, { message }));
16097
+ const bytes = toBinary17(LiveOfferFrameSchema, create44(LiveOfferFrameSchema, { message }));
15923
16098
  if (bytes.byteLength > MAX_LIVE_FRAME_BYTES) return;
15924
16099
  this.#effect(link, { case: "send", value: bytes });
15925
16100
  }
15926
16101
  export(binding, base, requestId) {
16102
+ if (this.kernel.isResident(binding.workspace) === false) {
16103
+ return create44(CustodyOfferBatchRequestSchema, { protocolVersion: 2 });
16104
+ }
15927
16105
  const mount = workspaceMount(binding.workspace);
15928
16106
  const head = this.kernel.head(mount, requestId);
15929
16107
  if (!base || !head || base === head) return create44(CustodyOfferBatchRequestSchema, { protocolVersion: 2 });
@@ -15969,7 +16147,7 @@ var init_live_correspondence_desk = __esm({
15969
16147
  if (!bytes.byteLength || bytes.byteLength > MAX_LIVE_FRAME_BYTES) return;
15970
16148
  let frame;
15971
16149
  try {
15972
- frame = fromBinary18(LiveOfferFrameSchema, bytes);
16150
+ frame = fromBinary19(LiveOfferFrameSchema, bytes);
15973
16151
  } catch {
15974
16152
  let ring;
15975
16153
  try {
@@ -15984,6 +16162,7 @@ var init_live_correspondence_desk = __esm({
15984
16162
  }
15985
16163
  if (frame.message.case === "frontier") {
15986
16164
  this.#announced(link, frame.message.value.head);
16165
+ if (this.kernel.isResident(link.binding.workspace) === false) return;
15987
16166
  if (!frame.message.value.response) {
15988
16167
  this.#send(link, { case: "frontier", value: {
15989
16168
  head: this.kernel.head(workspaceMount(link.binding.workspace), ++this.#requestId) ?? "",
@@ -16000,6 +16179,10 @@ var init_live_correspondence_desk = __esm({
16000
16179
  if (frame.message.case !== "offers") return;
16001
16180
  const batch = frame.message.value;
16002
16181
  if (batch.protocolVersion !== 2 || !batch.requestId || batch.source.case !== "inline" || !batch.source.value.offers.length) return;
16182
+ if (this.kernel.isResident(link.binding.workspace) === false) {
16183
+ this.remoteAdvanced?.(link.binding.workspace);
16184
+ return;
16185
+ }
16003
16186
  if ([...this.#pending.values()].some((pending) => pending.link === link && pending.bytes.length === bytes.length && pending.bytes.every((byte, index) => byte === bytes[index]))) return;
16004
16187
  if (this.#pending.size >= 32) return;
16005
16188
  this.#pending.set(request.requestId, { link, bytes });
@@ -16007,7 +16190,16 @@ var init_live_correspondence_desk = __esm({
16007
16190
  protocolVersion: 2,
16008
16191
  requestId: request.requestId,
16009
16192
  target: { workspace: link.binding.workspace, session: link.binding.replicaId },
16010
- command: { case: "admitCustodyOffers", value: create44(CustodyOfferBatchRequestSchema, { ...batch, baseHead: void 0 }) }
16193
+ // HTTP sender reconciliation controls are not part of a live proposal.
16194
+ // Keeping fastForwardOnly while removing baseHead silently skips every
16195
+ // offer against a nonempty local head. The Kernel judges sealed causality;
16196
+ // live receivers neither ask for a return archive nor confirm the sender.
16197
+ command: { case: "admitCustodyOffers", value: create44(CustodyOfferBatchRequestSchema, {
16198
+ ...batch,
16199
+ baseHead: void 0,
16200
+ observedHead: void 0,
16201
+ fastForwardOnly: false
16202
+ }) }
16011
16203
  });
16012
16204
  }
16013
16205
  /** Upstream news is a frontier this replica has NEVER seen: neither its own head nor the
@@ -16016,6 +16208,10 @@ var init_live_correspondence_desk = __esm({
16016
16208
  #announced(link, head) {
16017
16209
  if (!head || link.lastAnnounced === head) return;
16018
16210
  link.lastAnnounced = head;
16211
+ if (this.kernel.isResident(link.binding.workspace) === false) {
16212
+ this.remoteAdvanced?.(link.binding.workspace);
16213
+ return;
16214
+ }
16019
16215
  const mount = workspaceMount(link.binding.workspace);
16020
16216
  if (head === this.kernel.head(mount, ++this.#requestId) || head === this.kernel.resolveRef(mount, ++this.#requestId, "refs/remotes/nomos/main")) return;
16021
16217
  this.remoteAdvanced?.(link.binding.workspace);
@@ -16025,6 +16221,10 @@ var init_live_correspondence_desk = __esm({
16025
16221
  #placementAnnounced(link, frontier) {
16026
16222
  if (!frontier || link.lastPlacementAnnounced === frontier) return;
16027
16223
  link.lastPlacementAnnounced = frontier;
16224
+ if (this.kernel.isResident(link.binding.workspace) === false) {
16225
+ this.placementAdvanced?.(link.binding.workspace);
16226
+ return;
16227
+ }
16028
16228
  const mount = workspaceMount(link.binding.workspace);
16029
16229
  if (frontier === this.kernel.resolveRef(mount, ++this.#requestId, PLACEMENT_REF2)) return;
16030
16230
  this.placementAdvanced?.(link.binding.workspace);
@@ -16041,11 +16241,13 @@ var init_live_correspondence_desk = __esm({
16041
16241
  disconnect(workspace) {
16042
16242
  const link = this.#links.get(workspace);
16043
16243
  if (!link) return;
16244
+ if (link.state === "open") this.linkClosed?.(workspace);
16044
16245
  this.#effect(link, { case: "close", value: true });
16045
16246
  this.#links.delete(workspace);
16046
16247
  for (const [id, pending] of this.#pending) if (pending.link === link) this.#pending.delete(id);
16047
16248
  }
16048
16249
  #hello(link) {
16250
+ if (this.kernel.isResident(link.binding.workspace) === false) return;
16049
16251
  const head = this.kernel.head(workspaceMount(link.binding.workspace), ++this.#requestId);
16050
16252
  this.#send(link, { case: "frontier", value: { head: head ?? "" } });
16051
16253
  }
@@ -16053,19 +16255,20 @@ var init_live_correspondence_desk = __esm({
16053
16255
  const now = this.clock.monotonicNanoseconds();
16054
16256
  let wake;
16055
16257
  for (const link of this.#links.values()) {
16056
- if (this.kernel.isResident(link.binding.workspace) === false) {
16258
+ const resident = this.kernel.isResident(link.binding.workspace) !== false;
16259
+ if (link.publisher && !resident) {
16057
16260
  if (link.wasResident) this.disconnect(link.binding.workspace);
16058
16261
  else wake = wake === void 0 || wake > 250n ? 250n : wake;
16059
16262
  continue;
16060
16263
  }
16061
- link.wasResident = true;
16264
+ if (resident) link.wasResident = true;
16062
16265
  if (link.state === "opening" && now >= link.due) {
16063
16266
  this.#effect(link, { case: "close", value: true });
16064
16267
  link.state = "closed";
16065
16268
  }
16066
16269
  if (link.state === "closed" && now >= link.due) this.#open(link);
16067
16270
  if (link.state === "open") {
16068
- if (link.dirty) {
16271
+ if (link.dirty && resident) {
16069
16272
  link.dirty = false;
16070
16273
  try {
16071
16274
  link.published ??= link.publisher ? this.kernel.head(workspaceMount(link.binding.workspace), ++this.#requestId) : this.kernel.resolveRef(workspaceMount(link.binding.workspace), ++this.#requestId, "refs/remotes/nomos/main");
@@ -16084,8 +16287,7 @@ var init_live_correspondence_desk = __esm({
16084
16287
  return wake;
16085
16288
  }
16086
16289
  close() {
16087
- for (const link of this.#links.values()) this.#effect(link, { case: "close", value: true });
16088
- this.#links.clear();
16290
+ for (const workspace of [...this.#links.keys()]) this.disconnect(workspace);
16089
16291
  this.#pending.clear();
16090
16292
  }
16091
16293
  };
@@ -16257,9 +16459,9 @@ var init_records_desk = __esm({
16257
16459
  command.namespace === void 0 ? {} : { "custody.children_namespace": command.namespace },
16258
16460
  () => this.#kernel.childWorkspaces(mount, request.requestId)
16259
16461
  );
16260
- const namespace = command.namespace;
16261
- const selected = namespace === void 0 ? result.children : result.children.filter(
16262
- (child) => child.status === ChildWorkspaceLifecycleStatus.ACTIVE && isKeyedBirthOf(namespace, child.workspace)
16462
+ const namespace2 = command.namespace;
16463
+ const selected = namespace2 === void 0 ? result.children : result.children.filter(
16464
+ (child) => child.status === ChildWorkspaceLifecycleStatus.ACTIVE && isKeyedBirthOf(namespace2, child.workspace)
16263
16465
  );
16264
16466
  return create46(ChildWorkspaceListSchema, {
16265
16467
  children: selected.map((child) => create46(ChildWorkspaceSchema, {
@@ -16629,46 +16831,6 @@ var init_recovery_desk = __esm({
16629
16831
  }
16630
16832
  });
16631
16833
 
16632
- // ../peer-office/src/runtime/peer_desk_store.ts
16633
- var recordId, copy2, MemoryPeerDeskStore;
16634
- var init_peer_desk_store = __esm({
16635
- "../peer-office/src/runtime/peer_desk_store.ts"() {
16636
- "use strict";
16637
- recordId = (namespace, key2) => `${namespace.length}:${namespace}${key2}`;
16638
- copy2 = (record) => ({
16639
- ...record,
16640
- value: record.value.slice()
16641
- });
16642
- MemoryPeerDeskStore = class {
16643
- #records = /* @__PURE__ */ new Map();
16644
- list(namespace) {
16645
- return [...this.#records.values()].filter((record) => record.namespace === namespace).sort((left, right) => left.key.localeCompare(right.key)).map(copy2);
16646
- }
16647
- compareExchange(namespace, key2, expectedRevision, value) {
16648
- const id = recordId(namespace, key2);
16649
- const current = this.#records.get(id);
16650
- if (current?.revision !== expectedRevision) {
16651
- throw new Error(
16652
- `peer desk record '${namespace}/${key2}' changed at revision ${current?.revision ?? "absent"}`
16653
- );
16654
- }
16655
- if (value === void 0) {
16656
- this.#records.delete(id);
16657
- return void 0;
16658
- }
16659
- const next = Object.freeze({
16660
- namespace,
16661
- key: key2,
16662
- revision: (current?.revision ?? 0n) + 1n,
16663
- value: value.slice()
16664
- });
16665
- this.#records.set(id, next);
16666
- return copy2(next);
16667
- }
16668
- };
16669
- }
16670
- });
16671
-
16672
16834
  // ../peer-office/src/runtime/correspondence_recovery.ts
16673
16835
  import { create as create50 } from "@bufbuild/protobuf";
16674
16836
  var CorrespondenceRecoveryWork;
@@ -16854,7 +17016,7 @@ var init_custody_replacement = __esm({
16854
17016
  });
16855
17017
 
16856
17018
  // ../peer-office/src/runtime/custody_offer.ts
16857
- import { create as create53, fromBinary as fromBinary19, toBinary as toBinary17 } from "@bufbuild/protobuf";
17019
+ import { create as create53, fromBinary as fromBinary20, toBinary as toBinary18 } from "@bufbuild/protobuf";
16858
17020
  function settleCustodyOfferExchange(awaiting, response) {
16859
17021
  if (response.status === 202 && response.contentType?.includes("application/json")) {
16860
17022
  try {
@@ -16884,7 +17046,7 @@ function settleCustodyOfferExchange(awaiting, response) {
16884
17046
  }
16885
17047
  }
16886
17048
  function encodeInlineCustodyOffer(args) {
16887
- return toBinary17(CustodyOfferBatchRequestSchema, create53(CustodyOfferBatchRequestSchema, {
17049
+ return toBinary18(CustodyOfferBatchRequestSchema, create53(CustodyOfferBatchRequestSchema, {
16888
17050
  protocolVersion: 2,
16889
17051
  requestId: args.requestId,
16890
17052
  source: {
@@ -16904,7 +17066,7 @@ function encodeInlineCustodyOffer(args) {
16904
17066
  }));
16905
17067
  }
16906
17068
  function decodeCustodyOffer(bytes, requestId) {
16907
- const response = fromBinary19(CustodyOfferBatchResponseSchema, bytes);
17069
+ const response = fromBinary20(CustodyOfferBatchResponseSchema, bytes);
16908
17070
  if (response.protocolVersion !== 2 || response.requestId !== requestId) {
16909
17071
  throw new Error("custody offer returned a mismatched generated response");
16910
17072
  }
@@ -17016,7 +17178,7 @@ var init_custody_offer = __esm({
17016
17178
  });
17017
17179
 
17018
17180
  // ../peer-office/src/runtime/workspace_sync.ts
17019
- import { create as create54, fromBinary as fromBinary20 } from "@bufbuild/protobuf";
17181
+ import { create as create54, fromBinary as fromBinary21 } from "@bufbuild/protobuf";
17020
17182
  function releaseSyncJudgment(workspace) {
17021
17183
  judgedThisLifetime.delete(workspace);
17022
17184
  }
@@ -17095,6 +17257,7 @@ var init_workspace_sync = __esm({
17095
17257
  #offerSequence = 0;
17096
17258
  #lastStep;
17097
17259
  #probeOnly;
17260
+ #liveConnected;
17098
17261
  /** Set when this round adopted the upstream's own head as its base (see #establishBase). */
17099
17262
  #establishedBase;
17100
17263
  #receiveState;
@@ -17127,6 +17290,7 @@ var init_workspace_sync = __esm({
17127
17290
  this.#directoryAnswered = args.directoryAnswered;
17128
17291
  this.#placementFetched = args.placementFetched;
17129
17292
  this.#probeOnly = args.probeOnly ?? false;
17293
+ this.#liveConnected = args.liveConnected === true;
17130
17294
  this.#receiveState = args.receiveState;
17131
17295
  this.#completeHistory = args.completeHistory === true;
17132
17296
  this.#repairMissingCommit = args.repairMissingCommit === true;
@@ -17197,6 +17361,9 @@ var init_workspace_sync = __esm({
17197
17361
  #openRound() {
17198
17362
  if (this.#receiveState || this.#replaceLocalHead !== void 0) return this.#leaseEffect();
17199
17363
  if (!this.#localHead) return this.#leaseEffect();
17364
+ if (this.#liveConnected && !this.#probeOnly && this.#holdsLocalWork() && this.#previousHead) {
17365
+ return this.#offerOrReconcile();
17366
+ }
17200
17367
  const requestId = `${this.#binding.replicaId}:${this.#requestId}:${this.workId}:frontier`;
17201
17368
  return this.#beginOffer(encodeInlineCustodyOffer({
17202
17369
  session: this.#binding.replicaId,
@@ -17428,6 +17595,18 @@ var init_workspace_sync = __esm({
17428
17595
  return this.#finishOfferOutcome(false);
17429
17596
  }
17430
17597
  const admission = outcome.value;
17598
+ globalThis.__nomosSyncDiagnostic?.("sync.admission", {
17599
+ workspace: this.#mount.workspace,
17600
+ phase: state.phase,
17601
+ local: this.#localHead,
17602
+ tracked: this.#previousHead,
17603
+ remote: admission.main,
17604
+ sealed: admission.sealedMain,
17605
+ resultBase: admission.resultBase,
17606
+ resultBytes: admission.resultPack.byteLength,
17607
+ recoveryRequired: admission.recoveryRequired,
17608
+ summary: summarizeCustodyAdmission(admission)
17609
+ });
17431
17610
  this.#desiredHead = admission.main || void 0;
17432
17611
  if (!this.#desiredHead) return this.#transportFailure("resident peer returned no admitted frontier", false);
17433
17612
  this.#candidateDurable = admission.sealedMain === this.#desiredHead;
@@ -17702,7 +17881,7 @@ var init_workspace_sync = __esm({
17702
17881
  #acceptLawProducts(response) {
17703
17882
  if (response.status !== 200 || response.contentType?.split(";")[0]?.trim() !== LAW_PRODUCTS_MEDIA_TYPE) return;
17704
17883
  try {
17705
- const exported = fromBinary20(ExportLawProductsResponseSchema, response.body);
17884
+ const exported = fromBinary21(ExportLawProductsResponseSchema, response.body);
17706
17885
  this.#fetchedLawProducts = { head: exported.head, products: exported.products };
17707
17886
  } catch {
17708
17887
  }
@@ -18044,6 +18223,19 @@ var init_workspace_sync = __esm({
18044
18223
  return step;
18045
18224
  }
18046
18225
  #finish(value) {
18226
+ globalThis.__nomosSyncDiagnostic?.("sync.finished", {
18227
+ workspace: value.workspace,
18228
+ previous: value.previousHead,
18229
+ current: value.currentHead,
18230
+ stillAhead: value.stillAhead,
18231
+ deferred: String(value.deferred),
18232
+ admitted: String(value.admitted),
18233
+ reconnect: value.reconnectRequired,
18234
+ directOfferDeferred: value.directOfferDeferred,
18235
+ pushFailed: value.pushFailed,
18236
+ failure: value.pushError?.message,
18237
+ wallMs: elapsedMillis(this.#clock, this.#started)
18238
+ });
18047
18239
  this.#state = { phase: WorkspaceSyncPhase.Done };
18048
18240
  this.#current = void 0;
18049
18241
  return this.#remember({ case: "synced", value });
@@ -18108,6 +18300,10 @@ var init_workspace_sync_dependencies = __esm({
18108
18300
  this.#plan = [this.#args.root];
18109
18301
  return this.#advance();
18110
18302
  }
18303
+ if (this.#args.liveConnected && this.#args.kernel.resolveRef(this.#args.root.mount, this.#args.requestId, trackedMain2)) {
18304
+ this.#plan = this.#planDependencies();
18305
+ return this.#advance();
18306
+ }
18111
18307
  this.#current = this.#work(this.#args.root, `${this.workId}:frontier`, true);
18112
18308
  return this.#accept(this.#current.start());
18113
18309
  }
@@ -18427,7 +18623,7 @@ var init_offer_transport_contract = __esm({
18427
18623
  });
18428
18624
 
18429
18625
  // ../peer-office/src/runtime/workspace_effect_delivery.ts
18430
- import { create as create56, fromBinary as fromBinary21, toBinary as toBinary18 } from "@bufbuild/protobuf";
18626
+ import { create as create56, fromBinary as fromBinary22, toBinary as toBinary19 } from "@bufbuild/protobuf";
18431
18627
  function answered(response) {
18432
18628
  const text = (response.contentType ?? "").startsWith("text/") || (response.contentType ?? "").includes("json") ? new TextDecoder().decode(response.body.subarray(0, RETRY_DETAIL_CHARACTERS)).trim() : "";
18433
18629
  return `HTTP ${response.status} ${response.contentType || "without a media type"}${text ? `: ${text}` : ""}`;
@@ -18818,7 +19014,7 @@ var init_workspace_effect_delivery = __esm({
18818
19014
  }
18819
19015
  let status;
18820
19016
  try {
18821
- status = fromBinary21(WorkspaceEffectStatusResponseSchema, observation.body);
19017
+ status = fromBinary22(WorkspaceEffectStatusResponseSchema, observation.body);
18822
19018
  } catch {
18823
19019
  return this.#transportFailed("mailbox returned an invalid effect observation");
18824
19020
  }
@@ -18833,7 +19029,7 @@ var init_workspace_effect_delivery = __esm({
18833
19029
  return this.#advance(this.#delivery.next(response2, this.#settlement));
18834
19030
  }
18835
19031
  if (receipt.outcome.value.status === 202 && (receipt.outcome.value.contentType ?? "").includes(WORKSPACE_EFFECT_DEFERRED)) {
18836
- const deferred = fromBinary21(WorkspaceEffectDeferredSchema, receipt.outcome.value.body);
19032
+ const deferred = fromBinary22(WorkspaceEffectDeferredSchema, receipt.outcome.value.body);
18837
19033
  this.#deferredRetryAfterMillis = Math.max(
18838
19034
  this.#deferredRetryAfterMillis ?? 0,
18839
19035
  Number(deferred.retryAfterMillis)
@@ -18858,7 +19054,7 @@ var init_workspace_effect_delivery = __esm({
18858
19054
  }
18859
19055
  let applied;
18860
19056
  try {
18861
- applied = fromBinary21(OfferResponseSchema, receipt.outcome.value.body);
19057
+ applied = fromBinary22(OfferResponseSchema, receipt.outcome.value.body);
18862
19058
  } catch {
18863
19059
  return this.#transportFailed("remote workspace returned an invalid offer response");
18864
19060
  }
@@ -18980,7 +19176,7 @@ var init_workspace_effect_delivery = __esm({
18980
19176
  url: this.#mailboxUrl,
18981
19177
  contentType: WORKSPACE_EFFECT_STATUS,
18982
19178
  accept: WORKSPACE_EFFECT_STATUS_RESPONSE,
18983
- body: toBinary18(WorkspaceEffectStatusRequestSchema, create56(WorkspaceEffectStatusRequestSchema, {
19179
+ body: toBinary19(WorkspaceEffectStatusRequestSchema, create56(WorkspaceEffectStatusRequestSchema, {
18984
19180
  sourceWorkspaceGenesis: offer.sourceWorkspaceGenesis,
18985
19181
  effectDigest: offer.effectDigest
18986
19182
  }))
@@ -19007,7 +19203,7 @@ var init_workspace_effect_delivery = __esm({
19007
19203
  url: this.#mailboxUrl,
19008
19204
  contentType: CARRIED_OFFER,
19009
19205
  accept: CARRIED_OFFER_RESPONSE,
19010
- body: toBinary18(OfferRequestSchema, body)
19206
+ body: toBinary19(OfferRequestSchema, body)
19011
19207
  });
19012
19208
  this.#pending = create56(CorrespondencePendingSchema, {
19013
19209
  workId: this.workId,
@@ -19020,7 +19216,7 @@ var init_workspace_effect_delivery = __esm({
19020
19216
  });
19021
19217
 
19022
19218
  // ../peer-office/src/runtime/replica_follow_lane.ts
19023
- import { create as create57, toBinary as toBinary19 } from "@bufbuild/protobuf";
19219
+ import { create as create57, toBinary as toBinary20 } from "@bufbuild/protobuf";
19024
19220
  var ReplicaFollowLane;
19025
19221
  var init_replica_follow_lane = __esm({
19026
19222
  "../peer-office/src/runtime/replica_follow_lane.ts"() {
@@ -19102,7 +19298,7 @@ var init_replica_follow_lane = __esm({
19102
19298
  if (action === ReplicaFollowAction.RefreshCredential) {
19103
19299
  return {
19104
19300
  workspace,
19105
- frame: toBinary19(RuntimeRequestSchema, create57(RuntimeRequestSchema, {
19301
+ frame: toBinary20(RuntimeRequestSchema, create57(RuntimeRequestSchema, {
19106
19302
  protocolVersion: 2,
19107
19303
  requestId,
19108
19304
  command: {
@@ -19117,7 +19313,7 @@ var init_replica_follow_lane = __esm({
19117
19313
  const replaceLocalHead = this.#controller.replacementHead(workspace);
19118
19314
  return {
19119
19315
  workspace,
19120
- frame: toBinary19(RuntimeRequestSchema, create57(RuntimeRequestSchema, {
19316
+ frame: toBinary20(RuntimeRequestSchema, create57(RuntimeRequestSchema, {
19121
19317
  protocolVersion: 2,
19122
19318
  requestId,
19123
19319
  command: {
@@ -19314,7 +19510,7 @@ var init_http_obligation_delivery = __esm({
19314
19510
  });
19315
19511
 
19316
19512
  // ../peer-office/src/runtime/correspondence_desk.ts
19317
- import { create as create59, toBinary as toBinary20 } from "@bufbuild/protobuf";
19513
+ import { create as create59, toBinary as toBinary21 } from "@bufbuild/protobuf";
19318
19514
  var REFETCH_AWAITS_PROVIDER, LOCAL_COPY_REFETCHING, CorrespondenceDesk;
19319
19515
  var init_correspondence_desk = __esm({
19320
19516
  "../peer-office/src/runtime/correspondence_desk.ts"() {
@@ -19372,6 +19568,7 @@ var init_correspondence_desk = __esm({
19372
19568
  #onSyncCompleted;
19373
19569
  #onPlacementFetched;
19374
19570
  #onShallowMount;
19571
+ #onOutboxHistoryRequired;
19375
19572
  #remoteOffers = new CorrespondenceWorkRegistry();
19376
19573
  #recoveries = new CorrespondenceWorkRegistry();
19377
19574
  #deliveries = new CorrespondenceWorkRegistry();
@@ -19418,6 +19615,7 @@ var init_correspondence_desk = __esm({
19418
19615
  this.#onSyncCompleted = args.onSyncCompleted;
19419
19616
  this.#onPlacementFetched = args.onPlacementFetched;
19420
19617
  this.#onShallowMount = args.onShallowMount;
19618
+ this.#onOutboxHistoryRequired = args.onOutboxHistoryRequired;
19421
19619
  this.#clock = args.clock;
19422
19620
  this.#outboxClock = new OutboxObservationClock(args.clock, args.peerIdentity);
19423
19621
  this.#executesCustodianObligations = args.executesCustodianObligations ?? false;
@@ -19581,6 +19779,15 @@ var init_correspondence_desk = __esm({
19581
19779
  this.#followLane.dependencyAdvanced(workspace);
19582
19780
  this.reportFollows();
19583
19781
  }
19782
+ /** Received custody can release correspondence and foreign-read dependencies,
19783
+ * but is not newly authored work to send back to its upstream. Recovery is
19784
+ * driven separately by missing history, reconnects and provider announcements.
19785
+ * In particular an optimistic relay is not a durable upstream receipt. */
19786
+ receivedFrontierChanged(workspace) {
19787
+ this.wakeOutbox(workspace);
19788
+ this.#followLane.dependencyAdvanced(workspace);
19789
+ this.reportFollows();
19790
+ }
19584
19791
  /**
19585
19792
  * Tell a workspace's sessions what its durable follow ALREADY knows.
19586
19793
  *
@@ -19817,8 +20024,16 @@ var init_correspondence_desk = __esm({
19817
20024
  )
19818
20025
  );
19819
20026
  } catch (error) {
20027
+ if (error instanceof KernelHistoryRequired && this.#onOutboxHistoryRequired) {
20028
+ const retry = this.#onOutboxHistoryRequired(workspace, binding.credentialCapability);
20029
+ this.#outboxDueAt.set(workspace, now + Math.max(250, retry));
20030
+ return { nextAfterMillis: 0 };
20031
+ }
19820
20032
  const format = localCopyFormatRefusal(error);
19821
- if (format === void 0) throw error;
20033
+ if (format === void 0) {
20034
+ this.#outboxDueAt.set(workspace, now + 3e4);
20035
+ return { nextAfterMillis: 0 };
20036
+ }
19822
20037
  this.#readability.mark(workspace, void 0, format);
19823
20038
  this.#outboxDueAt.delete(workspace);
19824
20039
  return { nextAfterMillis: 0 };
@@ -19899,7 +20114,7 @@ var init_correspondence_desk = __esm({
19899
20114
  };
19900
20115
  return {
19901
20116
  workspace,
19902
- frame: toBinary20(RuntimeRequestSchema, create59(RuntimeRequestSchema, {
20117
+ frame: toBinary21(RuntimeRequestSchema, create59(RuntimeRequestSchema, {
19903
20118
  protocolVersion: 2,
19904
20119
  requestId,
19905
20120
  target: { workspace, session: binding.session },
@@ -20098,6 +20313,7 @@ var init_correspondence_desk = __esm({
20098
20313
  requestId: request.requestId,
20099
20314
  workId: id,
20100
20315
  probeOnly,
20316
+ liveConnected: this.#openLinks.has(target3.mount.workspace),
20101
20317
  ...beforeConverge === void 0 ? {} : { beforeConverge },
20102
20318
  ...target3.receiveState === void 0 ? {} : { receiveState: target3.receiveState },
20103
20319
  ...target3.offerHead === void 0 ? {} : { offerHead: target3.offerHead },
@@ -20125,6 +20341,7 @@ var init_correspondence_desk = __esm({
20125
20341
  root,
20126
20342
  work,
20127
20343
  outbound: command.admit,
20344
+ liveConnected: this.#openLinks.has(mount.workspace),
20128
20345
  dependency: (workspace, source, acquire2 = false) => {
20129
20346
  if (this.#roundInFlight(workspace, workId2)) return void 0;
20130
20347
  const existing = this.#follows.bindingForWorkspace(workspace);
@@ -20595,7 +20812,7 @@ var init_identity_witness_cache = __esm({
20595
20812
  });
20596
20813
 
20597
20814
  // ../peer-office/src/runtime/identity_witness_read.ts
20598
- import { create as create62, fromBinary as fromBinary22, toBinary as toBinary21 } from "@bufbuild/protobuf";
20815
+ import { create as create62, fromBinary as fromBinary23, toBinary as toBinary22 } from "@bufbuild/protobuf";
20599
20816
  function prepareWitnessRead(args) {
20600
20817
  if (args.reception.workspace !== args.rootWorkspace) {
20601
20818
  throw new Error("identity-provider witness route addresses another workspace");
@@ -20633,7 +20850,7 @@ function prepareWitnessRead(args) {
20633
20850
  contentType: "application/vnd.nomos.runtime-request+protobuf",
20634
20851
  accept: "application/vnd.nomos.runtime-response+protobuf",
20635
20852
  bearerToken: args.bearerToken.slice(),
20636
- body: toBinary21(RuntimeRequestSchema, request),
20853
+ body: toBinary22(RuntimeRequestSchema, request),
20637
20854
  // Opening provider custody from cold storage can exceed 30 seconds.
20638
20855
  timeoutMillis: 5 * 6e4
20639
20856
  })
@@ -20663,7 +20880,7 @@ function acceptWitnessResponse(pending, receipt) {
20663
20880
  `identity-provider witness receipt '${receipt.effectId}' does not answer '${pending.effectId}'`
20664
20881
  );
20665
20882
  }
20666
- const response = fromBinary22(RuntimeResponseSchema, responseBody2(receipt));
20883
+ const response = fromBinary23(RuntimeResponseSchema, responseBody2(receipt));
20667
20884
  if (response.protocolVersion !== RUNTIME_V2_PROTOCOL_VERSION) {
20668
20885
  throw new Error("identity-provider root returned an incompatible runtime response");
20669
20886
  }
@@ -21029,7 +21246,7 @@ var init_admission_durability_desk = __esm({
21029
21246
  });
21030
21247
 
21031
21248
  // ../peer-office/src/runtime/identity_recovery_desk.ts
21032
- import { create as create66, fromBinary as fromBinary23, toBinary as toBinary22 } from "@bufbuild/protobuf";
21249
+ import { create as create66, fromBinary as fromBinary24, toBinary as toBinary23 } from "@bufbuild/protobuf";
21033
21250
  var cloneCall, IdentityRecoveryDesk;
21034
21251
  var init_identity_recovery_desk = __esm({
21035
21252
  "../peer-office/src/runtime/identity_recovery_desk.ts"() {
@@ -21038,7 +21255,7 @@ var init_identity_recovery_desk = __esm({
21038
21255
  init_credentials_desk_pb();
21039
21256
  init_identity_desk_pb();
21040
21257
  init_application_desk_pb();
21041
- cloneCall = (call) => fromBinary23(CallRequestSchema, toBinary22(CallRequestSchema, call));
21258
+ cloneCall = (call) => fromBinary24(CallRequestSchema, toBinary23(CallRequestSchema, call));
21042
21259
  IdentityRecoveryDesk = class {
21043
21260
  #identity;
21044
21261
  #application;
@@ -21056,7 +21273,7 @@ var init_identity_recovery_desk = __esm({
21056
21273
  if (!command.request || !["query", "offer"].includes(command.request.operation.case ?? "")) {
21057
21274
  throw new Error("identity-provider recovery demand did not originate from an application call");
21058
21275
  }
21059
- const originalCall = toBinary22(CallRequestSchema, command.request);
21276
+ const originalCall = toBinary23(CallRequestSchema, command.request);
21060
21277
  const step = this.#identity.execute(
21061
21278
  runtimeRequest,
21062
21279
  create66(IdentityProviderWitnessRequestSchema, {
@@ -21136,7 +21353,7 @@ var init_identity_recovery_desk = __esm({
21136
21353
  }
21137
21354
  }
21138
21355
  #adoptAndRetry(runtimeRequest, command, originalCall, requirement, ready) {
21139
- const original = fromBinary23(CallRequestSchema, originalCall);
21356
+ const original = fromBinary24(CallRequestSchema, originalCall);
21140
21357
  const query2 = original.operation.case === "query" ? original.operation.value : void 0;
21141
21358
  const offer = original.operation.case === "offer" ? original.operation.value : void 0;
21142
21359
  const target3 = query2?.target ?? offer?.target;
@@ -21184,7 +21401,7 @@ var init_identity_recovery_desk = __esm({
21184
21401
  const retryCommand = create66(KernelCallRequestSchema, {
21185
21402
  session: command.session,
21186
21403
  credentialUse: command.credentialUse,
21187
- request: cloneCall(fromBinary23(CallRequestSchema, originalCall))
21404
+ request: cloneCall(fromBinary24(CallRequestSchema, originalCall))
21188
21405
  });
21189
21406
  const retried = this.#application.call(runtimeRequest, retryCommand);
21190
21407
  if (retried.outcome.case === "failure" && retried.outcome.value.identityProviderWitnessRequired) {
@@ -21258,7 +21475,7 @@ var init_peer_maintenance_scheduler = __esm({
21258
21475
  });
21259
21476
 
21260
21477
  // ../peer-office/src/runtime/peer_background_scheduler.ts
21261
- import { create as create67, toBinary as toBinary23 } from "@bufbuild/protobuf";
21478
+ import { create as create67, toBinary as toBinary24 } from "@bufbuild/protobuf";
21262
21479
  function yielding(paper) {
21263
21480
  if (paper.frame !== void 0 || paper.nextAfterMillis === void 0 || paper.nextAfterMillis > 0) return paper;
21264
21481
  return { ...paper, nextAfterMillis: BACKGROUND_CONTINUATION_YIELD_MILLIS };
@@ -21298,7 +21515,7 @@ var init_peer_background_scheduler = __esm({
21298
21515
  const recovery = retentionOnly ? {} : this.#subscriptions.nextRecovery(id, excludedWorkspaces);
21299
21516
  if (recovery.request) {
21300
21517
  return {
21301
- frame: toBinary23(RuntimeRequestSchema, recovery.request),
21518
+ frame: toBinary24(RuntimeRequestSchema, recovery.request),
21302
21519
  nextAfterMillis: 0,
21303
21520
  workspace: recovery.request.target.workspace
21304
21521
  };
@@ -21306,7 +21523,7 @@ var init_peer_background_scheduler = __esm({
21306
21523
  const retention = this.#residency.nextRetention();
21307
21524
  if (retention.request !== void 0) {
21308
21525
  return {
21309
- frame: toBinary23(RuntimeRequestSchema, create67(RuntimeRequestSchema, {
21526
+ frame: toBinary24(RuntimeRequestSchema, create67(RuntimeRequestSchema, {
21310
21527
  protocolVersion: 2,
21311
21528
  requestId: id,
21312
21529
  command: {
@@ -21323,7 +21540,7 @@ var init_peer_background_scheduler = __esm({
21323
21540
  const convergence = this.#receivingGroup.nextBackgroundPaper(id, excludedWorkspaces);
21324
21541
  if (convergence.frame !== void 0) {
21325
21542
  return {
21326
- frame: toBinary23(RuntimeRequestSchema, convergence.frame),
21543
+ frame: toBinary24(RuntimeRequestSchema, convergence.frame),
21327
21544
  nextAfterMillis: 0,
21328
21545
  ...convergence.workspace === void 0 ? {} : { workspace: convergence.workspace }
21329
21546
  };
@@ -21384,7 +21601,7 @@ var init_peer_background_scheduler = __esm({
21384
21601
  const recovery = this.#subscriptions.nextRecovery(id, excluded);
21385
21602
  if (recovery.request) {
21386
21603
  return {
21387
- frame: toBinary23(RuntimeRequestSchema, recovery.request),
21604
+ frame: toBinary24(RuntimeRequestSchema, recovery.request),
21388
21605
  nextAfterMillis: 0,
21389
21606
  workspace: recovery.request.target.workspace
21390
21607
  };
@@ -21392,7 +21609,7 @@ var init_peer_background_scheduler = __esm({
21392
21609
  const convergence = this.#receivingGroup.nextBackgroundPaper(id, excluded);
21393
21610
  if (convergence.frame !== void 0) {
21394
21611
  return {
21395
- frame: toBinary23(RuntimeRequestSchema, convergence.frame),
21612
+ frame: toBinary24(RuntimeRequestSchema, convergence.frame),
21396
21613
  nextAfterMillis: 0,
21397
21614
  ...convergence.workspace === void 0 ? {} : { workspace: convergence.workspace }
21398
21615
  };
@@ -21764,7 +21981,7 @@ var init_history_acquisition_state = __esm({
21764
21981
  });
21765
21982
 
21766
21983
  // ../peer-office/src/runtime/history_acquisition_desk.ts
21767
- import { create as create69, toBinary as toBinary24 } from "@bufbuild/protobuf";
21984
+ import { create as create69, toBinary as toBinary25 } from "@bufbuild/protobuf";
21768
21985
  function assertState2(record, state) {
21769
21986
  switch (state.case) {
21770
21987
  case HistoryAcquisitionPhase.Desired:
@@ -21783,7 +22000,7 @@ function assertState2(record, state) {
21783
22000
  }
21784
22001
  throw corrupt2(record, `invalid '${state.case}' state`);
21785
22002
  }
21786
- var HISTORY_ACQUISITION_NAMESPACE, HISTORY_BACKGROUND_START_MILLIS, SLICE_ANSWER_MILLIS, encoder3, decoder3, workId, effectId, encode2, upgraded, decode2, corrupt2, HistoryAcquisitionDesk;
22003
+ var HISTORY_ACQUISITION_NAMESPACE, HISTORY_BACKGROUND_START_MILLIS, SLICE_ANSWER_MILLIS, encoder4, decoder4, workId, effectId, encode2, upgraded, decode2, corrupt2, HistoryAcquisitionDesk;
21787
22004
  var init_history_acquisition_desk = __esm({
21788
22005
  "../peer-office/src/runtime/history_acquisition_desk.ts"() {
21789
22006
  "use strict";
@@ -21794,15 +22011,15 @@ var init_history_acquisition_desk = __esm({
21794
22011
  HISTORY_ACQUISITION_NAMESPACE = "nomos.peer-desk.history-acquisition/v1";
21795
22012
  HISTORY_BACKGROUND_START_MILLIS = 1e4;
21796
22013
  SLICE_ANSWER_MILLIS = 5 * 6e4;
21797
- encoder3 = new TextEncoder();
21798
- decoder3 = new TextDecoder();
22014
+ encoder4 = new TextEncoder();
22015
+ decoder4 = new TextDecoder();
21799
22016
  workId = (workspace) => `history-acquisition:${workspace}`;
21800
22017
  effectId = (workspace, attempt) => `history-acquisition:${workspace}:${HistoryAcquisitionPhase.Acquiring}:${attempt}`;
21801
22018
  encode2 = (work) => {
21802
22019
  if (!work.credentialCapability) {
21803
22020
  throw new Error(`history acquisition for '${work.workspace}' has not restored its credential capability`);
21804
22021
  }
21805
- return encoder3.encode(JSON.stringify({
22022
+ return encoder4.encode(JSON.stringify({
21806
22023
  version: 2,
21807
22024
  workspace: work.workspace,
21808
22025
  credentialCapability: work.credentialCapability,
@@ -21811,7 +22028,7 @@ var init_history_acquisition_desk = __esm({
21811
22028
  };
21812
22029
  upgraded = (state) => state.case === "backoff" ? { case: HistoryAcquisitionPhase.Paced, attempt: state.attempt, delayMillis: state.delayMillis, failed: true } : state;
21813
22030
  decode2 = (record) => {
21814
- const value = JSON.parse(decoder3.decode(record.value));
22031
+ const value = JSON.parse(decoder4.decode(record.value));
21815
22032
  if (!value || typeof value !== "object") throw corrupt2(record, "not an object");
21816
22033
  const candidate = value;
21817
22034
  if (candidate.version !== 1 && candidate.version !== 2 || candidate.workspace !== record.key || !candidate.state) {
@@ -21856,6 +22073,21 @@ var init_history_acquisition_desk = __esm({
21856
22073
  this.#ensure(workspace, credentialCapability);
21857
22074
  this.#dueAt.set(workspace, this.#now() + HISTORY_BACKGROUND_START_MILLIS);
21858
22075
  }
22076
+ /** A background kernel read needs an omitted ancestor now. Queue one bounded
22077
+ * slice on the existing history lane; a failed slice keeps its retry pace. */
22078
+ requestFromBackground(workspace, credentialCapability) {
22079
+ if (!workspace) throw new Error("kernel history requirement names no workspace");
22080
+ this.#ensure(workspace, credentialCapability);
22081
+ const work = this.#get(workspace);
22082
+ const now = this.#now();
22083
+ if (work.state.case === HistoryAcquisitionPhase.Paced && work.state.failed) {
22084
+ const due2 = this.#dueAt.get(workspace) ?? now + work.state.delayMillis;
22085
+ this.#dueAt.set(workspace, due2);
22086
+ if (due2 > now) return due2 - now;
22087
+ }
22088
+ this.#dueAt.set(workspace, now);
22089
+ return 250;
22090
+ }
21859
22091
  /** An operation needs history this custody lacks: its next slice now, joining one in flight. */
21860
22092
  begin(workspace, credentialCapability) {
21861
22093
  if (!workspace) throw new Error("kernel history requirement names no workspace");
@@ -21952,7 +22184,7 @@ var init_history_acquisition_desk = __esm({
21952
22184
  return {
21953
22185
  workspace: next.workspace,
21954
22186
  nextAfterMillis: 0,
21955
- frame: toBinary24(RuntimeRequestSchema, create69(RuntimeRequestSchema, {
22187
+ frame: toBinary25(RuntimeRequestSchema, create69(RuntimeRequestSchema, {
21956
22188
  protocolVersion: 2,
21957
22189
  requestId,
21958
22190
  target: { workspace: next.workspace, session: `history-materialisation:${next.workspace}` },
@@ -22053,7 +22285,7 @@ var init_history_acquisition_desk = __esm({
22053
22285
  });
22054
22286
 
22055
22287
  // ../peer-office/src/peer_office.ts
22056
- import { create as create70, toBinary as toBinary25 } from "@bufbuild/protobuf";
22288
+ import { create as create70, toBinary as toBinary26 } from "@bufbuild/protobuf";
22057
22289
  function isAnsweredStateRead(command, response) {
22058
22290
  if (command.request?.operation.case !== "query" || response.outcome.case !== "query" || response.outcome.value.result.case === "readIndexPending") return false;
22059
22291
  switch (command.request.operation.value.query.case) {
@@ -22095,6 +22327,7 @@ var init_peer_office = __esm({
22095
22327
  init_credentials_desk_pb();
22096
22328
  init_framework_pb();
22097
22329
  init_sha256();
22330
+ init_custody_receipts();
22098
22331
  init_custodian_placement();
22099
22332
  init_custody_admission_desk();
22100
22333
  init_kernel_queries();
@@ -22240,7 +22473,7 @@ var init_peer_office = __esm({
22240
22473
  this.#trace,
22241
22474
  this.#readability
22242
22475
  );
22243
- this.#custodyAdmission = new CustodyAdmissionDesk(this.#kernel, this.#custody);
22476
+ this.#custodyAdmission = new CustodyAdmissionDesk(this.#kernel, this.#custody, new CustodyReceipts(seatedStore));
22244
22477
  this.#queries = new KernelQueries(this.#kernel, this.#credentials);
22245
22478
  this.#follows = new ReplicaFollowController(
22246
22479
  new ReplicaFollowDesk(seatedStore),
@@ -22402,6 +22635,7 @@ var init_peer_office = __esm({
22402
22635
  // Lazy history: a head-only mount materialises its history in the background, never on
22403
22636
  // the path of an operation (architecture/lazy_history.md).
22404
22637
  onShallowMount: (workspace, credentialCapability) => this.#historyAcquisition.materialise(workspace, credentialCapability),
22638
+ onOutboxHistoryRequired: (workspace, credentialCapability) => this.#historyAcquisition.requestFromBackground(workspace, credentialCapability),
22405
22639
  onSyncCompleted: (session, event) => {
22406
22640
  if (event.result?.workspace) {
22407
22641
  this.#replicaInventory.placementMayHaveChanged(event.result.workspace);
@@ -22751,7 +22985,7 @@ var init_peer_office = __esm({
22751
22985
  this.#origins.observeReceipt(request);
22752
22986
  const response = this.#fenced(this.#handleRequest(request));
22753
22987
  this.#paperSlots.answered(request, response, (session) => this.#sessions.bindingIfPresent(session)?.workspace);
22754
- return { responseProtobuf: toBinary25(RuntimeResponseSchema, response) };
22988
+ return { responseProtobuf: toBinary26(RuntimeResponseSchema, response) };
22755
22989
  }
22756
22990
  /** Every response leaving the office passes the origin fence (see fenceEffects). */
22757
22991
  #fenced(response) {
@@ -22868,8 +23102,8 @@ var init_peer_office = __esm({
22868
23102
  this.#replicaInventory.placementMayHaveChanged(workspace);
22869
23103
  }
22870
23104
  }
22871
- /** Execute a typed paper after the access desk; never skip lifecycle or
22872
- * session-binding checks merely because its caller is another local desk. */
23105
+ /** Execute a typed paper after the access desk. Custody admission addresses a
23106
+ * workspace by replica identity; application calls retain session binding. */
22873
23107
  #dispatchRequest(request) {
22874
23108
  validateRuntimeV2Request(request);
22875
23109
  try {
@@ -22883,18 +23117,20 @@ var init_peer_office = __esm({
22883
23117
  if (!request.target.workspace || !request.target.session) {
22884
23118
  throw new Error("addressed runtime request requires workspace and session");
22885
23119
  }
22886
- const binding = this.#sessions.bindingIfPresent(request.target.session);
22887
- if (binding !== void 0) {
22888
- if (binding.workspace !== request.target.workspace) {
22889
- throw new Error(
22890
- `session '${request.target.session}' is bound to workspace '${binding.workspace}', not '${request.target.workspace}'`
22891
- );
23120
+ if (request.command.case !== "admitCustodyOffers") {
23121
+ const binding = this.#sessions.bindingIfPresent(request.target.session);
23122
+ if (binding !== void 0) {
23123
+ if (binding.workspace !== request.target.workspace) {
23124
+ throw new Error(
23125
+ `session '${request.target.session}' is bound to workspace '${binding.workspace}', not '${request.target.workspace}'`
23126
+ );
23127
+ }
23128
+ } else {
23129
+ this.#bindInteraction(create70(BindSessionRequestSchema, {
23130
+ session: request.target.session,
23131
+ workspace: request.target.workspace
23132
+ }));
22892
23133
  }
22893
- } else {
22894
- this.#bindInteraction(create70(BindSessionRequestSchema, {
22895
- session: request.target.session,
22896
- workspace: request.target.workspace
22897
- }));
22898
23134
  }
22899
23135
  }
22900
23136
  switch (request.command.case) {
@@ -23091,7 +23327,7 @@ var init_peer_office = __esm({
23091
23327
  ReadMaintenanceCause.ADMITTED_OFFER
23092
23328
  );
23093
23329
  this.#subscriptions.refreshWorkspace(request.target.workspace);
23094
- this.#correspondence.workspaceFrontierChanged(request.target.workspace);
23330
+ this.#correspondence.receivedFrontierChanged(request.target.workspace);
23095
23331
  }
23096
23332
  return this.#birthCustodyResponse(
23097
23333
  request,
@@ -23670,6 +23906,15 @@ function createBackgroundLanes(options) {
23670
23906
  const correspondenceNotBefore = /* @__PURE__ */ new Map();
23671
23907
  let retention = 0;
23672
23908
  let closed = false;
23909
+ let selectionFailures = 0;
23910
+ const selectionFault = (error) => {
23911
+ try {
23912
+ options.onSelectionError?.(error);
23913
+ } catch {
23914
+ }
23915
+ selectionFailures += 1;
23916
+ wake(Math.min(3e4, 250 * 2 ** Math.min(selectionFailures - 1, 7)));
23917
+ };
23673
23918
  const wake = (delayMillis = 0) => {
23674
23919
  if (closed) return;
23675
23920
  const delay = Math.max(0, Math.ceil(delayMillis));
@@ -23680,53 +23925,58 @@ function createBackgroundLanes(options) {
23680
23925
  }
23681
23926
  wakeAt = at;
23682
23927
  timer = setTimer(() => {
23683
- timer = void 0;
23684
- wakeAt = void 0;
23685
- if (closed) return;
23686
- const now = options.monotonicNanoseconds();
23687
- for (const [workspace2, at2] of correspondenceNotBefore) {
23688
- if (at2 <= now) correspondenceNotBefore.delete(workspace2);
23689
- }
23690
- const backoffMillis = correspondenceNotBefore.size ? Math.min(...[...correspondenceNotBefore.values()].map((at2) => Number((at2 - now + 999999n) / 1000000n))) : void 0;
23691
- const retentionOnly = correspondenceInFlight;
23692
- const next = options.nextPaper(retentionOnly, new Set(correspondenceNotBefore.keys()));
23693
- if (next.frame === void 0) {
23694
- const delays = [next.nextAfterMillis, backoffMillis].filter((delay2) => delay2 !== void 0);
23695
- if (delays.length) wake(Math.min(...delays));
23696
- return;
23697
- }
23698
- if (options.isRetention(next.frame)) {
23699
- retention += 1;
23928
+ try {
23929
+ timer = void 0;
23930
+ wakeAt = void 0;
23931
+ if (closed) return;
23932
+ const now = options.monotonicNanoseconds();
23933
+ for (const [workspace2, at2] of correspondenceNotBefore) {
23934
+ if (at2 <= now) correspondenceNotBefore.delete(workspace2);
23935
+ }
23936
+ const backoffMillis = correspondenceNotBefore.size ? Math.min(...[...correspondenceNotBefore.values()].map((at2) => Number((at2 - now + 999999n) / 1000000n))) : void 0;
23937
+ const retentionOnly = correspondenceInFlight;
23938
+ const next = options.nextPaper(retentionOnly, new Set(correspondenceNotBefore.keys()));
23939
+ selectionFailures = 0;
23940
+ if (next.frame === void 0) {
23941
+ const delays = [next.nextAfterMillis, backoffMillis].filter((delay2) => delay2 !== void 0);
23942
+ if (delays.length) wake(Math.min(...delays));
23943
+ return;
23944
+ }
23945
+ if (options.isRetention(next.frame)) {
23946
+ retention += 1;
23947
+ void options.drive(next.frame).then(
23948
+ () => {
23949
+ retention -= 1;
23950
+ wake(0);
23951
+ },
23952
+ () => {
23953
+ retention -= 1;
23954
+ wake(0);
23955
+ }
23956
+ );
23957
+ wake(next.nextAfterMillis ?? 0);
23958
+ return;
23959
+ }
23960
+ if (retentionOnly) throw new Error("background desk reserved correspondence while its lane was unavailable");
23961
+ const workspace = next.workspace;
23962
+ if (!workspace) throw new Error("background correspondence has no source workspace");
23963
+ if (correspondenceNotBefore.has(workspace)) throw new Error("background desk bypassed a workspace's physical backoff");
23964
+ correspondenceInFlight = true;
23700
23965
  void options.drive(next.frame).then(
23701
23966
  () => {
23702
- retention -= 1;
23703
- wake(0);
23967
+ correspondenceInFlight = false;
23968
+ wake(next.nextAfterMillis ?? 0);
23704
23969
  },
23705
23970
  () => {
23706
- retention -= 1;
23971
+ correspondenceInFlight = false;
23972
+ correspondenceNotBefore.set(workspace, options.monotonicNanoseconds() + BigInt(failureBackoffMillis) * 1000000n);
23707
23973
  wake(0);
23708
23974
  }
23709
23975
  );
23710
- wake(next.nextAfterMillis ?? 0);
23711
- return;
23976
+ wake(0);
23977
+ } catch (error) {
23978
+ selectionFault(error);
23712
23979
  }
23713
- if (retentionOnly) throw new Error("background desk reserved correspondence while its lane was unavailable");
23714
- const workspace = next.workspace;
23715
- if (!workspace) throw new Error("background correspondence has no source workspace");
23716
- if (correspondenceNotBefore.has(workspace)) throw new Error("background desk bypassed a workspace's physical backoff");
23717
- correspondenceInFlight = true;
23718
- void options.drive(next.frame).then(
23719
- () => {
23720
- correspondenceInFlight = false;
23721
- wake(next.nextAfterMillis ?? 0);
23722
- },
23723
- () => {
23724
- correspondenceInFlight = false;
23725
- correspondenceNotBefore.set(workspace, options.monotonicNanoseconds() + BigInt(failureBackoffMillis) * 1000000n);
23726
- wake(0);
23727
- }
23728
- );
23729
- wake(0);
23730
23980
  }, delay);
23731
23981
  };
23732
23982
  return {
@@ -23754,7 +24004,7 @@ var init_background_lanes = __esm({
23754
24004
  });
23755
24005
 
23756
24006
  // ../peer-office/src/runtime/frame_runner.ts
23757
- import { fromBinary as fromBinary24 } from "@bufbuild/protobuf";
24007
+ import { fromBinary as fromBinary25 } from "@bufbuild/protobuf";
23758
24008
  function createPeerOfficeFrameRunner(kernel, credentials, profile, observations, custody, postEvent, maintenanceSettled, driveBackground, peerDeskStore, executeBackground) {
23759
24009
  if (!peerDeskStore) {
23760
24010
  throw new Error("Peer Office frame runner requires an explicit PeerDeskStore capability");
@@ -23775,7 +24025,7 @@ function createPeerOfficeFrameRunner(kernel, credentials, profile, observations,
23775
24025
  const event = peer2.nextEvent();
23776
24026
  if (event === void 0) return;
23777
24027
  if (maintenanceSettled !== void 0) {
23778
- const decoded = fromBinary24(RuntimeEventSchema, event);
24028
+ const decoded = fromBinary25(RuntimeEventSchema, event);
23779
24029
  if (decoded.event.case === "maintenanceProgress" && decoded.event.value.kernel && !decoded.event.value.kernel.maintenancePending) {
23780
24030
  maintenanceSettled(decoded.event.value);
23781
24031
  }
@@ -23810,11 +24060,12 @@ function createPeerOfficeFrameRunner(kernel, credentials, profile, observations,
23810
24060
  return paper;
23811
24061
  },
23812
24062
  drive: (frame) => driveBackground(frame).catch((error) => {
23813
- peer2.backgroundPaperAbandoned(fromBinary24(RuntimeRequestSchema, frame).requestId);
24063
+ peer2.backgroundPaperAbandoned(fromBinary25(RuntimeRequestSchema, frame).requestId);
23814
24064
  throw error;
23815
24065
  }),
23816
- isRetention: (frame) => fromBinary24(RuntimeRequestSchema, frame).command.case === "retainFrontier",
23817
- monotonicNanoseconds: () => observations.monotonicNanoseconds()
24066
+ isRetention: (frame) => fromBinary25(RuntimeRequestSchema, frame).command.case === "retainFrontier",
24067
+ monotonicNanoseconds: () => observations.monotonicNanoseconds(),
24068
+ onSelectionError: (error) => console.error("Nomos background paper selection failed", error)
23818
24069
  });
23819
24070
  const scheduleCorrespondence = (delayMillis = 0) => {
23820
24071
  lanes?.wake(delayMillis);
@@ -23823,7 +24074,7 @@ function createPeerOfficeFrameRunner(kernel, credentials, profile, observations,
23823
24074
  handleFrame(frame) {
23824
24075
  const response = peer2.invoke(frame).responseProtobuf;
23825
24076
  drainEvents();
23826
- if (fromBinary24(RuntimeRequestSchema, frame).command.case !== "workspaceStatus") {
24077
+ if (fromBinary25(RuntimeRequestSchema, frame).command.case !== "workspaceStatus") {
23827
24078
  scheduleMaintenance();
23828
24079
  scheduleCorrespondence();
23829
24080
  }
@@ -23885,21 +24136,21 @@ var init_frame_runner = __esm({
23885
24136
  });
23886
24137
 
23887
24138
  // ../peer-office/src/runtime/platform_effect_driver.ts
23888
- import { create as create71, fromBinary as fromBinary25, toBinary as toBinary26 } from "@bufbuild/protobuf";
24139
+ import { create as create71, fromBinary as fromBinary26, toBinary as toBinary27 } from "@bufbuild/protobuf";
23889
24140
  async function drivePeerFrame(runner, initialFrame, fetchImpl = globalThis.fetch, custody, bornCustody, credentialRefresh, yieldWakeToCaller = false, deviceIdentity, lawPackage, yieldLocalReadToCaller = false, yieldHistoryToCaller = false, performExternalEffect) {
23890
24141
  const persistBornCustody = bornCustody ?? (custody?.persistBornCustody ? (effect) => custody.persistBornCustody(effect) : void 0);
23891
24142
  let responseFrame = runner.handleFrame(initialFrame);
23892
24143
  const satisfied = /* @__PURE__ */ new Set();
23893
24144
  const resendable = (() => {
23894
24145
  try {
23895
- return fromBinary25(RuntimeRequestSchema, initialFrame).command.case !== "continueCorrespondence";
24146
+ return fromBinary26(RuntimeRequestSchema, initialFrame).command.case !== "continueCorrespondence";
23896
24147
  } catch {
23897
24148
  return false;
23898
24149
  }
23899
24150
  })();
23900
24151
  let historyRetries = 0;
23901
24152
  for (; ; ) {
23902
- const response = fromBinary25(RuntimeResponseSchema, responseFrame);
24153
+ const response = fromBinary26(RuntimeResponseSchema, responseFrame);
23903
24154
  if (response.outcome.case === "historyAcquired" && resendable && historyRetries < 32) {
23904
24155
  historyRetries += 1;
23905
24156
  responseFrame = runner.handleFrame(initialFrame);
@@ -23909,7 +24160,7 @@ async function drivePeerFrame(runner, initialFrame, fetchImpl = globalThis.fetch
23909
24160
  if (yieldLocalReadToCaller) return responseFrame;
23910
24161
  const pending2 = response.outcome.value;
23911
24162
  await new Promise((resolve4) => setTimeout(resolve4, pending2.resumeAfterMillis));
23912
- responseFrame = runner.handleFrame(toBinary26(RuntimeRequestSchema, create71(RuntimeRequestSchema, {
24163
+ responseFrame = runner.handleFrame(toBinary27(RuntimeRequestSchema, create71(RuntimeRequestSchema, {
23913
24164
  protocolVersion: response.protocolVersion,
23914
24165
  requestId: response.requestId,
23915
24166
  command: { case: "continueLocalRead", value: create71(ContinueLocalReadRequestSchema, { workId: pending2.workId }) }
@@ -24009,7 +24260,7 @@ async function drivePeerFrame(runner, initialFrame, fetchImpl = globalThis.fetch
24009
24260
  outcome: { case: "failure", value: { reason: PeerEffectFailureReason.TRANSPORT, message: error instanceof Error ? error.message : String(error) } }
24010
24261
  });
24011
24262
  }
24012
- responseFrame = runner.handleFrame(toBinary26(RuntimeRequestSchema, create71(RuntimeRequestSchema, {
24263
+ responseFrame = runner.handleFrame(toBinary27(RuntimeRequestSchema, create71(RuntimeRequestSchema, {
24013
24264
  protocolVersion: response.protocolVersion,
24014
24265
  requestId: response.requestId,
24015
24266
  command: { case: "continueCorrespondence", value: { workId: pending.workId, receipt: receipt2 } }
@@ -24037,7 +24288,7 @@ async function drivePeerFrame(runner, initialFrame, fetchImpl = globalThis.fetch
24037
24288
  }) : pending.effect.case === "retainFrontier" ? await executeRetainFrontierEffect(pending.effect.value, custody) : pending.effect.case === "wake" ? await executeWakeEffect(pending.effect.value) : pending.effect.case === "refreshCredential" ? await executeCredentialRefreshEffect(pending.effect.value, credentialRefresh) : pending.effect.case === "deviceIdentity" ? await executeDeviceIdentityEffect(pending.effect.value, deviceIdentity) : pending.effect.case === "lawPackage" ? await executeLawPackageEffect(pending.effect.value, lawPackage) : pending.effect.case === "historyAcquisition" ? await executeHistoryAcquisitionEffect(pending.effect.value, custody) : (() => {
24038
24289
  throw new Error(`correspondence work '${pending.workId}' has no effect`);
24039
24290
  })();
24040
- responseFrame = runner.handleFrame(toBinary26(RuntimeRequestSchema, create71(RuntimeRequestSchema, {
24291
+ responseFrame = runner.handleFrame(toBinary27(RuntimeRequestSchema, create71(RuntimeRequestSchema, {
24041
24292
  protocolVersion: response.protocolVersion,
24042
24293
  requestId: response.requestId,
24043
24294
  command: {
@@ -24109,11 +24360,11 @@ async function executeDeviceIdentityEffect(effect, store) {
24109
24360
  await store.save(effect.identity, effect.operation.value.secret.slice());
24110
24361
  } else if (effect.operation.case === "loadRecovery") {
24111
24362
  const bytes = await store.load(`nomos-device-recovery-v1|${effect.identity}`);
24112
- if (bytes !== void 0) recovery = fromBinary25(DeviceRecoveryRecordSchema, bytes);
24363
+ if (bytes !== void 0) recovery = fromBinary26(DeviceRecoveryRecordSchema, bytes);
24113
24364
  } else if (effect.operation.case === "saveRecovery") {
24114
24365
  const record = effect.operation.value.record;
24115
24366
  if (!record) throw new Error("device recovery save contains no record");
24116
- await store.save(`nomos-device-recovery-v1|${effect.identity}`, toBinary26(DeviceRecoveryRecordSchema, record));
24367
+ await store.save(`nomos-device-recovery-v1|${effect.identity}`, toBinary27(DeviceRecoveryRecordSchema, record));
24117
24368
  } else throw new Error("device identity effect has no operation");
24118
24369
  return create71(PeerEffectReceiptSchema, { effectId: effect.effectId, outcome: {
24119
24370
  case: "deviceIdentity",
@@ -24225,7 +24476,7 @@ var init_platform_effect_driver = __esm({
24225
24476
  correspondenceWakeups = /* @__PURE__ */ new WeakMap();
24226
24477
  deliveryIdentity = (requestFrame) => {
24227
24478
  try {
24228
- const request = fromBinary25(RuntimeRequestSchema, requestFrame);
24479
+ const request = fromBinary26(RuntimeRequestSchema, requestFrame);
24229
24480
  if (request.command.case !== "deliverWorkspaceEffects") return void 0;
24230
24481
  const command = request.command.value;
24231
24482
  return `${command.sourceSession}\0${command.targetWorkspace}\0${command.sourceCommit ?? ""}`;
@@ -24236,7 +24487,7 @@ var init_platform_effect_driver = __esm({
24236
24487
  arrangeCorrespondenceWakeup = (runner, requestFrame, responseFrame, fetchImpl) => {
24237
24488
  const identity = deliveryIdentity(requestFrame);
24238
24489
  if (!identity) return;
24239
- const response = fromBinary25(RuntimeResponseSchema, responseFrame);
24490
+ const response = fromBinary26(RuntimeResponseSchema, responseFrame);
24240
24491
  const retryAt = response.outcome.case === "workspaceEffectsDelivered" ? response.outcome.value.retryAtMillis : void 0;
24241
24492
  const wakeups = correspondenceWakeups.get(runner) ?? /* @__PURE__ */ new Map();
24242
24493
  correspondenceWakeups.set(runner, wakeups);
@@ -24361,13 +24612,19 @@ var init_platform_effect_driver = __esm({
24361
24612
  };
24362
24613
  executeGitFetchWithAlongside = async (effect, fetchImpl) => {
24363
24614
  if (!effect.alongside) return executeGitFetchEffect(effect, fetchImpl);
24364
- const [fetched, alongside] = await Promise.all([
24365
- executeGitFetchEffect(effect, fetchImpl),
24366
- executeHttpEffect(effect.alongside, fetchImpl)
24367
- ]);
24368
- if (fetched.outcome.case === "gitFetch" && alongside.outcome.case === "response") {
24615
+ const cancelAlongside = new AbortController();
24616
+ let alongside;
24617
+ void executeHttpEffect(effect.alongside, (input, init) => fetchImpl(input, {
24618
+ ...init,
24619
+ signal: init?.signal ? AbortSignal.any([init.signal, cancelAlongside.signal]) : cancelAlongside.signal
24620
+ })).then((receipt) => {
24621
+ alongside = receipt;
24622
+ });
24623
+ const fetched = await executeGitFetchEffect(effect, fetchImpl);
24624
+ if (fetched.outcome.case === "gitFetch" && alongside?.outcome.case === "response") {
24369
24625
  fetched.outcome.value.alongside = alongside.outcome.value;
24370
24626
  }
24627
+ cancelAlongside.abort();
24371
24628
  return fetched;
24372
24629
  };
24373
24630
  executeGitPushEffect = async (effect, fetchImpl) => {
@@ -24427,25 +24684,26 @@ var init_platform_effect_driver = __esm({
24427
24684
  });
24428
24685
 
24429
24686
  // ../platform-shells/shared/socket_effects.ts
24430
- import { create as create72, fromBinary as fromBinary26, toBinary as toBinary27 } from "@bufbuild/protobuf";
24687
+ import { create as create72, fromBinary as fromBinary27, toBinary as toBinary28 } from "@bufbuild/protobuf";
24431
24688
  function socketEffects(invoke2, permits = () => true) {
24432
24689
  const sockets = /* @__PURE__ */ new Map();
24433
24690
  let sequence = 50000000000n;
24434
24691
  let closed = false;
24435
24692
  const receipt = (connectionId, observation) => {
24436
24693
  if (closed) return;
24437
- const frame = toBinary27(RuntimeRequestSchema, create72(RuntimeRequestSchema, {
24694
+ const frame = toBinary28(RuntimeRequestSchema, create72(RuntimeRequestSchema, {
24438
24695
  protocolVersion: 2,
24439
24696
  requestId: ++sequence,
24440
24697
  command: { case: "socketReceipt", value: create72(PeerSocketReceiptSchema, { connectionId, observation }) }
24441
24698
  }));
24442
- void Promise.resolve().then(() => invoke2(frame)).catch(() => {
24699
+ void Promise.resolve().then(() => invoke2(frame)).catch((error) => {
24700
+ console.warn("[nomos-socket] receipt failed", { connectionId, error });
24443
24701
  sockets.get(connectionId)?.close();
24444
24702
  });
24445
24703
  };
24446
24704
  return {
24447
24705
  consume(frame) {
24448
- const event = fromBinary26(RuntimeEventSchema, frame);
24706
+ const event = fromBinary27(RuntimeEventSchema, frame);
24449
24707
  if (event.event.case !== "socketEffect") return false;
24450
24708
  const effect = event.event.value;
24451
24709
  const id = effect.connectionId;
@@ -24461,6 +24719,7 @@ function socketEffects(invoke2, permits = () => true) {
24461
24719
  socket.onopen = () => receipt(id, { case: "opened", value: true });
24462
24720
  socket.onmessage = (message) => {
24463
24721
  if (message.data instanceof ArrayBuffer) receipt(id, { case: "received", value: new Uint8Array(message.data) });
24722
+ else if (typeof message.data === "string") receipt(id, { case: "received", value: new TextEncoder().encode(message.data) });
24464
24723
  };
24465
24724
  socket.onclose = () => {
24466
24725
  if (sockets.get(id) === socket) sockets.delete(id);
@@ -24501,17 +24760,17 @@ var init_socket_effects = __esm({
24501
24760
  });
24502
24761
 
24503
24762
  // ../platform-shells/shared/credential_effects.ts
24504
- import { create as create73, fromBinary as fromBinary27, toBinary as toBinary28 } from "@bufbuild/protobuf";
24763
+ import { create as create73, fromBinary as fromBinary28, toBinary as toBinary29 } from "@bufbuild/protobuf";
24505
24764
  function credentialEffects(invoke2, provider) {
24506
24765
  return { consume(frame) {
24507
- const event = fromBinary27(RuntimeEventSchema, frame);
24766
+ const event = fromBinary28(RuntimeEventSchema, frame);
24508
24767
  if (event.event.case !== "credentialRefreshRequested" || provider === externalPeerEffect) return false;
24509
24768
  const pending = event.event.value.pending;
24510
24769
  if (pending?.effect.case !== "refreshCredential") throw new Error("credential refresh event omitted its physical effect");
24511
24770
  const effect = pending.effect.value;
24512
24771
  void Promise.resolve().then(async () => {
24513
24772
  const receipt = await executeCredentialRefreshEffect(effect, provider);
24514
- const response = fromBinary27(RuntimeResponseSchema, await invoke2(toBinary28(RuntimeRequestSchema, create73(RuntimeRequestSchema, {
24773
+ const response = fromBinary28(RuntimeResponseSchema, await invoke2(toBinary29(RuntimeRequestSchema, create73(RuntimeRequestSchema, {
24515
24774
  protocolVersion: 2,
24516
24775
  requestId: event.sequence,
24517
24776
  command: { case: "continueCorrespondence", value: create73(ContinueCorrespondenceRequestSchema, { workId: pending.workId, receipt }) }
@@ -24534,7 +24793,7 @@ var init_credential_effects = __esm({
24534
24793
  });
24535
24794
 
24536
24795
  // ../platform-shells/shared/peer_office_host.ts
24537
- import { create as create74, fromBinary as fromBinary28, toBinary as toBinary29 } from "@bufbuild/protobuf";
24796
+ import { create as create74, fromBinary as fromBinary29, toBinary as toBinary30 } from "@bufbuild/protobuf";
24538
24797
  function openPeerOfficeHost(kernel, shell, fetchImpl = globalThis.fetch, maintenanceSettled, postEvent = () => {
24539
24798
  }, credentialRefresh, yieldWakeToCaller = false, deviceIdentity, lawPackage, performExternalEffect) {
24540
24799
  let runner;
@@ -24583,7 +24842,7 @@ function openPeerOfficeHost(kernel, shell, fetchImpl = globalThis.fetch, mainten
24583
24842
  );
24584
24843
  const providerOrigins = [...configuredOrigins];
24585
24844
  if (providerOrigins.length > 0) {
24586
- const configured = fromBinary28(RuntimeResponseSchema, runner.handleFrame(toBinary29(
24845
+ const configured = fromBinary29(RuntimeResponseSchema, runner.handleFrame(toBinary30(
24587
24846
  RuntimeRequestSchema,
24588
24847
  create74(RuntimeRequestSchema, {
24589
24848
  protocolVersion: 2,
@@ -24597,7 +24856,7 @@ function openPeerOfficeHost(kernel, shell, fetchImpl = globalThis.fetch, mainten
24597
24856
  }
24598
24857
  return {
24599
24858
  async invoke(args) {
24600
- const request = fromBinary28(RuntimeRequestSchema, args.requestBytes);
24859
+ const request = fromBinary29(RuntimeRequestSchema, args.requestBytes);
24601
24860
  if (request.protocolVersion !== 2) {
24602
24861
  throw new Error(`unsupported Nomos runtime protocol ${request.protocolVersion}`);
24603
24862
  }
@@ -24653,7 +24912,7 @@ var init_peer_office_host = __esm({
24653
24912
  init_socket_effects();
24654
24913
  init_credential_effects();
24655
24914
  targetOf = (frame) => {
24656
- const target3 = fromBinary28(RuntimeRequestSchema, frame).target;
24915
+ const target3 = fromBinary29(RuntimeRequestSchema, frame).target;
24657
24916
  return {
24658
24917
  ...target3?.session === void 0 ? {} : { session: target3.session },
24659
24918
  ...target3?.workspace === void 0 ? {} : { workspace: target3.workspace }
@@ -24707,21 +24966,21 @@ var init_sqlite_peer_desk_store = __esm({
24707
24966
  }
24708
24967
  return this.#opened = database;
24709
24968
  }
24710
- list(namespace) {
24969
+ list(namespace2) {
24711
24970
  const rows = this.#database().prepare(`
24712
24971
  SELECT record_key AS key, revision, value
24713
24972
  FROM peer_desk_record
24714
24973
  WHERE namespace = ?
24715
24974
  ORDER BY record_key
24716
- `).all(namespace);
24975
+ `).all(namespace2);
24717
24976
  return rows.map((row) => ({
24718
- namespace,
24977
+ namespace: namespace2,
24719
24978
  key: row.key,
24720
24979
  revision: BigInt(row.revision),
24721
24980
  value: Uint8Array.from(row.value)
24722
24981
  }));
24723
24982
  }
24724
- compareExchange(namespace, key2, expectedRevision, value) {
24983
+ compareExchange(namespace2, key2, expectedRevision, value) {
24725
24984
  const expected = expectedRevision === void 0 ? void 0 : Number(expectedRevision);
24726
24985
  if (expected !== void 0 && (!Number.isSafeInteger(expected) || expected <= 0)) {
24727
24986
  throw new Error(`peer desk revision ${expectedRevision} cannot be represented by SQLite`);
@@ -24734,8 +24993,8 @@ var init_sqlite_peer_desk_store = __esm({
24734
24993
  const removed = database.prepare(`
24735
24994
  DELETE FROM peer_desk_record
24736
24995
  WHERE namespace = ? AND record_key = ? AND revision = ?
24737
- `).run(namespace, key2, expected);
24738
- if (removed.changes !== 1) this.#conflict(namespace, key2);
24996
+ `).run(namespace2, key2, expected);
24997
+ if (removed.changes !== 1) this.#conflict(namespace2, key2);
24739
24998
  return this.#commit(void 0);
24740
24999
  }
24741
25000
  const bytes = Buffer.from(value.buffer, value.byteOffset, value.byteLength);
@@ -24747,14 +25006,14 @@ var init_sqlite_peer_desk_store = __esm({
24747
25006
  INSERT INTO peer_desk_record(namespace, record_key, revision, value)
24748
25007
  VALUES (?, ?, 1, ?)
24749
25008
  ON CONFLICT(namespace, record_key) DO NOTHING
24750
- `).run(namespace, key2, bytes) : database.prepare(`
25009
+ `).run(namespace2, key2, bytes) : database.prepare(`
24751
25010
  UPDATE peer_desk_record
24752
25011
  SET revision = ?, value = ?
24753
25012
  WHERE namespace = ? AND record_key = ? AND revision = ?
24754
- `).run(nextRevision, bytes, namespace, key2, expected);
24755
- if (changed.changes !== 1) this.#conflict(namespace, key2);
25013
+ `).run(nextRevision, bytes, namespace2, key2, expected);
25014
+ if (changed.changes !== 1) this.#conflict(namespace2, key2);
24756
25015
  return this.#commit({
24757
- namespace,
25016
+ namespace: namespace2,
24758
25017
  key: key2,
24759
25018
  revision: BigInt(nextRevision),
24760
25019
  value: value.slice()
@@ -24772,12 +25031,12 @@ var init_sqlite_peer_desk_store = __esm({
24772
25031
  this.#database().exec("COMMIT");
24773
25032
  return value;
24774
25033
  }
24775
- #conflict(namespace, key2) {
25034
+ #conflict(namespace2, key2) {
24776
25035
  const current = this.#database().prepare(`
24777
25036
  SELECT revision FROM peer_desk_record WHERE namespace = ? AND record_key = ?
24778
- `).get(namespace, key2);
25037
+ `).get(namespace2, key2);
24779
25038
  throw new Error(
24780
- `peer desk record '${namespace}/${key2}' changed at revision ${current?.revision ?? "absent"}`
25039
+ `peer desk record '${namespace2}/${key2}' changed at revision ${current?.revision ?? "absent"}`
24781
25040
  );
24782
25041
  }
24783
25042
  };
@@ -25174,7 +25433,7 @@ __export(peer_office_exports, {
25174
25433
  signEraCertification: () => signEraCertification,
25175
25434
  verifyRemoteChain: () => verifyRemoteChain
25176
25435
  });
25177
- import { create as create76, fromBinary as fromBinary29, toBinary as toBinary30 } from "@bufbuild/protobuf";
25436
+ import { create as create76, fromBinary as fromBinary30, toBinary as toBinary31 } from "@bufbuild/protobuf";
25178
25437
  import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
25179
25438
  import {
25180
25439
  existsSync as existsSync5,
@@ -25255,13 +25514,13 @@ async function invokeLocalPeerOffice(cloud, command, target3) {
25255
25514
  command
25256
25515
  });
25257
25516
  const office = await peer(cloud);
25258
- const response = fromBinary29(RuntimeResponseSchema, await office.invoke({
25517
+ const response = fromBinary30(RuntimeResponseSchema, await office.invoke({
25259
25518
  ...target3 === void 0 ? {} : {
25260
25519
  workspace: target3.workspace,
25261
25520
  authToken: target3.authToken,
25262
25521
  sourceDeviceKeySecret: target3.authorSecret
25263
25522
  },
25264
- requestBytes: toBinary30(RuntimeRequestSchema, request)
25523
+ requestBytes: toBinary31(RuntimeRequestSchema, request)
25265
25524
  }));
25266
25525
  if (response.requestId !== requestId) {
25267
25526
  throw new Error(`Peer Office returned response ${response.requestId} for request ${requestId}`);