@catamorphic/work-server 0.1.0-alpha.43 → 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 (66) hide show
  1. package/README.md +4 -1
  2. package/dist/{chunk-kcck20aw.js → chunk-ynxz0am9.js} +80 -9
  3. package/dist/chunk-ynxz0am9.js.map +11 -0
  4. package/dist/cluster.d.ts +19 -1
  5. package/dist/cluster.d.ts.map +1 -1
  6. package/dist/index.d.ts +2 -2
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +784 -197
  9. package/dist/index.js.map +18 -16
  10. package/dist/machines/contract.d.ts +138 -14
  11. package/dist/machines/contract.d.ts.map +1 -1
  12. package/dist/machines/sequencer.d.ts +33 -6
  13. package/dist/machines/sequencer.d.ts.map +1 -1
  14. package/dist/machines/simulation.d.ts +64 -0
  15. package/dist/machines/simulation.d.ts.map +1 -1
  16. package/dist/machines/work-machines.d.ts +20 -2
  17. package/dist/machines/work-machines.d.ts.map +1 -1
  18. package/dist/server.d.ts +11 -1
  19. package/dist/server.d.ts.map +1 -1
  20. package/dist/testing.d.ts +1 -1
  21. package/dist/testing.d.ts.map +1 -1
  22. package/dist/testing.js +208 -17
  23. package/dist/testing.js.map +4 -4
  24. package/dist/workers/cache-archive-routes.d.ts +24 -0
  25. package/dist/workers/cache-archive-routes.d.ts.map +1 -0
  26. package/dist/workers/harness-sign-ins.d.ts +32 -1
  27. package/dist/workers/harness-sign-ins.d.ts.map +1 -1
  28. package/dist/workers/machine-store.d.ts +37 -0
  29. package/dist/workers/machine-store.d.ts.map +1 -1
  30. package/dist/workers/member-machine-routes.d.ts +3 -0
  31. package/dist/workers/member-machine-routes.d.ts.map +1 -1
  32. package/dist/workers/member-machines.d.ts +52 -5
  33. package/dist/workers/member-machines.d.ts.map +1 -1
  34. package/dist/workers/placement.d.ts +10 -0
  35. package/dist/workers/placement.d.ts.map +1 -1
  36. package/dist/workers/sign-in-store.d.ts +67 -0
  37. package/dist/workers/sign-in-store.d.ts.map +1 -0
  38. package/dist/workers/sign-ins.d.ts +4 -6
  39. package/dist/workers/sign-ins.d.ts.map +1 -1
  40. package/dist/workers/worker-protocol.d.ts +9 -1
  41. package/dist/workers/worker-protocol.d.ts.map +1 -1
  42. package/dist/workers/worker-registry.d.ts +20 -6
  43. package/dist/workers/worker-registry.d.ts.map +1 -1
  44. package/dist/workers/worker-runtime.d.ts.map +1 -1
  45. package/package.json +18 -19
  46. package/src/cluster.ts +62 -7
  47. package/src/index.ts +7 -0
  48. package/src/machines/contract-kit.ts +1 -1
  49. package/src/machines/contract.ts +191 -19
  50. package/src/machines/sequencer.ts +106 -11
  51. package/src/machines/simulation.ts +370 -20
  52. package/src/machines/work-machines.ts +33 -3
  53. package/src/server.ts +106 -9
  54. package/src/testing.ts +1 -0
  55. package/src/workers/cache-archive-routes.ts +125 -0
  56. package/src/workers/harness-sign-ins.ts +207 -22
  57. package/src/workers/machine-store.ts +337 -56
  58. package/src/workers/member-machine-routes.ts +58 -3
  59. package/src/workers/member-machines.ts +168 -14
  60. package/src/workers/placement.ts +7 -0
  61. package/src/workers/sign-in-store.ts +241 -0
  62. package/src/workers/sign-ins.ts +9 -33
  63. package/src/workers/worker-protocol.ts +9 -1
  64. package/src/workers/worker-registry.ts +47 -6
  65. package/src/workers/worker-runtime.ts +5 -1
  66. package/dist/chunk-kcck20aw.js.map +0 -11
