@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.
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 +198 -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/schema.js ADDED
@@ -0,0 +1,302 @@
1
+ // schema.js — one recursive item tree with lifecycle,
2
+ // attempts, sessions, artifacts and an append-only ledger.
3
+ //
4
+ // Drizzle owns the table/column types, constraints, indexes, generated
5
+ // columns and relations; drizzle-kit generates the SQL in .migrations/ from
6
+ // this file. The src/store modules query these tables directly.
7
+ //
8
+ // The tree is `parent_id`: a task can split into subtasks without a schema
9
+ // change. `id` is opaque — nothing may parse it; `kind` is the discriminator.
10
+
11
+ import { sql } from "drizzle-orm";
12
+ import {
13
+ sqliteTable,
14
+ text,
15
+ integer,
16
+ index,
17
+ uniqueIndex,
18
+ check,
19
+ primaryKey,
20
+ } from "drizzle-orm/sqlite-core";
21
+
22
+ export const ITEM_STATUSES = ["backlog", "ready", "in_progress", "blocked", "review", "done", "cancelled"];
23
+ export const EPIC_STATUSES = ITEM_STATUSES;
24
+ export const STORY_STATUSES = ITEM_STATUSES;
25
+ export const TASK_STATUSES = ITEM_STATUSES;
26
+ export const ALL_STATUSES = ITEM_STATUSES;
27
+ export const EXECUTION_KINDS = ["pipeclaw", "subagent", "cli", "gate", "manual"];
28
+ export const ITEM_KINDS = ["epic", "story", "task"];
29
+ export const ATTEMPT_STATUSES = ["claimed", "running", "gated", "done", "failed", "released", "cancelled"];
30
+ export const SESSION_KINDS = ["claim", "review", "system", "fanout"];
31
+ export const WAKE_KINDS = ["task", "story", "append", "review", "unblocked"];
32
+ export const ADMISSION_STATUSES = ["queued", "offered", "accepted", "active", "done", "cancelled", "expired"];
33
+ export const EDGE_KINDS = ["depends_on"];
34
+ export const DELIVERY_STATUSES = ["pending", "delivering", "delivered", "dead", "cancelled"];
35
+ export const WEBHOOK_STATES = ["active", "suspect", "disabled"];
36
+
37
+ const inList = (values) => sql.raw(values.map((v) => `'${v}'`).join(", "));
38
+
39
+ export const items = sqliteTable("items", {
40
+ id: text("id").primaryKey(),
41
+ kind: text("kind").notNull(),
42
+ parentId: text("parent_id").references(() => items.id, { onDelete: "cascade" }),
43
+ childKey: text("child_key"),
44
+ visitSeq: integer("visit_seq").notNull().default(0),
45
+ title: text("title").notNull(),
46
+ description: text("description"),
47
+ acceptance: text("acceptance"),
48
+ priority: integer("priority").notNull().default(50),
49
+ size: text("size"),
50
+ ownerTeam: text("owner_team"),
51
+ // Agent that planned the ticket; the dispatcher wakes it for the review.
52
+ createdBy: text("created_by"),
53
+ executionKind: text("execution_kind").notNull().default("manual"),
54
+ executionArgs: text("execution_args").notNull().default("{}"),
55
+ createdAt: integer("created_at").notNull(),
56
+ }, (table) => [
57
+ check("items_kind", sql`${table.kind} IN (${inList(ITEM_KINDS)})`),
58
+ check("items_execution_kind", sql`${table.executionKind} IN (${inList(EXECUTION_KINDS)})`),
59
+ check("items_root", sql`(${table.kind} = 'epic' AND ${table.parentId} IS NULL) OR (${table.kind} <> 'epic' AND ${table.parentId} IS NOT NULL)`),
60
+ uniqueIndex("uq_items_child").on(table.parentId, table.childKey, table.visitSeq).where(sql`${table.childKey} IS NOT NULL`),
61
+ index("idx_items_parent").on(table.parentId),
62
+ index("idx_items_kind_created").on(table.kind, table.createdAt),
63
+ ]);
64
+
65
+ export const itemState = sqliteTable("item_state", {
66
+ itemId: text("item_id").primaryKey().references(() => items.id, { onDelete: "cascade" }),
67
+ revision: integer("revision").notNull().default(0),
68
+ status: text("status").notNull(),
69
+ stateJson: text("state_json").notNull().default("{}"),
70
+ waitKind: text("wait_kind").generatedAlwaysAs(sql`json_extract(${sql.identifier("state_json")}, '$.wait.kind')`, { mode: "virtual" }),
71
+ currentChildKey: text("current_child_key").generatedAlwaysAs(sql`json_extract(${sql.identifier("state_json")}, '$.currentChildKey')`, { mode: "virtual" }),
72
+ assigneeHarness: text("assignee_harness"),
73
+ assigneeAgent: text("assignee_agent"),
74
+ updatedAt: integer("updated_at").notNull(),
75
+ closedAt: integer("closed_at"),
76
+ deletedAt: integer("deleted_at"),
77
+ }, (table) => [
78
+ check("item_state_status", sql`${table.status} IN (${inList(ALL_STATUSES)})`),
79
+ check("item_state_assignment_pair", sql`(${table.assigneeHarness} IS NULL) = (${table.assigneeAgent} IS NULL)`),
80
+ check("item_state_human_pair", sql`(${table.assigneeAgent} IS 'human') = (${table.assigneeHarness} IS 'human_in_the_loop')`),
81
+ check("item_state_ready_assigned", sql`${table.status} <> 'ready' OR (${table.assigneeHarness} IS NOT NULL AND ${table.assigneeAgent} IS NOT NULL)`),
82
+ index("idx_state_ready").on(table.status, table.assigneeHarness, table.assigneeAgent),
83
+ index("idx_state_updated").on(table.updatedAt),
84
+ index("idx_state_deleted").on(table.deletedAt),
85
+ ]);
86
+
87
+ export const itemTags = sqliteTable("item_tags", {
88
+ itemId: text("item_id").notNull().references(() => items.id, { onDelete: "cascade" }),
89
+ tag: text("tag").notNull(),
90
+ source: text("source"),
91
+ createdAt: integer("created_at").notNull(),
92
+ }, (table) => [
93
+ primaryKey({ columns: [table.itemId, table.tag] }),
94
+ index("idx_tags_tag").on(table.tag),
95
+ ]);
96
+
97
+ export const workSessions = sqliteTable("work_sessions", {
98
+ id: text("id").primaryKey(),
99
+ itemId: text("item_id").notNull().references(() => items.id, { onDelete: "cascade" }),
100
+ harness: text("harness").notNull(),
101
+ agentId: text("agent_id").notNull(),
102
+ externalSessionId: text("external_session_id").notNull(),
103
+ sessionKey: text("session_key").generatedAlwaysAs(
104
+ sql`${sql.identifier("harness")} || ':' || ${sql.identifier("agent_id")} || ':' || ${sql.identifier("external_session_id")}`,
105
+ { mode: "virtual" },
106
+ ),
107
+ kind: text("kind").notNull().default("claim"),
108
+ parentSessionId: text("parent_session_id").references(() => workSessions.id, { onDelete: "set null" }),
109
+ createdAt: integer("created_at").notNull(),
110
+ endedAt: integer("ended_at"),
111
+ deletedAt: integer("deleted_at"),
112
+ }, (table) => [
113
+ check("work_sessions_kind", sql`${table.kind} IN (${inList(SESSION_KINDS)})`),
114
+ uniqueIndex("uq_sessions_identity").on(table.harness, table.agentId, table.externalSessionId),
115
+ index("idx_sessions_item").on(table.itemId),
116
+ index("idx_sessions_parent").on(table.parentSessionId),
117
+ ]);
118
+
119
+ export const attempts = sqliteTable("attempts", {
120
+ id: text("id").primaryKey(),
121
+ itemId: text("item_id").notNull().references(() => items.id, { onDelete: "cascade" }),
122
+ attemptNo: integer("attempt_no").notNull(),
123
+ sessionId: text("session_id").notNull().references(() => workSessions.id, { onDelete: "restrict" }),
124
+ consumerId: text("consumer_id"),
125
+ ownerInstance: text("owner_instance"),
126
+ leaseEpoch: integer("lease_epoch").notNull().default(0),
127
+ status: text("status").notNull(),
128
+ claimedAt: integer("claimed_at").notNull(),
129
+ heartbeatAt: integer("heartbeat_at"),
130
+ leaseSeconds: integer("lease_seconds").notNull(),
131
+ expiresAt: integer("expires_at").generatedAlwaysAs(
132
+ sql`COALESCE(${sql.identifier("heartbeat_at")}, ${sql.identifier("claimed_at")}) + ${sql.identifier("lease_seconds")} * 1000`,
133
+ { mode: "virtual" },
134
+ ),
135
+ endedAt: integer("ended_at"),
136
+ resultJson: text("result_json"),
137
+ resultSummary: text("result_summary").generatedAlwaysAs(sql`json_extract(${sql.identifier("result_json")}, '$.summary')`, { mode: "virtual" }),
138
+ errorType: text("error_type"),
139
+ gateRecordJson: text("gate_record_json"),
140
+ gateType: text("gate_type").generatedAlwaysAs(sql`json_extract(${sql.identifier("gate_record_json")}, '$.type')`, { mode: "virtual" }),
141
+ }, (table) => [
142
+ check("attempts_status", sql`${table.status} IN (${inList(ATTEMPT_STATUSES)})`),
143
+ uniqueIndex("uq_attempt_item_no").on(table.itemId, table.attemptNo),
144
+ index("idx_attempt_session").on(table.sessionId),
145
+ uniqueIndex("uq_attempt_live").on(table.itemId).where(sql`${table.endedAt} IS NULL`),
146
+ index("idx_attempts_expiry").on(table.status, table.expiresAt),
147
+ ]);
148
+
149
+ export const artifacts = sqliteTable("artifacts", {
150
+ id: text("id").primaryKey(),
151
+ itemId: text("item_id").notNull().references(() => items.id, { onDelete: "cascade" }),
152
+ attemptId: text("attempt_id").references(() => attempts.id, { onDelete: "set null" }),
153
+ kind: text("kind").notNull(),
154
+ uri: text("uri").notNull(),
155
+ sha256: text("sha256"),
156
+ label: text("label"),
157
+ createdAt: integer("created_at").notNull(),
158
+ deletedAt: integer("deleted_at"),
159
+ }, (table) => [
160
+ uniqueIndex("uq_artifacts_uri").on(table.uri),
161
+ index("idx_artifacts_item").on(table.itemId),
162
+ index("idx_artifacts_attempt").on(table.attemptId),
163
+ ]);
164
+
165
+ export const itemEvents = sqliteTable("item_events", {
166
+ id: integer("id").primaryKey({ autoIncrement: true }),
167
+ itemId: text("item_id").notNull().references(() => items.id, { onDelete: "restrict" }),
168
+ attemptId: text("attempt_id").references(() => attempts.id, { onDelete: "set null" }),
169
+ sessionId: text("session_id").references(() => workSessions.id, { onDelete: "set null" }),
170
+ fromStatus: text("from_status"),
171
+ toStatus: text("to_status").notNull(),
172
+ kind: text("kind"),
173
+ actor: text("actor"),
174
+ note: text("note"),
175
+ payloadJson: text("payload_json"),
176
+ createdAt: integer("created_at").notNull(),
177
+ }, (table) => [
178
+ index("idx_item_events_item").on(table.itemId),
179
+ index("idx_item_events_created").on(table.createdAt),
180
+ ]);
181
+
182
+ export const itemEdges = sqliteTable("item_edges", {
183
+ fromItemId: text("from_item_id").notNull().references(() => items.id, { onDelete: "cascade" }),
184
+ toItemId: text("to_item_id").notNull().references(() => items.id, { onDelete: "cascade" }),
185
+ kind: text("kind").notNull().default("depends_on"),
186
+ createdAt: integer("created_at").notNull(),
187
+ }, (table) => [
188
+ primaryKey({ columns: [table.fromItemId, table.toItemId, table.kind] }),
189
+ check("item_edges_kind", sql`${table.kind} IN (${inList(EDGE_KINDS)})`),
190
+ index("idx_edges_from").on(table.fromItemId),
191
+ index("idx_edges_to").on(table.toItemId),
192
+ ]);
193
+
194
+ export const admissionQueue = sqliteTable("admission_queue", {
195
+ id: text("id").primaryKey(),
196
+ kind: text("kind").notNull(),
197
+ itemId: text("item_id").notNull().references(() => items.id, { onDelete: "cascade" }),
198
+ harness: text("harness").notNull(),
199
+ agentId: text("agent_id").notNull(),
200
+ status: text("status").notNull().default("queued"),
201
+ eventId: integer("event_id"),
202
+ createdAt: integer("created_at").notNull(),
203
+ endedAt: integer("ended_at"),
204
+ }, (table) => [
205
+ check("admission_kind", sql`${table.kind} IN (${inList(WAKE_KINDS)})`),
206
+ check("admission_status", sql`${table.status} IN (${inList(ADMISSION_STATUSES)})`),
207
+ uniqueIndex("uq_admission_live").on(table.itemId, table.harness).where(sql`${table.endedAt} IS NULL`),
208
+ index("idx_admission_harness").on(table.status, table.harness, table.createdAt),
209
+ index("idx_admission_global").on(table.status, table.createdAt),
210
+ index("idx_admission_item").on(table.itemId),
211
+ ]);
212
+
213
+ export const admissionAttempts = sqliteTable("admission_attempts", {
214
+ admissionId: text("admission_id").notNull().references(() => admissionQueue.id, { onDelete: "cascade" }),
215
+ attemptNo: integer("attempt_no").notNull(),
216
+ executorId: text("executor_id"),
217
+ consumerId: text("consumer_id"),
218
+ activeConsumerId: text("active_consumer_id"),
219
+ leaseEpoch: integer("lease_epoch").notNull().default(0),
220
+ leaseUntil: integer("lease_until"),
221
+ offeredAt: integer("offered_at").notNull(),
222
+ acceptedAt: integer("accepted_at"),
223
+ endedAt: integer("ended_at"),
224
+ }, (table) => [
225
+ primaryKey({ columns: [table.admissionId, table.attemptNo] }),
226
+ uniqueIndex("uq_admission_attempt_live").on(table.admissionId).where(sql`${table.endedAt} IS NULL`),
227
+ index("idx_admission_attempts_executor").on(table.executorId, table.endedAt),
228
+ ]);
229
+
230
+ export const webhooks = sqliteTable("webhooks", {
231
+ topic: text("topic").notNull(),
232
+ id: text("id").notNull(),
233
+ harness: text("harness"),
234
+ executorId: text("executor_id"),
235
+ url: text("url").notNull(),
236
+ bearer: text("bearer").notNull(),
237
+ timeoutMs: integer("timeout_ms"),
238
+ createdAt: integer("created_at").notNull(),
239
+ updatedAt: integer("updated_at").notNull(),
240
+ lastSeenAt: integer("last_seen_at").notNull(),
241
+ instanceId: text("instance_id"),
242
+ generation: integer("generation").notNull().default(0),
243
+ state: text("state").notNull().default("active"),
244
+ failureCount: integer("failure_count").notNull().default(0),
245
+ lastError: text("last_error"),
246
+ disabledAt: integer("disabled_at"),
247
+ leaseUntil: integer("lease_until"),
248
+ managed: integer("managed").notNull().default(0),
249
+ }, (table) => [
250
+ primaryKey({ columns: [table.topic, table.id] }),
251
+ check("webhooks_state", sql`${table.state} IN (${inList(WEBHOOK_STATES)})`),
252
+ index("idx_webhooks_topic_harness").on(table.topic, table.harness, table.state, table.lastSeenAt),
253
+ ]);
254
+
255
+ export const dispatchEvents = sqliteTable("dispatch_events", {
256
+ id: text("id").primaryKey(),
257
+ admissionId: text("admission_id").notNull().references(() => admissionQueue.id, { onDelete: "cascade" }),
258
+ attemptNo: integer("attempt_no").notNull(),
259
+ itemId: text("item_id").notNull().references(() => items.id, { onDelete: "cascade" }),
260
+ sourceEventId: integer("source_event_id"),
261
+ payloadJson: text("payload_json").notNull().default("{}"),
262
+ createdAt: integer("created_at").notNull(),
263
+ publishedAt: integer("published_at"),
264
+ }, (table) => [
265
+ uniqueIndex("uq_dispatch_event_attempt").on(table.admissionId, table.attemptNo),
266
+ index("idx_dispatch_events_created").on(table.createdAt),
267
+ ]);
268
+
269
+ export const dispatchDeliveries = sqliteTable("dispatch_deliveries", {
270
+ id: integer("id").primaryKey({ autoIncrement: true }),
271
+ admissionId: text("admission_id").notNull().references(() => admissionQueue.id, { onDelete: "cascade" }),
272
+ attemptNo: integer("attempt_no").notNull(),
273
+ eventId: text("event_id"),
274
+ consumerId: text("consumer_id").notNull(),
275
+ status: text("status").notNull().default("pending"),
276
+ attempts: integer("attempts").notNull().default(0),
277
+ nextAt: integer("next_at").notNull(),
278
+ lastStatus: integer("last_status"),
279
+ lastError: text("last_error"),
280
+ deliveredAt: integer("delivered_at"),
281
+ deadAt: integer("dead_at"),
282
+ createdAt: integer("created_at").notNull(),
283
+ updatedAt: integer("updated_at").notNull(),
284
+ }, (table) => [
285
+ check("delivery_status", sql`${table.status} IN (${inList(DELIVERY_STATUSES)})`),
286
+ uniqueIndex("uq_delivery_grain").on(table.admissionId, table.attemptNo, table.consumerId),
287
+ index("idx_delivery_due").on(table.status, table.nextAt),
288
+ index("idx_delivery_attempt").on(table.admissionId, table.attemptNo),
289
+ index("idx_delivery_event").on(table.eventId, table.consumerId),
290
+ ]);
291
+
292
+ export const dispatchDeliveryAttempts = sqliteTable("dispatch_delivery_attempts", {
293
+ id: integer("id").primaryKey({ autoIncrement: true }),
294
+ deliveryId: integer("delivery_id").notNull().references(() => dispatchDeliveries.id, { onDelete: "cascade" }),
295
+ attemptNo: integer("attempt_no").notNull(),
296
+ status: text("status").notNull(),
297
+ responseStatus: integer("response_status"),
298
+ error: text("error"),
299
+ createdAt: integer("created_at").notNull(),
300
+ }, (table) => [
301
+ index("idx_delivery_attempts_delivery").on(table.deliveryId, table.attemptNo),
302
+ ]);
@@ -0,0 +1,314 @@
1
+ // Durable wake admission. The queue is the identity and route; delivery
2
+ // attempts live in admission_attempts so offer/accept/retry history has one
3
+ // grain. Offer TTL, backoff, and executor ownership are attempt facts.
4
+ import { newAdmissionId } from "../ids.js";
5
+ import { HUMAN_HARNESS } from "../reserved.js";
6
+
7
+ const LIVE = "ended_at IS NULL";
8
+
9
+ export function createAdmissionApi({ core }) {
10
+ const { db, now } = core;
11
+
12
+ function liveAttempt(admissionId) {
13
+ return db.prepare(`
14
+ SELECT * FROM admission_attempts
15
+ WHERE admission_id=? AND ended_at IS NULL
16
+ ORDER BY attempt_no DESC LIMIT 1
17
+ `).get(admissionId) ?? null;
18
+ }
19
+
20
+ function attemptCount(admissionId) {
21
+ return db.prepare("SELECT COUNT(*) AS n FROM admission_attempts WHERE admission_id=?").get(admissionId).n;
22
+ }
23
+
24
+ function rowById(id) {
25
+ const row = db.prepare("SELECT * FROM admission_queue WHERE id=?").get(id);
26
+ if (!row) return null;
27
+ const attempt = liveAttempt(id);
28
+ return {
29
+ ...row,
30
+ offers: attemptCount(id),
31
+ attempt_no: attempt?.attempt_no ?? null,
32
+ executor_id: attempt?.executor_id ?? null,
33
+ active_consumer_id: attempt?.active_consumer_id ?? null,
34
+ lease_epoch: attempt?.lease_epoch ?? 0,
35
+ lease_until: attempt?.lease_until ?? null,
36
+ offered_at: attempt?.offered_at ?? null,
37
+ accepted_at: attempt?.accepted_at ?? null,
38
+ };
39
+ }
40
+
41
+ function endAttempts(ids, at) {
42
+ if (!ids.length) return;
43
+ const marks = ids.map(() => "?").join(",");
44
+ db.prepare(`UPDATE admission_attempts SET ended_at=? WHERE admission_id IN (${marks}) AND ended_at IS NULL`)
45
+ .run(at, ...ids);
46
+ }
47
+
48
+ function live(itemId, harness) {
49
+ return db.prepare(`SELECT * FROM admission_queue WHERE item_id=? AND harness=? AND ${LIVE}`)
50
+ .get(itemId, harness) ?? null;
51
+ }
52
+
53
+ function enqueue({ kind, itemId, harness, agentId, eventId = null, at = now() }) {
54
+ if (!itemId || !harness || !agentId) return null;
55
+ if (eventId != null) {
56
+ const seen = db.prepare(`
57
+ SELECT id FROM admission_queue
58
+ WHERE event_id=? AND kind=? AND item_id=? AND agent_id=? LIMIT 1
59
+ `).get(eventId, kind, itemId, agentId);
60
+ if (seen) return rowById(seen.id);
61
+ }
62
+ const existing = live(itemId, harness);
63
+ if (existing) {
64
+ if (existing.status === "active") return rowById(existing.id);
65
+ if (existing.event_id === eventId && existing.agent_id === agentId && existing.kind === kind) {
66
+ return rowById(existing.id);
67
+ }
68
+ const reset = existing.status === "offered" || existing.status === "accepted" || existing.status === "expired";
69
+ if (reset) endAttempts([existing.id], at);
70
+ db.prepare(`
71
+ UPDATE admission_queue
72
+ SET kind=?, agent_id=?, event_id=?, status=?
73
+ WHERE id=?
74
+ `).run(kind, agentId, eventId, reset ? "queued" : existing.status, existing.id);
75
+ return rowById(existing.id);
76
+ }
77
+ const id = newAdmissionId();
78
+ db.prepare(`
79
+ INSERT INTO admission_queue(id, kind, item_id, harness, agent_id, status, event_id, created_at)
80
+ VALUES (?, ?, ?, ?, ?, 'queued', ?, ?)
81
+ `).run(id, kind, itemId, harness, agentId, eventId, at);
82
+ return rowById(id);
83
+ }
84
+
85
+ function queued(harness, at = now(), limit = null) {
86
+ const sql = `SELECT * FROM admission_queue
87
+ WHERE status='queued' AND ended_at IS NULL
88
+ AND (harness=? OR harness='*')
89
+ ORDER BY created_at ASC, id ASC${limit ? " LIMIT ?" : ""}`;
90
+ return limit ? db.prepare(sql).all(harness, limit) : db.prepare(sql).all(harness);
91
+ }
92
+
93
+ function offers(harness) {
94
+ return db.prepare(`SELECT * FROM admission_queue
95
+ WHERE status='offered' AND ended_at IS NULL
96
+ AND (harness=? OR harness='*')
97
+ ORDER BY created_at ASC, id ASC`).all(harness);
98
+ }
99
+
100
+ function markOffered(id, at = now(), { activeConsumerId = null, leaseMs = null, pickActive = null } = {}) {
101
+ const row = db.prepare("SELECT * FROM admission_queue WHERE id=? AND status='queued' AND ended_at IS NULL").get(id);
102
+ if (!row) return null;
103
+ const attemptNo = db.prepare(
104
+ "SELECT COALESCE(MAX(attempt_no),0)+1 AS n FROM admission_attempts WHERE admission_id=?"
105
+ ).get(id).n;
106
+ const active = activeConsumerId ?? (typeof pickActive === "function" ? pickActive(attemptNo) : null);
107
+ db.prepare("INSERT INTO admission_attempts(admission_id, attempt_no, offered_at, active_consumer_id, lease_until) VALUES (?, ?, ?, ?, ?)")
108
+ .run(id, attemptNo, at, active, leaseMs == null ? null : at + leaseMs);
109
+ const r = db.prepare("UPDATE admission_queue SET status='offered' WHERE id=? AND status='queued' AND ended_at IS NULL")
110
+ .run(id);
111
+ if (r.changes === 0) {
112
+ db.prepare("DELETE FROM admission_attempts WHERE admission_id=? AND attempt_no=?").run(id, attemptNo);
113
+ return null;
114
+ }
115
+ return rowById(id);
116
+ }
117
+
118
+ function fail(id, at = now()) {
119
+ endAttempts([id], at);
120
+ db.prepare("UPDATE admission_queue SET status='expired' WHERE id=? AND status='offered' AND ended_at IS NULL").run(id);
121
+ }
122
+
123
+ function requeue(id, at = now()) {
124
+ endAttempts([id], at);
125
+ db.prepare(`
126
+ UPDATE admission_queue SET status='queued'
127
+ WHERE id=? AND status IN ('offered','accepted') AND ended_at IS NULL
128
+ `).run(id);
129
+ }
130
+
131
+ function activate(itemId, harness, at = now()) {
132
+ const ids = db.prepare(`
133
+ SELECT id FROM admission_queue
134
+ WHERE item_id=? AND ended_at IS NULL AND status IN ('queued','offered','accepted')
135
+ AND (harness=? OR harness='*')
136
+ `).all(itemId, harness).map((r) => r.id);
137
+ endAttempts(ids, at);
138
+ db.prepare(`
139
+ UPDATE admission_queue SET status='active'
140
+ WHERE item_id=? AND ended_at IS NULL AND status IN ('queued','offered','accepted')
141
+ AND (harness=? OR harness='*')
142
+ `).run(itemId, harness);
143
+ }
144
+
145
+ function release(itemId, status, at = now(), exceptEventId = null) {
146
+ const terminal = status === "done" || status === "cancelled";
147
+ const skip = exceptEventId != null ? " AND (event_id IS NULL OR event_id != ?)" : "";
148
+ const args = exceptEventId != null ? [itemId, exceptEventId] : [itemId];
149
+ const ids = db.prepare(`SELECT id FROM admission_queue WHERE item_id=? AND ended_at IS NULL${skip}`)
150
+ .all(...args).map((r) => r.id);
151
+ endAttempts(ids, at);
152
+ const sql = `UPDATE admission_queue SET status=?, ended_at=? WHERE item_id=? AND ended_at IS NULL${skip}`;
153
+ const updateArgs = [terminal ? status : "done", at, ...args];
154
+ db.prepare(sql).run(...updateArgs);
155
+ }
156
+
157
+ function expire({ at = now(), offerMs, baseBackoffMs, maxBackoffMs, maxAttempts }) {
158
+ const rows = db.prepare(`
159
+ SELECT q.id, q.kind, q.status, a.attempt_no, a.offered_at, a.accepted_at
160
+ FROM admission_queue q
161
+ JOIN admission_attempts a ON a.admission_id=q.id AND a.ended_at IS NULL
162
+ WHERE q.status IN ('offered','accepted') AND q.ended_at IS NULL
163
+ AND COALESCE(a.accepted_at, a.offered_at) + ? < ?
164
+ `).all(offerMs, at);
165
+ for (const row of rows) {
166
+ db.prepare("UPDATE admission_attempts SET ended_at=? WHERE admission_id=? AND attempt_no=?")
167
+ .run(at, row.id, row.attempt_no);
168
+ // Planner wakes have no task CAS. Once a planner has accepted the wake
169
+ // lease they are one-shot; an unaccepted offer must retry, or a 202 from
170
+ // a receiver that never spawned a session would silently lose the wake.
171
+ const planner = row.kind === "story" || row.kind === "append" || row.kind === "review";
172
+ if (planner && row.accepted_at != null) {
173
+ db.prepare("UPDATE admission_queue SET status='done', ended_at=? WHERE id=?").run(at, row.id);
174
+ continue;
175
+ }
176
+ const attempts = attemptCount(row.id);
177
+ db.prepare("UPDATE admission_queue SET status='expired', ended_at=? WHERE id=?")
178
+ .run(attempts >= maxAttempts ? at : null, row.id);
179
+ }
180
+ const expired = db.prepare(`
181
+ SELECT q.id, COUNT(a.attempt_no) AS attempts, MAX(a.ended_at) AS last_ended
182
+ FROM admission_queue q
183
+ JOIN admission_attempts a ON a.admission_id=q.id
184
+ WHERE q.status='expired' AND q.ended_at IS NULL
185
+ GROUP BY q.id
186
+ `).all();
187
+ for (const row of expired) {
188
+ const attempts = row.attempts || 1;
189
+ const backoff = Math.min(maxBackoffMs, baseBackoffMs * 2 ** Math.max(0, attempts - 1));
190
+ if ((row.last_ended ?? 0) + backoff <= at) {
191
+ db.prepare("UPDATE admission_queue SET status='queued' WHERE id=? AND status='expired'").run(row.id);
192
+ }
193
+ }
194
+ }
195
+
196
+
197
+ function acceptWake({ id, attemptNo, consumerId, leaseEpoch = null, leaseMs = 90000, at = now() }) {
198
+ if (!id || !consumerId || !Number.isInteger(attemptNo)) return { error: "bad_request" };
199
+ db.exec("BEGIN IMMEDIATE");
200
+ try {
201
+ const row = db.prepare(`
202
+ SELECT * FROM admission_queue WHERE id=? AND ended_at IS NULL
203
+ `).get(id);
204
+ const attempt = row ? liveAttempt(id) : null;
205
+ if (!row || !attempt || attempt.attempt_no !== attemptNo) {
206
+ db.exec("ROLLBACK");
207
+ return { error: "not_live" };
208
+ }
209
+ if (row.kind !== "story" && row.kind !== "append" && row.kind !== "review") {
210
+ db.exec("ROLLBACK");
211
+ return { error: "wrong_kind" };
212
+ }
213
+ if (attempt.active_consumer_id && attempt.active_consumer_id !== consumerId) {
214
+ db.exec("ROLLBACK");
215
+ return { error: "stale_lease" };
216
+ }
217
+ const currentEpoch = attempt.lease_epoch ?? 0;
218
+ let nextEpoch = currentEpoch;
219
+ if (!Number.isInteger(leaseEpoch) || leaseEpoch !== currentEpoch) {
220
+ db.exec("ROLLBACK");
221
+ return { error: "stale_lease" };
222
+ }
223
+ if (currentEpoch === 0) nextEpoch = 1;
224
+ db.prepare(`
225
+ UPDATE admission_attempts
226
+ SET active_consumer_id=?, lease_epoch=?, lease_until=?, accepted_at=?
227
+ WHERE admission_id=? AND attempt_no=? AND ended_at IS NULL
228
+ `).run(consumerId, nextEpoch, at + leaseMs, at, id, attemptNo);
229
+ db.prepare("UPDATE admission_queue SET status='accepted' WHERE id=? AND status IN ('offered','accepted')").run(id);
230
+ db.exec("COMMIT");
231
+ return {
232
+ admissionId: id, attemptNo, consumerId, leaseEpoch: nextEpoch,
233
+ leaseUntil: at + leaseMs, acceptedAt: at,
234
+ };
235
+ } catch (err) {
236
+ db.exec("ROLLBACK");
237
+ throw err;
238
+ }
239
+ }
240
+
241
+ function resetOffers(at = now()) {
242
+ const ids = db.prepare("SELECT id FROM admission_queue WHERE status IN ('offered','accepted') AND ended_at IS NULL")
243
+ .all().map((r) => r.id);
244
+ endAttempts(ids, at);
245
+ db.prepare("UPDATE admission_queue SET status='queued' WHERE status IN ('offered','accepted') AND ended_at IS NULL")
246
+ .run();
247
+ }
248
+
249
+ function lastEventId() {
250
+ return db.prepare("SELECT COALESCE(MAX(event_id), 0) AS id FROM admission_queue").get().id;
251
+ }
252
+
253
+ function setParentCursor(itemId, at = now()) {
254
+ const child = db.prepare("SELECT parent_id, child_key FROM items WHERE id=?").get(itemId);
255
+ if (!child?.child_key || !child.parent_id) return;
256
+ db.prepare(`
257
+ UPDATE item_state SET state_json=json_set(state_json, '$.currentChildKey', ?), updated_at=?
258
+ WHERE item_id=? AND deleted_at IS NULL
259
+ `).run(child.child_key, at, child.parent_id);
260
+ }
261
+
262
+ function slots() {
263
+ const active = new Map();
264
+ for (const r of db.prepare(`
265
+ SELECT assignee_harness AS harness, COUNT(*) AS n
266
+ FROM item_state
267
+ WHERE status='in_progress' AND deleted_at IS NULL AND assignee_harness IS NOT NULL
268
+ AND assignee_harness != ?
269
+ GROUP BY assignee_harness
270
+ `).all(HUMAN_HARNESS)) active.set(r.harness, r.n);
271
+ const reserved = new Map();
272
+ for (const r of db.prepare(`
273
+ SELECT harness, COUNT(*) AS n
274
+ FROM admission_queue
275
+ WHERE status IN ('offered','accepted') AND ended_at IS NULL
276
+ GROUP BY harness
277
+ `).all()) reserved.set(r.harness, r.n);
278
+ return { active, reserved };
279
+ }
280
+
281
+ function slotCount(harness) {
282
+ const { active, reserved } = slots();
283
+ return (active.get(harness) ?? 0) + (reserved.get(harness) ?? 0);
284
+ }
285
+
286
+ function globalSlotCount() {
287
+ const { active, reserved } = slots();
288
+ let n = 0;
289
+ for (const v of active.values()) n += v;
290
+ for (const v of reserved.values()) n += v;
291
+ return n;
292
+ }
293
+
294
+ return {
295
+ enqueue,
296
+ live,
297
+ get: rowById,
298
+ queued,
299
+ offers,
300
+ markOffered,
301
+ fail,
302
+ requeue,
303
+ activate,
304
+ release,
305
+ expire,
306
+ resetOffers,
307
+ acceptWake,
308
+ lastEventId,
309
+ setParentCursor,
310
+ slots,
311
+ slotCount,
312
+ globalSlotCount,
313
+ };
314
+ }
@@ -0,0 +1,24 @@
1
+ // Artifacts are links (or content-addressed URIs) attached to an item and
2
+ // optionally to the attempt that produced them.
3
+
4
+ import { newArtifactId } from "../ids.js";
5
+
6
+ export function createArtifactApi({ core }) {
7
+ const { db, now } = core;
8
+
9
+ return {
10
+ add({ itemId, attemptId = null, kind = "link", uri, sha256 = null, label = null }) {
11
+ if (!uri) throw new Error("artifact requires a uri");
12
+ const id = newArtifactId();
13
+ db.prepare(`
14
+ INSERT INTO artifacts(id, item_id, attempt_id, kind, uri, sha256, label, created_at)
15
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
16
+ ON CONFLICT(uri) DO NOTHING
17
+ `).run(id, itemId, attemptId, kind, uri, sha256, label, now());
18
+ return db.prepare("SELECT * FROM artifacts WHERE uri=?").get(uri) ?? null;
19
+ },
20
+ listFor(itemId) {
21
+ return db.prepare("SELECT * FROM artifacts WHERE item_id=? AND deleted_at IS NULL ORDER BY created_at ASC").all(itemId);
22
+ },
23
+ };
24
+ }
@@ -0,0 +1,22 @@
1
+ // Attempt rows are the claim history: one live attempt per item, numbered
2
+ // monotonically. The lease and gate projections live on the row.
3
+
4
+ export function createAttemptApi({ core }) {
5
+ const { db, endAttempt } = core;
6
+
7
+ const attemptApi = {
8
+ list({ itemId = null, status = null, live = false } = {}) {
9
+ const where = [];
10
+ const args = [];
11
+ if (itemId) { where.push("item_id=?"); args.push(itemId); }
12
+ if (status) { where.push("status=?"); args.push(status); }
13
+ if (live) where.push("ended_at IS NULL");
14
+ return db.prepare(`SELECT * FROM attempts${where.length ? ` WHERE ${where.join(" AND ")}` : ""} ORDER BY attempt_no DESC`)
15
+ .all(...args);
16
+ },
17
+ get(id) { return db.prepare("SELECT * FROM attempts WHERE id=?").get(id) ?? null; },
18
+ end(id, opts) { endAttempt(id, opts); return attemptApi.get(id); },
19
+ };
20
+
21
+ return attemptApi;
22
+ }