@catamorphic/work-server 0.1.0-alpha.42 → 0.1.0-alpha.44

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 (74) hide show
  1. package/README.md +4 -1
  2. package/dist/agents.d.ts.map +1 -1
  3. package/dist/{chunk-kcck20aw.js → chunk-ynxz0am9.js} +80 -9
  4. package/dist/chunk-ynxz0am9.js.map +11 -0
  5. package/dist/cluster.d.ts +19 -1
  6. package/dist/cluster.d.ts.map +1 -1
  7. package/dist/execution-config.d.ts +2 -1
  8. package/dist/execution-config.d.ts.map +1 -1
  9. package/dist/index.d.ts +2 -2
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +962 -268
  12. package/dist/index.js.map +21 -19
  13. package/dist/machines/contract.d.ts +138 -14
  14. package/dist/machines/contract.d.ts.map +1 -1
  15. package/dist/machines/sequencer.d.ts +33 -6
  16. package/dist/machines/sequencer.d.ts.map +1 -1
  17. package/dist/machines/simulation.d.ts +64 -0
  18. package/dist/machines/simulation.d.ts.map +1 -1
  19. package/dist/machines/work-machines.d.ts +40 -2
  20. package/dist/machines/work-machines.d.ts.map +1 -1
  21. package/dist/server.d.ts +11 -1
  22. package/dist/server.d.ts.map +1 -1
  23. package/dist/testing.d.ts +1 -1
  24. package/dist/testing.d.ts.map +1 -1
  25. package/dist/testing.js +208 -17
  26. package/dist/testing.js.map +4 -4
  27. package/dist/workers/cache-archive-routes.d.ts +24 -0
  28. package/dist/workers/cache-archive-routes.d.ts.map +1 -0
  29. package/dist/workers/disk-care.d.ts +36 -1
  30. package/dist/workers/disk-care.d.ts.map +1 -1
  31. package/dist/workers/harness-sign-ins.d.ts +32 -1
  32. package/dist/workers/harness-sign-ins.d.ts.map +1 -1
  33. package/dist/workers/machine-store.d.ts +37 -0
  34. package/dist/workers/machine-store.d.ts.map +1 -1
  35. package/dist/workers/member-machine-routes.d.ts +3 -0
  36. package/dist/workers/member-machine-routes.d.ts.map +1 -1
  37. package/dist/workers/member-machines.d.ts +52 -5
  38. package/dist/workers/member-machines.d.ts.map +1 -1
  39. package/dist/workers/placement.d.ts +10 -0
  40. package/dist/workers/placement.d.ts.map +1 -1
  41. package/dist/workers/sign-in-store.d.ts +67 -0
  42. package/dist/workers/sign-in-store.d.ts.map +1 -0
  43. package/dist/workers/sign-ins.d.ts +4 -6
  44. package/dist/workers/sign-ins.d.ts.map +1 -1
  45. package/dist/workers/worker-protocol.d.ts +9 -1
  46. package/dist/workers/worker-protocol.d.ts.map +1 -1
  47. package/dist/workers/worker-registry.d.ts +20 -6
  48. package/dist/workers/worker-registry.d.ts.map +1 -1
  49. package/dist/workers/worker-runtime.d.ts.map +1 -1
  50. package/package.json +18 -19
  51. package/src/agents.ts +5 -0
  52. package/src/cluster.ts +62 -7
  53. package/src/execution-config.ts +2 -1
  54. package/src/index.ts +7 -0
  55. package/src/machines/contract-kit.ts +1 -1
  56. package/src/machines/contract.ts +191 -19
  57. package/src/machines/sequencer.ts +106 -11
  58. package/src/machines/simulation.ts +370 -20
  59. package/src/machines/work-machines.ts +71 -3
  60. package/src/server.ts +120 -29
  61. package/src/testing.ts +1 -0
  62. package/src/workers/cache-archive-routes.ts +125 -0
  63. package/src/workers/disk-care.ts +157 -6
  64. package/src/workers/harness-sign-ins.ts +207 -22
  65. package/src/workers/machine-store.ts +341 -58
  66. package/src/workers/member-machine-routes.ts +58 -3
  67. package/src/workers/member-machines.ts +168 -14
  68. package/src/workers/placement.ts +7 -0
  69. package/src/workers/sign-in-store.ts +241 -0
  70. package/src/workers/sign-ins.ts +9 -33
  71. package/src/workers/worker-protocol.ts +9 -1
  72. package/src/workers/worker-registry.ts +47 -6
  73. package/src/workers/worker-runtime.ts +9 -3
  74. package/dist/chunk-kcck20aw.js.map +0 -11
