@leitwerk-dev/watcher-utils 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/LICENSE +13 -0
  2. package/dist/chunk-3KGAUQIG.js +31 -0
  3. package/dist/chunk-3KGAUQIG.js.map +1 -0
  4. package/dist/chunk-IU3L35PC.js +14 -0
  5. package/dist/chunk-IU3L35PC.js.map +1 -0
  6. package/dist/chunk-XF2QQLPO.js +63 -0
  7. package/dist/chunk-XF2QQLPO.js.map +1 -0
  8. package/dist/chunk-XLVMFO6W.js +160 -0
  9. package/dist/chunk-XLVMFO6W.js.map +1 -0
  10. package/dist/duration-parse.d.ts +11 -0
  11. package/dist/duration-parse.d.ts.map +1 -0
  12. package/dist/duration-parse.js +16 -0
  13. package/dist/duration-parse.js.map +1 -0
  14. package/dist/index.d.ts +8 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +8 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/poll-loop.d.ts +24 -0
  19. package/dist/poll-loop.d.ts.map +1 -0
  20. package/dist/poll-loop.js +59 -0
  21. package/dist/poll-loop.js.map +1 -0
  22. package/dist/process-helpers.d.ts +30 -0
  23. package/dist/process-helpers.d.ts.map +1 -0
  24. package/dist/process-helpers.js +33 -0
  25. package/dist/process-helpers.js.map +1 -0
  26. package/dist/trigger-files.d.ts +10 -0
  27. package/dist/trigger-files.d.ts.map +1 -0
  28. package/dist/trigger-files.js +31 -0
  29. package/dist/trigger-files.js.map +1 -0
  30. package/dist/watcher-coordinator.d.ts +99 -0
  31. package/dist/watcher-coordinator.d.ts.map +1 -0
  32. package/dist/watcher-coordinator.js +131 -0
  33. package/dist/watcher-coordinator.js.map +1 -0
  34. package/package.json +43 -0
  35. package/src/duration-parse.ts +21 -0
  36. package/src/index.ts +49 -0
  37. package/src/poll-loop.ts +81 -0
  38. package/src/process-helpers.ts +54 -0
  39. package/src/trigger-files.ts +33 -0
  40. package/src/watcher-coordinator.ts +280 -0
