@igorjpimenta/winch 2026.11.23-beta.3 → 2026.11.25-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.
@@ -106,6 +106,13 @@
106
106
  "when": 1795442379791,
107
107
  "tag": "0014_usage_events",
108
108
  "breakpoints": true
109
+ },
110
+ {
111
+ "idx": 15,
112
+ "version": "6",
113
+ "when": 1795538678619,
114
+ "tag": "0015_moaning_captain_cross",
115
+ "breakpoints": true
109
116
  }
110
117
  ]
111
- }
118
+ }
package/README.md CHANGED
@@ -123,12 +123,36 @@ is the single scheduler:
123
123
  subscription; transient failures retry until the failure threshold or attempt
124
124
  cap. A heartbeat does not erase that state.
125
125
  - Caps are per harness (`WINCH_DISPATCH_HARNESS_MAX`) and global
126
- (`WINCH_DISPATCH_GLOBAL_MAX`). The server listens on
126
+ (`WINCH_DISPATCH_GLOBAL_MAX`). A consumer's running wake children are capped
127
+ by `WINCH_DISPATCH_WAKE_MAX`: a delivery counts as running until the receiver
128
+ settles it, so an offer re-offered while its child is alive cannot stack a
129
+ second process. The server listens on
127
130
  `WINCH_DISPATCH_PORT` (default 38293, localhost-only unless `--host` says
128
131
  otherwise). Status changes enqueue their wake in the same SQLite transaction
129
132
  and ring `/dispatch/notify` on `WINCH_DISPATCH_URL`; the interval pump is
130
133
  recovery, not routing.
131
134
 
135
+ **Prerequisite: one subscription per harness, before anything can wake.**
136
+ The pump only offers queued admissions to harnesses present in the
137
+ `webhooks` table, so assigning with no matching subscription succeeds but
138
+ never delivers — the admissions sit `queued` with no attempts while the
139
+ dispatch server looks healthy. `backlog_plan` reports this as
140
+ `warning: { code: "no_route" }` when no subscription is registered at all,
141
+ and `backlog_assign` reports it per harness. Register the receiver first:
142
+
143
+ ```sh
144
+ winch webhook bearer # prints a receiver token, store it for the receiver
145
+ winch webhook register --topic dispatch --harness <harness> \
146
+ --url <receiver-url> --bearer <token>
147
+ ```
148
+
149
+ Manual rows are never swept; `winch webhook revoke --topic dispatch --id <id>`
150
+ removes one. Harness plugins register themselves instead (below), but only if
151
+ `WINCH_DISPATCH_URL` matches the port `winch webhook serve` is actually
152
+ listening on — the default is `38293`, and a `serve --port 38493` with
153
+ `WINCH_DISPATCH_URL` still on `38293` leaves `webhooks` empty while both
154
+ processes run.
155
+
132
156
  Adapters register one route per `WINCH_CONSUMER_ID` (default
133
157
  `harness:hostname`), with `WINCH_EXECUTOR_ID` as the live instance and a
134
158
  `WINCH_WEBHOOK_BEARER` generated by `winch webhook bearer`. Registration is a
@@ -376,8 +400,7 @@ through unchanged. History and live rows share one envelope shape.
376
400
 
377
401
  Delivery-dynamics notes the envelopes will not tell you: heartbeats renew the
378
402
  claim lease (only silence gets swept); an unmerged close dissolves its gate
379
- (late approvals answer `gate_dissolved`); starvation lives in the watcher
380
- manifest (`deferred` list), not the envelopes; a disputed
403
+ (late approvals answer `gate_dissolved`); a disputed
381
404
  completion is a new ticket linked by dep edge with a `supersedes: ITM-x` note,
382
405
  never a rewrite of history.
383
406
 
@@ -441,6 +464,7 @@ refuse as likely typos, unknown meta keys are ignored for forward compat.
441
464
  | Event history limit (dispatch boot catch-up batch) | `WINCH_EVENT_HISTORY_LIMIT` | 200 |
442
465
  | Dispatch port / poll / lease sweep | `WINCH_DISPATCH_PORT` / `WINCH_DISPATCH_INTERVAL_MS` / `WINCH_DISPATCH_SWEEP_MS` | 38293 / 1000 / 30000 ms |
443
466
  | Dispatch caps per harness / global | `WINCH_DISPATCH_HARNESS_MAX` / `WINCH_DISPATCH_GLOBAL_MAX` | 8 / 16 |
467
+ | Running wake children per consumer | `WINCH_DISPATCH_WAKE_MAX` | 8 |
444
468
  | Dispatch consumer heartbeat TTL | `WINCH_DISPATCH_CONSUMER_TTL_MS` | 90000 ms |
445
469
  | Offer TTL / backoff / attempts | `WINCH_DISPATCH_OFFER_MS` / `WINCH_DISPATCH_OFFER_BACKOFF_MS` / `WINCH_DISPATCH_OFFER_MAX_BACKOFF_MS` / `WINCH_DISPATCH_OFFER_MAX_ATTEMPTS` | 120000 / 30000 / 300000 ms / 5 |
