@inflatable-cookie/longhorn 0.1.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 (178) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +38 -0
  3. package/package.json +205 -0
  4. package/src/agent-control/index.ts +20 -0
  5. package/src/agent-control/inject.ts +4 -0
  6. package/src/agent-control/shim.ts +722 -0
  7. package/src/bridge/direct.ts +22 -0
  8. package/src/bridge/generated/fields.ts +32 -0
  9. package/src/bridge/generated/protocol.ts +218 -0
  10. package/src/bridge/generated/variant-fields.ts +10 -0
  11. package/src/bridge/index.ts +15 -0
  12. package/src/bridge/job.ts +51 -0
  13. package/src/bridge/loopback.ts +84 -0
  14. package/src/bridge/operation.ts +166 -0
  15. package/src/bridge/router.ts +71 -0
  16. package/src/bridge/runtime/connection.ts +318 -0
  17. package/src/bridge/runtime/policy.ts +89 -0
  18. package/src/bridge/runtime/retry.ts +60 -0
  19. package/src/bridge/runtime.ts +3 -0
  20. package/src/bridge/session.ts +67 -0
  21. package/src/bridge/stream/connection.ts +146 -0
  22. package/src/bridge/stream/source.ts +61 -0
  23. package/src/bridge/stream/tracker.ts +109 -0
  24. package/src/bridge/stream.ts +6 -0
  25. package/src/bridge/supervision.ts +204 -0
  26. package/src/bridge/validation/base.ts +164 -0
  27. package/src/bridge/validation/jobs.ts +105 -0
  28. package/src/bridge/validation/negotiation.ts +242 -0
  29. package/src/bridge/validation/operations.ts +213 -0
  30. package/src/bridge/validation/streams.ts +47 -0
  31. package/src/bridge/validation.ts +5 -0
  32. package/src/commands/client.ts +124 -0
  33. package/src/commands/controller.ts +411 -0
  34. package/src/commands/generated/fields.ts +43 -0
  35. package/src/commands/generated/protocol.ts +876 -0
  36. package/src/commands/generated/variant-fields.ts +88 -0
  37. package/src/commands/index.ts +13 -0
  38. package/src/commands/keyboard.ts +361 -0
  39. package/src/commands/ports.ts +82 -0
  40. package/src/commands/projectors.ts +306 -0
  41. package/src/commands/validation.ts +444 -0
  42. package/src/config/client.ts +215 -0
  43. package/src/config/generated/base.ts +714 -0
  44. package/src/config/generated/fields.ts +54 -0
  45. package/src/config/generated/label-template.ts +14 -0
  46. package/src/config/generated/labels.ts +30 -0
  47. package/src/config/generated/protocol.ts +3 -0
  48. package/src/config/generated/restore.ts +658 -0
  49. package/src/config/generated/variant-fields.ts +129 -0
  50. package/src/config/index.ts +12 -0
  51. package/src/config/names.ts +19 -0
  52. package/src/config/validation/commands.ts +155 -0
  53. package/src/config/validation/outcomes.ts +243 -0
  54. package/src/config/validation/primitives.ts +174 -0
  55. package/src/config/validation/projection.ts +351 -0
  56. package/src/config/validation.ts +7 -0
  57. package/src/core/connection.ts +252 -0
  58. package/src/core/index.ts +2 -0
  59. package/src/core/transport.ts +24 -0
  60. package/src/history/client.ts +65 -0
  61. package/src/history/controller.ts +385 -0
  62. package/src/history/direct.ts +21 -0
  63. package/src/history/generated/fields.ts +18 -0
  64. package/src/history/generated/protocol.ts +389 -0
  65. package/src/history/generated/variant-fields.ts +27 -0
  66. package/src/history/index.ts +13 -0
  67. package/src/history/ports.ts +31 -0
  68. package/src/history/serialized.ts +38 -0
  69. package/src/history/validation.ts +334 -0
  70. package/src/history-tree/client.ts +16 -0
  71. package/src/history-tree/controller.ts +199 -0
  72. package/src/history-tree/direct.ts +3 -0
  73. package/src/history-tree/generated/fields.ts +26 -0
  74. package/src/history-tree/generated/protocol.ts +711 -0
  75. package/src/history-tree/generated/variant-fields.ts +39 -0
  76. package/src/history-tree/index.ts +13 -0
  77. package/src/history-tree/ports.ts +43 -0
  78. package/src/history-tree/serialized.ts +15 -0
  79. package/src/history-tree/validation.ts +269 -0
  80. package/src/layout/generated/protocol.ts +289 -0
  81. package/src/layout/index.ts +4 -0
  82. package/src/layout/ratio.ts +22 -0
  83. package/src/layout/validation.ts +110 -0
  84. package/src/layout/visibility.ts +30 -0
  85. package/src/licence/client.ts +32 -0
  86. package/src/licence/controller.ts +301 -0
  87. package/src/licence/direct.ts +3 -0
  88. package/src/licence/generated/fields.ts +17 -0
  89. package/src/licence/generated/key-conformance.json +42 -0
  90. package/src/licence/generated/protocol.ts +249 -0
  91. package/src/licence/generated/variant-fields.ts +34 -0
  92. package/src/licence/index.ts +14 -0
  93. package/src/licence/key.ts +125 -0
  94. package/src/licence/ports.ts +39 -0
  95. package/src/licence/serialized.ts +13 -0
  96. package/src/licence/validation.ts +226 -0
  97. package/src/native-content/client.ts +474 -0
  98. package/src/native-content/direct.ts +16 -0
  99. package/src/native-content/generated/fields.ts +32 -0
  100. package/src/native-content/generated/protocol.ts +498 -0
  101. package/src/native-content/generated/variant-fields.ts +77 -0
  102. package/src/native-content/index.ts +12 -0
  103. package/src/native-content/ports.ts +46 -0
  104. package/src/native-content/serialized.ts +50 -0
  105. package/src/native-content/validation/base.ts +194 -0
  106. package/src/native-content/validation/messages.ts +192 -0
  107. package/src/native-content/validation/state.ts +404 -0
  108. package/src/native-content/validation.ts +7 -0
  109. package/src/notifications/client.ts +106 -0
  110. package/src/notifications/controller.ts +240 -0
  111. package/src/notifications/direct.ts +12 -0
  112. package/src/notifications/generated/fields.ts +19 -0
  113. package/src/notifications/generated/labels.ts +20 -0
  114. package/src/notifications/generated/protocol.ts +522 -0
  115. package/src/notifications/generated/variant-fields.ts +37 -0
  116. package/src/notifications/index.ts +16 -0
  117. package/src/notifications/ports.ts +22 -0
  118. package/src/notifications/serialized.ts +27 -0
  119. package/src/notifications/toast.ts +41 -0
  120. package/src/notifications/tone.ts +27 -0
  121. package/src/notifications/validation.ts +246 -0
  122. package/src/operation/bridge.ts +168 -0
  123. package/src/operation/client.ts +167 -0
  124. package/src/operation/controller.ts +321 -0
  125. package/src/operation/direct.ts +15 -0
  126. package/src/operation/generated/fields.ts +20 -0
  127. package/src/operation/generated/labels.ts +15 -0
  128. package/src/operation/generated/protocol.ts +762 -0
  129. package/src/operation/generated/variant-fields.ts +60 -0
  130. package/src/operation/index.ts +14 -0
  131. package/src/operation/ports.ts +29 -0
  132. package/src/operation/serialized.ts +39 -0
  133. package/src/operation/validation.ts +479 -0
  134. package/src/settings/client.ts +142 -0
  135. package/src/settings/connection.ts +246 -0
  136. package/src/settings/generated/fields.ts +34 -0
  137. package/src/settings/generated/protocol.ts +668 -0
  138. package/src/settings/generated/variant-fields.ts +26 -0
  139. package/src/settings/index.ts +12 -0
  140. package/src/settings/names.ts +8 -0
  141. package/src/settings/registry.ts +141 -0
  142. package/src/settings/validation/authority.ts +66 -0
  143. package/src/settings/validation/command.ts +165 -0
  144. package/src/settings/validation/error.ts +33 -0
  145. package/src/settings/validation/primitives.ts +203 -0
  146. package/src/settings/validation/projection.ts +50 -0
  147. package/src/settings/validation/registry.ts +170 -0
  148. package/src/settings/validation.ts +4 -0
  149. package/src/surface-transfer/client.ts +54 -0
  150. package/src/surface-transfer/generated/fields.ts +12 -0
  151. package/src/surface-transfer/generated/protocol.ts +61 -0
  152. package/src/surface-transfer/generated/variant-fields.ts +30 -0
  153. package/src/surface-transfer/index.ts +9 -0
  154. package/src/surface-transfer/validation.ts +209 -0
  155. package/src/surfaces/client.ts +140 -0
  156. package/src/surfaces/generated/fields.ts +19 -0
  157. package/src/surfaces/generated/protocol.ts +217 -0
  158. package/src/surfaces/generated/variant-fields.ts +42 -0
  159. package/src/surfaces/index.ts +9 -0
  160. package/src/surfaces/validation.ts +199 -0
  161. package/src/transfer/client.ts +133 -0
  162. package/src/transfer/connection.ts +87 -0
  163. package/src/transfer/generated/fields.ts +23 -0
  164. package/src/transfer/generated/protocol.ts +171 -0
  165. package/src/transfer/generated/variant-fields.ts +45 -0
  166. package/src/transfer/index.ts +11 -0
  167. package/src/transfer/payload.ts +71 -0
  168. package/src/transfer/validation.ts +282 -0
  169. package/src/update/client.ts +29 -0
  170. package/src/update/controller.ts +255 -0
  171. package/src/update/direct.ts +3 -0
  172. package/src/update/generated/fields.ts +14 -0
  173. package/src/update/generated/protocol.ts +238 -0
  174. package/src/update/generated/variant-fields.ts +44 -0
  175. package/src/update/index.ts +14 -0
  176. package/src/update/ports.ts +36 -0
  177. package/src/update/serialized.ts +12 -0
  178. package/src/update/validation.ts +191 -0
