@igorjpimenta/winch 2026.11.22-beta.3 → 2026.11.23-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 { startEventServer } from "./events-ws.js";
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 (err) {
190
- // --harness (or any unknown flag) on serve means the caller is still
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
- const modes = ["ws", "mcp"].filter((k) => values[k]);
201
- if (modes.length !== 1) {
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
- wsHistoryLimit: { env: "WINCH_WS_HISTORY_LIMIT", parse: parseInt, check: (v) => v > 0 },
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
- wsHistoryLimit: 200,
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\"" : key === "wsPort" ? "a port 1-65535" : "a positive integer"} — got ${JSON.stringify(raw) ?? "nothing"}.`);
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
@@ -13,6 +13,7 @@ import {
13
13
  sqliteTable,
14
14
  text,
15
15
  integer,
16
+ real,
16
17
  index,
17
18
  uniqueIndex,
18
19
  check,
@@ -33,6 +34,7 @@ export const ADMISSION_STATUSES = ["queued", "offered", "accepted", "active", "d
33
34
  export const EDGE_KINDS = ["depends_on"];
34
35
  export const DELIVERY_STATUSES = ["pending", "delivering", "delivered", "dead", "cancelled"];
35
36
  export const WEBHOOK_STATES = ["active", "suspect", "disabled"];
37
+ export const USAGE_SOURCES = ["api"];
36
38
 
37
39
  const inList = (values) => sql.raw(values.map((v) => `'${v}'`).join(", "));
38
40
 
@@ -179,6 +181,34 @@ export const itemEvents = sqliteTable("item_events", {
179
181
  index("idx_item_events_created").on(table.createdAt),
180
182
  ]);
181
183
 
184
+ export const usageEvents = sqliteTable("usage_events", {
185
+ id: integer("id").primaryKey({ autoIncrement: true }),
186
+ itemId: text("item_id").notNull().references(() => items.id, { onDelete: "restrict" }),
187
+ sessionId: text("session_id").references(() => workSessions.id, { onDelete: "set null" }),
188
+ attemptId: text("attempt_id").references(() => attempts.id, { onDelete: "set null" }),
189
+ harness: text("harness").notNull(),
190
+ agentId: text("agent_id").notNull(),
191
+ externalSessionId: text("external_session_id").notNull(),
192
+ model: text("model"),
193
+ tokensIn: integer("tokens_in"),
194
+ tokensOut: integer("tokens_out"),
195
+ cacheRead: integer("cache_read"),
196
+ costUsd: real("cost_usd"),
197
+ toolCalls: integer("tool_calls"),
198
+ source: text("source").notNull().default("api"),
199
+ turnRef: text("turn_ref"),
200
+ createdAt: integer("created_at").notNull(),
201
+ }, (table) => [
202
+ check("usage_source", sql`${table.source} IN (${inList(USAGE_SOURCES)})`),
203
+ check("usage_nonneg", sql`(${table.tokensIn} IS NULL OR ${table.tokensIn} >= 0) AND (${table.tokensOut} IS NULL OR ${table.tokensOut} >= 0) AND (${table.cacheRead} IS NULL OR ${table.cacheRead} >= 0) AND (${table.costUsd} IS NULL OR ${table.costUsd} >= 0) AND (${table.toolCalls} IS NULL OR ${table.toolCalls} >= 0)`),
204
+ index("idx_usage_item").on(table.itemId),
205
+ index("idx_usage_session").on(table.sessionId),
206
+ index("idx_usage_attempt").on(table.attemptId),
207
+ index("idx_usage_created").on(table.createdAt),
208
+ index("idx_usage_identity").on(table.harness, table.agentId, table.externalSessionId),
209
+ uniqueIndex("uq_usage_turn").on(table.harness, table.agentId, table.externalSessionId, table.turnRef).where(sql`${table.turnRef} IS NOT NULL`),
210
+ ]);
211
+
182
212
  export const itemEdges = sqliteTable("item_edges", {
183
213
  fromItemId: text("from_item_id").notNull().references(() => items.id, { onDelete: "cascade" }),
184
214
  toItemId: text("to_item_id").notNull().references(() => items.id, { onDelete: "cascade" }),
@@ -266,7 +296,7 @@ export const dispatchEvents = sqliteTable("dispatch_events", {
266
296
  index("idx_dispatch_events_created").on(table.createdAt),
267
297
  ]);
268
298
 
269
- export const dispatchDeliveries = sqliteTable("dispatch_deliveries", {
299
+ export const webhookDeliveries = sqliteTable("webhook_deliveries", {
270
300
  id: integer("id").primaryKey({ autoIncrement: true }),
271
301
  admissionId: text("admission_id").notNull().references(() => admissionQueue.id, { onDelete: "cascade" }),
272
302
  attemptNo: integer("attempt_no").notNull(),
@@ -289,9 +319,9 @@ export const dispatchDeliveries = sqliteTable("dispatch_deliveries", {
289
319
  index("idx_delivery_event").on(table.eventId, table.consumerId),
290
320
  ]);
291
321
 
292
- export const dispatchDeliveryAttempts = sqliteTable("dispatch_delivery_attempts", {
322
+ export const webhookDeliveryAttempts = sqliteTable("webhook_delivery_attempts", {
293
323
  id: integer("id").primaryKey({ autoIncrement: true }),
294
- deliveryId: integer("delivery_id").notNull().references(() => dispatchDeliveries.id, { onDelete: "cascade" }),
324
+ deliveryId: integer("delivery_id").notNull().references(() => webhookDeliveries.id, { onDelete: "cascade" }),
295
325
  attemptNo: integer("attempt_no").notNull(),
296
326
  status: text("status").notNull(),
297
327
  responseStatus: integer("response_status"),
@@ -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 dispatch_deliveries WHERE id=?").get(id) ?? null;
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 dispatch_deliveries(admission_id, attempt_no, event_id, consumer_id, status, attempts,
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(dispatch_deliveries.event_id, excluded.event_id)
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 dispatch_deliveries
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 dispatch_deliveries${where.length ? ` WHERE ${where.join(" AND ")}` : ""}
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 dispatch_deliveries
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 dispatch_deliveries
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 dispatch_deliveries SET status='delivering', updated_at=? WHERE id=? AND status='pending'");
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 dispatch_deliveries SET status='pending', next_at=?, updated_at=?
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 dispatch_delivery_attempts(delivery_id, attempt_no, status, response_status, error, created_at)
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 dispatch_deliveries
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 dispatch_deliveries
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 dispatch_deliveries
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 dispatch_deliveries
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 dispatch_deliveries
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 dispatch_deliveries
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
  },
@@ -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 WebSocket stream and tools.
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;
@@ -36,8 +36,9 @@ 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 "../dispatch.js";
40
- import { toEventMessage } from "../events-ws.js";
39
+ import { observe } from "../webhook/core.js";
40
+ import { toEventMessage } from "../webhook/envelope.js";
41
+ import { createUsageApi } from "./usage.js";
41
42
 
42
43
  export { MAX_ATTEMPTS };
43
44
  export { EPIC_STATUSES, STORY_STATUSES, TASK_STATUSES, EXECUTION_KINDS, ITEM_KINDS };
@@ -70,6 +71,7 @@ export function createStore({ dbPath, logger, config: explicitConfig, notifyDisp
70
71
  apis.admission = createAdmissionApi({ core });
71
72
  apis.delivery = createDeliveryApi({ core });
72
73
  apis.dispatchEvent = createDispatchEventApi({ core });
74
+ apis.usage = createUsageApi({ core });
73
75
 
74
76
  const notifyBase = process.env.WINCH_DISPATCH_URL ?? `http://127.0.0.1:${cfg.dispatchPort}`;
75
77
  const targetUrl = notifyUrl ?? `${notifyBase.replace(/\/+$/, "")}/dispatch/notify`;
@@ -115,6 +117,7 @@ export function createStore({ dbPath, logger, config: explicitConfig, notifyDisp
115
117
  admission: apis.admission,
116
118
  delivery: apis.delivery,
117
119
  dispatchEvent: apis.dispatchEvent,
120
+ usage: apis.usage,
118
121
  epic: apis.epic,
119
122
  story: apis.story,
120
123
  task: apis.task,
@@ -0,0 +1,85 @@
1
+ // usage.js — LLM cost/usage tracking on top of the v8 ledger.
2
+ //
3
+ // One append-only `usage_events` row per reported turn. The row carries the
4
+ // identity triple denormalized (so it survives session deletion), an item_id
5
+ // attribution and optional session/attempt links. Aggregations read this table
6
+ // directly; there is no rollup.
7
+
8
+ export function createUsageApi({ core }) {
9
+ const { db, now } = core;
10
+
11
+ function record({
12
+ harness, agent, session, itemId,
13
+ sessionId = null, attemptId = null,
14
+ usage, source = "api", turnRef = null, at = null,
15
+ }) {
16
+ if (!usage || !itemId) return null;
17
+ const u = usage;
18
+ const r = db.prepare(`
19
+ INSERT OR IGNORE INTO usage_events(
20
+ item_id, session_id, attempt_id, harness, agent_id, external_session_id,
21
+ model, tokens_in, tokens_out, cache_read, cost_usd, tool_calls,
22
+ source, turn_ref, created_at
23
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
24
+ `).run(
25
+ itemId, sessionId, attemptId, harness, agent, session,
26
+ u.model ?? null, u.tokensIn ?? null, u.tokensOut ?? null, u.cacheRead ?? null,
27
+ u.costUsd ?? null, u.toolCalls ?? null, source ?? "api", turnRef, at ?? now(),
28
+ );
29
+ return r.changes ? Number(r.lastInsertRowid) : null;
30
+ }
31
+
32
+ function whereClause({ itemId, harness, agent, session, model, since } = {}) {
33
+ const where = [];
34
+ const args = [];
35
+ if (itemId) { where.push("item_id=?"); args.push(itemId); }
36
+ if (harness) { where.push("harness=?"); args.push(harness); }
37
+ if (agent) { where.push("agent_id=?"); args.push(agent); }
38
+ if (session) { where.push("external_session_id=?"); args.push(session); }
39
+ if (model) { where.push("model=?"); args.push(model); }
40
+ if (since) { where.push("created_at>=?"); args.push(since); }
41
+ return { where, args };
42
+ }
43
+
44
+ function list(opts = {}) {
45
+ const { where, args } = whereClause(opts);
46
+ const sql = `SELECT u.*, i.kind AS item_kind
47
+ FROM usage_events u JOIN items i ON i.id=u.item_id
48
+ ${where.length ? `WHERE ${where.join(" AND ")}` : ""}
49
+ ORDER BY u.created_at DESC`;
50
+ return db.prepare(sql).all(...args).map((r) => ({
51
+ id: r.id,
52
+ itemId: r.item_id,
53
+ itemKind: r.item_kind,
54
+ sessionId: r.session_id,
55
+ attemptId: r.attempt_id,
56
+ harness: r.harness,
57
+ agentId: r.agent_id,
58
+ externalSessionId: r.external_session_id,
59
+ model: r.model,
60
+ tokensIn: r.tokens_in,
61
+ tokensOut: r.tokens_out,
62
+ cacheRead: r.cache_read,
63
+ costUsd: r.cost_usd,
64
+ toolCalls: r.tool_calls,
65
+ source: r.source,
66
+ turnRef: r.turn_ref,
67
+ at: r.created_at,
68
+ }));
69
+ }
70
+
71
+ function summary(opts = {}) {
72
+ const { where, args } = whereClause(opts);
73
+ const sql = `SELECT COUNT(*) AS calls,
74
+ COALESCE(SUM(tokens_in),0) AS tokens_in,
75
+ COALESCE(SUM(tokens_out),0) AS tokens_out,
76
+ COALESCE(SUM(cache_read),0) AS cache_read,
77
+ COALESCE(SUM(cost_usd),0) AS cost_usd,
78
+ COALESCE(SUM(tool_calls),0) AS tool_calls
79
+ FROM usage_events
80
+ ${where.length ? `WHERE ${where.join(" AND ")}` : ""}`;
81
+ return db.prepare(sql).get(...args);
82
+ }
83
+
84
+ return { record, list, summary };
85
+ }
@@ -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 ?? args?.taskId;
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
 
@@ -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",
@@ -35,6 +35,22 @@ export function createToolHandlers(store, logger) {
35
35
  async function handle(name, args, identity, meta = null) {
36
36
  assertCleanTriple(identity, `caller identity for ${name}`);
37
37
  const cfg = resolveRequestConfig(baseConfig, meta);
38
+ // Implicit session bind: an item-touching call binds the session to that
39
+ // item, so a later POST /usage attributes to the last-touched item.
40
+ try {
41
+ const fromArgs = (typeof args?.taskId === "string" || typeof args?.task_id === "string" ||
42
+ typeof args?.id === "string" || typeof args?.epicId === "string" ||
43
+ typeof args?.epic_id === "string" || typeof args?.storyId === "string" ||
44
+ typeof args?.story_id === "string");
45
+ const itemId = fromArgs
46
+ ? (args?.taskId ?? args?.task_id ?? args?.id ?? args?.epicId ?? args?.epic_id ?? args?.storyId ?? args?.story_id)
47
+ : null;
48
+ if (fromArgs && itemId) {
49
+ store.session.ensure({ harness: identity.harness, agentId: identity.agent, externalSessionId: identity.session, itemId, kind: "claim" });
50
+ }
51
+ } catch (e) {
52
+ logger?.warn?.(`winch: session bind failed: ${e?.message}`);
53
+ }
38
54
  const fn = handlers[name];
39
55
  if (!fn) return err(`unknown tool: ${name}`, "unknown_tool");
40
56
  return fn(args, identity, cfg);
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[], unrouted:object[], blocked:object[], gates: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 — the events WebSocket
56
- // streams every row, and clients track their own seen state.
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 "./reserved.js";
6
- import { pickConsumer } from "./dispatch-webhook.js";
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
- ${ownerForItem} AS consumer_id
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 ${ownerForItem} = ?)
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 dispatch_deliveries d
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 dispatch_deliveries d
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();