@leitwerk-dev/watcher-utils 0.2.0 → 0.3.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 (45) hide show
  1. package/README.md +5 -0
  2. package/dist/{chunk-HG5TEBHZ.js → chunk-B77B4EKW.js} +5 -7
  3. package/dist/chunk-B77B4EKW.js.map +1 -0
  4. package/dist/{chunk-IU3L35PC.js → chunk-D57H46H7.js} +1 -1
  5. package/dist/chunk-D57H46H7.js.map +1 -0
  6. package/dist/{chunk-3KGAUQIG.js → chunk-EWA6E2ZM.js} +1 -1
  7. package/dist/chunk-EWA6E2ZM.js.map +1 -0
  8. package/dist/{chunk-USTHXEZJ.js → chunk-Y4PXUOYO.js} +6 -4
  9. package/dist/chunk-Y4PXUOYO.js.map +1 -0
  10. package/dist/duration-parse.d.ts +2 -0
  11. package/dist/duration-parse.d.ts.map +1 -1
  12. package/dist/duration-parse.js +1 -1
  13. package/dist/index.d.ts +2 -5
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +4 -65
  16. package/dist/index.js.map +1 -1
  17. package/dist/poll-loop.d.ts +22 -2
  18. package/dist/poll-loop.d.ts.map +1 -1
  19. package/dist/poll-loop.js +2 -2
  20. package/dist/polling-coordinator.d.ts +17 -1
  21. package/dist/polling-coordinator.d.ts.map +1 -1
  22. package/dist/polling-coordinator.js +3 -3
  23. package/dist/process-helpers.d.ts +15 -0
  24. package/dist/process-helpers.d.ts.map +1 -1
  25. package/dist/process-helpers.js +1 -1
  26. package/dist/watcher-coordinator.d.ts +77 -2
  27. package/dist/watcher-coordinator.d.ts.map +1 -1
  28. package/dist/watcher-coordinator.js +147 -10
  29. package/dist/watcher-coordinator.js.map +1 -1
  30. package/package.json +4 -4
  31. package/src/duration-parse.ts +5 -1
  32. package/src/index.ts +1 -42
  33. package/src/poll-loop.ts +25 -7
  34. package/src/polling-coordinator.ts +23 -3
  35. package/src/process-helpers.ts +30 -3
  36. package/src/watcher-coordinator.ts +99 -11
  37. package/dist/chunk-3KGAUQIG.js.map +0 -1
  38. package/dist/chunk-HG5TEBHZ.js.map +0 -1
  39. package/dist/chunk-IU3L35PC.js.map +0 -1
  40. package/dist/chunk-USTHXEZJ.js.map +0 -1
  41. package/dist/chunk-XLVMFO6W.js +0 -160
  42. package/dist/chunk-XLVMFO6W.js.map +0 -1
  43. package/dist/trigger-files.d.ts +0 -10
  44. package/dist/trigger-files.d.ts.map +0 -1
  45. package/src/trigger-files.ts +0 -33
