@igorjpimenta/winch 2026.11.23-beta.1 → 2026.11.23-beta.3

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
@@ -10,10 +10,11 @@ import { createStore } from "./store/index.js";
10
10
  import { readyTasks } from "./ready-queue.js";
11
11
  import { tick } from "./watcher.js";
12
12
  import { shipRelease } from "./release.js";
13
- import { collectPRs, applyMergeOutcomes } from "./merges.js";
13
+ import { collectPRs, applyMergeOutcomes, closeHitlAndFreeParents, isHitlChild } from "./merges.js";
14
14
  import { startMcpServer } from "./mcp.js";
15
15
  import { startDispatchServer } from "./webhook/server.js";
16
16
  import { declaredFromEnv } from "./identity.js";
17
+ import { HUMAN_AGENT } from "./reserved.js";
17
18
  import { resolveDbPath } from "./paths.js";
18
19
 
19
20
  export { resolveDbPath };
@@ -48,6 +49,8 @@ const USAGE = `usage: winch <command>
48
49
  watch one watcher tick (JSON manifest on stdout)
49
50
  resume <taskId> [--actor <name>] resolve a human gate: blocked → ready
50
51
  next list the current ready queue
52
+ hitl [--status S] list the human-in-the-loop queue (PR/release/design children)
53
+ resolve <taskId> [--note N] human closes a HITL child; frees parked parents
51
54
  release-epic --epic <id> [--task ID] [--version V] [--base B]
52
55
  merge-detect [--dry-run] apply merged/closed PR outcomes
53
56
  webhook serve [--port N] [--host H] serve dispatch registration, recovery and the wake pump
@@ -117,7 +120,9 @@ export async function runCli(argv) {
117
120
  case "next": {
118
121
  const store = openStore();
119
122
  try {
120
- const rows = readyTasks(store, { limit: 20 });
123
+ // Human work lives in `winch hitl` — keep it out of the agent queue.
124
+ const rows = readyTasks(store, { limit: 20 })
125
+ .filter((r) => r.task.assignee_agent !== HUMAN_AGENT);
121
126
  console.log(JSON.stringify(
122
127
  rows.map((r) => ({ taskId: r.task.id, title: r.task.title, assigned: r.task.assignee_agent, story: r.story.id, epic: r.epic.id })),
123
128
  null, 2
@@ -128,6 +133,88 @@ export async function runCli(argv) {
128
133
  return;
129
134
  }
130
135
 
136
+ case "hitl": {
137
+ const { values } = parseArgs({
138
+ args: rest,
139
+ options: { status: { type: "string" }, config: { type: "string" } },
140
+ allowPositionals: true,
141
+ });
142
+ const store = openStore(loadConfig(values));
143
+ try {
144
+ const want = values.status ?? null;
145
+ const rows = store.item.list({ kind: "task" })
146
+ .filter((t) => isHitlChild(t))
147
+ .filter((t) => (want ? t.status === want : t.status !== "done" && t.status !== "cancelled"))
148
+ .map((t) => {
149
+ const artifacts = store.artifact.listFor(t.id);
150
+ const parents = store.dep.listIncoming(t.id)
151
+ .map((e) => store.task.get(e.from_id))
152
+ .filter(Boolean)
153
+ .map((p) => ({ id: p.id, title: p.title, status: p.status }));
154
+ // artifacts.uri is globally unique — a PR attached before spawn
155
+ // sits on the parent; surface both so the reviewer finds the link.
156
+ const parentUris = new Set(artifacts.map((a) => a.uri));
157
+ for (const p of store.dep.listIncoming(t.id)) {
158
+ for (const a of store.artifact.listFor(p.from_id)) {
159
+ if (!parentUris.has(a.uri)) {
160
+ artifacts.push({ ...a, via: p.from_id });
161
+ parentUris.add(a.uri);
162
+ }
163
+ }
164
+ }
165
+ return {
166
+ taskId: t.id,
167
+ title: t.title,
168
+ status: t.status,
169
+ acceptance: t.acceptance,
170
+ artifacts: artifacts.map((a) => ({ kind: a.kind, uri: a.uri, label: a.label, via: a.via })),
171
+ parents,
172
+ };
173
+ });
174
+ console.log(JSON.stringify(rows, null, 2));
175
+ } finally {
176
+ store.close();
177
+ }
178
+ return;
179
+ }
180
+
181
+ case "resolve": {
182
+ const { values, positionals } = parseArgs({
183
+ args: rest,
184
+ options: { note: { type: "string" }, config: { type: "string" } },
185
+ allowPositionals: true,
186
+ });
187
+ const taskId = positionals[0];
188
+ if (!taskId) fail("usage: winch resolve <taskId> [--note <text>]");
189
+ const store = openStore(loadConfig(values));
190
+ try {
191
+ const task = store.task.get(taskId);
192
+ if (!task) fail(`winch resolve: not found: ${taskId}`);
193
+ if (!isHitlChild(task)) {
194
+ fail(`winch resolve: ${taskId} is not a HITL child (assignee ${task.assignee_agent ?? "none"}) — only human-assigned review children resolve here`);
195
+ }
196
+ if (task.status === "done" || task.status === "cancelled") {
197
+ console.log(JSON.stringify({ ok: true, task: { id: task.id, status: task.status }, doneTasks: [], alreadyResolved: true }, null, 2));
198
+ return;
199
+ }
200
+ const note = values.note ?? "resolved by operator";
201
+ const out = closeHitlAndFreeParents(store, task.id, {
202
+ actor: "operator",
203
+ resultSummary: note,
204
+ note: `hitl resolved: ${note}`,
205
+ });
206
+ console.log(JSON.stringify({
207
+ ok: true,
208
+ task: { id: task.id, status: store.task.get(task.id)?.status },
209
+ doneTasks: out.doneTasks,
210
+ freedParents: out.resumed,
211
+ }, null, 2));
212
+ } finally {
213
+ store.close();
214
+ }
215
+ return;
216
+ }
217
+
131
218
  case "release-epic": {
132
219
  const { values } = parseArgs({
133
220
  args: rest,
package/src/config.js CHANGED
@@ -39,6 +39,11 @@ function parseInt(raw) {
39
39
  return Number(s);
40
40
  }
41
41
 
42
+ function parseKindList(raw) {
43
+ const toks = Array.isArray(raw) ? raw : String(raw ?? "").split(",");
44
+ return toks.map((t) => String(t ?? "").trim()).filter(Boolean);
45
+ }
46
+
42
47
  // key -> { env, parse, check }. parse normalizes (string|number|array) to the
43
48
  // stored shape; check rejects out-of-range values. Stored shapes are plain
44
49
  // JSON: a resolved config survives a round-trip through JSON by construction.
@@ -74,6 +79,7 @@ const SPEC = {
74
79
  noteReasonLimit: { env: "WINCH_NOTE_REASON_LIMIT", parse: parseInt, check: (v) => v > 0 },
75
80
  noteArtifactLimit: { env: "WINCH_NOTE_ARTIFACT_LIMIT", parse: parseInt, check: (v) => v > 0 },
76
81
  maxArtifacts: { env: "WINCH_MAX_ARTIFACTS", parse: parseInt, check: (v) => v > 0 },
82
+ hitlArtifactKinds: { env: "WINCH_HITL_ARTIFACT_KINDS", parse: parseKindList, check: (v) => Array.isArray(v) },
77
83
  };
78
84
 
79
85
  export const CONFIG_DEFAULTS = {
@@ -108,6 +114,7 @@ export const CONFIG_DEFAULTS = {
108
114
  noteReasonLimit: 1000,
109
115
  noteArtifactLimit: 500,
110
116
  maxArtifacts: 50,
117
+ hitlArtifactKinds: ["pr", "release", "design"],
111
118
  };
112
119
 
113
120
  export const CONFIG_ENV = Object.fromEntries(
package/src/merges.js CHANGED
@@ -4,6 +4,12 @@
4
4
  // Markers come from release PR bodies: `Backlog: <item-id>`, optional
5
5
  // `Backlog-Task: <task-id>`, optional `Release: vX.Y.Z`. gh reports state as
6
6
  // MERGED / CLOSED / OPEN — normalized here, callers pass raw values.
7
+ //
8
+ // HITL: a marker may name the parent or its human-review child. On MERGED,
9
+ // open HITL children close first, the PR attaches as a `pr` artifact, then
10
+ // waiting parents cascade to done once deps resolve.
11
+
12
+ import { depsResolved } from "./deps.js";
7
13
 
8
14
  export function parseMarkers(body = "") {
9
15
  const out = { epicId: null, taskId: null, version: null };
@@ -17,8 +23,91 @@ export function parseMarkers(body = "") {
17
23
  return out;
18
24
  }
19
25
 
26
+ export function isHitlChild(task) {
27
+ return !!task && task.assignee_agent === "human" && task.assignee_harness === "human_in_the_loop";
28
+ }
29
+
30
+ export function openHitlChildren(store, parentId) {
31
+ return store.dep.listOutgoing(parentId)
32
+ .map((e) => store.task.get(e.to_id))
33
+ .filter((c) => isHitlChild(c) && c.status !== "done" && c.status !== "cancelled");
34
+ }
35
+
36
+ export function hitlParents(store, childId) {
37
+ return store.dep.listIncoming(childId)
38
+ .map((e) => store.task.get(e.from_id))
39
+ .filter(Boolean);
40
+ }
41
+
42
+ function attachPrArtifact(store, itemId, pr, dryRun) {
43
+ const uri = pr.url;
44
+ if (!uri || dryRun) return;
45
+ store.artifact.add({
46
+ itemId,
47
+ kind: "pr",
48
+ uri,
49
+ label: `PR #${pr.number}`,
50
+ });
51
+ }
52
+
20
53
  /**
21
- * @param {Array<{number:number, state:string, title:string, body:string}>} prs
54
+ * Close a HITL child (or any task) and cascade parents that were parked on
55
+ * it: resume deps waits, then done any parent whose deps are now resolved
56
+ * and that is not mid-claim. Used by merge-detect and `winch resolve`.
57
+ */
58
+ export function closeHitlAndFreeParents(store, taskId, { actor = "system", resultSummary, note } = {}) {
59
+ const out = { doneTasks: [], resumed: [] };
60
+ const task = store.task.get(taskId);
61
+ if (!task) return out;
62
+ const children = openHitlChildren(store, task.id);
63
+ const parents = isHitlChild(task) ? hitlParents(store, task.id) : [];
64
+
65
+ for (const c of children) {
66
+ if (c.status !== "done" && c.status !== "cancelled") {
67
+ store.task.update(c.id, {
68
+ status: "done",
69
+ result_summary: resultSummary ?? `resolved by ${actor}`,
70
+ actor,
71
+ note: note ?? `hitl resolved: ${actor}`,
72
+ });
73
+ out.doneTasks.push(c.id);
74
+ }
75
+ }
76
+ if (task.status !== "done" && task.status !== "cancelled") {
77
+ store.task.update(task.id, {
78
+ status: "done",
79
+ result_summary: resultSummary ?? `resolved by ${actor}`,
80
+ actor,
81
+ note: note ?? `hitl resolved: ${actor}`,
82
+ });
83
+ out.doneTasks.push(task.id);
84
+ }
85
+ store.task.resumeDependencyWaits();
86
+
87
+ const waiting = new Map();
88
+ for (const p of parents) waiting.set(p.id, p);
89
+ for (const c of children) {
90
+ for (const p of hitlParents(store, c.id)) waiting.set(p.id, p);
91
+ }
92
+ for (const p of waiting.values()) {
93
+ const cur = store.task.get(p.id);
94
+ if (!cur || cur.status === "done" || cur.status === "cancelled" || cur.status === "in_progress") continue;
95
+ if (!depsResolved(store, cur.id)) continue;
96
+ store.task.update(cur.id, {
97
+ status: "done",
98
+ result_summary: resultSummary ?? `closed via HITL child ${task.id} (${actor})`,
99
+ actor,
100
+ note: note ?? `closed via HITL child: ${task.id}`,
101
+ });
102
+ out.doneTasks.push(cur.id);
103
+ store.task.resumeDependencyWaits();
104
+ out.resumed.push(cur.id);
105
+ }
106
+ return out;
107
+ }
108
+
109
+ /**
110
+ * @param {Array<{number:number, state:string, title:string, body:string, url?:string}>} prs
22
111
  * @param {{exec?: Function, cwd?: string, dryRun?: boolean}} opts — exec runs
23
112
  * the git tag when a Release marker lands; tests inject a recorder.
24
113
  * @returns summary of every transition applied (idempotent on re-run)
@@ -39,21 +128,65 @@ export function applyMergeOutcomes(store, prs, { exec = null, cwd = process.cwd(
39
128
 
40
129
  if (state === "MERGED") {
41
130
  if (task) {
42
- if (task.status !== "done") {
131
+ const children = openHitlChildren(store, task.id);
132
+ const parents = isHitlChild(task) ? hitlParents(store, task.id) : [];
133
+ const needsWork = task.status !== "done" || children.length > 0;
134
+ if (needsWork) {
43
135
  // A merge lands regardless of who holds the claim. When it takes
44
136
  // a task out from under a working agent, the note names the
45
137
  // displacement — the agent's next tool call would otherwise fail
46
138
  // with no account of why its task completed itself.
47
139
  const displaced = task.status === "in_progress" && task.assignee_agent ? ` (displaced ${task.assignee_agent})` : "";
48
140
  if (!dryRun) {
49
- store.task.update(task.id, {
50
- status: "done",
51
- result_summary: `merged via PR #${pr.number}: ${pr.title}`,
52
- actor: "merge-detector",
53
- note: `merged: PR #${pr.number}${displaced}`,
54
- });
141
+ // artifacts.uri is globally unique — one PR row, on the HITL
142
+ // child when one exists (the review unit), else the marked task.
143
+ attachPrArtifact(store, (children[0] ?? task).id, pr, dryRun);
144
+ for (const c of children) {
145
+ if (c.status !== "done") {
146
+ store.task.update(c.id, {
147
+ status: "done",
148
+ result_summary: `merged via PR #${pr.number}: ${pr.title}`,
149
+ actor: "merge-detector",
150
+ note: `merged: PR #${pr.number}`,
151
+ });
152
+ out.doneTasks.push(c.id);
153
+ }
154
+ }
155
+ if (task.status !== "done") {
156
+ store.task.update(task.id, {
157
+ status: "done",
158
+ result_summary: `merged via PR #${pr.number}: ${pr.title}`,
159
+ actor: "merge-detector",
160
+ note: `merged: PR #${pr.number}${displaced}`,
161
+ });
162
+ out.doneTasks.push(task.id);
163
+ }
164
+ store.task.resumeDependencyWaits();
165
+ // Parents that were parked on a HITL child close once the dep
166
+ // resolves — the human merge was the only remaining gate.
167
+ const waiting = new Map();
168
+ for (const p of parents) waiting.set(p.id, p);
169
+ for (const c of children) {
170
+ for (const p of hitlParents(store, c.id)) waiting.set(p.id, p);
171
+ }
172
+ for (const p of waiting.values()) {
173
+ const cur = store.task.get(p.id);
174
+ if (!cur || cur.status === "done" || cur.status === "cancelled" || cur.status === "in_progress") continue;
175
+ if (!depsResolved(store, cur.id)) continue;
176
+ store.task.update(cur.id, {
177
+ status: "done",
178
+ result_summary: `closed via HITL child (PR #${pr.number})`,
179
+ actor: "merge-detector",
180
+ note: `closed via HITL child: PR #${pr.number}`,
181
+ });
182
+ out.doneTasks.push(cur.id);
183
+ store.task.resumeDependencyWaits();
184
+ }
185
+ } else {
186
+ if (task.status !== "done") out.doneTasks.push(task.id);
187
+ for (const c of children) out.doneTasks.push(c.id);
188
+ for (const p of parents) out.doneTasks.push(p.id);
55
189
  }
56
- out.doneTasks.push(task.id);
57
190
  }
58
191
  }
59
192
  if (markers.epicId && markers.version) {
@@ -94,7 +227,8 @@ export function applyMergeOutcomes(store, prs, { exec = null, cwd = process.cwd(
94
227
  } else if (state === "CLOSED") {
95
228
  // Unmerged close = the work did not land. Anything mid-flight on that PR
96
229
  // returns to the queue for a fresh claim; 'done' stays done — a later
97
- // revert is a new ticket, not a rewrite of history.
230
+ // revert is a new ticket, not a rewrite of history. A HITL child stays
231
+ // ready (the human still owns it); a parent parked on deps stays parked.
98
232
  if (task) {
99
233
  const reopenable = task.status === "in_progress" || task.status === "review"
100
234
  || (task.status === "blocked" && task.gate_type);
@@ -104,7 +238,8 @@ export function applyMergeOutcomes(store, prs, { exec = null, cwd = process.cwd(
104
238
  const dissolved = task.status === "blocked" && task.gate_type;
105
239
  if (!dryRun) {
106
240
  store.task.update(task.id, {
107
- status: task.assignee_agent ? "ready" : "backlog", gate_type: null, blocked_at: null,
241
+ status: task.assignee_agent ? "ready" : "backlog",
242
+ gate_type: null, blocked_at: null,
108
243
  actor: "merge-detector",
109
244
  note: dissolved ? `gate dissolved: closed unmerged PR #${pr.number}` : `closed unmerged: PR #${pr.number}`,
110
245
  });
@@ -125,7 +260,7 @@ export function applyMergeOutcomes(store, prs, { exec = null, cwd = process.cwd(
125
260
  export function collectPRs({ exec, cwd = process.cwd(), limit = 100 } = {}) {
126
261
  const raw = exec(
127
262
  "gh",
128
- ["pr", "list", "--state", "merged", "--state", "closed", "--limit", String(limit), "--json", "number,title,body,state"],
263
+ ["pr", "list", "--state", "merged", "--state", "closed", "--limit", String(limit), "--json", "number,title,body,state,url"],
129
264
  { cwd, encoding: "utf8" }
130
265
  );
131
266
  return JSON.parse(raw);
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" }),
@@ -2,6 +2,8 @@
2
2
  // optionally to the attempt that produced them.
3
3
 
4
4
  import { newArtifactId } from "../ids.js";
5
+ import { addDep } from "../deps.js";
6
+ import { HUMAN_AGENT, HUMAN_HARNESS } from "../reserved.js";
5
7
 
6
8
  export function createArtifactApi({ core }) {
7
9
  const { db, now } = core;
@@ -22,3 +24,72 @@ export function createArtifactApi({ core }) {
22
24
  },
23
25
  };
24
26
  }
27
+
28
+ export function inferArtifactKind(uri) {
29
+ if (typeof uri === "string" && /github\.com\/[^/\s]+\/[^/\s]+\/pull\/\d+/.test(uri)) return "pr";
30
+ return "link";
31
+ }
32
+
33
+ /**
34
+ * Store an artifact; when its kind is human-gated (config hitlArtifactKinds),
35
+ * open the HITL child: a ready task assigned to the reserved human pair,
36
+ * a depends-on edge from the parent, and a deps wait that parks the parent
37
+ * until the child resolves. Idempotent per (parent, kind, uri).
38
+ */
39
+ export function attachArtifact(store, { itemId, attemptId = null, kind = "link", uri, sha256 = null, label = null }) {
40
+ const row = store.artifact.add({ itemId, attemptId, kind, uri, sha256, label });
41
+ const hitlKinds = store.config?.hitlArtifactKinds ?? [];
42
+ if (!hitlKinds.includes(kind)) return row;
43
+
44
+ const parent = store.task.get(itemId);
45
+ if (!parent) return row;
46
+
47
+ const childKey = `hitl:${kind}:${uri}`;
48
+ const parentId = parent.story_id ?? parent.parent_id ?? parent.id;
49
+ let child = store.item.byChild(parentId, childKey, 0);
50
+ if (!child) {
51
+ child = store.task.create({
52
+ storyId: parentId,
53
+ title: `Review & merge: ${label ?? `#${kind} artifact`}`,
54
+ description:
55
+ `Human-in-the-loop artifact (${kind}): ${uri}\n\n` +
56
+ `Parent task: ${parent.id} — ${parent.title}\n` +
57
+ `Close this child once the artifact is resolved (PR merged, release approved, design accepted). The parent cannot close until then.`,
58
+ status: "ready",
59
+ assigned: HUMAN_AGENT,
60
+ assigneeHarness: HUMAN_HARNESS,
61
+ executionKind: "gate",
62
+ childKey,
63
+ });
64
+ }
65
+
66
+ const edge = store.dep.get(parent.id, child.id);
67
+ if (!edge) {
68
+ const r = addDep(store, parent.id, child.id);
69
+ if (r.ok) {
70
+ store.event.append({
71
+ itemId: parent.id,
72
+ fromStatus: parent.status,
73
+ toStatus: parent.status,
74
+ actor: "system",
75
+ note: `dep: ${parent.id} depends on HITL ${child.id} (${kind}: ${uri})`,
76
+ });
77
+ }
78
+ }
79
+
80
+ const st = store.state.get(parent.id);
81
+ const alreadyWaiting = st?.state_json?.wait?.kind === "deps";
82
+ if (!alreadyWaiting && ["backlog", "ready", "in_progress"].includes(parent.status)) {
83
+ try {
84
+ store.task.blockOnDeps({
85
+ id: parent.id,
86
+ childId: child.id,
87
+ actor: "system",
88
+ note: `waiting on HITL child ${child.id}`,
89
+ });
90
+ } catch {
91
+ // status raced away — the dep edge alone still gates claim/close
92
+ }
93
+ }
94
+ return row;
95
+ }
@@ -38,6 +38,7 @@ import { createDeliveryApi } from "./delivery.js";
38
38
  import { createDispatchEventApi } from "./dispatch-events.js";
