@igorjpimenta/winch 2026.11.23-beta.2 → 2026.11.24-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -17,6 +17,7 @@ contract itself is the only integration surface.
17
17
  - **Dependency DAG** - forward-only deps, cycle-checked, cancelled deps count as resolved.
18
18
  - **Webhook wakes** - every work-making transition fans out to consumer webhooks; subscribers wake agents, no polling.
19
19
  - **Human gates** - block/resume with gate types; one resume per gate, actor-checked.
20
+ - **Human-gated artifacts** - attaching a `pr`/`release`/`design` artifact spawns a review child for the reserved `human` pair and parks the parent until it resolves.
20
21
  - **Content-addressed evidence** - artifacts recorded on close, carried into downstream handoffs.
21
22
 
22
23
  It is local-first and harness-neutral: OpenCode, OpenClaw and future harnesses
@@ -128,6 +129,27 @@ is the single scheduler:
128
129
  and ring `/dispatch/notify` on `WINCH_DISPATCH_URL`; the interval pump is
129
130
  recovery, not routing.
130
131
 
132
+ **Prerequisite: one subscription per harness, before anything can wake.**
133
+ The pump only offers queued admissions to harnesses present in the
134
+ `webhooks` table, so assigning with no matching subscription succeeds but
135
+ never delivers — the admissions sit `queued` with no attempts while the
136
+ dispatch server looks healthy. `backlog_plan` reports this as
137
+ `warning: { code: "no_route" }` when no subscription is registered at all,
138
+ and `backlog_assign` reports it per harness. Register the receiver first:
139
+
140
+ ```sh
141
+ winch webhook bearer # prints a receiver token, store it for the receiver
142
+ winch webhook register --topic dispatch --harness <harness> \
143
+ --url <receiver-url> --bearer <token>
144
+ ```
145
+
146
+ Manual rows are never swept; `winch webhook revoke --topic dispatch --id <id>`
147
+ removes one. Harness plugins register themselves instead (below), but only if
148
+ `WINCH_DISPATCH_URL` matches the port `winch webhook serve` is actually
149
+ listening on — the default is `38293`, and a `serve --port 38493` with
150
+ `WINCH_DISPATCH_URL` still on `38293` leaves `webhooks` empty while both
151
+ processes run.
152
+
131
153
  Adapters register one route per `WINCH_CONSUMER_ID` (default
132
154
  `harness:hostname`), with `WINCH_EXECUTOR_ID` as the live instance and a
133
155
  `WINCH_WEBHOOK_BEARER` generated by `winch webhook bearer`. Registration is a
@@ -161,7 +183,7 @@ checkpoints on turn end, resumes from the latest checkpoint, receives dispatch
161
183
  wakes at `POST /api/winch/dispatch`, and reconciles `in_progress` attempts
162
184
  after a restart.
163
185
 
164
- openclaw plugins install npm:@igorjpimenta/winch-openclaw@latest
186
+ openclaw plugins install npm:@igorjpimenta/winch-openclaw@beta
165
187
 
166
188
  One daemon for all harnesses (recommended):
167
189
 
@@ -215,7 +237,7 @@ canonical form for new setup:
215
237
  }
216
238
  }
217
239
  },
218
- "plugins": ["@igorjpimenta/winch-opencode"]
240
+ "plugins": ["@igorjpimenta/winch-opencode@beta"]
219
241
  }
220
242
 
221
243
  Or via the CLI:
@@ -240,9 +262,9 @@ loopback endpoint and starts a claimable session with `opencode run`.
240
262
  | `backlog_delegate` | split work from a task to another worker (agent or human); each child becomes its own card, the parent parks in `blocked` until all children close, then returns to `ready` for the accountable. `childKey`/`visitSeq` make retries idempotent and start new rounds |
241
263
  | `backlog_get` | read an epic, story or task by id - acceptance, results, artifacts, dependencies, readiness |
242
264
  | `backlog_claim` | claim one task by id, or the highest-priority ready task when the id is omitted; atomic CAS under a lease |
243
- | `backlog_update` | heartbeat and append progress, comment or artifact to a claimed task; pass the `leaseEpoch` for wake-owned attempts |
265
+ | `backlog_update` | heartbeat and append progress, comment or artifact to a claimed task; pass the `leaseEpoch` for wake-owned attempts. `addArtifact` accepts a URI or `{uri, kind?, label?}`; kinds in `hitlArtifactKinds` (default `pr`/`release`/`design`) spawn the human review child |
244
266
  | `backlog_accept_wake` | take the single-flight execution lease for a story/append/review wake before planning |
