@githolon/dsl 0.13.0 → 0.15.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.
@@ -15,8 +15,8 @@
15
15
  // final bridge = NomosBridge(transport);
16
16
  // await bridge.ready; // resolves on the runner's {event:ready}
17
17
  // await bridge.connect(cloud: 'https://nomos.captainapp.co.uk', workspace: myWs, clientId: deviceId);
18
- // final head = await bridge.dispatch(domain: 'guestbook', directiveId: 'signGuestbook',
19
- // payload: {'author': 'ada', 'message': 'hi', 'mood': 'delighted'}, domainHash: GUESTBOOK_DOMAIN_HASH);
18
+ // final app = GuestbookClient(bridge);
19
+ // final head = await app.signGuestbook(SignGuestbookPayload(author: 'ada', message: 'hi', mood: 'delighted'));
20
20
  // final rows = await bridge.query('entriesByAuthor', {'author': 'ada'});
21
21
  //
22
22
  // (Put the runner bundle at `assets/nomos/nomos-runner.{html,js}` and declare it under `flutter: assets:`.)
@@ -10,7 +10,7 @@
10
10
  /// - The hand-written kernel WIRE types (`Value`, `Field`/`WireField`, `Hlc`,
11
11
  /// `Op`, `FieldOp`, `Event`, `Schema`/`WireDriver`) — byte-compatible with
12
12
  /// serde_json. See `src/wire.dart`, `src/driver.dart`.
13
- /// - The ONE write verb `dispatch(intent)` (`src/dispatch.dart`) + the typed
13
+ /// - The ONE effectful write verb `offer(intent)` (`src/offer.dart`) + the typed
14
14
  /// reactive read engine `NomosReads` (`src/subscriptions.dart`).
15
15
  /// - The framework PRIMITIVES ONLY. The CODE-GENERATED per-domain types
16
16
  /// (aggregates + public intent payloads + enums + `watch…` read accessors) NO LONGER
@@ -18,14 +18,14 @@
18
18
  /// `co2_nomos_domains` (`ts_packages/co2-nomos-domains/dart/`), emitted there by
19
19
  /// `ts_packages/co2-nomos-domains/src/emit_dart.ts`. Tenant domains squatting in
20
20
  /// the framework package was the wrong topology; this barrel now exports ONLY the
21
- /// hand-written framework wire/dispatch/read/provider primitives. App code that
21
+ /// hand-written framework wire/offer/read/provider primitives. App code that
22
22
  /// wants the typed domain surface imports `package:co2_nomos_domains/co2_nomos_domains.dart`,
23
23
  /// which re-exports this framework barrel PLUS every generated domain.
24
24
  library;
25
25
 
26
26
  export 'src/wire.dart';
27
27
  export 'src/driver.dart';
28
- export 'src/dispatch.dart';
28
+ export 'src/offer.dart';
29
29
  export 'src/subscriptions.dart';
30
30
  export 'src/schema_validation.dart';
31
31
  // THE WEBVIEW BRIDGE (app-binding boundary) — the async Dart runtime that drives the REAL githolon running
@@ -33,7 +33,7 @@ export 'src/schema_validation.dart';
33
33
  export 'src/webview_bridge.dart';
34
34
  // The PROVIDER boundary (server-side capability-provider SDK runtime: TaskOutcome /
35
35
  // TaskSuccess / TaskFailure / TaskResult / TaskProvider / HostClock). The symmetric twin
36
- // of `dispatch.dart`; the generated per-task provider classes build on it.
36
+ // of `offer.dart`; the generated per-task provider classes build on it.
37
37
  export 'src/provider.dart';
38
38
 
39
39
  // ── NO generated domains here ──────────────────────────────────────────────
@@ -5,19 +5,19 @@
5
5
  // wasm = determinism. No native, no wasmtime, no 2nd artifact, no domain-JS on bare V8.
6
6
  // If a file isn't this / hosting this / authoring for this / proving this — it's gone.
7
7
 
8
- /// The ONE write verb: `dispatch(intent)`.
8
+ /// The ONE effectful write verb: `offer(intent)`.
9
9
  ///
10
- /// END-STATE (the "dispatch(intent) purge", Jack 2026-06-01): app code's only
11
- /// write verb is `dispatch(intent)`. The frontend constructs ONLY a typed
10
+ /// END-STATE (the "offer(intent) purge", Jack 2026-06-18): app code's only
11
+ /// effectful write verb is `offer(intent)`. The frontend constructs ONLY a typed
12
12
  /// generated intent DTO (a [NomosIntent]) — it never hand-types an engine rule
