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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/.migrations/0000_next_katie_power.sql +99 -0
  2. package/.migrations/0001_add-events-kind.sql +8 -0
  3. package/.migrations/0002_drop-session-budgets.sql +1 -0
  4. package/.migrations/0003_pink_siren.sql +8 -0
  5. package/.migrations/0004_salty_trauma.sql +1 -0
  6. package/.migrations/0005_classy_havok.sql +1 -0
  7. package/.migrations/0006_recursive_items.sql +265 -0
  8. package/.migrations/0007_unify_statuses.sql +35 -0
  9. package/.migrations/0008_core_dispatch.sql +61 -0
  10. package/.migrations/0009_webhooks.sql +17 -0
  11. package/.migrations/0010_dispatch_consumer_id.sql +1 -0
  12. package/.migrations/0011_dispatch_delivery_leases.sql +53 -0
  13. package/.migrations/0012_dispatch_fencing_audit.sql +32 -0
  14. package/.migrations/meta/0000_snapshot.json +658 -0
  15. package/.migrations/meta/0001_snapshot.json +665 -0
  16. package/.migrations/meta/0002_snapshot.json +604 -0
  17. package/.migrations/meta/0003_snapshot.json +656 -0
  18. package/.migrations/meta/0004_snapshot.json +664 -0
  19. package/.migrations/meta/0005_snapshot.json +671 -0
  20. package/.migrations/meta/0006_snapshot.json +1089 -0
  21. package/.migrations/meta/0007_unify_statuses_snapshot.json +1097 -0
  22. package/.migrations/meta/0008_snapshot.json +1382 -0
  23. package/.migrations/meta/0009_snapshot.json +1428 -0
  24. package/.migrations/meta/0010_snapshot.json +1435 -0
  25. package/.migrations/meta/0011_snapshot.json +1670 -0
  26. package/.migrations/meta/0012_snapshot.json +1900 -0
  27. package/.migrations/meta/_journal.json +97 -0
  28. package/README.md +480 -2
  29. package/bin/winch.js +4 -0
  30. package/package.json +36 -4
  31. package/plugins/README.md +304 -0
  32. package/plugins/openclaw/winch/README.md +71 -0
  33. package/plugins/openclaw/winch/dispatch.js +236 -0
  34. package/plugins/openclaw/winch/index.js +139 -0
  35. package/plugins/openclaw/winch/meta.js +35 -0
  36. package/plugins/openclaw/winch/openclaw.plugin.json +43 -0
  37. package/plugins/openclaw/winch/package.json +37 -0
  38. package/plugins/opencode/winch/dispatch.js +228 -0
  39. package/plugins/opencode/winch/hooks.js +22 -0
  40. package/plugins/opencode/winch/identity.js +34 -0
  41. package/plugins/opencode/winch/index.js +104 -0
  42. package/plugins/opencode/winch/package.json +26 -0
  43. package/src/cli.js +434 -0
  44. package/src/config.js +181 -0
  45. package/src/db.js +39 -0
  46. package/src/deps.js +70 -0
  47. package/src/dispatch-server.js +204 -0
  48. package/src/dispatch-webhook.js +221 -0
  49. package/src/dispatch.js +258 -0
  50. package/src/events-ws.js +269 -0
  51. package/src/identity.js +140 -0
  52. package/src/ids.js +18 -0
  53. package/src/mcp-http.js +208 -0
  54. package/src/mcp.js +107 -0
  55. package/src/merges.js +150 -0
  56. package/src/paths.js +15 -0
  57. package/src/ready-queue.js +77 -0
  58. package/src/release.js +96 -0
  59. package/src/reserved.js +23 -0
  60. package/src/schema.js +302 -0
  61. package/src/store/admission.js +314 -0
  62. package/src/store/artifacts.js +24 -0
  63. package/src/store/attempts.js +22 -0
  64. package/src/store/claims.js +182 -0
  65. package/src/store/core.js +225 -0
  66. package/src/store/delivery.js +137 -0
  67. package/src/store/deps.js +62 -0
  68. package/src/store/dispatch-events.js +38 -0
  69. package/src/store/epics.js +31 -0
  70. package/src/store/events.js +21 -0
  71. package/src/store/gates.js +85 -0
  72. package/src/store/index.js +135 -0
  73. package/src/store/items.js +303 -0
  74. package/src/store/stories.js +37 -0
  75. package/src/store/sweep.js +77 -0
  76. package/src/store/tasks.js +190 -0
  77. package/src/store/webhook.js +197 -0
  78. package/src/tools/accept-wake.js +30 -0
  79. package/src/tools/assign.js +75 -0
  80. package/src/tools/claim.js +88 -0
  81. package/src/tools/definitions.js +371 -0
  82. package/src/tools/delegate.js +147 -0
  83. package/src/tools/index.js +44 -0
  84. package/src/tools/plan.js +262 -0
  85. package/src/tools/read.js +103 -0
  86. package/src/tools/report.js +190 -0
  87. package/src/tools/shared.js +62 -0
  88. package/src/watcher.js +105 -0
