@igorjpimenta/winch 0.0.0-stage → 2026.11.22-beta.2

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 (88) hide show
  1. package/.migrations/0000_next_katie_power.sql +99 -0
  2. package/.migrations/0001_add-events-kind.sql +8 -0
  3. package/.migrations/0002_drop-session-budgets.sql +1 -0
  4. package/.migrations/0003_pink_siren.sql +8 -0
  5. package/.migrations/0004_salty_trauma.sql +1 -0
  6. package/.migrations/0005_classy_havok.sql +1 -0
  7. package/.migrations/0006_recursive_items.sql +265 -0
  8. package/.migrations/0007_unify_statuses.sql +35 -0
  9. package/.migrations/0008_core_dispatch.sql +61 -0
  10. package/.migrations/0009_webhooks.sql +17 -0
  11. package/.migrations/0010_dispatch_consumer_id.sql +1 -0
  12. package/.migrations/0011_dispatch_delivery_leases.sql +53 -0
  13. package/.migrations/0012_dispatch_fencing_audit.sql +32 -0
  14. package/.migrations/meta/0000_snapshot.json +658 -0
  15. package/.migrations/meta/0001_snapshot.json +665 -0
  16. package/.migrations/meta/0002_snapshot.json +604 -0
  17. package/.migrations/meta/0003_snapshot.json +656 -0
  18. package/.migrations/meta/0004_snapshot.json +664 -0
  19. package/.migrations/meta/0005_snapshot.json +671 -0
  20. package/.migrations/meta/0006_snapshot.json +1089 -0
  21. package/.migrations/meta/0007_unify_statuses_snapshot.json +1097 -0
  22. package/.migrations/meta/0008_snapshot.json +1382 -0
  23. package/.migrations/meta/0009_snapshot.json +1428 -0
  24. package/.migrations/meta/0010_snapshot.json +1435 -0
  25. package/.migrations/meta/0011_snapshot.json +1670 -0
  26. package/.migrations/meta/0012_snapshot.json +1900 -0
  27. package/.migrations/meta/_journal.json +97 -0
  28. package/README.md +480 -2
  29. package/bin/winch.js +4 -0
  30. package/package.json +36 -4
  31. package/plugins/README.md +304 -0
  32. package/plugins/openclaw/winch/README.md +71 -0
  33. package/plugins/openclaw/winch/dispatch.js +236 -0
  34. package/plugins/openclaw/winch/index.js +139 -0
  35. package/plugins/openclaw/winch/meta.js +35 -0
  36. package/plugins/openclaw/winch/openclaw.plugin.json +43 -0
  37. package/plugins/openclaw/winch/package.json +37 -0
  38. package/plugins/opencode/winch/dispatch.js +228 -0
  39. package/plugins/opencode/winch/hooks.js +22 -0
  40. package/plugins/opencode/winch/identity.js +34 -0
  41. package/plugins/opencode/winch/index.js +104 -0
  42. package/plugins/opencode/winch/package.json +26 -0
  43. package/src/cli.js +434 -0
  44. package/src/config.js +181 -0
  45. package/src/db.js +39 -0
  46. package/src/deps.js +70 -0
  47. package/src/dispatch-server.js +204 -0
  48. package/src/dispatch-webhook.js +221 -0
  49. package/src/dispatch.js +258 -0
  50. package/src/events-ws.js +269 -0
  51. package/src/identity.js +140 -0
  52. package/src/ids.js +18 -0
  53. package/src/mcp-http.js +208 -0
  54. package/src/mcp.js +107 -0
  55. package/src/merges.js +150 -0
  56. package/src/paths.js +15 -0
  57. package/src/ready-queue.js +77 -0
  58. package/src/release.js +96 -0
  59. package/src/reserved.js +23 -0
  60. package/src/schema.js +302 -0
  61. package/src/store/admission.js +314 -0
  62. package/src/store/artifacts.js +24 -0
  63. package/src/store/attempts.js +22 -0
  64. package/src/store/claims.js +182 -0
  65. package/src/store/core.js +225 -0
  66. package/src/store/delivery.js +137 -0
  67. package/src/store/deps.js +62 -0
  68. package/src/store/dispatch-events.js +38 -0
  69. package/src/store/epics.js +31 -0
  70. package/src/store/events.js +21 -0
  71. package/src/store/gates.js +85 -0
  72. package/src/store/index.js +135 -0
  73. package/src/store/items.js +303 -0
  74. package/src/store/stories.js +37 -0
  75. package/src/store/sweep.js +77 -0
  76. package/src/store/tasks.js +190 -0
  77. package/src/store/webhook.js +197 -0
  78. package/src/tools/accept-wake.js +30 -0
  79. package/src/tools/assign.js +75 -0
  80. package/src/tools/claim.js +88 -0
  81. package/src/tools/definitions.js +371 -0
  82. package/src/tools/delegate.js +147 -0
  83. package/src/tools/index.js +44 -0
  84. package/src/tools/plan.js +262 -0
  85. package/src/tools/read.js +103 -0
  86. package/src/tools/report.js +190 -0
  87. package/src/tools/shared.js +62 -0
  88. package/src/watcher.js +105 -0