@@ -3,11 +3,14 @@ import {
3
3
  DEFAULT_LOST_AFTER_MINUTES,
4
4
  type MachineEvent,
5
5
  type MachineFacts,
6
+ type MachinePreparation,
6
7
  type MachinePrincipal,
7
8
  type MachinesHook,
8
9
  type MachineVerb,
9
10
  normalizePrincipals,
10
11
  type PersonFacts,
12
+ preparedFor,
13
+ SIGN_IN_WAIT_MINUTES,
11
14
  type WaitingWork,
12
15
  } from "./contract.js";
13
16
  import {
@@ -28,7 +31,10 @@ import {
28
31
  * test moves. A machine the hook's `create` answered for boots and
29
32
  * connects by itself after `bootSeconds`; a test places work, ends it,
30
33
  * 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.
34
+ * asked to do. A machine the hook prepares for an Environment is prepared
35
+ * after `prepareSeconds`, and a chat placed on a machine that is not pays
36
+ * for the image and the caches itself, which {@link SimulatedWork.startOf}
37
+ * tells. No server, database or cloud is involved.
32
38
  */
33
39
 
34
40
  /** One call the simulated Work made into the hook. */
@@ -45,6 +51,31 @@ export interface SimulatedCall {
45
51
  error?: string;
46
52
  }
47
53
 
54
+ /** How a piece of work started on its machine. */
55
+ export interface SimulatedStart {
56
+ machine: string;
57
+ /** ISO 8601, by the simulation's clock. */
58
+ at: string;
59
+ /**
60
+ * What its own preparation had to do there: build or pull the
61
+ * Environment's image, fill its caches. Both false on a machine prepared
62
+ * for its Environment.
63
+ */
64
+ imageBuilt: boolean;
65
+ cachesFilled: boolean;
66
+ }
67
+
68
+ interface SimulatedPreparation {
69
+ project: string;
70
+ environment: string;
71
+ status: MachinePreparation["status"];
72
+ commit: string | null;
73
+ error: string | null;
74
+ since: number;
75
+ /** When it is prepared, while it is preparing. */
76
+ readyAt: number | null;
77
+ }
78
+
48
79
  interface SimulatedMachine {
49
80
  name: string;
50
81
  managed: boolean;
@@ -53,6 +84,11 @@ interface SimulatedMachine {
53
84
  generation: number;
54
85
  labels: Readonly<Record<string, string>>;
55
86
  for: readonly MachinePrincipal[] | null;
87
+ spare: boolean;
88
+ project: string | null;
89
+ preparations: SimulatedPreparation[];
90
+ /** Its worker connected and `onConnected` has not heard yet. */
91
+ connectedPending: boolean;
56
92
  trusted: boolean;
57
93
  options: Readonly<Record<string, unknown>>;
58
94
  lostAfterMinutes: number | null;
@@ -73,18 +109,41 @@ interface SimulatedMachine {
73
109
  /** When its worker connects, once it boots. */
74
110
  connectsAt: number | null;
75
111
  lastSeenAt: number | null;
76
- /** Live workspaces: the work on it. */
77
- holding: WaitingWork[];
112
+ /** Its workspaces: the work on it, busy, quiet or stopped (ADR 0361). */
113
+ holding: HeldWorkspace[];
78
114
  lastReleasedAt: number | null;
79
115
  resets: number;
80
116
  }
81
117
 
118
+ /**
119
+ * A workspace a machine holds (ADR 0361): `busy` while its chat works,
120
+ * `quiet` once its turn ended and nobody uses it, `stopped` once its
121
+ * machine stopped with it. A stopped one keeps its reservation.
122
+ */
123
+ interface HeldWorkspace {
124
+ work: WaitingWork;
125
+ state: "busy" | "quiet" | "stopped";
126
+ /** When it became quiet. */
127
+ quietAt: number | null;
128
+ }
129
+
82
130
  export interface SimulatedWorkOptions {
83
131
  hook: MachinesHook;
84
132
  /** ISO 8601 start of the simulation's clock. */
85
133
  start?: string;
86
134
  /** Seconds a created or started machine takes to connect (default 60). */
87
135
  bootSeconds?: number;
136
+ /**
137
+ * Seconds a preparation takes: the image build and the cache fills
138
+ * (default 600).
139
+ */
140
+ prepareSeconds?: number;
141
+ /** A preparation that fails, with this error, instead of finishing. */
142
+ failPreparation?: (args: {
143
+ machine: string;
144
+ project: string;
145
+ environment: string;
146
+ }) => string | undefined;
88
147
  /** Workspaces one machine holds at once (default 4). */
89
148
  workspacesPerMachine?: number;
90
149
  /** How machines isolate agents (default "sandbox"). */
@@ -111,6 +170,8 @@ export class SimulatedWork {
111
170
  string,
112
171
  { name: string; state: "starting" | "resuming" }
113
172
  >();
173
+ // Replica memory (single process): how each piece of work started here.
174
+ private readonly starts = new Map<string, SimulatedStart>();
114
175
  private workCount = 0;
115
176
  private generations = 0;
116
177
  // Replica memory (single process): machines that a test keeps disconnected.
@@ -152,11 +213,19 @@ export class SimulatedWork {
152
213
  /** Where a piece of work runs, once it has a machine. */
153
214
  placedOn(workId: string): string | undefined {
154
215
  for (const machine of this.machines.values())
155
- if (machine.holding.some((work) => work.id === workId))
216
+ if (machine.holding.some((held) => held.work.id === workId))
156
217
  return machine.name;
157
218
  return undefined;
158
219
  }
159
220
 
221
+ /**
222
+ * How a piece of work started: on which machine, and whether its own
223
+ * preparation built the image or filled the caches there.
224
+ */
225
+ startOf(workId: string): SimulatedStart | undefined {
226
+ return this.starts.get(workId);
227
+ }
228
+
160
229
  /** Add work that needs a machine; it waits until one takes it. */
161
230
  addWork(
162
231
  work: Partial<Omit<WaitingWork, "id">> & { project: string },
@@ -172,6 +241,7 @@ export class SimulatedWork {
172
241
  requirements: { resources: {}, capabilities: [] },
173
242
  reason: "unavailable",
174
243
  waitingSince: this.now,
244
+ machine: null,
175
245
  ...work,
176
246
  };
177
247
  this.waitingWork.push(added);
@@ -184,11 +254,83 @@ export class SimulatedWork {
184
254
  this.waitingWork = this.waitingWork.filter((work) => work.id !== workId);
185
255
  for (const machine of this.machines.values()) {
186
256
  const before = machine.holding.length;
187
- machine.holding = machine.holding.filter((work) => work.id !== workId);
257
+ machine.holding = machine.holding.filter(
258
+ (held) => held.work.id !== workId,
259
+ );
188
260
  if (machine.holding.length < before) machine.lastReleasedAt = this.clock;
189
261
  }
190
262
  }
191
263
 
264
+ /**
265
+ * The work's turn ended and nobody uses its workspace (ADR 0361): the
266
+ * machine keeps it, quiet, and may stop with it.
267
+ */
268
+ quietWork(workId: string): void {
269
+ const held = this.heldWorkspace(workId);
270
+ if (held?.state !== "busy") return;
271
+ held.state = "quiet";
272
+ held.quietAt = this.clock;
273
+ }
274
+
275
+ /**
276
+ * The work's chat works again in its kept workspace (ADR 0361): a quiet
277
+ * one is busy at once; a stopped one is woken while its machine serves,
278
+ * or waits for that machine by name.
279
+ */
280
+ workAgain(workId: string): void {
281
+ const machine = [...this.machines.values()].find((candidate) =>
282
+ candidate.holding.some((held) => held.work.id === workId),
283
+ );
284
+ const held = this.heldWorkspace(workId);
285
+ if (!machine || !held || held.state === "busy") return;
286
+ if (held.state === "quiet" || this.serves(machine)) {
287
+ held.state = "busy";
288
+ held.quietAt = null;
289
+ return;
290
+ }
291
+ if (this.waitingWork.some((work) => work.id === workId)) return;
292
+ this.waitingWork.push({
293
+ ...held.work,
294
+ reason: "unavailable",
295
+ machine: machine.name,
296
+ waitingSince: this.now,
297
+ });
298
+ }
299
+
300
+ private heldWorkspace(workId: string): HeldWorkspace | undefined {
301
+ for (const machine of this.machines.values()) {
302
+ const held = machine.holding.find((entry) => entry.work.id === workId);
303
+ if (held) return held;
304
+ }
305
+ return undefined;
306
+ }
307
+
308
+ /** It takes work now: running, live, and neither dropped nor being reset. */
309
+ private serves(machine: SimulatedMachine): boolean {
310
+ return (
311
+ machine.phase === "running" &&
312
+ this.live(machine) &&
313
+ machine.droppedAt === null &&
314
+ machine.reset === null
315
+ );
316
+ }
317
+
318
+ /**
319
+ * A machine's stopped workspaces go with it (ADR 0361): work waiting for
320
+ * it waits for any machine open to it instead. A sign-in stays for its
321
+ * member's machine (ADR 0363).
322
+ */
323
+ private forgetStopped(machine: SimulatedMachine): void {
324
+ machine.holding = machine.holding.filter(
325
+ (held) => held.state !== "stopped",
326
+ );
327
+ this.waitingWork = this.waitingWork.map((work) =>
328
+ work.machine === machine.name && work.kind !== "sign-in"
329
+ ? { ...work, machine: null }
330
+ : work,
331
+ );
332
+ }
333
+
192
334
  /** An operator enrolls a machine by hand; it connects after it boots. */
193
335
  enrollByHand(args: {
194
336
  name: string;
@@ -199,6 +341,8 @@ export class SimulatedWork {
199
341
  const machine = this.blank({
200
342
  name: args.name,
201
343
  managed: false,
344
+ spare: false,
345
+ project: null,
202
346
  for: args.for === undefined ? null : normalizePrincipals(args.for),
203
347
  labels: args.labels ?? {},
204
348
  trusted: args.trusted ?? false,
@@ -235,6 +379,27 @@ export class SimulatedWork {
235
379
  this.require(name).disabledAt = disabled ? this.clock : null;
236
380
  }
237
381
 
382
+ /**
383
+ * A member begins a sign-in on a stopped machine of their own (ADR
384
+ * 0363): work for exactly that machine, which it takes once it serves
385
+ * (the app begins the sign-in again there). It holds no workspace, and
386
+ * after {@link SIGN_IN_WAIT_MINUTES} it waits no more.
387
+ */
388
+ beginSignIn(args: {
389
+ machine: string;
390
+ member: string;
391
+ project: string;
392
+ environment?: string;
393
+ }): WaitingWork {
394
+ return this.addWork({
395
+ kind: "sign-in",
396
+ machine: args.machine,
397
+ user: args.member,
398
+ project: args.project,
399
+ ...(args.environment ? { environment: args.environment } : {}),
400
+ });
401
+ }
402
+
238
403
  /**
239
404
  * The next create's answer is lost on its way back (the server stopped,
240
405
  * the network failed): the hook made its machine, and Work must ask again.
@@ -296,7 +461,10 @@ export class SimulatedWork {
296
461
  (machine.phase === "resuming" && machine.alive === false) ||
297
462
  (machine.phase === "starting" &&
298
463
  machine.connectsAt !== null &&
299
- !this.neverConnect.has(machine.name)),
464
+ !this.neverConnect.has(machine.name)) ||
465
+ (machine.connectedPending && this.live(machine)) ||
466
+ (this.live(machine) &&
467
+ machine.preparations.some((entry) => entry.status === "preparing")),
300
468
  );
301
469
  }
302
470
 
@@ -314,6 +482,8 @@ export class SimulatedWork {
314
482
  name: string;
315
483
  managed: boolean;
316
484
  for: readonly MachinePrincipal[] | null;
485
+ spare: boolean;
486
+ project: string | null;
317
487
  labels: Readonly<Record<string, string>>;
318
488
  trusted: boolean;
319
489
  options: Readonly<Record<string, unknown>>;
@@ -322,6 +492,8 @@ export class SimulatedWork {
322
492
  }): SimulatedMachine {
323
493
  return {
324
494
  ...args,
495
+ preparations: [],
496
+ connectedPending: false,
325
497
  ref: null,
326
498
  enrollment: null,
327
499
  generation: 0,
@@ -383,9 +555,28 @@ export class SimulatedWork {
383
555
  machine.startAskedAt = null;
384
556
  machine.alive = true;
385
557
  machine.connectsAt = null;
558
+ machine.connectedPending = true;
386
559
  this.emit(kind, machine);
387
560
  }
388
561
  if (this.live(machine)) machine.lastSeenAt = this.clock;
562
+ // A preparation ends once its image is built and its caches filled.
563
+ for (const preparation of machine.preparations)
564
+ if (
565
+ preparation.status === "preparing" &&
566
+ preparation.readyAt !== null &&
567
+ preparation.readyAt <= this.clock &&
568
+ this.live(machine)
569
+ ) {
570
+ const error = this.options.failPreparation?.({
571
+ machine: machine.name,
572
+ project: preparation.project,
573
+ environment: preparation.environment,
574
+ });
575
+ preparation.status = error === undefined ? "prepared" : "failed";
576
+ preparation.error = error ?? null;
577
+ preparation.since = this.clock;
578
+ preparation.readyAt = null;
579
+ }
389
580
  }
390
581
  this.place();
391
582
  }
@@ -393,7 +584,39 @@ export class SimulatedWork {
393
584
  private place(): void {
394
585
  const capacity = this.options.workspacesPerMachine ?? 4;
395
586
  const isolation = this.options.isolation ?? "sandbox";
587
+ // A sign-in that waited its time is no reason for a machine.
588
+ this.waitingWork = this.waitingWork.filter(
589
+ (work) =>
590
+ work.kind !== "sign-in" ||
591
+ this.clock - Date.parse(work.waitingSince) <
592
+ SIGN_IN_WAIT_MINUTES * 60_000,
593
+ );
396
594
  this.waitingWork = this.waitingWork.filter((work) => {
595
+ // A sign-in needs its machine serving (ADR 0363).
596
+ if (work.kind === "sign-in") {
597
+ const machine = work.machine ? this.machines.get(work.machine) : null;
598
+ if (!machine || !this.serves(machine) || !machineTakes(machine, work))
599
+ return true;
600
+ this.starts.set(work.id, {
601
+ machine: machine.name,
602
+ at: this.now,
603
+ imageBuilt: false,
604
+ cachesFilled: false,
605
+ });
606
+ this.waitingFor.delete(work.id);
607
+ return false;
608
+ }
609
+ // Its stopped workspace is woken where it is kept (ADR 0361).
610
+ if (work.machine !== null) {
611
+ const keeper = this.machines.get(work.machine);
612
+ const held = keeper?.holding.find((entry) => entry.work.id === work.id);
613
+ if (!keeper || !held) return true;
614
+ if (!this.serves(keeper)) return true;
615
+ held.state = "busy";
616
+ held.quietAt = null;
617
+ this.waitingFor.delete(work.id);
618
+ return false;
619
+ }
397
620
  const takers = [...this.machines.values()]
398
621
  .filter(
399
622
  (machine) =>
@@ -407,20 +630,54 @@ export class SimulatedWork {
407
630
  (machine.for !== null && machine.for.length === 1)) &&
408
631
  machineTakes(machine, work),
409
632
  )
410
- // Narrowest first: a machine for fewer principals before a shared one.
633
+ // Narrowest first: a machine for fewer principals before a shared
634
+ // one; among those, one prepared for the work's Environment.
411
635
  .sort(
412
636
  (left, right) =>
413
637
  (left.for?.length ?? Number.POSITIVE_INFINITY) -
414
- (right.for?.length ?? Number.POSITIVE_INFINITY),
638
+ (right.for?.length ?? Number.POSITIVE_INFINITY) ||
639
+ Number(this.warm(right, work)) - Number(this.warm(left, work)),
415
640
  );
416
641
  const taker = takers[0];
417
642
  if (!taker) return true;
418
- taker.holding.push(work);
643
+ const warm = this.warm(taker, work);
644
+ taker.holding.push({ work, state: "busy", quietAt: null });
645
+ // A spare is handed to the first chat key placed on it, in the step
646
+ // that places the chat (ADR 0360): no second key lands there.
647
+ if (taker.spare && work.key !== null && work.kind !== "fill") {
648
+ taker.for = [{ project: work.project, key: work.key }];
649
+ taker.spare = false;
650
+ }
651
+ this.starts.set(work.id, {
652
+ machine: taker.name,
653
+ at: this.now,
654
+ imageBuilt: !warm,
655
+ cachesFilled: !warm,
656
+ });
419
657
  this.waitingFor.delete(work.id);
420
658
  return false;
421
659
  });
422
660
  }
423
661
 
662
+ private warm(machine: SimulatedMachine, work: WaitingWork): boolean {
663
+ return preparedFor({
664
+ machine: { preparations: this.preparationsOf(machine) },
665
+ project: work.project,
666
+ environment: work.environment,
667
+ });
668
+ }
669
+
670
+ private preparationsOf(machine: SimulatedMachine): MachinePreparation[] {
671
+ return machine.preparations.map((preparation) => ({
672
+ project: preparation.project,
673
+ environment: preparation.environment,
674
+ status: preparation.status,
675
+ commit: preparation.commit,
676
+ error: preparation.error,
677
+ since: iso(preparation.since),
678
+ }));
679
+ }
680
+
424
681
  private emit(kind: MachineEvent["kind"], machine: SimulatedMachine): void {
425
682
  const event: MachineEvent = {
426
683
  kind,
@@ -431,6 +688,7 @@ export class SimulatedWork {
431
688
  managed: machine.managed,
432
689
  labels: machine.labels,
433
690
  for: machine.for,
691
+ project: machine.project,
434
692
  options: machine.options,
435
693
  reason: machine.reason,
436
694
  },
@@ -471,6 +729,7 @@ export class SimulatedWork {
471
729
  ? (machine.droppedAt ?? machine.phaseSince)
472
730
  : machine.phaseSince;
473
731
  const connected = machine.phase !== "starting";
732
+ const live = machine.holding.filter((held) => held.state !== "stopped");
474
733
  const facts: MachineFacts = {
475
734
  name: machine.name,
476
735
  ref: machine.ref,
@@ -479,13 +738,17 @@ export class SimulatedWork {
479
738
  since: iso(since),
480
739
  labels: machine.labels,
481
740
  for: machine.for,
741
+ spare: machine.spare,
742
+ project: machine.project,
743
+ preparations: this.preparationsOf(machine),
482
744
  trusted: machine.trusted,
483
745
  options: machine.options,
484
746
  reason: machine.reason,
485
747
  holding: {
486
- workspaces: machine.holding.length,
748
+ workspaces: live.length,
749
+ stopped: machine.holding.length - live.length,
487
750
  for: normalizePrincipals(
488
- machine.holding.map((work) =>
751
+ live.map(({ work }) =>
489
752
  work.user !== null
490
753
  ? { user: work.user }
491
754
  : work.key !== null
@@ -494,10 +757,16 @@ export class SimulatedWork {
494
757
  ),
495
758
  ),
496
759
  },
497
- idleSince:
760
+ quietSince:
498
761
  (state === "serving" || state === "draining") &&
499
- machine.holding.length === 0
500
- ? iso(Math.max(machine.phaseSince, machine.lastReleasedAt ?? 0))
762
+ live.every((held) => held.state === "quiet")
763
+ ? iso(
764
+ Math.max(
765
+ machine.phaseSince,
766
+ machine.lastReleasedAt ?? 0,
767
+ ...live.map((held) => held.quietAt ?? 0),
768
+ ),
769
+ )
501
770
  : null,
502
771
  lastSeenAt:
503
772
  machine.lastSeenAt === null ? null : iso(machine.lastSeenAt),
@@ -539,6 +808,7 @@ export class SimulatedWork {
539
808
  : iso(machine.destroyRequestedAt),
540
809
  lostAfterMinutes: machine.lostAfterMinutes,
541
810
  revoked: machine.revoked,
811
+ connectedPending: machine.connectedPending,
542
812
  };
543
813
  });
544
814
  }
@@ -573,8 +843,25 @@ export class SimulatedWork {
573
843
  const stop = hook.stop?.bind(hook);
574
844
  const start = hook.start?.bind(hook);
575
845
  const describe = hook.describe?.bind(hook);
846
+ const onConnected = hook.onConnected?.bind(hook);
576
847
  return {
577
848
  plan: (facts) => hook.plan(facts),
849
+ ...(onConnected
850
+ ? {
851
+ onConnected: (args) =>
852
+ record(
853
+ {
854
+ verb: "onConnected",
855
+ name: args.machine.name,
856
+ ref: args.machine.ref,
857
+ idempotencyKey: null,
858
+ },
859
+ async () => {
860
+ await onConnected(args);
861
+ },
862
+ ),
863
+ }
864
+ : {}),
578
865
  create: async (request) => {
579
866
  const entry: SimulatedCall = {
580
867
  verb: "create",
@@ -642,9 +929,17 @@ export class SimulatedWork {
642
929
  machine.revoked = true;
643
930
  machine.alive = false;
644
931
  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 });
932
+ // Its work is retired: its busy chats wait for another machine. A
933
+ // quiet or stopped workspace goes with it; its chat continues from
934
+ // its save when it next works (ADR 0361).
935
+ this.forgetStopped(machine);
936
+ for (const { work, state } of machine.holding)
937
+ if (state === "busy")
938
+ this.waitingWork.push({
939
+ ...work,
940
+ machine: null,
941
+ waitingSince: this.now,
942
+ });
648
943
  machine.holding = [];
649
944
  };
650
945
  return {
@@ -660,6 +955,8 @@ export class SimulatedWork {
660
955
  name: planned.name,
661
956
  managed: true,
662
957
  for: planned.for,
958
+ spare: planned.spare,
959
+ project: planned.project,
663
960
  labels: planned.labels,
664
961
  trusted: planned.trusted,
665
962
  options: planned.options,
@@ -707,6 +1004,41 @@ export class SimulatedWork {
707
1004
  machine.trusted = settings.trusted;
708
1005
  machine.reason = settings.reason;
709
1006
  machine.lostAfterMinutes = settings.lostAfterMinutes;
1007
+ machine.spare = settings.spare;
1008
+ machine.project = settings.project;
1009
+ }),
1010
+ prepare: async ({ name, project, environment, commit }) => {
1011
+ const machine = this.require(name);
1012
+ const existing = machine.preparations.find(
1013
+ (entry) =>
1014
+ entry.project === project && entry.environment === environment,
1015
+ );
1016
+ // Joined as it is, unless it failed: then it starts again.
1017
+ if (!existing || existing.status === "failed") {
1018
+ const started: SimulatedPreparation = {
1019
+ project,
1020
+ environment,
1021
+ status: "preparing",
1022
+ commit: commit ?? null,
1023
+ error: null,
1024
+ since: this.clock,
1025
+ readyAt: this.clock + (this.options.prepareSeconds ?? 600) * 1_000,
1026
+ };
1027
+ machine.preparations = [
1028
+ ...machine.preparations.filter((entry) => entry !== existing),
1029
+ started,
1030
+ ];
1031
+ }
1032
+ const preparation = this.preparationsOf(machine).find(
1033
+ (entry) =>
1034
+ entry.project === project && entry.environment === environment,
1035
+ );
1036
+ if (!preparation) throw new Error("The preparation was not recorded");
1037
+ return preparation;
1038
+ },
1039
+ heardConnected: async ({ name }) =>
1040
+ set(name, (machine) => {
1041
+ machine.connectedPending = false;
710
1042
  }),
711
1043
  setFor: async ({ name, for: principals }) =>
712
1044
  set(name, (machine) => {
@@ -720,10 +1052,14 @@ export class SimulatedWork {
720
1052
  reset: async ({ name }) => {
721
1053
  const machine = this.require(name);
722
1054
  if (!this.live(machine)) return "offline";
723
- if (machine.holding.length > 0) return "busy";
1055
+ if (machine.holding.some((held) => held.state !== "stopped"))
1056
+ return "busy";
1057
+ this.forgetStopped(machine);
724
1058
  machine.for = machine.reset?.for ?? machine.for;
725
1059
  machine.reset = null;
726
1060
  machine.resets += 1;
1061
+ // Nothing of a preparation is left on a reset machine.
1062
+ machine.preparations = [];
727
1063
  return "done";
728
1064
  },
729
1065
  drop: async ({ name }) =>
@@ -736,7 +1072,11 @@ export class SimulatedWork {
736
1072
  }),
737
1073
  retire: async ({ name }) => {
738
1074
  const machine = this.require(name);
739
- if (machine.holding.length > 0 && !machine.revoked) return false;
1075
+ if (
1076
+ machine.holding.some((held) => held.state !== "stopped") &&
1077
+ !machine.revoked
1078
+ )
1079
+ return false;
740
1080
  condemn(machine);
741
1081
  return true;
742
1082
  },
@@ -749,10 +1089,18 @@ export class SimulatedWork {
749
1089
  condemn(machine);
750
1090
  return true;
751
1091
  },
1092
+ // Its quiet workspaces stop with it (ADR 0361); a busy one keeps it.
752
1093
  beginStop: async ({ name }) => {
753
1094
  const machine = this.require(name);
754
- if (machine.holding.length > 0 || machine.phase !== "running")
1095
+ if (
1096
+ machine.holding.some((held) => held.state === "busy") ||
1097
+ machine.phase !== "running"
1098
+ )
755
1099
  return false;
1100
+ for (const held of machine.holding) {
1101
+ held.state = "stopped";
1102
+ held.quietAt = null;
1103
+ }
756
1104
  phase(machine, "stopping");
757
1105
  return true;
758
1106
  },
@@ -773,6 +1121,8 @@ export class SimulatedWork {
773
1121
  machine.connectsAt = this.clock + this.bootMs;
774
1122
  }),
775
1123
  forget: async ({ name }) => {
1124
+ const machine = this.machines.get(name);
1125
+ if (machine) this.forgetStopped(machine);
776
1126
  this.machines.delete(name);
777
1127
  },
778
1128
  note: async ({ name, notice }) =>