@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,231 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import {
3
+ PlacementWaitsService,
4
+ releaseReplicaClaim,
5
+ renewReplicaClaim,
6
+ takeReplicaClaim,
7
+ } from "@catamorphic/core";
8
+ import type { DB } from "@catamorphic/db";
9
+ import { getTracer, withSpan } from "@catamorphic/otel";
10
+ import type { Kysely } from "kysely";
11
+ import type { WorkWorkerRegistry } from "../workers/worker-registry.js";
12
+ import type { MachineEvent, MachinesHook, PersonFacts } from "./contract.js";
13
+ import {
14
+ emptySummary,
15
+ MachinePassFencedError,
16
+ type MachinePassSummary,
17
+ type MachineWorld,
18
+ runMachinePass,
19
+ } from "./sequencer.js";
20
+
21
+ const tracer = getTracer("@catamorphic/work-server");
22
+
23
+ /** How long a pass waits for one machine's reset; a slower one finishes later. */
24
+ const RESET_WAIT_MS = 3 * 60_000;
25
+
26
+ /**
27
+ * The sequencer's world on the Work server (ADR 0349): machines, their
28
+ * workers and what they hold in Postgres, by the database's clock.
29
+ */
30
+ export function workMachineWorld(deps: {
31
+ db: Kysely<DB>;
32
+ tenantId: string;
33
+ workers: WorkWorkerRegistry;
34
+ controlPlaneUrl: string;
35
+ people: () => Promise<PersonFacts[]>;
36
+ event: (event: MachineEvent) => Promise<void>;
37
+ resetWaitMs?: number;
38
+ }): MachineWorld {
39
+ const { workers } = deps;
40
+ const machines = workers.machines;
41
+ const waits = new PlacementWaitsService(deps.db);
42
+ return {
43
+ controlPlaneUrl: deps.controlPlaneUrl,
44
+ now: () => machines.now(),
45
+ records: () => machines.records(),
46
+ work: () => machines.work(),
47
+ people: () => deps.people(),
48
+ intend: (args) => machines.intend(args),
49
+ enrollment: (args) => machines.enrollment(args),
50
+ reissue: (args) => machines.reissue(args),
51
+ created: (args) => machines.created(args),
52
+ refused: (args) => machines.refused(args),
53
+ configure: (args) => machines.configure(args),
54
+ setFor: (args) => machines.setFor(args),
55
+ beginReset: (args) => machines.beginReset(args),
56
+ reset: ({ name }) =>
57
+ workers.resetPlacement({
58
+ name,
59
+ timeoutMs: deps.resetWaitMs ?? RESET_WAIT_MS,
60
+ }),
61
+ drop: ({ name }) => machines.setDropped({ name, dropped: true }),
62
+ undrop: ({ name }) => machines.setDropped({ name, dropped: false }),
63
+ retire: (args) => workers.retireMachine(args),
64
+ declareLost: (args) => workers.declareLost(args),
65
+ beginStop: (args) => workers.beginStop(args),
66
+ stopped: async ({ name }) => {
67
+ await machines.setPhase({ name, phase: "stopped", from: ["stopping"] });
68
+ },
69
+ beginResume: (args) => workers.beginResume(args),
70
+ startAsked: (args) => machines.startAsked(args),
71
+ forget: (args) => machines.forget(args),
72
+ note: (args) => machines.note(args),
73
+ failed: (args) => machines.failed(args),
74
+ succeeded: (args) => machines.succeeded(args),
75
+ event: (event) => deps.event(event),
76
+ planned: (args) => machines.planned(args),
77
+ waiting: ({ machines: byWork }) =>
78
+ waits.setMachines({ tenantId: deps.tenantId, machines: byWork }),
79
+ };
80
+ }
81
+
82
+ /**
83
+ * Keeps machines in step with the host's plan (ADR 0349). A pass runs only
84
+ * while this replica holds the tenant's sequencer claim (ADR 0193),
85
+ * renewed as it goes and checked before every change and every call into
86
+ * host code, so replicas take turns and no machine is made twice.
87
+ */
88
+ export class WorkMachines {
89
+ private running: Promise<MachinePassSummary> | undefined;
90
+ private readonly holder = randomUUID();
91
+ /** What the latest pass of this replica saw; see {@link check}. */
92
+ private seen: string | undefined;
93
+
94
+ constructor(
95
+ private readonly deps: {
96
+ db: Kysely<DB>;
97
+ tenantId: string;
98
+ hook: MachinesHook;
99
+ world: MachineWorld;
100
+ workers: WorkWorkerRegistry;
101
+ /** How long a pass holds its claim without renewing (default 2 minutes). */
102
+ leaseMs?: number;
103
+ planTimeoutMs?: number;
104
+ verbTimeoutMs?: number;
105
+ log?: (line: string) => void;
106
+ },
107
+ ) {}
108
+
109
+ /** One pass; concurrent callers on this replica share it. */
110
+ pass(): Promise<MachinePassSummary> {
111
+ this.running ??= withSpan(
112
+ {
113
+ tracer,
114
+ name: "machines.pass",
115
+ attributes: { "catamorphic.tenant.id": this.deps.tenantId },
116
+ },
117
+ () => this.guardedPass(),
118
+ ).finally(() => {
119
+ this.running = undefined;
120
+ });
121
+ return this.running;
122
+ }
123
+
124
+ /** Start a pass without waiting for it; its outcome reaches the listing and the log. */
125
+ passSoon(): void {
126
+ void this.pass().catch((error: unknown) =>
127
+ this.deps.log?.(`Machine pass failed: ${message(error)}`),
128
+ );
129
+ }
130
+
131
+ /** Waits for a pass in progress (shutdown); starts none. */
132
+ async settle(): Promise<void> {
133
+ await this.running?.catch(() => undefined);
134
+ }
135
+
136
+ /**
137
+ * Whether anything a plan reads changed since a pass of this replica
138
+ * last looked: waiting work, what machines hold, a machine connecting,
139
+ * becoming unreachable or lost, accounts and roles. One cheap look every
140
+ * few seconds; a full pass only when it changed. What it remembers is
141
+ * this replica's own shortcut (ADR 0193): the pass runs under the
142
+ * tenant's claim either way.
143
+ */
144
+ async check(): Promise<void> {
145
+ const seen = await this.deps.workers.machines.signature();
146
+ if (seen === this.seen) return;
147
+ this.passSoon();
148
+ }
149
+
150
+ private get leaseMs(): number {
151
+ return this.deps.leaseMs ?? 120_000;
152
+ }
153
+
154
+ private async guardedPass(): Promise<MachinePassSummary> {
155
+ const claim = {
156
+ db: this.deps.db,
157
+ name: `machine-reconciler:${this.deps.tenantId}`,
158
+ holder: this.holder,
159
+ };
160
+ const ttlSeconds = Math.max(1, Math.ceil(this.leaseMs / 1000));
161
+ if (!(await takeReplicaClaim({ ...claim, ttlSeconds }))) {
162
+ // Another replica is sequencing; its pass covers this one.
163
+ return { ...emptySummary(), busy: true };
164
+ }
165
+ // What this pass sees; a change after this starts another.
166
+ this.seen = await this.deps.workers.machines
167
+ .signature()
168
+ .catch(() => this.seen);
169
+ const lease = { lost: false };
170
+ // A call into host code can outlast the claim; keep it while the pass runs.
171
+ const heartbeat = setInterval(
172
+ () => {
173
+ void renewReplicaClaim({ ...claim, ttlSeconds })
174
+ .then((held) => {
175
+ if (!held) lease.lost = true;
176
+ })
177
+ .catch(() => undefined);
178
+ },
179
+ Math.max(1_000, this.leaseMs / 4),
180
+ );
181
+ heartbeat.unref();
182
+ const fence = async () => {
183
+ if (lease.lost || !(await renewReplicaClaim({ ...claim, ttlSeconds }))) {
184
+ lease.lost = true;
185
+ throw new MachinePassFencedError();
186
+ }
187
+ };
188
+ let summary = emptySummary();
189
+ try {
190
+ summary = await runMachinePass({
191
+ hook: this.deps.hook,
192
+ world: this.deps.world,
193
+ fence,
194
+ defaultLostAfterMinutes: this.deps.workers.machines.defaultLostMinutes,
195
+ ...(this.deps.planTimeoutMs !== undefined
196
+ ? { planTimeoutMs: this.deps.planTimeoutMs }
197
+ : {}),
198
+ ...(this.deps.verbTimeoutMs !== undefined
199
+ ? { verbTimeoutMs: this.deps.verbTimeoutMs }
200
+ : {}),
201
+ ...(this.deps.log ? { log: this.deps.log } : {}),
202
+ });
203
+ } catch (error) {
204
+ if (!(error instanceof MachinePassFencedError)) throw error;
205
+ this.deps.log?.(
206
+ "Machine pass stopped: another replica took over the sequencer",
207
+ );
208
+ } finally {
209
+ clearInterval(heartbeat);
210
+ await releaseReplicaClaim(claim).catch(() => undefined);
211
+ }
212
+ const changed =
213
+ summary.created.length +
214
+ summary.updated.length +
215
+ summary.reset.length +
216
+ summary.released.length +
217
+ summary.lost.length +
218
+ summary.stopped.length +
219
+ summary.resumed.length +
220
+ summary.destroyed.length;
221
+ if (changed > 0 || summary.failed.length > 0)
222
+ this.deps.log?.(
223
+ `Machines: ${summary.created.length} created, ${summary.updated.length} updated, ${summary.reset.length} reset, ${summary.released.length} released, ${summary.lost.length} lost, ${summary.stopped.length} stopped, ${summary.resumed.length} resumed, ${summary.destroyed.length} destroyed, ${summary.failed.length} failed`,
224
+ );
225
+ return summary;
226
+ }
227
+ }
228
+
229
+ function message(error: unknown): string {
230
+ return error instanceof Error ? error.message : String(error);
231
+ }