@githolon/dsl 0.108.6 → 0.110.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (307) hide show
  1. package/assets/operation-contract.wasm +0 -0
  2. package/check_package.mjs +12 -15
  3. package/compile_package.mjs +17 -18
  4. package/compile_proof.mjs +16 -1
  5. package/dart/CHANGELOG.md +76 -1
  6. package/dart/README.md +25 -2
  7. package/dart/lib/src/admission_decision.dart +41 -0
  8. package/dart/lib/src/application_framework_calls.dart +52 -2
  9. package/dart/lib/src/application_model_adoption.dart +187 -0
  10. package/dart/lib/src/application_status.dart +73 -0
  11. package/dart/lib/src/console_enrolment.dart +271 -0
  12. package/dart/lib/src/console_http_io.dart +26 -0
  13. package/dart/lib/src/console_http_stub.dart +7 -0
  14. package/dart/lib/src/dev_cloud.dart +69 -22
  15. package/dart/lib/src/generated_call.dart +83 -23
  16. package/dart/lib/src/kernel_primitives.dart +119 -0
  17. package/dart/lib/src/nms_conformance_runtime.dart +1 -1
  18. package/dart/lib/src/nms_generated_runtime.dart +32 -10
  19. package/dart/lib/src/nms_test_environment.dart +1 -1
  20. package/dart/lib/src/node_runner_transport.dart +41 -46
  21. package/dart/lib/src/observed_session_directory.dart +70 -0
  22. package/dart/lib/src/operation_receipts.dart +112 -0
  23. package/dart/lib/src/peer_application_streams.dart +103 -0
  24. package/dart/lib/src/reception/dart_reception.dart +4280 -0
  25. package/dart/lib/src/reception/event_desk.dart +211 -0
  26. package/dart/lib/src/reception/extremum_read.dart +46 -0
  27. package/dart/lib/src/reception/local_copies.dart +371 -0
  28. package/dart/lib/src/reception/peer_office_connection.dart +11 -0
  29. package/dart/lib/src/reception/progress_desk.dart +267 -0
  30. package/dart/lib/src/reception/reception_contract.dart +11 -0
  31. package/dart/lib/src/reception/reception_session.dart +284 -0
  32. package/dart/lib/src/reception/sync_diagnostics.dart +26 -0
  33. package/dart/lib/src/reception/workspace_preparation_report.dart +126 -0
  34. package/dart/lib/src/replica_readiness.dart +123 -0
  35. package/dart/lib/src/runner/node-entry.mjs +23905 -15774
  36. package/dart/lib/src/runtime_v2_gateway.dart +56 -3
  37. package/dart/lib/src/runtime_v2_transport.dart +544 -3
  38. package/dart/lib/src/session_bound.dart +200 -311
  39. package/dart/lib/src/signing_identity_kernel.dart +84 -0
  40. package/dart/lib/src/sync_status_projection.dart +548 -0
  41. package/dart/lib/src/sync_status_reducer.dart +170 -0
  42. package/dart/lib/src/test_harness.dart +809 -1153
  43. package/dart/lib/src/testing/test_custody.dart +66 -0
  44. package/dart/lib/src/testing/test_peer.dart +328 -0
  45. package/dart/lib/src/typed_watch_registry.dart +169 -0
  46. package/dart/lib/src/workspace_open_progress.dart +27 -0
  47. package/dart/pubspec.lock +24 -1
  48. package/dart/pubspec.yaml +7 -2
  49. package/dart/pubspec_overrides.yaml +2 -0
  50. package/dart/test/admission_decision_test.dart +48 -0
  51. package/dart/test/background_model_adoption_test.dart +228 -0
  52. package/dart/test/bundle_version_pairing_test.dart +4 -4
  53. package/dart/test/child_authentication_repair_test.dart +359 -0
  54. package/dart/test/cloud_bound_local_shell_test.dart +119 -0
  55. package/dart/test/console_enrolment_refusal_test.dart +52 -0
  56. package/dart/test/console_enrolment_test.dart +227 -0
  57. package/dart/test/errors_test.dart +5 -5
  58. package/dart/test/event_plane_seam_test.dart +50 -164
  59. package/dart/test/extremum_read_test.dart +58 -0
  60. package/dart/test/fixtures/wedge/wedge-entry.mjs +3 -21
  61. package/dart/test/generated_query_test.dart +32 -0
  62. package/dart/test/harness_phase_timeout_test.dart +18 -23
  63. package/dart/test/kernel_author_after_read_test.dart +242 -0
  64. package/dart/test/kernel_fence_test.dart +137 -0
  65. package/dart/test/local_copies_test.dart +222 -0
  66. package/dart/test/model_adoption_test.dart +198 -0
  67. package/dart/test/node_peer_local_custody_test.dart +153 -0
  68. package/dart/test/offer_authentication_proof_test.dart +352 -52
  69. package/dart/test/operation_compatibility_test.dart +151 -0
  70. package/dart/test/platform_credential_effect_test.dart +386 -0
  71. package/dart/test/receiving_group_open_test.dart +213 -0
  72. package/dart/test/reception/workspace_preparation_report_test.dart +103 -0
  73. package/dart/test/reception_span_trace_test.dart +23 -0
  74. package/dart/test/replica_readiness_test.dart +156 -0
  75. package/dart/test/runtime_projections_test.dart +92 -0
  76. package/dart/test/runtime_v2_gateway_test.dart +131 -0
  77. package/dart/test/signing_identity_kernel_test.dart +75 -0
  78. package/dart/test/sync_status_preparation_report_test.dart +29 -0
  79. package/dart/test/sync_status_reducer_test.dart +419 -0
  80. package/dart/test/test_harness_test.dart +71 -95
  81. package/dart/test/typed_query_watch_test.dart +170 -0
  82. package/dart/test/typed_watch_registry_test.dart +249 -0
  83. package/dart_lints/README.md +18 -0
  84. package/dart_lints/lib/nomos_lints.dart +70 -0
  85. package/dart_lints/pubspec.lock +580 -0
  86. package/dart_lints/pubspec.yaml +12 -0
  87. package/dart_lints/test/reference_identity_test.dart +75 -0
  88. package/dart_types/CHANGELOG.md +18 -0
  89. package/dart_types/lib/nomos_kernel_protocol.dart +21 -1
  90. package/dart_types/lib/nomos_types.dart +9 -1
  91. package/dart_types/lib/src/admission_decision.dart +37 -0
  92. package/dart_types/lib/src/aggregate_meta.dart +1 -1
  93. package/dart_types/lib/src/approved_model.dart +65 -0
  94. package/dart_types/lib/src/custody.dart +10 -18
  95. package/dart_types/lib/src/error_info.dart +4 -4
  96. package/dart_types/lib/src/errors.dart +29 -29
  97. package/dart_types/lib/src/foreign_ref.dart +62 -33
  98. package/dart_types/lib/src/local_work_rejected.dart +3 -3
  99. package/dart_types/lib/src/nomos_ref.dart +3 -1
  100. package/dart_types/lib/src/principal.dart +2 -2
  101. package/dart_types/lib/src/proto/google/protobuf/any.pb.dart +163 -0
  102. package/dart_types/lib/src/proto/google/protobuf/any.pbenum.dart +11 -0
  103. package/dart_types/lib/src/proto/nomos/discovery/v1/workspace_placement.pb.dart +137 -0
  104. package/dart_types/lib/src/proto/nomos/discovery/v1/workspace_placement.pbenum.dart +11 -0
  105. package/dart_types/lib/src/proto/nomos/kernel/v1/kernel.pb.dart +20721 -10433
  106. package/dart_types/lib/src/proto/nomos/kernel/v1/kernel.pbenum.dart +555 -27
  107. package/dart_types/lib/src/proto/nomos/runtime/v2/application_desk.pb.dart +387 -0
  108. package/dart_types/lib/src/proto/nomos/runtime/v2/application_desk.pbenum.dart +46 -0
  109. package/dart_types/lib/src/proto/nomos/runtime/v2/application_readiness_desk.pb.dart +295 -0
  110. package/dart_types/lib/src/proto/nomos/runtime/v2/application_readiness_desk.pbenum.dart +139 -0
  111. package/dart_types/lib/src/proto/nomos/runtime/v2/authentication_desk.pb.dart +269 -0
  112. package/dart_types/lib/src/proto/nomos/runtime/v2/authentication_desk.pbenum.dart +103 -0
  113. package/dart_types/lib/src/proto/nomos/runtime/v2/compatibility_desk.pb.dart +417 -0
  114. package/dart_types/lib/src/proto/nomos/runtime/v2/compatibility_desk.pbenum.dart +62 -0
  115. package/dart_types/lib/src/proto/nomos/runtime/v2/correspondence_desk.pb.dart +9968 -0
  116. package/dart_types/lib/src/proto/nomos/runtime/v2/correspondence_desk.pbenum.dart +133 -0
  117. package/dart_types/lib/src/proto/nomos/runtime/v2/credentials_desk.pb.dart +204 -0
  118. package/dart_types/lib/src/proto/nomos/runtime/v2/credentials_desk.pbenum.dart +54 -0
  119. package/dart_types/lib/src/proto/nomos/runtime/v2/custody_desk.pb.dart +1550 -0
  120. package/dart_types/lib/src/proto/nomos/runtime/v2/custody_desk.pbenum.dart +11 -0
  121. package/dart_types/lib/src/proto/nomos/runtime/v2/framework.pb.dart +710 -0
  122. package/dart_types/lib/src/proto/nomos/runtime/v2/framework.pbenum.dart +11 -0
  123. package/dart_types/lib/src/proto/nomos/runtime/v2/identity_desk.pb.dart +845 -0
  124. package/dart_types/lib/src/proto/nomos/runtime/v2/identity_desk.pbenum.dart +11 -0
  125. package/dart_types/lib/src/proto/nomos/runtime/v2/interaction_desk.pb.dart +198 -0
  126. package/dart_types/lib/src/proto/nomos/runtime/v2/interaction_desk.pbenum.dart +11 -0
  127. package/dart_types/lib/src/proto/nomos/runtime/v2/law_desk.pb.dart +369 -0
  128. package/dart_types/lib/src/proto/nomos/runtime/v2/law_desk.pbenum.dart +11 -0
  129. package/dart_types/lib/src/proto/nomos/runtime/v2/maintenance_desk.pb.dart +609 -0
  130. package/dart_types/lib/src/proto/nomos/runtime/v2/maintenance_desk.pbenum.dart +65 -0
  131. package/dart_types/lib/src/proto/nomos/runtime/v2/model_adoption_desk.pb.dart +358 -0
  132. package/dart_types/lib/src/proto/nomos/runtime/v2/model_adoption_desk.pbenum.dart +100 -0
  133. package/dart_types/lib/src/proto/nomos/runtime/v2/observability_desk.pb.dart +2231 -0
  134. package/dart_types/lib/src/proto/nomos/runtime/v2/observability_desk.pbenum.dart +271 -0
  135. package/dart_types/lib/src/proto/nomos/runtime/v2/placement_desk.pb.dart +1286 -0
  136. package/dart_types/lib/src/proto/nomos/runtime/v2/placement_desk.pbenum.dart +11 -0
  137. package/dart_types/lib/src/proto/nomos/runtime/v2/receiving_group_desk.pb.dart +636 -0
  138. package/dart_types/lib/src/proto/nomos/runtime/v2/receiving_group_desk.pbenum.dart +116 -0
  139. package/dart_types/lib/src/proto/nomos/runtime/v2/records_desk.pb.dart +1637 -0
  140. package/dart_types/lib/src/proto/nomos/runtime/v2/records_desk.pbenum.dart +175 -0
  141. package/dart_types/lib/src/proto/nomos/runtime/v2/recovery_desk.pb.dart +1269 -0
  142. package/dart_types/lib/src/proto/nomos/runtime/v2/recovery_desk.pbenum.dart +129 -0
  143. package/dart_types/lib/src/proto/nomos/runtime/v2/residency_desk.pb.dart +2782 -0
  144. package/dart_types/lib/src/proto/nomos/runtime/v2/residency_desk.pbenum.dart +97 -0
  145. package/dart_types/lib/src/proto/nomos/runtime/v2/runtime.pb.dart +2232 -8627
  146. package/dart_types/lib/src/proto/nomos/runtime/v2/runtime.pbenum.dart +0 -358
  147. package/dart_types/lib/src/proto/nomos/runtime/v2/sealing_desk.pb.dart +1639 -0
  148. package/dart_types/lib/src/proto/nomos/runtime/v2/sealing_desk.pbenum.dart +46 -0
  149. package/dart_types/lib/src/runtime_outcome.dart +133 -0
  150. package/dart_types/lib/src/subscriptions.dart +116 -23
  151. package/dart_types/pubspec.yaml +1 -1
  152. package/dart_types/test/extremum_subscriptions_test.dart +40 -0
  153. package/dart_types/test/foreign_ref_resolution_test.dart +75 -0
  154. package/dart_types/test/nomos_ref_address_test.dart +25 -0
  155. package/dart_types/test/ordered_subscriptions_test.dart +34 -0
  156. package/operation_contract_check.mjs +24 -0
  157. package/package.json +11 -6
  158. package/src/aggregate.ts +70 -10
  159. package/src/application_topology.ts +18 -11
  160. package/src/attested.ts +3 -0
  161. package/src/attested_core.ts +46 -3
  162. package/src/birth_meter_ensure.ts +19 -7
  163. package/src/births.ts +29 -4
  164. package/src/build_package.ts +140 -13
  165. package/src/business_birth.ts +181 -4
  166. package/src/codegen_call_proto.ts +1274 -0
  167. package/src/codegen_call_usda.ts +49 -6
  168. package/src/codegen_dart.ts +79 -44
  169. package/src/codegen_dart_client.ts +458 -800
  170. package/src/{codegen_dart_application.ts → codegen_dart_facade.ts} +331 -582
  171. package/src/codegen_dart_framework_calls.ts +320 -37
  172. package/src/codegen_dart_indexed_variant.ts +159 -0
  173. package/src/codegen_dart_scenario.ts +42 -13
  174. package/src/codegen_proof.ts +3 -3
  175. package/src/codegen_provider_dart.ts +5 -0
  176. package/src/codegen_query_proto.ts +158 -0
  177. package/src/codegen_refusal.ts +189 -0
  178. package/src/codegen_result_proto.ts +931 -0
  179. package/src/codegen_result_usda.ts +4 -0
  180. package/src/codegen_ts.ts +464 -616
  181. package/src/codegen_workspace_access.ts +105 -0
  182. package/src/compatibility_graph.ts +759 -0
  183. package/src/compatibility_usda.ts +264 -0
  184. package/src/compile_package_main.ts +2083 -1248
  185. package/src/custody_placement.ts +156 -0
  186. package/src/custody_placement_usda.ts +91 -0
  187. package/src/decl_shapes.ts +21 -2
  188. package/src/describe_model.ts +1 -0
  189. package/src/directive.ts +59 -2
  190. package/src/drivers.ts +51 -0
  191. package/src/engine_entry.ts +52 -8
  192. package/src/evolve_preview.ts +11 -4
  193. package/src/exists.ts +2 -0
  194. package/src/fields.ts +75 -11
  195. package/src/flow_gate.ts +2 -1
  196. package/src/framework/application_home.ts +170 -18
  197. package/src/framework/attested_receipts.ts +8 -3
  198. package/src/framework/auth_provider_law.ts +169 -9
  199. package/src/framework/birth_certificate_law.ts +4 -0
  200. package/src/framework/capability.ts +34 -3
  201. package/src/framework/child_authentication.ts +346 -0
  202. package/src/framework/console_governance.ts +295 -0
  203. package/src/framework/delegated_roles.ts +301 -0
  204. package/src/framework/domain_lifecycle.ts +26 -13
  205. package/src/framework/founding_genesis.ts +193 -0
  206. package/src/framework/framework_aggregates.ts +1 -1
  207. package/src/framework/genesis.ts +6 -1
  208. package/src/framework/governance_relations.ts +19 -0
  209. package/src/framework/home.ts +5 -734
  210. package/src/framework/legacy/child_auth_provider_epoch.ts +73 -0
  211. package/src/framework/model_authority_repair.ts +116 -0
  212. package/src/framework/model_authority_seed.ts +185 -0
  213. package/src/framework/model_transition.ts +211 -0
  214. package/src/framework/owned_custody.ts +1 -1
  215. package/src/framework/principal_enrollment.ts +302 -0
  216. package/src/framework/receiving_group.ts +857 -0
  217. package/src/framework/receiving_group_recovery.ts +314 -0
  218. package/src/framework/relations.ts +4 -8
  219. package/src/framework/signing_identity.ts +242 -95
  220. package/src/framework/source_roster.ts +11 -5
  221. package/src/framework/workspace_access.ts +149 -0
  222. package/src/framework/workspace_invariant.ts +73 -52
  223. package/src/framework/workspaces.ts +407 -40
  224. package/src/framework_call_definitions.ts +32 -3
  225. package/src/generated_client_bundle_boundary.ts +97 -0
  226. package/src/generated_client_names.ts +1 -0
  227. package/src/identity_usda.ts +27 -0
  228. package/src/index.ts +183 -12
  229. package/src/indexed_variant.ts +83 -0
  230. package/src/intent.ts +173 -45
  231. package/src/law_check.ts +8 -5
  232. package/src/law_dependency_index.ts +231 -0
  233. package/src/law_graph.ts +508 -71
  234. package/src/law_graph_usda.ts +170 -24
  235. package/src/law_identity.ts +119 -81
  236. package/src/law_source_map.ts +4 -1
  237. package/src/law_units.ts +498 -0
  238. package/src/law_value_type.ts +7 -3
  239. package/src/member_authentication.ts +302 -0
  240. package/src/null_meta.ts +1 -1
  241. package/src/openusd_compiled_layer.ts +132 -0
  242. package/src/operation_contract_check.ts +31 -0
  243. package/src/ordered_read.ts +2 -1
  244. package/src/package_config.ts +33 -12
  245. package/src/package_dependencies.ts +1 -0
  246. package/src/plan_source_slice.ts +30 -1
  247. package/src/protobuf_field_number.ts +36 -0
  248. package/src/provenance_wire.ts +6 -0
  249. package/src/query.ts +2 -1
  250. package/src/read.ts +50 -0
  251. package/src/relation.ts +4 -1
  252. package/src/relation_schema.ts +15 -2
  253. package/src/report.ts +2 -2
  254. package/src/sqlite_computation_bundle.ts +78 -0
  255. package/src/sqlite_computed.ts +102 -0
  256. package/src/sqlite_counts.ts +154 -0
  257. package/src/sqlite_layout.ts +823 -0
  258. package/src/sqlite_reads.ts +275 -0
  259. package/src/sqlite_samples.ts +185 -0
  260. package/src/stable_id_identity_bridge.ts +1 -1
  261. package/src/stable_ids_for_module.ts +16 -4
  262. package/src/test_call_usda.ts +6 -6
  263. package/src/usda_relationship_integrity.ts +20 -3
  264. package/src/usda_text.ts +21 -1
  265. package/src/value_object.ts +81 -11
  266. package/src/wire.ts +22 -0
  267. package/src/wire_encode.ts +227 -20
  268. package/src/workspace_sharding.ts +15 -6
  269. package/src/workspace_sharing.ts +51 -49
  270. package/src/zod_introspection.ts +2 -0
  271. package/compat_package.mjs +0 -46
  272. package/dart/lib/src/home.dart +0 -15
  273. package/dart/lib/src/runner/offline-install.mjs +0 -15367
  274. package/dart/lib/src/source_trust.dart +0 -51
  275. package/dart/lib/src/webview_bridge.dart +0 -6540
  276. package/dart/lib/src/workspace_name.dart +0 -30
  277. package/dart/test/acquire_session_credentials_test.dart +0 -150
  278. package/dart/test/acquire_session_test.dart +0 -534
  279. package/dart/test/adv_realm_interference_test.dart +0 -600
  280. package/dart/test/cloud_bound_topology_test.dart +0 -168
  281. package/dart/test/cluster_births_test.dart +0 -202
  282. package/dart/test/cluster_device_keyed_acceptance_test.dart +0 -105
  283. package/dart/test/cluster_local_autosync_test.dart +0 -123
  284. package/dart/test/cluster_scale_test.dart +0 -122
  285. package/dart/test/compat_test.dart +0 -61
  286. package/dart/test/dlq_session_surface_test.dart +0 -222
  287. package/dart/test/first_app_gauntlet_test.dart +0 -386
  288. package/dart/test/fixtures/wedge/fake-install.mjs +0 -11
  289. package/dart/test/four_layer_nested_topology_test.dart +0 -290
  290. package/dart/test/home_parity_test.dart +0 -13
  291. package/dart/test/local_sync_inert_test.dart +0 -107
  292. package/dart/test/node_runner_transport_test.dart +0 -78
  293. package/dart/test/parent_signer_recovery_test.dart +0 -155
  294. package/dart/test/residency_refusal_test.dart +0 -49
  295. package/dart/test/sealing_client_test.dart +0 -181
  296. package/dart/test/session_bound_test.dart +0 -285
  297. package/dart/test/stale_bundle_test.dart +0 -80
  298. package/dart/test/vo_read_typing_test.dart +0 -131
  299. package/dart/test/watch_after_offer_stall_test.dart +0 -100
  300. package/dart/test/webview_bridge_test.dart +0 -1930
  301. package/dart/test/workspace_name_test.dart +0 -24
  302. package/runtime/generated-application-host.js +0 -22860
  303. package/src/codegen_query_usda.ts +0 -214
  304. package/src/compat_manifest.ts +0 -26
  305. package/src/compat_package_main.ts +0 -224
  306. package/src/shape_compat.ts +0 -352
  307. package/src/usd_state.ts +0 -505
