@igorjpimenta/winch 0.0.0-stage → 2026.11.22-beta.3
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.
- package/.migrations/0000_next_katie_power.sql +99 -0
- package/.migrations/0001_add-events-kind.sql +8 -0
- package/.migrations/0002_drop-session-budgets.sql +1 -0
- package/.migrations/0003_pink_siren.sql +8 -0
- package/.migrations/0004_salty_trauma.sql +1 -0
- package/.migrations/0005_classy_havok.sql +1 -0
- package/.migrations/0006_recursive_items.sql +265 -0
- package/.migrations/0007_unify_statuses.sql +35 -0
- package/.migrations/0008_core_dispatch.sql +61 -0
- package/.migrations/0009_webhooks.sql +17 -0
- package/.migrations/0010_dispatch_consumer_id.sql +1 -0
- package/.migrations/0011_dispatch_delivery_leases.sql +53 -0
- package/.migrations/0012_dispatch_fencing_audit.sql +32 -0
- package/.migrations/meta/0000_snapshot.json +658 -0
- package/.migrations/meta/0001_snapshot.json +665 -0
- package/.migrations/meta/0002_snapshot.json +604 -0
- package/.migrations/meta/0003_snapshot.json +656 -0
- package/.migrations/meta/0004_snapshot.json +664 -0
- package/.migrations/meta/0005_snapshot.json +671 -0
- package/.migrations/meta/0006_snapshot.json +1089 -0
- package/.migrations/meta/0007_unify_statuses_snapshot.json +1097 -0
- package/.migrations/meta/0008_snapshot.json +1382 -0
- package/.migrations/meta/0009_snapshot.json +1428 -0
- package/.migrations/meta/0010_snapshot.json +1435 -0
- package/.migrations/meta/0011_snapshot.json +1670 -0
- package/.migrations/meta/0012_snapshot.json +1900 -0
- package/.migrations/meta/_journal.json +97 -0
- package/README.md +480 -2
- package/bin/winch.js +4 -0
- package/package.json +36 -4
- package/plugins/README.md +304 -0
- package/plugins/openclaw/winch/README.md +71 -0
- package/plugins/openclaw/winch/dispatch.js +236 -0
- package/plugins/openclaw/winch/index.js +139 -0
- package/plugins/openclaw/winch/meta.js +35 -0
- package/plugins/openclaw/winch/openclaw.plugin.json +43 -0
- package/plugins/openclaw/winch/package.json +37 -0
- package/plugins/opencode/winch/dispatch.js +228 -0
- package/plugins/opencode/winch/hooks.js +22 -0
- package/plugins/opencode/winch/identity.js +34 -0
- package/plugins/opencode/winch/index.js +198 -0
- package/plugins/opencode/winch/package.json +26 -0
- package/src/cli.js +434 -0
- package/src/config.js +181 -0
- package/src/db.js +39 -0
- package/src/deps.js +70 -0
- package/src/dispatch-server.js +204 -0
- package/src/dispatch-webhook.js +221 -0
- package/src/dispatch.js +258 -0
- package/src/events-ws.js +269 -0
- package/src/identity.js +140 -0
- package/src/ids.js +18 -0
- package/src/mcp-http.js +208 -0
- package/src/mcp.js +107 -0
- package/src/merges.js +150 -0
- package/src/paths.js +15 -0
- package/src/ready-queue.js +77 -0
- package/src/release.js +96 -0
- package/src/reserved.js +23 -0
- package/src/schema.js +302 -0
- package/src/store/admission.js +314 -0
- package/src/store/artifacts.js +24 -0
- package/src/store/attempts.js +22 -0
- package/src/store/claims.js +182 -0
- package/src/store/core.js +225 -0
- package/src/store/delivery.js +137 -0
- package/src/store/deps.js +62 -0
- package/src/store/dispatch-events.js +38 -0
- package/src/store/epics.js +31 -0
- package/src/store/events.js +21 -0
- package/src/store/gates.js +85 -0
- package/src/store/index.js +135 -0
- package/src/store/items.js +303 -0
- package/src/store/stories.js +37 -0
- package/src/store/sweep.js +77 -0
- package/src/store/tasks.js +190 -0
- package/src/store/webhook.js +197 -0
- package/src/tools/accept-wake.js +30 -0
- package/src/tools/assign.js +75 -0
- package/src/tools/claim.js +88 -0
- package/src/tools/definitions.js +371 -0
- package/src/tools/delegate.js +147 -0
- package/src/tools/index.js +44 -0
- package/src/tools/plan.js +262 -0
- package/src/tools/read.js +103 -0
- package/src/tools/report.js +190 -0
- package/src/tools/shared.js +62 -0
- package/src/watcher.js +105 -0
|
@@ -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
|
+
}
|
package/src/dispatch.js
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
// Core dispatch: route lifecycle rows to wake admissions, then admit offers
|
|
2
|
+
// under per-harness and global caps. The harness accepts an offer; only the
|
|
3
|
+
// winner starts a session. Item status remains the work acknowledgement.
|
|
4
|
+
|
|
5
|
+
import { HUMAN_AGENT, HUMAN_HARNESS } from "./reserved.js";
|
|
6
|
+
import { pickConsumer } from "./dispatch-webhook.js";
|
|
7
|
+
|
|
8
|
+
const RELEASING_STATUSES = new Set(["done", "cancelled", "blocked", "backlog", "review"]);
|
|
9
|
+
|
|
10
|
+
function isHuman(agent, harness) {
|
|
11
|
+
return agent === HUMAN_AGENT || harness === HUMAN_HARNESS;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function add(out, itemId, kind, agent, harness, reason) {
|
|
15
|
+
if (!itemId || !agent || isHuman(agent, harness)) return;
|
|
16
|
+
out.push({ itemId, kind, agentId: agent, harness: harness || "*", reason });
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function routesForEvent(ev) {
|
|
20
|
+
const out = [];
|
|
21
|
+
const item = ev?.item;
|
|
22
|
+
if (!item?.id) return out;
|
|
23
|
+
|
|
24
|
+
const addTask = (itemId, agent, harness, reason) => {
|
|
25
|
+
if (!agent) return;
|
|
26
|
+
add(out, itemId, "task", agent, harness, reason);
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
switch (ev.kind) {
|
|
30
|
+
case "task.created":
|
|
31
|
+
case "task.assigned":
|
|
32
|
+
case "task.released":
|
|
33
|
+
case "gate.resolved": {
|
|
34
|
+
if (item.status !== "ready") break;
|
|
35
|
+
addTask(item.id, item.assigned, item.assigneeHarness, ev.kind);
|
|
36
|
+
break;
|
|
37
|
+
}
|
|
38
|
+
case "story.created":
|
|
39
|
+
case "story.assigned": {
|
|
40
|
+
if (item.status !== "ready") break;
|
|
41
|
+
add(out, item.id, "story", item.assigned, item.assigneeHarness, ev.kind);
|
|
42
|
+
break;
|
|
43
|
+
}
|
|
44
|
+
case "task.restored": {
|
|
45
|
+
if (item.status !== "ready") break;
|
|
46
|
+
addTask(item.id, item.assigned, item.assigneeHarness, ev.kind);
|
|
47
|
+
break;
|
|
48
|
+
}
|
|
49
|
+
case "task.appended": {
|
|
50
|
+
if (item.status !== "ready") break;
|
|
51
|
+
const agent = ev.epicCreatedBy ?? item.createdBy;
|
|
52
|
+
const harness = ev.epicAssigneeHarness ?? "*";
|
|
53
|
+
add(out, ev.epicId ?? item.id, "append", agent, harness, ev.kind);
|
|
54
|
+
break;
|
|
55
|
+
}
|
|
56
|
+
case "epic.completed": {
|
|
57
|
+
if (item.kind !== "epic") break;
|
|
58
|
+
const agent = ev.epicCreatedBy ?? item.createdBy;
|
|
59
|
+
const harness = ev.epicAssigneeHarness ?? "*";
|
|
60
|
+
add(out, item.id, "review", agent, harness, ev.kind);
|
|
61
|
+
break;
|
|
62
|
+
}
|
|
63
|
+
default:
|
|
64
|
+
break;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
for (const u of ev?.unblocked ?? []) {
|
|
68
|
+
addTask(u.id, u.assigned, u.assigneeHarness, "unblocked");
|
|
69
|
+
}
|
|
70
|
+
const seen = new Set();
|
|
71
|
+
return out.filter((r) => {
|
|
72
|
+
const key = `${r.itemId}\0${r.kind}\0${r.harness}\0${r.agentId}`;
|
|
73
|
+
if (seen.has(key)) return false;
|
|
74
|
+
seen.add(key);
|
|
75
|
+
return true;
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function observe(store, ev, at = Date.now()) {
|
|
80
|
+
const item = ev?.item;
|
|
81
|
+
if (item?.id) {
|
|
82
|
+
const harness = item.assigneeHarness ?? ev.storyAssigneeHarness ?? ev.epicAssigneeHarness ?? "*";
|
|
83
|
+
if (item.status === "in_progress") {
|
|
84
|
+
store.admission.activate(item.id, harness, at);
|
|
85
|
+
// `ready` is not generally releasing: assignment to ready is the wake.
|
|
86
|
+
} else if (RELEASING_STATUSES.has(item.status) ||
|
|
87
|
+
(item.status === "ready" && (ev.kind === "task.released" || ev.kind === "gate.resolved"))) {
|
|
88
|
+
// A duplicate event must not release the row that event just admitted.
|
|
89
|
+
store.admission.release(item.id, item.status, at, ev.id ?? null);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
const routes = routesForEvent(ev);
|
|
93
|
+
for (const route of routes) {
|
|
94
|
+
store.admission.enqueue({ ...route, eventId: ev.id ?? null, at });
|
|
95
|
+
}
|
|
96
|
+
return routes;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
function trimOffers(store, harness, at, config) {
|
|
101
|
+
const offered = store.admission.offers(harness)
|
|
102
|
+
.map((row) => store.admission.get(row.id))
|
|
103
|
+
.filter(Boolean)
|
|
104
|
+
.sort((a, b) => (a.offered_at ?? 0) - (b.offered_at ?? 0)
|
|
105
|
+
|| (a.attempt_no ?? 0) - (b.attempt_no ?? 0)
|
|
106
|
+
|| String(a.id).localeCompare(String(b.id)));
|
|
107
|
+
|
|
108
|
+
const { active, reserved } = store.admission.slots();
|
|
109
|
+
const activeHarness = active.get(harness) ?? 0;
|
|
110
|
+
const activeGlobal = [...active.values()].reduce((n, v) => n + v, 0);
|
|
111
|
+
const reservedGlobal = [...reserved.values()].reduce((n, v) => n + v, 0);
|
|
112
|
+
const otherReserved = Math.max(0, reservedGlobal - offered.length);
|
|
113
|
+
const keep = Math.max(0, Math.min(
|
|
114
|
+
config.dispatchHarnessMax - activeHarness,
|
|
115
|
+
config.dispatchGlobalMax - activeGlobal - otherReserved,
|
|
116
|
+
offered.length,
|
|
117
|
+
));
|
|
118
|
+
const keptOffers = offered.slice(0, keep);
|
|
119
|
+
for (const row of offered.slice(keep)) store.admission.requeue(row.id, at);
|
|
120
|
+
return { offered, keptOffers, activeHarness, activeGlobal, otherReserved };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function recover(store, { harness, consumerId = null, at = Date.now(), config = store.config, mutate = false } = {}) {
|
|
124
|
+
if (mutate) store.admission.expire({
|
|
125
|
+
at,
|
|
126
|
+
offerMs: config.dispatchOfferMs,
|
|
127
|
+
baseBackoffMs: config.dispatchOfferBackoffMs,
|
|
128
|
+
maxBackoffMs: config.dispatchOfferMaxBackoffMs,
|
|
129
|
+
maxAttempts: config.dispatchOfferMaxAttempts,
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
const ownerForItem = `COALESCE(
|
|
133
|
+
a.consumer_id,
|
|
134
|
+
(SELECT aa.active_consumer_id
|
|
135
|
+
FROM admission_queue q
|
|
136
|
+
JOIN admission_attempts aa ON aa.admission_id=q.id
|
|
137
|
+
WHERE q.item_id=s.item_id AND q.status='active' AND q.ended_at IS NULL
|
|
138
|
+
ORDER BY aa.attempt_no DESC LIMIT 1)
|
|
139
|
+
)`;
|
|
140
|
+
const resume = store.db.prepare(`
|
|
141
|
+
SELECT s.item_id, s.assignee_agent, s.assignee_harness,
|
|
142
|
+
a.id AS attempt_id, a.attempt_no, a.claimed_at, a.heartbeat_at, a.expires_at,
|
|
143
|
+
a.lease_epoch, a.owner_instance,
|
|
144
|
+
ws.id AS session_id, ws.external_session_id, ws.session_key,
|
|
145
|
+
${ownerForItem} AS consumer_id
|
|
146
|
+
FROM item_state s
|
|
147
|
+
LEFT JOIN attempts a ON a.item_id=s.item_id AND a.ended_at IS NULL
|
|
148
|
+
LEFT JOIN work_sessions ws ON ws.id=a.session_id
|
|
149
|
+
WHERE s.status='in_progress' AND s.deleted_at IS NULL AND s.assignee_harness=?
|
|
150
|
+
AND (? IS NULL OR ${ownerForItem} = ?)
|
|
151
|
+
ORDER BY a.claimed_at ASC, s.updated_at ASC
|
|
152
|
+
`).all(harness, consumerId, consumerId).map((r) => ({
|
|
153
|
+
task: store.task.get(r.item_id),
|
|
154
|
+
attemptId: r.attempt_id ?? null,
|
|
155
|
+
attemptNo: r.attempt_no ?? null,
|
|
156
|
+
sessionId: r.session_id ?? null,
|
|
157
|
+
sessionKey: r.session_key ?? null,
|
|
158
|
+
leaseEpoch: r.lease_epoch ?? 0,
|
|
159
|
+
ownerInstance: r.owner_instance ?? null,
|
|
160
|
+
leaseExpiresAt: r.expires_at ?? null,
|
|
161
|
+
consumerId: r.consumer_id ?? null,
|
|
162
|
+
needsRepair: r.attempt_id == null,
|
|
163
|
+
}));
|
|
164
|
+
|
|
165
|
+
let offered, keptOffers, activeHarness, activeGlobal, otherReserved;
|
|
166
|
+
if (mutate) {
|
|
167
|
+
({ offered, keptOffers, activeHarness, activeGlobal, otherReserved } = trimOffers(store, harness, at, config));
|
|
168
|
+
} else {
|
|
169
|
+
offered = store.admission.offers(harness)
|
|
170
|
+
.map((row) => store.admission.get(row.id))
|
|
171
|
+
.filter(Boolean)
|
|
172
|
+
.sort((a, b) => (a.offered_at ?? 0) - (b.offered_at ?? 0)
|
|
173
|
+
|| (a.attempt_no ?? 0) - (b.attempt_no ?? 0)
|
|
174
|
+
|| String(a.id).localeCompare(String(b.id)));
|
|
175
|
+
keptOffers = offered;
|
|
176
|
+
const slots = store.admission.slots();
|
|
177
|
+
activeHarness = slots.active.get(harness) ?? 0;
|
|
178
|
+
activeGlobal = [...slots.active.values()].reduce((n, v) => n + v, 0);
|
|
179
|
+
otherReserved = Math.max(0, [...slots.reserved.values()].reduce((n, v) => n + v, 0) - offered.length);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const start = keptOffers
|
|
183
|
+
.filter((live) => !consumerId || !live.active_consumer_id || live.active_consumer_id === consumerId)
|
|
184
|
+
.map((live) => ({
|
|
185
|
+
admissionId: live.id,
|
|
186
|
+
itemId: live.item_id,
|
|
187
|
+
attemptNo: live.attempt_no ?? null,
|
|
188
|
+
kind: live.kind,
|
|
189
|
+
agent: live.agent_id,
|
|
190
|
+
harness: live.harness,
|
|
191
|
+
eventId: live.event_id ?? null,
|
|
192
|
+
offerExpiresAt: (live.offered_at ?? at) + config.dispatchOfferMs,
|
|
193
|
+
activeConsumerId: live.active_consumer_id ?? null,
|
|
194
|
+
leaseEpoch: live.lease_epoch ?? 0,
|
|
195
|
+
status: live.status,
|
|
196
|
+
}));
|
|
197
|
+
|
|
198
|
+
const usedHarness = activeHarness + keptOffers.length;
|
|
199
|
+
const usedGlobal = activeGlobal + otherReserved + keptOffers.length;
|
|
200
|
+
let free = Math.max(0, Math.min(
|
|
201
|
+
config.dispatchHarnessMax - usedHarness,
|
|
202
|
+
config.dispatchGlobalMax - usedGlobal,
|
|
203
|
+
));
|
|
204
|
+
if (mutate) for (const row of store.admission.queued(harness, at)) {
|
|
205
|
+
if (free <= 0) break;
|
|
206
|
+
const next = store.admission.markOffered(row.id, at, {
|
|
207
|
+
pickActive: (attemptNo) => pickConsumer(store, { ...row, attempt_no: attemptNo }),
|
|
208
|
+
leaseMs: config.dispatchConsumerTtlMs,
|
|
209
|
+
});
|
|
210
|
+
if (!next) continue;
|
|
211
|
+
start.push({
|
|
212
|
+
admissionId: next.id,
|
|
213
|
+
itemId: next.item_id,
|
|
214
|
+
attemptNo: next.attempt_no ?? null,
|
|
215
|
+
kind: next.kind,
|
|
216
|
+
agent: next.agent_id,
|
|
217
|
+
harness: next.harness,
|
|
218
|
+
eventId: next.event_id ?? null,
|
|
219
|
+
offerExpiresAt: at + config.dispatchOfferMs,
|
|
220
|
+
activeConsumerId: next.active_consumer_id ?? null,
|
|
221
|
+
leaseEpoch: next.lease_epoch ?? 0,
|
|
222
|
+
status: "offered",
|
|
223
|
+
});
|
|
224
|
+
free--;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
return { resume, start: consumerId ? start.filter((row) => row.activeConsumerId === consumerId) : start, free };
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export function tick(store, { at = Date.now(), reachable = [], config = store.config } = {}) {
|
|
231
|
+
store.admission.expire({
|
|
232
|
+
at,
|
|
233
|
+
offerMs: config.dispatchOfferMs,
|
|
234
|
+
baseBackoffMs: config.dispatchOfferBackoffMs,
|
|
235
|
+
maxBackoffMs: config.dispatchOfferMaxBackoffMs,
|
|
236
|
+
maxAttempts: config.dispatchOfferMaxAttempts,
|
|
237
|
+
});
|
|
238
|
+
const offered = [];
|
|
239
|
+
const harnesses = [...new Set(reachable)].filter(Boolean).sort();
|
|
240
|
+
for (const harness of harnesses) trimOffers(store, harness, at, config);
|
|
241
|
+
let globalUsed = store.admission.globalSlotCount();
|
|
242
|
+
for (const harness of harnesses) {
|
|
243
|
+
let harnessUsed = store.admission.slotCount(harness);
|
|
244
|
+
for (const row of store.admission.queued(harness, at)) {
|
|
245
|
+
if (harnessUsed >= config.dispatchHarnessMax || globalUsed >= config.dispatchGlobalMax) break;
|
|
246
|
+
const next = store.admission.markOffered(row.id, at, {
|
|
247
|
+
pickActive: (attemptNo) => pickConsumer(store, { ...row, attempt_no: attemptNo }),
|
|
248
|
+
leaseMs: config.dispatchConsumerTtlMs,
|
|
249
|
+
});
|
|
250
|
+
if (!next) continue;
|
|
251
|
+
store.admission.setParentCursor(next.item_id, at);
|
|
252
|
+
offered.push(next);
|
|
253
|
+
harnessUsed++;
|
|
254
|
+
globalUsed++;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return offered;
|
|
258
|
+
}
|