@igorjpimenta/winch 2026.11.22-beta.3 → 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 +2 -2
- 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
|
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",
|
package/src/watcher.js
CHANGED
|
@@ -21,14 +21,13 @@ import { readyTasks } from "./ready-queue.js";
|
|
|
21
21
|
export const MAX_ACTIVE_PER_AGENT = 2;
|
|
22
22
|
|
|
23
23
|
/**
|
|
24
|
-
* @returns {{ts:number, swept:string[], resolved:string[], waits:object[], routed:object[], human:object[], deferred:object[],
|
|
24
|
+
* @returns {{ts:number, swept:string[], resolved:string[], waits:object[], routed:object[], human:object[], deferred:object[], blocked:object[], gates:object[]}}
|
|
25
25
|
* swept — lease-expired tasks the sweep requeued or escalated this tick
|
|
26
26
|
* resolved — dependency-wait tasks returned to ready this tick
|
|
27
27
|
* waits — gate-waiting rows written this tick (24h/72h age thresholds, one per gate per level)
|
|
28
28
|
* routed — claimable AND assigned AND assignee under the active cap: the cron wakes `assigned`
|
|
29
29
|
* human — claimable human work: ready for a person, never woken through an agent harness
|
|
30
30
|
* deferred — claimable AND assigned BUT assignee at MAX_ACTIVE: never woken (starvation metric)
|
|
31
|
-
* unrouted — always empty while ready requires an assignment; kept for manifest compatibility
|
|
32
31
|
*/
|
|
33
32
|
export function tick(store, { config: override = null } = {}) {
|
|
34
33
|
const cfg = override ?? store.config;
|
|
@@ -52,8 +51,8 @@ export function tick(store, { config: override = null } = {}) {
|
|
|
52
51
|
.slice(0, cfg.blockedLimit)
|
|
53
52
|
.map((t) => ({ id: t.id, title: t.title, assigned: t.assignee_agent, gate_type: t.gate_type, blocked_at: t.blocked_at }));
|
|
54
53
|
// Gated tasks are separated from plain blocks for visibility. Who should
|
|
55
|
-
// be told about them is a subscriber decision —
|
|
56
|
-
//
|
|
54
|
+
// be told about them is a subscriber decision — event envelopes carry every
|
|
55
|
+
// row, and webhook subscribers track their own seen state.
|
|
57
56
|
const gates = store.item
|
|
58
57
|
.list({ kind: "task", status: "blocked" })
|
|
59
58
|
.filter((t) => t.gate_type)
|
|
@@ -71,14 +70,6 @@ export function tick(store, { config: override = null } = {}) {
|
|
|
71
70
|
const deferred = claimable
|
|
72
71
|
.filter((c) => c.assigned && c.assigned !== HUMAN_AGENT && (active.get(c.assigned) ?? 0) >= cfg.maxActivePerAgent)
|
|
73
72
|
.map((c) => ({ ...c, activeCount: active.get(c.assigned) }));
|
|
74
|
-
const unrouted = claimable
|
|
75
|
-
.filter((c) => !c.assigned)
|
|
76
|
-
// Waiting-age gauge: the wire streams transitions, never waiting, so the
|
|
77
|
-
// manifest carries how long each unrouted task has sat idle instead.
|
|
78
|
-
.map((c) => {
|
|
79
|
-
const row = store.task.get(c.taskId);
|
|
80
|
-
return { ...c, idleMs: row ? nowTs - (row.updated_at ?? nowTs) : 0 };
|
|
81
|
-
});
|
|
82
73
|
|
|
83
74
|
return {
|
|
84
75
|
ts: nowTs,
|
|
@@ -88,7 +79,6 @@ export function tick(store, { config: override = null } = {}) {
|
|
|
88
79
|
routed,
|
|
89
80
|
human,
|
|
90
81
|
deferred,
|
|
91
|
-
unrouted,
|
|
92
82
|
blocked,
|
|
93
83
|
gates,
|
|
94
84
|
};
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
// under per-harness and global caps. The harness accepts an offer; only the
|
|
3
3
|
// winner starts a session. Item status remains the work acknowledgement.
|
|
4
4
|
|
|
5
|
-
import { HUMAN_AGENT, HUMAN_HARNESS } from "
|
|
6
|
-
import { pickConsumer } from "./
|
|
5
|
+
import { HUMAN_AGENT, HUMAN_HARNESS } from "../reserved.js";
|
|
6
|
+
import { pickConsumer } from "./delivery.js";
|
|
7
7
|
|
|
8
8
|
const RELEASING_STATUSES = new Set(["done", "cancelled", "blocked", "backlog", "review"]);
|
|
9
9
|
|
|
@@ -129,25 +129,17 @@ export function recover(store, { harness, consumerId = null, at = Date.now(), co
|
|
|
129
129
|
maxAttempts: config.dispatchOfferMaxAttempts,
|
|
130
130
|
});
|
|
131
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
132
|
const resume = store.db.prepare(`
|
|
141
133
|
SELECT s.item_id, s.assignee_agent, s.assignee_harness,
|
|
142
134
|
a.id AS attempt_id, a.attempt_no, a.claimed_at, a.heartbeat_at, a.expires_at,
|
|
143
135
|
a.lease_epoch, a.owner_instance,
|
|
144
136
|
ws.id AS session_id, ws.external_session_id, ws.session_key,
|
|
145
|
-
|
|
137
|
+
a.consumer_id AS consumer_id
|
|
146
138
|
FROM item_state s
|
|
147
139
|
LEFT JOIN attempts a ON a.item_id=s.item_id AND a.ended_at IS NULL
|
|
148
140
|
LEFT JOIN work_sessions ws ON ws.id=a.session_id
|
|
149
141
|
WHERE s.status='in_progress' AND s.deleted_at IS NULL AND s.assignee_harness=?
|
|
150
|
-
AND (? IS NULL OR
|
|
142
|
+
AND (? IS NULL OR a.consumer_id = ?)
|
|
151
143
|
ORDER BY a.claimed_at ASC, s.updated_at ASC
|
|
152
144
|
`).all(harness, consumerId, consumerId).map((r) => ({
|
|
153
145
|
task: store.task.get(r.item_id),
|
|
@@ -197,9 +197,9 @@ export async function deliverDue(store, { config = store.config, logger = null,
|
|
|
197
197
|
FROM admission_queue q
|
|
198
198
|
JOIN admission_attempts aa ON aa.admission_id=q.id AND aa.ended_at IS NULL
|
|
199
199
|
WHERE q.status IN ('offered','accepted') AND q.ended_at IS NULL
|
|
200
|
-
AND EXISTS (SELECT 1 FROM
|
|
200
|
+
AND EXISTS (SELECT 1 FROM webhook_deliveries d
|
|
201
201
|
WHERE d.admission_id=q.id AND d.attempt_no=aa.attempt_no)
|
|
202
|
-
AND NOT EXISTS (SELECT 1 FROM
|
|
202
|
+
AND NOT EXISTS (SELECT 1 FROM webhook_deliveries d
|
|
203
203
|
WHERE d.admission_id=q.id AND d.attempt_no=aa.attempt_no
|
|
204
204
|
AND d.status != 'dead')
|
|
205
205
|
`).all();
|