@igorjpimenta/winch 2026.11.23-beta.2 → 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/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
@@ -161,7 +162,7 @@ checkpoints on turn end, resumes from the latest checkpoint, receives dispatch
161
162
  wakes at `POST /api/winch/dispatch`, and reconciles `in_progress` attempts
162
163
  after a restart.
163
164
 
164
- openclaw plugins install npm:@igorjpimenta/winch-openclaw@latest
165
+ openclaw plugins install npm:@igorjpimenta/winch-openclaw@beta
165
166
 
166
167
  One daemon for all harnesses (recommended):
167
168
 
@@ -215,7 +216,7 @@ canonical form for new setup:
215
216
  }
216
217
  }
217
218
  },
218
- "plugins": ["@igorjpimenta/winch-opencode"]
219
+ "plugins": ["@igorjpimenta/winch-opencode@beta"]
219
220
  }
220
221
 
221
222
  Or via the CLI:
@@ -240,9 +241,9 @@ loopback endpoint and starts a claimable session with `opencode run`.
240
241
  | `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
242
  | `backlog_get` | read an epic, story or task by id - acceptance, results, artifacts, dependencies, readiness |
242
243
  | `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 |
244
+ | `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
245
  | `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 |
246
+ | `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
247
  | `backlog_block` / `backlog_resume` | open a human gate (with optional `gateType` and `blockedBy` dep edge) and resolve it (`actor` optional) |
247
248
 
248
249
  ## Task lifecycle
@@ -261,6 +262,23 @@ work, but neither value is a caller identity, and agent dispatchers never wake
261
262
  it. A block parks it until an operator resumes it; the last task closes its
262
263
  story, and the last story closes the epic.
263
264
 
265
+ Human-gated artifacts use that same pair. Attaching an artifact whose kind is
266
+ in `hitlArtifactKinds` (`WINCH_HITL_ARTIFACT_KINDS`, default
267
+ `pr,release,design`) while a task is claimed:
268
+
269
+ 1. stores the artifact (URI unique across the store);
270
+ 2. spawns a ready child assigned to `human`/`human_in_the_loop`
271
+ (`execution_kind: gate`, keyed `hitl:<kind>:<uri>` for idempotency);
272
+ 3. adds `parent → child` on the dependency DAG and parks the parent in a
273
+ deps wait — claim and `backlog_done` refuse until the child resolves.
274
+
275
+ The PR body carries `Backlog:` / `Backlog-Task:` markers; the claim handoff's
276
+ `receiverPrompt` states the protocol (attach while `in_progress`, never
277
+ self-complete while a child is open). Resolution is human-only: merge the PR
278
+ and `merge-detect` closes the child and frees the parent, or run
279
+ `winch resolve <childId>` for non-PR kinds. `winch hitl` lists the human
280
+ queue; `winch next` excludes it.
281
+
264
282
  ```mermaid
265
283
  flowchart LR
266
284
  Z[backlog] -->|assign| A[ready]
@@ -299,9 +317,11 @@ Claim leases, attempt caps, and gate rules: [lifecycle](docs/lifecycle.md).
299
317
  | `serve --mcp http --port N [--host H]` | serve the same tools over Streamable HTTP (shared daemon) |
300
318
  | `watch` | one watcher tick (JSON manifest on stdout) |
301
319
  | `resume <taskId> [--actor <name>]` | resolve a human gate: blocked to ready |
302
- | `next` | list the current ready queue |
320
+ | `next` | list the current ready queue (agent work only — human HITL children are excluded) |
321
+ | `hitl [--status S]` | list the human-in-the-loop queue (PR/release/design review children, with artifacts and parents) |
322
+ | `resolve <taskId> [--note N]` | operator closes a HITL child; frees parents parked on it |
303
323
  | `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 |
324
+ | `merge-detect [--dry-run]` | apply merged/closed PR outcomes (closes HITL children and cascades parents) |
305
325
  | `webhook bearer` | generate a dispatch bearer |
306
326
  | `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
327
  | `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.23-beta.3",
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.23-beta.3",
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.23-beta.3",
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
+ }
@@ -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
  },
@@ -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
@@ -57,6 +57,15 @@ export function renderReceiverPrompt({ task, story, epic, artifacts }) {
57
57
  `## Acceptance\n${story?.acceptance ?? "(none recorded)"}`,
58
58
  `## Upstream artifacts\n${artifacts.length ? artifacts.map((a) => `- ${a}`).join("\n") : "(none yet)"}`,
59
59
  `## Parent\n${epic?.title ?? "(none)"} — ${story?.title ?? "(none)"}`,
60
+ `## PR protocol (mandatory when opening a pull request)\n` +
61
+ `1. PR body MUST contain:\n` +
62
+ ` Backlog: <epic-id>\n` +
63
+ ` Backlog-Task: <this task id>\n` +
64
+ `2. Attach the PR while in_progress — never at done:\n` +
65
+ ` backlog_update({ taskId, addArtifact: "<pr-url>", addArtifactKind: "pr" })\n` +
66
+ ` This spawns the human review child and parks this task on it.\n` +
67
+ `3. Never call backlog_done while a HITL child is open — the human merge\n` +
68
+ ` resolves the child; merge-detect then closes this task.`,
60
69
  ];
61
70
  return parts.filter(Boolean).join("\n\n");
62
71
  }