446
470
  | Delivery backoff / max / attempts / failure threshold / claim lease | `WINCH_DISPATCH_DELIVERY_BACKOFF_MS` / `WINCH_DISPATCH_DELIVERY_MAX_BACKOFF_MS` / `WINCH_DISPATCH_DELIVERY_MAX_ATTEMPTS` / `WINCH_DISPATCH_DELIVERY_FAILURE_THRESHOLD` / `WINCH_DISPATCH_DELIVERY_LEASE_MS` | 30000 / 300000 ms / 5 / 4 / 300000 ms |
@@ -448,7 +472,6 @@ refuse as likely typos, unknown meta keys are ignored for forward compat.
448
472
  | Dispatch management auth | `WINCH_DISPATCH_TOKEN` | unset (loopback) |
449
473
  | MCP HTTP port | `WINCH_MCP_HTTP_PORT` | 38292 |
450
474
  | DB path | `WINCH_DB` | `~/.winch/store.sqlite` |
451
- | Wake routing cap | `WINCH_MAX_ACTIVE_PER_AGENT` | 2 |
452
475
  | Scan limits (tick / candidates / blocked list) | `WINCH_SCAN_LIMIT` / `WINCH_CANDIDATES` / `WINCH_BLOCKED_LIMIT` | 50 / 5 / 20 |
453
476
  | Dep cycle-check cap | `WINCH_DFS_NODES` | 500 nodes |
454
477
  | Note caps (progress / result / reason / artifact) | `WINCH_NOTE_{PROGRESS,RESULT,REASON,ARTIFACT}_LIMIT` | 2000 / 4000 / 1000 / 500 |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@igorjpimenta/winch",
3
- "version": "2026.11.23-beta.3",
3
+ "version": "2026.11.25-beta.1",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -182,6 +182,40 @@ export function resumePrompt(row) {
182
182
  return `Resume ${taskId} attempt ${attemptId} leaseEpoch ${leaseEpoch}. You already own this task. Do not call backlog_claim. Call backlog_update with taskId "${taskId}", attemptId "${attemptId}", leaseEpoch ${leaseEpoch}, heartbeat true. If it returns stale_claim, stop. Then continue from the existing brief.`;
183
183
  }
184
184
 