@@ -1,8 +1,9 @@
1
- // Generated tenant-facing Dart application facade.
1
+ import { refusalContracts, refusalType, refusalDecoder } from "./codegen_refusal.js";
2
+ // Generated tenant-facing Dart facade.
2
3
  //
3
- // The bridge-bound `<domain>.client.dart` is an implementation detail. This file is the exported
4
+ // The session-bound `<domain>.client.dart` is an implementation detail. This file is the exported
4
5
  // application contract: business inputs in, business ids/models out. It deliberately has no public
5
- // bridge/session/workspace/actor/sync surface.
6
+ // session/session/workspace/actor/sync surface.
6
7
  import type { z } from "zod";
7
8
 
8
9
  import type { AggregateHandle } from "./aggregate.js";
@@ -28,12 +29,12 @@ import {
28
29
  } from "./codegen_dart.js";
29
30
  import {
30
31
  dartClientClassName,
31
- dartInternalChildAuthenticationRecoveryMethod,
32
32
  dartInternalSourceTrustMethod,
33
- dartInternalWorkspaceSharingReceiptMethod,
34
33
  } from "./codegen_dart_client.js";
35
34
  import { finishCount } from "./count.js";
36
35
  import { finishSum } from "./sum.js";
36
+ import { finishExtremum } from "./extremum.js";
37
+ import { finishExists } from "./exists.js";
37
38
  import {
38
39
  isNamespacedAggregate,
39
40
  qualifyReadProjectionType,
@@ -44,16 +45,12 @@ import {
44
45
  isFrameworkDirective,
45
46
  isFrameworkQuery,
46
47
  } from "./framework/framework_aggregates.js";
47
- import {
48
- childAuthenticationRecoveryAggregateId,
49
- isBusinessIntent,
50
- } from "./intent.js";
48
+ import { isBusinessIntent } from "./intent.js";
51
49
  import { contractTypeName } from "./contract.js";
52
50
  import { admitsNull } from "./null_meta.js";
53
- import type {
54
- WorkspaceSharingPolicy,
55
- WorkspaceSharingReceipt,
56
- } from "./workspace_sharing.js";
51
+ import type { WorkspaceSharingPolicy } from "./workspace_sharing.js";
52
+ import { publishingIntentOf } from "./codegen_call_proto.js";
53
+ import type { LawGraph } from "./law_graph.js";
57
54
 
58
55
  type AnyDirective = Directive<z.ZodTypeAny>;
59
56
 
@@ -99,7 +96,6 @@ const reserved = new Set([
99
96
  const safe = (s: string) => (reserved.has(s) ? `${s}_` : s);
100
97
  const member = (s: string) => safe(lcFirst(camel(s)));
101
98
  const TENANT_ROOT_MEMBERS = new Map<string, string>([
102
- ["nomosWidget", "the generated Nomos Flutter bootstrap"],
103
99
  ["currentUser", "the generated signed-in application participant"],
104
100
  ["currentStatus", "the generated application status"],
105
101
  ["watchStatus", "the generated application status watch"],
@@ -131,6 +127,7 @@ function keyType(
131
127
  const first = key.includes(".") ? key.split(".")[0]! : key;
132
128
  const field = aggregate?.fields[first] as Field | undefined;
133
129
  if (field?.kind === "int" || field?.kind === "counter") return "int";
130
+ if (field?.kind === "bool") return "bool";
134
131
  if (field?.kind === "ref") {
135
132
  if (field.foreignRef !== undefined) {
136
133
  const target =
@@ -159,93 +156,6 @@ function keyType(
159
156
  return "String";
160
157
  }
161
158
 
162
- function sharingOrderValue(
163
- policy: WorkspaceSharingPolicy,
164
- fieldName: string,
165
- target: "wire" | "value" = "value"
166
- ): string {
167
- const field = policy.orders.fields[fieldName];
168
- if (field === undefined) {
169
- throw new Error(
170
- `workspaceSharing(${policy.orders.id}): unknown order field '${fieldName}'`
171
- );
172
- }
173
- const value =
174
- `(order.${member(fieldName)} ?? (throw StateError(` +
175
- `'Incomplete ${policy.orders.id} ${member(fieldName)}')))`;
176
- if (target === "wire" && field.kind === "enum") return `${value}.wire`;
177
- if (field.kind === "ref") return `NmsInternalNomosRefs.id(${value})`;
178
- return value;
179
- }
180
-
181
- function sharingReceiptCondition(
182
- policy: WorkspaceSharingPolicy,
183
- receipt: WorkspaceSharingReceipt
184
- ): string {
185
- const condition = receipt.when;
186
- if (condition === undefined) return "true";
187
- const field = policy.orders.fields[condition.field];
188
- if (field === undefined) {
189
- throw new Error(
190
- `workspaceSharing(${policy.orders.id}): unknown receipt field '${condition.field}'`
191
- );
192
- }
193
- if (!field.isOptional) {
194
- if (condition.is === "absent") {
195
- throw new Error(
196
- `workspaceSharing(${policy.orders.id}): '${condition.field}' cannot be absent because it is required`
197
- );
198
- }
199
- return "true";
200
- }
201
- return `order.${member(condition.field)} ${
202
- condition.is === "present" ? "!=" : "=="
203
- } null`;
204
- }
205
-
206
- function sharingReceiptPayload(
207
- policy: WorkspaceSharingPolicy,
208
- receipt: WorkspaceSharingReceipt,
209
- refused: boolean,
210
- enumDartTypes: ReadonlyMap<string, string>
211
- ): string[] {
212
- const fields = introspectPayload(
213
- receipt.records.payloadSchema as z.ZodTypeAny,
214
- new Map(enumDartTypes)
215
- );
216
- return fields.flatMap((target) => {
217
- if (target.name === "failureReason") {
218
- return refused
219
- ? [
220
- ` failureReason: share.message ?? 'shareDeliveryRefused',`,
221
- ]
222
- : target.optional
223
- ? [` ${member(target.name)}: null,`]
224
- : (() => {
225
- throw new Error(
226
- `workspaceSharing(${policy.orders.id}): delivered receipt '${receipt.records.id}' requires failureReason`
227
- );
228
- })();
229
- }
230
- if (target.name === "deliveryHead" && target.optional) {
231
- return [` ${member(target.name)}: null,`];
232
- }
233
- const sourceName = receipt.payload?.[target.name] ?? target.name;
234
- const source = policy.orders.fields[sourceName];
235
- if (source === undefined) {
236
- if (target.optional) return [` ${member(target.name)}: null,`];
237
- throw new Error(
238
- `workspaceSharing(${policy.orders.id}): receipt '${receipt.records.id}' requires '${target.name}', ` +
239
- `but the durable order does not record '${sourceName}'`
240
- );
241
- }
242
- const raw = sharingOrderValue(policy, sourceName);
243
- const expression =
244
- source.kind === "enum" ? `${target.dartType}.fromWire(${raw}.wire)` : raw;
245
- return [` ${member(target.name)}: ${expression},`];
246
- });
247
- }
248
-
249
159
  export const dartApplicationClassName = (domain: string): string =>
250
160
  `${cap(camel(domain))}Application`;
251
161
  export const dartApplicationActivityClassName = (domain: string): string =>
@@ -347,7 +257,10 @@ function dartConflictPublicClassNames(mod: DomainModule): string[] {
347
257
 
348
258
  export function dartApplicationPublicClassNames(
349
259
  mod: DomainModule,
350
- opts: { readonly tenantRoot?: boolean } = {}
260
+ opts: {
261
+ readonly tenantRoot?: boolean;
262
+ readonly callUsda: DartApplicationOptions["callUsda"];
263
+ }
351
264
  ): string[] {
352
265
  registerDartNames(mod.aggregates);
353
266
  const actions = (
@@ -361,6 +274,7 @@ export function dartApplicationPublicClassNames(
361
274
  (directive as { businessBirth?: unknown }).businessBirth === undefined &&
362
275
  (directive as { birthsChild?: unknown }).birthsChild !== true &&
363
276
  !isFrameworkDirective(directive) &&
277
+ publishingIntentOf(opts.callUsda.graph, mod.domain ?? mod.name, directive.id) === undefined &&
364
278
  dartActionOutputs(directive, mod.aggregates).length > 0
365
279
  );
366
280
  return [
@@ -373,6 +287,10 @@ export function dartApplicationPublicClassNames(
373
287
  : []),
374
288
  ]
375
289
  : []),
290
+ ...((mod.workspaceInvariants ?? []).some(rule => rule.refusal) ? [
291
+ "AdmissionDecision", "Admitted", "DomainRefused", "FrameworkRefused", "UnsupportedRefusalContract",
292
+ "NomosDomainRefusalEvidence", "KernelRefusalCode",
293
+ ] : []),
376
294
  dartApplicationClassName(mod.domain ?? mod.name),
377
295
  dartApplicationActivityClassName(mod.domain ?? mod.name),
378
296
  ...actions.map((directive) => dartActionResultClassName(directive.id)),
@@ -401,6 +319,14 @@ export interface DartApplicationOptions {
401
319
  readonly tenantRoot?: boolean;
402
320
  /** Relative compiler-generated framework-call implementation for this exact application closure. */
403
321
  readonly applicationFrameworkCallsImportUri?: string;
322
+ /** Generated typed RelationTuple read; no independent bookmark index. */
323
+ readonly workspaceAccessReadImportUri?: string;
324
+ /** Canonical typed-law graph and its rendered USDA paths: the authority for which directives are
325
+ * business actions (a directive offered only THROUGH another intent is never a second action). */
326
+ readonly callUsda: {
327
+ readonly graph: LawGraph;
328
+ readonly paths: ReadonlyMap<string, string>;
329
+ };
404
330
  }
405
331
 
406
332
  /**
@@ -412,7 +338,7 @@ export interface DartApplicationOptions {
412
338
  */
413
339
  export function generateDartApplication(
414
340
  mod: DomainModule,
415
- opts: DartApplicationOptions = {}
341
+ opts: DartApplicationOptions
416
342
  ): string {
417
343
  registerDartNames(mod.aggregates);
418
344
  const domain = mod.domain ?? mod.name;
@@ -431,6 +357,44 @@ export function generateDartApplication(
431
357
  );
432
358
  const packageDomains = opts.packageAggregateDomains ?? {};
433
359
  const appLines: string[] = [];
360
+ const foreignContractResolvers: string[] = [];
361
+ // A locator never owns another domain's private nominal decoder. The target
362
+ // application reads its declared implementing aggregate and projects only
363
+ // the public contract fields, after the ordinary authenticated read.
364
+ for (const contract of mod.contracts ?? []) {
365
+ const implementations = mod.aggregates.filter(aggregate => aggregate.implementsContracts?.includes(contract.id));
366
+ if (implementations.length === 0) continue;
367
+ const type = contractTypeName(contract.id);
368
+ foreignContractResolvers.push(
369
+ `Future<${type}?> nomosInternalResolve${application}${type}(`,
370
+ ` ${application} application, ForeignRef<${type}> reference) async {`,
371
+ ` _nmsRequireReference(reference.ref, ${JSON.stringify(contract.id)}, application._client.session.workspace);`,
372
+ ` final matches = <${type}>[];`,
373
+ );
374
+ for (const aggregate of implementations) {
375
+ foreignContractResolvers.push(
376
+ ` for (final row in await application._client.${member(`${concreteClassName(aggregate.id)}ById`)}(reference.id)) {`,
377
+ ` matches.add(${type}(`,
378
+ ` id: row.ref.id,`,
379
+ ...Object.keys(contract.fields).map((name) => {
380
+ const access = `row.${member(name)}`;
381
+ const source = aggregate.fields[name]!;
382
+ const value = source.kind === "enum" ? `${access}?.wire`
383
+ : source.kind === "ref" ? `${access}?.id`
384
+ : source.kind === "string" && (isSha256DigestSchema(source.zod) || isGitObjectIdSchema(source.zod)) ? `${access}?.value`
385
+ : access;
386
+ return ` ${member(name)}: ${value},`;
387
+ }),
388
+ ` ));`,
389
+ ` }`,
390
+ );
391
+ }
392
+ foreignContractResolvers.push(
393
+ ` if (matches.length > 1) throw StateError('Multiple nominal records implement ${type} at this address');`,
394
+ ` return matches.isEmpty ? null : matches.single;`,
395
+ `}`, ``,
396
+ );
397
+ }
434
398
  const applicationMembers = new Map<string, string>();
435
399
  const claimApplicationMember = (name: string, owner: string): void => {
436
400
  const prior = applicationMembers.get(name);
@@ -443,7 +407,6 @@ export function generateDartApplication(
443
407
  applicationMembers.set(name, owner);
444
408
  };
445
409
  claimApplicationMember("activity", "the generated business history");
446
- claimApplicationMember("model", "the generated model lifecycle");
447
410
  const collectionLines = new Map<string, string[]>();
448
411
  const collectionMembers = new Map<string, Set<string>>();
449
412
  const siblingImports = new Map<string, Set<string>>();
@@ -459,6 +422,7 @@ export function generateDartApplication(
459
422
  mod.surfacedResolvers ?? [];
460
423
  const sharingPolicies: readonly WorkspaceSharingPolicy[] =
461
424
  mod.applicationWorkspaceSharing ?? [];
425
+ const hasWorkspaceAccessRead = opts.workspaceAccessReadImportUri !== undefined;
462
426
  const hasVersionedRefs = mod.aggregates.some((aggregate) =>
463
427
  Object.values(aggregate.fields as Record<string, Field>).some(
464
428
  (field) => field.versionedForeignRef !== undefined
@@ -600,23 +564,9 @@ export function generateDartApplication(
600
564
  "object" &&
601
565
  (directive as { businessBirthInternal?: unknown })
602
566
  .businessBirthInternal !== true &&
603
- !isFrameworkDirective(directive)
567
+ !isFrameworkDirective(directive) &&
568
+ publishingIntentOf(opts.callUsda.graph, domain, directive.id) === undefined
604
569
  );
605
- const childAuthenticationRecoveryByAggregate = new Map<
606
- string,
607
- AnyDirective
608
- >();
609
- for (const directive of directives) {
610
- if (!isBusinessIntent(directive)) continue;
611
- const aggregateId = childAuthenticationRecoveryAggregateId(directive);
612
- if (aggregateId === undefined) continue;
613
- if (childAuthenticationRecoveryByAggregate.has(aggregateId)) {
614
- throw new Error(
615
- `generated application '${domain}' has more than one child authentication recovery action for '${aggregateId}'`
616
- );
617
- }
618
- childAuthenticationRecoveryByAggregate.set(aggregateId, directive);
619
- }
620
570
  const actionReferenceChecks = (directive: AnyDirective): string[] => {
621
571
  let specs: ReturnType<typeof introspectPayload>;
622
572
  try {
@@ -644,7 +594,7 @@ export function generateDartApplication(
644
594
  : [
645
595
  ` _nmsRequireReference(target, ${JSON.stringify(
646
596
  targetBinding.aggregateId
647
- )}, _client.session?.workspace ?? '');`,
597
+ )}, _client.session.workspace);`,
648
598
  ];
649
599
  return [
650
600
  ...targetChecks,
@@ -667,7 +617,7 @@ export function generateDartApplication(
667
617
  const expectedWorkspace =
668
618
  spec.shape === "addressRef" || foreignReferenceIds.has(spec.name)
669
619
  ? "''"
670
- : "_client.session?.workspace ?? ''";
620
+ : "_client.session.workspace";
671
621
  const value = `facts.${member(spec.name)}`;
672
622
  const check = `_nmsRequireReference(${value}, ${JSON.stringify(
673
623
  targetWire
@@ -842,17 +792,21 @@ export function generateDartApplication(
842
792
  }' needs exactly keys ${satisfactionQuery.key.join(", ")}`
843
793
  );
844
794
  }
845
- // A declared satisfaction query means trust is already a typed law fact.
846
- // The kernel's foreign-read policy evaluates that fact while admitting the
847
- // business offer. Do not create a second, client-side read-then-auto-grant
848
- // authority ceremony.
849
- if (satisfactionQuery !== undefined) {
850
- return { prelude: [], call };
851
- }
852
- const trustIndent = " ";
795
+ // The declaration names how to observe enrollment; it does not prove a
796
+ // row exists. Seat a missing source through the declared, gated law action.
797
+ // Existing rows are left for the kernel to judge, including a revoked or
798
+ // mismatched identity: this preflight must not silently replace them.
799
+ const satisfactionPrelude = satisfactionQuery === undefined ? [] : [
800
+ ` final sourceTrustAlreadySatisfied = (await _client.${member(satisfactionQuery.id)}(${satisfactionQuery.key
801
+ .map(key => `${member(key)}: ${factValue(satisfactionArgs[key]!)}`)
802
+ .join(", ")})).isNotEmpty;`,
803
+ " if (!sourceTrustAlreadySatisfied) {",
804
+ ];
805
+ const trustIndent = satisfactionQuery === undefined ? " " : " ";
853
806
  return {
854
807
  prelude: [
855
- `${trustIndent}final sourceGenesis = await _client.bridge.nomosWorkspaceGenesis(${factValue(
808
+ ...satisfactionPrelude,
809
+ `${trustIndent}final sourceGenesis = await _client.session.nomosWorkspaceGenesis(${factValue(
856
810
  trust.fromPayload
857
811
  )});`,
858
812
  `${trustIndent}await _client.${dartInternalSourceTrustMethod(
@@ -868,6 +822,7 @@ export function generateDartApplication(
868
822
  trust.keyHashesField
869
823
  )}: const <${keyElementType}>[],`,
870
824
  `${trustIndent} ));`,
825
+ ...(satisfactionQuery === undefined ? [] : [" }"]),
871
826
  ],
872
827
  call,
873
828
  };
@@ -880,167 +835,47 @@ export function generateDartApplication(
880
835
  ` /// A uid crosses the string boundary once. Generated invitation actions then require`,
881
836
  ` /// [Recipient<User>], so an email address, principal or record id cannot be substituted.`,
882
837
  ` Recipient<User> recipient(String uid) =>`,
883
- ` NmsInternalApplicationHost.recipient<User>(uid);`,
838
+ ` _nmsReception.recipient<User>(uid);`,
884
839
  ``,
885
840
  ` /// Create a single-use invitation. Transport [Invitation.link] however your product chooses.`,
886
841
  ` Future<Invitation<User>> createInvitation() =>`,
887
- ` NmsInternalApplicationHost.createInvitation<User>(_client.bridge);`,
842
+ ` _nmsReception.createInvitation<User>();`,
888
843
  ``,
889
- ` /// Redeem a transported invitation link as the verified [currentUser].`,
890
- ` Future<void> redeemInvitation(String link) =>`,
891
- ` NmsInternalApplicationHost.redeemInvitation<User>(`,
892
- ` _client.bridge,`,
893
- ` frameworkCalls: nomosInternalApplicationFrameworkCalls,`,
894
- ` link: link,`,
895
- ` identity: _client.actor,`,
896
- ` policies: [`,
844
+ // ONE construction site for this domain's policies. The pending lookup runs on the domain
845
+ // CLIENT — the framework-internal sharing query is deliberately absent from the application
846
+ // surface — so a multi-domain package application cannot rebuild these from outside; it
847
+ // composes THESE instead (compile_package_main's generatedPackageApplication).
848
+ ` /// Framework-internal: the invitation policies declared by this domain.`,
849
+ ` List<NmsReceptionInvitationPolicy> get nomosInternalInvitationPolicies => [`,
897
850
  ...sharingPolicies
898
851
  .map((policy) => [
899
- ` NmsInternalInvitationPolicy(`,
852
+ ` NmsReceptionInvitationPolicy(`,
900
853
  ` domain: ${JSON.stringify(domain)},`,
901
854
  ` domainHash: _client.domainHash,`,
902
- ` query: ${JSON.stringify(
903
- policy.invitationLaw.pendingByRecipient.id
904
- )},`,
905
855
  ` redeem: ${JSON.stringify(
906
856
  policy.invitationLaw.redeem.id
907
857
  )},`,
908
- ` personField: ${JSON.stringify(policy.person)},`,
909
- ` roleField: ${JSON.stringify(policy.role)},`,
910
- ` scopeField: ${JSON.stringify(policy.scope)},`,
858
+ ` pending: (address) async => (await _client.${member(
859
+ policy.invitationLaw.pendingByRecipient.id
860
+ )}(${member(
861
+ policy.person
862
+ )}: address)).map((row) => NmsReceptionInvitationMatch(`,
863
+ ` orderId: row.ref.id,`,
864
+ ` object: row.${member(policy.scope)}.toString(),`,
865
+ ` relation: row.${member(policy.role)}.toString(),`,
866
+ ` )).toList(growable: false),`,
911
867
  ` ),`,
912
868
  ])
913
869
  .flat(),
914
- ` ],`,
915
- ` );`,
916
- ``
917
- );
918
- for (const [index, policy] of sharingPolicies.entries()) {
919
- const pendingKey = policy.pending.key[0]!;
920
- const pendingMethod = member(policy.pending.id);
921
- const pendingAggregate = aggregates.get(policy.pending.returns);
922
- const pendingField = pendingAggregate?.fields[pendingKey] as
923
- | Field
924
- | undefined;
925
- const pendingValue =
926
- pendingField?.kind === "enum"
927
- ? `${keyType(
928
- pendingAggregate,
929
- pendingKey,
930
- enumDartTypes
931
- )}.fromWire(${JSON.stringify(policy.pendingValue)})`
932
- : JSON.stringify(policy.pendingValue);
933
- const person = sharingOrderValue(policy, policy.person, "wire");
934
- const role = sharingOrderValue(policy, policy.role, "wire");
935
- const scope = sharingOrderValue(policy, policy.scope, "wire");
936
- const receiptLines = (
937
- receipt: WorkspaceSharingReceipt,
938
- refused: boolean
939
- ): string[] => {
940
- const condition = sharingReceiptCondition(policy, receipt);
941
- const body = [
942
- ` await _client.${dartInternalWorkspaceSharingReceiptMethod(
943
- receipt.records.id
944
- )}((`,
945
- ...sharingReceiptPayload(policy, receipt, refused, enumDartTypes),
946
- ` ));`,
947
- ` continue;`,
948
- ];
949
- // A receipt with no `when` is the policy's exhaustive fallback. Emitting `if (true)` makes both
950
- // the following fallback error and any later receipt dead Dart code, turning generated code into an
951
- // analyzer warning. Keep the same semantics but emit the exhaustive body directly.
952
- return condition === "true"
953
- ? body
954
- : [` if (${condition}) {`, ...body, ` }`];
955
- };
956
- const delivered = policy.delivered.flatMap((receipt) =>
957
- receiptLines(receipt, false)
958
- );
959
- const refused = policy.refused.flatMap((receipt) =>
960
- receiptLines(receipt, true)
961
- );
962
- const deliveredExhaustive = policy.delivered.some(
963
- (receipt) => sharingReceiptCondition(policy, receipt) === "true"
964
- );
965
- const refusedExhaustive = policy.refused.some(
966
- (receipt) => sharingReceiptCondition(policy, receipt) === "true"
967
- );
968
- appLines.push(
969
- ` Future<void>? _nmsWorkspaceSharingDrain${index};`,
970
- ` StreamSubscription<Object?>? _nmsWorkspaceSharingSync${index};`,
971
- ` bool _nmsWorkspaceSharingNeedsRetry${index} = false;`,
972
- ``,
973
- ` Future<void> _nmsStartWorkspaceSharing${index}() async {`,
974
- ` await _nmsDrainWorkspaceSharing${index}();`,
975
- ` _nmsWorkspaceSharingSync${index} ??= _client.bridge.syncStatus.map<Object?>((status) {`,
976
- ` if (_nmsWorkspaceSharingDrain${index} == null &&`,
977
- ` (status.phase == SyncPhase.offline || status.phase == SyncPhase.error || status.behind > 0)) {`,
978
- ` _nmsWorkspaceSharingNeedsRetry${index} = true;`,
979
- ` } else if (status.phase == SyncPhase.idle && _nmsWorkspaceSharingNeedsRetry${index}) {`,
980
- ` _nmsWorkspaceSharingNeedsRetry${index} = false;`,
981
- ` unawaited(_nmsDrainWorkspaceSharing${index}());`,
982
- ` }`,
983
- ` return status;`,
984
- ` }).listen((_) {});`,
985
- ` }`,
986
- ``,
987
- ` Future<void> _nmsDrainWorkspaceSharing${index}() {`,
988
- ` final active = _nmsWorkspaceSharingDrain${index};`,
989
- ` if (active != null) return active;`,
990
- ` final started = _nmsDrainWorkspaceSharingOnce${index}();`,
991
- ` _nmsWorkspaceSharingDrain${index} = started;`,
992
- ` return started.whenComplete(() {`,
993
- ` if (identical(_nmsWorkspaceSharingDrain${index}, started)) {`,
994
- ` _nmsWorkspaceSharingDrain${index} = null;`,
995
- ` }`,
996
- ` });`,
997
- ` }`,
998
- ``,
999
- ` Future<void> _nmsDrainWorkspaceSharingOnce${index}() async {`,
1000
- ` final orders = await _client.${pendingMethod}(`,
1001
- ` ${member(pendingKey)}: ${pendingValue},`,
1002
- ` );`,
1003
- ` for (final order in orders) {`,
1004
- ` late final ApplicationShareResult share;`,
1005
- ` try {`,
1006
- ` share = await NmsInternalApplicationHost.shareWith(`,
1007
- ` _client.bridge, person: ${person}, role: ${role}, scope: ${scope}, identity: _client.actor,`,
1008
- ` );`,
1009
- ` } catch (_) {`,
1010
- ` continue;`,
1011
- ` }`,
1012
- ` if (share.awaitingRecipient) continue;`,
1013
- ` if (share.delivered) {`,
1014
- ...delivered,
1015
- ...(deliveredExhaustive
1016
- ? []
1017
- : [
1018
- ` throw StateError('No delivered receipt matches ${policy.orders.id} \${NmsInternalNomosRefs.id(order.ref)}');`,
1019
- ]),
1020
- ` }`,
1021
- ...refused,
1022
- ...(refusedExhaustive
1023
- ? []
1024
- : [
1025
- ` throw StateError('No refused receipt matches ${policy.orders.id} \${NmsInternalNomosRefs.id(order.ref)}');`,
1026
- ]),
1027
- ` }`,
1028
- ` }`,
1029
- ``
1030
- );
1031
- }
1032
- appLines.push(
1033
- ` Future<void> _nmsStartWorkspaceSharing() async {`,
1034
- ...sharingPolicies.map(
1035
- (_policy, index) => ` await _nmsStartWorkspaceSharing${index}();`
1036
- ),
1037
- ` }`,
870
+ ` ];`,
1038
871
  ``,
1039
- ` Future<void> _nmsDrainWorkspaceSharing() async {`,
1040
- ...sharingPolicies.map(
1041
- (_policy, index) => ` await _nmsDrainWorkspaceSharing${index}();`
1042
- ),
1043
- ` }`,
872
+ ` /// Redeem a transported invitation link as the verified [currentUser].`,
873
+ ` Future<void> redeemInvitation(String link) =>`,
874
+ ` _nmsReception.redeemInvitation<User>(`,
875
+ ` frameworkCalls: nomosInternalApplicationFrameworkCalls,`,
876
+ ` link: link,`,
877
+ ` policies: nomosInternalInvitationPolicies,`,
878
+ ` );`,
1044
879
  ``
1045
880
  );
1046
881
  }
@@ -1050,13 +885,10 @@ export function generateDartApplication(
1050
885
  policy.initiatedBy.map((intent) => intent.id)
1051
886
  )
1052
887
  );
1053
- const afterBusinessWrite = (directive: AnyDirective): string[] =>
1054
- sharingInitiatorIds.has(directive.id)
1055
- ? [` await _nmsDrainWorkspaceSharing();`]
1056
- : [];
888
+ const afterBusinessWrite = (_directive: AnyDirective): string[] => [];
1057
889
  const businessActionDoc = (directive: AnyDirective): string => {
1058
890
  return sharingInitiatorIds.has(directive.id)
1059
- ? "One business action. Nomos durably delivers its access change and retries after restart or reconnect; do not mirror delivery in application state."
891
+ ? "One business action. Peer Office durably delivers its correspondence in the background; do not mirror delivery in application state."
1060
892
  : "One business action; every consequence commits atomically.";
1061
893
  };
1062
894
 
@@ -1096,8 +928,6 @@ export function generateDartApplication(
1096
928
  : concreteClassName(rootAggregate.id)
1097
929
  )
1098
930
  );
1099
- const childAuthenticationRecovery =
1100
- childAuthenticationRecoveryByAggregate.get(birth.aggregateId);
1101
931
  if (targetFile !== mod.name) {
1102
932
  addSibling(`${targetFile}.application.dart`, targetApplication);
1103
933
  addSibling(`${targetFile}.application.dart`, opener);
@@ -1118,7 +948,7 @@ export function generateDartApplication(
1118
948
  ` final reference = await _client.${method}(facts);`,
1119
949
  opts.supportImport === "package"
1120
950
  ? ` return ${rootCollection}._nmsOpenReference(reference);`
1121
- : ` return ${opener}(_client.bridge, reference, _client.actor);`,
951
+ : ` return ${opener}(_nmsReception, reference);`,
1122
952
  ` }`,
1123
953
  ``
1124
954
  );
@@ -1131,7 +961,7 @@ export function generateDartApplication(
1131
961
  ` final reference = await _client.birth(facts);`,
1132
962
  opts.supportImport === "package"
1133
963
  ? ` return _nmsOpenReference(reference);`
1134
- : ` return ${opener}(_client.bridge, reference, _client.actor);`,
964
+ : ` return ${opener}(_nmsReception, reference);`,
1135
965
  ` }`,
1136
966
  ``,
1137
967
  ]);
@@ -1143,44 +973,12 @@ export function generateDartApplication(
1143
973
  ? `${concreteClassName(birth.aggregateId)}ReadModel`
1144
974
  : readModelClassName(rootAggregate.id);
1145
975
  addCollectionMember(birth.aggregateId, "open", [
1146
- ` final Map<String, Future<${targetApplication}>> _nmsApplications = {};`,
1147
- ``,
1148
- ` Future<${targetApplication}> _nmsOpenReference(NomosRef<${rootType}> reference) {`,
1149
- ` final workspace = NmsInternalNomosRefs.workspace(reference);`,
1150
- ` final existing = _nmsApplications[workspace];`,
1151
- ` if (existing != null) {`,
1152
- ` return NmsInternalApplicationHost.nmsInternalAwaitReferencedApplication(`,
1153
- ` workspace: workspace, opening: existing,`,
1154
- ` );`,
1155
- ` }`,
1156
- ` late final Future<${targetApplication}> opened;`,
1157
- ` opened = (() async {`,
1158
- ` try {`,
1159
- ` return await ${opener}(`,
1160
- ` _client.bridge, reference, _client.actor,`,
1161
- ...(childAuthenticationRecovery === undefined
1162
- ? []
1163
- : [
1164
- ` recoverAuthentication: () => _client.${dartInternalChildAuthenticationRecoveryMethod(
1165
- birth.aggregateId
1166
- )}(workspace),`,
1167
- ]),
1168
- ` );`,
1169
- ` } catch (_) {`,
1170
- ` if (identical(_nmsApplications[workspace], opened)) {`,
1171
- ` _nmsApplications.remove(workspace);`,
1172
- ` }`,
1173
- ` rethrow;`,
1174
- ` }`,
1175
- ` })();`,
1176
- ` _nmsApplications[workspace] = opened;`,
1177
- ` return NmsInternalApplicationHost.nmsInternalAwaitReferencedApplication(`,
1178
- ` workspace: workspace, opening: opened,`,
1179
- ` );`,
1180
- ` }`,
976
+ ` Future<${targetApplication}> _nmsOpenReference(NomosRef<${rootType}> reference) =>`,
977
+ ` ${opener}(_nmsReception, reference);`,
1181
978
  ``,
1182
979
  ` /// Open the workspace named by a typed ${rootType} custody reference.`,
1183
- ` /// The reference supplies identity and routing only; normal authority checks still apply.`,
980
+ ` /// The reference supplies stable identity only; the peer runtime resolves placement,`,
981
+ ` /// and normal authority checks still apply.`,
1184
982
  ` Future<${targetApplication}> openReference(NomosRef<${rootType}> reference) {`,
1185
983
  ` _nmsRequireReference(reference, ${JSON.stringify(
1186
984
  birth.aggregateId
@@ -1188,32 +986,45 @@ export function generateDartApplication(
1188
986
  ` return _nmsOpenReference(reference);`,
1189
987
  ` }`,
1190
988
  ``,
989
+ ` /// Follow the workspace named by a typed ${rootType} reference without opening`,
990
+ ` /// or reading it. The peer fetches and prepares its local copy in the background.`,
991
+ ` Future<void> fetchReference(NomosRef<${rootType}> reference) {`,
992
+ ` _nmsRequireReference(reference, ${JSON.stringify(birth.aggregateId)}, '');`,
993
+ ` return _nmsReception.fetchWorkspace(reference.workspace);`,
994
+ ` }`,
995
+ ``,
1191
996
  ` /// Open the ${birth.aggregateId} whose ${birth.keyField} is [key].`,
1192
- ` Future<${targetApplication}> open(String key) => _nmsOpenReference(`,
997
+ ` /// THE OFFICE NAMES THE WORKSPACE this key addresses: the derivation is law,`,
998
+ ` /// and a generated copy of it would silently address a different workspace`,
999
+ ` /// the moment either side moved.`,
1000
+ ` Future<${targetApplication}> open(String key) async => _nmsOpenReference(`,
1193
1001
  ` NmsInternalNomosRefs.create<${rootType}>(`,
1194
- ` workspace: deriveWorkspaceName(${JSON.stringify(
1195
- birth.namespace
1196
- )}, key),`,
1002
+ ` workspace: await _nmsReception.keyedBirthWorkspace(`,
1003
+ ` namespace: ${JSON.stringify(birth.namespace)}, key: key,`,
1004
+ ` ),`,
1197
1005
  ` type: ${JSON.stringify(birth.aggregateId)},`,
1198
1006
  ` id: ${JSON.stringify(birth.rootId)},`,
1199
1007
  ` ),`,
1200
1008
  ` );`,
1201
1009
  ``,
1202
- ` /// Current kernel-owned progress while [open] prepares this workspace.`,
1203
- ` ApplicationWorkspaceOpenProgress? openProgress(String key) =>`,
1204
- ` NomosApplicationObservability.workspaceOpenProgress(`,
1205
- ` deriveWorkspaceName(${JSON.stringify(
1206
- birth.namespace
1207
- )}, key),`,
1208
- ` );`,
1010
+ ` /// Fetch the ${birth.aggregateId} whose ${birth.keyField} is [key] onto this device now,`,
1011
+ ` /// opening and reading nothing: its placement's follow mounts the provider's head in`,
1012
+ ` /// the background. Completes once that follow exists (e.g. prefetching every workspace`,
1013
+ ` /// a list names, all at once, so each is local before it is tapped).`,
1014
+ ` Future<void> fetch(String key) async => _nmsReception.fetchWorkspace(`,
1015
+ ` await _nmsReception.keyedBirthWorkspace(`,
1016
+ ` namespace: ${JSON.stringify(birth.namespace)}, key: key,`,
1017
+ ` ),`,
1018
+ ` );`,
1209
1019
  ``,
1210
1020
  ` /// Kernel-owned progress updates while [open] prepares this workspace.`,
1021
+ ` /// ONE LANE: the stream is the whole surface. A synchronous snapshot`,
1022
+ ` /// would have to answer before the office has named the workspace, so`,
1023
+ ` /// it could only ever answer null or hold a cached name of its own.`,
1211
1024
  ` Stream<ApplicationWorkspaceOpenProgress> watchOpenProgress(String key) =>`,
1212
- ` NomosApplicationObservability.watchWorkspaceOpenProgress(`,
1213
- ` deriveWorkspaceName(${JSON.stringify(
1214
- birth.namespace
1215
- )}, key),`,
1216
- ` );`,
1025
+ ` Stream<String>.fromFuture(_nmsReception.keyedBirthWorkspace(`,
1026
+ ` namespace: ${JSON.stringify(birth.namespace)}, key: key,`,
1027
+ ` )).asyncExpand(_nmsReception.streams.workspaceOpenProgress);`,
1217
1028
  ``,
1218
1029
  ]);
1219
1030
  addCollectionMember(birth.aggregateId, "mine", [
@@ -1224,18 +1035,11 @@ export function generateDartApplication(
1224
1035
  ` if (principal == null || principal.trim().isEmpty) {`,
1225
1036
  ` throw StateError('The signed-in person is not available.');`,
1226
1037
  ` }`,
1227
- ` final births = await _client.bridge.query(`,
1228
- ` 'birthRecordsByPrincipal',`,
1229
- ` {'principal': principal},`,
1230
- ` );`,
1038
+ ` final births = await _nmsReception.activeChildWorkspaces(namespace: ${JSON.stringify(
1039
+ birth.namespace
1040
+ )});`,
1231
1041
  ` final records = <${rootModel}>[];`,
1232
- ` for (final row in births) {`,
1233
- ` final raw = row['data'];`,
1234
- ` if (raw is! Map) continue;`,
1235
- ` final child = (raw['child'] ?? '').toString();`,
1236
- ` if (!child.startsWith(${JSON.stringify(
1237
- `${birth.namespace}-`
1238
- )})) continue;`,
1042
+ ` for (final child in births) {`,
1239
1043
  ` final reference = NmsInternalNomosRefs.create<${rootType}>(workspace: child, type: ${JSON.stringify(
1240
1044
  birth.aggregateId
1241
1045
  )}, id: ${JSON.stringify(birth.rootId)});`,
@@ -1252,9 +1056,10 @@ export function generateDartApplication(
1252
1056
  ` if (principal == null || principal.trim().isEmpty) {`,
1253
1057
  ` throw StateError('The signed-in person is not available.');`,
1254
1058
  ` }`,
1255
- ` return _client.bridge`,
1256
- ` .watch('birthRecordsByPrincipal', {'principal': principal})`,
1257
- ` .asyncMap((_) => mine());`,
1059
+ ` return _nmsReception.streams.refreshOn(`,
1060
+ ` read: mine,`,
1061
+ ` changes: [_nmsReception.streams.childWorkspaces],`,
1062
+ ` );`,
1258
1063
  ` }`,
1259
1064
  ``,
1260
1065
  ` /// Every ${birth.aggregateId} the signed-in person can use, whether founded or shared.`,
@@ -1272,29 +1077,40 @@ export function generateDartApplication(
1272
1077
  ` return records;`,
1273
1078
  ` }`,
1274
1079
  ``,
1275
- ` /// The ${birth.aggregateId} lives shared with the signed-in person.`,
1276
- ` /// Unlike [available], this does not open lives founded by that person.`,
1277
- ` Future<List<${rootModel}>> shared() async {`,
1278
- ` final records = <${rootModel}>[];`,
1279
- ` final seen = <String>{};`,
1280
- ` final shares = await _client.bridge.query('sharedByObject', {'object': 'workspace:self'}, null, _client.actor);`,
1281
- ` for (final row in shares) {`,
1282
- ` final raw = row['data'];`,
1283
- ` if (raw is! Map) continue;`,
1284
- ` final workspace = (raw['asserterWorkspace'] ?? '').toString();`,
1285
- ` final object = (raw['object'] ?? '').toString();`,
1286
- ` final prunedAt = (raw['prunedAt'] ?? '').toString();`,
1080
+ ` /// Home-local Zanzibar discovery. Does not open or contact any shared workspace.`,
1081
+ ` Future<List<({NomosRef<${rootType}> reference, String object, String relation})>> sharedReferences() async {`,
1082
+ ...(!hasWorkspaceAccessRead
1083
+ ? [` throw StateError('This application has no compiled received-access query');`]
1084
+ : [
1085
+ ` final principal = _client.actor;`,
1086
+ ` if (principal == null || principal.isEmpty) throw StateError('No signed-in principal');`,
1087
+ ` final shares = await nomosInternalReadReceivedAccess(_client.session, principal);`,
1088
+ ` final references = <({NomosRef<${rootType}> reference, String object, String relation})>[];`,
1089
+ ` for (final share in shares) {`,
1090
+ ` final workspace = share.workspace;`,
1287
1091
  ` if (!workspace.startsWith(${JSON.stringify(
1288
1092
  `${birth.namespace}-`
1289
- )}) ||`,
1290
- ` object != 'workspace:self' ||`,
1291
- ` prunedAt.isNotEmpty ||`,
1292
- ` !seen.add(workspace)) continue;`,
1093
+ )})) continue;`,
1293
1094
  ` final reference = NmsInternalNomosRefs.create<${rootType}>(workspace: workspace, type: ${JSON.stringify(
1294
1095
  birth.aggregateId
1295
1096
  )}, id: ${JSON.stringify(birth.rootId)});`,
1296
- ` final application = await _nmsOpenReference(reference);`,
1297
- ` final record = await application.${rootCollection}.find(reference);`,
1097
+ ` references.add((reference: reference, object: share.object, relation: share.relation));`,
1098
+ ` }`,
1099
+ ` return references;`,
1100
+ ]),
1101
+ ` }`,
1102
+ ``,
1103
+ ` Stream<List<({NomosRef<${rootType}> reference, String object, String relation})>> watchSharedReferences() =>`,
1104
+ ` _nmsReception.streams.refreshOn(read: sharedReferences, changes: [_nmsReception.streams.workspaceChanges]);`,
1105
+ ``,
1106
+ ` /// Explicitly resolve shared references to full business records. Lists should use [sharedReferences].`,
1107
+ ` Future<List<${rootModel}>> shared() async {`,
1108
+ ` final records = <${rootModel}>[];`,
1109
+ ` final seen = <String>{};`,
1110
+ ` for (final share in await sharedReferences()) {`,
1111
+ ` if (!seen.add(NmsInternalNomosRefs.workspace(share.reference))) continue;`,
1112
+ ` final application = await _nmsOpenReference(share.reference);`,
1113
+ ` final record = await application.${rootCollection}.find(share.reference);`,
1298
1114
  ` if (record != null) records.add(record);`,
1299
1115
  ` }`,
1300
1116
  ` return records;`,
@@ -1302,46 +1118,17 @@ export function generateDartApplication(
1302
1118
  ``,
1303
1119
  ` /// React when this person's shared ${birth.aggregateId} lives change.`,
1304
1120
  ` Stream<List<${rootModel}>> watchShared() =>`,
1305
- ` _client.bridge`,
1306
- ` .watch('sharedByObject', {'object': 'workspace:self'}, null, _client.actor, 60000)`,
1307
- ` .asyncMap((_) => shared());`,
1121
+ ` _nmsReception.streams.workspaceChanges.asyncMap((_) => shared());`,
1308
1122
  ``,
1309
1123
  ` /// React when this person's available ${birth.aggregateId} lives change.`,
1310
1124
  ` Stream<List<${rootModel}>> watchAvailable() =>`,
1311
- ` Stream<List<${rootModel}>>.multi((events) {`,
1312
- ` var reading = false;`,
1313
- ` var reread = false;`,
1314
- ` Future<void> refresh() async {`,
1315
- ` if (reading) {`,
1316
- ` reread = true;`,
1317
- ` return;`,
1318
- ` }`,
1319
- ` reading = true;`,
1320
- ` do {`,
1321
- ` reread = false;`,
1322
- ` try {`,
1323
- ` final records = await available();`,
1324
- ` if (!events.isClosed) events.add(records);`,
1325
- ` } catch (error, stackTrace) {`,
1326
- ` if (!events.isClosed) events.addError(error, stackTrace);`,
1327
- ` }`,
1328
- ` } while (reread && !events.isClosed);`,
1329
- ` reading = false;`,
1330
- ` }`,
1331
- ` final birthChanges = _client.bridge`,
1332
- ` .watch('birthRecordsByPrincipal', {'principal': _client.actor}, null, null, 60000)`,
1333
- ` .skip(1)`,
1334
- ` .listen((_) { refresh(); }, onError: events.addError);`,
1335
- ` final shareChanges = _client.bridge`,
1336
- ` .watch('sharedByObject', {'object': 'workspace:self'}, null, _client.actor, 60000)`,
1337
- ` .skip(1)`,
1338
- ` .listen((_) { refresh(); }, onError: events.addError);`,
1339
- ` events.onCancel = () async {`,
1340
- ` await birthChanges.cancel();`,
1341
- ` await shareChanges.cancel();`,
1342
- ` };`,
1343
- ` refresh();`,
1344
- ` });`,
1125
+ ` _nmsReception.streams.refreshOn(`,
1126
+ ` read: available,`,
1127
+ ` changes: [`,
1128
+ ` _nmsReception.streams.childWorkspaces,`,
1129
+ ` _nmsReception.streams.workspaceChanges.skip(1),`,
1130
+ ` ],`,
1131
+ ` );`,
1345
1132
  ``,
1346
1133
  ` /// Continue working in the business application that produced [record].`,
1347
1134
  ` Future<${targetApplication}> applicationOf(${rootModel} record) {`,
@@ -1453,6 +1240,20 @@ export function generateDartApplication(
1453
1240
  }>(change, ${JSON.stringify(output.aggregateId)})`
1454
1241
  )
1455
1242
  .join(", ")})`;
1243
+ const contracts = refusalContracts(mod, directive.id);
1244
+ if (contracts.length > 0) {
1245
+ const decisionMethod = `decide${cap(camel(directive.id))}`;
1246
+ const returnType = resultExpression === undefined ? "NomosOperationReceipt" : resultClass;
1247
+ const args = emptyPayload ? "" : directive.targetBinding === undefined ? "facts" : targetOnly ? "target" : "target, facts";
1248
+ const lines = [
1249
+ ` /// Exhaustive admission decision; operational failures keep their runtime meaning.`,
1250
+ ` Future<AdmissionDecision<${returnType}, ${refusalType(directive.id, contracts)}>> ${decisionMethod}(${targetParameter}) =>`,
1251
+ ` nmsAdmissionDecision(() => ${method}(${args}), ${refusalDecoder(directive.id)});`,
1252
+ ``,
1253
+ ];
1254
+ if (isBusinessIntent(directive)) { claimApplicationMember(decisionMethod, `admission decision '${directive.id}'`); appLines.push(...lines); }
1255
+ else addCollectionMember(directive.aggregateId, decisionMethod, lines);
1256
+ }
1456
1257
  if (isBusinessIntent(directive)) {
1457
1258
  claimApplicationMember(method, `business intent '${directive.id}'`);
1458
1259
  const sourceTrust = sourceTrustAction(directive);
@@ -1768,9 +1569,8 @@ export function generateDartApplication(
1768
1569
  ` final id = ${sourceFieldValue};`,
1769
1570
  ` if (id == null) return null;`,
1770
1571
  ` final application = await ${opener}(`,
1771
- ` _client.bridge,`,
1572
+ ` _nmsReception,`,
1772
1573
  ` id,`,
1773
- ` _client.actor,`,
1774
1574
  ` );`,
1775
1575
  ` return application.${targetCollection}.find(`,
1776
1576
  ` id,`,
@@ -1779,9 +1579,8 @@ export function generateDartApplication(
1779
1579
  : [
1780
1580
  ` final id = ${sourceFieldValue};`,
1781
1581
  ` final application = await ${opener}(`,
1782
- ` _client.bridge,`,
1582
+ ` _nmsReception,`,
1783
1583
  ` id,`,
1784
- ` _client.actor,`,
1785
1584
  ` );`,
1786
1585
  ` return application.${targetCollection}.find(`,
1787
1586
  ` id,`,
@@ -1799,17 +1598,15 @@ export function generateDartApplication(
1799
1598
  ` final id = ${sourceFieldValue};`,
1800
1599
  ` if (id == null) return Future<${targetApplication}?>.value(null);`,
1801
1600
  ` return ${opener}(`,
1802
- ` _client.bridge,`,
1601
+ ` _nmsReception,`,
1803
1602
  ` id,`,
1804
- ` _client.actor,`,
1805
1603
  ` );`,
1806
1604
  ]
1807
1605
  : [
1808
1606
  ` final id = record.${sourceFieldMember};`,
1809
1607
  ` return ${opener}(`,
1810
- ` _client.bridge,`,
1608
+ ` _nmsReception,`,
1811
1609
  ` id,`,
1812
- ` _client.actor,`,
1813
1610
  ` );`,
1814
1611
  ]),
1815
1612
  ` }`,
@@ -1820,7 +1617,23 @@ export function generateDartApplication(
1820
1617
  const target =
1821
1618
  foreign.targetIsContract === true
1822
1619
  ? contractTypeName(foreign.targetAggregateId)
1823
- : concreteClassName(foreign.targetAggregateId);
1620
+ : readModelClassName(foreign.targetAggregateId);
1621
+ const targetOwner =
1622
+ packageDomains[foreign.targetAggregateId] ??
1623
+ (aggregates.has(foreign.targetAggregateId) ? { domain, name: mod.name } : undefined) ??
1624
+ (foreign.targetDomain === undefined
1625
+ ? undefined
1626
+ : Object.values(packageDomains).find(
1627
+ (candidate) => candidate.domain === foreign.targetDomain
1628
+ ));
1629
+ const targetApplication = targetOwner === undefined ? undefined : dartApplicationClassName(targetOwner.domain);
1630
+ const opener = targetApplication === undefined ? undefined : `nomosInternalOpen${targetApplication}`;
1631
+ const resolver = targetApplication === undefined ? undefined : `nomosInternalResolve${targetApplication}${target}`;
1632
+ if (targetOwner !== undefined && targetOwner.domain !== domain) {
1633
+ addSibling(`${targetOwner.name}.application.dart`, targetApplication!);
1634
+ addSibling(`${targetOwner.name}.application.dart`, opener!);
1635
+ if (foreign.targetIsContract === true) addSibling(`${targetOwner.name}.application.dart`, resolver!);
1636
+ }
1824
1637
  const fieldMember = member(fieldName);
1825
1638
  const fieldValue = admitsNull(field)
1826
1639
  ? `record.${fieldMember}.valueOrNull`
@@ -1834,7 +1647,14 @@ export function generateDartApplication(
1834
1647
  ` Future<${target}?> ${method}(${sourceModel} record) async {`,
1835
1648
  ` final reference = ${fieldValue};`,
1836
1649
  ` if (reference == null) return null;`,
1837
- ` final target = await NmsInternalForeignRefs.resolve(reference, _client.bridge.foreignReader());`,
1650
+ ...(targetOwner !== undefined ? [
1651
+ ` final application = await ${opener}(_nmsReception, reference.ref);`,
1652
+ foreign.targetIsContract === true
1653
+ ? ` final target = await ${resolver}(application, reference);`
1654
+ : ` final target = await application.${member(plural(concreteClassName(foreign.targetAggregateId)))}.find(NmsInternalNomosRefs.create<${concreteClassName(foreign.targetAggregateId)}>(workspace: reference.workspace, type: ${JSON.stringify(foreign.targetAggregateId)}, id: reference.id));`,
1655
+ ] : [
1656
+ ` final target = await NmsInternalForeignRefs.resolve(reference, _client.session.foreignReader());`,
1657
+ ]),
1838
1658
  ` if (target == null) return null;`,
1839
1659
  ` return NmsInternalRecordOrigins.remember(target, workspace: NmsInternalNomosRefs.workspace(reference.ref), type: ${JSON.stringify(
1840
1660
  foreign.targetAggregateId
@@ -1842,13 +1662,6 @@ export function generateDartApplication(
1842
1662
  ` }`,
1843
1663
  ``,
1844
1664
  ]);
1845
- const targetOwner =
1846
- packageDomains[foreign.targetAggregateId] ??
1847
- (foreign.targetDomain === undefined
1848
- ? undefined
1849
- : Object.values(packageDomains).find(
1850
- (candidate) => candidate.domain === foreign.targetDomain
1851
- ));
1852
1665
  if (targetOwner !== undefined && targetOwner.domain !== domain) {
1853
1666
  const targetApplication = dartApplicationClassName(targetOwner.domain);
1854
1667
  const opener = `nomosInternalOpen${targetApplication}`;
@@ -1861,9 +1674,8 @@ export function generateDartApplication(
1861
1674
  ` final reference = ${fieldValue};`,
1862
1675
  ` if (reference == null) return Future<${targetApplication}?>.value(null);`,
1863
1676
  ` return ${opener}(`,
1864
- ` _client.bridge,`,
1677
+ ` _nmsReception,`,
1865
1678
  ` reference.ref,`,
1866
- ` _client.actor,`,
1867
1679
  ` );`,
1868
1680
  ` }`,
1869
1681
  ``,
@@ -1872,8 +1684,21 @@ export function generateDartApplication(
1872
1684
  }
1873
1685
  }
1874
1686
 
1687
+ for (const ordered of mod.orderedReads ?? []) {
1688
+ const model = readModelClassName(ordered.of);
1689
+ const result = ordered.limit === 1 ? `${model}?` : `List<${model}>`;
1690
+ const method = member(ordered.id);
1691
+ const watch = `watch${cap(camel(ordered.id))}`;
1692
+ addCollectionMember(ordered.of, method, [
1693
+ ` Future<${result}> ${method}() => _client.${method}();`,
1694
+ ` Stream<${result}> ${watch}() => _client.${watch}();`,
1695
+ ``,
1696
+ ]);
1697
+ }
1698
+
1875
1699
  for (const count of (mod.counts ?? []).map((raw) => finishCount(raw))) {
1876
1700
  const method = member(count.id);
1701
+ const watch = `watch${cap(camel(count.id))}`;
1877
1702
  const groupType =
1878
1703
  count.by == null
1879
1704
  ? ""
@@ -1884,6 +1709,17 @@ export function generateDartApplication(
1884
1709
  : ` Future<int> ${method}(${groupType} ${keyParam(
1885
1710
  count.by
1886
1711
  )}) => _client.${method}(${keyParam(count.by)});`,
1712
+ count.by == null
1713
+ ? ` Stream<int> ${watch}() => _client.${watch}();`
1714
+ : ` Stream<int> ${watch}(${groupType} ${keyParam(count.by)}) => _client.${watch}(${keyParam(count.by)});`,
1715
+ ]);
1716
+ }
1717
+ for (const membership of (mod.exists_ ?? []).map(finishExists)) {
1718
+ const method = member(membership.id);
1719
+ const parameter = membership.by == null ? ""
1720
+ : `${keyType(aggregates.get(membership.of), membership.by, enumDartTypes)} ${keyParam(membership.by)}`;
1721
+ addCollectionMember(membership.of, method, [
1722
+ ` Future<bool> ${method}(${parameter}) => _client.${method}(${membership.by == null ? "" : keyParam(membership.by)});`,
1887
1723
  ]);
1888
1724
  }
1889
1725
  for (const sum of (mod.sums ?? []).map((raw) => finishSum(raw))) {
@@ -1901,6 +1737,15 @@ export function generateDartApplication(
1901
1737
  ]);
1902
1738
  }
1903
1739
 
1740
+ for (const extremum of [...(mod.mins ?? []), ...(mod.maxes ?? [])].map(finishExtremum)) {
1741
+ const method = member(extremum.id);
1742
+ const parameter = extremum.by == null ? ""
1743
+ : `${keyType(aggregates.get(extremum.of), extremum.by, enumDartTypes)} ${keyParam(extremum.by)}`;
1744
+ addCollectionMember(extremum.of, method, [
1745
+ ` Future<int?> ${method}(${parameter}) => _client.${method}(${extremum.by == null ? "" : keyParam(extremum.by)});`,
1746
+ ]);
1747
+ }
1748
+
1904
1749
  for (const aggregate of mod.aggregates) {
1905
1750
  if (
1906
1751
  (aggregate as { businessBirthInternal?: unknown })
@@ -1920,7 +1765,7 @@ export function generateDartApplication(
1920
1765
  ` /// Use this at UI boundaries such as route parameters that intentionally retain only`,
1921
1766
  ` /// the local aggregate id. Use [fromAddress] when the workspace is part of the value.`,
1922
1767
  ` ${aggregateRefType} ref(String id) {`,
1923
- ` final workspace = _client.session?.workspace ?? '';`,
1768
+ ` final workspace = _client.session.workspace;`,
1924
1769
  ` if (workspace.isEmpty) {`,
1925
1770
  ` throw StateError('Cannot qualify a ${concrete} id before its application workspace is open.');`,
1926
1771
  ` }`,
@@ -1955,10 +1800,10 @@ export function generateDartApplication(
1955
1800
  aggregate.id
1956
1801
  )}, '');`,
1957
1802
  ` final targetWorkspace = NmsInternalNomosRefs.workspace(reference);`,
1958
- ` final currentWorkspace = _client.session?.workspace ?? '';`,
1803
+ ` final currentWorkspace = _client.session.workspace;`,
1959
1804
  ` if (currentWorkspace.isNotEmpty && targetWorkspace != currentWorkspace) {`,
1960
1805
  ` final application = await nomosInternalOpen${application}(`,
1961
- ` _client.bridge, reference, _client.actor,`,
1806
+ ` _nmsReception, reference,`,
1962
1807
  ` );`,
1963
1808
  ` return application.${member(plural(concrete))}.find(reference);`,
1964
1809
  ` }`,
@@ -1975,10 +1820,10 @@ export function generateDartApplication(
1975
1820
  aggregate.id
1976
1821
  )}, '');`,
1977
1822
  ` final targetWorkspace = NmsInternalNomosRefs.workspace(reference);`,
1978
- ` final currentWorkspace = _client.session?.workspace ?? '';`,
1823
+ ` final currentWorkspace = _client.session.workspace;`,
1979
1824
  ` if (currentWorkspace.isNotEmpty && targetWorkspace != currentWorkspace) {`,
1980
1825
  ` return Stream.fromFuture(nomosInternalOpen${application}(`,
1981
- ` _client.bridge, reference, _client.actor,`,
1826
+ ` _nmsReception, reference,`,
1982
1827
  ` )).asyncExpand(`,
1983
1828
  ` (application) => application.${member(
1984
1829
  plural(concrete)
@@ -2021,7 +1866,7 @@ export function generateDartApplication(
2021
1866
  const property = member(plural(concrete));
2022
1867
  claimApplicationMember(property, `aggregate collection '${aggregateId}'`);
2023
1868
  appLines.push(` final ${collection} ${property};`);
2024
- initializers.push(`${property} = ${collection}._(client)`);
1869
+ initializers.push(`${property} = ${collection}._(client, reception)`);
2025
1870
  collections.push(
2026
1871
  `/// The canonical generated surface for ${concrete} records and navigation.`,
2027
1872
  `///`,
@@ -2030,7 +1875,8 @@ export function generateDartApplication(
2030
1875
  `/// a repository or parallel application state.`,
2031
1876
  `final class ${collection} {`,
2032
1877
  ` final ${client} _client;`,
2033
- ` ${collection}._(this._client);`,
1878
+ ` final NmsReceptionSession _nmsReception;`,
1879
+ ` ${collection}._(this._client, this._nmsReception);`,
2034
1880
  ``,
2035
1881
  ...members,
2036
1882
  `}`,
@@ -2051,6 +1897,7 @@ export function generateDartApplication(
2051
1897
  : "nomos_client.dart";
2052
1898
  const applicationInitializers = [
2053
1899
  "_client = client",
1900
+ "_nmsReception = reception",
2054
1901
  ...(tenantRoot ? ["currentUser = currentUser"] : []),
2055
1902
  `activity = ${activity}._(client)`,
2056
1903
  ...(resolverBindings.length > 0 ? [`conflicts = client.conflicts`] : []),
@@ -2059,48 +1906,34 @@ export function generateDartApplication(
2059
1906
  return [
2060
1907
  `// AUTO-GENERATED by nomos-compile — the tenant application surface for "${domain}".`,
2061
1908
  `// Business facts in, business records out. Runtime lifecycle is deliberately absent.`,
2062
- ...(sharingPolicies.length > 0
2063
- ? [`import 'dart:async' show StreamSubscription, unawaited;`]
2064
- : []),
2065
- `import '${runtimeImport}' show NmsInternalForeignRefs, NmsInternalNomosRefs, NmsInternalRecordOrigins, NomosBridge, NomosOfferOutcome, NomosOperationReceipt, NomosRef, NomosSession${
2066
- usesWorkspaceName ? ", deriveWorkspaceName" : ""
2067
- }${
1909
+ ...((mod.workspaceInvariants ?? []).some(rule => rule.refusal) ? [
1910
+ `export 'package:nomos_types/nomos_types.dart' show AdmissionDecision, Admitted, DomainRefused, FrameworkRefused, UnsupportedRefusalContract, NomosDomainRefusalEvidence, KernelRefusalCode;`,
1911
+ ] : []),
1912
+ ...(opts.workspaceAccessReadImportUri === undefined ? [] : [
1913
+ `import '${opts.workspaceAccessReadImportUri}' show nomosInternalReadReceivedAccess;`,
1914
+ ]),
1915
+ `import '${runtimeImport}' show NmsInternalForeignRefs, NmsInternalNomosRefs, NmsInternalRecordOrigins, NmsUsdaResult, NomosOfferOutcome, NomosOperationReceipt, NomosRef${(mod.workspaceInvariants ?? []).some(rule => rule.refusal) ? ", AdmissionDecision, nmsAdmissionDecision" : ""}${sharingPolicies.length > 0 ? ", Invitation, Recipient, User" : ""}${
1916
+ tenantRoot ? ", NmsInternalUsers" : ""
1917
+ };`,
1918
+ `import 'package:nomos_client/src/reception/reception_session.dart' show NmsReceptionSession${
2068
1919
  sharingPolicies.length > 0
2069
- ? ", Invitation, Recipient, SyncPhase, User"
1920
+ ? ", NmsReceptionInvitationPolicy, NmsReceptionInvitationMatch"
2070
1921
  : ""
2071
- }${
2072
- tenantRoot ? ", NmsInternalUsers, nmsInternalReceivingGroupNameOf" : ""
2073
1922
  };`,
2074
- ...(opts.flutterHost === true || sharingPolicies.length > 0
1923
+ ...(usesWorkspaceName
1924
+ ? [
1925
+ `import 'package:nomos_client/src/workspace_open_progress.dart' show ApplicationWorkspaceOpenProgress;`,
1926
+ ]
1927
+ : []),
1928
+ ...(opts.flutterHost === true ||
1929
+ sharingPolicies.length > 0 ||
1930
+ usesWorkspaceName
2075
1931
  ? [
2076
- ...(tenantRoot ? [`import 'package:flutter/widgets.dart';`] : []),
2077
- ...(sharingPolicies.length > 0
2078
- ? [
2079
- `import 'package:nomos_flutter/src/application_share.dart' show ApplicationShareResult;`,
2080
- ]
2081
- : []),
2082
1932
  ...(opts.flutterHost === true
2083
1933
  ? [
2084
- `import 'package:nomos_flutter/src/application_status.dart' show ${
2085
- tenantRoot ? "ApplicationSignIn, " : ""
2086
- }ApplicationStatus;`,
1934
+ `import 'package:nomos_client/src/application_status.dart' show ApplicationStatus;`,
2087
1935
  ]
2088
1936
  : []),
2089
- `import 'package:nomos_flutter/src/generated_application_host.dart' show ${
2090
- tenantRoot
2091
- ? "ApplicationModelChange, NomosApplicationStartupState, "
2092
- : ""
2093
- }${
2094
- usesWorkspaceName
2095
- ? "ApplicationWorkspaceOpenProgress, NomosApplicationObservability, "
2096
- : ""
2097
- }NmsInternalApplicationUserBinding${
2098
- opts.flutterHost === true || sharingPolicies.length > 0
2099
- ? ", NmsInternalApplicationHost"
2100
- : ""
2101
- }${
2102
- sharingPolicies.length > 0 ? ", NmsInternalInvitationPolicy" : ""
2103
- };`,
2104
1937
  ]
2105
1938
  : []),
2106
1939
  `import '${typesImport}';`,
@@ -2112,31 +1945,21 @@ export function generateDartApplication(
2112
1945
  ...[...explicitTypeImportUris].sort().map((uri) => `import '${uri}';`),
2113
1946
  `import '${mod.name}.client.dart' show ${client}${
2114
1947
  resolverBindings.length > 0 ? `, ${cap(camel(domain))}Conflicts` : ""
2115
- };`,
1948
+ }${mod.directives.filter(command => refusalContracts(mod, command.id).length > 0).map(command => `, ${refusalDecoder(command.id)}`).join("")};`,
2116
1949
  ...imports,
2117
1950
  ``,
2118
1951
  ...(tenantRoot
2119
- ? [`/// The canonical stateful entry point for this business domain.`]
1952
+ ? [`/// The canonical typed facade for this business domain.`]
2120
1953
  : [
2121
1954
  `/// A business domain handle owned by the generated package application.`,
2122
1955
  ]),
2123
1956
  `///`,
2124
- `/// Use its business actions, records, watches, status and decisions directly. Nomos owns`,
2125
- `/// persistence, synchronization, access delivery and recovery underneath this object;`,
2126
- `/// do not create a parallel repository, runtime host, session, or application-state copy.`,
1957
+ `/// Use its business actions, records, watches, status and decisions directly. Peer Office`,
1958
+ `/// owns persistence, synchronization, access delivery and recovery underneath this object.`,
2127
1959
  ...(tenantRoot
2128
1960
  ? [
2129
1961
  `///`,
2130
- `/// Canonical bootstrap:`,
2131
- "/// ```dart",
2132
- `/// return ${application}.nomosWidget(`,
2133
- `/// cloud: cloud,`,
2134
- `/// application: '${domain}',`,
2135
- `/// signIn: signIn,`,
2136
- `/// builder: (context, application) => MyBusinessUi(application: application),`,
2137
- `/// );`,
2138
- "/// ```",
2139
- `/// Pass that same [${application}] down. It is the application state.`,
1962
+ `/// Reception supplies this facade once for the Peer Office application desk.`,
2140
1963
  ]
2141
1964
  : [
2142
1965
  `///`,
@@ -2145,63 +1968,29 @@ export function generateDartApplication(
2145
1968
  ]),
2146
1969
  `final class ${application} {`,
2147
1970
  ` final ${client} _client;`,
1971
+ ` final NmsReceptionSession _nmsReception;`,
2148
1972
  ...(tenantRoot ? [` final User currentUser;`] : []),
2149
1973
  ` final ${activity} activity;`,
2150
1974
  ...appLines,
2151
- ` ${application}._(${client} client${
1975
+ ` ${application}._(${client} client, NmsReceptionSession reception${
2152
1976
  tenantRoot ? ", User currentUser" : ""
2153
1977
  }) : ${applicationInitializers.join(", ")};`,
2154
1978
  ``,
2155
- ` /// Prove, adopt or restore the law this application was generated against.`,
2156
- ` NomosModel get model => _client.model;`,
2157
1979
  ...(opts.flutterHost === true
2158
1980
  ? [
2159
1981
  ``,
2160
1982
  ` /// Current durability and convergence for this workspace in product language.`,
2161
- ` ApplicationStatus get currentStatus => NmsInternalApplicationHost.currentStatus(_client.bridge);`,
1983
+ ` ApplicationStatus get currentStatus => _nmsReception.currentStatus;`,
2162
1984
  ``,
2163
1985
  ` /// React whenever this workspace saves, receives work, goes offline or needs attention.`,
2164
- ` Stream<ApplicationStatus> watchStatus() => NmsInternalApplicationHost.watchStatus(_client.bridge);`,
1986
+ ` Stream<ApplicationStatus> watchStatus() => _nmsReception.streams.status;`,
2165
1987
  ``,
2166
1988
  ` /// Wait until accepted local work is in shared custody and this workspace has caught up.`,
2167
1989
  ` Future<void> whenCurrent({Duration timeout = const Duration(minutes: 2)}) =>`,
2168
- ` NmsInternalApplicationHost.whenCurrent(_client.bridge, timeout: timeout);`,
1990
+ ` _nmsReception.whenCurrent(timeout: timeout);`,
2169
1991
  ``,
2170
1992
  ` /// The parent operation which created this workspace during this application run, if any.`,
2171
- ` NomosOperationReceipt? get creationReceipt => NmsInternalApplicationHost.creationReceipt(_client.bridge);`,
2172
- ]
2173
- : []),
2174
- ...(opts.flutterHost === true && tenantRoot
2175
- ? [
2176
- ``,
2177
- ` /// Mount the one application at the UI boundary and pass [application] down.`,
2178
- ` ///`,
2179
- ` /// This is the only application bootstrap tenant code should own.`,
2180
- ` ///`,
2181
- ` /// The object supplied to [builder] is the application state. Keep it as the only`,
2182
- ` /// business-state dependency; do not recreate its records in providers, repositories or caches.`,
2183
- ` static Widget nomosWidget({`,
2184
- ` Key? key,`,
2185
- ` required String cloud,`,
2186
- ` required String application,`,
2187
- ` required ApplicationSignIn signIn,`,
2188
- ` required Widget Function(BuildContext context, ${application} application) builder,`,
2189
- ` Widget Function(BuildContext context)? loadingBuilder,`,
2190
- ` Widget Function(BuildContext context, Object error, VoidCallback retry)? errorBuilder,`,
2191
- ` ApplicationModelChange? onModelChange,`,
2192
- ` ValueChanged<NomosApplicationStartupState>? onStartupStateChanged,`,
2193
- ` Duration startupTimeout = const Duration(minutes: 3),`,
2194
- ` }) => NmsInternalApplicationHost.home<${application}>(`,
2195
- ` key: key, cloud: cloud, application: application, signIn: signIn,`,
2196
- ...(opts.applicationFrameworkCallsImportUri === undefined
2197
- ? []
2198
- : [` frameworkCalls: nomosInternalApplicationFrameworkCalls,`]),
2199
- ` bind: nomosInternalBind${application}, builder: builder,`,
2200
- ` loadingBuilder: loadingBuilder, errorBuilder: errorBuilder,`,
2201
- ` onModelChange: onModelChange,`,
2202
- ` onStartupStateChanged: onStartupStateChanged,`,
2203
- ` startupTimeout: startupTimeout,`,
2204
- ` );`,
1993
+ ` NomosOperationReceipt? get creationReceipt => _nmsReception.creationReceipt;`,
2205
1994
  ]
2206
1995
  : []),
2207
1996
  `}`,
@@ -2228,6 +2017,7 @@ export function generateDartApplication(
2228
2017
  ``,
2229
2018
  ...actionResultDeclarations,
2230
2019
  ...collections,
2020
+ ...foreignContractResolvers,
2231
2021
  ...conflictDeclarations,
2232
2022
  `bool _nmsReferenceTypeMatches(String actual, String expected) =>`,
2233
2023
  ` actual == expected || actual.endsWith('.\$expected');`,
@@ -2300,76 +2090,35 @@ export function generateDartApplication(
2300
2090
  : []),
2301
2091
  ]
2302
2092
  : []),
2303
- ...(opts.flutterHost === true
2093
+ `Future<${application}> nomosInternalReceive${application}(`,
2094
+ ` NmsReceptionSession reception) async {`,
2095
+ ` final application = ${application}._(`,
2096
+ ` await ${client}.bind(reception.desk, actor: reception.user.actor),`,
2097
+ ` reception${tenantRoot ? "," : ""}`,
2098
+ ...(tenantRoot
2304
2099
  ? [
2305
- `Future<${application}> nomosInternalBind${application}(`,
2306
- ` NomosSession session, NmsInternalApplicationUserBinding user) async {`,
2307
- ` final application = ${application}._(`,
2308
- ` await ${client}.bind(session, actor: user.nmsInternalActor)${
2309
- tenantRoot ? "," : ""
2310
- }`,
2311
- ...(tenantRoot
2312
- ? [
2313
- ` NmsInternalUsers.create(identityId: user.nmsInternalIdentityId, identityAddress: user.nmsInternalIdentityAddress),`,
2314
- ]
2315
- : []),
2316
- ` );`,
2100
+ ` NmsInternalUsers.create(identityId: reception.user.identityId, identityAddress: reception.user.identityAddress),`,
2317
2101
  ]
2318
- : [
2319
- `Future<${application}> nomosInternalBind${application}(NomosSession session, String? actor) async {`,
2320
- ` final application = ${application}._(await ${client}.bind(session, actor: actor));`,
2321
- ]),
2322
- ...(sharingPolicies.length > 0
2323
- ? [` await application._nmsStartWorkspaceSharing();`]
2324
2102
  : []),
2103
+ ` );`,
2325
2104
  ` return application;`,
2326
2105
  `}`,
2327
2106
  ``,
2328
- `Future<${application}> nomosInternalOpen${application}<TAggregate>(`,
2329
- ` NomosBridge bridge, NomosRef<TAggregate> reference, String? actor,`,
2330
- ` {Future<void> Function()? recoverAuthentication}) async {`,
2331
- ...(opts.flutterHost === true
2332
- ? [
2333
- ` return NmsInternalApplicationHost.nmsInternalOpenReferencedApplication<${application}>(`,
2334
- ` parent: bridge,`,
2335
- ` workspace: NmsInternalNomosRefs.workspace(reference),`,
2336
- ` open: () async {`,
2337
- ]
2338
- : []),
2339
2107
  ...(tenantRoot
2340
2108
  ? [
2341
- ` final signedIn = actor?.trim() ?? '';`,
2342
- ` if (signedIn.isEmpty) throw StateError('Nomos could not identify the signed-in application user.');`,
2343
- ` final client = await ${client}.open(`,
2344
- ` bridge, ref: reference, actor: signedIn,`,
2345
- ` recoverAuthentication: recoverAuthentication,`,
2346
- ` );`,
2347
- ` final application = ${application}._(`,
2348
- ` client,`,
2349
- ` NmsInternalUsers.create(`,
2350
- ` identityId: nmsInternalReceivingGroupNameOf(signedIn),`,
2351
- ` identityAddress: 'nomos-identity:\${Uri.encodeComponent(nmsInternalReceivingGroupNameOf(signedIn))}',`,
2352
- ` ),`,
2353
- ` );`,
2354
- ]
2355
- : [
2356
- ` final client = await ${client}.open(`,
2357
- ` bridge, ref: reference, actor: actor,`,
2358
- ` recoverAuthentication: recoverAuthentication,`,
2359
- ` );`,
2360
- ` final application = ${application}._(client);`,
2361
- ]),
2362
- ...(sharingPolicies.length > 0
2363
- ? [` await application._nmsStartWorkspaceSharing();`]
2364
- : []),
2365
- ` return application;`,
2366
- ...(opts.flutterHost === true
2367
- ? [
2368
- ` },`,
2369
- ` bridgeOf: (application) => application._client.bridge,`,
2370
- ` );`,
2109
+ `/// Receive the generated application vocabulary from an already-open Reception session.`,
2110
+ `/// This binds types only; Peer Office retains every lifecycle responsibility.`,
2111
+ `Future<${application}> receive${application}(`,
2112
+ ` NmsReceptionSession reception) =>`,
2113
+ ` nomosInternalReceive${application}(reception);`,
2114
+ ``,
2371
2115
  ]
2372
2116
  : []),
2117
+ `Future<${application}> nomosInternalOpen${application}<TAggregate>(`,
2118
+ ` NmsReceptionSession reception, NomosRef<TAggregate> reference,`,
2119
+ `) async {`,
2120
+ ` final child = await reception.follow(NmsInternalNomosRefs.workspace(reference));`,
2121
+ ` return nomosInternalReceive${application}(child);`,
2373
2122
  `}`,
2374
2123
  ``,
2375
2124
  ].join("\n");