@@ -1 +1 @@
1
- {"version":3,"file":"watcher-coordinator.d.ts","sourceRoot":"","sources":["../src/watcher-coordinator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AACpE,OAAO,EACN,KAAK,wBAAwB,EAE7B,KAAK,aAAa,EAClB,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,uBAAuB,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACvF,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EAGN,KAAK,oBAAoB,EAEzB,KAAK,oBAAoB,EACzB,MAAM,sBAAsB,CAAC;AAE9B,MAAM,WAAW,qBAAqB;IACrC,OAAO,CAAC,EAAE,EAAE,MAAM,GAAG,eAAe,GAAG,IAAI,CAAC;CAC5C;AAED,MAAM,WAAW,eAAe;IAC/B,WAAW,CAAC,CAAC,SAAS,uBAAuB,EAC5C,IAAI,EAAE,CAAC,EACP,OAAO,EAAE,eAAe,CAAC,CAAC,CAAC,EAC3B,UAAU,CAAC,EAAE,MAAM,GACjB,IAAI,CAAC;CACR;AAED,MAAM,WAAW,oBAAoB;IACpC,EAAE,EAAE,OAAO,CAAC;IACZ,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,eAAe,GAAG,IAAI,CAAC;CACjC;AA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,eAAe,GAAG,MAAM,CAAC;CAChD;AAED,gBAAgB;AAChB,wBAAsB,kCAAkC,CACvD,IAAI,EAAE,+BAA+B,GACnC,OAAO,CAAC,IAAI,CAAC,CAuBf;AAED,gBAAgB;AAChB,wBAAgB,wCAAwC,CACvD,IAAI,EAAE;IACL,gBAAgB;IAChB,UAAU,EAAE,oBAAoB,CAAC;CACjC,EACD,OAAO,EAAE,eAAe,GACtB,OAAO,CAET;AAED,gBAAgB;AAChB,wBAAgB,uBAAuB,CACtC,WAAW,SAAS;IACnB,gBAAgB;IAChB,WAAW,EAAE,OAAO,CAAC;CACrB,EACA,UAAU,EAAE,WAAW,GAAG,WAAW,CAEtC;AAED,gBAAgB;AAChB,wBAAgB,oBAAoB,CAAC,MAAM,EAAE;IAC5C,gBAAgB;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,gBAAgB;IAChB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC9B,GAAG,MAAM,CAIT"}
@@ -1,14 +1,151 @@
1
1
  import {
2
- continueWatcherAgentStartup,
3
- deferWatcherLaunchStart,
4
- launchFailureMessage,
5
- requireWatcherStartTurnId,
6
- runWatcherAbortReconciliation,
7
- runWatcherCompletionReconciliation,
8
- runWatcherDiscoveryPass,
9
- shouldEnsureWorkerForExistingActiveAgent
10
- } from "./chunk-XLVMFO6W.js";
11
- import "./chunk-3KGAUQIG.js";
2
+ ensureWorkerForActiveAgent,
3
+ hasProcessEvent,
4
+ processNeedsWorker
5
+ } from "./chunk-EWA6E2ZM.js";
6
+
7
+ // src/watcher-coordinator.ts
8
+ import {
9
+ recordWriteIfMissing
10
+ } from "@leitwerk-dev/external-writes/internal";
11
+ function requireWatcherStartTurnId(launchPlan, targetLabel) {
12
+ if (launchPlan.startTurnId) {
13
+ return launchPlan.startTurnId;
14
+ }
15
+ throw new Error(
16
+ `Watcher launcher '${launchPlan.launcherId}' did not declare a startTurnId for ${targetLabel}`
17
+ );
18
+ }
19
+ async function continueWatcherAgentStartup(deps, opts) {
20
+ const { process } = opts;
21
+ if (!hasProcessEvent(deps.events, process.id, "agent_created")) {
22
+ deps.events.create({
23
+ instanceId: process.id,
24
+ eventType: "agent_created",
25
+ data: opts.createdEventData
26
+ });
27
+ }
28
+ await opts.afterCreatedEvent?.(process);
29
+ await opts.beforeStart?.(process);
30
+ let currentProcess = deps.processes.getById(process.id) ?? process;
31
+ if (currentProcess.lifecycleStatus === "discovered") {
32
+ const startResult = await deps.commands.startProcess(currentProcess.id, opts.startTurnId);
33
+ if (!startResult.ok) {
34
+ currentProcess = startResult.process ?? currentProcess;
35
+ throw new Error(startResult.message ?? "Failed to start process");
36
+ }
37
+ currentProcess = startResult.process ?? currentProcess;
38
+ if (opts.broadcastCreated !== false) {
39
+ deps.broadcaster.sendDurable(
40
+ "process.created",
41
+ {
42
+ process: currentProcess,
43
+ processId: currentProcess.processId,
44
+ ...opts.createdBroadcastData
45
+ },
46
+ currentProcess.id
47
+ );
48
+ }
49
+ }
50
+ await ensureWorkerForActiveAgent(deps, currentProcess);
51
+ return currentProcess.id;
52
+ }
53
+ async function runWatcherDiscoveryPass(opts) {
54
+ for (const item of opts.items) {
55
+ try {
56
+ const existingAgent = opts.findExistingAgent(item);
57
+ if (existingAgent) {
58
+ if (existingAgent.lifecycleStatus === "discovered") {
59
+ const resumeResult = await opts.resumeDiscoveredAgent(existingAgent, item);
60
+ if (resumeResult === "skipped") {
61
+ opts.result.skipped.push(opts.getResultLabel(item));
62
+ }
63
+ continue;
64
+ }
65
+ if (opts.ensureWorkerForExistingAgent) {
66
+ const handled = await opts.ensureWorkerForExistingAgent(existingAgent, item);
67
+ if (handled) {
68
+ continue;
69
+ }
70
+ }
71
+ opts.result.skipped.push(opts.getResultLabel(item));
72
+ continue;
73
+ }
74
+ const createResult = await opts.createAgent(item);
75
+ if (createResult?.outcome === "created") {
76
+ opts.result.created.push(opts.getResultLabel(item));
77
+ continue;
78
+ }
79
+ if (createResult?.outcome === "skipped") {
80
+ opts.result.skipped.push(opts.getResultLabel(item));
81
+ }
82
+ } catch (error) {
83
+ opts.result.errors.push(opts.formatError(item, error));
84
+ }
85
+ }
86
+ }
87
+ async function runWatcherAbortReconciliation(opts) {
88
+ for (const process of opts.candidates) {
89
+ try {
90
+ const shouldAbort = await opts.shouldAbort(process);
91
+ if (!shouldAbort) {
92
+ continue;
93
+ }
94
+ const abortResult = await opts.commands.abortProcess(process.id);
95
+ if (!abortResult.ok) {
96
+ if (abortResult.code === "worker_reconcile_failed") {
97
+ throw new Error(abortResult.message ?? "Failed to abort process");
98
+ }
99
+ continue;
100
+ }
101
+ const abortedAgent = abortResult.process ?? process;
102
+ if (!hasProcessEvent(opts.events, abortedAgent.id, "aborted_label_removed")) {
103
+ opts.events.create({
104
+ instanceId: abortedAgent.id,
105
+ eventType: "aborted_label_removed",
106
+ data: opts.getAbortedEventData(abortedAgent)
107
+ });
108
+ }
109
+ opts.result.aborted.push(opts.getResultLabel(process));
110
+ } catch (error) {
111
+ opts.result.errors.push(
112
+ `${opts.getErrorLabel(process)}: ${error instanceof Error ? error.message : String(error)}`
113
+ );
114
+ }
115
+ }
116
+ }
117
+ async function runWatcherCompletionReconciliation(opts) {
118
+ for (const process of opts.candidates) {
119
+ try {
120
+ const reconciliation = await opts.reconcile(process);
121
+ if (!reconciliation.changed) {
122
+ continue;
123
+ }
124
+ if (reconciliation.writeIdentity) {
125
+ recordWriteIfMissing(
126
+ opts.externalWrites,
127
+ process.id,
128
+ reconciliation.writeIdentity,
129
+ reconciliation.metadata
130
+ );
131
+ }
132
+ opts.result.labelExchanged.push(opts.getResultLabel(process));
133
+ } catch (error) {
134
+ opts.result.errors.push(
135
+ `${opts.getErrorLabel(process)}: ${error instanceof Error ? error.message : String(error)}`
136
+ );
137
+ }
138
+ }
139
+ }
140
+ function shouldEnsureWorkerForExistingActiveAgent(deps, process) {
141
+ return processNeedsWorker(process) && !deps.supervisor.getWorker(process.id);
142
+ }
143
+ function deferWatcherLaunchStart(launchPlan) {
144
+ return launchPlan.startTurnId === null ? launchPlan : { ...launchPlan, startTurnId: null };
145
+ }
146
+ function launchFailureMessage(result) {
147
+ return typeof result.body.error === "string" && result.body.error.trim().length > 0 ? result.body.error : `Process launch failed with status ${result.status}`;
148
+ }
12
149
  export {
13
150
  continueWatcherAgentStartup,
14
151
  deferWatcherLaunchStart,
@@ -1 +1 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
1
+ {"version":3,"sources":["../src/watcher-coordinator.ts"],"sourcesContent":["import type { ProcessInstance, TurnId } from \"@leitwerk-dev/domain\";\nimport type { WriteIdentity } from \"@leitwerk-dev/external-writes\";\nimport {\n\ttype ExternalWriteLogRepoLike,\n\trecordWriteIfMissing,\n} from \"@leitwerk-dev/external-writes/internal\";\nimport type { KnownDurableWsFrameType, WsPayloadByType } from \"@leitwerk-dev/protocol\";\nimport type { PollResult } from \"./poll-loop.js\";\nimport {\n\tensureWorkerForActiveAgent,\n\thasProcessEvent,\n\ttype ProcessEventRepoLike,\n\tprocessNeedsWorker,\n\ttype WorkerSupervisorLike,\n} from \"./process-helpers.js\";\n\n/** @internal */\nexport interface AgentRepoAccessorLike {\n\t/** @internal */\n\tgetById(id: string): ProcessInstance | null;\n}\n\n/** @internal */\nexport interface BroadcasterLike {\n\t/** @internal */\n\tsendDurable<T extends KnownDurableWsFrameType>(\n\t\ttype: T,\n\t\tpayload: WsPayloadByType[T],\n\t\tinstanceId?: string,\n\t): void;\n}\n\n/** @internal */\nexport interface WatcherCommandResult {\n\t/** @internal */\n\tok: boolean;\n\t/** @internal */\n\tcode?: string;\n\t/** @internal */\n\tmessage?: string;\n\t/** @internal */\n\tprocess?: ProcessInstance | null;\n}\n\n/** @internal */\nexport interface WatcherCommandServiceLike {\n\t/** @internal */\n\tstartProcess(instanceId: string, startTurnId: TurnId): Promise<WatcherCommandResult>;\n\t/** @internal */\n\tabortProcess(instanceId: string): Promise<WatcherCommandResult>;\n}\n\n/** @internal */\nexport interface WatcherStartupDeps {\n\t/** @internal */\n\tprocesses: AgentRepoAccessorLike;\n\t/** @internal */\n\tevents: ProcessEventRepoLike;\n\t/** @internal */\n\tbroadcaster: BroadcasterLike;\n\t/** @internal */\n\tcommands: WatcherCommandServiceLike;\n\t/** @internal */\n\tsupervisor: WorkerSupervisorLike;\n}\n\n/** @internal */\nexport interface ContinueWatcherAgentStartupOptions {\n\t/** @internal */\n\tprocess: ProcessInstance;\n\t/** @internal */\n\tstartTurnId: TurnId;\n\t/** @internal */\n\tcreatedEventData: Record<string, unknown>;\n\t/** @internal */\n\tcreatedBroadcastData: Record<string, unknown>;\n\t/** Defaults to true. Set false when the shared launch executor already emitted process.created. @internal */\n\tbroadcastCreated?: boolean;\n\t/** @internal */\n\tafterCreatedEvent?: (process: ProcessInstance) => Promise<void> | void;\n\t/** @internal */\n\tbeforeStart?: (process: ProcessInstance) => Promise<void>;\n}\n\n/** @internal */\nexport function requireWatcherStartTurnId(\n\tlaunchPlan: {\n\t\t/** @internal */\n\t\tlauncherId: string;\n\t\t/** @internal */\n\t\tstartTurnId: TurnId | null;\n\t},\n\ttargetLabel: string,\n): TurnId {\n\tif (launchPlan.startTurnId) {\n\t\treturn launchPlan.startTurnId;\n\t}\n\tthrow new Error(\n\t\t`Watcher launcher '${launchPlan.launcherId}' did not declare a startTurnId for ${targetLabel}`,\n\t);\n}\n\n/** @internal */\nexport async function continueWatcherAgentStartup(\n\tdeps: WatcherStartupDeps,\n\topts: ContinueWatcherAgentStartupOptions,\n): Promise<string> {\n\tconst { process } = opts;\n\n\tif (!hasProcessEvent(deps.events, process.id, \"agent_created\")) {\n\t\tdeps.events.create({\n\t\t\tinstanceId: process.id,\n\t\t\teventType: \"agent_created\",\n\t\t\tdata: opts.createdEventData,\n\t\t});\n\t}\n\n\tawait opts.afterCreatedEvent?.(process);\n\tawait opts.beforeStart?.(process);\n\n\tlet currentProcess = deps.processes.getById(process.id) ?? process;\n\tif (currentProcess.lifecycleStatus === \"discovered\") {\n\t\tconst startResult = await deps.commands.startProcess(currentProcess.id, opts.startTurnId);\n\t\tif (!startResult.ok) {\n\t\t\tcurrentProcess = startResult.process ?? currentProcess;\n\t\t\tthrow new Error(startResult.message ?? \"Failed to start process\");\n\t\t}\n\t\tcurrentProcess = startResult.process ?? currentProcess;\n\t\tif (opts.broadcastCreated !== false) {\n\t\t\tdeps.broadcaster.sendDurable(\n\t\t\t\t\"process.created\",\n\t\t\t\t{\n\t\t\t\t\tprocess: currentProcess,\n\t\t\t\t\tprocessId: currentProcess.processId,\n\t\t\t\t\t...opts.createdBroadcastData,\n\t\t\t\t},\n\t\t\t\tcurrentProcess.id,\n\t\t\t);\n\t\t}\n\t}\n\n\tawait ensureWorkerForActiveAgent(deps, currentProcess);\n\treturn currentProcess.id;\n}\n\n/** @internal */\nexport type DiscoveryResumeResult = \"handled\" | \"skipped\" | undefined;\n\n/** @internal */\nexport type DiscoveryCreateResult =\n\t| {\n\t\t\t/** @internal */\n\t\t\toutcome: \"created\";\n\t\t\t/** @internal */\n\t\t\tinstanceId: string;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\toutcome: \"skipped\";\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\toutcome: \"handled\";\n\t }\n\t| null\n\t| undefined;\n\n/** @internal */\nexport interface DiscoveryPassOptions<TItem> {\n\t/** @internal */\n\titems: readonly TItem[];\n\t/** @internal */\n\tresult: PollResult;\n\t/** @internal */\n\tfindExistingAgent(item: TItem): ProcessInstance | null;\n\t/** @internal */\n\tgetResultLabel(item: TItem): string;\n\t/** @internal */\n\tresumeDiscoveredAgent(process: ProcessInstance, item: TItem): Promise<DiscoveryResumeResult>;\n\t/** @internal */\n\tcreateAgent(item: TItem): Promise<DiscoveryCreateResult>;\n\t/** @internal */\n\tensureWorkerForExistingAgent?(process: ProcessInstance, item: TItem): Promise<boolean>;\n\t/** @internal */\n\tformatError(item: TItem, error: unknown): string;\n}\n\n/** @internal */\nexport async function runWatcherDiscoveryPass<TItem>(\n\topts: DiscoveryPassOptions<TItem>,\n): Promise<void> {\n\tfor (const item of opts.items) {\n\t\ttry {\n\t\t\tconst existingAgent = opts.findExistingAgent(item);\n\t\t\tif (existingAgent) {\n\t\t\t\tif (existingAgent.lifecycleStatus === \"discovered\") {\n\t\t\t\t\tconst resumeResult = await opts.resumeDiscoveredAgent(existingAgent, item);\n\t\t\t\t\tif (resumeResult === \"skipped\") {\n\t\t\t\t\t\topts.result.skipped.push(opts.getResultLabel(item));\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (opts.ensureWorkerForExistingAgent) {\n\t\t\t\t\tconst handled = await opts.ensureWorkerForExistingAgent(existingAgent, item);\n\t\t\t\t\tif (handled) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\topts.result.skipped.push(opts.getResultLabel(item));\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst createResult = await opts.createAgent(item);\n\t\t\tif (createResult?.outcome === \"created\") {\n\t\t\t\topts.result.created.push(opts.getResultLabel(item));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (createResult?.outcome === \"skipped\") {\n\t\t\t\topts.result.skipped.push(opts.getResultLabel(item));\n\t\t\t}\n\t\t} catch (error) {\n\t\t\topts.result.errors.push(opts.formatError(item, error));\n\t\t}\n\t}\n}\n\n/** @internal */\nexport interface AbortReconciliationOptions {\n\t/** @internal */\n\tcandidates: readonly ProcessInstance[];\n\t/** @internal */\n\tresult: PollResult;\n\t/** @internal */\n\tevents: ProcessEventRepoLike;\n\t/** @internal */\n\tcommands: WatcherCommandServiceLike;\n\t/** @internal */\n\tshouldAbort(process: ProcessInstance): Promise<boolean>;\n\t/** @internal */\n\tgetResultLabel(process: ProcessInstance): string;\n\t/** @internal */\n\tgetErrorLabel(process: ProcessInstance): string;\n\t/** @internal */\n\tgetAbortedEventData(process: ProcessInstance): Record<string, unknown>;\n}\n\n/** @internal */\nexport async function runWatcherAbortReconciliation(\n\topts: AbortReconciliationOptions,\n): Promise<void> {\n\tfor (const process of opts.candidates) {\n\t\ttry {\n\t\t\tconst shouldAbort = await opts.shouldAbort(process);\n\t\t\tif (!shouldAbort) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst abortResult = await opts.commands.abortProcess(process.id);\n\t\t\tif (!abortResult.ok) {\n\t\t\t\tif (abortResult.code === \"worker_reconcile_failed\") {\n\t\t\t\t\tthrow new Error(abortResult.message ?? \"Failed to abort process\");\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst abortedAgent = abortResult.process ?? process;\n\t\t\tif (!hasProcessEvent(opts.events, abortedAgent.id, \"aborted_label_removed\")) {\n\t\t\t\topts.events.create({\n\t\t\t\t\tinstanceId: abortedAgent.id,\n\t\t\t\t\teventType: \"aborted_label_removed\",\n\t\t\t\t\tdata: opts.getAbortedEventData(abortedAgent),\n\t\t\t\t});\n\t\t\t}\n\t\t\topts.result.aborted.push(opts.getResultLabel(process));\n\t\t} catch (error) {\n\t\t\topts.result.errors.push(\n\t\t\t\t`${opts.getErrorLabel(process)}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/** @internal */\nexport interface CompletionReconciliationResult {\n\t/** @internal */\n\tchanged: boolean;\n\t/** @internal */\n\twriteIdentity?: WriteIdentity;\n\t/** @internal */\n\tmetadata?: Record<string, unknown>;\n}\n\n/** @internal */\nexport interface CompletionReconciliationOptions {\n\t/** @internal */\n\tcandidates: readonly ProcessInstance[];\n\t/** @internal */\n\tresult: PollResult;\n\t/** @internal */\n\texternalWrites: ExternalWriteLogRepoLike;\n\t/** @internal */\n\treconcile(process: ProcessInstance): Promise<CompletionReconciliationResult>;\n\t/** @internal */\n\tgetResultLabel(process: ProcessInstance): string;\n\t/** @internal */\n\tgetErrorLabel(process: ProcessInstance): string;\n}\n\n/** @internal */\nexport async function runWatcherCompletionReconciliation(\n\topts: CompletionReconciliationOptions,\n): Promise<void> {\n\tfor (const process of opts.candidates) {\n\t\ttry {\n\t\t\tconst reconciliation = await opts.reconcile(process);\n\t\t\tif (!reconciliation.changed) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (reconciliation.writeIdentity) {\n\t\t\t\trecordWriteIfMissing(\n\t\t\t\t\topts.externalWrites,\n\t\t\t\t\tprocess.id,\n\t\t\t\t\treconciliation.writeIdentity,\n\t\t\t\t\treconciliation.metadata,\n\t\t\t\t);\n\t\t\t}\n\t\t\topts.result.labelExchanged.push(opts.getResultLabel(process));\n\t\t} catch (error) {\n\t\t\topts.result.errors.push(\n\t\t\t\t`${opts.getErrorLabel(process)}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/** @internal */\nexport function shouldEnsureWorkerForExistingActiveAgent(\n\tdeps: {\n\t\t/** @internal */\n\t\tsupervisor: WorkerSupervisorLike;\n\t},\n\tprocess: ProcessInstance,\n): boolean {\n\treturn processNeedsWorker(process) && !deps.supervisor.getWorker(process.id);\n}\n\n/** @internal */\nexport function deferWatcherLaunchStart<\n\tTLaunchPlan extends {\n\t\t/** @internal */\n\t\tstartTurnId: unknown;\n\t},\n>(launchPlan: TLaunchPlan): TLaunchPlan {\n\treturn launchPlan.startTurnId === null ? launchPlan : { ...launchPlan, startTurnId: null };\n}\n\n/** @internal */\nexport function launchFailureMessage(result: {\n\t/** @internal */\n\tstatus: number;\n\t/** @internal */\n\tbody: Record<string, unknown>;\n}): string {\n\treturn typeof result.body.error === \"string\" && result.body.error.trim().length > 0\n\t\t? result.body.error\n\t\t: `Process launch failed with status ${result.status}`;\n}\n"],"mappings":";;;;;;;AAEA;AAAA,EAEC;AAAA,OACM;AAgFA,SAAS,0BACf,YAMA,aACS;AACT,MAAI,WAAW,aAAa;AAC3B,WAAO,WAAW;AAAA,EACnB;AACA,QAAM,IAAI;AAAA,IACT,qBAAqB,WAAW,UAAU,uCAAuC,WA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c,OAAO,CAAC,KAAK,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,MAC1F;AAAA,IACD;AAAA,EACD;AACD;AA6BA,eAAsB,mCACrB,MACgB;AAChB,aAAW,WAAW,KAAK,YAAY;AACtC,QAAI;AACH,YAAM,iBAAiB,MAAM,KAAK,UAAU,OAAO;AACnD,UAAI,CAAC,eAAe,SAAS;AAC5B;AAAA,MACD;AAEA,UAAI,eAAe,eAAe;AACjC;AAAA,UACC,KAAK;AAAA,UACL,QAAQ;AAAA,UACR,eAAe;AAAA,UACf,eAAe;AAAA,QAChB;AAAA,MACD;AACA,WAAK,OAAO,eAAe,KAAK,KAAK,eAAe,OAAO,CAAC;AAAA,IAC7D,SAAS,OAAO;AACf,WAAK,OAAO,OAAO;AAAA,QAClB,GAAG,KAAK,cAAc,OAAO,CAAC,KAAK,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,MAC1F;AAAA,IACD;AAAA,EACD;AACD;AAGO,SAAS,yCACf,MAIA,SACU;AACV,SAAO,mBAAmB,OAAO,KAAK,CAAC,KAAK,WAAW,UAAU,QAAQ,EAAE;AAC5E;AAGO,SAAS,wBAKd,YAAsC;AACvC,SAAO,WAAW,gBAAgB,OAAO,aAAa,EAAE,GAAG,YAAY,aAAa,KAAK;AAC1F;AAGO,SAAS,qBAAqB,QAK1B;AACV,SAAO,OAAO,OAAO,KAAK,UAAU,YAAY,OAAO,KAAK,MAAM,KAAK,EAAE,SAAS,IAC/E,OAAO,KAAK,QACZ,qCAAqC,OAAO,MAAM;AACtD;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leitwerk-dev/watcher-utils",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/leitwerk-dev/leitwerk.git",
@@ -18,9 +18,9 @@
18
18
  "build": "tsup --silent"
19
19
  },
20
20
  "dependencies": {
21
- "@leitwerk-dev/domain": "0.2.0",
22
- "@leitwerk-dev/external-writes": "0.2.0",
23
- "@leitwerk-dev/protocol": "0.2.0",
21
+ "@leitwerk-dev/domain": "0.3.0",
22
+ "@leitwerk-dev/external-writes": "0.3.0",
23
+ "@leitwerk-dev/protocol": "0.3.0",
24
24
  "ms": "^2.1.3"
25
25
  },
26
26
  "devDependencies": {
@@ -7,10 +7,14 @@ import ms from "ms";
7
7
  * `options.allowHours` is retained for existing callers; the underlying `ms`
8
8
  * parser supports hours and other common duration units by default.
9
9
  */
10
+ /** @public */
10
11
  export function parseDurationMs(
11
12
  value: string,
12
13
  defaultMs: number,
13
- _options: { allowHours?: boolean } = {},
14
+ _options: {
15
+ /** @public */
16
+ allowHours?: boolean;
17
+ } = {},
14
18
  ): number {
15
19
  const parsed = ms(value.trim() as ms.StringValue);
16
20
  if (!Number.isFinite(parsed) || parsed < 0) {
package/src/index.ts CHANGED
@@ -1,48 +1,7 @@
1
1
  export { parseDurationMs } from "./duration-parse.js";
2
2
  export {
3
- createPollLoop,
4
3
  createPollSchedule,
5
4
  emptyPollResult,
6
- type PollLoop,
7
5
  type PollResult,
8
- type PollResultWithErrors,
9
6
  } from "./poll-loop.js";
10
- export {
11
- createPollingCoordinator,
12
- type PollingCoordinator,
13
- type PollingLogger,
14
- type PollingRegistration,
15
- type RegisteredPoller,
16
- } from "./polling-coordinator.js";
17
- export {
18
- ensureWorkerForActiveAgent,
19
- hasProcessEvent,
20
- type ProcessEventRepoLike,
21
- processNeedsWorker,
22
- type WorkerSupervisorLike,
23
- } from "./process-helpers.js";
24
- export {
25
- consumeTriggerFile,
26
- errorCode,
27
- readTriggerFile,
28
- type TriggerFileReadResult,
29
- } from "./trigger-files.js";
30
- export {
31
- type AgentRepoAccessorLike,
32
- type BroadcasterLike,
33
- type CompletionReconciliationOptions,
34
- type CompletionReconciliationResult,
35
- type ContinueWatcherAgentStartupOptions,
36
- continueWatcherAgentStartup,
37
- type DiscoveryPassOptions,
38
- deferWatcherLaunchStart,
39
- launchFailureMessage,
40
- requireWatcherStartTurnId,
41
- runWatcherAbortReconciliation,
42
- runWatcherCompletionReconciliation,
43
- runWatcherDiscoveryPass,
44
- shouldEnsureWorkerForExistingActiveAgent,
45
- type WatcherCommandResult,
46
- type WatcherCommandServiceLike,
47
- type WatcherStartupDeps,
48
- } from "./watcher-coordinator.js";
7
+ export { createPollingCoordinator } from "./polling-coordinator.js";
package/src/poll-loop.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { parseDurationMs } from "./duration-parse.js";
2
2
 
3
- /** Reserve the next poll time for a caller-owned key, before starting its work. */
3
+ /** Reserve the next poll time for a caller-owned key, before starting its work. @public */
4
4
  export function createPollSchedule(now: () => number = () => Date.now()) {
5
5
  const dueAt = new Map<string, number>();
6
6
  return (key: string, interval = "30s", timestamp = now()): boolean => {
@@ -10,14 +10,21 @@ export function createPollSchedule(now: () => number = () => Date.now()) {
10
10
  };
11
11
  }
12
12
 
13
+ /** @public */
13
14
  export interface PollResult {
15
+ /** @public */
14
16
  created: string[];
17
+ /** @internal */
15
18
  aborted: string[];
19
+ /** @internal */
16
20
  labelExchanged: string[];
21
+ /** @public */
17
22
  skipped: string[];
23
+ /** @public */
18
24
  errors: string[];
19
25
  }
20
26
 
27
+ /** @public */
21
28
  export function emptyPollResult(): PollResult {
22
29
  return {
23
30
  created: [],
@@ -28,26 +35,39 @@ export function emptyPollResult(): PollResult {
28
35
  };
29
36
  }
30
37
 
38
+ /** @internal */
31
39
  export interface PollResultWithErrors {
40
+ /** @internal */
32
41
  readonly errors: readonly string[];
33
42
  }
34
43
 
44
+ /** @internal */
35
45
  export interface PollLoop<T extends PollResultWithErrors = PollResult> {
46
+ /** @internal */
36
47
  poll(): Promise<T>;
48
+ /** @internal */
37
49
  start(): void;
38
- stop(): void;
50
+ /** @internal */
51
+ stop(): Promise<void>;
39
52
  }
40
53
 
41
54
  /**
42
55
  * Create a non-overlapping polling loop. `pollOnce` is the actual work;
43
56
  * concurrent calls to `poll()` coalesce into the in-flight promise.
44
57
  */
58
+ /** @internal */
45
59
  export function createPollLoop<T extends PollResultWithErrors>(opts: {
60
+ /** @internal */
46
61
  pollOnce: () => Promise<T>;
62
+ /** @internal */
47
63
  isEnabled: () => boolean;
64
+ /** @internal */
48
65
  pollInterval: () => string;
66
+ /** @internal */
49
67
  defaultIntervalMs?: number;
68
+ /** @internal */
50
69
  onScheduledResult: (result: T, durationMs: number) => void;
70
+ /** @internal */
51
71
  onScheduledError: (error: unknown, durationMs: number) => void;
52
72
  }): PollLoop<T> {
53
73
  let timer: ReturnType<typeof setInterval> | null = null;
@@ -90,12 +110,10 @@ export function createPollLoop<T extends PollResultWithErrors>(opts: {
90
110
  timer = setInterval(pollScheduled, ms);
91
111
  pollScheduled();
92
112
  },
93
- stop() {
94
- if (!timer) {
95
- return;
96
- }
97
- clearInterval(timer);
113
+ async stop() {
114
+ if (timer) clearInterval(timer);
98
115
  timer = null;
116
+ await pollInFlight;
99
117
  },
100
118
  };
101
119
  }
@@ -1,28 +1,44 @@
1
1
  import { createPollLoop, type PollResult, type PollResultWithErrors } from "./poll-loop.js";
2
2
 
3
+ /** @internal */
3
4
  export interface PollingLogger {
5
+ /** @internal */
4
6
  warn(payload: Record<string, unknown>, message?: string): void;
7
+ /** @internal */
5
8
  error(payload: Record<string, unknown>, message?: string): void;
6
9
  }
7
10
 
11
+ /** @internal */
8
12
  export interface PollingRegistration<T extends PollResultWithErrors> {
13
+ /** @internal */
9
14
  id: string;
15
+ /** @internal */
10
16
  pollOnce(): Promise<T>;
17
+ /** @internal */
11
18
  isEnabled(): boolean;
19
+ /** @internal */
12
20
  pollInterval(): string;
21
+ /** @internal */
13
22
  defaultIntervalMs?: number;
14
23
  }
15
24
 
25
+ /** @internal */
16
26
  export interface RegisteredPoller<T extends PollResultWithErrors = PollResult> {
27
+ /** @internal */
17
28
  poll(): Promise<T>;
18
29
  }
19
30
 
31
+ /** @internal */
20
32
  export interface PollingCoordinator {
33
+ /** @internal */
21
34
  create<T extends PollResultWithErrors>(registration: PollingRegistration<T>): RegisteredPoller<T>;
35
+ /** @internal */
22
36
  start(): void;
23
- stop(): void;
37
+ /** @internal */
38
+ stop(): Promise<void>;
24
39
  }
25
40
 
41
+ /** @internal */
26
42
  export function createPollingCoordinator(logger: PollingLogger): PollingCoordinator {
27
43
  const loops = new Map<string, ReturnType<typeof createPollLoop>>();
28
44
  let sealed = false;
@@ -56,8 +72,12 @@ export function createPollingCoordinator(logger: PollingLogger): PollingCoordina
56
72
  sealed = true;
57
73
  for (const loop of loops.values()) loop.start();
58
74
  },
59
- stop() {
60
- for (const loop of loops.values()) loop.stop();
75
+ async stop() {
76
+ const results = await Promise.allSettled([...loops.values()].map((loop) => loop.stop()));
77
+ const errors = results
78
+ .filter((result) => result.status === "rejected")
79
+ .map((result) => result.reason);
80
+ if (errors.length) throw new AggregateError(errors, "Polling shutdown failed");
61
81
  },
62
82
  };
63
83
  }
@@ -1,18 +1,38 @@
1
1
  import type { ProcessInstance } from "@leitwerk-dev/domain";
2
2
 
3
+ /** @internal */
3
4
  export interface ProcessEventRepoLike {
4
- create(input: { instanceId: string; eventType: string; data?: Record<string, unknown> }): unknown;
5
- listByInstance(instanceId: string, limit?: number): Array<{ eventType: string }>;
5
+ /** @internal */
6
+ create(input: {
7
+ /** @internal */
8
+ instanceId: string;
9
+ /** @internal */
10
+ eventType: string;
11
+ /** @internal */
12
+ data?: Record<string, unknown>;
13
+ }): unknown;
14
+ /** @internal */
15
+ listByInstance(
16
+ instanceId: string,
17
+ limit?: number,
18
+ ): Array<{
19
+ /** @internal */
20
+ eventType: string;
21
+ }>;
6
22
  }
7
23
 
24
+ /** @internal */
8
25
  export interface WorkerSupervisorLike {
26
+ /** @internal */
9
27
  spawnWorker(instanceId: string): Promise<unknown>;
28
+ /** @internal */
10
29
  getWorker(instanceId: string): unknown | undefined;
11
30
  }
12
31
 
13
32
  /**
14
33
  * Check whether a process already has an event of the given type.
15
34
  */
35
+ /** @internal */
16
36
  export function hasProcessEvent(
17
37
  events: ProcessEventRepoLike,
18
38
  instanceId: string,
@@ -21,6 +41,7 @@ export function hasProcessEvent(
21
41
  return events.listByInstance(instanceId, 200).some((event) => event.eventType === eventType);
22
42
  }
23
43
 
44
+ /** @internal */
24
45
  export function processNeedsWorker(
25
46
  process: Pick<ProcessInstance, "selectedTurnId" | "lifecycleStatus">,
26
47
  ): boolean {
@@ -32,8 +53,14 @@ export function processNeedsWorker(
32
53
  * no running worker. No-ops when the process is not worker-runnable or already
33
54
  * has a worker.
34
55
  */
56
+ /** @internal */
35
57
  export async function ensureWorkerForActiveAgent(
36
- deps: { events: ProcessEventRepoLike; supervisor: WorkerSupervisorLike },
58
+ deps: {
59
+ /** @internal */
60
+ events: ProcessEventRepoLike;
61
+ /** @internal */
62
+ supervisor: WorkerSupervisorLike;
63
+ },
37
64
  process: ProcessInstance,
38
65
  ): Promise<void> {
39
66
  if (!processNeedsWorker(process) || deps.supervisor.getWorker(process.id)) {