13
- /// id, never builds an `Event`, never holds an `Hlc`. `dispatch` ships the
13
+ /// id, never builds an `Event`, never holds an `Hlc`. `offer` ships the
14
14
  /// intent payload as DATA to the kernel's FRB `author(domain, directiveId, payloadJson,
15
15
  /// actor)`; the sealed engine runs the REAL `.plan()` and is the SOLE lowering
16
16
  /// authority (HLC + intent id are kernel-allocated host-side).
17
17
  ///
18
18
  /// This file is HAND-WRITTEN and domain-AGNOSTIC (declared ONCE, here): the
19
19
  /// generated per-domain intent classes `implements NomosIntent`, so a single
20
- /// generic `dispatch` covers every public intent of every domain — replacing the
20
+ /// generic `offer` covers every public intent of every domain — replacing the
21
21
  /// ~63-method write façade.
22
22
  library;
23
23
 
@@ -39,7 +39,7 @@ abstract interface class NomosIntent {
39
39
  }
40
40
 
41
41
  /// The kernel write seam: the FRB `NomosClient.author` signature, as a function
42
- /// type. `dispatch` takes this (rather than importing the FRB client) so the
42
+ /// type. `offer` takes this (rather than importing the FRB client) so the
43
43
  /// generated `nomos_dsl` package stays free of a `flutter_rust_bridge` dependency
44
44
  /// — the app threads `client.author` in. Returns the new HEAD commit oid (hex).
