@catamorphic/work-server 0.1.0-alpha.39 → 0.1.0-alpha.41

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 (114) hide show
  1. package/NOTICE.txt +7 -0
  2. package/README.md +9 -9
  3. package/dist/admission/routes.d.ts +1 -1
  4. package/dist/admission/routes.d.ts.map +1 -1
  5. package/dist/agent-capabilities.d.ts.map +1 -1
  6. package/dist/agents.d.ts +5 -6
  7. package/dist/agents.d.ts.map +1 -1
  8. package/dist/auth/fastify-auth.d.ts.map +1 -1
  9. package/dist/auth/work-auth-types.d.ts +2 -0
  10. package/dist/auth/work-auth-types.d.ts.map +1 -1
  11. package/dist/auth/work-auth.d.ts.map +1 -1
  12. package/dist/chunk-kcck20aw.js +676 -0
  13. package/dist/chunk-kcck20aw.js.map +11 -0
  14. package/dist/cluster.d.ts +8 -7
  15. package/dist/cluster.d.ts.map +1 -1
  16. package/dist/config.d.ts +5 -15
  17. package/dist/config.d.ts.map +1 -1
  18. package/dist/execution-config.d.ts +22 -0
  19. package/dist/execution-config.d.ts.map +1 -1
  20. package/dist/fake-agent.d.ts +1 -0
  21. package/dist/fake-agent.d.ts.map +1 -1
  22. package/dist/index.d.ts +3 -2
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +2730 -2851
  25. package/dist/index.js.map +28 -28
  26. package/dist/machines/contract-kit.d.ts +91 -0
  27. package/dist/machines/contract-kit.d.ts.map +1 -0
  28. package/dist/machines/contract.d.ts +383 -0
  29. package/dist/machines/contract.d.ts.map +1 -0
  30. package/dist/machines/sequencer.d.ts +267 -0
  31. package/dist/machines/sequencer.d.ts.map +1 -0
  32. package/dist/machines/simulation.d.ts +124 -0
  33. package/dist/machines/simulation.d.ts.map +1 -0
  34. package/dist/machines/work-machines.d.ts +61 -0
  35. package/dist/machines/work-machines.d.ts.map +1 -0
  36. package/dist/server.d.ts +15 -11
  37. package/dist/server.d.ts.map +1 -1
  38. package/dist/setup/machines.d.ts +9 -17
  39. package/dist/setup/machines.d.ts.map +1 -1
  40. package/dist/shares/share-routes.d.ts +1 -1
  41. package/dist/shares/share-routes.d.ts.map +1 -1
  42. package/dist/testing.d.ts +8 -0
  43. package/dist/testing.d.ts.map +1 -0
  44. package/dist/testing.js +1013 -0
  45. package/dist/testing.js.map +11 -0
  46. package/dist/workers/disk-care.d.ts +41 -0
  47. package/dist/workers/disk-care.d.ts.map +1 -0
  48. package/dist/workers/harness-sign-ins.d.ts +146 -0
  49. package/dist/workers/harness-sign-ins.d.ts.map +1 -0
  50. package/dist/workers/machine-store.d.ts +196 -0
  51. package/dist/workers/machine-store.d.ts.map +1 -0
  52. package/dist/workers/member-machine-routes.d.ts +5 -3
  53. package/dist/workers/member-machine-routes.d.ts.map +1 -1
  54. package/dist/workers/member-machines.d.ts +47 -28
  55. package/dist/workers/member-machines.d.ts.map +1 -1
  56. package/dist/workers/placement.d.ts +23 -40
  57. package/dist/workers/placement.d.ts.map +1 -1
  58. package/dist/workers/sign-ins.d.ts +44 -17
  59. package/dist/workers/sign-ins.d.ts.map +1 -1
  60. package/dist/workers/worker-protocol.d.ts +5 -2
  61. package/dist/workers/worker-protocol.d.ts.map +1 -1
  62. package/dist/workers/worker-registry.d.ts +174 -223
  63. package/dist/workers/worker-registry.d.ts.map +1 -1
  64. package/dist/workers/worker-routes.d.ts.map +1 -1
  65. package/dist/workers/worker-runtime.d.ts.map +1 -1
  66. package/package.json +31 -21
  67. package/src/admission/routes.ts +5 -2
  68. package/src/agent-capabilities.ts +22 -8
  69. package/src/agents.ts +52 -23
  70. package/src/auth/fastify-auth.ts +149 -17
  71. package/src/auth/work-auth-types.ts +2 -0
  72. package/src/auth/work-auth.ts +27 -0
  73. package/src/cluster.ts +115 -42
  74. package/src/config.ts +15 -41
  75. package/src/execution-config.ts +40 -0
  76. package/src/fake-agent.ts +21 -4
  77. package/src/index.ts +26 -12
  78. package/src/machines/contract-kit.ts +648 -0
  79. package/src/machines/contract.ts +522 -0
  80. package/src/machines/sequencer.ts +1010 -0
  81. package/src/machines/simulation.ts +833 -0
  82. package/src/machines/work-machines.ts +231 -0
  83. package/src/server.ts +235 -150
  84. package/src/setup/machines.ts +128 -121
  85. package/src/shares/share-routes.ts +17 -1
  86. package/src/testing.ts +22 -0
  87. package/src/workers/disk-care.ts +121 -0
  88. package/src/workers/fake-claude-cli.ts +95 -0
  89. package/src/workers/fake-codex-cli.ts +11 -4
  90. package/src/workers/harness-sign-ins.ts +580 -0
  91. package/src/workers/machine-store.ts +1065 -0
  92. package/src/workers/member-machine-routes.ts +92 -20
  93. package/src/workers/member-machines.ts +163 -99
  94. package/src/workers/placement.ts +59 -70
  95. package/src/workers/sign-ins.ts +109 -52
  96. package/src/workers/worker-protocol.ts +5 -2
  97. package/src/workers/worker-registry.ts +894 -754
  98. package/src/workers/worker-routes.ts +4 -1
  99. package/src/workers/worker-runtime.ts +55 -23
  100. package/dist/test-support.d.ts +0 -133
  101. package/dist/test-support.d.ts.map +0 -1
  102. package/dist/workers/codex-sign-ins.d.ts +0 -107
  103. package/dist/workers/codex-sign-ins.d.ts.map +0 -1
  104. package/dist/workers/install-script.d.ts +0 -71
  105. package/dist/workers/install-script.d.ts.map +0 -1
  106. package/dist/workers/machine-classes.d.ts +0 -115
  107. package/dist/workers/machine-classes.d.ts.map +0 -1
  108. package/dist/workers/machine-rules.d.ts +0 -402
  109. package/dist/workers/machine-rules.d.ts.map +0 -1
  110. package/src/test-support.ts +0 -404
  111. package/src/workers/codex-sign-ins.ts +0 -360
  112. package/src/workers/install-script.ts +0 -394
  113. package/src/workers/machine-classes.ts +0 -152
  114. package/src/workers/machine-rules.ts +0 -1954