245
- | `backlog_done` | close a claimed task with a result; closing the last task closes its story, and the last story closes the epic and wakes the agent that planned it |
267
+ | `backlog_done` | close a claimed task with a result; refuses while deps are unmet (`deps_unmet`) or when a HITL artifact is only now being attached (`hitl_at_done`); closing the last task closes its story, and the last story closes the epic and wakes the agent that planned it |
246
268
  | `backlog_block` / `backlog_resume` | open a human gate (with optional `gateType` and `blockedBy` dep edge) and resolve it (`actor` optional) |
247
269
 
248
270
  ## Task lifecycle
@@ -261,6 +283,23 @@ work, but neither value is a caller identity, and agent dispatchers never wake
261
283
  it. A block parks it until an operator resumes it; the last task closes its
262
284
  story, and the last story closes the epic.
263
285
 
286
+ Human-gated artifacts use that same pair. Attaching an artifact whose kind is
287
+ in `hitlArtifactKinds` (`WINCH_HITL_ARTIFACT_KINDS`, default
288
+ `pr,release,design`) while a task is claimed:
289
+
290
+ 1. stores the artifact (URI unique across the store);
291
+ 2. spawns a ready child assigned to `human`/`human_in_the_loop`
292
+ (`execution_kind: gate`, keyed `hitl:<kind>:<uri>` for idempotency);
293
+ 3. adds `parent → child` on the dependency DAG and parks the parent in a
294
+ deps wait — claim and `backlog_done` refuse until the child resolves.
295
+
296
+ The PR body carries `Backlog:` / `Backlog-Task:` markers; the claim handoff's
297
+ `receiverPrompt` states the protocol (attach while `in_progress`, never
298
+ self-complete while a child is open). Resolution is human-only: merge the PR
299
+ and `merge-detect` closes the child and frees the parent, or run
300
+ `winch resolve <childId>` for non-PR kinds. `winch hitl` lists the human
301
+ queue; `winch next` excludes it.
302
+
264
303
  ```mermaid
265
304
  flowchart LR
266
305
  Z[backlog] -->|assign| A[ready]
@@ -299,9 +338,11 @@ Claim leases, attempt caps, and gate rules: [lifecycle](docs/lifecycle.md).
299
338
  | `serve --mcp http --port N [--host H]` | serve the same tools over Streamable HTTP (shared daemon) |
300
339
  | `watch` | one watcher tick (JSON manifest on stdout) |
301
340
  | `resume <taskId> [--actor <name>]` | resolve a human gate: blocked to ready |
302
- | `next` | list the current ready queue |
341
+ | `next` | list the current ready queue (agent work only — human HITL children are excluded) |
342
+ | `hitl [--status S]` | list the human-in-the-loop queue (PR/release/design review children, with artifacts and parents) |
343
+ | `resolve <taskId> [--note N]` | operator closes a HITL child; frees parents parked on it |
303
344
  | `release-epic --epic <id> [--task ID] [--version V] [--base B]` | release notes + branch/PR with backlog markers |
304
- | `merge-detect [--dry-run]` | apply merged/closed PR outcomes |
345
+ | `merge-detect [--dry-run]` | apply merged/closed PR outcomes (closes HITL children and cascades parents) |
305
346
  | `webhook bearer` | generate a dispatch bearer |
306
347
  | `webhook register --topic T [--harness H] [--executor E] --url U [--id I] [--bearer B]` | register or replace a webhook subscription; a bearer is generated and printed when omitted |
307
348
  | `webhook list [--topic T] [--harness H]` | list webhook subscriptions with bearer redacted |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@igorjpimenta/winch",
3
- "version": "2026.11.23-beta.2",
3
+ "version": "2026.11.24-beta.1",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -75,3 +75,20 @@ Environment:
75
75
  | `WINCH_DISPATCH_TOKEN` | management bearer for register/recover/notify; required for a non-loopback winch bind |
76
76
 
77
77
  Requires OpenClaw ≥ 2026.5.18 (declared as `openclaw.install.minHostVersion`).
78
+
79
+ ## Human artifacts (HITL)
80
+
81
+ This plugin adds no HITL logic — the server owns it. What an OpenClaw session
82
+ needs to know:
83
+
84
+ - **Agents** get the PR protocol from the claim handoff's `receiverPrompt`:
85
+ put `Backlog:` / `Backlog-Task:` in the PR body, attach with
86
+ `backlog_update({ addArtifact: "<pr-url>", addArtifactKind: "pr" })` while
87
+ `in_progress`, and never `backlog_done` while a review child is open.
88
+ - **Operators** list the human queue with `winch hitl` (not `winch next`,
89
+ which excludes `human`). Resolve a non-PR child with
90
+ `winch resolve <taskId> --note "…"`. For PR children, merge on GitHub —
91
+ `merge-detect` closes the child and frees the parent within its schedule.
92
+ - **Wakes never target humans**: the reserved `human`/`human_in_the_loop`
93
+ pair is excluded from agent wake lists; the gateway will not start a
94
+ session for a review child.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@igorjpimenta/winch-openclaw",
3
- "version": "2026.11.19-beta.1",
3
+ "version": "2026.11.24-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",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@igorjpimenta/winch-opencode",
3
- "version": "2026.11.23-beta.1",
3
+ "version": "2026.11.24-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/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);
@@ -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
+ }
@@ -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,
@@ -300,7 +302,22 @@ export const TOOL_DEFS = [
300
302
  heartbeat: { type: "boolean", description: "Refresh liveness (default true)." },
301
303
  progressSummary: { type: "string", description: "One-line progress note for the audit trail." },
302
304
  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." },
305
+ addArtifact: {
306
+ 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.",
307
+ anyOf: [
308
+ { type: "string" },
309
+ {
310
+ type: "object",
311
+ properties: {
312
+ uri: { type: "string" },
313
+ kind: { type: "string" },
314
+ label: { type: "string" },
315
+ },
316
+ required: ["uri"],
317
+ },
318
+ ],
319
+ },
320
+ addArtifactKind: { type: "string", description: "Override artifact kind (e.g. pr). Defaults to inference from the URI." },
304
321
  },
305
322
  },
306
323
  },
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,7 +1,8 @@
1
1
  // report.js — work reporting and gates: update, done, block, resume.
2
- import { addDep } from "../deps.js";
2
+ import { addDep, depsResolved } from "../deps.js";
3
3
  import { identitySessionKey } from "../identity.js";
4
4
  import { ok, err, clampNote } from "./shared.js";
5
+ import { attachArtifact, inferArtifactKind } from "../store/artifacts.js";
5
6
 
6
7
  function checkAttemptLease(store, task, args) {
7
8
  if (!args?.attemptId) {
@@ -40,7 +41,7 @@ export function createReportTools({ store, logger }) {
40
41
  const noteParts = [];
41
42
  if (args?.progressSummary) noteParts.push(`progress: ${clampNote(args.progressSummary, cfg.noteProgressLimit)}`);
42
43
  if (args?.comment) noteParts.push(`comment: ${clampNote(args.comment, cfg.noteProgressLimit)}`);
43
- if (args?.addArtifact) noteParts.push(`artifact: ${clampNote(args.addArtifact, cfg.noteArtifactLimit)}`);
44
+ if (args?.addArtifact) noteParts.push(`artifact: ${clampNote(typeof args.addArtifact === "string" ? args.addArtifact : args.addArtifact?.uri, cfg.noteArtifactLimit)}`);
44
45
  if (noteParts.length) {
45
46
  store.event.append({
46
47
  itemId: task.id,
@@ -51,6 +52,22 @@ export function createReportTools({ store, logger }) {
51
52
  note: noteParts.join(" | "),
52
53
  });
53
54
  }
55
+ if (args?.addArtifact) {
56
+ const raw = args.addArtifact;
57
+ const uri = typeof raw === "string" ? raw : raw?.uri;
58
+ if (uri) {
59
+ const kind = args.addArtifactKind
60
+ ?? (typeof raw === "object" && raw.kind ? raw.kind : null)
61
+ ?? inferArtifactKind(uri);
62
+ attachArtifact(store, {
63
+ itemId: task.id,
64
+ attemptId: task.attempt_id,
65
+ kind,
66
+ uri: String(uri),
67
+ label: (typeof raw === "object" && raw.label) || null,
68
+ });
69
+ }
70
+ }
54
71
  const fresh = store.task.get(task.id);
55
72
  return ok(JSON.stringify({ ok: true, task: { id: fresh.id, status: fresh.status, last_heartbeat: fresh.last_heartbeat, attempt_count: fresh.attempt_count } }), { status: "ok", taskId: task.id, agentId });
56
73
  } catch (e) {
@@ -70,12 +87,50 @@ export function createReportTools({ store, logger }) {
70
87
  try {
71
88
  const summary = clampNote(args.resultSummary, cfg.noteResultLimit);
72
89
  const artifacts = Array.isArray(args.artifacts) ? args.artifacts.slice(0, cfg.maxArtifacts) : [];
73
- const resultSummary = artifacts.length ? `${summary}\n\nartifacts: ${artifacts.join(", ")}` : summary;
90
+ const hitlKinds = cfg.hitlArtifactKinds ?? [];
91
+ for (const a of artifacts) {
92
+ const uri = typeof a === "string" ? a : a?.uri;
93
+ const kind = (typeof a === "object" && a.kind) || inferArtifactKind(uri);
94
+ if (hitlKinds.includes(kind)) {
95
+ return err(
96
+ `HITL artifact (${kind}) must be attached while in_progress via backlog_update addArtifact — it opens the human review child that gates this close: ${uri}`,
97
+ "hitl_at_done",
98
+ { taskId: task.id },
99
+ );
100
+ }
101
+ }
102
+ if (!depsResolved(store, task.id)) {
103
+ const openDeps = store.dep.listOutgoing(task.id)
104
+ .map((e) => e.to_id)
105
+ .filter((id) => {
106
+ const d = store.item.get(id, { includeDeleted: true });
107
+ return d && d.status !== "done" && d.status !== "cancelled";
108
+ });
109
+ return err(
110
+ `${task.id} cannot close: unresolved deps ${openDeps.join(", ")}`,
111
+ "deps_unmet",
112
+ { taskId: task.id, openDeps },
113
+ );
114
+ }
115
+ const artifactUris = artifacts
116
+ .map((a) => (typeof a === "string" ? a : a?.uri))
117
+ .filter(Boolean);
118
+ const resultSummary = artifactUris.length ? `${summary}\n\nartifacts: ${artifactUris.join(", ")}` : summary;
74
119
  const updated = store.task.update(task.id, {
75
120
  status: "done", result_summary: resultSummary, actor: agentId, note: "done",
76
121
  sessionKey, harness: identity.harness, session: identity.session, agentId,
77
122
  });
78
- for (const uri of artifacts) store.artifact.add({ itemId: task.id, attemptId: updated.attempt_id, kind: "link", uri });
123
+ for (const a of artifacts) {
124
+ const uri = typeof a === "string" ? a : a?.uri;
125
+ if (!uri) continue;
126
+ store.artifact.add({
127
+ itemId: task.id,
128
+ attemptId: updated.attempt_id,
129
+ kind: (typeof a === "object" && a.kind) || inferArtifactKind(uri),
130
+ uri,
131
+ label: (typeof a === "object" && a.label) || null,
132
+ });
133
+ }
79
134
  store.task.resumeDependencyWaits();
80
135
  // Close upward, one level at a time: a story closes when its last task
81
136
  // does, and the epic closes only when its last story does. The epic
@@ -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) {
@@ -57,6 +97,15 @@ export function renderReceiverPrompt({ task, story, epic, artifacts }) {
57
97
  `## Acceptance\n${story?.acceptance ?? "(none recorded)"}`,
58
98
  `## Upstream artifacts\n${artifacts.length ? artifacts.map((a) => `- ${a}`).join("\n") : "(none yet)"}`,
59
99
  `## Parent\n${epic?.title ?? "(none)"} — ${story?.title ?? "(none)"}`,
100
+ `## PR protocol (mandatory when opening a pull request)\n` +
101
+ `1. PR body MUST contain:\n` +
102
+ ` Backlog: <epic-id>\n` +
103
+ ` Backlog-Task: <this task id>\n` +
104
+ `2. Attach the PR while in_progress — never at done:\n` +
105
+ ` backlog_update({ taskId, addArtifact: "<pr-url>", addArtifactKind: "pr" })\n` +
106
+ ` This spawns the human review child and parks this task on it.\n` +
107
+ `3. Never call backlog_done while a HITL child is open — the human merge\n` +
108
+ ` resolves the child; merge-detect then closes this task.`,
60
109
  ];
61
110
  return parts.filter(Boolean).join("\n\n");
62
111
  }