45
45
  typedef Authorer = String Function({
@@ -54,7 +54,7 @@ typedef Authorer = String Function({
54
54
  /// intent object — nothing is hand-typed. Builds NO `Event` and NO `Hlc`: the
55
55
  /// engine lowers. [actor] is the authenticated actor the caller threads from auth.
56
56
  /// Returns the new HEAD commit oid (hex).
57
- String dispatch(NomosIntent intent,
57
+ String offer(NomosIntent intent,
58
58
  {required Authorer author, required String actor}) =>
59
59
  author(
60
60
  domain: intent.domain,
@@ -7,22 +7,22 @@
7
7
 
8
8
  /// The PROVIDER boundary: the typed server-side capability-provider SDK runtime.
9
9
  ///
10
- /// This is the SYMMETRIC TWIN of `dispatch.dart` (the peer write boundary). Where
11
- /// the peer authors an Order (`createTranscribeVoiceNote(...)` -> `dispatch`), a
10
+ /// This is the SYMMETRIC TWIN of `offer.dart` (the peer write boundary). Where
11
+ /// the peer authors an Obligation (`createTranscribeVoiceNote(...)` -> `offer`), a
12
12
  /// PROVIDER (Whisper, a renderer, a multi-target PR transporter) is the
13
- /// other end of the framework `impureCapability` Order→Receipt pair: it WATCHES `requested`
13
+ /// other end of the framework `impureCapability` Obligation→Receipt pair: it WATCHES `requested`
14
14
  /// task rows, performs the impure side-effect OUTSIDE the fold, and authors the RECEIPT
15
15
  /// (`complete…`/`fail…`/`block…`/`deadLetter…`) back through the SAME write path. The receipt is an ordinary
16
16
  /// intent — the provider is a Nomos author, NOT a bypass (ONE-WRITE-PATH).
17
- /// Order and Receipt are intent roles, not provider-owned jobs or privileged server
17
+ /// Obligation and Receipt are intent roles, not provider-owned jobs or privileged server
18
18
  /// mutation channels.
19
19
  ///
20
20
  /// PRINCIPLE (Jack 2026-06-04): code is ~free; INTEGRATION POINTS are expensive +
21
21
  /// fuckup-guaranteed. So the generated provider SDK is fully TYPED to the boundary —
22
- /// the dev writes a typed `handler(Order) -> Result | Failure | Blocked | DeadLetter`; the generated
23
- /// dispatcher DECODES the incoming Order JSON into the typed Order and ENCODES the typed
22
+ /// the dev writes a typed `handler(Obligation) -> Result | Failure | Blocked | DeadLetter`; the generated
23
+ /// dispatcher DECODES the incoming Obligation JSON into the typed Obligation and ENCODES the typed
24
24
  /// outcome into the ordinary Receipt intent. NO dynamic / `Map<String, dynamic>` / raw-JSON leaks
25
- /// into the dev-facing API; the types stop ONLY at the actual JSON serde (`handleOrder`).
25
+ /// into the dev-facing API; the types stop ONLY at the actual JSON serde (`handleObligation`).
26
26
  ///
27
27
  /// This file is HAND-WRITTEN and domain-AGNOSTIC (declared ONCE, here): the generated
28
28
  /// per-task provider classes build on these interfaces, so the round-trip mechanism is
@@ -31,9 +31,9 @@ library;
31
31
 
32
32
  import 'dart:convert';
33
33
 
34
- import 'dispatch.dart' show NomosIntent;
34
+ import 'offer.dart' show NomosIntent;
35
35
 
36
- /// The typed OUTCOME a provider handler returns for one Order: success, failure, blocked,
36
+ /// The typed OUTCOME a provider handler returns for one Obligation: success, failure, blocked,
37
37
  /// or dead-lettered.
38
38
  /// SEALED so a generated dispatcher's `switch` is EXHAUSTIVE — a new outcome variant is
39
39
  /// a compile error at every dispatcher, never a silent fall-through. The mirror of the
@@ -44,7 +44,7 @@ sealed class TaskOutcome<R> {
44
44
 
45
45
  /// The SUCCESS outcome: the typed [result] the handler produced. The generated
46
46
  /// dispatcher maps this → the `complete…` Receipt directive (status:completed +
47
- /// resultRef + closesOrder).
47
+ /// resultRef + closesObligation).
48
48
  final class TaskSuccess<R> extends TaskOutcome<R> {
49
49
  /// The typed result the handler produced (e.g. a transcription's `resultRef`).
50
50
  final R result;
@@ -53,7 +53,7 @@ final class TaskSuccess<R> extends TaskOutcome<R> {
53
53
 
54
54
  /// The FAILURE outcome: the [failureReason] the handler recorded. The generated
55
55
  /// dispatcher maps this → the `fail…` Receipt directive (status:failed + failureReason +
56
- /// closesOrder). A recorded failure is the terminal state — NOT a retry storm
56
+ /// closesObligation). A recorded failure is the terminal state — NOT a retry storm
57
57
  /// (conformance X1's "declined is recorded" discipline at the task scale).
58
58
  final class TaskFailure<R> extends TaskOutcome<R> {
59
59
  /// Why the side-effect failed (recorded onto the task, never re-thrown into the fold).
@@ -63,13 +63,13 @@ final class TaskFailure<R> extends TaskOutcome<R> {
63
63
 
64
64
  /// The BLOCKED outcome: the provider cannot proceed until an external condition changes.
65
65
  /// The generated dispatcher maps this -> the `block...` Receipt directive
66
- /// (status:blocked + blockedReason + nextAction + closesOrder). This is terminal for this
67
- /// order; recovery is a fresh explicit Order after the next action is satisfied.
66
+ /// (status:blocked + blockedReason + nextAction + closesObligation). This is terminal for this
67
+ /// obligation; recovery is a fresh explicit Obligation after the next action is satisfied.
68
68
  final class TaskBlocked<R> extends TaskOutcome<R> {
69
69
  /// Why the provider cannot proceed.
70
70
  final String blockedReason;
71
71
 
72
- /// What the host/human must do before a fresh order can proceed.
72
+ /// What the host/human must do before a fresh obligation can proceed.
73
73
  final String nextAction;
74
74
 
75
75
  const TaskBlocked({
@@ -78,11 +78,11 @@ final class TaskBlocked<R> extends TaskOutcome<R> {
78
78
  });
79
79
  }
80
80
 
81
- /// The DEAD-LETTER outcome: stop retrying this order and park it in the DLQ. The generated
81
+ /// The DEAD-LETTER outcome: stop retrying this obligation and park it in the DLQ. The generated
82
82
  /// dispatcher maps this -> the `deadLetter...` Receipt directive
83
- /// (status:deadLettered + deadLetterReason + closesOrder).
83
+ /// (status:deadLettered + deadLetterReason + closesObligation).
84
84
  final class TaskDeadLetter<R> extends TaskOutcome<R> {
85
- /// Why this order was moved to the DLQ.
85
+ /// Why this obligation was moved to the DLQ.
86
86
  final String deadLetterReason;
87
87
  const TaskDeadLetter(this.deadLetterReason);
88
88
  }
@@ -106,34 +106,34 @@ abstract interface class TaskResult {
106
106
  typedef HostClock = int Function();
107
107
 
108
108
  /// The minimal contract a generated per-task provider exposes. Generic in the typed
109
- /// Order/Result; the generated subtype binds them. `handleOrder` is the ONE seam a host
109
+ /// Obligation/Result; the generated subtype binds them. `handleObligation` is the ONE seam a host
110
110
  /// loop calls per `requested` row.
111
111
  abstract interface class TaskProvider<O, R> {
112
112
  /// The framework `impureCapability` ids this provider is bound to (provenance — the host
113
113
  /// can assert it is draining the right capability). Carried as DATA, never hand-typed.
114
- String get orderDirectiveId;
114
+ String get obligationDirectiveId;
115
115
  String get completeDirectiveId;
116
116
  String get failDirectiveId;
117
117
  String get blockDirectiveId;
118
118
  String get deadLetterDirectiveId;
119
119
 
120
- /// DECODE an incoming Order intent's payload JSON into the typed [O], run the
120
+ /// DECODE an incoming Obligation intent's payload JSON into the typed [O], run the
121
121
  /// registered typed handler, and ENCODE the outcome into the ordinary Receipt intent — a
122
- /// [NomosIntent] ready for the ONE write path (`dispatch`). `now` stamps the
122
+ /// [NomosIntent] ready for the ONE write path (`offer`). `now` stamps the
123
123
  /// terminal time. Decoding raw JSON happens HERE and only here; the handler the dev
124
124
  /// writes sees ONLY the typed [O] and returns ONLY a typed [TaskOutcome].
125
- NomosIntent handleOrder(String orderPayloadJson, {required HostClock now});
125
+ NomosIntent handleObligation(String obligationPayloadJson, {required HostClock now});
126
126
 
127
- /// Convenience: decode an Order payload from an already-parsed map (the host may have
128
- /// the row's `data` map in hand from a read). Same path as [handleOrder].
129
- NomosIntent handleOrderMap(
130
- Map<String, Object?> orderPayload, {
127
+ /// Convenience: decode an Obligation payload from an already-parsed map (the host may have
128
+ /// the row's `data` map in hand from a read). Same path as [handleObligation].
129
+ NomosIntent handleObligationMap(
130
+ Map<String, Object?> obligationPayload, {
131
131
  required HostClock now,
132
132
  });
133
133
  }
134
134
 
135
- /// Decode an Order payload JSON string to a map for a generated `…Order.fromJson`.
136
- /// Shared so every generated provider decodes Orders identically (the symmetry of the
135
+ /// Decode an Obligation payload JSON string to a map for a generated `…Obligation.fromJson`.
136
+ /// Shared so every generated provider decodes Obligations identically (the symmetry of the
137
137
  /// client's `jsonEncode(toPayloadJson())`).
138
- Map<String, Object?> decodeOrderPayload(String orderPayloadJson) =>
139
- (jsonDecode(orderPayloadJson) as Map<String, Object?>);
138
+ Map<String, Object?> decodeObligationPayload(String obligationPayloadJson) =>
139
+ (jsonDecode(obligationPayloadJson) as Map<String, Object?>);
@@ -7,8 +7,8 @@
7
7
 
8
8
  /// The READ half of the client boundary: typed, reactive subscriptions.
9
9
  ///
10
- /// END-STATE (the "dispatch(intent) purge", Jack 2026-06-01): the app's ONLY
11
- /// Nomos surface is `dispatch(intent)` (write — see `dispatch.dart`) + TYPED
10
+ /// END-STATE (the "offer(intent) purge", Jack 2026-06-18): the app's ONLY
11
+ /// Nomos surface is `offer(intent)` (write — see `offer.dart`) + TYPED
12
12
  /// PUB/SUB SUBSCRIPTIONS (read — here + the generated per-domain accessors). The
13
13
  /// app reads ONLY through generated typed accessors (`watchSites()`,
14
14
  /// `watchSite(id)`, indexed-field queries → typed results); it never hand-writes a
@@ -75,7 +75,7 @@ typedef Summer = int Function(String sumId, String groupKey);
75
75
  /// A "projection changed" tick: fires (any value) whenever a write may have
76
76
  /// advanced the projection, so the subscription re-runs its indexed read. The
77
77
  /// `query()`/`query_by_id()` closures are SYNCHRONOUS point-in-time reads; this tick is what
78
- /// makes a typed accessor REACTIVE. The app threads its existing post-`dispatch`
78
+ /// makes a typed accessor REACTIVE. The app threads its existing post-`offer`
79
79
  /// invalidation signal in here (today the runtime's ~750ms projection poll / the
80
80
  /// write-completion broadcast). A read with no live tick is a one-shot current read.
81
81
  typedef ReadTick = Stream<void>;
@@ -8,7 +8,7 @@
8
8
  /// stable message protocol, so the generated typed Dart client drives the real kernel — never a
9
9
  /// `MemoryPersistence` pretending to be a GitHolon.
10
10
  ///
11
- /// A WebView round-trip is ASYNC, so the bridge is async (unlike the sync FRB `Authorer` in `dispatch.dart`).
11
+ /// A WebView round-trip is ASYNC, so the bridge is async (unlike the sync FRB `Authorer` in `offer.dart`).
12
12
  /// The generated per-domain Dart client wraps a [NomosBridge]; the bridge owns request/reply correlation +
13
13
  /// reactive `watch` streams. The platform TRANSPORT ([BridgeTransport]) is injected — `dart:js_util` on web,
14
14
  /// a WebView JS-channel on mobile — so this protocol logic is pure Dart + fully unit-testable.
@@ -41,6 +41,16 @@ class NomosBridge {
41
41
  final BridgeTransport _transport;
42
42
  final Map<int, Completer<Object?>> _pending = {};
43
43
  final Map<String, StreamController<List<dynamic>>> _watches = {};
44
+ final StreamController<Map<String, Object?>> _syncEvents =
45
+ StreamController<Map<String, Object?>>.broadcast();
46
+ final StreamController<Map<String, Object?>> _signalEvents =
47
+ StreamController<Map<String, Object?>>.broadcast();
48
+ final StreamController<Map<String, Object?>> _flameEvents =
49
+ StreamController<Map<String, Object?>>.broadcast();
50
+ final StreamController<Map<String, Object?>> _spanEvents =
51
+ StreamController<Map<String, Object?>>.broadcast();
52
+ final List<Map<String, Object?>> _spanBuffer =
53
+ []; // recent span events — so BOOT spans (emitted during connect, before the UI subscribes) survive
44
54
  final Completer<void> _ready = Completer<void>();
45
55
  int _seq = 0;
46
56
  late final StreamSubscription<Map<String, Object?>> _sub;
@@ -53,7 +63,8 @@ class NomosBridge {
53
63
  Future<void> get ready => _ready.future;
54
64
 
55
65
  void _onMessage(Map<String, Object?> m) {
56
- if (m['v'] != kWebviewBridgeVersion) return; // a foreign-version message is ignored (forward-compatible)
66
+ if (m['v'] != kWebviewBridgeVersion)
67
+ return; // a foreign-version message is ignored (forward-compatible)
57
68
  final event = m['event'];
58
69
  if (event == 'ready') {
59
70
  if (!_ready.isCompleted) _ready.complete();
@@ -61,7 +72,37 @@ class NomosBridge {
61
72
  }
62
73
  if (event == 'watch') {
63
74
  final ctrl = _watches[m['subId']];
64
- if (ctrl != null && !ctrl.isClosed) ctrl.add((m['rows'] as List?) ?? const []);
75
+ if (ctrl != null && !ctrl.isClosed) {
76
+ if (m['ok'] == false) {
77
+ ctrl.addError(NomosBridgeError(
78
+ (m['error'] ?? 'the watch read failed').toString()));
79
+ } else {
80
+ ctrl.add((m['rows'] as List?) ?? const []);
81
+ }
82
+ }
83
+ return;
84
+ }
85
+ if (event == 'sync' || event == 'link') {
86
+ // autoSync telemetry: each round { event:'sync', reason, result } and socket state { event:'link', status }.
87
+ if (!_syncEvents.isClosed) _syncEvents.add(m);
88
+ return;
89
+ }
90
+ if (event == 'trace') {
91
+ // the realtime cloud flamepath: { event:'trace', trace:{at, oid, edge, clients} } — one per admission.
92
+ if (!_flameEvents.isClosed) _flameEvents.add(m);
93
+ return;
94
+ }
95
+ if (event == 'signal') {
96
+ // signal holon projection: ephemeral coordination such as peer frontiers / lag.
97
+ if (!_signalEvents.isClosed) _signalEvents.add(m);
98
+ return;
99
+ }
100
+ if (event == 'span') {
101
+ // LIVE per-layer span: { event:'span', span:{ phase:'begin'|'end', id, track, name, kind, t0|t1 } }.
102
+ _spanBuffer.add(m);
103
+ if (_spanBuffer.length > 400)
104
+ _spanBuffer.removeRange(0, _spanBuffer.length - 400);
105
+ if (!_spanEvents.isClosed) _spanEvents.add(m);
65
106
  return;
66
107
  }
67
108
  final id = m['id'];
@@ -71,7 +112,8 @@ class NomosBridge {
71
112
  if (m['ok'] == true) {
72
113
  completer.complete(m['result']);
73
114
  } else {
74
- completer.completeError(NomosBridgeError((m['error'] ?? 'the githolon refused the request').toString()));
115
+ completer.completeError(NomosBridgeError(
116
+ (m['error'] ?? 'the githolon refused the request').toString()));
75
117
  }
76
118
  }
77
119
 
@@ -81,65 +123,147 @@ class NomosBridge {
81
123
  final id = ++_seq;
82
124
  final completer = Completer<Object?>();
83
125
  _pending[id] = completer;
84
- _transport.send({'v': kWebviewBridgeVersion, 'id': id, 'op': op, 'args': args});
126
+ _transport
127
+ .send({'v': kWebviewBridgeVersion, 'id': id, 'op': op, 'args': args});
85
128
  return completer.future;
86
129
  }
87
130
 
88
- Map<String, Object?> _asMap(Object? v) => (v as Map?)?.cast<String, Object?>() ?? const {};
131
+ Map<String, Object?> _asMap(Object? v) =>
132
+ (v as Map?)?.cast<String, Object?>() ?? const {};
89
133
  List<Map<String, dynamic>> _asRows(Object? v) =>
90
- ((_asMap(v)['rows'] as List?) ?? const []).map((e) => (e as Map).cast<String, dynamic>()).toList();
134
+ ((_asMap(v)['rows'] as List?) ?? const [])
135
+ .map((e) => (e as Map).cast<String, dynamic>())
136
+ .toList();
91
137
 
92
138
  // ── the runtime-aware surface (the boundary the generated Dart client wraps) ──
93
139
 
94
140
  /// Open the user/estate workspace: pull its ledger, boot the local holon under the installed law.
95
- Future<void> connect({required String cloud, required String workspace, String? clientId, String? authToken, String? restoreFrom}) async {
96
- await _call('connect', {'cloud': cloud, 'workspace': workspace, if (clientId != null) 'clientId': clientId, if (authToken != null) 'authToken': authToken, if (restoreFrom != null) 'restoreFrom': restoreFrom});
97
- }
98
-
99
- /// LOCAL-FIRST write: author `directiveId` under `domainHash`. Returns the new local head; durable on [sync].
100
- Future<String> dispatch({required String domain, required String directiveId, required Map<String, Object?> payload, required String domainHash}) async {
101
- final r = _asMap(await _call('dispatch', {'domain': domain, 'directiveId': directiveId, 'payload': payload, 'domainHash': domainHash}));
102
- return r['head'].toString();
141
+ Future<void> connect(
142
+ {required String cloud,
143
+ required String workspace,
144
+ String? clientId,
145
+ String? authToken,
146
+ String? restoreFrom}) async {
147
+ await _call('connect', {
148
+ 'cloud': cloud,
149
+ 'workspace': workspace,
150
+ if (clientId != null) 'clientId': clientId,
151
+ if (authToken != null) 'authToken': authToken,
152
+ if (restoreFrom != null) 'restoreFrom': restoreFrom
153
+ });
103
154
  }
104
155
 
105
- /// §5 cross-custody delivery: a `recordShare` carrying a pre-signed §3 quote into a home holon.
106
- Future<String> deliverShare({required Map<String, Object?> quote, required String domainHash}) async {
107
- final r = _asMap(await _call('deliverShare', {'quote': quote, 'domainHash': domainHash}));
156
+ /// LOCAL-FIRST offer: carry opaque intent bytes into the GitHolon. Returns the new local head; durable on [sync].
157
+ Future<String> offer({required String intentBytes}) async {
158
+ final r = _asMap(await _call('offer', {'intentBytes': intentBytes}));
108
159
  return r['head'].toString();
109
160
  }
110
161
 
111
162
  /// A declared query's rows from the local projection.
112
- Future<List<Map<String, dynamic>>> query(String queryId, [Map<String, Object?> params = const {}]) async =>
163
+ Future<List<Map<String, dynamic>>> query(String queryId,
164
+ [Map<String, Object?> params = const {}]) async =>
113
165
  _asRows(await _call('query', {'queryId': queryId, 'params': params}));
114
166
 
115
167
  /// A single aggregate by id (the by-id read).
116
- Future<List<Map<String, dynamic>>> queryById(String id) async => _asRows(await _call('queryById', {'id': id}));
168
+ Future<List<Map<String, dynamic>>> queryById(String id) async =>
169
+ _asRows(await _call('queryById', {'id': id}));
117
170
 
118
171
  /// A maintained O(1) count / sum.
119
- Future<int> count(String countId, [String group = '']) async => ((_asMap(await _call('count', {'countId': countId, 'group': group}))['count']) as num).toInt();
120
- Future<int> sum(String sumId, [String group = '']) async => ((_asMap(await _call('sum', {'sumId': sumId, 'group': group}))['sum']) as num).toInt();
172
+ Future<int> count(String countId, [String group = '']) async =>
173
+ ((_asMap(await _call('count', {'countId': countId, 'group': group}))[
174
+ 'count']) as num)
175
+ .toInt();
176
+ Future<int> sum(String sumId, [String group = '']) async =>
177
+ ((_asMap(await _call('sum', {'sumId': sumId, 'group': group}))['sum'])
178
+ as num)
179
+ .toInt();
121
180
 
122
181
  /// Push local writes → the session branch → cloud admission, and pull canonical main back.
123
- Future<Map<String, Object?>> sync({bool admit = true}) async => _asMap(await _call('sync', {'admit': admit}));
182
+ Future<Map<String, Object?>> sync({bool admit = true}) async =>
183
+ _asMap(await _call('sync', {'admit': admit}));
184
+
185
+ /// PERSIST: a base64 snapshot of the whole local holon (the bare nomos.git incl. un-synced writes + the
186
+ /// DLQ). Store it on disk and pass it back as `connect(restoreFrom:)` next launch — the app then boots from
187
+ /// LOCAL CUSTODY (no network clone), instant at any chain length. Returns the snapshot string.
188
+ Future<String> export() async =>
189
+ (_asMap(await _call('export'))['snapshot'] ?? '').toString();
190
+
191
+ /// The local ledger tip (an O(1) ref read). Cheap change signal — persistence skips re-exporting an
192
+ /// unchanged snapshot when [head] matches the last saved tip.
193
+ Future<String> head() async =>
194
+ (_asMap(await _call('head'))['head'] ?? '').toString();
195
+
196
+ /// AUTO-SYNC — event-driven background sync. The edge DOORBELL converges peers' writes in real time and a
197
+ /// local write flushes the up leg at once; `fallbackMs` is only a just-in-case safety pull (default 60s).
198
+ /// Each round arrives on [syncEvents] as `{ event:'sync', reason, result }`; socket state as `{event:'link'}`.
199
+ /// Call once after [connect] — then the app never polls.
200
+ Future<void> autoSync(
201
+ {int? debounceMs, int? fallbackMs, String? signalId}) async =>
202
+ await _call('autoSync', {
203
+ if (debounceMs != null) 'debounceMs': debounceMs,
204
+ if (fallbackMs != null) 'fallbackMs': fallbackMs,
205
+ if (signalId != null) 'signalId': signalId
206
+ });
207
+ Future<void> stopAutoSync() async {
208
+ await _call('stopAutoSync');
209
+ }
210
+
211
+ /// Background-sync telemetry: each autoSync round (`event:'sync'`) and doorbell socket state (`event:'link'`).
212
+ Stream<Map<String, Object?>> get syncEvents => _syncEvents.stream;
213
+
214
+ /// Ephemeral signal-holon projections (`event:'signal'`), currently peer frontiers / lag for the workspace.
215
+ Stream<Map<String, Object?>> get signalEvents => _signalEvents.stream;
216
+
217
+ /// THE REALTIME FLAMEPATH: one event per admission the edge broadcasts over the doorbell —
218
+ /// `{ at, oid, edge:{totalMs,scanMs,fetchMs,gateFoldMs,sealMs,intents}, clients:[{client,n}] }`.
219
+ /// Every subscriber sees EVERY admission (yours and your peers') — the cloud track of the flame chart.
220
+ Stream<Map<String, Object?>> get flameEvents => _flameEvents.stream;
221
+
222
+ /// LIVE per-layer spans of the local pipeline (begin/end as they happen): mutex wait, githolon author,
223
+ /// push, converge … The host renders in-progress bars so a hang is visible WHILE it blocks, not after.
224
+ Stream<Map<String, Object?>> get spanEvents => _spanEvents.stream;
225
+
226
+ /// The buffered recent span events — replay these on first build to recover the BOOT flamepath
227
+ /// (fetch wasm / clone ledger / instantiate) that streamed during connect(), before the UI subscribed.
228
+ List<Map<String, Object?>> get recentSpans => List.unmodifiable(_spanBuffer);
229
+
230
+ /// Ledger size (commits) + branch-vs-main (ahead) + projection bytes — the dashboard's slow state.
231
+ Future<Map<String, Object?>> metrics() async =>
232
+ _asMap(await _call('metrics'));
124
233
 
125
234
  /// Diagnostics — is the expected law installed/active/drift-free here? (The generated client surfaces it
126
235
  /// so the app can answer "can I author this directive, and if not what deploy fixes it".)
127
- Future<Map<String, Object?>> lawStatus(String hash) async => _asMap(await _call('lawStatus', {'hash': hash}));
236
+ Future<Map<String, Object?>> lawStatus(String hash) async =>
237
+ _asMap(await _call('lawStatus', {'hash': hash}));
128
238
 
129
239
  /// Reactive local read: a stream of row-sets that re-emits on every local change. Cancelling the
130
240
  /// subscription tells the runner to drop the watch.
131
- Stream<List<dynamic>> watch(String queryId, [Map<String, Object?> params = const {}]) =>
241
+ Stream<List<dynamic>> watch(String queryId,
242
+ [Map<String, Object?> params = const {}]) =>
132
243
  _watchStream(kind: 'query', queryId: queryId, params: params);
133
- Stream<List<dynamic>> watchById(String id) => _watchStream(kind: 'byId', id: id);
244
+ Stream<List<dynamic>> watchById(String id) =>
245
+ _watchStream(kind: 'byId', id: id);
134
246
 
135
- Stream<List<dynamic>> _watchStream({required String kind, String? queryId, Map<String, Object?>? params, String? id}) {
247
+ Stream<List<dynamic>> _watchStream(
248
+ {required String kind,
249
+ String? queryId,
250
+ Map<String, Object?>? params,
251
+ String? id}) {
136
252
  final subId = 'w${++_seq}';
137
253
  late final StreamController<List<dynamic>> ctrl;
138
254
  ctrl = StreamController<List<dynamic>>(
139
- onListen: () => _call('watch', {'subId': subId, 'kind': kind, if (queryId != null) 'queryId': queryId, if (params != null) 'params': params, if (id != null) 'id': id}),
255
+ onListen: () => _call('watch', {
256
+ 'subId': subId,
257
+ 'kind': kind,
258
+ if (queryId != null) 'queryId': queryId,
259
+ if (params != null) 'params': params,
260
+ if (id != null) 'id': id
261
+ }),
140
262
  onCancel: () async {
141
263
  _watches.remove(subId);
142
- try { await _call('unwatch', {'subId': subId}); } catch (_) {}
264
+ try {
265
+ await _call('unwatch', {'subId': subId});
266
+ } catch (_) {}
143
267
  },
144
268
  );
145
269
  _watches[subId] = ctrl;
@@ -157,5 +281,9 @@ class NomosBridge {
157
281
  if (!w.isClosed) await w.close();
158
282
  }
159
283
  _watches.clear();
284
+ if (!_syncEvents.isClosed) await _syncEvents.close();
285
+ if (!_signalEvents.isClosed) await _signalEvents.close();
286
+ if (!_flameEvents.isClosed) await _flameEvents.close();
287
+ if (!_spanEvents.isClosed) await _spanEvents.close();
160
288
  }
161
289
  }