@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,258 @@
1
+ // Core dispatch: route lifecycle rows to wake admissions, then admit offers
2
+ // under per-harness and global caps. The harness accepts an offer; only the
3
+ // winner starts a session. Item status remains the work acknowledgement.
4
+
5
+ import { HUMAN_AGENT, HUMAN_HARNESS } from "./reserved.js";
6
+ import { pickConsumer } from "./dispatch-webhook.js";
7
+
8
+ const RELEASING_STATUSES = new Set(["done", "cancelled", "blocked", "backlog", "review"]);
9
+
10
+ function isHuman(agent, harness) {
11
+ return agent === HUMAN_AGENT || harness === HUMAN_HARNESS;
12
+ }
13
+
14
+ function add(out, itemId, kind, agent, harness, reason) {
15
+ if (!itemId || !agent || isHuman(agent, harness)) return;
16
+ out.push({ itemId, kind, agentId: agent, harness: harness || "*", reason });
17
+ }
18
+
19
+ export function routesForEvent(ev) {
20
+ const out = [];
21
+ const item = ev?.item;
22
+ if (!item?.id) return out;
23
+
24
+ const addTask = (itemId, agent, harness, reason) => {
25
+ if (!agent) return;
26
+ add(out, itemId, "task", agent, harness, reason);
27
+ };
28
+
29
+ switch (ev.kind) {
30
+ case "task.created":
31
+ case "task.assigned":
32
+ case "task.released":
33
+ case "gate.resolved": {
34
+ if (item.status !== "ready") break;
35
+ addTask(item.id, item.assigned, item.assigneeHarness, ev.kind);
36
+ break;
37
+ }
38
+ case "story.created":
39
+ case "story.assigned": {
40
+ if (item.status !== "ready") break;
41
+ add(out, item.id, "story", item.assigned, item.assigneeHarness, ev.kind);
42
+ break;
43
+ }
44
+ case "task.restored": {
45
+ if (item.status !== "ready") break;
46
+ addTask(item.id, item.assigned, item.assigneeHarness, ev.kind);
47
+ break;
48
+ }
49
+ case "task.appended": {
50
+ if (item.status !== "ready") break;
51
+ const agent = ev.epicCreatedBy ?? item.createdBy;
52
+ const harness = ev.epicAssigneeHarness ?? "*";
53
+ add(out, ev.epicId ?? item.id, "append", agent, harness, ev.kind);
54
+ break;
55
+ }
56
+ case "epic.completed": {
57
+ if (item.kind !== "epic") break;
58
+ const agent = ev.epicCreatedBy ?? item.createdBy;
59
+ const harness = ev.epicAssigneeHarness ?? "*";
60
+ add(out, item.id, "review", agent, harness, ev.kind);
61
+ break;
62
+ }
63
+ default:
64
+ break;
65
+ }
66
+
67
+ for (const u of ev?.unblocked ?? []) {
68
+ addTask(u.id, u.assigned, u.assigneeHarness, "unblocked");
69
+ }
70
+ const seen = new Set();
71
+ return out.filter((r) => {
72
+ const key = `${r.itemId}\0${r.kind}\0${r.harness}\0${r.agentId}`;
73
+ if (seen.has(key)) return false;
74
+ seen.add(key);
75
+ return true;
76
+ });
77
+ }
78
+
79
+ export function observe(store, ev, at = Date.now()) {
80
+ const item = ev?.item;
81
+ if (item?.id) {
82
+ const harness = item.assigneeHarness ?? ev.storyAssigneeHarness ?? ev.epicAssigneeHarness ?? "*";
83
+ if (item.status === "in_progress") {
84
+ store.admission.activate(item.id, harness, at);
85
+ // `ready` is not generally releasing: assignment to ready is the wake.
86
+ } else if (RELEASING_STATUSES.has(item.status) ||
87
+ (item.status === "ready" && (ev.kind === "task.released" || ev.kind === "gate.resolved"))) {
88
+ // A duplicate event must not release the row that event just admitted.
89
+ store.admission.release(item.id, item.status, at, ev.id ?? null);
90
+ }
91
+ }
92
+ const routes = routesForEvent(ev);
93
+ for (const route of routes) {
94
+ store.admission.enqueue({ ...route, eventId: ev.id ?? null, at });
95
+ }
96
+ return routes;
97
+ }
98
+
99
+
100
+ function trimOffers(store, harness, at, config) {
101
+ const offered = store.admission.offers(harness)
102
+ .map((row) => store.admission.get(row.id))
103
+ .filter(Boolean)
104
+ .sort((a, b) => (a.offered_at ?? 0) - (b.offered_at ?? 0)
105
+ || (a.attempt_no ?? 0) - (b.attempt_no ?? 0)
106
+ || String(a.id).localeCompare(String(b.id)));
107
+
108
+ const { active, reserved } = store.admission.slots();
109
+ const activeHarness = active.get(harness) ?? 0;
110
+ const activeGlobal = [...active.values()].reduce((n, v) => n + v, 0);
111
+ const reservedGlobal = [...reserved.values()].reduce((n, v) => n + v, 0);
112
+ const otherReserved = Math.max(0, reservedGlobal - offered.length);
113
+ const keep = Math.max(0, Math.min(
114
+ config.dispatchHarnessMax - activeHarness,
115
+ config.dispatchGlobalMax - activeGlobal - otherReserved,
116
+ offered.length,
117
+ ));
118
+ const keptOffers = offered.slice(0, keep);
119
+ for (const row of offered.slice(keep)) store.admission.requeue(row.id, at);
120
+ return { offered, keptOffers, activeHarness, activeGlobal, otherReserved };
121
+ }
122
+
123
+ export function recover(store, { harness, consumerId = null, at = Date.now(), config = store.config, mutate = false } = {}) {
124
+ if (mutate) store.admission.expire({
125
+ at,
126
+ offerMs: config.dispatchOfferMs,
127
+ baseBackoffMs: config.dispatchOfferBackoffMs,
128
+ maxBackoffMs: config.dispatchOfferMaxBackoffMs,
129
+ maxAttempts: config.dispatchOfferMaxAttempts,
130
+ });
131
+
132
+ const ownerForItem = `COALESCE(
133
+ a.consumer_id,
134
+ (SELECT aa.active_consumer_id
135
+ FROM admission_queue q
136
+ JOIN admission_attempts aa ON aa.admission_id=q.id
137
+ WHERE q.item_id=s.item_id AND q.status='active' AND q.ended_at IS NULL
138
+ ORDER BY aa.attempt_no DESC LIMIT 1)
139
+ )`;
140
+ const resume = store.db.prepare(`
141
+ SELECT s.item_id, s.assignee_agent, s.assignee_harness,
142
+ a.id AS attempt_id, a.attempt_no, a.claimed_at, a.heartbeat_at, a.expires_at,
143
+ a.lease_epoch, a.owner_instance,
144
+ ws.id AS session_id, ws.external_session_id, ws.session_key,
145
+ ${ownerForItem} AS consumer_id
146
+ FROM item_state s
147
+ LEFT JOIN attempts a ON a.item_id=s.item_id AND a.ended_at IS NULL
148
+ LEFT JOIN work_sessions ws ON ws.id=a.session_id
149
+ WHERE s.status='in_progress' AND s.deleted_at IS NULL AND s.assignee_harness=?
150
+ AND (? IS NULL OR ${ownerForItem} = ?)
151
+ ORDER BY a.claimed_at ASC, s.updated_at ASC
152
+ `).all(harness, consumerId, consumerId).map((r) => ({
153
+ task: store.task.get(r.item_id),
154
+ attemptId: r.attempt_id ?? null,
155
+ attemptNo: r.attempt_no ?? null,
156
+ sessionId: r.session_id ?? null,
157
+ sessionKey: r.session_key ?? null,
158
+ leaseEpoch: r.lease_epoch ?? 0,
159
+ ownerInstance: r.owner_instance ?? null,
160
+ leaseExpiresAt: r.expires_at ?? null,
161
+ consumerId: r.consumer_id ?? null,
162
+ needsRepair: r.attempt_id == null,
163
+ }));
164
+
165
+ let offered, keptOffers, activeHarness, activeGlobal, otherReserved;
166
+ if (mutate) {
167
+ ({ offered, keptOffers, activeHarness, activeGlobal, otherReserved } = trimOffers(store, harness, at, config));
168
+ } else {
169
+ offered = store.admission.offers(harness)
170
+ .map((row) => store.admission.get(row.id))
171
+ .filter(Boolean)
172
+ .sort((a, b) => (a.offered_at ?? 0) - (b.offered_at ?? 0)
173
+ || (a.attempt_no ?? 0) - (b.attempt_no ?? 0)
174
+ || String(a.id).localeCompare(String(b.id)));
175
+ keptOffers = offered;
176
+ const slots = store.admission.slots();
177
+ activeHarness = slots.active.get(harness) ?? 0;
178
+ activeGlobal = [...slots.active.values()].reduce((n, v) => n + v, 0);
179
+ otherReserved = Math.max(0, [...slots.reserved.values()].reduce((n, v) => n + v, 0) - offered.length);
180
+ }
181
+
182
+ const start = keptOffers
183
+ .filter((live) => !consumerId || !live.active_consumer_id || live.active_consumer_id === consumerId)
184
+ .map((live) => ({
185
+ admissionId: live.id,
186
+ itemId: live.item_id,
187
+ attemptNo: live.attempt_no ?? null,
188
+ kind: live.kind,
189
+ agent: live.agent_id,
190
+ harness: live.harness,
191
+ eventId: live.event_id ?? null,
192
+ offerExpiresAt: (live.offered_at ?? at) + config.dispatchOfferMs,
193
+ activeConsumerId: live.active_consumer_id ?? null,
194
+ leaseEpoch: live.lease_epoch ?? 0,
195
+ status: live.status,
196
+ }));
197
+
198
+ const usedHarness = activeHarness + keptOffers.length;
199
+ const usedGlobal = activeGlobal + otherReserved + keptOffers.length;
200
+ let free = Math.max(0, Math.min(
201
+ config.dispatchHarnessMax - usedHarness,
202
+ config.dispatchGlobalMax - usedGlobal,
203
+ ));
204
+ if (mutate) for (const row of store.admission.queued(harness, at)) {
205
+ if (free <= 0) break;
206
+ const next = store.admission.markOffered(row.id, at, {
207
+ pickActive: (attemptNo) => pickConsumer(store, { ...row, attempt_no: attemptNo }),
208
+ leaseMs: config.dispatchConsumerTtlMs,
209
+ });
210
+ if (!next) continue;
211
+ start.push({
212
+ admissionId: next.id,
213
+ itemId: next.item_id,
214
+ attemptNo: next.attempt_no ?? null,
215
+ kind: next.kind,
216
+ agent: next.agent_id,
217
+ harness: next.harness,
218
+ eventId: next.event_id ?? null,
219
+ offerExpiresAt: at + config.dispatchOfferMs,
220
+ activeConsumerId: next.active_consumer_id ?? null,
221
+ leaseEpoch: next.lease_epoch ?? 0,
222
+ status: "offered",
223
+ });
224
+ free--;
225
+ }
226
+
227
+ return { resume, start: consumerId ? start.filter((row) => row.activeConsumerId === consumerId) : start, free };
228
+ }
229
+
230
+ export function tick(store, { at = Date.now(), reachable = [], config = store.config } = {}) {
231
+ store.admission.expire({
232
+ at,
233
+ offerMs: config.dispatchOfferMs,
234
+ baseBackoffMs: config.dispatchOfferBackoffMs,
235
+ maxBackoffMs: config.dispatchOfferMaxBackoffMs,
236
+ maxAttempts: config.dispatchOfferMaxAttempts,
237
+ });
238
+ const offered = [];
239
+ const harnesses = [...new Set(reachable)].filter(Boolean).sort();
240
+ for (const harness of harnesses) trimOffers(store, harness, at, config);
241
+ let globalUsed = store.admission.globalSlotCount();
242
+ for (const harness of harnesses) {
243
+ let harnessUsed = store.admission.slotCount(harness);
244
+ for (const row of store.admission.queued(harness, at)) {
245
+ if (harnessUsed >= config.dispatchHarnessMax || globalUsed >= config.dispatchGlobalMax) break;
246
+ const next = store.admission.markOffered(row.id, at, {
247
+ pickActive: (attemptNo) => pickConsumer(store, { ...row, attempt_no: attemptNo }),
248
+ leaseMs: config.dispatchConsumerTtlMs,
249
+ });
250
+ if (!next) continue;
251
+ store.admission.setParentCursor(next.item_id, at);
252
+ offered.push(next);
253
+ harnessUsed++;
254
+ globalUsed++;
255
+ }
256
+ }
257
+ return offered;
258
+ }
@@ -0,0 +1,269 @@
1
+ // events-ws.js — the read-only event pipe.
2
+ // Tails the item_events ledger and broadcasts every new row; dispatch wakes
3
+ // leave over executor webhooks served by dispatch-server.js, not this socket.
4
+ //
5
+ // Wire protocol (JSON text frames):
6
+ // server → client:
7
+ // {"type":"welcome","payload":"v3","lastEventId":N}
8
+ // {"type":"history","events":[...]} backlog of envelopes, oldest-first
9
+ // {"type":"event","kind":...,"item":{...},...} one flat envelope per new row, in id order
10
+ //
11
+ // Clients track their own seen state: reconnecting replays history, so a
12
+ // missed frame costs a re-read, never a lost event. The admission queue owns
13
+ // wake delivery and retry; MCP claim remains the work-level guard. No auth
14
+ // in-process — bind localhost, or put a bearer-checked reverse proxy in front.
15
+
16
+ import http from "node:http";
17
+ import crypto from "node:crypto";
18
+ import { collectStoryArtifacts } from "./tools/index.js";
19
+ import { depsResolved } from "./deps.js";
20
+ import { HUMAN_AGENT } from "./reserved.js";
21
+
22
+ const WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
23
+ export const DEFAULT_WS_PORT = 38291;
24
+ export const HISTORY_LIMIT = 200;
25
+
26
+ function acceptKey(key) {
27
+ return crypto.createHash("sha1").update(key + WS_GUID).digest("base64");
28
+ }
29
+
30
+ // Server → client frames are never masked (RFC 6455 §5.3).
31
+ function encodeFrame(text) {
32
+ const payload = Buffer.from(text, "utf8");
33
+ const len = payload.length;
34
+ let header;
35
+ if (len < 126) {
36
+ header = Buffer.from([0x81, len]);
37
+ } else if (len < 65536) {
38
+ header = Buffer.alloc(4);
39
+ header[0] = 0x81;
40
+ header[1] = 126;
41
+ header.writeUInt16BE(len, 2);
42
+ } else {
43
+ header = Buffer.alloc(10);
44
+ header[0] = 0x81;
45
+ header[1] = 127;
46
+ header.writeBigUInt64BE(BigInt(len), 2);
47
+ }
48
+ return Buffer.concat([header, payload]);
49
+ }
50
+
51
+ export function lastEventId(store) {
52
+ return store.event.lastEventId();
53
+ }
54
+
55
+ export function eventsSince(store, id, limit = HISTORY_LIMIT) {
56
+ return store.event.since(id, limit);
57
+ }
58
+
59
+ export function eventsLatest(store, limit = HISTORY_LIMIT) {
60
+ return store.event.latest(limit);
61
+ }
62
+
63
+ // Stable kind for a stored transition. Structural inference covers task.*
64
+ // (created, claimed, progressed, completed, released, blocked, cancelled,
65
+ // updated) and gate.* (opened, resolved, dissolved); producers may store
66
+ // story.*, deps.* and release.*. A stored `kind` wins; otherwise the row maps
67
+ // by transition structure alone. Notes are free text and can change, so no
68
+ // branch here may read note content —
69
+ // a renamed note must never reclassify history.
70
+ //
71
+ // Pre-standardization rows still carry `todo` as a task status; map it with
72
+ // `ready` so the append-only history keeps the meaning it streamed with.
73
+ export function kindForEvent(row) {
74
+ if (row.kind) return row.kind;
75
+ const from = row.from_status;
76
+ const to = row.to_status;
77
+ if (from == null) return "task.created";
78
+ if ((from === "ready" || from === "todo") && to === "in_progress") return "task.claimed";
79
+ if (from === "in_progress" && to === "in_progress") return "task.progressed";
80
+ if (to === "done") return "task.completed";
81
+ if (to === "cancelled") return "task.cancelled";
82
+ if (to === "blocked") return "task.blocked";
83
+ if (to === "ready" || to === "todo") return "task.released";
84
+ return "task.updated";
85
+ }
86
+
87
+ // One envelope shape for history and live rows alike: the stored transition
88
+ // plus the task, story and epic context a subscriber would otherwise fetch
89
+ // once per row. Artifacts come from the same collector the claim handoff
90
+ // uses, so both paths agree on what "the artifacts" means.
91
+ function unblockedFor(store, row, kind) {
92
+ const terminal = row.to_status === "done" || row.to_status === "cancelled";
93
+ const claims = terminal
94
+ || kind === "task.released" || kind === "task.appended"
95
+ || kind === "deps.resolved" || kind === "gate.resolved";
96
+ if (!claims) return [];
97
+
98
+ const ids = new Set();
99
+ if (terminal) {
100
+ for (const edge of store.dep.listIncoming(row.item_id)) ids.add(edge.from_id);
101
+ } else if (row.item_id) {
102
+ ids.add(row.item_id);
103
+ }
104
+
105
+ const out = [];
106
+ for (const id of ids) {
107
+ const task = store.task.get(id);
108
+ if (!task || task.status !== "ready" || !task.assignee_agent || task.assignee_agent === HUMAN_AGENT) continue;
109
+ if (!depsResolved(store, id)) continue;
110
+ out.push({ id: task.id, assigned: task.assignee_agent, assigneeHarness: task.assignee_harness });
111
+ if (out.length === 20) break;
112
+ }
113
+ return out;
114
+ }
115
+
116
+ export function toEventMessage(store, row, { includeArtifacts = true, includeUnblocked = true } = {}) {
117
+ const kind = kindForEvent(row);
118
+ const item = !row.item_id ? null : store.item.get(row.item_id);
119
+ const itemKind = item?.kind ?? null;
120
+ const task = itemKind === "task" ? item : null;
121
+ const story = itemKind === "story" ? item : task?.story_id ? store.story.get(task.story_id) : null;
122
+ const epic = itemKind === "epic" ? item : story?.epic_id ? store.epic.get(story.epic_id) : item?.epic_id ? store.epic.get(item.epic_id) : null;
123
+ const actorSession = row.session_id ? store.session.get(row.session_id) : null;
124
+ return {
125
+ type: "event",
126
+ kind,
127
+ id: row.id,
128
+ at: row.created_at,
129
+ fromStatus: row.from_status ?? null,
130
+ toStatus: row.to_status,
131
+ // Normalised item: a dispatcher routes assignment and review wakes without
132
+ // knowing which level the row is about.
133
+ item: item
134
+ ? {
135
+ id: item.id,
136
+ kind: itemKind,
137
+ title: item.title,
138
+ status: item.status,
139
+ assigned: item.assignee_agent ?? null,
140
+ assigneeHarness: item.assignee_harness ?? null,
141
+ createdBy: item.created_by ?? null,
142
+ }
143
+ : null,
144
+ epicId: epic?.id ?? null,
145
+ epicCreatedBy: epic?.created_by ?? null,
146
+ epicAssigneeHarness: epic?.assignee_harness ?? null,
147
+ storyId: story?.id ?? null,
148
+ storyAssigned: story?.assignee_agent ?? null,
149
+ storyAssigneeHarness: story?.assignee_harness ?? null,
150
+ // Work a transition just made claimable: a dispatcher wakes these without
151
+ // recomputing the dependency graph. Creation and direct assignment already
152
+ // route their own item, so only a close looks at incoming edges.
153
+ unblocked: includeUnblocked ? unblockedFor(store, row, kind) : [],
154
+ task: task
155
+ ? {
156
+ id: task.id,
157
+ title: task.title,
158
+ story: story ? story.title : null,
159
+ epic: epic ? epic.title : null,
160
+ acceptance: story ? story.acceptance : null,
161
+ artifacts: includeArtifacts && story ? collectStoryArtifacts(store, story.id) : [],
162
+ assignee: task.assignee_agent,
163
+ }
164
+ : null,
165
+ actor: row.actor,
166
+ actorHarness: actorSession?.harness ?? null,
167
+ note: row.note,
168
+ };
169
+ }
170
+
171
+ export function startEventServer({ store, port = null, host = "127.0.0.1", intervalMs = null, historyLimit = null, logger } = {}) {
172
+ const cfg = store.config ?? {};
173
+ const listenPort = port ?? cfg.wsPort ?? DEFAULT_WS_PORT;
174
+ const pollMs = intervalMs ?? cfg.wsIntervalMs ?? 1000;
175
+ const histLimit = historyLimit ?? cfg.wsHistoryLimit ?? HISTORY_LIMIT;
176
+ const clients = new Map();
177
+ let closing = false;
178
+ let cursor = lastEventId(store);
179
+
180
+ function send(socket, obj) {
181
+ if (socket.destroyed || !socket.writable) return false;
182
+ try {
183
+ socket.write(encodeFrame(JSON.stringify(obj)));
184
+ return true;
185
+ } catch {
186
+ return false;
187
+ }
188
+ }
189
+
190
+ function broadcast(obj) {
191
+ const frame = encodeFrame(JSON.stringify(obj));
192
+ for (const client of [...clients.values()]) {
193
+ const sock = client.socket;
194
+ if (sock.destroyed || !sock.writable) {
195
+ clients.delete(sock);
196
+ continue;
197
+ }
198
+ sock.write(frame);
199
+ }
200
+ }
201
+
202
+ const server = http.createServer((req, res) => {
203
+ res.writeHead(404, { "content-type": "application/json" });
204
+ res.end(JSON.stringify({ error: "not found" }));
205
+ });
206
+
207
+ server.on("upgrade", (req, socket) => {
208
+ const key = req.headers["sec-websocket-key"];
209
+ if ((req.headers.upgrade || "").toLowerCase() !== "websocket" || !key) {
210
+ socket.destroy();
211
+ return;
212
+ }
213
+ socket.write(
214
+ "HTTP/1.1 101 Switching Protocols\r\n" +
215
+ "Upgrade: websocket\r\n" +
216
+ "Connection: Upgrade\r\n" +
217
+ `Sec-WebSocket-Accept: ${acceptKey(key)}\r\n\r\n`
218
+ );
219
+ const client = { socket, connectedAt: Date.now() };
220
+ clients.set(socket, client);
221
+ logger?.info?.(`winch: ws subscriber connected (${clients.size} total)`);
222
+ try {
223
+ send(socket, { type: "welcome", payload: "v3", lastEventId: cursor });
224
+ send(socket, { type: "history", events: eventsLatest(store, histLimit).map((row) => toEventMessage(store, row)) });
225
+ } catch {
226
+ clients.delete(socket);
227
+ }
228
+
229
+ const drop = () => {
230
+ clients.delete(socket);
231
+ if (closing) return;
232
+ };
233
+ socket.on("close", drop);
234
+ socket.on("error", drop);
235
+ });
236
+
237
+ const timer = setInterval(() => {
238
+ try {
239
+ const rows = eventsSince(store, cursor, histLimit);
240
+ if (rows.length) {
241
+ cursor = rows[rows.length - 1].id;
242
+ for (const row of rows) {
243
+ broadcast(toEventMessage(store, row));
244
+ }
245
+ }
246
+ } catch (err) {
247
+ logger?.warn?.(`winch: event poll failed: ${err?.message ?? err}`);
248
+ }
249
+ }, pollMs);
250
+ if (typeof timer.unref === "function") timer.unref();
251
+
252
+ return new Promise((resolve, reject) => {
253
+ server.once("error", reject);
254
+ server.listen(listenPort, host, () => {
255
+ resolve({
256
+ port: server.address().port,
257
+ host,
258
+ clients: () => clients.size,
259
+ close: () =>
260
+ new Promise((res) => {
261
+ closing = true;
262
+ clearInterval(timer);
263
+ for (const client of clients.values()) client.socket.destroy();
264
+ server.close(() => res());
265
+ }),
266
+ });
267
+ });
268
+ });
269
+ }
@@ -0,0 +1,140 @@
1
+ // identity.js — harness declared, agent and session stamped per call.
2
+ //
3
+ // One thing is declared, two things arrive with the work. The server is
4
+ // CONSTRUCTED with the harness it serves (each MCP entry names its own
5
+ // consumer); the agent and session of each call
6
+ // are the calling harness's job to stamp — via the before_tool_call
7
+ // companion plugin — exactly the way lineage attributes per-call cost to an
8
+ // agent and a session instead of a configured default.
9
+ //
10
+ // Nothing here defaults, ever: an unnamed harness refuses construction, and
11
+ // an unstamped call refuses execution. A key that cannot say which harness
12
+ // and which of its calls it belongs to would poison claims.
13
+
14
+ import { isReservedLayer } from "./reserved.js";
15
+
16
+ // A usable layer names something: non-empty, and neither of the two tokens
17
+ // no key may carry ("unknown", "instance:*"). Assignment sentinels are
18
+ // reserved targets, so a caller can never mint a key from one either.
19
+ function isUsableLayer(layer, v) {
20
+ return (
21
+ typeof v === "string" &&
22
+ v.trim() !== "" &&
23
+ !/^(unknown|instance:.*)$/i.test(v.trim()) &&
24
+ !isReservedLayer(layer, v)
25
+ );
26
+ }
27
+
28
+ /** Throw unless the triple is usable. `who` names the entry point —
29
+ * declaration (construction), resolved identity (per request), caller
30
+ * identity (direct tool entry), session key (the mint itself). */
31
+ export function assertCleanTriple(id, who = "identity") {
32
+ const bad = ["harness", "agent", "session"].filter((k) => !isUsableLayer(k, id?.[k]));
33
+ if (bad.length > 0) {
34
+ throw new Error(`winch: refused ${who} (bad layers: ${bad.join(", ")}). Provide real harness/agent/session values.`);
35
+ }
36
+ return { harness: id.harness.trim(), agent: id.agent.trim(), session: id.session.trim() };
37
+ }
38
+
39
+ /** Declaration = a usable harness, plus the usage line constructors hit.
40
+ * Missing and reserved refuse differently on purpose: the first tells the
41
+ * operator what to add, the second that the value itself can never identify.
42
+ * Both are the same predicate — no separate reserved-token code path. */
43
+ export function assertDeclaration(base) {
44
+ const h = typeof base?.harness === "string" ? base.harness.trim() : "";
45
+ if (h === "") {
46
+ throw new Error(
47
+ "winch: identity declaration incomplete (missing: harness). " +
48
+ "Declare the consumer at construction — CLI: WINCH_HARNESS env " +
49
+ "(stdio) / X-Winch-Harness header (HTTP); " +
50
+ "embedders: startMcpServer({ base: { harness } }). " +
51
+ "Agent and session are never declared: they arrive per call."
52
+ );
53
+ }
54
+ if (/^(unknown|instance:.*)$/i.test(h) || isReservedLayer("harness", h)) {
55
+ throw new Error(
56
+ `winch: refused declaration (reserved: harness). ` +
57
+ `"${h}" cannot identify a consumer — declare the real harness name.`
58
+ );
59
+ }
60
+ return { harness: h };
61
+ }
62
+
63
+ /** Build a declaration from environment variables (the CLI path). */
64
+ export function declaredFromEnv(env = process.env) {
65
+ return assertDeclaration({ harness: env.WINCH_HARNESS });
66
+ }
67
+
68
+ /**
69
+ * Per-request identity: the declared harness, plus the agent and session the
70
+ * calling harness stamped on this call. Three trusted channels, in order:
71
+ * `_meta.winch` (a companion with request-params access, e.g. openclaw),
72
+ * `args._meta.winch` (a companion whose output lands inside arguments —
73
+ * same twin, different dispatch shape), `winch_agent`/`winch_session` args
74
+ * (a companion limited to flat args mutation, e.g. opencode — sound only
75
+ * over stdio, where the spawner is the sole peer). The first wholly-usable
76
+ * pair wins; halves never splice across channels. Anything else refuses —
77
+ * the hook layer owns stamping, not config, and unidentified callers are
78
+ * never given keys.
79
+ */
80
+ export function resolveIdentity({ meta, args, base }) {
81
+ const declared = assertDeclaration(base);
82
+ const m = meta?.winch ?? meta ?? null;
83
+ const am = args?._meta?.winch ?? null;
84
+ const usable = (layer, v) => (isUsableLayer(layer, v) ? String(v).trim() : null);
85
+ const mAgent = usable("agent", m?.agent), mSession = usable("session", m?.session);
86
+ const amAgent = usable("agent", am?.agent), amSession = usable("session", am?.session);
87
+ const aAgent = usable("agent", args?.winch_agent), aSession = usable("session", args?.winch_session);
88
+ const mConsumer = usable("consumer", m?.consumer), amConsumer = usable("consumer", am?.consumer);
89
+ const aConsumer = usable("consumer", args?.winch_consumer);
90
+ const mInstance = usable("instance", m?.instance), amInstance = usable("instance", am?.instance);
91
+ const aInstance = usable("instance", args?.winch_instance);
92
+ // Whole pairs only: a meta half never splices with an args half, so no
93
+ // call can assemble an identity across trust channels.
94
+ const pair = (mAgent && mSession)
95
+ ? { agent: mAgent, session: mSession, source: "meta" }
96
+ : (amAgent && amSession)
97
+ ? { agent: amAgent, session: amSession, source: "args-meta" }
98
+ : (aAgent && aSession)
99
+ ? { agent: aAgent, session: aSession, source: "args" }
100
+ : null;
101
+ if (!pair) {
102
+ if ((mAgent || amAgent || aAgent) && (mSession || amSession || aSession)) {
103
+ throw new Error(
104
+ "winch: refused caller identity (halves in different channels — pairs never splice). " +
105
+ "Stamp a whole agent+session in one channel: _meta.winch or winch_agent/winch_session args."
106
+ );
107
+ }
108
+ const bad = [];
109
+ if (!mAgent && !amAgent && !aAgent) bad.push("agent");
110
+ if (!mSession && !amSession && !aSession) bad.push("session");
111
+ throw new Error(
112
+ `winch: refused caller identity (unresolved ${bad.join(" and ")}). ` +
113
+ "The calling harness must stamp agent and session on each call — " +
114
+ "via _meta.winch where reachable, else stamped winch_agent/winch_session args. " +
115
+ "Unidentified callers fail; they are never given default keys."
116
+ );
117
+ }
118
+ const consumer = pair.source === "meta" ? mConsumer
119
+ : pair.source === "args-meta" ? amConsumer
120
+ : aConsumer;
121
+ const instance = pair.source === "meta" ? mInstance
122
+ : pair.source === "args-meta" ? amInstance
123
+ : aInstance;
124
+ return {
125
+ harness: declared.harness,
126
+ agent: pair.agent,
127
+ session: pair.session,
128
+ consumer: consumer ?? null,
129
+ instance: instance ?? null,
130
+ source: { harness: "declared", agent: pair.source, session: pair.source },
131
+ };
132
+ }
133
+
134
+ // Claim key: one slot per harness×agent×session triple. The mint
135
+ // point is guarded too, so a key the constructor and resolver both missed
136
+ // still fails here — nowhere mints a poisoned key.
137
+ export function identitySessionKey(id) {
138
+ const clean = assertCleanTriple(id, "session key");
139
+ return `${clean.harness}:${clean.agent}:${clean.session}`;
140
+ }
package/src/ids.js ADDED
@@ -0,0 +1,18 @@
1
+ import { randomBytes } from "node:crypto";
2
+
3
+ const ALPHABET = "abcdefghijkmnopqrstuvwxyz23456789";
4
+
5
+ function suffix(len = 8) {
6
+ const bytes = randomBytes(len);
7
+ let out = "";
8
+ for (let i = 0; i < len; i++) out += ALPHABET[bytes[i] % ALPHABET.length];
9
+ return out;
10
+ }
11
+
12
+ // Item ids are opaque: they carry no rank or kind. `items.kind` is the only
13
+ // discriminator; nothing in winch may parse a prefix.
14
+ export function newItemId() { return `ITM-${suffix()}`; }
15
+ export function newAttemptId() { return `ATT-${suffix()}`; }
16
+ export function newSessionId() { return `SES-${suffix()}`; }
17
+ export function newArtifactId() { return `ART-${suffix()}`; }
18
+ export function newAdmissionId() { return `ADM-${suffix()}`; }