@igorjpimenta/winch 2026.11.22-beta.2 → 2026.11.23-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.migrations/0013_webhook_delivery_tables.sql +2 -0
- package/.migrations/meta/0013_snapshot.json +1900 -0
- package/.migrations/meta/_journal.json +8 -1
- package/README.md +27 -43
- package/package.json +1 -1
- package/plugins/README.md +4 -4
- package/plugins/opencode/winch/index.js +111 -17
- package/src/cli.js +5 -16
- package/src/config.js +3 -7
- package/src/schema.js +3 -3
- package/src/store/delivery.js +16 -16
- package/src/store/events.js +1 -1
- package/src/store/index.js +2 -2
- package/src/tools/assign.js +1 -1
- package/src/tools/definitions.js +0 -1
- package/src/watcher.js +3 -13
- package/src/{dispatch.js → webhook/core.js} +4 -12
- package/src/{dispatch-webhook.js → webhook/delivery.js} +2 -2
- package/src/webhook/envelope.js +131 -0
- package/src/{dispatch-server.js → webhook/server.js} +8 -12
- package/src/events-ws.js +0 -269
|
@@ -92,6 +92,13 @@
|
|
|
92
92
|
"when": 1795056387292,
|
|
93
93
|
"tag": "0012_dispatch_fencing_audit",
|
|
94
94
|
"breakpoints": true
|
|
95
|
+
},
|
|
96
|
+
{
|
|
97
|
+
"idx": 13,
|
|
98
|
+
"version": "6",
|
|
99
|
+
"when": 1795440999481,
|
|
100
|
+
"tag": "0013_webhook_delivery_tables",
|
|
101
|
+
"breakpoints": true
|
|
95
102
|
}
|
|
96
103
|
]
|
|
97
|
-
}
|
|
104
|
+
}
|
package/README.md
CHANGED
|
@@ -4,9 +4,9 @@
|
|
|
4
4
|
|
|
5
5
|
Winch is a pull-based delivery backlog - epic to story to task with a dependency
|
|
6
6
|
DAG - served as an MCP server. The spec lives in the records: a planner writes
|
|
7
|
-
it once, a worker reads it, claims atomically, and reports back.
|
|
8
|
-
|
|
9
|
-
polling it.
|
|
7
|
+
it once, a worker reads it, claims atomically, and reports back. Webhook wakes
|
|
8
|
+
fan every work-making transition out to consumers, so a harness wakes agents
|
|
9
|
+
from the queue instead of polling it.
|
|
10
10
|
|
|
11
11
|
Winch is harness-agnostic: the server contains no harness-specific code. The
|
|
12
12
|
adapters under `plugins/` are optional and installed per harness; the MCP
|
|
@@ -15,7 +15,7 @@ contract itself is the only integration surface.
|
|
|
15
15
|
- **Spec in the records** - goal, acceptance criteria, dependencies, capabilities all written once by the planner.
|
|
16
16
|
- **Atomic claim** - CAS under a lease; highest-priority ready task selected when no id is given.
|
|
17
17
|
- **Dependency DAG** - forward-only deps, cycle-checked, cancelled deps count as resolved.
|
|
18
|
-
- **
|
|
18
|
+
- **Webhook wakes** - every work-making transition fans out to consumer webhooks; subscribers wake agents, no polling.
|
|
19
19
|
- **Human gates** - block/resume with gate types; one resume per gate, actor-checked.
|
|
20
20
|
- **Content-addressed evidence** - artifacts recorded on close, carried into downstream handoffs.
|
|
21
21
|
|
|
@@ -57,7 +57,7 @@ Inside your harness agent:
|
|
|
57
57
|
Verify from the operator side - no transcript reading:
|
|
58
58
|
|
|
59
59
|
$ winch next # task gone from the ready queue
|
|
60
|
-
$ winch serve
|
|
60
|
+
$ winch webhook serve # watch the wake pump light up
|
|
61
61
|
|
|
62
62
|
All MCP tools and their contracts are defined in `src/tools/` - or just list
|
|
63
63
|
them from the running server.
|
|
@@ -69,9 +69,6 @@ them from the running server.
|
|
|
69
69
|
- The **MCP server** exposes the whole backlog as tools over stdio (one pipe per
|
|
70
70
|
harness) or streamable HTTP (one shared daemon). Identity is stamped at the
|
|
71
71
|
transport edge.
|
|
72
|
-
- The **Event stream** (`winch serve --ws`) is a read-only feed of backlog
|
|
73
|
-
events; its frame protocol is in [WebSocket event
|
|
74
|
-
stream](docs/websocket.md).
|
|
75
72
|
- The **Dispatch server** (`winch webhook serve`) accepts executor
|
|
76
73
|
registration and recovery, pumps `admission_queue`, and fans wakes out to
|
|
77
74
|
consumer webhooks. Tasks accept with MCP `backlog_claim`; planner wakes accept
|
|
@@ -106,8 +103,7 @@ stamping automatically. Full contract, per-dimension table and adapter setup:
|
|
|
106
103
|
|
|
107
104
|
## Dispatch
|
|
108
105
|
|
|
109
|
-
`winch webhook serve` hosts the HTTP dispatch endpoints and the wake pump
|
|
110
|
-
`winch serve --ws` hosts only the read-only event stream. The dispatch server
|
|
106
|
+
`winch webhook serve` hosts the HTTP dispatch endpoints and the wake pump. It
|
|
111
107
|
is the single scheduler:
|
|
112
108
|
|
|
113
109
|
- It routes work-making transitions: `task.created`, `task.assigned`,
|
|
@@ -145,8 +141,8 @@ notify; a non-loopback bind refuses without it. See
|
|
|
145
141
|
`POST /dispatch/recover` returns assigned `in_progress` work with its
|
|
146
142
|
`attemptId`, `leaseEpoch`, and `ownerInstance`, so a restarted harness resumes
|
|
147
143
|
that attempt instead of re-claiming it. The winner is recorded on the work
|
|
148
|
-
attempt;
|
|
149
|
-
|
|
144
|
+
attempt; only that consumer gets the resume, and a claim that never named a
|
|
145
|
+
consumer is not fanned out. Standby consumers do
|
|
150
146
|
not resume the same attempt. Its first call is `backlog_update` with the
|
|
151
147
|
returned `attemptId` and `leaseEpoch`; a stale attempt or epoch gets
|
|
152
148
|
`stale_claim`. Expired leases return work to `ready` through the normal sweep.
|
|
@@ -292,7 +288,6 @@ Claim leases, attempt caps, and gate rules: [lifecycle](docs/lifecycle.md).
|
|
|
292
288
|
| Configure ports, bearer, store, webhooks | [Configuration](docs/configuration.md) |
|
|
293
289
|
| Understand claim/lease/gate rules | [Lifecycle](docs/lifecycle.md) |
|
|
294
290
|
| Webhook subscriptions, dispatch routing, recovery and CLI | [Webhooks](docs/webhooks.md) |
|
|
295
|
-
| Event stream frame protocol and retention | [WebSocket event stream](docs/websocket.md) |
|
|
296
291
|
| Run it on a host persistently | [Docker](docs/docker.md) |
|
|
297
292
|
| Publish a release | [Releases](docs/releases.md) |
|
|
298
293
|
|
|
@@ -313,7 +308,6 @@ Claim leases, attempt caps, and gate rules: [lifecycle](docs/lifecycle.md).
|
|
|
313
308
|
| `webhook deliveries [--status S] [--admission ID] [--consumer ID] [--limit N]` | inspect the per-consumer delivery ledger; `--status dead` lists dead letters |
|
|
314
309
|
| `webhook revoke [--topic T] --id I` | remove a webhook subscription |
|
|
315
310
|
| `webhook test [--topic T] [--harness H] [--id I]` | POST a ping to webhook subscriptions |
|
|
316
|
-
| `serve --ws --port N [--host H]` | stream store events over WebSocket |
|
|
317
311
|
| `webhook serve [--port N] [--host H]` | serve dispatch registration, recovery and the wake pump |
|
|
318
312
|
|
|
319
313
|
## Deploy (any server)
|
|
@@ -341,20 +335,13 @@ any VPS, compose host or cluster with one replica (SQLite has one writer).
|
|
|
341
335
|
remains the one-shot tick for hosts that do not run the dispatch service.
|
|
342
336
|
Claims still self-heal on the next tick when the DB lives elsewhere.
|
|
343
337
|
|
|
344
|
-
##
|
|
338
|
+
## Event envelopes
|
|
345
339
|
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
`{"type":"history","events":[...]}` (newest 200), then
|
|
352
|
-
- `{"type":"event","kind":"task.completed","id":N,"at":T,"item":{id,kind,
|
|
353
|
-
title,status,assigned},"task":{id,title,story,epic,acceptance,artifacts,
|
|
354
|
-
assignee},"actor":"...","note":"..."}` per insert, in id order.
|
|
355
|
-
- Dispatch wakes are not frames on this stream and run in a separate
|
|
356
|
-
`winch webhook serve` process; see [Webhooks](docs/webhooks.md) and
|
|
357
|
-
[WebSocket event stream](docs/websocket.md).
|
|
340
|
+
Every stored transition becomes one envelope (`src/webhook/envelope.js`): the stored
|
|
341
|
+
transition plus the task, story and epic context a subscriber would otherwise
|
|
342
|
+
fetch once per row. Webhook wakes are the main event driver — the dispatch
|
|
343
|
+
server projects these envelopes into wake payloads; see
|
|
344
|
+
[Webhooks](docs/webhooks.md).
|
|
358
345
|
|
|
359
346
|
Kinds are declared by their producer at write time and stored on the row's
|
|
360
347
|
`kind` column. Structural inference covers `task.*` and `gate.*`; producers
|
|
@@ -363,25 +350,22 @@ asserts a tag exists: merge-detect tags first and writes nothing on tag
|
|
|
363
350
|
failure. The emitter feeds the stored kind straight through; otherwise a row
|
|
364
351
|
maps by transition structure alone. Notes never classify anything: they are
|
|
365
352
|
free text and can change, so pre-kind rows keep exactly the meanings they
|
|
366
|
-
|
|
367
|
-
The structural mapping lives in `src/
|
|
353
|
+
were recorded with - an append-only log keeps its history.
|
|
354
|
+
The structural mapping lives in `src/webhook/envelope.js`; stored producer kinds pass
|
|
368
355
|
through unchanged. History and live rows share one envelope shape.
|
|
369
356
|
|
|
370
|
-
Delivery-dynamics notes the
|
|
371
|
-
lease (only silence gets swept); an unmerged close dissolves its gate
|
|
372
|
-
approvals answer `gate_dissolved`); starvation lives in the watcher
|
|
373
|
-
(`deferred` list
|
|
374
|
-
a new ticket linked by dep edge with a `supersedes: ITM-x` note,
|
|
375
|
-
rewrite of history.
|
|
357
|
+
Delivery-dynamics notes the envelopes will not tell you: heartbeats renew the
|
|
358
|
+
claim lease (only silence gets swept); an unmerged close dissolves its gate
|
|
359
|
+
(late approvals answer `gate_dissolved`); starvation lives in the watcher
|
|
360
|
+
manifest (`deferred` list), not the envelopes; a disputed
|
|
361
|
+
completion is a new ticket linked by dep edge with a `supersedes: ITM-x` note,
|
|
362
|
+
never a rewrite of history.
|
|
376
363
|
|
|
377
|
-
Rows carry their stored `kind
|
|
378
|
-
`task
|
|
364
|
+
Rows carry their stored `kind`, the normalized `item` block, and the task-context
|
|
365
|
+
block (`task` with story/epic/acceptance/artifacts) the claim handoff also uses.
|
|
379
366
|
|
|
380
367
|
The server never interprets a row - a gate opening is just another event, and
|
|
381
|
-
reminders, digests and dashboards are subscriber code.
|
|
382
|
-
history, so a missed frame costs a re-read, never a lost event. No auth in
|
|
383
|
-
process: keep the loopback bind, or put a bearer-checked reverse proxy in
|
|
384
|
-
front. Plain HTTP hits get 404.
|
|
368
|
+
reminders, digests and dashboards are subscriber code.
|
|
385
369
|
|
|
386
370
|
## Store
|
|
387
371
|
|
|
@@ -392,7 +376,7 @@ Schema lives in `src/schema.js` as Drizzle tables. The schema is one recursive
|
|
|
392
376
|
`items` tree (`kind` = epic/story/task, `parent_id` for nesting), with
|
|
393
377
|
`item_state`, `item_tags`, `item_edges`, `attempts`, `work_sessions`,
|
|
394
378
|
`artifacts`, `item_events`, `admission_queue`, `admission_attempts`,
|
|
395
|
-
`dispatch_events`, `
|
|
379
|
+
`dispatch_events`, `webhook_deliveries`, `webhook_delivery_attempts` and
|
|
396
380
|
`webhooks`. Item ids are opaque; `kind`
|
|
397
381
|
is the discriminator, never an id prefix. `npm run db:generate`
|
|
398
382
|
turns schema changes into SQL in `.migrations/`; `src/db.js` applies pending
|
|
@@ -434,7 +418,7 @@ refuse as likely typos, unknown meta keys are ignored for forward compat.
|
|
|
434
418
|
| Claim lease | `WINCH_LEASE_SECONDS` | 1800 (30 min) |
|
|
435
419
|
| Sweeper max attempts | `WINCH_MAX_ATTEMPTS` | 3 |
|
|
436
420
|
| Gate-wait thresholds | `WINCH_GATE_WAIT_LEVELS` (`"24h,72h"`, `ms|s|m|h|d` suffixes) | 24h / 72h |
|
|
437
|
-
|
|
|
421
|
+
| Event history limit (dispatch boot catch-up batch) | `WINCH_EVENT_HISTORY_LIMIT` | 200 |
|
|
438
422
|
| Dispatch port / poll / lease sweep | `WINCH_DISPATCH_PORT` / `WINCH_DISPATCH_INTERVAL_MS` / `WINCH_DISPATCH_SWEEP_MS` | 38293 / 1000 / 30000 ms |
|
|
439
423
|
| Dispatch caps per harness / global | `WINCH_DISPATCH_HARNESS_MAX` / `WINCH_DISPATCH_GLOBAL_MAX` | 8 / 16 |
|
|
440
424
|
| Dispatch consumer heartbeat TTL | `WINCH_DISPATCH_CONSUMER_TTL_MS` | 90000 ms |
|
package/package.json
CHANGED
package/plugins/README.md
CHANGED
|
@@ -135,8 +135,8 @@ execution lease is the guard for wakes with no claim.
|
|
|
135
135
|
The core query is `POST /dispatch/recover`; it returns assigned `in_progress`
|
|
136
136
|
work with `attemptId`, `leaseEpoch`, `ownerInstance`, `sessionId`, `sessionKey`
|
|
137
137
|
and lease expiry. The winning claim records its consumer on the work attempt,
|
|
138
|
-
so only that consumer gets the resume
|
|
139
|
-
|
|
138
|
+
so only that consumer gets the resume; a claim that never named a consumer is
|
|
139
|
+
not fanned out to any of them.
|
|
140
140
|
The plugin dedupes by task id and resumes the same attempt. Its first action is
|
|
141
141
|
`backlog_update` with the returned `attemptId` and `leaseEpoch`; a stale attempt
|
|
142
142
|
or epoch gets `stale_claim`, and only an expired lease returns the item to
|
|
@@ -205,7 +205,7 @@ so nobody but the adapter can write the identity args.
|
|
|
205
205
|
|
|
206
206
|
### Remote (HTTP) — loopback with a bearer
|
|
207
207
|
|
|
208
|
-
A persistent server (`winch serve --mcp http --port
|
|
208
|
+
A persistent server (`winch serve --mcp http --port 38292`) avoids per-call
|
|
209
209
|
spawns. Read the bearer from a `0600` file, not from the environment:
|
|
210
210
|
|
|
211
211
|
```jsonc
|
|
@@ -213,7 +213,7 @@ spawns. Read the bearer from a `0600` file, not from the environment:
|
|
|
213
213
|
"mcp": {
|
|
214
214
|
"winch": {
|
|
215
215
|
"type": "remote",
|
|
216
|
-
"url": "http://127.0.0.1:
|
|
216
|
+
"url": "http://127.0.0.1:38292/mcp",
|
|
217
217
|
"headers": {
|
|
218
218
|
"Authorization": "Bearer {file:~/.secrets/winch-bearer}",
|
|
219
219
|
"X-Winch-Harness": "opencode"
|
|
@@ -1,24 +1,109 @@
|
|
|
1
1
|
import { createWinchHooks } from "./hooks.js";
|
|
2
2
|
import { stampWinchEvent } from "./identity.js";
|
|
3
3
|
import { startDispatch, DEFAULT_DISPATCH_URL } from "./dispatch.js";
|
|
4
|
-
import { spawn } from "node:child_process";
|
|
5
|
-
import {
|
|
4
|
+
import { spawn, execFileSync } from "node:child_process";
|
|
5
|
+
import { mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
6
|
+
import os, { hostname } from "node:os";
|
|
7
|
+
import path from "node:path";
|
|
6
8
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
9
|
+
// A wake child is orphaned only when the process that spawned it is gone. A
|
|
10
|
+
// child whose owner is still running is doing real work, so it must not be
|
|
11
|
+
// reaped. The sweep therefore kills nothing except leftovers from a dead owner.
|
|
12
|
+
const SWEEP_MS = 60 * 1000;
|
|
13
|
+
|
|
14
|
+
function wakeStateDir() {
|
|
15
|
+
return path.join(os.homedir(), ".opencode", "state", "winch-wakes");
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function pidAlive(pid) {
|
|
19
|
+
try { process.kill(pid, 0); return true; }
|
|
20
|
+
catch (err) { return err?.code === "EPERM"; }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function processCommand(pid) {
|
|
24
|
+
try {
|
|
25
|
+
return execFileSync("ps", ["-o", "command=", "-p", String(pid)], { encoding: "utf8" }).trim();
|
|
26
|
+
} catch {
|
|
27
|
+
return "";
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function createWakeRunner({ logger = console, stateDir = wakeStateDir() } = {}) {
|
|
32
|
+
// Detached children lead their own process group; kill the group so a
|
|
33
|
+
// reaped turn's tool and MCP subprocesses go with it.
|
|
34
|
+
const reap = (pid) => {
|
|
35
|
+
try { process.kill(-pid, "SIGKILL"); }
|
|
36
|
+
catch { try { process.kill(pid, "SIGKILL"); } catch {} }
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const recordPath = (ownerPid, childPid) => path.join(stateDir, `wake-${ownerPid}-${childPid}.json`);
|
|
40
|
+
|
|
41
|
+
const wake = ({ agent, message }) =>
|
|
42
|
+
new Promise((resolve, reject) => {
|
|
43
|
+
const bin = process.env.OPENCODE_BIN || "opencode";
|
|
44
|
+
const child = spawn(bin, ["run", "--agent", agent, message], {
|
|
45
|
+
detached: true,
|
|
46
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
47
|
+
// A wake child loads the same config and would start its own dispatch
|
|
48
|
+
// listener, registering as another executor; then every wake fans out
|
|
49
|
+
// into more waking agents. Keep dispatch to the root instance only.
|
|
50
|
+
env: { ...process.env, WINCH_DISPATCH_ENABLED: "0" },
|
|
51
|
+
});
|
|
52
|
+
const file = child.pid ? recordPath(process.pid, child.pid) : null;
|
|
53
|
+
if (file) {
|
|
54
|
+
try {
|
|
55
|
+
mkdirSync(stateDir, { recursive: true });
|
|
56
|
+
writeFileSync(file, JSON.stringify({ pid: child.pid, ownerPid: process.pid, agent, message }));
|
|
57
|
+
} catch (err) {
|
|
58
|
+
logger?.warn?.(`winch: wake record not written: ${err?.message ?? err}`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const forget = () => { try { if (file) unlinkSync(file); } catch {} };
|
|
62
|
+
let stderr = "";
|
|
63
|
+
child.stderr?.on("data", (d) => { stderr = (stderr + d.toString()).slice(-2000); });
|
|
64
|
+
child.on("error", (err) => { forget(); reject(err); });
|
|
65
|
+
child.on("exit", (code) => {
|
|
66
|
+
forget();
|
|
67
|
+
code === 0 ? resolve() : reject(new Error(`exit ${code}${stderr ? `: ${stderr.trim().split("\n").slice(-2).join(" | ")}` : ""}`));
|
|
68
|
+
});
|
|
69
|
+
// Unref: an agent run must not hold its caller's event loop open, or a
|
|
70
|
+
// daemon could not shut down while a wake is in flight. A caller that
|
|
71
|
+
// awaits wake() must therefore keep its own handle alive — the exit
|
|
72
|
+
// event will not dispatch on an otherwise empty loop.
|
|
73
|
+
child.unref();
|
|
13
74
|
});
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
75
|
+
|
|
76
|
+
// Kill wake children whose spawning owner is no longer alive. Called at
|
|
77
|
+
// dispatch startup and on a sweep timer; never on close, because a child
|
|
78
|
+
// still owned by a live instance is not an orphan.
|
|
79
|
+
function reapOrphans() {
|
|
80
|
+
let names = [];
|
|
81
|
+
try { names = readdirSync(stateDir); } catch { return 0; }
|
|
82
|
+
let killed = 0;
|
|
83
|
+
for (const name of names) {
|
|
84
|
+
if (!name.startsWith("wake-") || !name.endsWith(".json")) continue;
|
|
85
|
+
const file = path.join(stateDir, name);
|
|
86
|
+
let entry;
|
|
87
|
+
try { entry = JSON.parse(readFileSync(file, "utf8")); }
|
|
88
|
+
catch { try { unlinkSync(file); } catch {} continue; }
|
|
89
|
+
if (!entry?.pid || !entry?.ownerPid) { try { unlinkSync(file); } catch {} continue; }
|
|
90
|
+
if (pidAlive(entry.ownerPid)) continue; // owner alive: not an orphan
|
|
91
|
+
if (pidAlive(entry.pid)) {
|
|
92
|
+
// Guard PID reuse: only kill a process still running this wake's
|
|
93
|
+
// command, never whatever now occupies the recycled pid.
|
|
94
|
+
const cmd = processCommand(entry.pid);
|
|
95
|
+
if (cmd.includes("--agent") && entry.message && cmd.includes(entry.message)) {
|
|
96
|
+
reap(entry.pid);
|
|
97
|
+
killed += 1;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
try { unlinkSync(file); } catch {}
|
|
101
|
+
}
|
|
102
|
+
if (killed) logger?.warn?.(`winch: reaped ${killed} orphaned wake(s)`);
|
|
103
|
+
return killed;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return { wake, reapOrphans };
|
|
22
107
|
}
|
|
23
108
|
|
|
24
109
|
function consumerIdFor(harness, cfg = {}) {
|
|
@@ -26,6 +111,9 @@ function consumerIdFor(harness, cfg = {}) {
|
|
|
26
111
|
}
|
|
27
112
|
|
|
28
113
|
function start({ cfg = {}, harness, logger }) {
|
|
114
|
+
const runner = createWakeRunner({ logger, stateDir: cfg.wakeStateDir });
|
|
115
|
+
runner.reapOrphans();
|
|
116
|
+
|
|
29
117
|
const executorId = cfg.winchExecutorId ?? process.env.WINCH_EXECUTOR_ID;
|
|
30
118
|
const consumerId = consumerIdFor(harness, cfg);
|
|
31
119
|
const bearer = process.env.WINCH_WEBHOOK_BEARER;
|
|
@@ -39,12 +127,18 @@ function start({ cfg = {}, harness, logger }) {
|
|
|
39
127
|
consumerId,
|
|
40
128
|
executorId,
|
|
41
129
|
bearer,
|
|
42
|
-
wake:
|
|
130
|
+
wake: runner.wake,
|
|
43
131
|
port: Number(cfg.dispatchPort ?? process.env.WINCH_DISPATCH_PORT ?? 0),
|
|
44
132
|
reconcileMs: Number(cfg.dispatchReconcileMs ?? process.env.WINCH_DISPATCH_RECONCILE_MS ?? 30000),
|
|
45
133
|
logger,
|
|
46
134
|
});
|
|
47
135
|
dispatch.ready.catch((err) => logger?.warn?.(`winch: dispatch listener failed: ${err?.message ?? err}`));
|
|
136
|
+
|
|
137
|
+
const sweep = setInterval(() => runner.reapOrphans(), Number(cfg.wakeSweepMs ?? SWEEP_MS));
|
|
138
|
+
sweep.unref?.();
|
|
139
|
+
const close = dispatch.close.bind(dispatch);
|
|
140
|
+
dispatch.close = async () => { clearInterval(sweep); await close(); };
|
|
141
|
+
dispatch.reapOrphans = runner.reapOrphans;
|
|
48
142
|
return dispatch;
|
|
49
143
|
}
|
|
50
144
|
|
package/src/cli.js
CHANGED
|
@@ -12,8 +12,7 @@ import { tick } from "./watcher.js";
|
|
|
12
12
|
import { shipRelease } from "./release.js";
|
|
13
13
|
import { collectPRs, applyMergeOutcomes } from "./merges.js";
|
|
14
14
|
import { startMcpServer } from "./mcp.js";
|
|
15
|
-
import {
|
|
16
|
-
import { startDispatchServer } from "./dispatch-server.js";
|
|
15
|
+
import { startDispatchServer } from "./webhook/server.js";
|
|
17
16
|
import { declaredFromEnv } from "./identity.js";
|
|
18
17
|
import { resolveDbPath } from "./paths.js";
|
|
19
18
|
|
|
@@ -46,7 +45,6 @@ const USAGE = `usage: winch <command>
|
|
|
46
45
|
serve --mcp stdio|http [--port N] [--host H]
|
|
47
46
|
serve the backlog tools over MCP stdio or Streamable HTTP
|
|
48
47
|
(stdio harness from WINCH_HARNESS env only; agent+session stamped per call)
|
|
49
|
-
serve --ws --port N [--host H] stream store events over WebSocket
|
|
50
48
|
watch one watcher tick (JSON manifest on stdout)
|
|
51
49
|
resume <taskId> [--actor <name>] resolve a human gate: blocked → ready
|
|
52
50
|
next list the current ready queue
|
|
@@ -179,27 +177,20 @@ export async function runCli(argv) {
|
|
|
179
177
|
({ values } = parseArgs({
|
|
180
178
|
args: rest,
|
|
181
179
|
options: {
|
|
182
|
-
ws: { type: "boolean" },
|
|
183
180
|
mcp: { type: "string" },
|
|
184
181
|
port: { type: "string" },
|
|
185
182
|
host: { type: "string" },
|
|
186
183
|
config: { type: "string" },
|
|
187
184
|
},
|
|
188
185
|
}));
|
|
189
|
-
} catch
|
|
190
|
-
|
|
191
|
-
// on the legacy `mcp --harness` surface: stdio harness is env-only.
|
|
192
|
-
if (/Unknown option|ERR_PARSE_ARGS_UNKNOWN_OPTION/.test(String(err?.message ?? err))) {
|
|
193
|
-
fail("winch serve --mcp takes no --harness flag: set WINCH_HARNESS in the environment.");
|
|
194
|
-
}
|
|
195
|
-
throw err;
|
|
186
|
+
} catch {
|
|
187
|
+
fail("usage: winch serve --mcp stdio|http [--port N] [--host H] [--config JSON|PATH]");
|
|
196
188
|
}
|
|
197
189
|
if (values.mcp !== undefined && values.mcp !== "stdio" && values.mcp !== "http") {
|
|
198
190
|
fail(`winch: --mcp must be stdio or http, got ${JSON.stringify(values.mcp)}`);
|
|
199
191
|
}
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
fail("usage: winch serve (--ws | --mcp stdio|http) [--port N] [--host H] [--config JSON|PATH]");
|
|
192
|
+
if (values.mcp === undefined) {
|
|
193
|
+
fail("usage: winch serve --mcp stdio|http [--port N] [--host H] [--config JSON|PATH]");
|
|
203
194
|
}
|
|
204
195
|
const store = openStore(loadConfig(values));
|
|
205
196
|
const logger = {
|
|
@@ -238,8 +229,6 @@ export async function runCli(argv) {
|
|
|
238
229
|
}
|
|
239
230
|
return;
|
|
240
231
|
}
|
|
241
|
-
await startEventServer({ store, port, host, logger });
|
|
242
|
-
logger.info(`winch: events on ws://${host}:${port ?? store.config.wsPort} (append-only; subscribers track their own state)`);
|
|
243
232
|
return;
|
|
244
233
|
}
|
|
245
234
|
|
package/src/config.js
CHANGED
|
@@ -46,10 +46,8 @@ const SPEC = {
|
|
|
46
46
|
leaseSeconds: { env: "WINCH_LEASE_SECONDS", parse: parseInt, check: (v) => v > 0 },
|
|
47
47
|
maxAttempts: { env: "WINCH_MAX_ATTEMPTS", parse: parseInt, check: (v) => v > 0 },
|
|
48
48
|
gateWaitLevels: { env: "WINCH_GATE_WAIT_LEVELS", parse: parseGateWaitLevels, check: (v) => v !== null },
|
|
49
|
-
wsPort: { env: "WINCH_WS_PORT", parse: parseInt, check: (v) => v >= 1 && v <= 65535 },
|
|
50
49
|
mcpHttpPort: { env: "WINCH_MCP_HTTP_PORT", parse: parseInt, check: (v) => v >= 1 && v <= 65535 },
|
|
51
|
-
|
|
52
|
-
wsIntervalMs: { env: "WINCH_WS_INTERVAL_MS", parse: parseInt, check: (v) => v > 0 },
|
|
50
|
+
eventHistoryLimit: { env: "WINCH_EVENT_HISTORY_LIMIT", parse: parseInt, check: (v) => v > 0 },
|
|
53
51
|
dispatchPort: { env: "WINCH_DISPATCH_PORT", parse: parseInt, check: (v) => v >= 1 && v <= 65535 },
|
|
54
52
|
dispatchIntervalMs: { env: "WINCH_DISPATCH_INTERVAL_MS", parse: parseInt, check: (v) => v > 0 },
|
|
55
53
|
dispatchSweepMs: { env: "WINCH_DISPATCH_SWEEP_MS", parse: parseInt, check: (v) => v > 0 },
|
|
@@ -82,10 +80,8 @@ export const CONFIG_DEFAULTS = {
|
|
|
82
80
|
leaseSeconds: 1800,
|
|
83
81
|
maxAttempts: 3,
|
|
84
82
|
gateWaitLevels: "24h,72h",
|
|
85
|
-
wsPort: 38291,
|
|
86
83
|
mcpHttpPort: 38292,
|
|
87
|
-
|
|
88
|
-
wsIntervalMs: 1000,
|
|
84
|
+
eventHistoryLimit: 200,
|
|
89
85
|
dispatchPort: 38293,
|
|
90
86
|
dispatchIntervalMs: 1000,
|
|
91
87
|
dispatchSweepMs: 30000,
|
|
@@ -126,7 +122,7 @@ function parseKey(key, raw, what) {
|
|
|
126
122
|
const spec = SPEC[key];
|
|
127
123
|
const parsed = spec.parse(raw);
|
|
128
124
|
if (parsed === null || !spec.check(parsed)) {
|
|
129
|
-
refused(what, key, `Expected ${key === "gateWaitLevels" ? "a duration list like \"24h,72h\"" :
|
|
125
|
+
refused(what, key, `Expected ${key === "gateWaitLevels" ? "a duration list like \"24h,72h\"" : "a positive integer"} — got ${JSON.stringify(raw) ?? "nothing"}.`);
|
|
130
126
|
}
|
|
131
127
|
return parsed;
|
|
132
128
|
}
|
package/src/schema.js
CHANGED
|
@@ -266,7 +266,7 @@ export const dispatchEvents = sqliteTable("dispatch_events", {
|
|
|
266
266
|
index("idx_dispatch_events_created").on(table.createdAt),
|
|
267
267
|
]);
|
|
268
268
|
|
|
269
|
-
export const
|
|
269
|
+
export const webhookDeliveries = sqliteTable("webhook_deliveries", {
|
|
270
270
|
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
271
271
|
admissionId: text("admission_id").notNull().references(() => admissionQueue.id, { onDelete: "cascade" }),
|
|
272
272
|
attemptNo: integer("attempt_no").notNull(),
|
|
@@ -289,9 +289,9 @@ export const dispatchDeliveries = sqliteTable("dispatch_deliveries", {
|
|
|
289
289
|
index("idx_delivery_event").on(table.eventId, table.consumerId),
|
|
290
290
|
]);
|
|
291
291
|
|
|
292
|
-
export const
|
|
292
|
+
export const webhookDeliveryAttempts = sqliteTable("webhook_delivery_attempts", {
|
|
293
293
|
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
294
|
-
deliveryId: integer("delivery_id").notNull().references(() =>
|
|
294
|
+
deliveryId: integer("delivery_id").notNull().references(() => webhookDeliveries.id, { onDelete: "cascade" }),
|
|
295
295
|
attemptNo: integer("attempt_no").notNull(),
|
|
296
296
|
status: text("status").notNull(),
|
|
297
297
|
responseStatus: integer("response_status"),
|
package/src/store/delivery.js
CHANGED
|
@@ -6,20 +6,20 @@ export function createDeliveryApi({ core }) {
|
|
|
6
6
|
const { db, now } = core;
|
|
7
7
|
|
|
8
8
|
function rowById(id) {
|
|
9
|
-
return db.prepare("SELECT * FROM
|
|
9
|
+
return db.prepare("SELECT * FROM webhook_deliveries WHERE id=?").get(id) ?? null;
|
|
10
10
|
}
|
|
11
11
|
|
|
12
12
|
const api = {
|
|
13
13
|
ensure({ admissionId, attemptNo, consumerId, eventId = null, at = now() }) {
|
|
14
14
|
db.prepare(`
|
|
15
|
-
INSERT INTO
|
|
15
|
+
INSERT INTO webhook_deliveries(admission_id, attempt_no, event_id, consumer_id, status, attempts,
|
|
16
16
|
next_at, created_at, updated_at)
|
|
17
17
|
VALUES (?, ?, ?, ?, 'pending', 0, ?, ?, ?)
|
|
18
18
|
ON CONFLICT(admission_id, attempt_no, consumer_id) DO UPDATE SET
|
|
19
|
-
event_id=COALESCE(
|
|
19
|
+
event_id=COALESCE(webhook_deliveries.event_id, excluded.event_id)
|
|
20
20
|
`).run(admissionId, attemptNo, eventId, consumerId, at, at, at);
|
|
21
21
|
return db.prepare(`
|
|
22
|
-
SELECT * FROM
|
|
22
|
+
SELECT * FROM webhook_deliveries
|
|
23
23
|
WHERE admission_id=? AND attempt_no=? AND consumer_id=?
|
|
24
24
|
`).get(admissionId, attemptNo, consumerId) ?? null;
|
|
25
25
|
},
|
|
@@ -32,7 +32,7 @@ export function createDeliveryApi({ core }) {
|
|
|
32
32
|
if (consumerId != null) { where.push("consumer_id=?"); args.push(consumerId); }
|
|
33
33
|
if (status != null) { where.push("status=?"); args.push(status); }
|
|
34
34
|
if (dueAt != null) { where.push("next_at<=?"); args.push(dueAt); }
|
|
35
|
-
const sql = `SELECT * FROM
|
|
35
|
+
const sql = `SELECT * FROM webhook_deliveries${where.length ? ` WHERE ${where.join(" AND ")}` : ""}
|
|
36
36
|
ORDER BY next_at ASC, id ASC${limit ? " LIMIT ?" : ""}`;
|
|
37
37
|
return limit ? db.prepare(sql).all(...args, limit) : db.prepare(sql).all(...args);
|
|
38
38
|
},
|
|
@@ -44,30 +44,30 @@ export function createDeliveryApi({ core }) {
|
|
|
44
44
|
claimDue({ at = now(), limit = 50, admissionId = null } = {}) {
|
|
45
45
|
const rows = admissionId
|
|
46
46
|
? db.prepare(`
|
|
47
|
-
SELECT * FROM
|
|
47
|
+
SELECT * FROM webhook_deliveries
|
|
48
48
|
WHERE status='pending' AND next_at<=? AND admission_id=?
|
|
49
49
|
ORDER BY next_at ASC, id ASC LIMIT ?
|
|
50
50
|
`).all(at, admissionId, limit)
|
|
51
51
|
: db.prepare(`
|
|
52
|
-
SELECT * FROM
|
|
52
|
+
SELECT * FROM webhook_deliveries
|
|
53
53
|
WHERE status='pending' AND next_at<=?
|
|
54
54
|
ORDER BY next_at ASC, id ASC LIMIT ?
|
|
55
55
|
`).all(at, limit);
|
|
56
|
-
const mark = db.prepare("UPDATE
|
|
56
|
+
const mark = db.prepare("UPDATE webhook_deliveries SET status='delivering', updated_at=? WHERE id=? AND status='pending'");
|
|
57
57
|
return rows.filter((row) => mark.run(at, row.id).changes > 0)
|
|
58
58
|
.map((row) => ({ ...row, status: "delivering", updated_at: at }));
|
|
59
59
|
},
|
|
60
60
|
|
|
61
61
|
releaseStale({ before, at = now() } = {}) {
|
|
62
62
|
return db.prepare(`
|
|
63
|
-
UPDATE
|
|
63
|
+
UPDATE webhook_deliveries SET status='pending', next_at=?, updated_at=?
|
|
64
64
|
WHERE status='delivering' AND updated_at < ?
|
|
65
65
|
`).run(at, at, before).changes;
|
|
66
66
|
},
|
|
67
67
|
|
|
68
68
|
recordAttempt({ deliveryId, attemptNo, status, responseStatus = null, error = null, at = now() }) {
|
|
69
69
|
db.prepare(`
|
|
70
|
-
INSERT INTO
|
|
70
|
+
INSERT INTO webhook_delivery_attempts(delivery_id, attempt_no, status, response_status, error, created_at)
|
|
71
71
|
VALUES (?, ?, ?, ?, ?, ?)
|
|
72
72
|
`).run(deliveryId, attemptNo, status, responseStatus, error == null ? null : String(error), at);
|
|
73
73
|
},
|
|
@@ -84,7 +84,7 @@ export function createDeliveryApi({ core }) {
|
|
|
84
84
|
|
|
85
85
|
markDelivered(id, { status = 202, at = now() } = {}) {
|
|
86
86
|
db.prepare(`
|
|
87
|
-
UPDATE
|
|
87
|
+
UPDATE webhook_deliveries
|
|
88
88
|
SET status='delivered', attempts=attempts+1, last_status=?, last_error=NULL,
|
|
89
89
|
delivered_at=?, updated_at=?
|
|
90
90
|
WHERE id=?
|
|
@@ -94,7 +94,7 @@ export function createDeliveryApi({ core }) {
|
|
|
94
94
|
|
|
95
95
|
markRetry(id, { status = null, error = null, nextAt, at = now() } = {}) {
|
|
96
96
|
db.prepare(`
|
|
97
|
-
UPDATE
|
|
97
|
+
UPDATE webhook_deliveries
|
|
98
98
|
SET status='pending', attempts=attempts+1, last_status=?, last_error=?,
|
|
99
99
|
next_at=?, updated_at=?
|
|
100
100
|
WHERE id=?
|
|
@@ -104,7 +104,7 @@ export function createDeliveryApi({ core }) {
|
|
|
104
104
|
|
|
105
105
|
markDead(id, { status = null, error = null, at = now() } = {}) {
|
|
106
106
|
db.prepare(`
|
|
107
|
-
UPDATE
|
|
107
|
+
UPDATE webhook_deliveries
|
|
108
108
|
SET status='dead', attempts=attempts+1, last_status=?, last_error=?,
|
|
109
109
|
dead_at=?, updated_at=?
|
|
110
110
|
WHERE id=?
|
|
@@ -114,7 +114,7 @@ export function createDeliveryApi({ core }) {
|
|
|
114
114
|
|
|
115
115
|
cancelForAttempt(admissionId, attemptNo, { at = now() } = {}) {
|
|
116
116
|
db.prepare(`
|
|
117
|
-
UPDATE
|
|
117
|
+
UPDATE webhook_deliveries
|
|
118
118
|
SET status='cancelled', updated_at=?
|
|
119
119
|
WHERE admission_id=? AND attempt_no=? AND status IN ('pending','delivering')
|
|
120
120
|
`).run(at, admissionId, attemptNo);
|
|
@@ -122,12 +122,12 @@ export function createDeliveryApi({ core }) {
|
|
|
122
122
|
|
|
123
123
|
resetForConsumer(admissionId, attemptNo, consumerId, { at = now() } = {}) {
|
|
124
124
|
db.prepare(`
|
|
125
|
-
UPDATE
|
|
125
|
+
UPDATE webhook_deliveries
|
|
126
126
|
SET status='pending', next_at=?, delivered_at=NULL, dead_at=NULL, updated_at=?
|
|
127
127
|
WHERE admission_id=? AND attempt_no=? AND consumer_id=?
|
|
128
128
|
`).run(at, at, admissionId, attemptNo, consumerId);
|
|
129
129
|
return db.prepare(`
|
|
130
|
-
SELECT * FROM
|
|
130
|
+
SELECT * FROM webhook_deliveries
|
|
131
131
|
WHERE admission_id=? AND attempt_no=? AND consumer_id=?
|
|
132
132
|
`).get(admissionId, attemptNo, consumerId) ?? null;
|
|
133
133
|
},
|
package/src/store/events.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Public event read API. Writers use core.appendEvent; this surface is the
|
|
2
|
-
// cursor/history readers used by the
|
|
2
|
+
// cursor/history readers used by the wake envelope (webhook/envelope.js) and tools.
|
|
3
3
|
|
|
4
4
|
export function createEventApi({ core }) {
|
|
5
5
|
const { db, appendEvent, eventById, eventsFor } = core;
|
package/src/store/index.js
CHANGED
|
@@ -36,8 +36,8 @@ import { createEventApi } from "./events.js";
|
|
|
36
36
|
import { createAdmissionApi } from "./admission.js";
|
|
37
37
|
import { createDeliveryApi } from "./delivery.js";
|
|
38
38
|
import { createDispatchEventApi } from "./dispatch-events.js";
|
|
39
|
-
import { observe } from "../
|
|
40
|
-
import { toEventMessage } from "../
|
|
39
|
+
import { observe } from "../webhook/core.js";
|
|
40
|
+
import { toEventMessage } from "../webhook/envelope.js";
|
|
41
41
|
|
|
42
42
|
export { MAX_ATTEMPTS };
|
|
43
43
|
export { EPIC_STATUSES, STORY_STATUSES, TASK_STATUSES, EXECUTION_KINDS, ITEM_KINDS };
|
package/src/tools/assign.js
CHANGED
|
@@ -10,7 +10,7 @@ export function createAssignTools({ store, logger }) {
|
|
|
10
10
|
return {
|
|
11
11
|
async backlog_assign(args, identity, cfg) {
|
|
12
12
|
const qualified = `${identity.harness}:${identity.agent}`;
|
|
13
|
-
const target = args?.id
|
|
13
|
+
const target = args?.id;
|
|
14
14
|
const kind = target ? store.itemKindOf(target) : null;
|
|
15
15
|
if (!kind) return err(`backlog_assign: not found: ${target}`, "not_found", { id: target ?? null });
|
|
16
16
|
|
package/src/tools/definitions.js
CHANGED
|
@@ -41,7 +41,6 @@ export const TOOL_DEFS = [
|
|
|
41
41
|
additionalProperties: false,
|
|
42
42
|
properties: {
|
|
43
43
|
id: { type: "string", description: "Item id (opaque) for a task or a story." },
|
|
44
|
-
taskId: { type: "string", description: "Deprecated alias for `id` when assigning a task." },
|
|
45
44
|
agent: { type: ["string", "null"], description: "Target agent id, or null/\"\" to unassign." },
|
|
46
45
|
capabilities: {
|
|
47
46
|
type: "array",
|