package/src/deps.js ADDED
@@ -0,0 +1,70 @@
1
+ // deps.js — dependency mutations with DAG cycle prevention.
2
+ //
3
+ // `addDep(store, from, to)` rejects with `{ok:false, code:"cycle", path:[...]}`
4
+ // if accepting the edge would create a cycle. We DFS forward from `to` over
5
+ // the existing item_edges graph; if we reach `from`, the new edge would close
6
+ // a loop. Depth-limited to avoid pathological graphs (500 nodes is plenty for
7
+ // any human-scale backlog).
8
+
9
+ const MAX_DFS_NODES = 500;
10
+
11
+ function reachable(store, startId, targetId) {
12
+ const cap = store.config?.dfsNodes ?? MAX_DFS_NODES;
13
+ if (startId === targetId) return [startId];
14
+ const seen = new Set([startId]);
15
+ const stack = [[startId, [startId]]];
16
+ let visited = 0;
17
+ while (stack.length) {
18
+ const [cur, trail] = stack.pop();
19
+ if (++visited > cap) return null;
20
+ const out = store.dep.listOutgoing(cur);
21
+ for (const edge of out) {
22
+ if (seen.has(edge.to_id)) continue;
23
+ if (edge.to_id === targetId) return [...trail, edge.to_id];
24
+ seen.add(edge.to_id);
25
+ stack.push([edge.to_id, [...trail, edge.to_id]]);
26
+ }
27
+ }
28
+ return null;
29
+ }
30
+
31
+ /**
32
+ * Add `from depends on to`. Rejects:
33
+ * - missing items
34
+ * - self-edge
35
+ * - duplicate edge (treated as ok / no-op)
36
+ * - would-be cycle
37
+ */
38
+ export function addDep(store, fromId, toId) {
39
+ if (fromId === toId) return { ok: false, code: "self_edge" };
40
+ const fromKind = store.itemKindOf(fromId);
41
+ const toKind = store.itemKindOf(toId);
42
+ if (!fromKind) return { ok: false, code: "from_not_found", id: fromId };
43
+ if (!toKind) return { ok: false, code: "to_not_found", id: toId };
44
+
45
+ // Would the new edge `from → to` create a cycle? It does iff there's an
46
+ // existing path `to → ... → from`. DFS from `to` looking for `from`.
47
+ const cyclePath = reachable(store, toId, fromId);
48
+ if (cyclePath) return { ok: false, code: "cycle", path: [fromId, ...cyclePath] };
49
+
50
+ store.dep.addRaw({ fromId, toId });
51
+ return { ok: true };
52
+ }
53
+
54
+ export function removeDep(store, fromId, toId) {
55
+ return store.dep.remove({ fromId, toId }) ? { ok: true } : { ok: false, code: "not_found" };
56
+ }
57
+
58
+ /**
59
+ * Are all dependencies of `id` resolved? Returns true iff every outgoing
60
+ * `id → other` has `other.status` in {done, cancelled}.
61
+ */
62
+ export function depsResolved(store, id) {
63
+ const out = store.dep.listOutgoing(id);
64
+ for (const edge of out) {
65
+ const item = store.item.get(edge.to_id, { includeDeleted: true });
66
+ if (!item) return false; // hard-deleted dep target = block (safer than ignoring)
67
+ if (item.status !== "done" && item.status !== "cancelled") return false;
68
+ }
69
+ return true;
70
+ }
@@ -0,0 +1,204 @@
1
+ // dispatch-server.js — HTTP dispatch endpoints and the admission queue pump.
2
+ // Executors register here and winch POSTs wakes from here; the read-only event
3
+ // stream lives in events-ws.js and shares no socket with dispatch.
4
+
5
+ import http from "node:http";
6
+ import { observe, recover, tick as dispatchTick } from "./dispatch.js";
7
+ import { deliverDue, deliverWake } from "./dispatch-webhook.js";
8
+ import { StaleRegistrationError } from "./store/webhook.js";
9
+ import { eventsSince, lastEventId, toEventMessage, HISTORY_LIMIT } from "./events-ws.js";
10
+
11
+ export const DEFAULT_DISPATCH_PORT = 38293;
12
+
13
+ export function startDispatchServer({ store, port = null, host = "127.0.0.1", intervalMs = null, logger } = {}) {
14
+ const cfg = store.config ?? {};
15
+ const listenPort = port ?? cfg.dispatchPort ?? DEFAULT_DISPATCH_PORT;
16
+ const pollMs = intervalMs ?? cfg.dispatchIntervalMs ?? 1000;
17
+ const sweepMs = cfg.dispatchSweepMs ?? 30000;
18
+ const consumerTtlMs = cfg.dispatchConsumerTtlMs ?? 90000;
19
+ const histLimit = cfg.wsHistoryLimit ?? HISTORY_LIMIT;
20
+ const authToken = String(process.env.WINCH_DISPATCH_TOKEN ?? "").trim() || null;
21
+ const loopback = host === "127.0.0.1" || host === "::1" || host === "localhost";
22
+ if (!loopback && !authToken) {
23
+ throw new Error("winch: dispatch server refuses a non-loopback host without WINCH_DISPATCH_TOKEN");
24
+ }
25
+ let closing = false;
26
+ let pumping = false;
27
+
28
+ const pruneConsumers = () => {
29
+ try { store.webhook.prune({ topic: "dispatch", before: Date.now() - consumerTtlMs }); } catch {}
30
+ };
31
+ const sweeper = sweepMs > 0
32
+ ? setInterval(() => {
33
+ try { store.task.sweepExpired({}); } catch {}
34
+ pruneConsumers();
35
+ }, sweepMs)
36
+ : null;
37
+ sweeper?.unref?.();
38
+
39
+ store.admission.resetOffers();
40
+ pruneConsumers();
41
+ // Repair a queue written before write-time routing existed. `enqueue` is
42
+ // idempotent per event, so replaying tells the same story without minting a
43
+ // second wake for rows the write hook already admitted.
44
+ let since = 0;
45
+ const cursor = lastEventId(store);
46
+ for (;;) {
47
+ const rows = eventsSince(store, since, histLimit);
48
+ if (!rows.length) break;
49
+ for (const row of rows) observe(store, toEventMessage(store, row), Date.now());
50
+ since = rows[rows.length - 1].id;
51
+ if (since >= cursor) break;
52
+ }
53
+
54
+ function json(res, status, body) {
55
+ res.writeHead(status, { "content-type": "application/json" });
56
+ res.end(JSON.stringify(body));
57
+ }
58
+
59
+ function unauthorized(req) {
60
+ if (!authToken) return false;
61
+ const auth = req.headers?.authorization ?? "";
62
+ return auth !== `Bearer ${authToken}`;
63
+ }
64
+
65
+ async function readJson(req, res) {
66
+ let size = 0;
67
+ let raw = "";
68
+ for await (const chunk of req) {
69
+ size += chunk.length;
70
+ if (size > 1024 * 1024) {
71
+ json(res, 413, { error: "body too large" });
72
+ return undefined;
73
+ }
74
+ raw += chunk;
75
+ }
76
+ if (!raw) return {};
77
+ try {
78
+ return JSON.parse(raw);
79
+ } catch {
80
+ json(res, 400, { error: "invalid json body" });
81
+ return undefined;
82
+ }
83
+ }
84
+
85
+ async function pump() {
86
+ if (pumping) return;
87
+ pumping = true;
88
+ try {
89
+ pruneConsumers();
90
+ const offered = dispatchTick(store, {
91
+ at: Date.now(),
92
+ reachable: store.webhook.harnesses({ topic: "dispatch" }),
93
+ config: cfg,
94
+ });
95
+ for (const row of offered) await deliverWake(store, row, { config: cfg, logger });
96
+ await deliverDue(store, { config: cfg, logger });
97
+ } catch (err) {
98
+ logger?.warn?.(`winch: dispatch pump failed: ${err?.message ?? err}`);
99
+ } finally {
100
+ pumping = false;
101
+ }
102
+ }
103
+
104
+ const server = http.createServer(async (req, res) => {
105
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
106
+ if (req.method === "POST" && url.pathname === "/dispatch/register") {
107
+ if (unauthorized(req)) { json(res, 401, { error: "unauthorized" }); return; }
108
+ const body = await readJson(req, res);
109
+ if (body === undefined) return;
110
+ try {
111
+ const harness = typeof body.harness === "string" ? body.harness.trim() : "";
112
+ const executorId = typeof body.executorId === "string" ? body.executorId.trim() : "";
113
+ const consumerId = typeof body.consumerId === "string" ? body.consumerId.trim() : "";
114
+ const instanceId = typeof body.instanceId === "string" ? body.instanceId.trim() : "";
115
+ const fresh = body.fresh === true;
116
+ if (!harness || (!consumerId && !executorId)) throw new Error("dispatch registration requires harness and consumerId or executorId");
117
+ const id = consumerId || executorId;
118
+ const row = store.webhook.upsert({
119
+ topic: "dispatch",
120
+ id,
121
+ harness,
122
+ executorId: executorId || null,
123
+ instanceId: instanceId || executorId || id,
124
+ url: body.url,
125
+ bearer: body.bearer,
126
+ timeoutMs: body.timeoutMs ?? null,
127
+ leaseMs: consumerTtlMs,
128
+ managed: true,
129
+ fresh,
130
+ });
131
+ if (executorId && id !== executorId) {
132
+ const legacy = store.webhook.get({ topic: "dispatch", id: executorId });
133
+ if (legacy?.executorId === executorId) store.webhook.remove({ topic: "dispatch", id: executorId });
134
+ }
135
+ json(res, 201, {
136
+ ok: true, topic: row.topic, id: row.id, harness: row.harness,
137
+ executorId: row.executorId, instanceId: row.instanceId,
138
+ generation: row.generation, leaseUntil: row.leaseUntil,
139
+ });
140
+ void pump();
141
+ } catch (err) {
142
+ if (err instanceof StaleRegistrationError || err?.code === "stale_instance") {
143
+ const current = err.current
144
+ ? { instanceId: err.current.instanceId ?? null, generation: err.current.generation ?? null,
145
+ state: err.current.state ?? null, leaseUntil: err.current.leaseUntil ?? null }
146
+ : null;
147
+ json(res, 409, { error: String(err.message ?? err), code: "stale_instance", current });
148
+ } else {
149
+ json(res, 400, { error: String(err?.message ?? err) });
150
+ }
151
+ }
152
+ return;
153
+ }
154
+ if (req.method === "POST" && url.pathname === "/dispatch/notify") {
155
+ if (unauthorized(req)) { json(res, 401, { error: "unauthorized" }); return; }
156
+ req.resume();
157
+ json(res, 202, { ok: true });
158
+ void pump();
159
+ return;
160
+ }
161
+ if (req.method === "POST" && url.pathname === "/dispatch/recover") {
162
+ if (unauthorized(req)) { json(res, 401, { error: "unauthorized" }); return; }
163
+ const body = await readJson(req, res);
164
+ if (body === undefined) return;
165
+ try {
166
+ const result = recover(store, {
167
+ harness: String(body.harness ?? "").trim(),
168
+ consumerId: String(body.consumerId ?? "").trim() || null,
169
+ at: Date.now(),
170
+ config: cfg,
171
+ mutate: true,
172
+ });
173
+ json(res, 200, result);
174
+ } catch (err) {
175
+ json(res, 400, { error: String(err?.message ?? err) });
176
+ }
177
+ return;
178
+ }
179
+ json(res, 404, { error: "not found" });
180
+ });
181
+
182
+ const timer = setInterval(() => {
183
+ if (closing) return;
184
+ void pump();
185
+ }, pollMs);
186
+ if (typeof timer.unref === "function") timer.unref();
187
+
188
+ return new Promise((resolve, reject) => {
189
+ server.once("error", reject);
190
+ server.listen(listenPort, host, () => {
191
+ resolve({
192
+ port: server.address().port,
193
+ host,
194
+ close: () =>
195
+ new Promise((res) => {
196
+ closing = true;
197
+ clearInterval(timer);
198
+ if (sweeper) clearInterval(sweeper);
199
+ server.close(() => res());
200
+ }),
201
+ });
202
+ });
203
+ });
204
+ }
@@ -0,0 +1,221 @@
1
+ // Outbound wake delivery over HTTP. Delivery is per consumer: every endpoint
2
+ // gets its own row and its own retry budget. A 2xx means the receiver accepted
3
+ // the request; the work is only accepted when the receiver wins the execution
4
+ // lease (a task claim, or the dispatcher's active-consumer lease).
5
+
6
+ const DEFAULT_TIMEOUT_MS = 3000;
7
+ const MAX_BODY_CHARS = 500;
8
+
9
+ function hashPick(items, key) {
10
+ if (!items.length) return null;
11
+ let h = 0;
12
+ for (let i = 0; i < key.length; i++) h = ((h * 31) + key.charCodeAt(i)) >>> 0;
13
+ return items[h % items.length];
14
+ }
15
+
16
+ export function consumersFor(store, harness) {
17
+ const rows = store.webhook.list({ topic: "dispatch" })
18
+ .filter((w) => w.state !== "disabled")
19
+ .filter((w) => harness === "*" || w.harness === harness);
20
+ return rows;
21
+ }
22
+
23
+ export function pickConsumer(store, row) {
24
+ const consumers = consumersFor(store, row.harness);
25
+ return hashPick(consumers, `${row.id}:${row.attempt_no ?? 0}`)?.id ?? null;
26
+ }
27
+
28
+ export function wakePayload(row, { at = Date.now(), offerMs = 120000, execution = "active", leaseEpoch = 0 } = {}) {
29
+ return {
30
+ type: "wake",
31
+ admissionId: row.id,
32
+ itemId: row.item_id,
33
+ attemptNo: row.attempt_no ?? null,
34
+ kind: row.kind,
35
+ harness: row.harness,
36
+ agent: row.agent_id,
37
+ eventId: row.event_id ?? null,
38
+ offerExpiresAt: at + offerMs,
39
+ execution,
40
+ leaseEpoch,
41
+ at,
42
+ };
43
+ }
44
+
45
+ async function postWake(endpoint, payload, timeoutMs) {
46
+ const headers = { "content-type": "application/json" };
47
+ if (endpoint.bearer) headers.authorization = `Bearer ${endpoint.bearer}`;
48
+ try {
49
+ const res = await fetch(endpoint.url, {
50
+ method: "POST",
51
+ headers,
52
+ body: JSON.stringify(payload),
53
+ signal: AbortSignal.timeout(timeoutMs),
54
+ });
55
+ const text = await res.text().catch(() => "");
56
+ return { id: endpoint.id, status: res.status, body: text.slice(0, MAX_BODY_CHARS) };
57
+ } catch (err) {
58
+ return { id: endpoint.id, status: 0, error: String(err?.message ?? err) };
59
+ }
60
+ }
61
+
62
+ function permanent(status) {
63
+ return status >= 400 && status < 500 && status !== 408 && status !== 425 && status !== 429;
64
+ }
65
+
66
+ export function ensureDeliveries(store, row, { at = Date.now() } = {}) {
67
+ const consumers = consumersFor(store, row.harness);
68
+ const event = row.attempt_no == null ? null : store.dispatchEvent.ensure({
69
+ admissionId: row.id,
70
+ attemptNo: row.attempt_no,
71
+ itemId: row.item_id,
72
+ sourceEventId: row.event_id ?? null,
73
+ payload: wakePayload(row, { at, leaseEpoch: row.lease_epoch ?? 0 }),
74
+ at,
75
+ });
76
+ for (const consumer of consumers) {
77
+ store.delivery.ensure({
78
+ admissionId: row.id,
79
+ attemptNo: row.attempt_no,
80
+ consumerId: consumer.id,
81
+ eventId: event?.id ?? null,
82
+ at,
83
+ });
84
+ }
85
+ return consumers;
86
+ }
87
+
88
+ async function deliverOne(store, delivery, row, { config, logger, at }) {
89
+ const endpoint = store.webhook.get({ topic: "dispatch", id: delivery.consumer_id });
90
+ if (!endpoint || endpoint.state === "disabled") {
91
+ store.delivery.markDead(delivery.id, { error: "consumer disabled", at });
92
+ store.delivery.recordAttempt({ deliveryId: delivery.id, attemptNo: delivery.attempts + 1, status: "dead", error: "consumer disabled", at });
93
+ return { ok: false, consumerId: delivery.consumer_id, status: 0, error: "consumer disabled" };
94
+ }
95
+ const execution = row.active_consumer_id === delivery.consumer_id ? "active" : "standby";
96
+ const payload = wakePayload(row, {
97
+ offerMs: config.dispatchOfferMs,
98
+ execution,
99
+ leaseEpoch: row.lease_epoch ?? 0,
100
+ });
101
+ const timeout = endpoint.timeoutMs ?? config.webhookTimeoutMs ?? DEFAULT_TIMEOUT_MS;
102
+ const result = await postWake(endpoint, payload, timeout);
103
+ const ok = result.status >= 200 && result.status < 300;
104
+
105
+ if (ok) {
106
+ store.delivery.markDelivered(delivery.id, { status: result.status, at });
107
+ store.delivery.recordAttempt({ deliveryId: delivery.id, attemptNo: delivery.attempts + 1, status: "delivered", responseStatus: result.status, at });
108
+ store.dispatchEvent.markPublished({ admissionId: row.id, attemptNo: row.attempt_no, at });
109
+ store.webhook.recordSuccess({ topic: "dispatch", id: endpoint.id, at });
110
+ return { ok: true, consumerId: endpoint.id, status: result.status, execution };
111
+ }
112
+
113
+ const attempts = delivery.attempts + 1;
114
+ const maxAttempts = config.dispatchDeliveryMaxAttempts ?? 5;
115
+ const disabled = permanent(result.status) || attempts >= maxAttempts;
116
+ const after = store.webhook.recordFailure({
117
+ topic: "dispatch",
118
+ id: endpoint.id,
119
+ status: result.status,
120
+ error: result.error ?? result.body ?? null,
121
+ permanent: disabled,
122
+ threshold: config.dispatchDeliveryFailureThreshold ?? 4,
123
+ at,
124
+ });
125
+ if (disabled || after?.state === "disabled") {
126
+ store.delivery.markDead(delivery.id, { status: result.status, error: result.error ?? result.body ?? null, at });
127
+ store.delivery.recordAttempt({ deliveryId: delivery.id, attemptNo: attempts, status: "dead", responseStatus: result.status, error: result.error ?? result.body ?? null, at });
128
+ } else {
129
+ const base = config.dispatchDeliveryBackoffMs ?? config.dispatchOfferBackoffMs ?? 30000;
130
+ const max = config.dispatchDeliveryMaxBackoffMs ?? config.dispatchOfferMaxBackoffMs ?? 300000;
131
+ const nextAt = at + Math.min(max, base * 2 ** Math.max(0, attempts - 1));
132
+ store.delivery.markRetry(delivery.id, { status: result.status, error: result.error ?? result.body ?? null, nextAt, at });
133
+ store.delivery.recordAttempt({ deliveryId: delivery.id, attemptNo: attempts, status: "retry", responseStatus: result.status, error: result.error ?? result.body ?? null, at });
134
+ }
135
+ logger?.warn?.(`winch: dispatch wake ${row.id} -> ${endpoint.id} failed (${result.status || result.error})${disabled ? " disabled" : ""}`);
136
+ return { ok: false, consumerId: endpoint.id, status: result.status, error: result.error ?? result.body ?? null, execution };
137
+ }
138
+
139
+ export function promoteStranded(store, { at = Date.now(), config = store.config } = {}) {
140
+ const rows = store.db.prepare(`
141
+ SELECT q.id, q.harness, aa.attempt_no, aa.active_consumer_id, aa.lease_until
142
+ FROM admission_queue q
143
+ JOIN admission_attempts aa ON aa.admission_id=q.id AND aa.ended_at IS NULL
144
+ WHERE q.status IN ('offered','accepted') AND q.ended_at IS NULL
145
+ `).all();
146
+ for (const row of rows) {
147
+ const consumers = consumersFor(store, row.harness);
148
+ if (!consumers.length) continue;
149
+ const active = consumers.find((c) => c.id === row.active_consumer_id);
150
+ const activeDelivery = row.active_consumer_id
151
+ ? store.delivery.list({ admissionId: row.id, attemptNo: row.attempt_no, consumerId: row.active_consumer_id })[0]
152
+ : null;
153
+ const leaseLive = (row.lease_until ?? 0) > at;
154
+ if (active && activeDelivery?.status !== "dead" && leaseLive) continue;
155
+ const next = consumers.find((c) => c.id !== row.active_consumer_id) ?? consumers[0];
156
+ if (!next || next.id === row.active_consumer_id) continue;
157
+ store.db.prepare(`
158
+ UPDATE admission_attempts SET active_consumer_id=?, lease_epoch=lease_epoch+1, lease_until=?
159
+ WHERE admission_id=? AND attempt_no=? AND ended_at IS NULL
160
+ `).run(next.id, at + (config.dispatchConsumerTtlMs ?? 90000), row.id, row.attempt_no);
161
+ store.delivery.ensure({ admissionId: row.id, attemptNo: row.attempt_no, consumerId: next.id, at });
162
+ store.delivery.resetForConsumer(row.id, row.attempt_no, next.id, { at });
163
+ }
164
+ }
165
+
166
+ export async function deliverDue(store, { config = store.config, logger = null, at = Date.now(), admissionId = null } = {}) {
167
+ promoteStranded(store, { at, config });
168
+ const leaseMs = config.dispatchDeliveryLeaseMs ?? 300000;
169
+ store.delivery.releaseStale({ before: at - leaseMs, at });
170
+ const due = store.delivery.claimDue({ at, limit: 200, admissionId });
171
+ const results = [];
172
+ for (const delivery of due) {
173
+ const row = store.admission.get(delivery.admission_id);
174
+ if (!row || !["offered", "accepted"].includes(row.status) || row.attempt_no !== delivery.attempt_no) {
175
+ store.delivery.cancelForAttempt(delivery.admission_id, delivery.attempt_no, { at });
176
+ continue;
177
+ }
178
+ try {
179
+ results.push(await deliverOne(store, delivery, row, { config, logger, at }));
180
+ } catch (err) {
181
+ const base = config.dispatchDeliveryBackoffMs ?? 30000;
182
+ store.delivery.markRetry(delivery.id, { error: String(err?.message ?? err), nextAt: at + base, at });
183
+ store.delivery.recordAttempt({ deliveryId: delivery.id, attemptNo: delivery.attempts + 1, status: "retry", error: String(err?.message ?? err), at });
184
+ logger?.warn?.(`winch: delivery ${delivery.id} crashed: ${err?.message ?? err}`);
185
+ }
186
+ }
187
+
188
+ if (admissionId) {
189
+ const row = store.admission.get(admissionId);
190
+ if (row && ["offered", "accepted"].includes(row.status)) {
191
+ const all = store.delivery.allForAttempt(row.id, row.attempt_no);
192
+ if (all.length && all.every((d) => d.status === "dead")) store.admission.fail(row.id, at);
193
+ }
194
+ }
195
+ const exhausted = store.db.prepare(`
196
+ SELECT q.id
197
+ FROM admission_queue q
198
+ JOIN admission_attempts aa ON aa.admission_id=q.id AND aa.ended_at IS NULL
199
+ WHERE q.status IN ('offered','accepted') AND q.ended_at IS NULL
200
+ AND EXISTS (SELECT 1 FROM dispatch_deliveries d
201
+ WHERE d.admission_id=q.id AND d.attempt_no=aa.attempt_no)
202
+ AND NOT EXISTS (SELECT 1 FROM dispatch_deliveries d
203
+ WHERE d.admission_id=q.id AND d.attempt_no=aa.attempt_no
204
+ AND d.status != 'dead')
205
+ `).all();
206
+ for (const row of exhausted) store.admission.fail(row.id, at);
207
+ return results;
208
+ }
209
+
210
+ export async function deliverWake(store, row, { config = store.config, logger = null, at = Date.now() } = {}) {
211
+ const consumers = ensureDeliveries(store, row, { at });
212
+ if (consumers.length === 0) {
213
+ store.admission.fail(row.id, at);
214
+ logger?.warn?.(`winch: no dispatch endpoint for ${row.harness}; requeueing ${row.id}`);
215
+ return { ok: false, delivered: [], failed: [] };
216
+ }
217
+ const results = await deliverDue(store, { config, logger, at, admissionId: row.id });
218
+ const delivered = results.filter((r) => r.ok);
219
+ const failed = results.filter((r) => !r.ok);
220
+ return { ok: delivered.length > 0, delivered, failed };
221
+ }