package/src/cluster.ts CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  import type { DB } from "@catamorphic/db";
14
14
  import type {
15
15
  EnvironmentBinding,
16
+ EnvironmentLimits,
16
17
  EnvironmentProvider,
17
18
  MachineDisk,
18
19
  SandboxProvider,
@@ -28,6 +29,7 @@ import {
28
29
  servesOnlyThisOwner,
29
30
  } from "@catamorphic/sandbox";
30
31
  import { type Kysely, sql } from "kysely";
32
+ import type { MachinePrincipal } from "./machines/contract.js";
31
33
  import {
32
34
  nodeAccess,
33
35
  type ScheduledPlacement,
@@ -86,6 +88,11 @@ export async function registerWorkMachine(args: {
86
88
  placement?: {
87
89
  workers(): Promise<Map<string, ScheduledPlacement>>;
88
90
  };
91
+ /**
92
+ * This machine gave a workspace's room back: hint the queue, so a run
93
+ * that found no room is tried now.
94
+ */
95
+ roomFreed?: () => void;
89
96
  }) {
90
97
  const nodes = new WorkerNodesService(args.db);
91
98
  let signIns = args.signIns?.() ?? [];
@@ -153,6 +160,7 @@ export async function registerWorkMachine(args: {
153
160
  allocationBindingId,
154
161
  requirements,
155
162
  fill,
163
+ environment,
156
164
  }) => {
157
165
  const candidates = await nodes.list({
158
166
  tenantId,
@@ -203,14 +211,33 @@ export async function registerWorkMachine(args: {
203
211
  node.descriptor.isolation !== "process"),
204
212
  );
205
213
  const tierOf = (policy: ScheduledPlacement | undefined) =>
206
- accessTier({
207
- access: policy ? nodeAccess(policy.for) : { everyone: true },
208
- owner,
209
- ...(projectId ? { projectId } : {}),
210
- ...(chatKey ? { chatKey } : {}),
211
- });
214
+ // A spare waits for its chat key (ADR 0360): until one takes it, it
215
+ // takes only its project's chats that have a key, and its fills.
216
+ policy?.spare && !chatKey && !fill
217
+ ? undefined
218
+ : accessTier({
219
+ access: policy ? nodeAccess(policy.for) : { everyone: true },
220
+ owner,
221
+ ...(projectId ? { projectId } : {}),
222
+ ...(chatKey ? { chatKey } : {}),
223
+ ...(fill ? { fill: true } : {}),
224
+ });
225
+ // Among machines as narrow as each other, one prepared for the
226
+ // Environment first: its image and caches are already there.
227
+ const warm = (policy: ScheduledPlacement | undefined) =>
228
+ Boolean(
229
+ environment &&
230
+ policy?.prepared?.some(
231
+ (entry) =>
232
+ entry.project === projectId &&
233
+ entry.environment === environment,
234
+ ),
235
+ );
212
236
  const ordered = placementOrder(
213
- eligible,
237
+ [...eligible].sort(
238
+ (left, right) =>
239
+ Number(warm(right.policy)) - Number(warm(left.policy)),
240
+ ),
214
241
  // Admission decided whom an Allocation's machine is for: it
215
242
  // resolves for that Allocation whatever the machine is for now.
216
243
  ({ node, policy }) =>
@@ -285,10 +312,18 @@ export async function registerWorkMachine(args: {
285
312
  // (ADR 0213), or a single person's server that accepted them.
286
313
  const ownSignIns =
287
314
  servesOnlyOwner || (selected.id === lease.id && args.ownSignIns);
315
+ // A machine whose principals name one owner (ADR 0362): what it has
316
+ // is theirs anyway, so a sandbox there may use all of it, while
317
+ // admission still reserves only what the work asks.
318
+ const ceiling = ownerCeiling({
319
+ for: chosen.policy?.for ?? null,
320
+ capacity: chosen.node.capacity,
321
+ });
288
322
  return {
289
323
  descriptor: selected.descriptor,
290
324
  workerNodeId: selected.id,
291
325
  ...(servesOnlyOwner ? { servesOnlyOwner } : {}),
326
+ ...(ceiling ? { ceiling } : {}),
292
327
  ...(ownSignIns ? { ownSignIns: true } : {}),
293
328
  // This process's own machine, or a worker any replica reaches
294
329
  // through the operation queue (ADR 0192). Another replica's own
@@ -430,6 +465,7 @@ export async function registerWorkMachine(args: {
430
465
  db: args.db,
431
466
  workerNode: lease,
432
467
  provider: args.sandboxProvider,
468
+ ...(args.roomFreed ? { roomFreed: args.roomFreed } : {}),
433
469
  })
434
470
  .catch((error) =>
435
471
  console.warn("[catamorphic] Workspace cleanup deferred", error),
@@ -525,3 +561,22 @@ export function workPushKeys(secret: string): {
525
561
  }
526
562
  throw new Error("Could not derive the deployment's notification signing key");
527
563
  }
564
+
565
+ /**
566
+ * The ceiling a machine offers a sandbox whose Environment names no
567
+ * `limits` (ADR 0362): its whole budget when its principals name one
568
+ * owner; otherwise none, and a sandbox's ceiling is its reservation.
569
+ */
570
+ export function ownerCeiling(args: {
571
+ for: readonly MachinePrincipal[] | null;
572
+ capacity: { cpuMillis?: number; memoryMb?: number } | null | undefined;
573
+ }): EnvironmentLimits | undefined {
574
+ if (!servesOneOwner(args.for) || !args.capacity) return undefined;
575
+ const { cpuMillis, memoryMb } = args.capacity;
576
+ return cpuMillis === undefined && memoryMb === undefined
577
+ ? undefined
578
+ : {
579
+ ...(cpuMillis !== undefined ? { cpuMillis } : {}),
580
+ ...(memoryMb !== undefined ? { memoryMb } : {}),
581
+ };
582
+ }
package/src/index.ts CHANGED
@@ -6,6 +6,8 @@
6
6
  */
7
7
  // What a company's own server file needs (ADR 0261), from one package.
8
8
  export {
9
+ type CacheArchiveKey,
10
+ type CacheStore,
9
11
  type ConnectionActionContext,
10
12
  type ConnectionActionGuard,
11
13
  ConnectionActionRefusedError,
@@ -67,19 +69,24 @@ export {
67
69
  DEFAULT_LOST_AFTER_MINUTES,
68
70
  type DesiredMachine,
69
71
  DesiredMachineSchema,
72
+ handedOffKey,
70
73
  MACHINE_EVENT_KINDS,
74
+ type MachineConnected,
71
75
  type MachineCreateRequest,
72
76
  type MachineCreateResult,
73
77
  type MachineEvent,
74
78
  type MachineEventKind,
75
79
  type MachineFacts,
76
80
  type MachinePlanFacts,
81
+ type MachinePreparation,
77
82
  type MachinePrincipal,
78
83
  type MachineState,
79
84
  type MachinesHook,
80
85
  type MachineTarget,
81
86
  type MachineVerb,
82
87
  type PersonFacts,
88
+ preparedFor,
89
+ spareProject,
83
90
  type WaitingWork,
84
91
  } from "./machines/contract.js";
85
92
  export type { MachinePassSummary } from "./machines/sequencer.js";
@@ -499,7 +499,7 @@ export async function checkMachinesHook(args: {
499
499
  if (after.length > 0)
500
500
  fail("plan does not flap", [
501
501
  `Nothing changed, yet within a simulated minute the plan had machines made or destroyed: ${recent(after)}.`,
502
- "Keep a machine while the reason for it holds. If the plan drops machines that are idle, give them an idle time of minutes, not seconds, and measure it from the machine's own idleSince.",
502
+ "Keep a machine while the reason for it holds. If the plan drops or stops machines that are quiet, give them a quiet time of minutes, not seconds, and measure it from the machine's own quietSince.",
503
503
  ]);
504
504
  for (const [name, calls] of groupByName(creates(sim.calls))) {
505
505
  const keys = new Set(calls.map((call) => call.idempotencyKey));
@@ -6,10 +6,11 @@ import { z } from "zod";
6
6
  * (`plan`) and makes the calls that touch its cloud (`create`, `destroy`,
7
7
  * `stop`, `start`, `describe`). Work sequences those calls (it records its
8
8
  * intent before each, repeats it until done, and never makes one machine
9
- * twice across replicas), enforces safety (nothing holding live work is
10
- * stopped or destroyed unless it is lost) and owns liveness, enrollment and
11
- * capacity. Everything here is plain data, so a plan can be tested without
12
- * a server.
9
+ * twice across replicas), enforces safety (nothing in use is stopped and
10
+ * nothing holding live work is destroyed unless it is lost; a machine
11
+ * stops with its quiet workspaces kept, ADR 0361) and owns liveness,
12
+ * enrollment and capacity. Everything here is plain data, so a plan can be
13
+ * tested without a server.
13
14
  */
14
15
 
15
16
  /**
@@ -69,9 +70,24 @@ export interface DesiredMachine {
69
70
  name: string;
70
71
  /**
71
72
  * Who may place work here: users, projects, chat keys. Omitted: anyone
72
- * whose role and Environment allow it. An empty list: nobody (a spare).
73
+ * whose role and Environment allow it. An empty list: nobody.
73
74
  */
74
75
  for?: readonly MachinePrincipal[];
76
+ /**
77
+ * A spare for one project's chats (ADR 0360): `for` names that project
78
+ * alone. It takes the project's cache fills and preparations, and the
79
+ * first chat with a chat key placed on it takes the machine: as Work
80
+ * places that chat, under the machine's lock, it narrows `for` to that
81
+ * key, so no second key is placed there. Nothing is reset. Plan it for
82
+ * its key from then on (its facts say whose it is), or drop it.
83
+ */
84
+ spare?: boolean;
85
+ /**
86
+ * The project that accounts for the machine (ADR 0364): its events are
87
+ * recorded for that project as well as the projects in `for`, so its
88
+ * workflows hear about its people's machines. It grants nobody access.
89
+ */
90
+ project?: string;
75
91
  /** Labels an Environment's `pool` selects on. */
76
92
  labels?: Readonly<Record<string, string>>;
77
93
  /** Default "running". "stopped" keeps the disk. */
@@ -92,6 +108,8 @@ export interface DesiredMachine {
92
108
  export const DesiredMachineSchema = z.strictObject({
93
109
  name: MachineNameSchema,
94
110
  for: z.array(MachinePrincipalSchema).max(500).optional(),
111
+ spare: z.boolean().optional(),
112
+ project: z.uuid().optional(),
95
113
  labels: MachineLabelsSchema.optional(),
96
114
  state: z.enum(["running", "stopped"]).optional(),
97
115
  options: z.record(z.string(), z.json()).optional(),
@@ -114,6 +132,12 @@ export const MachinePlanSchema = z
114
132
  .superRefine((machines, context) => {
115
133
  const seen = new Set<string>();
116
134
  for (const [index, machine] of machines.entries()) {
135
+ if (machine.spare && !spareProject(machine.for))
136
+ context.addIssue({
137
+ code: "custom",
138
+ message: `'${machine.name}' is a spare, so it is for one project and nothing else: for: [{ project }]`,
139
+ path: [index, "for"],
140
+ });
117
141
  if (seen.has(machine.name))
118
142
  context.addIssue({
119
143
  code: "custom",
@@ -132,8 +156,9 @@ export const MachinePlanSchema = z
132
156
  * - `serving`: connected and taking work.
133
157
  * - `draining`: the plan no longer names it; it takes no new work and is
134
158
  * destroyed once it holds none.
135
- * - `stopping`, `stopped`, `resuming`: its disk is kept; it offers no
136
- * capacity until it serves again.
159
+ * - `stopping`, `stopped`, `resuming`: its disk is kept, and the quiet
160
+ * workspaces it stopped with (ADR 0361); it offers no capacity until it
161
+ * serves again.
137
162
  * - `unreachable`: it was serving and has not called since its lease lapsed.
138
163
  * - `lost`: unreachable for its limit; its work is retired.
139
164
  * - `disabled`: an operator disabled it; its work waits and it is never lost.
@@ -151,6 +176,23 @@ export type MachineState =
151
176
  | "disabled"
152
177
  | "destroying";
153
178
 
179
+ /**
180
+ * A machine's preparation for one Environment of a project (ADR 0360).
181
+ * `prepared`: the Environment's image is on the machine and each cache it
182
+ * declares has a copy there, so a chat placed on it builds and fills
183
+ * nothing. `preparing`: on its way. `failed`: see `error`; ask again.
184
+ */
185
+ export interface MachinePreparation {
186
+ project: string;
187
+ environment: string;
188
+ status: "preparing" | "prepared" | "failed";
189
+ /** The published revision it was prepared from; null until it starts. */
190
+ commit: string | null;
191
+ error: string | null;
192
+ /** Since when it is in `status` (ISO 8601). */
193
+ since: string;
194
+ }
195
+
154
196
  /** One machine Work knows, as the plan reads it. */
155
197
  export interface MachineFacts {
156
198
  name: string;
@@ -164,14 +206,36 @@ export interface MachineFacts {
164
206
  labels: Readonly<Record<string, string>>;
165
207
  /** Who may place work here; null for anyone. */
166
208
  for: readonly MachinePrincipal[] | null;
209
+ /** A spare no chat key has taken yet (ADR 0360). */
210
+ spare: boolean;
211
+ /** The project that accounts for it, as the plan named it (ADR 0364). */
212
+ project: string | null;
213
+ /** What it was prepared for, so a plan tells a warm machine from a cold one. */
214
+ preparations: readonly MachinePreparation[];
167
215
  trusted: boolean;
168
216
  /** The options it was created with. */
169
217
  options: Readonly<Record<string, unknown>>;
170
218
  reason: string | null;
171
- /** Live workspaces on it, and whose they are. */
172
- holding: { workspaces: number; for: readonly MachinePrincipal[] };
173
- /** Since when it has held no workspace while serving; null while it holds one or is not serving. */
174
- idleSince: string | null;
219
+ /**
220
+ * Live workspaces on it and whose they are, and the stopped workspaces it
221
+ * keeps (ADR 0361): saved, their sandboxes stopped, each woken when its
222
+ * chat next works while the machine serves.
223
+ */
224
+ holding: {
225
+ workspaces: number;
226
+ stopped: number;
227
+ for: readonly MachinePrincipal[];
228
+ };
229
+ /**
230
+ * Since when nothing on it has been in use (ADR 0361), while it serves or
231
+ * drains: it holds no live workspace, or every one it holds is quiet (no
232
+ * turn queued, held or running in a chat working there, no terminal,
233
+ * preview or workflow command in the last two minutes, no preparation).
234
+ * Null while something is in use, or while it does not serve. A plan
235
+ * stops a machine quiet for long enough: Work stops its quiet workspaces
236
+ * with it and keeps them.
237
+ */
238
+ quietSince: string | null;
175
239
  /** When its worker last called; null before its first call. */
176
240
  lastSeenAt: string | null;
177
241
  /** What it offers, from its worker's own report; null before it first connected. */
@@ -204,14 +268,30 @@ export interface MachineFacts {
204
268
  lastError: { verb: MachineVerb; message: string; at: string } | null;
205
269
  }
206
270
 
207
- export type MachineVerb = "create" | "destroy" | "stop" | "start" | "describe";
271
+ export type MachineVerb =
272
+ | "create"
273
+ | "destroy"
274
+ | "stop"
275
+ | "start"
276
+ | "describe"
277
+ | "onConnected";
278
+
279
+ /**
280
+ * Minutes a sign-in begun on a stopped machine waits for it (ADR 0363):
281
+ * after this it is no reason for the machine to start.
282
+ */
283
+ export const SIGN_IN_WAIT_MINUTES = 10;
208
284
 
209
285
  /** Work that has no machine yet. */
210
286
  export interface WaitingWork {
211
- /** The chat's or run's id. */
287
+ /** The chat's, run's or sign-in's id. */
212
288
  id: string;
213
- /** A chat, a workflow run, or a cache fill. */
214
- kind: "chat" | "run" | "fill";
289
+ /**
290
+ * A chat, a workflow run, a cache fill, or a member's sign-in begun on a
291
+ * stopped machine of their own (ADR 0363), which needs that machine
292
+ * running and no workspace on it.
293
+ */
294
+ kind: "chat" | "run" | "fill" | "sign-in";
215
295
  project: string;
216
296
  /** The member whose work it is; null for the project's own. */
217
297
  user: string | null;
@@ -232,6 +312,14 @@ export interface WaitingWork {
232
312
  };
233
313
  /** No machine open to it had room (`capacity`), or none was online (`unavailable`). */
234
314
  reason: "capacity" | "unavailable";
315
+ /**
316
+ * The one machine it waits for, by name, which only that machine takes:
317
+ * the machine keeping the chat's stopped workspace (ADR 0361), or the
318
+ * member's machine a sign-in was begun on (ADR 0363). Null for work any
319
+ * machine open to it takes. A plan starts that machine and makes no
320
+ * other for it.
321
+ */
322
+ machine: string | null;
235
323
  /** ISO 8601. */
236
324
  waitingSince: string;
237
325
  }
@@ -346,6 +434,8 @@ export interface MachineEvent {
346
434
  managed: boolean;
347
435
  labels: Readonly<Record<string, string>>;
348
436
  for: readonly MachinePrincipal[] | null;
437
+ /** The project that accounts for it; null for none. */
438
+ project: string | null;
349
439
  options: Readonly<Record<string, unknown>>;
350
440
  reason: string | null;
351
441
  };
@@ -391,8 +481,10 @@ export interface MachinesHook {
391
481
  done: boolean;
392
482
  }>;
393
483
  /**
394
- * Stop the machine and keep its disk. `requestedAt` is stable for this
395
- * stop request. Without a stop verb, no machine is stopped.
484
+ * Stop the machine and keep its disk. Work asks once everything on it is
485
+ * quiet, having stopped its workspaces (ADR 0361). `requestedAt` is
486
+ * stable for this stop request. Without a stop verb, no machine is
487
+ * stopped.
396
488
  */
397
489
  stop?(
398
490
  args: MachineTarget & { requestedAt: string },
@@ -414,6 +506,76 @@ export interface MachinesHook {
414
506
  * also records each for the projects named in the machine's `for`.
415
507
  */
416
508
  onEvent?(event: MachineEvent): Promise<void> | void;
509
+ /**
510
+ * Run when a machine's worker connected and it serves (ADR 0360): made
511
+ * through this hook, resumed, or enrolled by hand. Plain host code: it
512
+ * may prepare the machine for the Environments it will run, start a
513
+ * workflow, or tell another system. Work calls it once per connection
514
+ * and again until it resolves, so make it safe to repeat. Nothing waits
515
+ * for it: the machine takes work meanwhile.
516
+ */
517
+ onConnected?(args: MachineConnected): Promise<void> | void;
518
+ }
519
+
520
+ /** What `onConnected` is given. */
521
+ export interface MachineConnected {
522
+ /** The machine as the plan reads it. */
523
+ machine: MachineFacts;
524
+ /**
525
+ * Prepare this machine for an Environment of a project, before any chat
526
+ * needs it: its image is built or pulled there, and each cache it
527
+ * declares is filled there (restored from the host's cache store where it
528
+ * holds one). Answers at once; the machine's `preparations` say how it
529
+ * goes. Safe to call again: it joins the preparation under way and starts
530
+ * a failed one again.
531
+ */
532
+ prepare(args: {
533
+ project: string;
534
+ environment: string;
535
+ /** A revision of main that went live; the current one by default. */
536
+ commit?: string;
537
+ }): Promise<MachinePreparation>;
538
+ }
539
+
540
+ /** The project a spare is for: its one principal, a project with no key. */
541
+ export function spareProject(
542
+ principals: readonly MachinePrincipal[] | null | undefined,
543
+ ): string | undefined {
544
+ const [only, ...rest] = principals ?? [];
545
+ return only && rest.length === 0 && "project" in only && !("key" in only)
546
+ ? only.project
547
+ : undefined;
548
+ }
549
+
550
+ /**
551
+ * The chat key a spare of `project` was handed to: its one principal now, a
552
+ * key of that project.
553
+ */
554
+ export function handedOffKey(args: {
555
+ project: string;
556
+ for: readonly MachinePrincipal[] | null;
557
+ }): string | undefined {
558
+ const [only, ...rest] = args.for ?? [];
559
+ return only &&
560
+ rest.length === 0 &&
561
+ "key" in only &&
562
+ only.project === args.project
563
+ ? only.key
564
+ : undefined;
565
+ }
566
+
567
+ /** Whether a machine is prepared for an Environment of a project. */
568
+ export function preparedFor(args: {
569
+ machine: Pick<MachineFacts, "preparations">;
570
+ project: string;
571
+ environment: string;
572
+ }): boolean {
573
+ return args.machine.preparations.some(
574
+ (entry) =>
575
+ entry.status === "prepared" &&
576
+ entry.project === args.project &&
577
+ entry.environment === args.environment,
578
+ );
417
579
  }
418
580
 
419
581
  /** Whether two principals name the same thing. */
@@ -507,13 +669,23 @@ export function servesNobody(
507
669
  return principals !== null && principals.length === 0;
508
670
  }
509
671
 
510
- /** Whether a machine for `principals` takes this waiting work. */
672
+ /**
673
+ * Whether a machine for `principals` takes this waiting work. A spare takes
674
+ * only its project's chats that have a key, and its cache fills.
675
+ */
511
676
  export function principalsTake(args: {
512
677
  for: readonly MachinePrincipal[] | null;
513
- work: Pick<WaitingWork, "project" | "user" | "key">;
678
+ spare?: boolean;
679
+ work: Pick<WaitingWork, "project" | "user" | "key" | "kind">;
514
680
  }): boolean {
515
681
  if (args.for === null) return true;
516
682
  const { work } = args;
683
+ // A sign-in is for the member's own machine, which takes no one else's.
684
+ if (work.kind === "sign-in")
685
+ return args.for.some(
686
+ (principal) => "user" in principal && principal.user === work.user,
687
+ );
688
+ if (args.spare && work.kind !== "fill" && work.key === null) return false;
517
689
  return args.for.some((principal) => {
518
690
  if ("user" in principal) return work.user === principal.user;
519
691
  if (work.user !== null || principal.project !== work.project) return false;