hive-tasks 1.2.0 → 1.5.0

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
@@ -4,7 +4,22 @@ import path from "node:path";
4
4
  import { git, out } from "./git.js";
5
5
  import { ensureState, repoInfo } from "./repo.js";
6
6
  import { listRaw, mutate, readTask } from "./store.js";
7
- import { create, isReady, isReclaimable, order, transition } from "./task.js";
7
+ import { create, isReady, isReclaimable, order, reopenPatch, transition } from "./task.js";
8
+ import {
9
+ advanceStage,
10
+ currentStage,
11
+ failStage,
12
+ isStaged,
13
+ matchesRole,
14
+ normalizeStages,
15
+ resetStage,
16
+ stageIndex,
17
+ stageRole,
18
+ stageStatePatch,
19
+ stageView,
20
+ stagesFromFlags,
21
+ } from "./stage.js";
22
+ import { resolveRole } from "./role.js";
8
23
  import { addVerdict, claimLeases, parseTtl, readMode, releaseLeases, toKey } from "./lease.js";
9
24
  import { append } from "./events.js";
10
25
 
@@ -15,10 +30,11 @@ const USAGE = [
15
30
  "",
16
31
  "USAGE",
17
32
  " hive-tasks init create .hive/ and the AGENTS.md section",
18
- " hive-tasks add --title T [--role R] [--scope P]... [--after ID]... [--tag T] [--priority N]",
19
- " [--goal G] [--acceptance CMD]",
33
+ " hive-tasks add --title T [--role R] [--scope P]... [--after ID]... [--review-of ID]",
34
+ " [--tag T] [--priority N] [--goal G] [--acceptance CMD]",
35
+ " [--stage ROLE[:ACCEPTANCE]]... [--stages FILE]",
20
36
  " hive-tasks list [--json] [--state S] [--role R]",
21
- " hive-tasks show <id> [--json]",
37
+ " hive-tasks show <id> [--json] card plus the resolved role source",
22
38
  " hive-tasks ready [--json] [--limit N] [--role R]",
23
39
  " hive-tasks next [--role R] [--json] the single best candidate",
24
40
  " hive-tasks claim <id> --agent A [--ttl 5m] card CAS, then hive leases",
@@ -26,8 +42,12 @@ const USAGE = [
26
42
  " hive-tasks plan --file plan.json create a whole DAG in one transaction",
27
43
  " hive-tasks done <id> [--sha S] [--verdict pass|fail] [--verify]",
28
44
  " hive-tasks fail <id> --reason R",
29
- " hive-tasks retry <id>",
45
+ " hive-tasks retry <id> [--stage KEY]",
30
46
  " hive-tasks block <id> --reason R | unblock <id>",
47
+ " hive-tasks reopen <id> [--reason R] [--agent A] [--stage KEY]",
48
+ " any state back to pending, attempt+1; a staged card",
49
+ " resets to KEY (default the first stage)",
50
+ " hive-tasks rm <id> [--force] [--json] delete a card; a claimed card needs --force",
31
51
  "",
32
52
  "ENVIRONMENT",
33
53
  " HIVE_AGENT=name identity used for claims",
@@ -45,17 +65,20 @@ function value(argv, index, flag) {
45
65
  }
46
66
 
47
67
  function parse(argv) {
48
- const out = { args: [], scopes: [], after: [], tags: [], json: false, reason: null, agent: null, ttl: null, verdict: null, sha: null, state: null, role: null, limit: null, title: null, goal: null, priority: 0, force: false, acceptance: null, verify: false, file: null };
68
+ const out = { args: [], scopes: [], after: [], tags: [], stageArgs: [], json: false, reason: null, agent: null, ttl: null, verdict: null, sha: null, state: null, role: null, limit: null, title: null, goal: null, priority: 0, force: false, acceptance: null, verify: false, file: null, stagesFile: null, reviewOf: null };
49
69
  for (let i = 0; i < argv.length; i++) {
50
70
  const arg = argv[i];
51
71
  if (arg === "--json") out.json = true;
52
72
  else if (arg === "--force") out.force = true;
53
73
  else if (arg === "--scope") out.scopes.push(value(argv, i++, arg));
54
74
  else if (arg === "--after") out.after.push(value(argv, i++, arg));
75
+ else if (arg === "--review-of") out.reviewOf = value(argv, i++, arg);
55
76
  else if (arg === "--tag") out.tags.push(value(argv, i++, arg));
56
77
  else if (arg === "--acceptance") out.acceptance = value(argv, i++, arg);
57
78
  else if (arg === "--verify") out.verify = true;
58
79
  else if (arg === "--file") out.file = value(argv, i++, arg);
80
+ else if (arg === "--stages") out.stagesFile = value(argv, i++, arg);
81
+ else if (arg === "--stage") out.stageArgs.push(value(argv, i++, arg));
59
82
  else if (arg === "--reason") out.reason = value(argv, i++, arg);
60
83
  else if (arg === "--agent") out.agent = value(argv, i++, arg);
61
84
  else if (arg === "--ttl") out.ttl = value(argv, i++, arg);
@@ -79,6 +102,19 @@ function identity(repo, explicit) {
79
102
  return name;
80
103
  }
81
104
 
105
+ const SUMMARY_MAX = 120;
106
+
107
+ /** One-line reason summary stored on the card that is reopened by a failed review. */
108
+ function summarize(text) {
109
+ const flat = String(text || "").replace(/\s+/g, " ").trim();
110
+ return flat.length > SUMMARY_MAX ? flat.slice(0, SUMMARY_MAX - 1) + "…" : flat;
111
+ }
112
+
113
+ function reviewFailureReason(reason) {
114
+ const detail = summarize(reason);
115
+ return detail ? "test failed: " + detail : "test failed";
116
+ }
117
+
82
118
  function board(repo) {
83
119
  return listRaw(repo).map((entry) => entry.value);
84
120
  }
@@ -87,41 +123,79 @@ function byId(tasks) {
87
123
  return new Map(tasks.map((task) => [task.id, task]));
88
124
  }
89
125
 
126
+ /** The target key of a retry/reopen --stage flag (the last one wins). */
127
+ function stageTarget(options) {
128
+ return options.stageArgs.length ? options.stageArgs[options.stageArgs.length - 1] : null;
129
+ }
130
+
90
131
  function readyList(repo, tasks, { role } = {}) {
91
132
  const free = readMode(repo) === "free";
92
133
  const map = byId(tasks);
93
134
  return tasks
94
- .filter((task) => (!role || task.role === role) && isReady(task, map, { modeFree: free }))
135
+ .filter((task) => matchesRole(task, role) && isReady(task, map, { modeFree: free }))
95
136
  .sort(order);
96
137
  }
97
138
 
98
- function publishPresence(repo, { agent, task, state, files }) {
99
- const key = toKey(agent);
100
- const ref = "refs/hive/v1/board/" + key + "/__key__";
101
- const value = { v: 1, agent, task: task ? task.id : "", state, files: files || [], updatedAt: new Date().toISOString(), host: "hive-tasks", pid: process.pid };
102
- const blob = out(["hash-object", "-w", "--stdin"], { cwd: repo.top, input: JSON.stringify(value) });
103
- const current = git(["rev-parse", "--verify", "--quiet", ref], { cwd: repo.top, allowFail: true }).stdout.trim();
104
- git(["update-ref", ref, blob, current || "0".repeat(blob.length)], { cwd: repo.top, allowFail: true });
139
+ /** JSON/print view of a card: stages, stage and stageState are always present. */
140
+ function viewTask(task) {
141
+ return { ...task, ...stageView(task) };
105
142
  }
106
143
 
107
- function printTask(task, json) {
108
- if (json) return process.stdout.write(JSON.stringify(task, null, 2) + "\n");
144
+ function printTask(task, json, extra = {}, extraLines = []) {
145
+ if (json) return process.stdout.write(JSON.stringify({ ...viewTask(task), ...extra }, null, 2) + "\n");
109
146
  const indent = " ";
110
147
  process.stdout.write(task.id + " [" + task.state + "] " + task.title + "\n");
111
148
  process.stdout.write(indent + "role: " + task.role + " owner: " + (task.owner || "-") + " attempt: " + task.attempt + "\n");
149
+ if (isStaged(task)) {
150
+ const stage = currentStage(task);
151
+ const parts = ["stage: " + task.stage + " (" + task.stageState + ") stage-role: " + (stage ? stage.role : "-")];
152
+ if (stage && stage.acceptance) parts.push("acceptance: " + stage.acceptance);
153
+ process.stdout.write(indent + parts.join(" ") + "\n");
154
+ if (task.stages.length > 1) {
155
+ process.stdout.write(indent + "chain: " + task.stages.map((entry) => entry.key + ":" + entry.state).join(" -> ") + "\n");
156
+ }
157
+ }
112
158
  if (task.scope.length) process.stdout.write(indent + "scope: " + task.scope.join(", ") + "\n");
113
159
  if (task.after.length) process.stdout.write(indent + "after: " + task.after.join(", ") + "\n");
160
+ if (task.reviewOf) process.stdout.write(indent + "review-of: " + task.reviewOf + "\n");
114
161
  if (task.goal) process.stdout.write(indent + "goal: " + task.goal + "\n");
162
+ for (const line of extraLines) process.stdout.write(indent + line + "\n");
163
+ }
164
+
165
+ function readStagesFile(file) {
166
+ let raw;
167
+ try {
168
+ raw = fs.readFileSync(file, "utf8");
169
+ } catch {
170
+ throw new Error("could not read stages file: " + file);
171
+ }
172
+ let parsed;
173
+ try {
174
+ parsed = JSON.parse(raw);
175
+ } catch {
176
+ throw new Error("stages file is not valid JSON: " + file);
177
+ }
178
+ if (!Array.isArray(parsed)) throw new Error("stages file must be a JSON array");
179
+ return parsed;
180
+ }
181
+
182
+ function publishPresence(repo, { agent, task, state, files }) {
183
+ const key = toKey(agent);
184
+ const ref = "refs/hive/v1/board/" + key + "/__key__";
185
+ const value = { v: 1, agent, task: task ? task.id : "", state, files: files || [], updatedAt: new Date().toISOString(), host: "hive-tasks", pid: process.pid };
186
+ const blob = out(["hash-object", "-w", "--stdin"], { cwd: repo.top, input: JSON.stringify(value) });
187
+ const current = git(["rev-parse", "--verify", "--quiet", ref], { cwd: repo.top, allowFail: true }).stdout.trim();
188
+ git(["update-ref", ref, blob, current || "0".repeat(blob.length)], { cwd: repo.top, allowFail: true });
115
189
  }
116
190
 
117
191
  function run(argv) {
118
192
  const command = argv[0];
119
193
  const options = parse(argv.slice(1));
120
- const repo = repoInfo(process.cwd());
121
-
122
194
  if (!command || command === "-h" || command === "--help" || command === "help") return process.stdout.write(USAGE + "\n");
123
195
  if (command === "-V" || command === "--version" || command === "version") return process.stdout.write(VERSION + "\n");
124
196
 
197
+ const repo = repoInfo(process.cwd());
198
+
125
199
  if (command === "init") {
126
200
  ensureState(repo);
127
201
  const file = path.join(repo.top, "AGENTS.md");
@@ -142,17 +216,23 @@ function run(argv) {
142
216
  const keys = new Map();
143
217
  const drafts = plan.map((entry) => {
144
218
  if (!entry || !entry.title) fail("every plan entry needs a title", 2);
145
- const task = create({
146
- title: entry.title,
147
- goal: entry.goal,
148
- role: entry.role,
149
- scope: entry.scope || [],
150
- after: [],
151
- priority: entry.priority,
152
- tags: entry.tags || [],
153
- acceptance: entry.acceptance || "",
154
- createdBy: options.agent || process.env.HIVE_AGENT || "planner",
155
- });
219
+ let task;
220
+ try {
221
+ task = create({
222
+ title: entry.title,
223
+ goal: entry.goal,
224
+ role: entry.role,
225
+ scope: entry.scope || [],
226
+ after: [],
227
+ priority: entry.priority,
228
+ tags: entry.tags || [],
229
+ acceptance: entry.acceptance || "",
230
+ createdBy: options.agent || process.env.HIVE_AGENT || "planner",
231
+ stages: entry.stages,
232
+ });
233
+ } catch (error) {
234
+ fail(error.message, 2);
235
+ }
156
236
  if (entry.key) keys.set(entry.key, task.id);
157
237
  return { entry, task };
158
238
  });
@@ -188,18 +268,116 @@ function run(argv) {
188
268
  return;
189
269
  }
190
270
 
271
+ if (command === "reopen") {
272
+ const id = options.args[0];
273
+ if (!id) fail("reopen needs a task id", 2);
274
+ const agent = options.agent || process.env.HIVE_AGENT || "unknown";
275
+ const reason = options.reason || "reopened";
276
+ const target = stageTarget(options);
277
+ const current = readTask(repo, id);
278
+ if (!current) fail("no such task: " + id, 2);
279
+ if (target && !isStaged(current)) fail("--stage only applies to a card with stages", 2);
280
+ if (target && isStaged(current) && stageIndex(current, target) < 0) fail("no such stage: " + target, 2);
281
+
282
+ // Legacy cards keep the idempotent no-op. A staged card always resets to
283
+ // the requested stage (default the first), so a chain can be re-run.
284
+ if (!isStaged(current) && current.state === "pending") {
285
+ append(repo, { actor: agent, kind: "reopen", task: id, reason, noop: true });
286
+ return printTask(current, options.json);
287
+ }
288
+
289
+ let previous = null;
290
+ let reopened = null;
291
+ const result = mutate(repo, (tasks) => {
292
+ previous = null;
293
+ reopened = null;
294
+ const task = byId(tasks).get(id);
295
+ if (!task) throw new Error("no such task: " + id);
296
+ if (!isStaged(task) && task.state === "pending") return null;
297
+ previous = task;
298
+ if (isStaged(task)) {
299
+ const reset = resetStage(task, target);
300
+ reopened = transition(task, "pending", { ...reopenPatch(task, reason), ...reset.patch });
301
+ } else {
302
+ reopened = transition(task, "pending", reopenPatch(task, reason));
303
+ }
304
+ return tasks.map((entry) => (entry.id === id ? reopened : entry));
305
+ });
306
+ if (!result.ok) fail("could not reopen " + id);
307
+
308
+ if (!reopened) {
309
+ append(repo, { actor: agent, kind: "reopen", task: id, reason, noop: true });
310
+ return printTask(readTask(repo, id), options.json);
311
+ }
312
+
313
+ // A claimed card may still hold hive leases; release exactly the claim we reset.
314
+ if (previous.state === "claimed") releaseLeases(repo, { paths: previous.scope, agent: previous.owner || agent });
315
+ append(repo, { actor: agent, kind: "reopen", task: id, from: previous.state, reason, attempt: reopened.attempt, stage: isStaged(reopened) ? reopened.stage : undefined });
316
+ return printTask(reopened, options.json);
317
+ }
318
+
319
+ if (command === "rm") {
320
+ const id = options.args[0];
321
+ if (!id) fail("rm needs a task id", 2);
322
+ const agent = options.agent || process.env.HIVE_AGENT || "unknown";
323
+ const current = readTask(repo, id);
324
+ if (!current) fail("no such task: " + id, 2);
325
+ if (current.state === "claimed" && !options.force) {
326
+ fail("task " + id + " is claimed by " + (current.owner || "another agent") + "; release or reopen it first, or use --force", 2);
327
+ }
328
+
329
+ // The blob is removed by the same CAS that reads the board, so a card that
330
+ // moved meanwhile (another writer, a concurrent claim) is re-checked
331
+ // instead of racing the tree write.
332
+ let deleted = null;
333
+ try {
334
+ const result = mutate(repo, (tasks) => {
335
+ const task = byId(tasks).get(id);
336
+ if (!task) throw new Error("no such task: " + id);
337
+ if (task.state === "claimed" && !options.force) {
338
+ throw new Error("task " + id + " is claimed by " + (task.owner || "another agent") + "; release or reopen it first, or use --force");
339
+ }
340
+ deleted = task;
341
+ return tasks.filter((entry) => entry.id !== id);
342
+ });
343
+ if (!result.ok) fail("could not delete " + id + " (too much contention)");
344
+ } catch (error) {
345
+ fail(error.message, 2);
346
+ }
347
+
348
+ // --force deletes a claimed card only after releasing exactly the leases
349
+ // that claim holds, so a forced delete cannot strand them.
350
+ if (deleted.state === "claimed") releaseLeases(repo, { paths: deleted.scope, agent: deleted.owner || agent });
351
+ append(repo, { actor: agent, kind: "task_delete", task: id, id, state: deleted.state });
352
+ if (options.json) return process.stdout.write(JSON.stringify({ ...viewTask(deleted), deleted: true }, null, 2) + "\n");
353
+ return process.stdout.write(id + " deleted [" + deleted.state + "] " + deleted.title + "\n");
354
+ }
355
+
191
356
  if (command === "add") {
192
357
  if (!options.title) fail("--title is required", 2);
358
+ if (options.reviewOf && !readTask(repo, options.reviewOf)) fail("no such task: " + options.reviewOf, 2);
359
+ if (options.stageArgs.length && options.stagesFile) fail("use --stage or --stages, not both", 2);
360
+ let stages = null;
361
+ try {
362
+ if (options.stagesFile) stages = normalizeStages(readStagesFile(options.stagesFile));
363
+ else if (options.stageArgs.length) stages = stagesFromFlags(options.stageArgs);
364
+ } catch (error) {
365
+ fail(error.message, 2);
366
+ }
367
+ const after = [...options.after];
368
+ if (options.reviewOf && !after.includes(options.reviewOf)) after.push(options.reviewOf);
193
369
  const task = create({
194
370
  title: options.title,
195
371
  goal: options.goal,
196
372
  role: options.role,
197
373
  scope: options.scopes,
198
- after: options.after,
374
+ after,
199
375
  priority: options.priority,
200
376
  tags: options.tags,
201
377
  acceptance: options.acceptance || "",
378
+ reviewOf: options.reviewOf,
202
379
  createdBy: options.agent || process.env.HIVE_AGENT || "unknown",
380
+ stages,
203
381
  });
204
382
  const result = mutate(repo, (tasks) => {
205
383
  const ids = byId(tasks);
@@ -207,7 +385,7 @@ function run(argv) {
207
385
  return [...tasks, task];
208
386
  });
209
387
  if (!result.ok) fail("could not write the task board (too much contention)");
210
- append(repo, { actor: task.createdBy, kind: "task_add", task: task.id });
388
+ append(repo, { actor: task.createdBy, kind: "task_add", task: task.id, stages: isStaged(task) ? task.stages.length : undefined });
211
389
  return printTask(task, options.json);
212
390
  }
213
391
 
@@ -216,12 +394,18 @@ function run(argv) {
216
394
  const selected = command === "ready"
217
395
  ? readyList(repo, tasks, { role: options.role })
218
396
  : tasks
219
- .filter((task) => (!options.state || task.state === options.state) && (!options.role || task.role === options.role))
397
+ .filter((task) => (!options.state || task.state === options.state) && matchesRole(task, options.role))
220
398
  .sort(order);
221
399
  const limited = options.limit ? selected.slice(0, options.limit) : selected;
222
- if (options.json) return process.stdout.write(JSON.stringify(limited, null, 2) + "\n");
400
+ if (options.json) {
401
+ const rows = limited.map((task) => {
402
+ const view = viewTask(task);
403
+ return command === "ready" ? { ...view, readyRole: stageRole(task) } : view;
404
+ });
405
+ return process.stdout.write(JSON.stringify(rows, null, 2) + "\n");
406
+ }
223
407
  if (limited.length === 0) return process.stdout.write(command === "ready" ? "Nothing ready.\n" : "No tasks.\n");
224
- for (const task of limited) process.stdout.write(task.id.padEnd(34) + task.state.padEnd(9) + task.role.padEnd(11) + task.title + "\n");
408
+ for (const task of limited) process.stdout.write(task.id.padEnd(34) + task.state.padEnd(9) + stageRole(task).padEnd(11) + task.title + "\n");
225
409
  return;
226
410
  }
227
411
 
@@ -232,7 +416,7 @@ function run(argv) {
232
416
  else process.stdout.write("Nothing ready.\n");
233
417
  return;
234
418
  }
235
- return printTask(first, options.json);
419
+ return printTask(first, options.json, { readyRole: stageRole(first) });
236
420
  }
237
421
 
238
422
  if (command === "show") {
@@ -240,7 +424,10 @@ function run(argv) {
240
424
  if (!id) fail("show needs a task id", 2);
241
425
  const task = readTask(repo, id);
242
426
  if (!task) fail("no such task: " + id, 2);
243
- return printTask(task, options.json);
427
+ const active = stageRole(task);
428
+ const resolved = resolveRole(repo, active, isStaged(task) ? task.stage : {});
429
+ const lines = ["role-source: " + resolved.source + " (adapter " + resolved.adapter + ", model " + (resolved.model || "-") + ")"];
430
+ return printTask(task, options.json, { roleSource: resolved.source, roleResolved: resolved }, lines);
244
431
  }
245
432
 
246
433
  if (command === "claim") {
@@ -248,6 +435,7 @@ function run(argv) {
248
435
  if (!id) fail("claim needs a task id", 2);
249
436
  const agent = identity(repo, options.agent);
250
437
  const ttlMs = parseTtl(options.ttl);
438
+ const stageOf = (task) => (isStaged(task) ? " at stage " + task.stage : "");
251
439
 
252
440
  const preview = readTask(repo, id);
253
441
  if (!preview) fail("no such task: " + id, 2);
@@ -255,7 +443,10 @@ function run(argv) {
255
443
  fail("mode is freeze: only fix-tagged cards may be claimed (use --force to override)", 2);
256
444
  }
257
445
  const reclaim = isReclaimable(preview);
258
- if (preview.state !== "pending" && !reclaim) fail("task " + id + " is " + preview.state, 2);
446
+ if (preview.state !== "pending" && !reclaim) fail("task " + id + " is " + preview.state + stageOf(preview), 2);
447
+ if (isStaged(preview) && preview.stageState !== "pending" && !(preview.stageState === "claimed" && reclaim)) {
448
+ fail("task " + id + " stage " + preview.stage + " is " + preview.stageState, 2);
449
+ }
259
450
  if (!isReady(preview, byId(board(repo)), { modeFree: true })) fail("task " + id + " is not ready (dependencies or mode)", 2);
260
451
 
261
452
  let claimed = null;
@@ -264,14 +455,20 @@ function run(argv) {
264
455
  const map = byId(tasks);
265
456
  const task = map.get(id);
266
457
  if (!task) throw new Error("no such task: " + id);
267
- if (task.state !== "pending" && !isReclaimable(task)) throw new Error("task " + id + " is " + task.state);
458
+ const canReclaim = isReclaimable(task);
459
+ if (task.state !== "pending" && !canReclaim) throw new Error("task " + id + " is " + task.state + stageOf(task));
460
+ if (isStaged(task) && task.stageState !== "pending" && !(task.stageState === "claimed" && canReclaim)) {
461
+ throw new Error("task " + id + " stage " + task.stage + " is " + task.stageState);
462
+ }
268
463
  if (!isReady(task, map, { modeFree: true })) throw new Error("task " + id + " is not ready (dependencies or mode)");
269
- claimed = transition(task, "claimed", {
464
+ const patch = {
270
465
  owner: agent,
271
466
  attempt: (task.attempt || 0) + 1,
272
467
  reason: null,
273
468
  claimedUntil: new Date(Date.now() + ttlMs).toISOString(),
274
- });
469
+ ...stageStatePatch(task, "claimed"),
470
+ };
471
+ claimed = transition(task, "claimed", patch);
275
472
  return tasks.map((entry) => (entry.id === id ? claimed : entry));
276
473
  });
277
474
  } catch (error) {
@@ -283,13 +480,16 @@ function run(argv) {
283
480
  const leases = claimLeases(repo, { paths: claimed.scope, agent, ttlMs, taskId: claimed.id });
284
481
  if (leases.granted === false) {
285
482
  const holder = leases.denied[0];
286
- mutate(repo, (tasks) => tasks.map((entry) => (entry.id === id ? transition(entry, "pending", { owner: null, reason: "lease held by " + holder.agent }) : entry)));
483
+ mutate(repo, (tasks) => tasks.map((entry) => {
484
+ if (entry.id !== id) return entry;
485
+ return transition(entry, "pending", { owner: null, claimedUntil: null, reason: "lease held by " + (holder ? holder.agent : "another agent"), ...stageStatePatch(entry, "pending") });
486
+ }));
287
487
  const detail = holder ? " (" + holder.agent + " holds " + holder.key + ")" : "";
288
488
  fail("could not claim " + id + ": path busy" + detail, 2);
289
489
  }
290
490
 
291
491
  publishPresence(repo, { agent, task: claimed, state: "working", files: claimed.scope });
292
- append(repo, { actor: agent, kind: "task_claim", task: claimed.id, attempt: claimed.attempt });
492
+ append(repo, { actor: agent, kind: "task_claim", task: claimed.id, attempt: claimed.attempt, stage: isStaged(claimed) ? claimed.stage : undefined });
293
493
  return printTask(claimed, options.json);
294
494
  }
295
495
 
@@ -299,39 +499,145 @@ function run(argv) {
299
499
  const agent = options.agent || process.env.HIVE_AGENT || "unknown";
300
500
  const current = readTask(repo, id);
301
501
  if (!current) fail("no such task: " + id, 2);
502
+ const target = stageTarget(options);
503
+ if (target && command !== "retry") fail("--stage only applies to retry and reopen", 2);
504
+ if (target && !isStaged(current)) fail("--stage only applies to a card with stages", 2);
505
+ if (target && isStaged(current) && stageIndex(current, target) < 0) fail("no such stage: " + target, 2);
302
506
 
303
507
  if ((command === "done" || command === "fail") && current.state !== "claimed") fail("task " + id + " is " + current.state + ", not claimed", 2);
508
+ if ((command === "done" || command === "fail") && isStaged(current) && current.stageState !== "claimed") fail("task " + id + " stage " + current.stage + " is " + current.stageState + ", not claimed", 2);
304
509
  if (command === "retry" && current.state !== "failed" && current.state !== "blocked") fail("task " + id + " is " + current.state + ", not failed or blocked", 2);
305
510
  if (command === "unblock" && current.state !== "blocked") fail("task " + id + " is " + current.state + ", not blocked", 2);
306
511
 
307
512
  if (command === "done" && options.verify) {
308
- if (!current.acceptance) fail("task " + id + " has no acceptance command", 2);
309
- const run = spawnSync("sh", ["-c", current.acceptance], { cwd: repo.top, encoding: "utf8" });
310
- if (run.stdout) process.stdout.write(run.stdout);
311
- if (run.stderr) process.stderr.write(run.stderr);
312
- if (run.status !== 0) fail("acceptance failed for " + id, 1);
513
+ const acceptance = isStaged(current) ? ((currentStage(current) || {}).acceptance || current.acceptance) : current.acceptance;
514
+ if (!acceptance) fail("task " + id + " has no acceptance command", 2);
515
+ const runVerify = spawnSync("sh", ["-c", acceptance], { cwd: repo.top, encoding: "utf8" });
516
+ if (runVerify.stdout) process.stdout.write(runVerify.stdout);
517
+ if (runVerify.stderr) process.stderr.write(runVerify.stderr);
518
+ if (runVerify.status !== 0) fail("acceptance failed for " + id, 1);
313
519
  }
314
520
 
315
521
  const head = git(["rev-parse", "--verify", "--quiet", "HEAD"], { cwd: repo.top, allowFail: true }).stdout.trim();
316
- const targetState = command === "done" ? "done" : command === "fail" ? "failed" : command === "block" ? "blocked" : "pending";
317
- const patch = {
318
- owner: null,
319
- verdict: command === "done" ? (options.verdict || null) : current.verdict,
320
- reason: options.reason || null,
321
- resultCommit: command === "done" ? (options.sha || head || null) : current.resultCommit,
322
- claimedUntil: null,
323
- };
324
-
325
- const result = mutate(repo, (tasks) => tasks.map((entry) => (entry.id === id ? transition(entry, targetState, patch) : entry)));
522
+
523
+ // Build the transition from the card as it is inside the CAS, so two
524
+ // writers cannot advance the same stage twice.
525
+ function planCommand(task) {
526
+ if (command === "done") {
527
+ if (isStaged(task)) {
528
+ if (task.stageState !== "claimed") throw new Error("task " + id + " stage " + task.stage + " is " + task.stageState + ", not claimed");
529
+ const advanced = advanceStage(task);
530
+ const events = [{ kind: "stage_done", stage: task.stage }];
531
+ if (advanced.nextStage) events.push({ kind: "stage_advanced", from: task.stage, stage: advanced.nextStage });
532
+ return {
533
+ targetState: advanced.finished ? "done" : "pending",
534
+ nextStage: advanced.nextStage,
535
+ patch: {
536
+ owner: null,
537
+ claimedUntil: null,
538
+ reason: null,
539
+ resultCommit: options.sha || head || null,
540
+ verdict: advanced.finished ? (options.verdict || null) : task.verdict,
541
+ ...advanced.patch,
542
+ },
543
+ events,
544
+ };
545
+ }
546
+ return {
547
+ targetState: "done",
548
+ nextStage: null,
549
+ patch: { owner: null, claimedUntil: null, reason: options.reason || null, verdict: options.verdict || null, resultCommit: options.sha || head || null },
550
+ events: [],
551
+ };
552
+ }
553
+ if (command === "fail") {
554
+ if (isStaged(task)) {
555
+ const failed = failStage(task, "failed");
556
+ const events = [{ kind: "stage_failed", stage: failed.from, state: "failed" }];
557
+ if (failed.rewound) events.push({ kind: "stage_rewound", from: failed.from, stage: failed.to, attempt: (task.attempt || 0) + 1 });
558
+ return {
559
+ targetState: failed.rewound ? "pending" : "failed",
560
+ nextStage: null,
561
+ patch: { owner: null, claimedUntil: null, reason: options.reason || null, ...failed.patch },
562
+ events,
563
+ };
564
+ }
565
+ return { targetState: "failed", nextStage: null, patch: { owner: null, claimedUntil: null, reason: options.reason || null }, events: [] };
566
+ }
567
+ if (command === "block") {
568
+ if (isStaged(task)) {
569
+ const blocked = failStage(task, "blocked");
570
+ const events = blocked.rewound ? [{ kind: "stage_rewound", from: blocked.from, stage: blocked.to, attempt: (task.attempt || 0) + 1 }] : [];
571
+ return {
572
+ targetState: blocked.rewound ? "pending" : "blocked",
573
+ nextStage: null,
574
+ patch: { owner: null, claimedUntil: null, reason: options.reason || null, ...blocked.patch },
575
+ events,
576
+ };
577
+ }
578
+ return { targetState: "blocked", nextStage: null, patch: { owner: null, claimedUntil: null, reason: options.reason || null }, events: [] };
579
+ }
580
+ if (command === "retry") {
581
+ if (isStaged(task)) {
582
+ const reset = resetStage(task, target || task.stage);
583
+ return { targetState: "pending", nextStage: null, patch: { owner: null, claimedUntil: null, reason: options.reason || null, ...reset.patch }, events: [] };
584
+ }
585
+ return { targetState: "pending", nextStage: null, patch: { owner: null, claimedUntil: null, reason: options.reason || null }, events: [] };
586
+ }
587
+ // unblock
588
+ if (isStaged(task)) {
589
+ return { targetState: "pending", nextStage: null, patch: { owner: null, claimedUntil: null, reason: options.reason || null, ...stageStatePatch(task, "pending") }, events: [] };
590
+ }
591
+ return { targetState: "pending", nextStage: null, patch: { owner: null, claimedUntil: null, reason: options.reason || null }, events: [] };
592
+ }
593
+
594
+ // A review card that fails sends its upstream card back to pending, so a
595
+ // rejected implementation becomes claimable again with a fresh attempt.
596
+ const upstreamReason = reviewFailureReason(options.reason);
597
+ let upstreamReopened = null;
598
+ let outcome = null;
599
+ const result = mutate(repo, (tasks) => {
600
+ const map = byId(tasks);
601
+ const task = map.get(id);
602
+ if (!task) throw new Error("no such task: " + id);
603
+ outcome = planCommand(task);
604
+ const next = transition(task, outcome.targetState, outcome.patch);
605
+ upstreamReopened = null;
606
+ if (command === "fail" && outcome.targetState === "failed" && task.reviewOf) {
607
+ const upstream = map.get(task.reviewOf);
608
+ if (upstream && upstream.state === "done") {
609
+ upstreamReopened = transition(upstream, "pending", reopenPatch(upstream, upstreamReason));
610
+ }
611
+ }
612
+ return tasks.map((entry) => {
613
+ if (entry.id === id) return next;
614
+ if (upstreamReopened && entry.id === upstreamReopened.id) return upstreamReopened;
615
+ return entry;
616
+ });
617
+ });
326
618
  if (!result.ok) fail("could not update " + id);
327
619
 
328
620
  if (current.state === "claimed") releaseLeases(repo, { paths: current.scope, agent: current.owner || agent });
329
621
  if (command === "done" && options.verdict && options.sha) {
330
622
  addVerdict(repo, { sha: options.sha, result: options.verdict });
331
623
  }
332
- publishPresence(repo, { agent, task: current, state: targetState === "done" ? "idle" : "working", files: [] });
333
- append(repo, { actor: agent, kind: "task_" + command, task: id, reason: options.reason || undefined });
334
- return printTask(readTask(repo, id), options.json);
624
+ publishPresence(repo, { agent, task: current, state: outcome.targetState === "done" ? "idle" : "working", files: [] });
625
+ append(repo, { actor: agent, kind: "task_" + command, task: id, reason: options.reason || undefined, stage: isStaged(current) ? current.stage : undefined });
626
+ for (const event of outcome.events) append(repo, { actor: agent, task: id, ...event });
627
+ if (command === "fail" && current.reviewOf && outcome.targetState === "failed") {
628
+ if (upstreamReopened) {
629
+ append(repo, { actor: agent, kind: "reopen", task: upstreamReopened.id, from: "done", reason: upstreamReason, attempt: upstreamReopened.attempt, via: "review_failed" });
630
+ }
631
+ append(repo, { actor: agent, kind: "review_failed", task: id, reviewOf: current.reviewOf, reopened: Boolean(upstreamReopened), reason: options.reason || undefined });
632
+ }
633
+
634
+ const finalCard = readTask(repo, id);
635
+ const lines = [];
636
+ if (command === "done" && isStaged(current)) {
637
+ lines.push(outcome.nextStage ? "next stage: " + outcome.nextStage + " (card stays pending)" : "stage chain complete");
638
+ }
639
+ const extra = command === "done" ? { nextStage: outcome.nextStage } : {};
640
+ return printTask(finalCard, options.json, extra, lines);
335
641
  }
336
642
 
337
643
  if (command === "stats") {