@@ -0,0 +1,280 @@
1
+ import type { ProcessInstance, TurnId } from "@leitwerk-dev/domain";
2
+ import {
3
+ type ExternalWriteLogRepoLike,
4
+ recordWriteIfMissing,
5
+ type WriteIdentity,
6
+ } from "@leitwerk-dev/external-writes";
7
+ import type { KnownDurableWsFrameType, WsPayloadByType } from "@leitwerk-dev/protocol";
8
+ import type { PollResult } from "./poll-loop.js";
9
+ import {
10
+ ensureWorkerForActiveAgent,
11
+ hasProcessEvent,
12
+ type ProcessEventRepoLike,
13
+ processNeedsWorker,
14
+ type WorkerSupervisorLike,
15
+ } from "./process-helpers.js";
16
+
17
+ export interface AgentRepoAccessorLike {
18
+ getById(id: string): ProcessInstance | null;
19
+ }
20
+
21
+ export interface BroadcasterLike {
22
+ sendDurable<T extends KnownDurableWsFrameType>(
23
+ type: T,
24
+ payload: WsPayloadByType[T],
25
+ instanceId?: string,
26
+ ): void;
27
+ }
28
+
29
+ export interface WatcherCommandResult {
30
+ ok: boolean;
31
+ code?: string;
32
+ message?: string;
33
+ process?: ProcessInstance | null;
34
+ }
35
+
36
+ export interface WatcherCommandServiceLike {
37
+ startProcess(instanceId: string, startTurnId: TurnId): Promise<WatcherCommandResult>;
38
+ abortProcess(instanceId: string): Promise<WatcherCommandResult>;
39
+ }
40
+
41
+ export interface WatcherStartupDeps {
42
+ processes: AgentRepoAccessorLike;
43
+ events: ProcessEventRepoLike;
44
+ broadcaster: BroadcasterLike;
45
+ commands: WatcherCommandServiceLike;
46
+ supervisor: WorkerSupervisorLike;
47
+ }
48
+
49
+ export interface ContinueWatcherAgentStartupOptions {
50
+ process: ProcessInstance;
51
+ startTurnId: TurnId;
52
+ createdEventData: Record<string, unknown>;
53
+ createdBroadcastData: Record<string, unknown>;
54
+ /** Defaults to true. Set false when the shared launch executor already emitted process.created. */
55
+ broadcastCreated?: boolean;
56
+ afterCreatedEvent?: (process: ProcessInstance) => Promise<void> | void;
57
+ beforeStart?: (process: ProcessInstance) => Promise<void>;
58
+ }
59
+
60
+ export function requireWatcherStartTurnId(
61
+ launchPlan: { launcherId: string; startTurnId: TurnId | null },
62
+ targetLabel: string,
63
+ ): TurnId {
64
+ if (launchPlan.startTurnId) {
65
+ return launchPlan.startTurnId;
66
+ }
67
+ throw new Error(
68
+ `Watcher launcher '${launchPlan.launcherId}' did not declare a startTurnId for ${targetLabel}`,
69
+ );
70
+ }
71
+
72
+ export async function continueWatcherAgentStartup(
73
+ deps: WatcherStartupDeps,
74
+ opts: ContinueWatcherAgentStartupOptions,
75
+ ): Promise<string> {
76
+ const { process } = opts;
77
+
78
+ if (!hasProcessEvent(deps.events, process.id, "agent_created")) {
79
+ deps.events.create({
80
+ instanceId: process.id,
81
+ eventType: "agent_created",
82
+ data: opts.createdEventData,
83
+ });
84
+ }
85
+
86
+ await opts.afterCreatedEvent?.(process);
87
+ await opts.beforeStart?.(process);
88
+
89
+ let currentProcess = deps.processes.getById(process.id) ?? process;
90
+ if (currentProcess.lifecycleStatus === "discovered") {
91
+ const startResult = await deps.commands.startProcess(currentProcess.id, opts.startTurnId);
92
+ if (!startResult.ok) {
93
+ currentProcess = startResult.process ?? currentProcess;
94
+ throw new Error(startResult.message ?? "Failed to start process");
95
+ }
96
+ currentProcess = startResult.process ?? currentProcess;
97
+ if (opts.broadcastCreated !== false) {
98
+ deps.broadcaster.sendDurable(
99
+ "process.created",
100
+ {
101
+ process: currentProcess,
102
+ processId: currentProcess.processId,
103
+ ...opts.createdBroadcastData,
104
+ },
105
+ currentProcess.id,
106
+ );
107
+ }
108
+ }
109
+
110
+ await ensureWorkerForActiveAgent(deps, currentProcess);
111
+ return currentProcess.id;
112
+ }
113
+
114
+ export type DiscoveryResumeResult = "handled" | "skipped" | undefined;
115
+
116
+ export type DiscoveryCreateResult =
117
+ | { outcome: "created"; instanceId: string }
118
+ | { outcome: "skipped" }
119
+ | { outcome: "handled" }
120
+ | null
121
+ | undefined;
122
+
123
+ export interface DiscoveryPassOptions<TItem> {
124
+ items: readonly TItem[];
125
+ result: PollResult;
126
+ findExistingAgent(item: TItem): ProcessInstance | null;
127
+ getResultLabel(item: TItem): string;
128
+ resumeDiscoveredAgent(process: ProcessInstance, item: TItem): Promise<DiscoveryResumeResult>;
129
+ createAgent(item: TItem): Promise<DiscoveryCreateResult>;
130
+ ensureWorkerForExistingAgent?(process: ProcessInstance, item: TItem): Promise<boolean>;
131
+ formatError(item: TItem, error: unknown): string;
132
+ }
133
+
134
+ export async function runWatcherDiscoveryPass<TItem>(
135
+ opts: DiscoveryPassOptions<TItem>,
136
+ ): Promise<void> {
137
+ for (const item of opts.items) {
138
+ try {
139
+ const existingAgent = opts.findExistingAgent(item);
140
+ if (existingAgent) {
141
+ if (existingAgent.lifecycleStatus === "discovered") {
142
+ const resumeResult = await opts.resumeDiscoveredAgent(existingAgent, item);
143
+ if (resumeResult === "skipped") {
144
+ opts.result.skipped.push(opts.getResultLabel(item));
145
+ }
146
+ continue;
147
+ }
148
+ if (opts.ensureWorkerForExistingAgent) {
149
+ const handled = await opts.ensureWorkerForExistingAgent(existingAgent, item);
150
+ if (handled) {
151
+ continue;
152
+ }
153
+ }
154
+ opts.result.skipped.push(opts.getResultLabel(item));
155
+ continue;
156
+ }
157
+
158
+ const createResult = await opts.createAgent(item);
159
+ if (createResult?.outcome === "created") {
160
+ opts.result.created.push(opts.getResultLabel(item));
161
+ continue;
162
+ }
163
+ if (createResult?.outcome === "skipped") {
164
+ opts.result.skipped.push(opts.getResultLabel(item));
165
+ }
166
+ } catch (error) {
167
+ opts.result.errors.push(opts.formatError(item, error));
168
+ }
169
+ }
170
+ }
171
+
172
+ export interface AbortReconciliationOptions {
173
+ candidates: readonly ProcessInstance[];
174
+ result: PollResult;
175
+ events: ProcessEventRepoLike;
176
+ commands: WatcherCommandServiceLike;
177
+ shouldAbort(process: ProcessInstance): Promise<boolean>;
178
+ getResultLabel(process: ProcessInstance): string;
179
+ getErrorLabel(process: ProcessInstance): string;
180
+ getAbortedEventData(process: ProcessInstance): Record<string, unknown>;
181
+ }
182
+
183
+ export async function runWatcherAbortReconciliation(
184
+ opts: AbortReconciliationOptions,
185
+ ): Promise<void> {
186
+ for (const process of opts.candidates) {
187
+ try {
188
+ const shouldAbort = await opts.shouldAbort(process);
189
+ if (!shouldAbort) {
190
+ continue;
191
+ }
192
+
193
+ const abortResult = await opts.commands.abortProcess(process.id);
194
+ if (!abortResult.ok) {
195
+ if (abortResult.code === "worker_reconcile_failed") {
196
+ throw new Error(abortResult.message ?? "Failed to abort process");
197
+ }
198
+ continue;
199
+ }
200
+
201
+ const abortedAgent = abortResult.process ?? process;
202
+ if (!hasProcessEvent(opts.events, abortedAgent.id, "aborted_label_removed")) {
203
+ opts.events.create({
204
+ instanceId: abortedAgent.id,
205
+ eventType: "aborted_label_removed",
206
+ data: opts.getAbortedEventData(abortedAgent),
207
+ });
208
+ }
209
+ opts.result.aborted.push(opts.getResultLabel(process));
210
+ } catch (error) {
211
+ opts.result.errors.push(
212
+ `${opts.getErrorLabel(process)}: ${error instanceof Error ? error.message : String(error)}`,
213
+ );
214
+ }
215
+ }
216
+ }
217
+
218
+ export interface CompletionReconciliationResult {
219
+ changed: boolean;
220
+ writeIdentity?: WriteIdentity;
221
+ metadata?: Record<string, unknown>;
222
+ }
223
+
224
+ export interface CompletionReconciliationOptions {
225
+ candidates: readonly ProcessInstance[];
226
+ result: PollResult;
227
+ externalWrites: ExternalWriteLogRepoLike;
228
+ reconcile(process: ProcessInstance): Promise<CompletionReconciliationResult>;
229
+ getResultLabel(process: ProcessInstance): string;
230
+ getErrorLabel(process: ProcessInstance): string;
231
+ }
232
+
233
+ export async function runWatcherCompletionReconciliation(
234
+ opts: CompletionReconciliationOptions,
235
+ ): Promise<void> {
236
+ for (const process of opts.candidates) {
237
+ try {
238
+ const reconciliation = await opts.reconcile(process);
239
+ if (!reconciliation.changed) {
240
+ continue;
241
+ }
242
+
243
+ if (reconciliation.writeIdentity) {
244
+ recordWriteIfMissing(
245
+ opts.externalWrites,
246
+ process.id,
247
+ reconciliation.writeIdentity,
248
+ reconciliation.metadata,
249
+ );
250
+ }
251
+ opts.result.labelExchanged.push(opts.getResultLabel(process));
252
+ } catch (error) {
253
+ opts.result.errors.push(
254
+ `${opts.getErrorLabel(process)}: ${error instanceof Error ? error.message : String(error)}`,
255
+ );
256
+ }
257
+ }
258
+ }
259
+
260
+ export function shouldEnsureWorkerForExistingActiveAgent(
261
+ deps: { supervisor: WorkerSupervisorLike },
262
+ process: ProcessInstance,
263
+ ): boolean {
264
+ return processNeedsWorker(process) && !deps.supervisor.getWorker(process.id);
265
+ }
266
+
267
+ export function deferWatcherLaunchStart<TLaunchPlan extends { startTurnId: unknown }>(
268
+ launchPlan: TLaunchPlan,
269
+ ): TLaunchPlan {
270
+ return launchPlan.startTurnId === null ? launchPlan : { ...launchPlan, startTurnId: null };
271
+ }
272
+
273
+ export function launchFailureMessage(result: {
274
+ status: number;
275
+ body: Record<string, unknown>;
276
+ }): string {
277
+ return typeof result.body.error === "string" && result.body.error.trim().length > 0
278
+ ? result.body.error
279
+ : `Process launch failed with status ${result.status}`;
280
+ }