@@ -0,0 +1,833 @@
1
+ import { createHash } from "node:crypto";
2
+ import {
3
+ DEFAULT_LOST_AFTER_MINUTES,
4
+ type MachineEvent,
5
+ type MachineFacts,
6
+ type MachinePrincipal,
7
+ type MachinesHook,
8
+ type MachineVerb,
9
+ normalizePrincipals,
10
+ type PersonFacts,
11
+ type WaitingWork,
12
+ } from "./contract.js";
13
+ import {
14
+ lostAfterMsOf,
15
+ type MachinePassSummary,
16
+ type MachinePhase,
17
+ type MachineRecord,
18
+ type MachineWorld,
19
+ machineStateOf,
20
+ machineTakes,
21
+ type PlannedMachine,
22
+ runMachinePass,
23
+ } from "./sequencer.js";
24
+
25
+ /*
26
+ * A simulated Work for testing a machines hook (ADR 0349): the real
27
+ * sequencer over machines, work and people kept in memory, with a clock a
28
+ * test moves. A machine the hook's `create` answered for boots and
29
+ * connects by itself after `bootSeconds`; a test places work, ends it,
30
+ * kills a machine, or enrolls one by hand, and reads what the hook was
31
+ * asked to do. No server, database or cloud is involved.
32
+ */
33
+
34
+ /** One call the simulated Work made into the hook. */
35
+ export interface SimulatedCall {
36
+ verb: MachineVerb;
37
+ name: string;
38
+ /** ISO 8601, by the simulation's clock. */
39
+ at: string;
40
+ ref: string | null;
41
+ idempotencyKey: string | null;
42
+ /** What the hook answered; undefined when it threw. */
43
+ answer?: unknown;
44
+ /** What it threw. */
45
+ error?: string;
46
+ }
47
+
48
+ interface SimulatedMachine {
49
+ name: string;
50
+ managed: boolean;
51
+ ref: string | null;
52
+ enrollment: { code: string; idempotencyKey: string } | null;
53
+ generation: number;
54
+ labels: Readonly<Record<string, string>>;
55
+ for: readonly MachinePrincipal[] | null;
56
+ trusted: boolean;
57
+ options: Readonly<Record<string, unknown>>;
58
+ lostAfterMinutes: number | null;
59
+ reason: string | null;
60
+ phase: MachinePhase;
61
+ phaseSince: number;
62
+ startAskedAt: number | null;
63
+ refused: { count: number; at: number } | null;
64
+ droppedAt: number | null;
65
+ disabledAt: number | null;
66
+ reset: { for: readonly MachinePrincipal[] | null } | null;
67
+ notice: string | null;
68
+ lastError: { verb: MachineVerb; message: string; at: number } | null;
69
+ destroyRequestedAt: number | null;
70
+ revoked: boolean;
71
+ /** Its worker runs and reaches the server. */
72
+ alive: boolean;
73
+ /** When its worker connects, once it boots. */
74
+ connectsAt: number | null;
75
+ lastSeenAt: number | null;
76
+ /** Live workspaces: the work on it. */
77
+ holding: WaitingWork[];
78
+ lastReleasedAt: number | null;
79
+ resets: number;
80
+ }
81
+
82
+ export interface SimulatedWorkOptions {
83
+ hook: MachinesHook;
84
+ /** ISO 8601 start of the simulation's clock. */
85
+ start?: string;
86
+ /** Seconds a created or started machine takes to connect (default 60). */
87
+ bootSeconds?: number;
88
+ /** Workspaces one machine holds at once (default 4). */
89
+ workspacesPerMachine?: number;
90
+ /** How machines isolate agents (default "sandbox"). */
91
+ isolation?: "process" | "sandbox";
92
+ people?: readonly PersonFacts[];
93
+ controlPlaneUrl?: string;
94
+ }
95
+
96
+ /** The simulated Work: machines, work and people in memory, and a clock. */
97
+ export class SimulatedWork {
98
+ /** Every call into the hook, in order. */
99
+ readonly calls: SimulatedCall[] = [];
100
+ /** Every machine event, in order. */
101
+ readonly events: MachineEvent[] = [];
102
+ /** What the latest plan failed with, or null. */
103
+ planError: string | null = null;
104
+ people: PersonFacts[];
105
+ private clock: number;
106
+ // Replica memory (single process): test fixtures are never shared by a server.
107
+ private readonly machines = new Map<string, SimulatedMachine>();
108
+ private waitingWork: WaitingWork[] = [];
109
+ // Replica memory (single process): placement decisions in this simulation.
110
+ private readonly waitingFor = new Map<
111
+ string,
112
+ { name: string; state: "starting" | "resuming" }
113
+ >();
114
+ private workCount = 0;
115
+ private generations = 0;
116
+ // Replica memory (single process): machines that a test keeps disconnected.
117
+ private readonly neverConnect = new Set<string>();
118
+ /** A create whose answer is lost on its way back, once. */
119
+ private answerLost = false;
120
+
121
+ constructor(private readonly options: SimulatedWorkOptions) {
122
+ this.clock = Date.parse(options.start ?? "2026-01-01T00:00:00.000Z");
123
+ this.people = [...(options.people ?? [])];
124
+ }
125
+
126
+ /** The simulation's time (ISO 8601). */
127
+ get now(): string {
128
+ return new Date(this.clock).toISOString();
129
+ }
130
+
131
+ /** Machines as the plan reads them. */
132
+ facts(): MachineFacts[] {
133
+ return this.records().map((record) => record.facts);
134
+ }
135
+
136
+ machine(name: string): MachineFacts | undefined {
137
+ return this.facts().find((machine) => machine.name === name);
138
+ }
139
+
140
+ /** Work still waiting for a machine. */
141
+ waiting(): readonly WaitingWork[] {
142
+ return this.waitingWork;
143
+ }
144
+
145
+ /** The machine being started or resumed for a piece of waiting work. */
146
+ startingFor(
147
+ workId: string,
148
+ ): { name: string; state: "starting" | "resuming" } | undefined {
149
+ return this.waitingFor.get(workId);
150
+ }
151
+
152
+ /** Where a piece of work runs, once it has a machine. */
153
+ placedOn(workId: string): string | undefined {
154
+ for (const machine of this.machines.values())
155
+ if (machine.holding.some((work) => work.id === workId))
156
+ return machine.name;
157
+ return undefined;
158
+ }
159
+
160
+ /** Add work that needs a machine; it waits until one takes it. */
161
+ addWork(
162
+ work: Partial<Omit<WaitingWork, "id">> & { project: string },
163
+ ): WaitingWork {
164
+ this.workCount += 1;
165
+ const added: WaitingWork = {
166
+ id: `work-${this.workCount}`,
167
+ kind: "chat",
168
+ user: null,
169
+ key: null,
170
+ environment: "default",
171
+ pool: {},
172
+ requirements: { resources: {}, capabilities: [] },
173
+ reason: "unavailable",
174
+ waitingSince: this.now,
175
+ ...work,
176
+ };
177
+ this.waitingWork.push(added);
178
+ this.place();
179
+ return added;
180
+ }
181
+
182
+ /** The work ended: its workspace is given back. */
183
+ finishWork(workId: string): void {
184
+ this.waitingWork = this.waitingWork.filter((work) => work.id !== workId);
185
+ for (const machine of this.machines.values()) {
186
+ const before = machine.holding.length;
187
+ machine.holding = machine.holding.filter((work) => work.id !== workId);
188
+ if (machine.holding.length < before) machine.lastReleasedAt = this.clock;
189
+ }
190
+ }
191
+
192
+ /** An operator enrolls a machine by hand; it connects after it boots. */
193
+ enrollByHand(args: {
194
+ name: string;
195
+ for?: readonly MachinePrincipal[];
196
+ labels?: Readonly<Record<string, string>>;
197
+ trusted?: boolean;
198
+ }): void {
199
+ const machine = this.blank({
200
+ name: args.name,
201
+ managed: false,
202
+ for: args.for === undefined ? null : normalizePrincipals(args.for),
203
+ labels: args.labels ?? {},
204
+ trusted: args.trusted ?? false,
205
+ options: {},
206
+ lostAfterMinutes: null,
207
+ reason: null,
208
+ });
209
+ machine.connectsAt = this.clock + this.bootMs;
210
+ this.machines.set(args.name, machine);
211
+ }
212
+
213
+ /** The machine dies: its worker stops calling. Its platform is the test's to end. */
214
+ lose(name: string): void {
215
+ const machine = this.require(name);
216
+ machine.alive = false;
217
+ machine.connectsAt = null;
218
+ }
219
+
220
+ /** A machine that was only unreachable calls again. */
221
+ revive(name: string): void {
222
+ const machine = this.require(name);
223
+ if (machine.phase !== "running" || machine.revoked) return;
224
+ machine.alive = true;
225
+ machine.lastSeenAt = this.clock;
226
+ }
227
+
228
+ /** A machine by this name never connects once created. */
229
+ neverConnects(name: string): void {
230
+ this.neverConnect.add(name);
231
+ }
232
+
233
+ /** An operator disables or enables a machine. */
234
+ setDisabled(name: string, disabled: boolean): void {
235
+ this.require(name).disabledAt = disabled ? this.clock : null;
236
+ }
237
+
238
+ /**
239
+ * The next create's answer is lost on its way back (the server stopped,
240
+ * the network failed): the hook made its machine, and Work must ask again.
241
+ */
242
+ loseNextCreateAnswer(): void {
243
+ this.answerLost = true;
244
+ }
245
+
246
+ /** Move the clock; machines boot, renew, and take waiting work as it passes. */
247
+ advance(args: { seconds?: number; minutes?: number }): void {
248
+ const until =
249
+ this.clock + (args.seconds ?? 0) * 1_000 + (args.minutes ?? 0) * 60_000;
250
+ while (this.clock < until) {
251
+ this.clock = Math.min(until, this.clock + 5_000);
252
+ this.tick();
253
+ }
254
+ this.tick();
255
+ }
256
+
257
+ /** One pass of the real sequencer over the simulation. */
258
+ async pass(): Promise<MachinePassSummary> {
259
+ this.tick();
260
+ const summary = await runMachinePass({
261
+ hook: this.recordingHook(),
262
+ world: this.world(),
263
+ verbTimeoutMs: 5_000,
264
+ planTimeoutMs: 5_000,
265
+ });
266
+ this.tick();
267
+ return summary;
268
+ }
269
+
270
+ /** Passes a few seconds apart until one changes nothing, or `limit` ran. */
271
+ async settle(args: { limit?: number; seconds?: number } = {}): Promise<{
272
+ quiet: boolean;
273
+ passes: MachinePassSummary[];
274
+ }> {
275
+ const passes: MachinePassSummary[] = [];
276
+ for (let index = 0; index < (args.limit ?? 40); index += 1) {
277
+ const before = this.calls.length;
278
+ const summary = await this.pass();
279
+ passes.push(summary);
280
+ const verbs = this.calls
281
+ .slice(before)
282
+ .filter((call) => call.verb !== "describe");
283
+ if (verbs.length === 0 && quietSummary(summary) && !this.transient())
284
+ return { quiet: true, passes };
285
+ this.advance({ seconds: args.seconds ?? 30 });
286
+ }
287
+ return { quiet: false, passes };
288
+ }
289
+
290
+ /** Something is still on its way: a boot, a stop, a destruction. */
291
+ private transient(): boolean {
292
+ return [...this.machines.values()].some(
293
+ (machine) =>
294
+ machine.phase === "stopping" ||
295
+ machine.phase === "destroying" ||
296
+ (machine.phase === "resuming" && machine.alive === false) ||
297
+ (machine.phase === "starting" &&
298
+ machine.connectsAt !== null &&
299
+ !this.neverConnect.has(machine.name)),
300
+ );
301
+ }
302
+
303
+ private get bootMs(): number {
304
+ return (this.options.bootSeconds ?? 60) * 1_000;
305
+ }
306
+
307
+ private require(name: string): SimulatedMachine {
308
+ const machine = this.machines.get(name);
309
+ if (!machine) throw new Error(`The simulation has no machine '${name}'`);
310
+ return machine;
311
+ }
312
+
313
+ private blank(args: {
314
+ name: string;
315
+ managed: boolean;
316
+ for: readonly MachinePrincipal[] | null;
317
+ labels: Readonly<Record<string, string>>;
318
+ trusted: boolean;
319
+ options: Readonly<Record<string, unknown>>;
320
+ lostAfterMinutes: number | null;
321
+ reason: string | null;
322
+ }): SimulatedMachine {
323
+ return {
324
+ ...args,
325
+ ref: null,
326
+ enrollment: null,
327
+ generation: 0,
328
+ phase: "starting",
329
+ phaseSince: this.clock,
330
+ startAskedAt: null,
331
+ refused: null,
332
+ droppedAt: null,
333
+ disabledAt: null,
334
+ reset: null,
335
+ notice: null,
336
+ lastError: null,
337
+ destroyRequestedAt: null,
338
+ revoked: false,
339
+ alive: false,
340
+ connectsAt: null,
341
+ lastSeenAt: null,
342
+ holding: [],
343
+ lastReleasedAt: null,
344
+ resets: 0,
345
+ };
346
+ }
347
+
348
+ private newEnrollment(machine: SimulatedMachine): void {
349
+ this.generations += 1;
350
+ machine.generation = this.generations;
351
+ const code = `wke_simulated_${machine.name}_${this.generations}`;
352
+ machine.enrollment = {
353
+ code,
354
+ idempotencyKey: createHash("sha256").update(code).digest("hex"),
355
+ };
356
+ }
357
+
358
+ private live(machine: SimulatedMachine): boolean {
359
+ return (
360
+ machine.alive &&
361
+ !machine.revoked &&
362
+ machine.disabledAt === null &&
363
+ (machine.phase === "running" || machine.phase === "resuming")
364
+ );
365
+ }
366
+
367
+ /** Boot what is due, renew what is alive, and place waiting work. */
368
+ private tick(): void {
369
+ for (const machine of this.machines.values()) {
370
+ if (
371
+ machine.connectsAt !== null &&
372
+ machine.connectsAt <= this.clock &&
373
+ !this.neverConnect.has(machine.name) &&
374
+ machine.disabledAt === null &&
375
+ (machine.phase === "starting" || machine.phase === "resuming")
376
+ ) {
377
+ const kind =
378
+ machine.phase === "starting"
379
+ ? "machine.connected"
380
+ : "machine.started";
381
+ machine.phase = "running";
382
+ machine.phaseSince = this.clock;
383
+ machine.startAskedAt = null;
384
+ machine.alive = true;
385
+ machine.connectsAt = null;
386
+ this.emit(kind, machine);
387
+ }
388
+ if (this.live(machine)) machine.lastSeenAt = this.clock;
389
+ }
390
+ this.place();
391
+ }
392
+
393
+ private place(): void {
394
+ const capacity = this.options.workspacesPerMachine ?? 4;
395
+ const isolation = this.options.isolation ?? "sandbox";
396
+ this.waitingWork = this.waitingWork.filter((work) => {
397
+ const takers = [...this.machines.values()]
398
+ .filter(
399
+ (machine) =>
400
+ machine.phase === "running" &&
401
+ this.live(machine) &&
402
+ machine.droppedAt === null &&
403
+ machine.reset === null &&
404
+ machine.holding.length < capacity &&
405
+ (machine.trusted ||
406
+ isolation === "sandbox" ||
407
+ (machine.for !== null && machine.for.length === 1)) &&
408
+ machineTakes(machine, work),
409
+ )
410
+ // Narrowest first: a machine for fewer principals before a shared one.
411
+ .sort(
412
+ (left, right) =>
413
+ (left.for?.length ?? Number.POSITIVE_INFINITY) -
414
+ (right.for?.length ?? Number.POSITIVE_INFINITY),
415
+ );
416
+ const taker = takers[0];
417
+ if (!taker) return true;
418
+ taker.holding.push(work);
419
+ this.waitingFor.delete(work.id);
420
+ return false;
421
+ });
422
+ }
423
+
424
+ private emit(kind: MachineEvent["kind"], machine: SimulatedMachine): void {
425
+ const event: MachineEvent = {
426
+ kind,
427
+ at: this.now,
428
+ machine: {
429
+ name: machine.name,
430
+ ref: machine.ref,
431
+ managed: machine.managed,
432
+ labels: machine.labels,
433
+ for: machine.for,
434
+ options: machine.options,
435
+ reason: machine.reason,
436
+ },
437
+ };
438
+ this.events.push(event);
439
+ void Promise.resolve(this.options.hook.onEvent?.(event)).catch(() => {});
440
+ }
441
+
442
+ private records(): MachineRecord[] {
443
+ const capacity = this.options.workspacesPerMachine ?? 4;
444
+ return [...this.machines.values()]
445
+ .sort((left, right) => left.name.localeCompare(right.name))
446
+ .map((machine) => {
447
+ const seen = machine.lastSeenAt ?? machine.phaseSince;
448
+ const state = machineStateOf({
449
+ phase: machine.phase,
450
+ dropped: machine.droppedAt !== null,
451
+ disabled: machine.disabledAt !== null,
452
+ live: this.live(machine),
453
+ unseenForMs: this.clock - seen,
454
+ lostAfterMs: lostAfterMsOf({
455
+ lostAfterMinutes: machine.lostAfterMinutes,
456
+ defaultMinutes: DEFAULT_LOST_AFTER_MINUTES,
457
+ }),
458
+ startAskedForMs:
459
+ machine.startAskedAt === null
460
+ ? null
461
+ : this.clock - machine.startAskedAt,
462
+ });
463
+ const since =
464
+ state === "unreachable" || state === "lost"
465
+ ? machine.phase === "resuming"
466
+ ? (machine.startAskedAt ?? seen)
467
+ : seen
468
+ : state === "disabled"
469
+ ? (machine.disabledAt ?? machine.phaseSince)
470
+ : state === "draining"
471
+ ? (machine.droppedAt ?? machine.phaseSince)
472
+ : machine.phaseSince;
473
+ const connected = machine.phase !== "starting";
474
+ const facts: MachineFacts = {
475
+ name: machine.name,
476
+ ref: machine.ref,
477
+ managed: machine.managed,
478
+ state,
479
+ since: iso(since),
480
+ labels: machine.labels,
481
+ for: machine.for,
482
+ trusted: machine.trusted,
483
+ options: machine.options,
484
+ reason: machine.reason,
485
+ holding: {
486
+ workspaces: machine.holding.length,
487
+ for: normalizePrincipals(
488
+ machine.holding.map((work) =>
489
+ work.user !== null
490
+ ? { user: work.user }
491
+ : work.key !== null
492
+ ? { project: work.project, key: work.key }
493
+ : { project: work.project },
494
+ ),
495
+ ),
496
+ },
497
+ idleSince:
498
+ (state === "serving" || state === "draining") &&
499
+ machine.holding.length === 0
500
+ ? iso(Math.max(machine.phaseSince, machine.lastReleasedAt ?? 0))
501
+ : null,
502
+ lastSeenAt:
503
+ machine.lastSeenAt === null ? null : iso(machine.lastSeenAt),
504
+ capacity: connected ? { workspaces: capacity } : null,
505
+ usage: connected
506
+ ? {
507
+ workspaces: machine.holding.length,
508
+ cpuMillis: 0,
509
+ memoryMb: 0,
510
+ storageMb: 0,
511
+ }
512
+ : null,
513
+ disk: null,
514
+ isolation: connected ? (this.options.isolation ?? "sandbox") : null,
515
+ signedIn: [],
516
+ notice: machine.notice,
517
+ lastError: machine.lastError
518
+ ? {
519
+ verb: machine.lastError.verb,
520
+ message: machine.lastError.message,
521
+ at: iso(machine.lastError.at),
522
+ }
523
+ : null,
524
+ };
525
+ return {
526
+ facts,
527
+ phase: machine.phase,
528
+ phaseSince: iso(machine.phaseSince),
529
+ idempotencyKey: machine.enrollment?.idempotencyKey ?? null,
530
+ dropped: machine.droppedAt !== null,
531
+ refused: machine.refused
532
+ ? { count: machine.refused.count, at: iso(machine.refused.at) }
533
+ : null,
534
+ reset: machine.reset,
535
+ startAsked: machine.startAskedAt !== null,
536
+ destroyRequestedAt:
537
+ machine.destroyRequestedAt === null
538
+ ? null
539
+ : iso(machine.destroyRequestedAt),
540
+ lostAfterMinutes: machine.lostAfterMinutes,
541
+ revoked: machine.revoked,
542
+ };
543
+ });
544
+ }
545
+
546
+ /** The hook, with every call recorded and a lost answer simulated. */
547
+ private recordingHook(): MachinesHook {
548
+ const { hook } = this.options;
549
+ const record = async <T>(
550
+ call: Pick<SimulatedCall, "verb" | "name" | "ref" | "idempotencyKey">,
551
+ run: () => Promise<T>,
552
+ ): Promise<T> => {
553
+ const entry: SimulatedCall = { ...call, at: this.now };
554
+ this.calls.push(entry);
555
+ try {
556
+ const answer = await run();
557
+ entry.answer = answer;
558
+ return answer;
559
+ } catch (error) {
560
+ entry.error = error instanceof Error ? error.message : String(error);
561
+ throw error;
562
+ }
563
+ };
564
+ const target = (args: {
565
+ name: string;
566
+ ref: string | null;
567
+ idempotencyKey: string | null;
568
+ }) => ({
569
+ name: args.name,
570
+ ref: args.ref,
571
+ idempotencyKey: args.idempotencyKey,
572
+ });
573
+ const stop = hook.stop?.bind(hook);
574
+ const start = hook.start?.bind(hook);
575
+ const describe = hook.describe?.bind(hook);
576
+ return {
577
+ plan: (facts) => hook.plan(facts),
578
+ create: async (request) => {
579
+ const entry: SimulatedCall = {
580
+ verb: "create",
581
+ name: request.name,
582
+ ref: null,
583
+ idempotencyKey: request.enrollment.idempotencyKey,
584
+ at: this.now,
585
+ };
586
+ this.calls.push(entry);
587
+ const answer = await hook.create(request).catch((error: unknown) => {
588
+ entry.error = error instanceof Error ? error.message : String(error);
589
+ throw error;
590
+ });
591
+ entry.answer = answer;
592
+ if (this.answerLost) {
593
+ // The hook answered (and may have made its machine); Work never
594
+ // heard it.
595
+ this.answerLost = false;
596
+ entry.error = "simulated: the answer was lost on its way back";
597
+ throw new Error(
598
+ "simulated: the answer to create was lost on its way back",
599
+ );
600
+ }
601
+ return answer;
602
+ },
603
+ destroy: (args) =>
604
+ record({ verb: "destroy", ...target(args) }, () => hook.destroy(args)),
605
+ ...(stop
606
+ ? {
607
+ stop: (args) =>
608
+ record({ verb: "stop", ...target(args) }, () => stop(args)),
609
+ }
610
+ : {}),
611
+ ...(start
612
+ ? {
613
+ start: (args) =>
614
+ record({ verb: "start", ...target(args) }, () => start(args)),
615
+ }
616
+ : {}),
617
+ ...(describe
618
+ ? {
619
+ describe: (args) =>
620
+ record({ verb: "describe", ...target(args) }, () =>
621
+ describe(args),
622
+ ),
623
+ }
624
+ : {}),
625
+ };
626
+ }
627
+
628
+ private world(): MachineWorld {
629
+ const set = (name: string, change: (machine: SimulatedMachine) => void) => {
630
+ const machine = this.machines.get(name);
631
+ if (machine) change(machine);
632
+ };
633
+ const phase = (machine: SimulatedMachine, next: MachinePhase) => {
634
+ machine.phase = next;
635
+ machine.phaseSince = this.clock;
636
+ machine.startAskedAt = null;
637
+ };
638
+ /** Revoke its worker and begin destroying it. */
639
+ const condemn = (machine: SimulatedMachine) => {
640
+ phase(machine, "destroying");
641
+ machine.destroyRequestedAt ??= this.clock;
642
+ machine.revoked = true;
643
+ machine.alive = false;
644
+ machine.connectsAt = null;
645
+ // Its work is retired: its chats wait for another machine.
646
+ for (const work of machine.holding)
647
+ this.waitingWork.push({ ...work, waitingSince: this.now });
648
+ machine.holding = [];
649
+ };
650
+ return {
651
+ controlPlaneUrl:
652
+ this.options.controlPlaneUrl ?? "https://work.example.test",
653
+ now: async () => this.now,
654
+ records: async () => this.records(),
655
+ work: async () => [...this.waitingWork],
656
+ people: async () => [...this.people],
657
+ intend: async ({ machine: planned }: { machine: PlannedMachine }) => {
658
+ if (this.machines.has(planned.name)) return false;
659
+ const machine = this.blank({
660
+ name: planned.name,
661
+ managed: true,
662
+ for: planned.for,
663
+ labels: planned.labels,
664
+ trusted: planned.trusted,
665
+ options: planned.options,
666
+ lostAfterMinutes: planned.lostAfterMinutes,
667
+ reason: planned.reason,
668
+ });
669
+ this.newEnrollment(machine);
670
+ this.machines.set(planned.name, machine);
671
+ return true;
672
+ },
673
+ enrollment: async ({ name }) =>
674
+ this.machines.get(name)?.enrollment ?? null,
675
+ reissue: async ({ name }) =>
676
+ set(name, (machine) => {
677
+ if (
678
+ machine.managed &&
679
+ !machine.enrollment &&
680
+ machine.phase === "starting"
681
+ )
682
+ this.newEnrollment(machine);
683
+ }),
684
+ created: async ({ name, ref }) =>
685
+ set(name, (machine) => {
686
+ machine.ref = ref;
687
+ machine.refused = null;
688
+ if (machine.phase === "starting")
689
+ machine.connectsAt ??= this.clock + this.bootMs;
690
+ }),
691
+ refused: async ({ name, reason }) =>
692
+ set(name, (machine) => {
693
+ machine.enrollment = null;
694
+ machine.refused = {
695
+ count: (machine.refused?.count ?? 0) + 1,
696
+ at: this.clock,
697
+ };
698
+ machine.lastError = {
699
+ verb: "create",
700
+ message: `Its platform refused: ${reason}`,
701
+ at: this.clock,
702
+ };
703
+ }),
704
+ configure: async ({ name, ...settings }) =>
705
+ set(name, (machine) => {
706
+ machine.labels = settings.labels;
707
+ machine.trusted = settings.trusted;
708
+ machine.reason = settings.reason;
709
+ machine.lostAfterMinutes = settings.lostAfterMinutes;
710
+ }),
711
+ setFor: async ({ name, for: principals }) =>
712
+ set(name, (machine) => {
713
+ machine.for = principals;
714
+ machine.reset = null;
715
+ }),
716
+ beginReset: async ({ name, for: principals }) =>
717
+ set(name, (machine) => {
718
+ machine.reset = { for: principals };
719
+ }),
720
+ reset: async ({ name }) => {
721
+ const machine = this.require(name);
722
+ if (!this.live(machine)) return "offline";
723
+ if (machine.holding.length > 0) return "busy";
724
+ machine.for = machine.reset?.for ?? machine.for;
725
+ machine.reset = null;
726
+ machine.resets += 1;
727
+ return "done";
728
+ },
729
+ drop: async ({ name }) =>
730
+ set(name, (machine) => {
731
+ machine.droppedAt ??= this.clock;
732
+ }),
733
+ undrop: async ({ name }) =>
734
+ set(name, (machine) => {
735
+ machine.droppedAt = null;
736
+ }),
737
+ retire: async ({ name }) => {
738
+ const machine = this.require(name);
739
+ if (machine.holding.length > 0 && !machine.revoked) return false;
740
+ condemn(machine);
741
+ return true;
742
+ },
743
+ declareLost: async ({ name, unseenForMs }) => {
744
+ const machine = this.require(name);
745
+ if (this.live(machine) && machine.phase === "running") return false;
746
+ const seen = machine.lastSeenAt ?? machine.phaseSince;
747
+ if (machine.phase === "running" && this.clock - seen < unseenForMs)
748
+ return false;
749
+ condemn(machine);
750
+ return true;
751
+ },
752
+ beginStop: async ({ name }) => {
753
+ const machine = this.require(name);
754
+ if (machine.holding.length > 0 || machine.phase !== "running")
755
+ return false;
756
+ phase(machine, "stopping");
757
+ return true;
758
+ },
759
+ stopped: async ({ name }) =>
760
+ set(name, (machine) => {
761
+ phase(machine, "stopped");
762
+ machine.alive = false;
763
+ }),
764
+ beginResume: async ({ name }) => {
765
+ const machine = this.require(name);
766
+ if (machine.phase !== "stopped") return false;
767
+ phase(machine, "resuming");
768
+ return true;
769
+ },
770
+ startAsked: async ({ name }) =>
771
+ set(name, (machine) => {
772
+ machine.startAskedAt = this.clock;
773
+ machine.connectsAt = this.clock + this.bootMs;
774
+ }),
775
+ forget: async ({ name }) => {
776
+ this.machines.delete(name);
777
+ },
778
+ note: async ({ name, notice }) =>
779
+ set(name, (machine) => {
780
+ machine.notice = notice;
781
+ }),
782
+ failed: async ({ name, verb, message }) =>
783
+ set(name, (machine) => {
784
+ machine.lastError = { verb, message, at: this.clock };
785
+ }),
786
+ succeeded: async ({ name, verb }) =>
787
+ set(name, (machine) => {
788
+ if (machine.lastError?.verb === verb) machine.lastError = null;
789
+ }),
790
+ event: async (event) => {
791
+ this.events.push(event);
792
+ await Promise.resolve(this.options.hook.onEvent?.(event)).catch(
793
+ () => {},
794
+ );
795
+ },
796
+ planned: async ({ error }) => {
797
+ this.planError = error;
798
+ },
799
+ waiting: async ({ machines }) => {
800
+ this.waitingFor.clear();
801
+ for (const [work, machine] of machines)
802
+ this.waitingFor.set(work, machine);
803
+ },
804
+ };
805
+ }
806
+
807
+ /** How often a machine was reset before its principals changed. */
808
+ resetsOf(name: string): number {
809
+ return this.machines.get(name)?.resets ?? 0;
810
+ }
811
+ }
812
+
813
+ function iso(time: number): string {
814
+ return new Date(time).toISOString();
815
+ }
816
+
817
+ /** A pass that changed nothing and failed at nothing. */
818
+ export function quietSummary(summary: MachinePassSummary): boolean {
819
+ return (
820
+ summary.planError === undefined &&
821
+ summary.created.length +
822
+ summary.updated.length +
823
+ summary.reset.length +
824
+ summary.released.length +
825
+ summary.lost.length +
826
+ summary.stopped.length +
827
+ summary.resumed.length +
828
+ summary.destroying.length +
829
+ summary.destroyed.length +
830
+ summary.failed.length ===
831
+ 0
832
+ );
833
+ }