@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
@@ -0,0 +1,182 @@
1
+ // Claim lifecycle: acquire a task, heartbeat its lease, release it, and the
2
+ // direct assignment path. Claim and release each write the attempt and event
3
+ // in the same BEGIN IMMEDIATE transaction.
4
+
5
+ import { HUMAN_AGENT, HUMAN_HARNESS, resolveAssignmentPair } from "../reserved.js";
6
+
7
+ export function createClaimMethods({ core, apis }) {
8
+ const {
9
+ db, cfg, now, splitSessionKey, ensureSession,
10
+ liveAttempt, endAttempt, createAttempt, appendEvent, eventById,
11
+ } = core;
12
+
13
+ return {
14
+ claim({ id, agentId, harness = null, session = null, sessionKey = null, watchdogMs = null, consumerId = null, ownerInstance = null }) {
15
+ const row = apis.item.get(id);
16
+ if (!row || row.kind !== "task") return null;
17
+ const parsed = splitSessionKey(sessionKey);
18
+ const h = harness ?? parsed?.harness ?? "system";
19
+ if (agentId === HUMAN_AGENT || h === HUMAN_HARNESS) return null;
20
+ const extSession = session ?? parsed?.session ?? `store-${agentId}`;
21
+ const t = now();
22
+ const leaseMs = watchdogMs ?? cfg.leaseSeconds * 1000;
23
+ const leaseSeconds = Math.floor(leaseMs / 1000);
24
+ db.exec("BEGIN IMMEDIATE");
25
+ try {
26
+ const r = db.prepare(`
27
+ UPDATE item_state SET status='in_progress', assignee_harness=?, assignee_agent=?, updated_at=?
28
+ WHERE item_id=? AND status='ready' AND deleted_at IS NULL
29
+ AND assignee_agent=? AND assignee_harness=?
30
+ `).run(h, agentId, t, id, agentId, h);
31
+ if (r.changes === 0) { db.exec("ROLLBACK"); return null; }
32
+ const parentSessionId = row.state_json?.fanout?.parentSessionId ?? null;
33
+ const sess = ensureSession({
34
+ harness: h, agentId, externalSessionId: extSession, itemId: id, kind: "claim", parentSessionId,
35
+ });
36
+ const liveAdmission = db.prepare(`
37
+ SELECT aa.lease_epoch, aa.active_consumer_id
38
+ FROM admission_queue q
39
+ JOIN admission_attempts aa ON aa.admission_id=q.id AND aa.ended_at IS NULL
40
+ WHERE q.item_id=? AND q.harness=? AND q.status IN ('offered','accepted') AND q.ended_at IS NULL
41
+ ORDER BY aa.attempt_no DESC LIMIT 1
42
+ `).get(id, h);
43
+ if (consumerId && liveAdmission?.active_consumer_id && liveAdmission.active_consumer_id !== consumerId) {
44
+ db.exec("ROLLBACK");
45
+ return null;
46
+ }
47
+ const leaseEpoch = consumerId ? Math.max(1, liveAdmission?.lease_epoch ?? 0) : 0;
48
+ const attempt = createAttempt({
49
+ itemId: id, sessionId: sess.id, status: "running", claimedAt: t, leaseSeconds,
50
+ consumerId, ownerInstance, leaseEpoch,
51
+ });
52
+ if (consumerId) {
53
+ db.prepare(`
54
+ UPDATE admission_attempts SET consumer_id=?
55
+ WHERE ended_at IS NULL
56
+ AND admission_id IN (
57
+ SELECT id FROM admission_queue
58
+ WHERE item_id=? AND status IN ('offered','accepted') AND ended_at IS NULL
59
+ )
60
+ `).run(consumerId, id);
61
+ }
62
+ const eventId = appendEvent({
63
+ itemId: id, attemptId: attempt.id, sessionId: sess.id,
64
+ fromStatus: "ready", toStatus: "in_progress", kind: "task.claimed",
65
+ actor: agentId, note: "claim", at: t,
66
+ });
67
+ db.exec("COMMIT");
68
+ const task = apis.task.get(id);
69
+ task.attempt_id = attempt.id;
70
+ task.owner_instance = ownerInstance;
71
+ task.lease_epoch = leaseEpoch;
72
+ task.lastEvent = eventById(eventId);
73
+ return task;
74
+ } catch (err) {
75
+ db.exec("ROLLBACK");
76
+ throw err;
77
+ }
78
+ },
79
+
80
+ assign({ id, agentId = null, harness = null, actor = "system", capabilities }) {
81
+ const existing = apis.task.get(id);
82
+ if (!existing) throw new Error(`task not found: ${id}`);
83
+ const next = agentId === "" ? null : (agentId ?? null);
84
+ if (existing.status === "in_progress" && (existing.assigned ?? null) !== next) {
85
+ throw new Error(`${existing.id} is in_progress by ${existing.assigned ?? "nobody"}; wait for release before reassigning`);
86
+ }
87
+ const pair = resolveAssignmentPair(next, harness);
88
+ if (pair.agent != null && pair.harness == null) throw new Error(`assignment requires a harness: ${id}`);
89
+ const t = now();
90
+ const h = pair.harness;
91
+ let status = existing.status;
92
+ if (pair.agent == null && status === "ready") status = "backlog";
93
+ else if (pair.agent != null && status === "backlog") status = "ready";
94
+ db.exec("BEGIN IMMEDIATE");
95
+ try {
96
+ db.prepare("UPDATE item_state SET revision=revision+1, status=?, assignee_harness=?, assignee_agent=?, updated_at=? WHERE item_id=?")
97
+ .run(status, h, pair.agent, t, id);
98
+ if (capabilities !== undefined) {
99
+ db.prepare("DELETE FROM item_tags WHERE item_id=?").run(id);
100
+ for (const tag of capabilities ?? []) {
101
+ db.prepare("INSERT OR IGNORE INTO item_tags(item_id, tag, source, created_at) VALUES (?, ?, ?, ?)")
102
+ .run(id, String(tag), "assign", t);
103
+ }
104
+ }
105
+ appendEvent({
106
+ itemId: id, fromStatus: existing.status, toStatus: status, kind: "task.assigned",
107
+ actor, note: `assign ${pair.agent ?? "nobody"}`, at: t,
108
+ });
109
+ db.exec("COMMIT");
110
+ } catch (err) {
111
+ db.exec("ROLLBACK");
112
+ throw err;
113
+ }
114
+ return apis.task.get(id);
115
+ },
116
+
117
+ heartbeat(id, agentId, attemptId = null, leaseEpoch = null) {
118
+ const t = now();
119
+ if (attemptId) {
120
+ const exact = db.prepare(`
121
+ UPDATE attempts SET heartbeat_at=?
122
+ WHERE id=? AND item_id=? AND ended_at IS NULL
123
+ AND (lease_epoch = 0 OR lease_epoch = ?)
124
+ AND session_id IN (SELECT id FROM work_sessions WHERE agent_id=?)
125
+ `).run(t, attemptId, id, leaseEpoch, agentId);
126
+ if (exact.changes === 0) return null;
127
+ db.prepare("UPDATE item_state SET updated_at=? WHERE item_id=?").run(t, id);
128
+ return apis.task.get(id);
129
+ }
130
+ let r = db.prepare(`
131
+ UPDATE attempts SET heartbeat_at=?
132
+ WHERE item_id=? AND ended_at IS NULL
133
+ AND (lease_epoch = 0 OR lease_epoch = ?)
134
+ AND session_id IN (SELECT id FROM work_sessions WHERE agent_id=?)
135
+ `).run(t, id, leaseEpoch, agentId);
136
+ if (r.changes === 0) {
137
+ // A live attempt that did not match is a stale session, not a missing
138
+ // attempt. Only heal when there is genuinely no live attempt.
139
+ const live = db.prepare("SELECT id FROM attempts WHERE item_id=? AND ended_at IS NULL").get(id);
140
+ if (live) return null;
141
+ // A live item_state row can exist without an attempt when seeded
142
+ // directly; heal it rather than refusing a heartbeat the row's status
143
+ // allows.
144
+ const row = apis.item.get(id);
145
+ if (!row || row.status !== "in_progress" || row.assignee_agent !== agentId) return null;
146
+ const session = ensureSession({
147
+ harness: row.assignee_harness ?? "system",
148
+ agentId, externalSessionId: `heartbeat-${id}`, itemId: id, kind: "system",
149
+ });
150
+ createAttempt({ itemId: id, sessionId: session.id, status: "running", claimedAt: t, leaseSeconds: cfg.leaseSeconds });
151
+ r = db.prepare("UPDATE attempts SET heartbeat_at=? WHERE item_id=? AND ended_at IS NULL").run(t, id);
152
+ if (r.changes === 0) return null;
153
+ }
154
+ db.prepare("UPDATE item_state SET updated_at=? WHERE item_id=?").run(t, id);
155
+ return apis.task.get(id);
156
+ },
157
+
158
+ release(id, note = "release", at = now()) {
159
+ db.exec("BEGIN IMMEDIATE");
160
+ try {
161
+ const live = liveAttempt(id);
162
+ if (!live) { db.exec("ROLLBACK"); return null; }
163
+ endAttempt(live.id, { status: "released", endedAt: at });
164
+ const row = apis.item.get(id);
165
+ const status = row?.assignee_harness && row?.assignee_agent ? "ready" : "backlog";
166
+ db.prepare("UPDATE item_state SET revision=revision+1, status=?, updated_at=? WHERE item_id=?").run(status, at, id);
167
+ const eventId = appendEvent({
168
+ itemId: id, attemptId: live.id, sessionId: live.session_id,
169
+ fromStatus: "in_progress", toStatus: status, kind: "task.released",
170
+ actor: null, note, at,
171
+ });
172
+ db.exec("COMMIT");
173
+ const task = apis.task.get(id);
174
+ task.lastEvent = eventById(eventId);
175
+ return task;
176
+ } catch (err) {
177
+ db.exec("ROLLBACK");
178
+ throw err;
179
+ }
180
+ },
181
+ };
182
+ }
@@ -0,0 +1,225 @@
1
+ // Shared context for the store modules: the SQL projection, row decoration,
2
+ // event/session/attempt primitives, and the status vocabulary. `createStore`
3
+ // owns the database handle; everything here closes over it.
4
+
5
+ import { newAttemptId, newSessionId } from "../ids.js";
6
+ import {
7
+ EPIC_STATUSES,
8
+ STORY_STATUSES,
9
+ TASK_STATUSES,
10
+ EXECUTION_KINDS,
11
+ ITEM_KINDS,
12
+ } from "../schema.js";
13
+
14
+ export const MAX_ATTEMPTS = 3;
15
+
16
+ export const STATUSES_BY_KIND = { epic: EPIC_STATUSES, story: STORY_STATUSES, task: TASK_STATUSES };
17
+ export const DEFAULT_STATUS = { epic: "backlog", story: "backlog", task: "backlog" };
18
+ export const ITEM_TERMINAL = new Set(["done", "cancelled"]);
19
+
20
+ export const ITEM_SELECT = `
21
+ SELECT i.id, i.kind, i.parent_id, i.child_key, i.visit_seq, i.title, i.description,
22
+ i.acceptance, i.priority, i.size, i.owner_team, i.created_by,
23
+ i.execution_kind, i.execution_args, i.created_at,
24
+ s.revision, s.status, s.state_json, s.wait_kind, s.current_child_key,
25
+ s.assignee_harness, s.assignee_agent,
26
+ s.updated_at, s.closed_at, s.deleted_at
27
+ FROM items i JOIN item_state s ON s.item_id = i.id`;
28
+
29
+ export function now() { return Date.now(); }
30
+ export function jsonOut(v) { return v == null ? null : JSON.stringify(v); }
31
+ export function jsonIn(v) { if (v == null) return null; try { return JSON.parse(v); } catch { return null; } }
32
+ export function splitSessionKey(key) {
33
+ if (typeof key !== "string") return null;
34
+ const parts = key.split(":");
35
+ if (parts.length < 3) return null;
36
+ return { harness: parts[0], agent: parts[1], session: parts.slice(2).join(":") };
37
+ }
38
+
39
+ export function createCore({ db, cfg }) {
40
+ let eventHook = null;
41
+
42
+ function ancestors(id) {
43
+ const rows = db.prepare(`
44
+ WITH RECURSIVE up(id, kind, parent_id, depth) AS (
45
+ SELECT id, kind, parent_id, 0 FROM items WHERE id = ?
46
+ UNION ALL
47
+ SELECT i.id, i.kind, i.parent_id, up.depth + 1
48
+ FROM items i JOIN up ON i.id = up.parent_id
49
+ WHERE up.depth < 64
50
+ )
51
+ SELECT id, kind FROM up ORDER BY depth ASC
52
+ `).all(id);
53
+ return rows;
54
+ }
55
+
56
+ function decorate(r, { includeDeleted = false } = {}) {
57
+ if (!r) return null;
58
+ if (!includeDeleted && r.deleted_at != null) return null;
59
+ const tags = db.prepare("SELECT tag FROM item_tags WHERE item_id=? ORDER BY tag ASC").all(r.id).map((t) => t.tag);
60
+ const live = db.prepare(
61
+ "SELECT * FROM attempts WHERE item_id=? AND ended_at IS NULL ORDER BY attempt_no DESC LIMIT 1"
62
+ ).get(r.id);
63
+ const latest = live ?? db.prepare(
64
+ "SELECT * FROM attempts WHERE item_id=? ORDER BY attempt_no DESC LIMIT 1"
65
+ ).get(r.id);
66
+ const count = db.prepare("SELECT COALESCE(MAX(attempt_no),0) AS n FROM attempts WHERE item_id=?").get(r.id).n;
67
+ const gated = r.status === "blocked"
68
+ ? db.prepare("SELECT * FROM attempts WHERE item_id=? AND gate_record_json IS NOT NULL ORDER BY attempt_no DESC LIMIT 1").get(r.id)
69
+ : null;
70
+ const chain = ancestors(r.id);
71
+ const story = r.kind === "task" ? chain.find((a) => a.kind === "story") : null;
72
+ const epic = r.kind === "epic" ? { id: r.id } : chain.find((a) => a.kind === "epic");
73
+ return {
74
+ ...r,
75
+ state_json: jsonIn(r.state_json) ?? {},
76
+ execution_args: jsonIn(r.execution_args) ?? {},
77
+ capabilities: tags,
78
+ assigned: r.assignee_agent ?? null,
79
+ attempt_count: count,
80
+ claimed_at: live?.claimed_at ?? null,
81
+ claim_expires_at: live?.expires_at ?? null,
82
+ lease_seconds: live?.lease_seconds ?? latest?.lease_seconds ?? null,
83
+ last_heartbeat: live?.heartbeat_at ?? latest?.heartbeat_at ?? null,
84
+ gate_type: gated?.gate_type ?? null,
85
+ blocked_at: gated?.ended_at ?? null,
86
+ result_summary: latest?.result_summary ?? null,
87
+ flow_id: null,
88
+ task_run_id: null,
89
+ story_id: story?.id ?? null,
90
+ epic_id: epic?.id ?? null,
91
+ attempt_id: live?.id ?? latest?.id ?? null,
92
+ session_id: live?.session_id ?? latest?.session_id ?? null,
93
+ };
94
+ }
95
+
96
+ function getRow(id, { includeDeleted = false } = {}) {
97
+ return decorate(db.prepare(`${ITEM_SELECT} WHERE i.id=?`).get(id), { includeDeleted });
98
+ }
99
+
100
+ function listRows({ kind = null, parentId, status = null, assigned = null, assignedHarness = null, includeDeleted = false } = {}) {
101
+ const where = [];
102
+ const args = [];
103
+ if (kind) { where.push("i.kind=?"); args.push(kind); }
104
+ if (parentId !== undefined) { where.push("i.parent_id=?"); args.push(parentId); }
105
+ if (status) { where.push("s.status=?"); args.push(status); }
106
+ if (assigned) { where.push("s.assignee_agent=?"); args.push(assigned); }
107
+ if (assignedHarness) { where.push("s.assignee_harness=?"); args.push(assignedHarness); }
108
+ if (!includeDeleted) where.push("s.deleted_at IS NULL");
109
+ const order = kind === "task"
110
+ ? "i.created_at ASC"
111
+ : "i.priority DESC, i.created_at ASC";
112
+ const sql = `${ITEM_SELECT}${where.length ? ` WHERE ${where.join(" AND ")}` : ""} ORDER BY ${order}`;
113
+ return db.prepare(sql).all(...args).map((r) => decorate(r, { includeDeleted }));
114
+ }
115
+
116
+ function appendEvent({ itemId, attemptId = null, sessionId = null, fromStatus = null, toStatus, kind = null, actor = null, note = null, payload = null, at = null }) {
117
+ const r = db.prepare(`
118
+ INSERT INTO item_events(item_id, attempt_id, session_id, from_status, to_status, kind, actor, note, payload_json, created_at)
119
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
120
+ `).run(itemId, attemptId, sessionId, fromStatus, toStatus, kind, actor, note, jsonOut(payload), at ?? now());
121
+ const id = Number(r.lastInsertRowid);
122
+ // Runs inside the caller's transaction, so a status write and its wake
123
+ // admission commit or roll back together.
124
+ if (eventHook) eventHook(id);
125
+ return id;
126
+ }
127
+
128
+ function eventById(id) {
129
+ return db.prepare("SELECT * FROM item_events WHERE id=?").get(id) ?? null;
130
+ }
131
+
132
+ function eventsFor(itemId, limit = null) {
133
+ const sql = `SELECT * FROM item_events WHERE item_id=? ORDER BY id DESC${limit ? " LIMIT ?" : ""}`;
134
+ const rows = limit ? db.prepare(sql).all(itemId, limit) : db.prepare(sql).all(itemId);
135
+ return limit ? rows : rows.reverse();
136
+ }
137
+
138
+ function kindForTransition(kind, fromStatus, toStatus, gateType) {
139
+ if (fromStatus == null) return `${kind}.created`;
140
+ if (toStatus === "blocked") return gateType ? "gate.opened" : `${kind}.blocked`;
141
+ if (fromStatus === "blocked" && toStatus === "ready") return gateType ? "gate.dissolved" : `${kind}.released`;
142
+ if (toStatus === "done") return `${kind}.completed`;
143
+ if (toStatus === "cancelled") return `${kind}.cancelled`;
144
+ if (kind === "task" && fromStatus === "ready" && toStatus === "in_progress") return "task.claimed";
145
+ if (toStatus === "ready") return `${kind}.released`;
146
+ return `${kind}.updated`;
147
+ }
148
+
149
+ function ensureSession({ harness, agentId, externalSessionId, itemId, kind = "claim", parentSessionId = null }) {
150
+ const existing = db.prepare(
151
+ "SELECT * FROM work_sessions WHERE harness=? AND agent_id=? AND external_session_id=?"
152
+ ).get(harness, agentId, externalSessionId);
153
+ if (existing) {
154
+ const parent = existing.parent_session_id ?? parentSessionId ?? null;
155
+ const nextKind = parent ? "fanout" : existing.kind;
156
+ db.prepare("UPDATE work_sessions SET item_id=?, parent_session_id=?, kind=? WHERE id=?")
157
+ .run(itemId, parent, nextKind, existing.id);
158
+ return db.prepare("SELECT * FROM work_sessions WHERE id=?").get(existing.id);
159
+ }
160
+ const id = newSessionId();
161
+ db.prepare(`
162
+ INSERT INTO work_sessions(id, item_id, harness, agent_id, external_session_id, kind, parent_session_id, created_at)
163
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
164
+ `).run(id, itemId, harness, agentId, externalSessionId, parentSessionId ? "fanout" : kind, parentSessionId, now());
165
+ return db.prepare("SELECT * FROM work_sessions WHERE id=?").get(id);
166
+ }
167
+
168
+ function systemSession(itemId) {
169
+ return ensureSession({ harness: "system", agentId: "system", externalSessionId: "system", itemId, kind: "system" });
170
+ }
171
+
172
+ function liveAttempt(itemId) {
173
+ return db.prepare("SELECT * FROM attempts WHERE item_id=? AND ended_at IS NULL ORDER BY attempt_no DESC LIMIT 1").get(itemId) ?? null;
174
+ }
175
+
176
+ function endAttempt(attemptId, { status, endedAt = now(), result = null, errorType = null, gateRecord = null } = {}) {
177
+ db.prepare(`
178
+ UPDATE attempts SET status=?, ended_at=?, result_json=COALESCE(?, result_json),
179
+ error_type=COALESCE(?, error_type), gate_record_json=COALESCE(?, gate_record_json)
180
+ WHERE id=?
181
+ `).run(status, endedAt, jsonOut(result), errorType, jsonOut(gateRecord), attemptId);
182
+ }
183
+
184
+ function createAttempt({ itemId, sessionId, status = "running", claimedAt = now(), leaseSeconds, result = null, errorType = null, gateRecord = null, endedAt = null, consumerId = null, ownerInstance = null, leaseEpoch = 0 }) {
185
+ const no = db.prepare("SELECT COALESCE(MAX(attempt_no),0)+1 AS n FROM attempts WHERE item_id=?").get(itemId).n;
186
+ const id = newAttemptId();
187
+ db.prepare(`
188
+ INSERT INTO attempts(id, item_id, attempt_no, session_id, status, claimed_at, heartbeat_at,
189
+ lease_seconds, ended_at, result_json, error_type, gate_record_json,
190
+ consumer_id, owner_instance, lease_epoch)
191
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
192
+ `).run(id, itemId, no, sessionId, status, claimedAt, status === "gated" ? null : claimedAt,
193
+ leaseSeconds, endedAt, jsonOut(result), errorType, jsonOut(gateRecord), consumerId, ownerInstance, leaseEpoch);
194
+ return db.prepare("SELECT * FROM attempts WHERE id=?").get(id);
195
+ }
196
+
197
+ return {
198
+ db,
199
+ cfg,
200
+ ITEM_SELECT,
201
+ STATUSES_BY_KIND,
202
+ DEFAULT_STATUS,
203
+ ITEM_TERMINAL,
204
+ now,
205
+ jsonIn,
206
+ jsonOut,
207
+ splitSessionKey,
208
+ ancestors,
209
+ decorate,
210
+ getRow,
211
+ listRows,
212
+ appendEvent,
213
+ setEventHook(fn) { eventHook = fn; },
214
+ eventById,
215
+ eventsFor,
216
+ kindForTransition,
217
+ ensureSession,
218
+ systemSession,
219
+ liveAttempt,
220
+ endAttempt,
221
+ createAttempt,
222
+ };
223
+ }
224
+
225
+ export { EPIC_STATUSES, STORY_STATUSES, TASK_STATUSES, EXECUTION_KINDS, ITEM_KINDS };
@@ -0,0 +1,137 @@
1
+ // Per-consumer delivery ledger. One row per admission attempt × consumer; the
2
+ // relay retries each row independently, so one failed endpoint cannot hide
3
+ // behind another endpoint's 2xx.
4
+
5
+ export function createDeliveryApi({ core }) {
6
+ const { db, now } = core;
7
+
8
+ function rowById(id) {
9
+ return db.prepare("SELECT * FROM dispatch_deliveries WHERE id=?").get(id) ?? null;
10
+ }
11
+
12
+ const api = {
13
+ ensure({ admissionId, attemptNo, consumerId, eventId = null, at = now() }) {
14
+ db.prepare(`
15
+ INSERT INTO dispatch_deliveries(admission_id, attempt_no, event_id, consumer_id, status, attempts,
16
+ next_at, created_at, updated_at)
17
+ VALUES (?, ?, ?, ?, 'pending', 0, ?, ?, ?)
18
+ ON CONFLICT(admission_id, attempt_no, consumer_id) DO UPDATE SET
19
+ event_id=COALESCE(dispatch_deliveries.event_id, excluded.event_id)
20
+ `).run(admissionId, attemptNo, eventId, consumerId, at, at, at);
21
+ return db.prepare(`
22
+ SELECT * FROM dispatch_deliveries
23
+ WHERE admission_id=? AND attempt_no=? AND consumer_id=?
24
+ `).get(admissionId, attemptNo, consumerId) ?? null;
25
+ },
26
+
27
+ list({ admissionId = null, attemptNo = null, consumerId = null, status = null, dueAt = null, limit = null } = {}) {
28
+ const where = [];
29
+ const args = [];
30
+ if (admissionId != null) { where.push("admission_id=?"); args.push(admissionId); }
31
+ if (attemptNo != null) { where.push("attempt_no=?"); args.push(attemptNo); }
32
+ if (consumerId != null) { where.push("consumer_id=?"); args.push(consumerId); }
33
+ if (status != null) { where.push("status=?"); args.push(status); }
34
+ if (dueAt != null) { where.push("next_at<=?"); args.push(dueAt); }
35
+ const sql = `SELECT * FROM dispatch_deliveries${where.length ? ` WHERE ${where.join(" AND ")}` : ""}
36
+ ORDER BY next_at ASC, id ASC${limit ? " LIMIT ?" : ""}`;
37
+ return limit ? db.prepare(sql).all(...args, limit) : db.prepare(sql).all(...args);
38
+ },
39
+
40
+ due(at = now(), limit = 50) {
41
+ return api.list({ status: "pending", dueAt: at, limit });
42
+ },
43
+
44
+ claimDue({ at = now(), limit = 50, admissionId = null } = {}) {
45
+ const rows = admissionId
46
+ ? db.prepare(`
47
+ SELECT * FROM dispatch_deliveries
48
+ WHERE status='pending' AND next_at<=? AND admission_id=?
49
+ ORDER BY next_at ASC, id ASC LIMIT ?
50
+ `).all(at, admissionId, limit)
51
+ : db.prepare(`
52
+ SELECT * FROM dispatch_deliveries
53
+ WHERE status='pending' AND next_at<=?
54
+ ORDER BY next_at ASC, id ASC LIMIT ?
55
+ `).all(at, limit);
56
+ const mark = db.prepare("UPDATE dispatch_deliveries SET status='delivering', updated_at=? WHERE id=? AND status='pending'");
57
+ return rows.filter((row) => mark.run(at, row.id).changes > 0)
58
+ .map((row) => ({ ...row, status: "delivering", updated_at: at }));
59
+ },
60
+
61
+ releaseStale({ before, at = now() } = {}) {
62
+ return db.prepare(`
63
+ UPDATE dispatch_deliveries SET status='pending', next_at=?, updated_at=?
64
+ WHERE status='delivering' AND updated_at < ?
65
+ `).run(at, at, before).changes;
66
+ },
67
+
68
+ recordAttempt({ deliveryId, attemptNo, status, responseStatus = null, error = null, at = now() }) {
69
+ db.prepare(`
70
+ INSERT INTO dispatch_delivery_attempts(delivery_id, attempt_no, status, response_status, error, created_at)
71
+ VALUES (?, ?, ?, ?, ?, ?)
72
+ `).run(deliveryId, attemptNo, status, responseStatus, error == null ? null : String(error), at);
73
+ },
74
+
75
+ pendingForAttempt(admissionId, attemptNo) {
76
+ return api.list({ admissionId, attemptNo, status: "pending" });
77
+ },
78
+
79
+ allForAttempt(admissionId, attemptNo) {
80
+ return api.list({ admissionId, attemptNo });
81
+ },
82
+
83
+ get: rowById,
84
+
85
+ markDelivered(id, { status = 202, at = now() } = {}) {
86
+ db.prepare(`
87
+ UPDATE dispatch_deliveries
88
+ SET status='delivered', attempts=attempts+1, last_status=?, last_error=NULL,
89
+ delivered_at=?, updated_at=?
90
+ WHERE id=?
91
+ `).run(status, at, at, id);
92
+ return rowById(id);
93
+ },
94
+
95
+ markRetry(id, { status = null, error = null, nextAt, at = now() } = {}) {
96
+ db.prepare(`
97
+ UPDATE dispatch_deliveries
98
+ SET status='pending', attempts=attempts+1, last_status=?, last_error=?,
99
+ next_at=?, updated_at=?
100
+ WHERE id=?
101
+ `).run(status, error == null ? null : String(error), nextAt, at, id);
102
+ return rowById(id);
103
+ },
104
+
105
+ markDead(id, { status = null, error = null, at = now() } = {}) {
106
+ db.prepare(`
107
+ UPDATE dispatch_deliveries
108
+ SET status='dead', attempts=attempts+1, last_status=?, last_error=?,
109
+ dead_at=?, updated_at=?
110
+ WHERE id=?
111
+ `).run(status, error == null ? null : String(error), at, at, id);
112
+ return rowById(id);
113
+ },
114
+
115
+ cancelForAttempt(admissionId, attemptNo, { at = now() } = {}) {
116
+ db.prepare(`
117
+ UPDATE dispatch_deliveries
118
+ SET status='cancelled', updated_at=?
119
+ WHERE admission_id=? AND attempt_no=? AND status IN ('pending','delivering')
120
+ `).run(at, admissionId, attemptNo);
121
+ },
122
+
123
+ resetForConsumer(admissionId, attemptNo, consumerId, { at = now() } = {}) {
124
+ db.prepare(`
125
+ UPDATE dispatch_deliveries
126
+ SET status='pending', next_at=?, delivered_at=NULL, dead_at=NULL, updated_at=?
127
+ WHERE admission_id=? AND attempt_no=? AND consumer_id=?
128
+ `).run(at, at, admissionId, attemptNo, consumerId);
129
+ return db.prepare(`
130
+ SELECT * FROM dispatch_deliveries
131
+ WHERE admission_id=? AND attempt_no=? AND consumer_id=?
132
+ `).get(admissionId, attemptNo, consumerId) ?? null;
133
+ },
134
+ };
135
+
136
+ return api;
137
+ }
@@ -0,0 +1,62 @@
1
+ // Edges between items. The primary key includes `kind`, so another edge kind
2
+ // needs no migration.
3
+
4
+ export function createDepApi({ core }) {
5
+ const { db, now } = core;
6
+
7
+ const row = (r) => r ? {
8
+ from_id: r.from_item_id, from_kind: r.from_kind,
9
+ to_id: r.to_item_id, to_kind: r.to_kind,
10
+ created_at: r.created_at, kind: r.kind,
11
+ } : null;
12
+
13
+ const depApi = {
14
+ addRaw({ fromId, toId, kind = "depends_on" }) {
15
+ db.prepare(`
16
+ INSERT INTO item_edges(from_item_id, to_item_id, kind, created_at) VALUES (?, ?, ?, ?)
17
+ ON CONFLICT(from_item_id, to_item_id, kind) DO NOTHING
18
+ `).run(fromId, toId, kind, now());
19
+ return depApi.get(fromId, toId);
20
+ },
21
+ get(fromId, toId) {
22
+ const r = db.prepare(`
23
+ SELECT e.from_item_id, e.to_item_id, e.kind, e.created_at,
24
+ fi.kind AS from_kind, ti.kind AS to_kind
25
+ FROM item_edges e
26
+ JOIN items fi ON fi.id=e.from_item_id
27
+ JOIN items ti ON ti.id=e.to_item_id
28
+ WHERE e.from_item_id=? AND e.to_item_id=?
29
+ `).get(fromId, toId);
30
+ return row(r);
31
+ },
32
+ remove({ fromId, toId }) {
33
+ const r = db.prepare("DELETE FROM item_edges WHERE from_item_id=? AND to_item_id=?").run(fromId, toId);
34
+ return r.changes > 0;
35
+ },
36
+ listOutgoing(fromId) {
37
+ return db.prepare(`
38
+ SELECT e.from_item_id, e.to_item_id, e.kind, e.created_at,
39
+ fi.kind AS from_kind, ti.kind AS to_kind
40
+ FROM item_edges e
41
+ JOIN items fi ON fi.id=e.from_item_id
42
+ JOIN items ti ON ti.id=e.to_item_id
43
+ WHERE e.from_item_id=?
44
+ `).all(fromId).map(row);
45
+ },
46
+ listIncoming(toId) {
47
+ return db.prepare(`
48
+ SELECT e.from_item_id, e.to_item_id, e.kind, e.created_at,
49
+ fi.kind AS from_kind, ti.kind AS to_kind
50
+ FROM item_edges e
51
+ JOIN items fi ON fi.id=e.from_item_id
52
+ JOIN items ti ON ti.id=e.to_item_id
53
+ WHERE e.to_item_id=?
54
+ `).all(toId).map(row);
55
+ },
56
+ all() {
57
+ return db.prepare("SELECT * FROM item_edges").all();
58
+ },
59
+ };
60
+
61
+ return depApi;
62
+ }
@@ -0,0 +1,38 @@
1
+ // Durable dispatch events: one immutable row per admission attempt. Delivery
2
+ // rows point at this event, so a retry keeps the same identity even when the
3
+ // admission attempt is re-queued.
4
+
5
+ export function createDispatchEventApi({ core }) {
6
+ const { db, now, jsonIn, jsonOut } = core;
7
+
8
+ function idFor(admissionId, attemptNo) {
9
+ return `${admissionId}:${attemptNo}`;
10
+ }
11
+
12
+ return {
13
+ ensure({ admissionId, attemptNo, itemId, sourceEventId = null, payload = {}, at = now() }) {
14
+ const id = idFor(admissionId, attemptNo);
15
+ db.prepare(`
16
+ INSERT INTO dispatch_events(id, admission_id, attempt_no, item_id, source_event_id, payload_json, created_at)
17
+ VALUES (?, ?, ?, ?, ?, ?, ?)
18
+ ON CONFLICT(admission_id, attempt_no) DO NOTHING
19
+ `).run(id, admissionId, attemptNo, itemId, sourceEventId, jsonOut(payload), at);
20
+ return this.get({ admissionId, attemptNo });
21
+ },
22
+
23
+ get({ admissionId, attemptNo }) {
24
+ const row = db.prepare(`
25
+ SELECT * FROM dispatch_events WHERE admission_id=? AND attempt_no=?
26
+ `).get(admissionId, attemptNo);
27
+ return row ? { ...row, payload_json: jsonIn(row.payload_json) ?? {} } : null;
28
+ },
29
+
30
+ markPublished({ admissionId, attemptNo, at = now() }) {
31
+ db.prepare(`
32
+ UPDATE dispatch_events SET published_at=COALESCE(published_at, ?)
33
+ WHERE admission_id=? AND attempt_no=?
34
+ `).run(at, admissionId, attemptNo);
35
+ return this.get({ admissionId, attemptNo });
36
+ },
37
+ };
38
+ }
@@ -0,0 +1,31 @@
1
+ // Epic facade: a small vocabulary over the recursive item API.
2
+
3
+ export function createEpicApi({ core, apis }) {
4
+ const { db } = core;
5
+
6
+ return {
7
+ create({ title, description, acceptance, status, ownerTeam, priority, id, createdBy }) {
8
+ return apis.item.create({
9
+ id, kind: "epic", title, description, acceptance,
10
+ status: status ?? "backlog", ownerTeam, priority,
11
+ createdBy, emit: false,
12
+ });
13
+ },
14
+ get(id) {
15
+ const row = apis.item.get(id);
16
+ return row?.kind === "epic" ? row : null;
17
+ },
18
+ list({ status } = {}) {
19
+ return apis.item.list({ kind: "epic", status });
20
+ },
21
+ update(id, patch) {
22
+ const existing = apis.epic.get(id);
23
+ if (!existing) throw new Error(`epic not found: ${id}`);
24
+ return apis.item.update(id, { ...patch, status: patch.status });
25
+ },
26
+ delete(id) {
27
+ const r = db.prepare("DELETE FROM items WHERE id=? AND kind='epic'").run(id);
28
+ return r.changes > 0;
29
+ },
30
+ };
31
+ }