185
+ // Core owns the wake window (delivered-but-unsettled children, capped by
186
+ // WINCH_DISPATCH_WAKE_MAX). This guard is the fail-safe for the pump/recover
187
+ // race: one live child per admission or session key, and every exit settles
188
+ // the admission so core can release the next wake.
189
+ export function createWakeGuard(wake, { settle = null } = {}) {
190
+ const keyFor = (payload) =>
191
+ payload?.admissionId ? `start:${payload.admissionId}`
192
+ : payload?.sessionKey ? `resume:${payload.sessionKey}`
193
+ : null;
194
+ const inflight = new Set();
195
+ return (payload) => {
196
+ const key = keyFor(payload);
197
+ if (key && inflight.has(key)) return Promise.resolve({ deduped: true });
198
+ if (key) inflight.add(key);
199
+ return Promise.resolve()
200
+ .then(() => wake(payload))
201
+ .finally(() => {
202
+ if (key) inflight.delete(key);
203
+ if (payload?.admissionId) settle?.(payload.admissionId);
204
+ });
205
+ };
206
+ }
207
+
208
+ export function postSettle({ baseUrl, admissionId, consumerId = null, bearer = null, logger = null, timeoutMs = 3000 }) {
209
+ const headers = { "content-type": "application/json" };
210
+ if (bearer) headers.authorization = `Bearer ${bearer}`;
211
+ return fetch(`${String(baseUrl).replace(/\/+$/, "")}/dispatch/notify`, {
212
+ method: "POST",
213
+ headers,
214
+ body: JSON.stringify({ type: "settle", admissionId, consumerId }),
215
+ signal: AbortSignal.timeout(timeoutMs),
216
+ }).catch((err) => logger?.warn?.(`winch: settle ${admissionId} failed: ${err?.message ?? err}`));
217
+ }
218
+
185
219
  export function startDispatch({ api, cfg = {}, harness = cfg.winchHarness ?? process.env.WINCH_HARNESS ?? "openclaw", wake, logger = console }) {
186
220
  if (cfg.dispatchEnabled === false) return null;
187
221
  const executorId = cfg.winchExecutorId ?? process.env.WINCH_EXECUTOR_ID;
@@ -194,8 +228,11 @@ export function startDispatch({ api, cfg = {}, harness = cfg.winchHarness ?? pro
194
228
  const baseUrl = process.env.WINCH_DISPATCH_URL ?? DEFAULT_DISPATCH_URL;
195
229
  const publicBaseUrl = cfg.dispatchPublicBaseUrl ?? process.env.WINCH_DISPATCH_PUBLIC_BASE_URL ?? "http://127.0.0.1:18789";
196
230
  const started = new Map();
231
+ const gatedWake = createWakeGuard(wake, {
232
+ settle: (admissionId) => void postSettle({ baseUrl, admissionId, consumerId, bearer, logger }),
233
+ });
197
234
 
198
- registerReceiver({ api, bearer, wake, started, logger });
235
+ registerReceiver({ api, bearer, wake: gatedWake, started, logger });
199
236
 
200
237
  let fresh = true;
201
238
  const run = async () => {
@@ -215,7 +252,7 @@ export function startDispatch({ api, cfg = {}, harness = cfg.winchHarness ?? pro
215
252
  return;
216
253
  }
217
254
  try {
218
- await recoverOnce({ baseUrl, harness, consumerId, executorId, wake, started, logger });
255
+ await recoverOnce({ baseUrl, harness, consumerId, executorId, wake: gatedWake, started, logger });
219
256
  } catch (err) {
220
257
  logger?.warn?.(`winch: dispatch recover failed: ${err?.message ?? err}`);
221
258
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@igorjpimenta/winch-openclaw",
3
- "version": "2026.11.23-beta.3",
3
+ "version": "2026.11.25-beta.1",
4
4
  "description": "OpenClaw companion for winch: stamps caller identity on winch MCP tool calls, receives HTTP dispatch wakes, and reconciles in-progress work.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -29,7 +29,7 @@ function processCommand(pid) {
29
29
  }
30
30
  }
31
31
 
32
- export function createWakeRunner({ logger = console, stateDir = wakeStateDir() } = {}) {
32
+ export function createWakeRunner({ logger = console, stateDir = wakeStateDir(), dispatchUrl = null, bearer = null, consumerId = null } = {}) {
33
33
  // Detached children lead their own process group; kill the group so a
34
34
  // reaped turn's tool and MCP subprocesses go with it.
35
35
  const reap = (pid) => {
@@ -39,7 +39,7 @@ export function createWakeRunner({ logger = console, stateDir = wakeStateDir() }
39
39
 
40
40
  const recordPath = (ownerPid, childPid) => path.join(stateDir, `wake-${ownerPid}-${childPid}.json`);
41
41
 
42
- const wake = ({ agent, message }) =>
42
+ const spawnWake = ({ agent, message }) =>
43
43
  new Promise((resolve, reject) => {
44
44
  const bin = process.env.OPENCODE_BIN || "opencode";
45
45
  const child = spawn(bin, ["run", "--agent", agent, message], {
@@ -74,6 +74,35 @@ export function createWakeRunner({ logger = console, stateDir = wakeStateDir() }
74
74
  child.unref();
75
75
  });
76
76
 
77
+ // Core owns the wake window: it counts delivered-but-unsettled children and
78
+ // refuses to exceed WINCH_DISPATCH_WAKE_MAX. This map is the fail-safe for
79
+ // the pump/recover race — one live child per key, never a queue.
80
+ const inflight = new Set();
81
+
82
+ const settleUrl = dispatchUrl ? `${String(dispatchUrl).replace(/\/+$/, "")}/dispatch/notify` : null;
83
+
84
+ // The window frees only when the child reports its exit.
85
+ const settle = (admissionId) => {
86
+ if (!admissionId || !settleUrl) return;
87
+ const headers = { "content-type": "application/json" };
88
+ if (bearer) headers.authorization = `Bearer ${bearer}`;
89
+ void fetch(settleUrl, {
90
+ method: "POST",
91
+ headers,
92
+ body: JSON.stringify({ type: "settle", admissionId, consumerId }),
93
+ signal: AbortSignal.timeout(3000),
94
+ }).catch((err) => logger?.warn?.(`winch: settle ${admissionId} failed: ${err?.message ?? err}`));
95
+ };
96
+
97
+ const wake = ({ agent, message, key = null, admissionId = null }) => {
98
+ if (key && inflight.has(key)) return Promise.resolve({ deduped: true });
99
+ if (key) inflight.add(key);
100
+ return spawnWake({ agent, message }).finally(() => {
101
+ if (key) inflight.delete(key);
102
+ settle(admissionId);
103
+ });
104
+ };
105
+
77
106
  // Kill wake children whose spawning owner is no longer alive. Called at
78
107
  // dispatch startup and on a sweep timer; never on close, because a child
79
108
  // still owned by a live instance is not an orphan.
@@ -112,18 +141,19 @@ function consumerIdFor(harness, cfg = {}) {
112
141
  }
113
142
 
114
143
  function start({ cfg = {}, harness, logger }) {
115
- const runner = createWakeRunner({ logger, stateDir: cfg.wakeStateDir });
116
- runner.reapOrphans();
117
-
118
144
  const executorId = cfg.winchExecutorId ?? process.env.WINCH_EXECUTOR_ID;
119
145
  const consumerId = consumerIdFor(harness, cfg);
120
146
  const bearer = process.env.WINCH_WEBHOOK_BEARER;
147
+ const dispatchUrl = process.env.WINCH_DISPATCH_URL ?? DEFAULT_DISPATCH_URL;
148
+ const runner = createWakeRunner({ logger, stateDir: cfg.wakeStateDir, dispatchUrl, bearer, consumerId });
149
+ runner.reapOrphans();
150
+
121
151
  if (!executorId || !bearer) {
122
152
  logger?.warn?.("winch: dispatch needs WINCH_EXECUTOR_ID and WINCH_WEBHOOK_BEARER; receiver disabled");
123
153
  return null;
124
154
  }
125
155
  const dispatch = startDispatch({
126
- baseUrl: process.env.WINCH_DISPATCH_URL ?? DEFAULT_DISPATCH_URL,
156
+ baseUrl: dispatchUrl,
127
157
  harness,
128
158
  consumerId,
129
159
  executorId,
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@igorjpimenta/winch-opencode",
3
- "version": "2026.11.23-beta.3",
3
+ "version": "2026.11.25-beta.1",
4
4
  "description": "OpenCode companion for winch: stamps agent and session identity on winch tool calls, receives HTTP dispatch wakes, reports LLM usage, and reconciles assigned in-progress work. No SDK dependency \u2014 a plain id/setup/server export.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/config.js CHANGED
@@ -56,9 +56,9 @@ const SPEC = {
56
56
  dispatchPort: { env: "WINCH_DISPATCH_PORT", parse: parseInt, check: (v) => v >= 1 && v <= 65535 },
57
57
  dispatchIntervalMs: { env: "WINCH_DISPATCH_INTERVAL_MS", parse: parseInt, check: (v) => v > 0 },
58
58
  dispatchSweepMs: { env: "WINCH_DISPATCH_SWEEP_MS", parse: parseInt, check: (v) => v > 0 },
59
- maxActivePerAgent: { env: "WINCH_MAX_ACTIVE_PER_AGENT", parse: parseInt, check: (v) => v > 0 },
60
59
  dispatchHarnessMax: { env: "WINCH_DISPATCH_HARNESS_MAX", parse: parseInt, check: (v) => v > 0 },
61
60
  dispatchGlobalMax: { env: "WINCH_DISPATCH_GLOBAL_MAX", parse: parseInt, check: (v) => v > 0 },
61
+ dispatchWakeMax: { env: "WINCH_DISPATCH_WAKE_MAX", parse: parseInt, check: (v) => v > 0 },
62
62
  dispatchOfferMs: { env: "WINCH_DISPATCH_OFFER_MS", parse: parseInt, check: (v) => v > 0 },
63
63
  dispatchOfferBackoffMs: { env: "WINCH_DISPATCH_OFFER_BACKOFF_MS", parse: parseInt, check: (v) => v > 0 },
64
64
  dispatchOfferMaxBackoffMs: { env: "WINCH_DISPATCH_OFFER_MAX_BACKOFF_MS", parse: parseInt, check: (v) => v > 0 },
@@ -91,9 +91,9 @@ export const CONFIG_DEFAULTS = {
91
91
  dispatchPort: 38293,
92
92
  dispatchIntervalMs: 1000,
93
93
  dispatchSweepMs: 30000,
94
- maxActivePerAgent: 2,
95
94
  dispatchHarnessMax: 8,
96
95
  dispatchGlobalMax: 16,
96
+ dispatchWakeMax: 8,
97
97
  dispatchOfferMs: 120000,
98
98
  dispatchOfferBackoffMs: 30000,
99
99
  dispatchOfferMaxBackoffMs: 300000,
package/src/schema.js CHANGED
@@ -308,6 +308,7 @@ export const webhookDeliveries = sqliteTable("webhook_deliveries", {
308
308
  lastStatus: integer("last_status"),
309
309
  lastError: text("last_error"),
310
310
  deliveredAt: integer("delivered_at"),
311
+ settledAt: integer("settled_at"),
311
312
  deadAt: integer("dead_at"),
312
313
  createdAt: integer("created_at").notNull(),
313
314
  updatedAt: integer("updated_at").notNull(),
@@ -92,6 +92,69 @@ export function createDeliveryApi({ core }) {
92
92
  return rowById(id);
93
93
  },
94
94
 
95
+ // Marks a delivery as a running child without counting an HTTP attempt —
96
+ // recover hands these rows to the receiver over its response, not the wire.
97
+ markRunning({ admissionId, attemptNo, consumerId, at = now() }) {
98
+ const row = api.ensure({ admissionId, attemptNo, consumerId, at });
99
+ db.prepare(`
100
+ UPDATE webhook_deliveries
101
+ SET status='delivered', delivered_at=?, settled_at=NULL, updated_at=?
102
+ WHERE id=? AND status NOT IN ('dead','cancelled')
103
+ `).run(at, at, row.id);
104
+ return rowById(row.id);
105
+ },
106
+
107
+ // The receiver reports a child exit; only a delivered row can settle, so a
108
+ // late or duplicated settle cannot disturb a fresh attempt. Returns the
109
+ // number of rows settled (0 means nothing was running for that key).
110
+ settle({ admissionId, attemptNo = null, consumerId = null, at = now() }) {
111
+ const where = ["status='delivered'", "admission_id=?"];
112
+ const args = [admissionId];
113
+ if (attemptNo != null) { where.push("attempt_no=?"); args.push(attemptNo); }
114
+ if (consumerId != null) { where.push("consumer_id=?"); args.push(consumerId); }
115
+ return db.prepare(`
116
+ UPDATE webhook_deliveries SET settled_at=?, updated_at=?
117
+ WHERE ${where.join(" AND ")}
118
+ `).run(at, at, ...args).changes;
119
+ },
120
+
121
+ // Running = delivered, not yet settled, within the settle lease. The lease
122
+ // is what frees the window when a receiver dies without settling; a live
123
+ // child re-marks its row on every redundant wake, refreshing it.
124
+ runningCount(consumerId, { after = 0 } = {}) {
125
+ return db.prepare(`
126
+ SELECT COUNT(DISTINCT admission_id) AS n FROM webhook_deliveries
127
+ WHERE consumer_id=? AND status='delivered' AND settled_at IS NULL AND delivered_at >= ?
128
+ `).get(consumerId, after).n;
129
+ },
130
+
131
+ runningAdmissionIds({ consumerId = null, after = 0 } = {}) {
132
+ const where = ["status='delivered'", "settled_at IS NULL", "delivered_at >= ?"];
133
+ const args = [after];
134
+ if (consumerId != null) { where.push("consumer_id=?"); args.push(consumerId); }
135
+ return new Set(db.prepare(`
136
+ SELECT DISTINCT admission_id FROM webhook_deliveries WHERE ${where.join(" AND ")}
137
+ `).all(...args).map((r) => r.admission_id));
138
+ },
139
+
140
+ isRunning(admissionId, { consumerId = null, after = 0 } = {}) {
141
+ const where = ["admission_id=?", "status='delivered'", "settled_at IS NULL", "delivered_at >= ?"];
142
+ const args = [admissionId, after];
143
+ if (consumerId != null) { where.push("consumer_id=?"); args.push(consumerId); }
144
+ return db.prepare(`SELECT 1 FROM webhook_deliveries WHERE ${where.join(" AND ")} LIMIT 1`)
145
+ .get(...args) != null;
146
+ },
147
+
148
+ // Puts a claimed row back without counting an attempt: a delivery held by
149
+ // the wake window was never actually posted.
150
+ defer(id, { nextAt, at = now() } = {}) {
151
+ db.prepare(`
152
+ UPDATE webhook_deliveries SET status='pending', next_at=?, updated_at=?
153
+ WHERE id=? AND status='delivering'
154
+ `).run(nextAt, at, id);
155
+ return rowById(id);
156
+ },
157
+
95
158
  markRetry(id, { status = null, error = null, nextAt, at = now() } = {}) {
96
159
  db.prepare(`
97
160
  UPDATE webhook_deliveries
@@ -123,7 +186,7 @@ export function createDeliveryApi({ core }) {
123
186
  resetForConsumer(admissionId, attemptNo, consumerId, { at = now() } = {}) {
124
187
  db.prepare(`
125
188
  UPDATE webhook_deliveries
126
- SET status='pending', next_at=?, delivered_at=NULL, dead_at=NULL, updated_at=?
189
+ SET status='pending', next_at=?, delivered_at=NULL, settled_at=NULL, dead_at=NULL, updated_at=?
127
190
  WHERE admission_id=? AND attempt_no=? AND consumer_id=?
128
191
  `).run(at, at, admissionId, attemptNo, consumerId);
129
192
  return db.prepare(`
@@ -4,7 +4,7 @@
4
4
  // stamped from the caller's declared transport identity, so an assignment can
5
5
  // never name an agent without saying which harness it belongs to. The reserved
6
6
  // agent `human` gets the reserved harness `human_in_the_loop` instead.
7
- import { ok, err } from "./shared.js";
7
+ import { ok, err, noRouteWarning } from "./shared.js";
8
8
 
9
9
  export function createAssignTools({ store, logger }) {
10
10
  return {
@@ -38,9 +38,13 @@ export function createAssignTools({ store, logger }) {
38
38
  note: `assign ${assigned ?? "nobody"}`,
39
39
  });
40
40
  logger?.info?.(`backlog: ${qualified} assigned ${story.id} -> ${assigned ?? "nobody"}`);
41
+ // Wake signal only when the write actually enqueued: routesForEvent
42
+ // admits story.assigned solely from ready.
43
+ const warning = updated.status === "ready" ? noRouteWarning(store, updated.assignee_harness) : null;
44
+ if (warning) logger?.warn?.(`backlog: ${warning.message}`);
41
45
  return ok(
42
- JSON.stringify({ ok: true, story: { id: updated.id, status: updated.status, assigned: updated.assignee_agent, capabilities: updated.capabilities } }),
43
- { status: "ok", level: "story", id: updated.id, assigned: updated.assignee_agent, agent: identity.agent }
46
+ JSON.stringify({ ok: true, story: { id: updated.id, status: updated.status, assigned: updated.assignee_agent, capabilities: updated.capabilities }, ...(warning ? { warning } : {}) }),
47
+ { status: "ok", level: "story", id: updated.id, assigned: updated.assignee_agent, agent: identity.agent, ...(warning ? { warning } : {}) }
44
48
  );
45
49
  } catch (e) {
46
50
  return err(`backlog_assign failed: ${e?.message}`, "rejected", { id: story.id });
@@ -63,9 +67,13 @@ export function createAssignTools({ store, logger }) {
63
67
  capabilities: args?.capabilities,
64
68
  });
65
69
  logger?.info?.(`backlog: ${qualified} assigned ${task.id} -> ${updated.assignee_agent ?? "nobody"}`);
70
+ // Wake signal only when the write actually enqueued: routesForEvent
71
+ // admits task.assigned solely from ready.
72
+ const warning = updated.status === "ready" ? noRouteWarning(store, updated.assignee_harness) : null;
73
+ if (warning) logger?.warn?.(`backlog: ${warning.message}`);
66
74
  return ok(
67
- JSON.stringify({ ok: true, task: { id: updated.id, status: updated.status, assigned: updated.assignee_agent, capabilities: updated.capabilities } }),
68
- { status: "ok", taskId: updated.id, assigned: updated.assignee_agent, agent: identity.agent }
75
+ JSON.stringify({ ok: true, task: { id: updated.id, status: updated.status, assigned: updated.assignee_agent, capabilities: updated.capabilities }, ...(warning ? { warning } : {}) }),
76
+ { status: "ok", taskId: updated.id, assigned: updated.assignee_agent, agent: identity.agent, ...(warning ? { warning } : {}) }
69
77
  );
70
78
  } catch (e) {
71
79
  return err(`backlog_assign failed: ${e?.message}`, "rejected", { taskId: task.id });
@@ -35,7 +35,8 @@ export const TOOL_DEFS = [
35
35
  "`backlog_append`, unassigned, so the planner can route them — use story assignment when the breakdown is not known at plan time. " +
36
36
  "Refuses to reassign a task already in progress by someone else. Passing `agent: null` or \"\" clears it. " +
37
37
  "The reserved agent `human` assigns human work with the reserved harness `human_in_the_loop`. " +
38
- "Optional `capabilities` replaces the item's capability tags.",
38
+ "Optional `capabilities` replaces the item's capability tags. " +
39
+ "A successful result may carry `warning.code: \"no_route\"` when no enabled dispatch subscription matches the harness — the row is ready but will not wake until a receiver is registered.",
39
40
  inputSchema: {
40
41
  type: "object",
41
42
  additionalProperties: false,
@@ -91,7 +92,8 @@ export const TOOL_DEFS = [
91
92
  "protocols a demand — the spec goes INTO the records (task description, story acceptance, capability tags), because a " +
92
93
  "worker receives only a task id and reads the record itself. Tasks land `backlog`; assigning one moves it to `ready`. Use " +
93
94
  "`backlog_assign`. `dependsOn` references other tasks in the same plan by key (default `s<story>t<task>`, zero-based) " +
94
- "and may only point backward, so the plan is acyclic by construction. All-or-nothing: an invalid key rolls back the plan.",
95
+ "and may only point backward, so the plan is acyclic by construction. All-or-nothing: an invalid key rolls back the plan. " +
96
+ "A successful result may carry `warning.code: \"no_route\"` when no dispatch subscription is registered at all — nothing can wake until a receiver is.",
95
97
  inputSchema: {
96
98
  type: "object",
97
99
  additionalProperties: false,
package/src/tools/plan.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // plan.js — create and reshape the plan: plan, append, drop, restore.
2
2
  import { addDep } from "../deps.js";
3
- import { ok, err } from "./shared.js";
3
+ import { ok, err, noSubscriptionWarning } from "./shared.js";
4
4
 
5
5
  export function createPlanTools({ store, logger }) {
6
6
  return {
@@ -82,9 +82,11 @@ export function createPlanTools({ store, logger }) {
82
82
  }
83
83
  }
84
84
  logger?.info?.(`backlog: ${identity.harness}:${identity.agent} planned ${epic.id} (${flat.length} tasks)`);
85
+ const warning = noSubscriptionWarning(store);
86
+ if (warning) logger?.warn?.(`backlog: ${warning.message}`);
85
87
  return ok(
86
- JSON.stringify({ epic: { id: epic.id, title: epic.title }, stories, dependencies }),
87
- { status: "ok", agentId: identity.agent, epicId: epic.id, tasks: flat.length }
88
+ JSON.stringify({ epic: { id: epic.id, title: epic.title }, stories, dependencies, ...(warning ? { warning } : {}) }),
89
+ { status: "ok", agentId: identity.agent, epicId: epic.id, tasks: flat.length, ...(warning ? { warning } : {}) }
88
90
  );
89
91
  } catch (e) {
90
92
  // The epic is the root; deleting it cascades everything written under it.
@@ -1,6 +1,9 @@
1
1
  // shared.js — the pieces every tool handler needs: result shapes, note
2
2
  // clamping, and the store-derived handoff text.
3
3
 
4
+ import { HUMAN_HARNESS } from "../reserved.js";
5
+ import { consumersFor } from "../webhook/delivery.js";
6
+
4
7
  export function ok(text, details) {
5
8
  return { content: [{ type: "text", text }], details };
6
9
  }
@@ -26,6 +29,43 @@ export function clampNote(s, max = 2000) {
26
29
  return s.length > max ? s.slice(0, max) + "…" : s;
27
30
  }
28
31
 
32
+ // no_route: dispatch only offers admissions to harnesses that have an enabled
33
+ // subscription (the pump's `reachable` set), and delivery fans out through the
34
+ // same `consumersFor` predicate — so an assignment whose harness matches no
35
+ // subscription can never be woken, however healthy the dispatch server looks.
36
+ // The reserved human harness never routes by design, so it never warns.
37
+ export function noRouteWarning(store, harness) {
38
+ if (!harness || harness === HUMAN_HARNESS) return null;
39
+ if (consumersFor(store, harness).length > 0) return null;
40
+ return {
41
+ code: "no_route",
42
+ harness,
43
+ message:
44
+ `no enabled dispatch subscription matches harness "${harness}"; ` +
45
+ `this assignment is ready but unroutable. Register a receiver first: ` +
46
+ `winch webhook register --topic dispatch --harness ${harness} --url <receiver-url> --bearer <token> ` +
47
+ `or run the harness plugin with WINCH_EXECUTOR_ID + WINCH_WEBHOOK_BEARER ` +
48
+ `(WINCH_DISPATCH_URL must match the port winch webhook serve is listening on, default 38293).`,
49
+ };
50
+ }
51
+
52
+ // Plan-time variant: nothing is assigned yet, but every wake the plan will
53
+ // produce (assignment, epic-creator fan-out) needs at least one subscription
54
+ // to exist. With zero subscriptions the whole pipeline is inert.
55
+ export function noSubscriptionWarning(store) {
56
+ if (store.webhook.harnesses({ topic: "dispatch" }).length > 0) return null;
57
+ return {
58
+ code: "no_route",
59
+ harness: null,
60
+ message:
61
+ `no dispatch subscriptions are registered; assigned rows will queue but nothing can deliver a wake. ` +
62
+ `Register a receiver first: ` +
63
+ `winch webhook register --topic dispatch --harness <harness> --url <receiver-url> --bearer <token> ` +
64
+ `or run the harness plugin with WINCH_EXECUTOR_ID + WINCH_WEBHOOK_BEARER ` +
65
+ `(WINCH_DISPATCH_URL must match the port winch webhook serve is listening on, default 38293).`,
66
+ };
67
+ }
68
+
29
69
  // Artifacts upstream tasks recorded on this story: addArtifact events,
30
70
  // explicit artifact rows, and done-result artifact lists, deduped.
31
71
  export function collectStoryArtifacts(store, storyId) {
package/src/watcher.js CHANGED
@@ -15,19 +15,13 @@ import { HUMAN_AGENT } from "./reserved.js";
15
15
  import { createStore } from "./store/index.js";
16
16
  import { readyTasks } from "./ready-queue.js";
17
17
 
18
- // An agent this busy should finish before it hears about more work. Keeps the
19
- // wake queue from stacking claims on an already-loaded assignee; the deferred
20
- // list is the starvation signal.
21
- export const MAX_ACTIVE_PER_AGENT = 2;
22
-
23
18
  /**
24
- * @returns {{ts:number, swept:string[], resolved:string[], waits:object[], routed:object[], human:object[], deferred:object[], blocked:object[], gates:object[]}}
19
+ * @returns {{ts:number, swept:string[], resolved:string[], waits:object[], routed:object[], human:object[], blocked:object[], gates:object[]}}
25
20
  * swept — lease-expired tasks the sweep requeued or escalated this tick
26
21
  * resolved — dependency-wait tasks returned to ready this tick
27
22
  * waits — gate-waiting rows written this tick (24h/72h age thresholds, one per gate per level)
28
- * routed — claimable AND assigned AND assignee under the active cap: the cron wakes `assigned`
23
+ * routed — claimable AND assigned: the cron wakes `assigned`
29
24
  * human — claimable human work: ready for a person, never woken through an agent harness
30
- * deferred — claimable AND assigned BUT assignee at MAX_ACTIVE: never woken (starvation metric)
31
25
  */
32
26
  export function tick(store, { config: override = null } = {}) {
33
27
  const cfg = override ?? store.config;
@@ -58,18 +52,8 @@ export function tick(store, { config: override = null } = {}) {
58
52
  .filter((t) => t.gate_type)
59
53
  .sort((a, b) => (a.blocked_at ?? 0) - (b.blocked_at ?? 0))
60
54
  .map((t) => ({ id: t.id, title: t.title, gate_type: t.gate_type, blocked_at: t.blocked_at, assigned: t.assignee_agent }));
61
- const active = new Map();
62
- for (const t of store.item.list({ kind: "task", status: "in_progress" })) {
63
- if (!t.assignee_agent) continue;
64
- active.set(t.assignee_agent, (active.get(t.assignee_agent) ?? 0) + 1);
65
- }
66
55
  const human = claimable.filter((c) => c.assigned === HUMAN_AGENT);
67
- const routed = claimable.filter(
68
- (c) => c.assigned && c.assigned !== HUMAN_AGENT && (active.get(c.assigned) ?? 0) < cfg.maxActivePerAgent
69
- );
70
- const deferred = claimable
71
- .filter((c) => c.assigned && c.assigned !== HUMAN_AGENT && (active.get(c.assigned) ?? 0) >= cfg.maxActivePerAgent)
72
- .map((c) => ({ ...c, activeCount: active.get(c.assigned) }));
56
+ const routed = claimable.filter((c) => c.assigned && c.assigned !== HUMAN_AGENT);
73
57
 
74
58
  return {
75
59
  ts: nowTs,
@@ -78,7 +62,6 @@ export function tick(store, { config: override = null } = {}) {
78
62
  waits,
79
63
  routed,
80
64
  human,
81
- deferred,
82
65
  blocked,
83
66
  gates,
84
67
  };
@@ -171,9 +171,21 @@ export function recover(store, { harness, consumerId = null, at = Date.now(), co
171
171
  otherReserved = Math.max(0, [...slots.reserved.values()].reduce((n, v) => n + v, 0) - offered.length);
172
172
  }
173
173
 
174
- const start = keptOffers
175
- .filter((live) => !consumerId || !live.active_consumer_id || live.active_consumer_id === consumerId)
176
- .map((live) => ({
174
+ const settleAfter = at - (config.dispatchDeliveryLeaseMs ?? 300000);
175
+ const wakeMax = config.dispatchWakeMax ?? 8;
176
+ const running = store.delivery.runningAdmissionIds({ consumerId, after: settleAfter });
177
+ const runningForConsumer = consumerId ? store.delivery.runningCount(consumerId, { after: settleAfter }) : 0;
178
+ let windowFree = Math.max(0, wakeMax - runningForConsumer);
179
+
180
+ const start = [];
181
+ for (const live of keptOffers) {
182
+ if (consumerId && live.active_consumer_id && live.active_consumer_id !== consumerId) continue;
183
+ if (running.has(live.id)) continue;
184
+ if (consumerId) {
185
+ if (windowFree <= 0) continue;
186
+ windowFree--;
187
+ }
188
+ start.push({
177
189
  admissionId: live.id,
178
190
  itemId: live.item_id,
179
191
  attemptNo: live.attempt_no ?? null,
@@ -185,7 +197,13 @@ export function recover(store, { harness, consumerId = null, at = Date.now(), co
185
197
  activeConsumerId: live.active_consumer_id ?? null,
186
198
  leaseEpoch: live.lease_epoch ?? 0,
187
199
  status: live.status,
188
- }));
200
+ });
201
+ // Handing a row over in this response starts its child: mark it running
202
+ // so the pump does not post a second wake for it.
203
+ if (mutate && consumerId) {
204
+ store.delivery.markRunning({ admissionId: live.id, attemptNo: live.attempt_no ?? null, consumerId, at });
205
+ }
206
+ }
189
207
 
190
208
  const usedHarness = activeHarness + keptOffers.length;
191
209
  const usedGlobal = activeGlobal + otherReserved + keptOffers.length;
@@ -194,7 +212,7 @@ export function recover(store, { harness, consumerId = null, at = Date.now(), co
194
212
  config.dispatchGlobalMax - usedGlobal,
195
213
  ));
196
214
  if (mutate) for (const row of store.admission.queued(harness, at)) {
197
- if (free <= 0) break;
215
+ if (free <= 0 || (consumerId && windowFree <= 0)) break;
198
216
  const next = store.admission.markOffered(row.id, at, {
199
217
  pickActive: (attemptNo) => pickConsumer(store, { ...row, attempt_no: attemptNo }),
200
218
  leaseMs: config.dispatchConsumerTtlMs,
@@ -213,6 +231,10 @@ export function recover(store, { harness, consumerId = null, at = Date.now(), co
213
231
  leaseEpoch: next.lease_epoch ?? 0,
214
232
  status: "offered",
215
233
  });
234
+ if (consumerId) {
235
+ windowFree--;
236
+ store.delivery.markRunning({ admissionId: next.id, attemptNo: next.attempt_no ?? null, consumerId, at });
237
+ }
216
238
  free--;
217
239
  }
218
240
 
@@ -92,6 +92,17 @@ async function deliverOne(store, delivery, row, { config, logger, at }) {
92
92
  store.delivery.recordAttempt({ deliveryId: delivery.id, attemptNo: delivery.attempts + 1, status: "dead", error: "consumer disabled", at });
93
93
  return { ok: false, consumerId: delivery.consumer_id, status: 0, error: "consumer disabled" };
94
94
  }
95
+ const settleAfter = at - (config.dispatchDeliveryLeaseMs ?? 300000);
96
+ if (store.delivery.isRunning(delivery.admission_id, { consumerId: delivery.consumer_id, after: settleAfter })) {
97
+ // A re-offer bumped attemptNo while this consumer's child for the same
98
+ // admission is still alive; the wake would stack a second process.
99
+ store.delivery.cancelForAttempt(delivery.admission_id, delivery.attempt_no, { at });
100
+ return { ok: false, consumerId: delivery.consumer_id, status: 0, error: "admission running" };
101
+ }
102
+ if (store.delivery.runningCount(delivery.consumer_id, { after: settleAfter }) >= (config.dispatchWakeMax ?? 8)) {
103
+ store.delivery.defer(delivery.id, { nextAt: at + 1000, at });
104
+ return { ok: false, consumerId: delivery.consumer_id, status: 0, error: "wake window full" };
105
+ }
95
106
  const execution = row.active_consumer_id === delivery.consumer_id ? "active" : "standby";
96
107
  const payload = wakePayload(row, {
97
108
  offerMs: config.dispatchOfferMs,
@@ -172,7 +172,16 @@ export function startDispatchServer({ store, port = null, host = "127.0.0.1", in
172
172
  }
173
173
  if (req.method === "POST" && url.pathname === "/dispatch/notify") {
174
174
  if (unauthorized(req)) { json(res, 401, { error: "unauthorized" }); return; }
175
- req.resume();
175
+ const body = await readJson(req, res);
176
+ if (body === undefined) return;
177
+ if (body?.type === "settle" && typeof body.admissionId === "string" && body.admissionId) {
178
+ store.delivery.settle({
179
+ admissionId: body.admissionId,
180
+ attemptNo: Number.isInteger(body.attemptNo) ? body.attemptNo : null,
181
+ consumerId: typeof body.consumerId === "string" && body.consumerId ? body.consumerId : null,
182
+ at: Date.now(),
183
+ });
184
+ }
176
185
  json(res, 202, { ok: true });
177
186
  void pump();
178
187
  return;