@igorjpimenta/winch 2026.11.24-beta.1 → 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,7 +123,10 @@ 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
@@ -397,8 +400,7 @@ through unchanged. History and live rows share one envelope shape.
397
400
 
398
401
  Delivery-dynamics notes the envelopes will not tell you: heartbeats renew the
399
402
  claim lease (only silence gets swept); an unmerged close dissolves its gate
400
- (late approvals answer `gate_dissolved`); starvation lives in the watcher
401
- manifest (`deferred` list), not the envelopes; a disputed
403
+ (late approvals answer `gate_dissolved`); a disputed
402
404
  completion is a new ticket linked by dep edge with a `supersedes: ITM-x` note,
403
405
  never a rewrite of history.
404
406
 
@@ -462,6 +464,7 @@ refuse as likely typos, unknown meta keys are ignored for forward compat.
462
464
  | Event history limit (dispatch boot catch-up batch) | `WINCH_EVENT_HISTORY_LIMIT` | 200 |
463
465
  | Dispatch port / poll / lease sweep | `WINCH_DISPATCH_PORT` / `WINCH_DISPATCH_INTERVAL_MS` / `WINCH_DISPATCH_SWEEP_MS` | 38293 / 1000 / 30000 ms |
464
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 |
465
468
  | Dispatch consumer heartbeat TTL | `WINCH_DISPATCH_CONSUMER_TTL_MS` | 90000 ms |
466
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 |
467
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 |
@@ -469,7 +472,6 @@ refuse as likely typos, unknown meta keys are ignored for forward compat.
469
472
  | Dispatch management auth | `WINCH_DISPATCH_TOKEN` | unset (loopback) |
470
473
  | MCP HTTP port | `WINCH_MCP_HTTP_PORT` | 38292 |
471
474
  | DB path | `WINCH_DB` | `~/.winch/store.sqlite` |
472
- | Wake routing cap | `WINCH_MAX_ACTIVE_PER_AGENT` | 2 |
473
475
  | Scan limits (tick / candidates / blocked list) | `WINCH_SCAN_LIMIT` / `WINCH_CANDIDATES` / `WINCH_BLOCKED_LIMIT` | 50 / 5 / 20 |
474
476
  | Dep cycle-check cap | `WINCH_DFS_NODES` | 500 nodes |
475
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.24-beta.1",
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.24-beta.1",
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.24-beta.1",
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(`
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;