@@ -0,0 +1,190 @@
1
+ // Task facade: the tool-facing task methods plus the state transition that
2
+ // ends/creates an attempt and then writes the item event.
3
+
4
+ import { depsResolved } from "../deps.js";
5
+ import { TASK_STATUSES } from "../schema.js";
6
+
7
+ export function createTaskApi({ core, apis }) {
8
+ const {
9
+ db, cfg, now, splitSessionKey, ensureSession, systemSession,
10
+ liveAttempt, endAttempt, createAttempt, appendEvent, ITEM_TERMINAL,
11
+ } = core;
12
+
13
+ const taskApi = {
14
+ create({ storyId, title, description, status, executionKind, executionArgs, capabilities, assigned, assigneeHarness, id, childKey, visitSeq, state }) {
15
+ const parent = apis.item.get(storyId, { includeDeleted: true });
16
+ if (!parent) throw new Error(`story not found: ${storyId}`);
17
+ if (parent.kind !== "story" && parent.kind !== "task") throw new Error(`task parent must be a story or task: ${storyId}`);
18
+ return apis.item.create({
19
+ id, kind: "task", parentId: storyId, childKey, visitSeq, title, description,
20
+ status, executionKind: executionKind ?? "manual",
21
+ executionArgs, capabilities, state,
22
+ assigneeAgent: assigned ?? null,
23
+ assigneeHarness: assigned ? assigneeHarness : null,
24
+ emit: true, note: "task created",
25
+ });
26
+ },
27
+ get(id) {
28
+ const row = apis.item.get(id);
29
+ return row?.kind === "task" ? row : null;
30
+ },
31
+ list({ storyId, status, assigned, assignedHarness } = {}) {
32
+ return apis.item.list({ kind: "task", parentId: storyId, status, assigned, assignedHarness });
33
+ },
34
+ update(id, patch) {
35
+ const existing = taskApi.get(id);
36
+ if (!existing) throw new Error(`task not found: ${id}`);
37
+ if (patch.status && !TASK_STATUSES.includes(patch.status)) throw new Error(`invalid task status: ${patch.status}`);
38
+ const t = patch.updatedAt ?? now();
39
+ const nextStatus = patch.status ?? existing.status;
40
+ const enteringGate = nextStatus === "blocked" && existing.status !== "blocked";
41
+ const leavingBlocked = existing.status === "blocked" && nextStatus !== "blocked";
42
+ const gateType = patch.gateType !== undefined ? patch.gateType : (enteringGate ? existing.gate_type : null);
43
+ const resultSummary = patch.result_summary !== undefined ? patch.result_summary : undefined;
44
+ const hasSession = patch.sessionKey || patch.harness || patch.session;
45
+ const parsed = splitSessionKey(patch.sessionKey);
46
+ let sessionId = patch.sessionId ?? null;
47
+ if (!sessionId && hasSession) {
48
+ const session = ensureSession({
49
+ harness: patch.harness ?? parsed?.harness ?? "system",
50
+ agentId: patch.agentId ?? patch.actor ?? existing.assignee_agent ?? "system",
51
+ externalSessionId: patch.session ?? parsed?.session ?? "system",
52
+ itemId: id,
53
+ });
54
+ sessionId = session.id;
55
+ }
56
+ db.exec("BEGIN IMMEDIATE");
57
+ try {
58
+ const live = liveAttempt(id);
59
+ if (enteringGate) {
60
+ const gateRecord = gateType ? { type: gateType, reason: patch.note ?? null, actor: patch.actor ?? null, openedAt: t } : null;
61
+ if (live) {
62
+ endAttempt(live.id, { status: gateRecord ? "gated" : "released", endedAt: t, gateRecord });
63
+ } else if (gateRecord) {
64
+ const session = sessionId ? { id: sessionId } : systemSession(id);
65
+ createAttempt({ itemId: id, sessionId: session.id, status: "gated", claimedAt: t, endedAt: t, leaseSeconds: cfg.leaseSeconds, gateRecord });
66
+ }
67
+ } else if (live && (ITEM_TERMINAL.has(nextStatus) || nextStatus === "ready" || leavingBlocked)) {
68
+ const status = ITEM_TERMINAL.has(nextStatus) ? nextStatus : "released";
69
+ const result = resultSummary !== undefined ? { summary: resultSummary } : null;
70
+ endAttempt(live.id, { status, endedAt: t, result });
71
+ } else if (live && resultSummary !== undefined) {
72
+ db.prepare("UPDATE attempts SET result_json=? WHERE id=?").run(JSON.stringify({ summary: resultSummary }), live.id);
73
+ } else if (!live && (ITEM_TERMINAL.has(nextStatus) || resultSummary !== undefined)) {
74
+ const session = sessionId ? { id: sessionId } : systemSession(id);
75
+ createAttempt({
76
+ itemId: id,
77
+ sessionId: session.id,
78
+ status: ITEM_TERMINAL.has(nextStatus) ? nextStatus : "running",
79
+ claimedAt: existing.claimed_at ?? t,
80
+ endedAt: ITEM_TERMINAL.has(nextStatus) ? (existing.closed_at ?? t) : null,
81
+ leaseSeconds: cfg.leaseSeconds,
82
+ result: resultSummary !== undefined ? { summary: resultSummary } : null,
83
+ });
84
+ }
85
+ db.exec("COMMIT");
86
+ } catch (err) {
87
+ db.exec("ROLLBACK");
88
+ throw err;
89
+ }
90
+ let assigneeHarness = patch.assignee_harness;
91
+ if (patch.assigned !== undefined && patch.assignee_harness === undefined) {
92
+ assigneeHarness = patch.assigned == null
93
+ ? null
94
+ : (patch.harness ?? parsed?.harness ?? existing.assignee_harness);
95
+ }
96
+ const row = apis.item.update(id, {
97
+ status: patch.status,
98
+ title: patch.title,
99
+ description: patch.description,
100
+ acceptance: patch.acceptance,
101
+ priority: patch.priority,
102
+ size: patch.size,
103
+ ownerTeam: patch.ownerTeam,
104
+ executionKind: patch.execution_kind ?? patch.executionKind,
105
+ executionArgs: patch.execution_args ?? patch.executionArgs,
106
+ assigneeHarness,
107
+ assigneeAgent: patch.assigned,
108
+ capabilities: patch.capabilities,
109
+ actor: patch.actor ?? null,
110
+ note: patch.note ?? null,
111
+ sessionId,
112
+ kind: patch.kind ?? (enteringGate ? (gateType ? "gate.opened" : "task.blocked") : (leavingBlocked && existing.gate_type ? "gate.dissolved" : undefined)),
113
+ event: patch.event,
114
+ updatedAt: t,
115
+ });
116
+ return row;
117
+ },
118
+ blockOnDeps({ id, note = null, childId = null, actor = "system", at = null }) {
119
+ const existing = taskApi.get(id);
120
+ if (!existing) throw new Error(`task not found: ${id}`);
121
+ if (!["backlog", "ready", "in_progress"].includes(existing.status)) {
122
+ throw new Error(`${existing.id} is ${existing.status}; cannot wait on dependencies`);
123
+ }
124
+ const t = at ?? now();
125
+ const state = { ...(existing.state_json ?? {}) };
126
+ state.wait = {
127
+ kind: "deps",
128
+ since: t,
129
+ ...(childId ? { childId } : {}),
130
+ ...(note ? { reason: note } : {}),
131
+ };
132
+ db.exec("BEGIN IMMEDIATE");
133
+ try {
134
+ const live = liveAttempt(id);
135
+ if (live) endAttempt(live.id, { status: "released", endedAt: t });
136
+ db.prepare("UPDATE item_state SET revision=revision+1, status='blocked', state_json=?, updated_at=? WHERE item_id=?")
137
+ .run(JSON.stringify(state), t, id);
138
+ appendEvent({
139
+ itemId: id, fromStatus: existing.status, toStatus: "blocked",
140
+ kind: "deps.waiting", actor,
141
+ note: note ?? (childId ? `waiting on ${childId}` : "waiting on dependencies"), at: t,
142
+ });
143
+ db.exec("COMMIT");
144
+ } catch (err) {
145
+ db.exec("ROLLBACK");
146
+ throw err;
147
+ }
148
+ return taskApi.get(id);
149
+ },
150
+ resumeDependencyWaits({ at = null } = {}) {
151
+ const rows = db.prepare(`
152
+ SELECT s.item_id, s.assignee_harness, s.assignee_agent, s.state_json
153
+ FROM item_state s JOIN items i ON i.id = s.item_id
154
+ WHERE i.kind = 'task' AND s.status = 'blocked' AND s.deleted_at IS NULL
155
+ AND s.wait_kind = 'deps'
156
+ `).all();
157
+ const resolved = [];
158
+ if (rows.length === 0) return resolved;
159
+ const t = at ?? now();
160
+ db.exec("BEGIN IMMEDIATE");
161
+ try {
162
+ const dependencyView = { dep: apis.dep, item: apis.item, config: cfg };
163
+ for (const row of rows) {
164
+ if (!depsResolved(dependencyView, row.item_id)) continue;
165
+ const status = row.assignee_harness && row.assignee_agent ? "ready" : "backlog";
166
+ const state = JSON.parse(row.state_json || "{}");
167
+ delete state.wait;
168
+ db.prepare("UPDATE item_state SET revision=revision+1, status=?, state_json=?, updated_at=? WHERE item_id=?")
169
+ .run(status, JSON.stringify(state), t, row.item_id);
170
+ appendEvent({
171
+ itemId: row.item_id, fromStatus: "blocked", toStatus: status,
172
+ kind: "deps.resolved", actor: "system", note: "dependencies resolved", at: t,
173
+ });
174
+ resolved.push(row.item_id);
175
+ }
176
+ db.exec("COMMIT");
177
+ } catch (err) {
178
+ db.exec("ROLLBACK");
179
+ throw err;
180
+ }
181
+ return resolved;
182
+ },
183
+ delete(id) {
184
+ const r = db.prepare("DELETE FROM items WHERE id=? AND kind='task'").run(id);
185
+ return r.changes > 0;
186
+ },
187
+ };
188
+
189
+ return taskApi;
190
+ }
@@ -0,0 +1,197 @@
1
+ // Webhook subscriptions, keyed by topic and stable id. A subscription is a
2
+ // lease owned by one live instance: a different instance may only take over
3
+ // after the current lease expires. Harness/executor are target metadata, not
4
+ // identity.
5
+
6
+ const DEFAULT_LEASE_MS = 90000;
7
+
8
+ export class StaleRegistrationError extends Error {
9
+ constructor(current) {
10
+ super(`subscription is leased by ${current?.instanceId ?? "another instance"}`);
11
+ this.name = "StaleRegistrationError";
12
+ this.code = "stale_instance";
13
+ this.current = current ?? null;
14
+ }
15
+ }
16
+
17
+ function required(value, name) {
18
+ const s = typeof value === "string" ? value.trim() : "";
19
+ if (!s) throw new Error(`webhook requires ${name}`);
20
+ return s;
21
+ }
22
+
23
+ function optional(value, name) {
24
+ if (value == null || value === "") return null;
25
+ if (typeof value !== "string") throw new Error(`webhook ${name} must be a string`);
26
+ const s = value.trim();
27
+ return s || null;
28
+ }
29
+
30
+ function toWebhook(row) {
31
+ if (!row) return null;
32
+ return {
33
+ topic: row.topic,
34
+ id: row.id,
35
+ harness: row.harness,
36
+ executorId: row.executor_id,
37
+ url: row.url,
38
+ bearer: row.bearer,
39
+ timeoutMs: row.timeout_ms,
40
+ createdAt: row.created_at,
41
+ updatedAt: row.updated_at,
42
+ lastSeenAt: row.last_seen_at,
43
+ instanceId: row.instance_id,
44
+ generation: row.generation,
45
+ state: row.state,
46
+ failureCount: row.failure_count,
47
+ lastError: row.last_error,
48
+ disabledAt: row.disabled_at,
49
+ leaseUntil: row.lease_until,
50
+ managed: Boolean(row.managed),
51
+ };
52
+ }
53
+
54
+ export function createWebhookApi({ core }) {
55
+ const { db, now } = core;
56
+
57
+ const api = {
58
+ upsert({
59
+ topic, id, harness = null, executorId = null, instanceId = null,
60
+ url, bearer, timeoutMs = null, at = now(), leaseMs = DEFAULT_LEASE_MS,
61
+ managed = false, fresh = false,
62
+ }) {
63
+ const t = required(topic, "a topic");
64
+ const i = required(id, "an id");
65
+ const h = optional(harness, "harness");
66
+ const e = optional(executorId, "executorId");
67
+ const explicitInstance = optional(instanceId, "instanceId");
68
+ const isManaged = managed === true || explicitInstance != null;
69
+ const inst = explicitInstance ?? e ?? i;
70
+ if (!Number.isInteger(leaseMs) || leaseMs <= 0) throw new Error("webhook leaseMs must be a positive integer");
71
+ let u;
72
+ try { u = new URL(url); } catch { throw new Error(`invalid webhook url: ${JSON.stringify(url)}`); }
73
+ if (u.protocol !== "http:" && u.protocol !== "https:") {
74
+ throw new Error(`webhook url must be http(s): ${JSON.stringify(url)}`);
75
+ }
76
+ if (typeof bearer !== "string" || bearer === "") {
77
+ throw new Error("webhook requires a bearer");
78
+ }
79
+ if (timeoutMs != null && (!Number.isInteger(timeoutMs) || timeoutMs <= 0)) {
80
+ throw new Error(`webhook timeoutMs must be a positive integer, got ${JSON.stringify(timeoutMs)}`);
81
+ }
82
+ const existing = api.get({ topic: t, id: i });
83
+ if (isManaged && existing?.managed && existing.instanceId && existing.instanceId !== inst
84
+ && existing.state !== "disabled" && (existing.leaseUntil ?? 0) > at) {
85
+ throw new StaleRegistrationError(existing);
86
+ }
87
+ const generation = existing
88
+ ? existing.generation + (isManaged && existing.instanceId && existing.instanceId !== inst ? 1 : 0)
89
+ : 0;
90
+ // A heartbeat refreshes the lease; it must not erase a failure or
91
+ // re-enable a disabled endpoint. Only a fresh process start (or an
92
+ // explicit CLI registration) resets the state.
93
+ const state = fresh ? "active" : (existing?.state ?? "active");
94
+ const failureCount = fresh ? 0 : (existing?.failureCount ?? 0);
95
+ const lastError = fresh ? null : (existing?.lastError ?? null);
96
+ const disabledAt = fresh ? null : (existing?.disabledAt ?? null);
97
+ const managedValue = isManaged ? 1 : (existing?.managed ? 1 : 0);
98
+ const instanceValue = isManaged ? inst : (existing?.instanceId ?? null);
99
+ const leaseUntil = managedValue ? at + leaseMs : null;
100
+ db.prepare(`
101
+ INSERT INTO webhooks(topic, id, harness, executor_id, url, bearer, timeout_ms, created_at, updated_at, last_seen_at,
102
+ instance_id, generation, state, failure_count, last_error, disabled_at, lease_until, managed)
103
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
104
+ ON CONFLICT(topic, id) DO UPDATE SET harness=excluded.harness, executor_id=excluded.executor_id,
105
+ url=excluded.url, bearer=excluded.bearer, timeout_ms=excluded.timeout_ms,
106
+ updated_at=excluded.updated_at, last_seen_at=excluded.last_seen_at,
107
+ instance_id=excluded.instance_id, generation=excluded.generation,
108
+ state=excluded.state, failure_count=excluded.failure_count, last_error=excluded.last_error,
109
+ disabled_at=excluded.disabled_at, lease_until=excluded.lease_until, managed=excluded.managed
110
+ `).run(t, i, h, e, u.toString(), bearer, timeoutMs ?? null, at, at, at, instanceValue, generation,
111
+ state, failureCount, lastError, disabledAt, leaseUntil, managedValue);
112
+ return api.get({ topic: t, id: i });
113
+ },
114
+
115
+ remove({ topic, id }) {
116
+ const r = db.prepare("DELETE FROM webhooks WHERE topic=? AND id=?").run(required(topic, "a topic"), required(id, "an id"));
117
+ return r.changes > 0;
118
+ },
119
+
120
+ list({ topic = null, harness = null } = {}) {
121
+ const clauses = [];
122
+ const params = [];
123
+ if (topic != null) { clauses.push("topic=?"); params.push(required(topic, "a topic")); }
124
+ if (harness != null) { clauses.push("harness=?"); params.push(optional(harness, "harness")); }
125
+ const where = clauses.length ? ` WHERE ${clauses.join(" AND ")}` : "";
126
+ return db.prepare(`SELECT * FROM webhooks${where} ORDER BY topic ASC, harness ASC, id ASC`)
127
+ .all(...params).map(toWebhook);
128
+ },
129
+
130
+ forHarness(harness, { topic = "dispatch" } = {}) {
131
+ return db.prepare(`
132
+ SELECT * FROM webhooks
133
+ WHERE topic=? AND (harness=? OR harness IS NULL) AND state != 'disabled'
134
+ ORDER BY id ASC
135
+ `).all(required(topic, "a topic"), required(harness, "a harness")).map(toWebhook);
136
+ },
137
+
138
+ recordSuccess({ topic, id, at = now() }) {
139
+ db.prepare(`
140
+ UPDATE webhooks SET state='active', failure_count=0, last_error=NULL, disabled_at=NULL, last_seen_at=?, updated_at=?
141
+ WHERE topic=? AND id=?
142
+ `).run(at, at, required(topic, "a topic"), required(id, "an id"));
143
+ return api.get({ topic, id });
144
+ },
145
+
146
+ recordFailure({ topic, id, status = null, error = null, permanent = false, threshold = 4, at = now() }) {
147
+ const row = api.get({ topic, id });
148
+ if (!row) return null;
149
+ const failures = row.failureCount + 1;
150
+ const disable = permanent || failures >= threshold;
151
+ db.prepare(`
152
+ UPDATE webhooks
153
+ SET state=?, failure_count=?, last_error=?, disabled_at=?, updated_at=?
154
+ WHERE topic=? AND id=?
155
+ `).run(disable ? "disabled" : "suspect", failures,
156
+ String(error ?? (status == null ? "unreachable" : `HTTP ${status}`)),
157
+ disable ? at : row.disabledAt, at, required(topic, "a topic"), required(id, "an id"));
158
+ return api.get({ topic, id });
159
+ },
160
+
161
+ disable({ topic, id, error = null, at = now() }) {
162
+ db.prepare(`
163
+ UPDATE webhooks SET state='disabled', last_error=?, disabled_at=?, updated_at=?
164
+ WHERE topic=? AND id=?
165
+ `).run(String(error ?? "disabled"), at, at, required(topic, "a topic"), required(id, "an id"));
166
+ return api.get({ topic, id });
167
+ },
168
+
169
+ prune({ topic, before = now() } = {}) {
170
+ // Disabled rows are retained as audit evidence. Manual subscriptions have
171
+ // no heartbeat and must not be swept just because traffic is quiet.
172
+ return db.prepare("DELETE FROM webhooks WHERE topic=? AND managed=1 AND state != 'disabled' AND last_seen_at < ?")
173
+ .run(required(topic, "a topic"), Number(before)).changes;
174
+ },
175
+
176
+ get({ topic, id }) {
177
+ const row = db.prepare("SELECT * FROM webhooks WHERE topic=? AND id=?")
178
+ .get(required(topic, "a topic"), required(id, "an id"));
179
+ return toWebhook(row);
180
+ },
181
+
182
+ topics() {
183
+ return db.prepare("SELECT DISTINCT topic FROM webhooks ORDER BY topic ASC")
184
+ .all().map((r) => r.topic);
185
+ },
186
+
187
+ harnesses({ topic = null } = {}) {
188
+ const rows = topic == null
189
+ ? db.prepare("SELECT DISTINCT harness FROM webhooks WHERE harness IS NOT NULL AND state != 'disabled' ORDER BY harness ASC").all()
190
+ : db.prepare("SELECT DISTINCT harness FROM webhooks WHERE topic=? AND harness IS NOT NULL AND state != 'disabled' ORDER BY harness ASC")
191
+ .all(required(topic, "a topic"));
192
+ return rows.map((r) => r.harness);
193
+ },
194
+ };
195
+
196
+ return api;
197
+ }
@@ -0,0 +1,30 @@
1
+ // Planner execution lease. Tasks use backlog_claim as their CAS; planner wakes
2
+ // (story/append/review) have no task row, so this is the one-winner guard.
3
+ import { ok, err } from "./shared.js";
4
+
5
+ export function createAcceptWakeTools({ store, logger }) {
6
+ return {
7
+ async backlog_accept_wake(args, identity, cfg) {
8
+ const id = typeof args?.admissionId === "string" ? args.admissionId.trim() : "";
9
+ const attemptNo = Number(args?.attemptNo);
10
+ const consumerId = identity.consumer;
11
+ const leaseEpoch = Number(args?.leaseEpoch);
12
+ if (!id || !Number.isInteger(attemptNo)) return err("backlog_accept_wake: admissionId and attemptNo are required", "rejected");
13
+ if (!consumerId) return err("backlog_accept_wake: caller has no consumer id", "rejected");
14
+ try {
15
+ const result = store.admission.acceptWake({
16
+ id, attemptNo, consumerId, leaseEpoch,
17
+ leaseMs: Math.max(cfg.dispatchConsumerTtlMs ?? 90000, cfg.dispatchOfferMs ?? 120000),
18
+ });
19
+ if (result?.error === "not_live") return err(`${id} attempt ${attemptNo} is not live; re-read recover.`, "stale_lease", { admissionId: id, attemptNo });
20
+ if (result?.error === "wrong_kind") return err(`${id} is a task wake; use backlog_claim.`, "rejected", { admissionId: id });
21
+ if (result?.error === "stale_lease") return err(`${id} is leased by another consumer or epoch.`, "stale_lease", { admissionId: id, attemptNo });
22
+ if (result?.error) return err(`backlog_accept_wake failed: ${result.error}`, "error", { admissionId: id });
23
+ return ok(JSON.stringify({ ok: true, ...result }), { status: "ok", admissionId: id, attemptNo, leaseEpoch: result.leaseEpoch });
24
+ } catch (e) {
25
+ logger?.warn?.(`backlog_accept_wake failed: ${e?.message}`);
26
+ return err(`backlog_accept_wake failed: ${e?.message}`, "error", { admissionId: id });
27
+ }
28
+ },
29
+ };
30
+ }
@@ -0,0 +1,75 @@
1
+ // assign.js — route an item to an agent; the row is the wake.
2
+ //
3
+ // The tool still takes only `agent`. The harness is not a parameter: it is
4
+ // stamped from the caller's declared transport identity, so an assignment can
5
+ // never name an agent without saying which harness it belongs to. The reserved
6
+ // agent `human` gets the reserved harness `human_in_the_loop` instead.
7
+ import { ok, err } from "./shared.js";
8
+
9
+ export function createAssignTools({ store, logger }) {
10
+ return {
11
+ async backlog_assign(args, identity, cfg) {
12
+ const qualified = `${identity.harness}:${identity.agent}`;
13
+ const target = args?.id ?? args?.taskId;
14
+ const kind = target ? store.itemKindOf(target) : null;
15
+ if (!kind) return err(`backlog_assign: not found: ${target}`, "not_found", { id: target ?? null });
16
+
17
+ if (kind === "story") {
18
+ const story = store.story.get(target);
19
+ if (story.status === "done" || story.status === "cancelled") {
20
+ return err(`${story.id} is ${story.status}; only live stories can be assigned.`, "rejected", { id: story.id });
21
+ }
22
+ if (args?.agent === null || args?.agent === "") {
23
+ return err(`${story.id}: agent is required; null/unassigned is not allowed.`, "rejected", { id: story.id });
24
+ }
25
+ try {
26
+ const assigned = args?.agent === undefined ? story.assignee_agent ?? null : (args.agent || null);
27
+ const updated = store.story.update(story.id, {
28
+ assigned,
29
+ assigneeHarness: assigned ? identity.harness : null,
30
+ capabilities: args?.capabilities !== undefined ? args.capabilities : story.capabilities ?? undefined,
31
+ });
32
+ store.event.append({
33
+ itemId: story.id,
34
+ fromStatus: story.status,
35
+ toStatus: updated.status,
36
+ kind: "story.assigned",
37
+ actor: qualified,
38
+ note: `assign ${assigned ?? "nobody"}`,
39
+ });
40
+ logger?.info?.(`backlog: ${qualified} assigned ${story.id} -> ${assigned ?? "nobody"}`);
41
+ return ok(
42
+ JSON.stringify({ ok: true, story: { id: updated.id, status: updated.status, assigned: updated.assignee_agent, capabilities: updated.capabilities } }),
43
+ { status: "ok", level: "story", id: updated.id, assigned: updated.assignee_agent, agent: identity.agent }
44
+ );
45
+ } catch (e) {
46
+ return err(`backlog_assign failed: ${e?.message}`, "rejected", { id: story.id });
47
+ }
48
+ }
49
+
50
+ if (kind !== "task") {
51
+ return err(`backlog_assign: ${target} is an ${kind}; assign a task or a story.`, "rejected", { id: target });
52
+ }
53
+ const task = store.task.get(target);
54
+ if (args?.agent === null || args?.agent === "" || args?.agent === undefined) {
55
+ return err(`${task.id}: agent is required; null/unassigned is not allowed.`, "rejected", { taskId: task.id });
56
+ }
57
+ try {
58
+ const updated = store.task.assign({
59
+ id: task.id,
60
+ agentId: args?.agent ?? null,
61
+ harness: identity.harness,
62
+ actor: qualified,
63
+ capabilities: args?.capabilities,
64
+ });
65
+ logger?.info?.(`backlog: ${qualified} assigned ${task.id} -> ${updated.assignee_agent ?? "nobody"}`);
66
+ return ok(
67
+ JSON.stringify({ ok: true, task: { id: updated.id, status: updated.status, assigned: updated.assignee_agent, capabilities: updated.capabilities } }),
68
+ { status: "ok", taskId: updated.id, assigned: updated.assignee_agent, agent: identity.agent }
69
+ );
70
+ } catch (e) {
71
+ return err(`backlog_assign failed: ${e?.message}`, "rejected", { taskId: task.id });
72
+ }
73
+ },
74
+ };
75
+ }
@@ -0,0 +1,88 @@
1
+ // claim.js — claim one task by id, or the next ready task for this agent.
2
+ import { readyTasks } from "../ready-queue.js";
3
+ import { identitySessionKey } from "../identity.js";
4
+ import { ok, err, collectStoryArtifacts, renderReceiverPrompt } from "./shared.js";
5
+
6
+ export function createClaimTools({ store, logger }) {
7
+ return {
8
+ async backlog_claim(args, identity, cfg) {
9
+ const agentId = identity.agent;
10
+ const sessionKey = identitySessionKey(identity);
11
+ // No id: pull the ready queue for this agent and take the first claim
12
+ // that wins its CAS. A loser moves to the next candidate, never retries
13
+ // the same row.
14
+ if (!args?.taskId) {
15
+ try {
16
+ const candidates = readyTasks(store, { agentId, harness: identity.harness, capabilities: args?.capabilities, limit: cfg.candidates });
17
+ if (candidates.length === 0) {
18
+ return ok(JSON.stringify({ empty: true }), { status: "empty", agentId });
19
+ }
20
+ if (args?.dryRun) {
21
+ const c = candidates[0];
22
+ return ok(JSON.stringify({ dryRun: true, task: c.task, story: { id: c.story.id, title: c.story.title, acceptance: c.story.acceptance }, epic: { id: c.epic.id, title: c.epic.title } }), { status: "ok", dryRun: true, agentId, taskId: c.task.id });
23
+ }
24
+ for (const c of candidates) {
25
+ const claimed = store.task.claim({ id: c.task.id, agentId, harness: identity.harness, session: identity.session, sessionKey, watchdogMs: cfg.leaseSeconds * 1000, consumerId: identity.consumer, ownerInstance: identity.instance });
26
+ if (!claimed) continue;
27
+ logger?.info?.(`backlog: ${agentId} claimed ${claimed.id} from the ready queue`);
28
+ const artifacts = collectStoryArtifacts(store, c.story.id);
29
+ const handoff = {
30
+ reason: "ready-queue claim",
31
+ priority: c.story.priority,
32
+ acceptance_criteria: c.story.acceptance,
33
+ artifacts,
34
+ receiverPrompt: renderReceiverPrompt({ task: claimed, story: c.story, epic: c.epic, artifacts }),
35
+ };
36
+ return ok(
37
+ JSON.stringify({
38
+ task: claimed,
39
+ story: { id: c.story.id, title: c.story.title, acceptance: c.story.acceptance, priority: c.story.priority },
40
+ epic: { id: c.epic.id, title: c.epic.title, priority: c.epic.priority },
41
+ handoff,
42
+ }),
43
+ { status: "ok", agentId, taskId: claimed.id }
44
+ );
45
+ }
46
+ return ok(JSON.stringify({ empty: true, raced: true }), { status: "empty", reason: "all_candidates_raced", agentId });
47
+ } catch (e) {
48
+ logger?.warn?.(`backlog_claim (ready queue) failed: ${e?.message}`);
49
+ return err(`backlog_claim failed: ${e?.message}`, "error");
50
+ }
51
+ }
52
+ const task = store.task.get(args?.taskId);
53
+ if (!task) return err(`backlog_claim: not found: ${args?.taskId}`, "not_found", { taskId: args?.taskId ?? null });
54
+ if (task.status !== "ready") return err(`${task.id} is ${task.status}, not ready — claim applies to ready tasks only.`, "not_claimed", { taskId: task.id });
55
+ try {
56
+ // No limit: an id lookup must not false-negative behind a paging cap.
57
+ const candidates = readyTasks(store, { agentId, harness: identity.harness, capabilities: args?.capabilities });
58
+ const c = candidates.find((cand) => cand.task.id === task.id);
59
+ if (!c) return err(`${task.id} is ready but not currently claimable (deps unmet or caps mismatch) — nothing claimed.`, "not_ready", { taskId: task.id });
60
+ if (args?.dryRun) {
61
+ return ok(JSON.stringify({ dryRun: true, task: c.task, story: { id: c.story.id, title: c.story.title, acceptance: c.story.acceptance }, epic: { id: c.epic.id, title: c.epic.title } }), { status: "ok", dryRun: true, agentId, taskId: task.id });
62
+ }
63
+ const claimed = store.task.claim({ id: c.task.id, agentId, harness: identity.harness, session: identity.session, sessionKey, watchdogMs: cfg.leaseSeconds * 1000, consumerId: identity.consumer, ownerInstance: identity.instance });
64
+ if (!claimed) return ok(JSON.stringify({ empty: true, raced: true }), { status: "empty", reason: "claim_raced", agentId, taskId: task.id });
65
+ logger?.info?.(`backlog: ${agentId} claimed ${claimed.id} by id`);
66
+ const artifacts = collectStoryArtifacts(store, c.story.id);
67
+ return ok(
68
+ JSON.stringify({
69
+ task: claimed,
70
+ story: { id: c.story.id, title: c.story.title, acceptance: c.story.acceptance, priority: c.story.priority },
71
+ epic: { id: c.epic.id, title: c.epic.title, priority: c.epic.priority },
72
+ handoff: {
73
+ reason: "by-id claim",
74
+ priority: c.story.priority,
75
+ acceptance_criteria: c.story.acceptance,
76
+ artifacts,
77
+ receiverPrompt: renderReceiverPrompt({ task: claimed, story: c.story, epic: c.epic, artifacts }),
78
+ },
79
+ }),
80
+ { status: "ok", agentId, taskId: claimed.id }
81
+ );
82
+ } catch (e) {
83
+ logger?.warn?.(`backlog_claim failed: ${e?.message}`);
84
+ return err(`backlog_claim failed: ${e?.message}`, "error");
85
+ }
86
+ },
87
+ };
88
+ }