39
39
  import { observe } from "../webhook/core.js";
40
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
+ }
@@ -300,7 +300,22 @@ export const TOOL_DEFS = [
300
300
  heartbeat: { type: "boolean", description: "Refresh liveness (default true)." },
301
301
  progressSummary: { type: "string", description: "One-line progress note for the audit trail." },
302
302
  comment: { type: "string", description: "Freeform note appended as an audit event." },
303
- addArtifact: { type: "string", description: "Artifact path/URL produced so far; recorded as an audit event and carried into downstream handoffs." },
303
+ addArtifact: {
304
+ description: "Artifact path/URL produced so far; recorded as an audit event and carried into downstream handoffs. String URI or {uri, kind?, label?}. Kinds in config hitlArtifactKinds (default pr/release/design) spawn the human review child.",
305
+ anyOf: [
306
+ { type: "string" },
307
+ {
308
+ type: "object",
309
+ properties: {
310
+ uri: { type: "string" },
311
+ kind: { type: "string" },
312
+ label: { type: "string" },
313
+ },
314
+ required: ["uri"],
315
+ },
316
+ ],
317
+ },
318
+ addArtifactKind: { type: "string", description: "Override artifact kind (e.g. pr). Defaults to inference from the URI." },
304
319
  },
305
320
  },
306
321
  },
@@ -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);