@@ -0,0 +1,282 @@
1
+ import {
2
+ TRANSFER_VARIANT_FIELDS,
3
+ TRANSFER_VARIANT_FIELDS_DISCRIMINANTS,
4
+ } from "./generated/variant-fields.ts";
5
+ import {
6
+ PANEL_TRANSFER_ERROR_CODES,
7
+ PANEL_TRANSFER_RESPONSE_STATUSES,
8
+ TRANSFER_ABORT_DOMAINS,
9
+ TRANSFER_CANCEL_RESPONSE_STATUSES,
10
+ TRANSFER_COMMIT_SELECTOR_KINDS,
11
+ TRANSFER_ERROR_CODES,
12
+ TRANSFER_LEASE_RESPONSE_STATUSES,
13
+ TRANSFER_PROTOCOL_VERSION,
14
+ TRANSFER_SESSION_RESPONSE_STATUSES,
15
+ TRANSFER_TARGET_BINDING_KINDS,
16
+ type PanelTransferResponse,
17
+ type TransferAbort,
18
+ type TransferCancelResponse,
19
+ type TransferClientSnapshot,
20
+ type TransferCommitSelector,
21
+ type TransferLeaseResponse,
22
+ type TransferSessionResponse,
23
+ type TransferTargetBinding,
24
+ } from "./generated/protocol.ts";
25
+ import { TRANSFER_FIELDS } from "./generated/fields.ts";
26
+
27
+ export type TransferProtocolValidationCode =
28
+ | "unsupported_protocol_version"
29
+ | "unknown_target_binding"
30
+ | "unknown_commit_selector"
31
+ | "unknown_abort_domain"
32
+ | "unknown_transfer_error_code"
33
+ | "unknown_panel_error_code"
34
+ | "unknown_response_status"
35
+ | "invalid_client_snapshot"
36
+ | "invalid_object"
37
+ | "unknown_field"
38
+ | "missing_field";
39
+
40
+ export class TransferProtocolValidationError extends Error {
41
+ readonly code: TransferProtocolValidationCode;
42
+ readonly received: unknown;
43
+
44
+ constructor(code: TransferProtocolValidationCode, received: unknown) {
45
+ super(`incompatible transfer protocol: ${code}`);
46
+ this.name = "TransferProtocolValidationError";
47
+ this.code = code;
48
+ this.received = received;
49
+ }
50
+ }
51
+
52
+ export function assertTransferProtocolVersion(
53
+ version: unknown,
54
+ ): asserts version is typeof TRANSFER_PROTOCOL_VERSION {
55
+ if (version !== TRANSFER_PROTOCOL_VERSION) {
56
+ throw new TransferProtocolValidationError(
57
+ "unsupported_protocol_version",
58
+ version,
59
+ );
60
+ }
61
+ }
62
+
63
+ export function assertValidTransferTargetBinding(
64
+ value: unknown,
65
+ ): asserts value is TransferTargetBinding {
66
+ const candidate = record(value);
67
+ assertKnown(
68
+ candidate.kind,
69
+ TRANSFER_TARGET_BINDING_KINDS,
70
+ "unknown_target_binding",
71
+ );
72
+ record(candidate, variantKeys("TransferTargetBinding", candidate));
73
+ }
74
+
75
+ export function assertValidTransferClientSnapshot(
76
+ value: unknown,
77
+ ): asserts value is TransferClientSnapshot {
78
+ const snapshot = record(value, TRANSFER_FIELDS.TransferClientSnapshot);
79
+ assertTransferProtocolVersion(snapshot.protocol_version);
80
+ if (
81
+ typeof snapshot.client_id !== "string" ||
82
+ !unsignedInteger(snapshot.client_epoch) ||
83
+ (snapshot.current_lease_generation !== null &&
84
+ !unsignedInteger(snapshot.current_lease_generation))
85
+ ) {
86
+ throw new TransferProtocolValidationError(
87
+ "invalid_client_snapshot",
88
+ value,
89
+ );
90
+ }
91
+ }
92
+
93
+ export function assertValidTransferCommitSelector(
94
+ value: unknown,
95
+ ): asserts value is TransferCommitSelector {
96
+ const candidate = record(value);
97
+ assertKnown(
98
+ candidate.kind,
99
+ TRANSFER_COMMIT_SELECTOR_KINDS,
100
+ "unknown_commit_selector",
101
+ );
102
+ record(candidate, variantKeys("TransferCommitSelector", candidate));
103
+ }
104
+
105
+ export function assertValidTransferAbort(
106
+ value: unknown,
107
+ ): asserts value is TransferAbort {
108
+ const abort = record(value, TRANSFER_FIELDS.TransferAbort);
109
+ assertTransferProtocolVersion(abort.protocol_version);
110
+ const source = record(abort.source);
111
+ assertKnown(
112
+ source.domain,
113
+ TRANSFER_ABORT_DOMAINS,
114
+ "unknown_abort_domain",
115
+ );
116
+ record(source, variantKeys("TransferAbortSource", source));
117
+ if (source.domain === "transfer") {
118
+ assertKnown(
119
+ source.code,
120
+ TRANSFER_ERROR_CODES,
121
+ "unknown_transfer_error_code",
122
+ );
123
+ } else {
124
+ assertKnown(
125
+ source.code,
126
+ PANEL_TRANSFER_ERROR_CODES,
127
+ "unknown_panel_error_code",
128
+ );
129
+ }
130
+ }
131
+
132
+ export function assertValidTransferSessionResponse(
133
+ value: unknown,
134
+ ): asserts value is TransferSessionResponse {
135
+ const response = responseWithStatus(
136
+ value,
137
+ TRANSFER_SESSION_RESPONSE_STATUSES,
138
+ "TransferSessionResponse",
139
+ );
140
+ if (response.status === "started") {
141
+ const session = record(response.session, TRANSFER_FIELDS.TransferSessionStarted);
142
+ assertTransferProtocolVersion(session.protocol_version);
143
+ assertTransferProtocolVersion(record(session.payload).protocol_version);
144
+ } else {
145
+ assertValidTransferAbort(response.abort);
146
+ }
147
+ }
148
+
149
+ export function assertValidTransferLeaseResponse(
150
+ value: unknown,
151
+ ): asserts value is TransferLeaseResponse {
152
+ const response = responseWithStatus(
153
+ value,
154
+ TRANSFER_LEASE_RESPONSE_STATUSES,
155
+ "TransferLeaseResponse",
156
+ );
157
+ if (response.status === "published") {
158
+ assertTransferProtocolVersion(record(response.lease).protocol_version);
159
+ } else {
160
+ assertValidTransferAbort(response.abort);
161
+ }
162
+ }
163
+
164
+ export function assertValidTransferCancelResponse(
165
+ value: unknown,
166
+ ): asserts value is TransferCancelResponse {
167
+ const response = responseWithStatus(
168
+ value,
169
+ TRANSFER_CANCEL_RESPONSE_STATUSES,
170
+ "TransferCancelResponse",
171
+ );
172
+ if (response.status === "cancelled") {
173
+ assertTransferProtocolVersion(
174
+ record(response.cancellation).protocol_version,
175
+ );
176
+ } else {
177
+ assertValidTransferAbort(response.abort);
178
+ }
179
+ }
180
+
181
+ export function assertValidPanelTransferResponse(
182
+ value: unknown,
183
+ ): asserts value is PanelTransferResponse {
184
+ const response = responseWithStatus(
185
+ value,
186
+ PANEL_TRANSFER_RESPONSE_STATUSES,
187
+ "PanelTransferResponse",
188
+ );
189
+ if (response.status === "committed") {
190
+ const completion = record(response.completion, TRANSFER_FIELDS.PanelTransferCompletion);
191
+ assertTransferProtocolVersion(completion.protocol_version);
192
+ assertValidTransferTargetBinding(
193
+ record(record(completion.target).binding),
194
+ );
195
+ } else {
196
+ assertValidTransferAbort(response.abort);
197
+ }
198
+ }
199
+
200
+ function responseWithStatus(
201
+ value: unknown,
202
+ statuses: readonly string[],
203
+ type: string,
204
+ ): Record<string, unknown> {
205
+ const response = record(value);
206
+ assertKnown(response.status, statuses, "unknown_response_status");
207
+ record(response, variantKeys(type, response));
208
+ return response;
209
+ }
210
+
211
+ /**
212
+ * Allowed keys for one tagged-union variant, from the generated map, with the
213
+ * discriminant's name read from the map too — this domain tags on `kind`,
214
+ * `status` and `domain`.
215
+ *
216
+ * A missing entry means the generator failed to read the union; every caller
217
+ * runs `assertKnown` over the discriminant above this.
218
+ */
219
+ function variantKeys(
220
+ type: string,
221
+ value: Record<string, unknown>,
222
+ ): readonly string[] {
223
+ const discriminant = value[TRANSFER_VARIANT_FIELDS_DISCRIMINANTS[type] ?? "kind"];
224
+ const keys = TRANSFER_VARIANT_FIELDS[type]?.[discriminant as string];
225
+ if (keys === undefined) {
226
+ throw new TransferProtocolValidationError("unknown_response_status", {
227
+ type,
228
+ discriminant,
229
+ });
230
+ }
231
+ return keys;
232
+ }
233
+
234
+ function assertKnown(
235
+ value: unknown,
236
+ known: readonly string[],
237
+ code: TransferProtocolValidationCode,
238
+ ): asserts value is string {
239
+ if (typeof value !== "string" || !known.includes(value)) {
240
+ throw new TransferProtocolValidationError(code, value);
241
+ }
242
+ }
243
+
244
+ /**
245
+ * Rejects a non-object, an unknown key, and a missing key.
246
+ *
247
+ * `allowed` comes from the generated field map, so the keys accepted are the
248
+ * Rust struct's and nothing else — contract 010's Boundary Validation Target.
249
+ * Passing no list keeps shape-only behaviour for the tagged unions, whose
250
+ * allowed keys depend on their discriminant and so are not one flat set.
251
+ */
252
+ function record(
253
+ value: unknown,
254
+ allowed?: readonly string[],
255
+ ): Record<string, unknown> {
256
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
257
+ throw new TransferProtocolValidationError("invalid_object", value);
258
+ }
259
+ const result = value as Record<string, unknown>;
260
+ if (allowed === undefined) return result;
261
+
262
+ const permitted = new Set(allowed);
263
+ for (const key of Object.keys(result)) {
264
+ if (!permitted.has(key)) {
265
+ throw new TransferProtocolValidationError("unknown_field", { key, value });
266
+ }
267
+ }
268
+ for (const key of allowed) {
269
+ if (!(key in result)) {
270
+ throw new TransferProtocolValidationError("missing_field", { key, value });
271
+ }
272
+ }
273
+ return result;
274
+ }
275
+
276
+ function unsignedInteger(value: unknown): value is number {
277
+ return (
278
+ typeof value === "number" &&
279
+ Number.isSafeInteger(value) &&
280
+ value >= 0
281
+ );
282
+ }
@@ -0,0 +1,29 @@
1
+ import type {
2
+ UpdateChangedEvent,
3
+ UpdateCheckCommand,
4
+ UpdateDeferCommand,
5
+ UpdateInstallCommand,
6
+ UpdateOutcomeProjection,
7
+ UpdateSelectChannelCommand,
8
+ UpdateSnapshot,
9
+ } from "./generated/protocol.ts";
10
+ import type { CheckedUpdatePort, UpdatePort, UpdateUnlisten } from "./ports.ts";
11
+ import {
12
+ assertUpdateChangedEvent,
13
+ assertUpdateCheckCommand,
14
+ assertUpdateDeferCommand,
15
+ assertUpdateInstallCommand,
16
+ assertUpdateOutcome,
17
+ assertUpdateSelectChannelCommand,
18
+ assertUpdateSnapshot,
19
+ } from "./validation.ts";
20
+
21
+ export class UpdateClient implements CheckedUpdatePort {
22
+ constructor(readonly port: UpdatePort) {}
23
+ async snapshot(): Promise<UpdateSnapshot> { const value = await this.port.snapshot(); assertUpdateSnapshot(value); return value; }
24
+ async check(command: UpdateCheckCommand): Promise<UpdateOutcomeProjection> { assertUpdateCheckCommand(command); const value = await this.port.check(command); assertUpdateOutcome(value); return value; }
25
+ async selectChannel(command: UpdateSelectChannelCommand): Promise<UpdateOutcomeProjection> { assertUpdateSelectChannelCommand(command); const value = await this.port.selectChannel(command); assertUpdateOutcome(value); return value; }
26
+ async defer(command: UpdateDeferCommand): Promise<UpdateOutcomeProjection> { assertUpdateDeferCommand(command); const value = await this.port.defer(command); assertUpdateOutcome(value); return value; }
27
+ async install(command: UpdateInstallCommand): Promise<UpdateOutcomeProjection> { assertUpdateInstallCommand(command); const value = await this.port.install(command); assertUpdateOutcome(value); return value; }
28
+ async listen(listener: (event: UpdateChangedEvent) => void): Promise<UpdateUnlisten> { if (this.port.listen === undefined) return () => {}; return this.port.listen((value) => { assertUpdateChangedEvent(value); listener(value); }); }
29
+ }
@@ -0,0 +1,255 @@
1
+ import { UpdateClient } from "./client.ts";
2
+ import {
3
+ UPDATE_PROTOCOL_VERSION,
4
+ type Channel,
5
+ type DeferralCause,
6
+ type UpdateAvailabilityProjection,
7
+ type UpdateProgressProjection,
8
+ type UpdateRejectionCode,
9
+ type UpdateSnapshot,
10
+ } from "./generated/protocol.ts";
11
+ import type { UpdatePort, UpdateUnlisten } from "./ports.ts";
12
+
13
+ export type UpdateControllerStatus =
14
+ | { readonly kind: "idle" }
15
+ | { readonly kind: "loading" }
16
+ | { readonly kind: "ready" }
17
+ | { readonly kind: "failed"; readonly error: unknown };
18
+
19
+ export interface UpdateControllerOptions {
20
+ readonly port: UpdatePort;
21
+ }
22
+
23
+ /**
24
+ * What an update indicator should do.
25
+ *
26
+ * A predicate rather than a rendering, and Longhorn's rather than a surface's:
27
+ * deriving it means reading five availability states against five progress
28
+ * states and a deferral, and two surfaces deriving it separately would drift.
29
+ *
30
+ * - `hidden` — collapse to nothing. There is nothing the operator can do here.
31
+ * - `quiet` — present, not insistent. Work is in flight, or they have already
32
+ * been asked and postponed.
33
+ * - `attention` — something is waiting for a decision.
34
+ */
35
+ export type UpdatePresence = "hidden" | "quiet" | "attention";
36
+
37
+ /**
38
+ * Holds update state for a surface and keeps the three outcomes apart.
39
+ *
40
+ * A command can end three ways, and collapsing any two of them produces a
41
+ * wrong message:
42
+ *
43
+ * - **Committed.** State moved. Read the snapshot.
44
+ * - **Committed with a deferral.** The install did not happen and that is not
45
+ * a failure — Card 154 step 6. The gate refused because the user has work in
46
+ * flight, and `deferral` says so. A surface that reports this as an error
47
+ * tells a customer their update is broken when nothing is.
48
+ * - **Rejected.** The authority refused. `lastRejection` carries the code, and
49
+ * this is the only one of the three that is a fault.
50
+ *
51
+ * Transport failures are the fourth thing, and land in `status`.
52
+ */
53
+ export class UpdateController {
54
+ readonly #client: UpdateClient;
55
+ readonly #observers = new Set<() => void>();
56
+ #status: UpdateControllerStatus = { kind: "idle" };
57
+ #snapshot?: UpdateSnapshot;
58
+ #lastRejection?: UpdateRejectionCode;
59
+ #started = false;
60
+ #lifecycle = 0;
61
+ #pending = false;
62
+ #unlisten: UpdateUnlisten[] = [];
63
+
64
+ constructor(options: UpdateControllerOptions) {
65
+ this.#client = new UpdateClient(options.port);
66
+ }
67
+
68
+ get status(): UpdateControllerStatus { return this.#status; }
69
+ get snapshot(): UpdateSnapshot | undefined { return this.#snapshot; }
70
+ get availability(): UpdateAvailabilityProjection | undefined { return this.#snapshot?.availability; }
71
+ get progress(): UpdateProgressProjection | undefined { return this.#snapshot?.progress; }
72
+ get channel(): Channel | undefined { return this.#snapshot?.channel; }
73
+ get installedVersion(): string | undefined { return this.#snapshot?.installedVersion; }
74
+ get pending(): boolean { return this.#pending; }
75
+
76
+ /**
77
+ * Why the last install did not proceed, when it did not.
78
+ *
79
+ * Present alongside a *committed* outcome. Card 154 step 6: a refused
80
+ * restart shows its reason and is not a failure.
81
+ */
82
+ get deferral(): { readonly version: string; readonly cause: DeferralCause } | undefined {
83
+ return this.#snapshot?.deferral ?? undefined;
84
+ }
85
+
86
+ /** The last refusal, cleared by the next command that commits. */
87
+ get lastRejection(): UpdateRejectionCode | undefined { return this.#lastRejection; }
88
+
89
+ /**
90
+ * Whether this install sits ahead of the channel it follows.
91
+ *
92
+ * Card 154 step 5 calls this the single most likely support question the
93
+ * feature generates: an install on `1.3.0-nightly.4` that selects production
94
+ * receives nothing until `1.3.0` ships, which is correct and reads as a
95
+ * broken updater unless the surface says so. Exposed as its own read so a
96
+ * surface cannot render it as "no update available" by omission.
97
+ */
98
+ get aheadOfChannel(): { readonly installed: string; readonly channel: string } | undefined {
99
+ const availability = this.#snapshot?.availability;
100
+ if (availability?.state !== "aheadOfChannel") return undefined;
101
+ return { installed: availability.installed, channel: availability.channel };
102
+ }
103
+
104
+ /**
105
+ * Whether an update indicator should show, and how loudly.
106
+ *
107
+ * Three availability states are deliberately `hidden`, because none of them
108
+ * is an install this application can perform:
109
+ *
110
+ * - `withheldByRollout` — a version exists and this install is not in the
111
+ * stage yet. Showing it would offer something that cannot be taken.
112
+ * - `aheadOfChannel` — nothing to install. It needs explaining, and the
113
+ * place to explain it is the settings panel, not a notification.
114
+ * - `managedElsewhere` — Homebrew or the App Store owns this install. There
115
+ * is a version and the operator can act, but not through the
116
+ * download-install-restart loop an indicator implies. Settings tells them
117
+ * where to get it.
118
+ *
119
+ * A postponed offer stays `quiet` rather than disappearing. They said "not
120
+ * now", not "never", and an indicator that vanishes gives them no way back.
121
+ */
122
+ get presence(): UpdatePresence {
123
+ const snapshot = this.#snapshot;
124
+ if (snapshot === undefined) return "hidden";
125
+
126
+ switch (snapshot.progress.state) {
127
+ case "downloading":
128
+ case "verifying":
129
+ case "installing":
130
+ return "quiet";
131
+ case "readyToInstall":
132
+ return "attention";
133
+ case "idle":
134
+ break;
135
+ }
136
+
137
+ if (snapshot.availability.state !== "offer") return "hidden";
138
+ // Postponed by the operator, not by the gate. A gate deferral is transient
139
+ // and the offer is still the answer; `userPostponed` is a decision.
140
+ return snapshot.deferral?.cause.cause === "userPostponed" ? "quiet" : "attention";
141
+ }
142
+
143
+ observe(observer: () => void): () => void {
144
+ this.#observers.add(observer);
145
+ return () => this.#observers.delete(observer);
146
+ }
147
+
148
+ async start(): Promise<void> {
149
+ if (this.#started) return;
150
+ this.#started = true;
151
+ const lifecycle = ++this.#lifecycle;
152
+ this.#setStatus({ kind: "loading" });
153
+ try {
154
+ const unlisten = await this.#client.listen(() => void this.refresh());
155
+ // The listen resolved after a stop, or after a restart replaced this
156
+ // lifetime. Contract 013: an adapter that outlives its owner keeps
157
+ // writing into state nobody is reading.
158
+ if (!this.#started || lifecycle !== this.#lifecycle) {
159
+ await unlisten();
160
+ return;
161
+ }
162
+ this.#unlisten.push(unlisten);
163
+ await this.refresh();
164
+ } catch (error) {
165
+ if (this.#started && lifecycle === this.#lifecycle) this.#setStatus({ kind: "failed", error });
166
+ }
167
+ }
168
+
169
+ async stop(): Promise<void> {
170
+ this.#started = false;
171
+ this.#lifecycle += 1;
172
+ const unlisten = this.#unlisten;
173
+ this.#unlisten = [];
174
+ for (const stop of unlisten) await stop();
175
+ this.#setStatus({ kind: "idle" });
176
+ }
177
+
178
+ async refresh(): Promise<void> {
179
+ const lifecycle = this.#lifecycle;
180
+ try {
181
+ const snapshot = await this.#client.snapshot();
182
+ if (lifecycle !== this.#lifecycle) return;
183
+ this.#snapshot = snapshot;
184
+ this.#setStatus({ kind: "ready" });
185
+ } catch (error) {
186
+ if (lifecycle === this.#lifecycle) this.#setStatus({ kind: "failed", error });
187
+ }
188
+ }
189
+
190
+ /** Asks the source for the channel's current manifest. */
191
+ async check(): Promise<void> {
192
+ await this.#command((client, epoch) =>
193
+ client.check({ protocolVersion: UPDATE_PROTOCOL_VERSION, authorityEpoch: epoch }),
194
+ );
195
+ }
196
+
197
+ /** Follows a different channel from now on. */
198
+ async selectChannel(channel: Channel): Promise<void> {
199
+ await this.#command((client, epoch) =>
200
+ client.selectChannel({ protocolVersion: UPDATE_PROTOCOL_VERSION, authorityEpoch: epoch, channel }),
201
+ );
202
+ }
203
+
204
+ /** Declines a version for now. */
205
+ async defer(version: string, cause: DeferralCause): Promise<void> {
206
+ await this.#command((client, epoch) =>
207
+ client.defer({ protocolVersion: UPDATE_PROTOCOL_VERSION, authorityEpoch: epoch, version, cause }),
208
+ );
209
+ }
210
+
211
+ /** Fetches, verifies, gates and installs. */
212
+ async install(version: string): Promise<void> {
213
+ await this.#command((client, epoch) =>
214
+ client.install({ protocolVersion: UPDATE_PROTOCOL_VERSION, authorityEpoch: epoch, version }),
215
+ );
216
+ }
217
+
218
+ async #command(
219
+ run: (client: UpdateClient, epoch: number) => Promise<import("./generated/protocol.ts").UpdateOutcomeProjection>,
220
+ ): Promise<void> {
221
+ const epoch = this.#snapshot?.authorityEpoch;
222
+ if (epoch === undefined) {
223
+ // No snapshot means no epoch to send, and inventing one would have the
224
+ // authority refuse it as stale. Say what is actually wrong.
225
+ this.#setStatus({ kind: "failed", error: new Error("update state has not been read yet") });
226
+ return;
227
+ }
228
+ const lifecycle = this.#lifecycle;
229
+ this.#pending = true;
230
+ this.#notify();
231
+ try {
232
+ const outcome = await run(this.#client, epoch);
233
+ if (lifecycle !== this.#lifecycle) return;
234
+ this.#snapshot = outcome.snapshot;
235
+ this.#lastRejection = outcome.status === "rejected" ? outcome.code : undefined;
236
+ this.#setStatus({ kind: "ready" });
237
+ } catch (error) {
238
+ if (lifecycle === this.#lifecycle) this.#setStatus({ kind: "failed", error });
239
+ } finally {
240
+ if (lifecycle === this.#lifecycle) {
241
+ this.#pending = false;
242
+ this.#notify();
243
+ }
244
+ }
245
+ }
246
+
247
+ #setStatus(status: UpdateControllerStatus): void {
248
+ this.#status = status;
249
+ this.#notify();
250
+ }
251
+
252
+ #notify(): void {
253
+ for (const observer of this.#observers) observer();
254
+ }
255
+ }
@@ -0,0 +1,3 @@
1
+ import type { UpdatePort } from "./ports.ts";
2
+ export type DirectUpdateHandlers = UpdatePort;
3
+ export function createDirectUpdatePort(handlers: DirectUpdateHandlers): UpdatePort { return handlers; }
@@ -0,0 +1,14 @@
1
+ // @generated by `effigy generate:update`; do not edit.
2
+ // Allowed field names per protocol type, from the Rust structs.
3
+ // A `record()` given one of these rejects unknown and missing keys —
4
+ // contract 010's Boundary Validation Target.
5
+
6
+ export const UPDATE_FIELDS: Record<string, readonly string[]> = {
7
+ "UpdateDeferralProjection": ["version", "cause"],
8
+ "UpdateSnapshot": ["protocolVersion", "authorityEpoch", "channel", "installedVersion", "availability", "deferral", "progress"],
9
+ "UpdateCheckCommand": ["protocolVersion", "authorityEpoch"],
10
+ "UpdateSelectChannelCommand": ["protocolVersion", "authorityEpoch", "channel"],
11
+ "UpdateDeferCommand": ["protocolVersion", "authorityEpoch", "version", "cause"],
12
+ "UpdateInstallCommand": ["protocolVersion", "authorityEpoch", "version"],
13
+ "UpdateChangedEvent": ["protocolVersion", "authorityEpoch", "kind"],
14
+ };