hive-tasks 1.8.1 → 1.10.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
@@ -3,8 +3,8 @@ import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { git, out } from "./git.js";
5
5
  import { ensureState, repoInfo } from "./repo.js";
6
- import { listRaw, mutate, readTask } from "./store.js";
7
- import { create, isDraft, isReady, isReclaimable, order, reopenPatch, transition } from "./task.js";
6
+ import { DEFAULT_PAGE_LIMIT, listRaw, mutate, readTask, readTaskPage, summarizeIndex } from "./store.js";
7
+ import { create, isDraft, isReady, isReclaimable, isSuperseded, now, order, reopenPatch, transition } from "./task.js";
8
8
  import {
9
9
  advanceStage,
10
10
  currentStage,
@@ -20,7 +20,7 @@ import {
20
20
  stagesFromFlags,
21
21
  } from "./stage.js";
22
22
  import { resolveRole } from "./role.js";
23
- import { addVerdict, claimLeases, parseTtl, readMode, releaseLeases, toKey } from "./lease.js";
23
+ import { addVerdict, claimLeases, listLeases, parseTtl, readMode, releaseLeases, toKey } from "./lease.js";
24
24
  import { append } from "./events.js";
25
25
 
26
26
  const VERSION = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
@@ -33,7 +33,17 @@ const USAGE = [
33
33
  " hive-tasks add --title T (--acceptance CMD | --draft) [--role R] [--scope P]...",
34
34
  " [--after ID]... [--review-of ID] [--tag T] [--priority N] [--goal G]",
35
35
  " [--stage ROLE[:ACCEPTANCE]]... [--stages FILE]",
36
- " hive-tasks list [--json] [--state S] [--role R]",
36
+ " hive-tasks edit <id> [--title T] [--scope-add P]... [--scope-remove P]...",
37
+ " [--acceptance CMD] [--priority N] [--after-set ID,ID] [--tag +T|-T]... [--role R]",
38
+ " change only the fields you pass",
39
+ " hive-tasks split <id> --into '<json array>' [--keep] [--reason R] [--json]",
40
+ " replace a task with finer entries; the old",
41
+ " task is superseded and points at the first subtask",
42
+ " hive-tasks supersede <id> --reason R [--replaced-by ID]",
43
+ " retire a task without done/failed; never dispatched",
44
+ " hive-tasks list [--json] [--state S] [--role R] [--limit N] [--cursor C]",
45
+ " a page of tasks newest stateChangedAt first",
46
+ " hive-tasks counts [--json] per-state counts + the oldest pending task",
37
47
  " hive-tasks show <id> [--json] card plus the resolved role source",
38
48
  " hive-tasks ready [--json] [--limit N] [--role R]",
39
49
  " hive-tasks next [--role R] [--json] the single best candidate",
@@ -51,8 +61,11 @@ const USAGE = [
51
61
  "",
52
62
  "CARD RULES",
53
63
  " add requires --acceptance unless --draft is passed; done --verify runs the command.",
64
+ " edit refuses an empty --acceptance; pass --acceptance - to clear it on a draft card.",
54
65
  " --draft stores draft: true: the card stays on the board but is never ready, next or",
55
66
  " claimable. Draft is a flag, not a state: pending/claimed/done/failed are unchanged.",
67
+ " superseded is a flag too: edit --superseded/--no-superseded on a pending or failed",
68
+ " task, or supersede in any state. A superseded task is never ready or claimable.",
56
69
  "",
57
70
  "ENVIRONMENT",
58
71
  " HIVE_AGENT=name identity used for claims",
@@ -70,13 +83,21 @@ function value(argv, index, flag) {
70
83
  }
71
84
 
72
85
  function parse(argv) {
73
- 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, draft: false };
86
+ const out = { args: [], scopes: [], scopeAdd: [], scopeRemove: [], after: [], afterSet: null, tags: [], stageArgs: [], into: [], json: false, keep: false, reason: null, agent: null, ttl: null, verdict: null, sha: null, state: null, role: null, limit: null, cursor: null, title: null, goal: null, priority: null, force: false, acceptance: null, verify: false, file: null, stagesFile: null, reviewOf: null, replacedBy: null, supersedeFlag: null, draft: false };
74
87
  for (let i = 0; i < argv.length; i++) {
75
88
  const arg = argv[i];
76
89
  if (arg === "--json") out.json = true;
77
90
  else if (arg === "--force") out.force = true;
78
91
  else if (arg === "--scope") out.scopes.push(value(argv, i++, arg));
92
+ else if (arg === "--scope-add") out.scopeAdd.push(value(argv, i++, arg));
93
+ else if (arg === "--scope-remove") out.scopeRemove.push(value(argv, i++, arg));
79
94
  else if (arg === "--after") out.after.push(value(argv, i++, arg));
95
+ else if (arg === "--after-set") out.afterSet = value(argv, i++, arg);
96
+ else if (arg === "--into") out.into.push(value(argv, i++, arg));
97
+ else if (arg === "--keep") out.keep = true;
98
+ else if (arg === "--replaced-by") out.replacedBy = value(argv, i++, arg);
99
+ else if (arg === "--superseded") out.supersedeFlag = true;
100
+ else if (arg === "--no-superseded") out.supersedeFlag = false;
80
101
  else if (arg === "--review-of") out.reviewOf = value(argv, i++, arg);
81
102
  else if (arg === "--tag") out.tags.push(value(argv, i++, arg));
82
103
  else if (arg === "--acceptance") out.acceptance = value(argv, i++, arg);
@@ -93,6 +114,7 @@ function parse(argv) {
93
114
  else if (arg === "--state") out.state = value(argv, i++, arg);
94
115
  else if (arg === "--role") out.role = value(argv, i++, arg);
95
116
  else if (arg === "--limit") out.limit = Number(value(argv, i++, arg));
117
+ else if (arg === "--cursor") out.cursor = Number(value(argv, i++, arg));
96
118
  else if (arg === "--title") out.title = value(argv, i++, arg);
97
119
  else if (arg === "--goal") out.goal = value(argv, i++, arg);
98
120
  else if (arg === "--priority") out.priority = Number(value(argv, i++, arg));
@@ -102,6 +124,11 @@ function parse(argv) {
102
124
  return out;
103
125
  }
104
126
 
127
+ function eventActor(fallback) {
128
+ const value = (process.env.HIVE_EVENT_ACTOR || '').trim();
129
+ return value !== '' ? value : (fallback || 'unknown');
130
+ }
131
+
105
132
  function identity(repo, explicit) {
106
133
  const name = explicit || process.env.HIVE_AGENT || git(["config", "--get", "hive.agent"], { cwd: repo.top, allowFail: true }).stdout.trim();
107
134
  if (!name) fail("an identity is required (--agent, HIVE_AGENT, or git config hive.agent)", 2);
@@ -126,6 +153,12 @@ function draftClaimMessage(id) {
126
153
  return "task " + id + " is a draft and cannot be claimed (rm it and re-add with --acceptance)";
127
154
  }
128
155
 
156
+ /** A superseded task keeps its lane but is never dispatched again. */
157
+ function supersededClaimMessage(task) {
158
+ const replaced = task.replacedBy ? " (replaced by " + task.replacedBy + ")" : "";
159
+ return "task " + task.id + " is superseded" + replaced + " and cannot be claimed";
160
+ }
161
+
129
162
  function board(repo) {
130
163
  return listRaw(repo).map((entry) => entry.value);
131
164
  }
@@ -134,6 +167,193 @@ function byId(tasks) {
134
167
  return new Map(tasks.map((task) => [task.id, task]));
135
168
  }
136
169
 
170
+ /** Parse --after-set: a comma list of dependency ids; an empty value clears it. */
171
+ function parseAfterSet(text) {
172
+ const ids = [];
173
+ for (const part of String(text).split(",")) {
174
+ const id = part.trim();
175
+ if (id !== "" && !ids.includes(id)) ids.push(id);
176
+ }
177
+ return ids;
178
+ }
179
+
180
+ /** True when following `afterIds` from the edited task can reach the task itself. */
181
+ function dependencyCycle(map, taskId, afterIds) {
182
+ const seen = new Set();
183
+ const stack = [...afterIds];
184
+ while (stack.length > 0) {
185
+ const id = stack.pop();
186
+ if (id === taskId) return true;
187
+ if (seen.has(id)) continue;
188
+ seen.add(id);
189
+ const task = map.get(id);
190
+ if (!task) continue;
191
+ stack.push(...(task.after || []));
192
+ }
193
+ return false;
194
+ }
195
+
196
+ /**
197
+ * Compute the patch and the changed field names for `edit`. Only fields the
198
+ * caller passed can change; every validation throws and the caller turns the
199
+ * message into exit 2 inside the CAS. Values are never stored in the event.
200
+ */
201
+ function planEdit(task, options, map) {
202
+ const patch = {};
203
+ const fields = [];
204
+
205
+ if (options.title !== null) {
206
+ const title = String(options.title).trim();
207
+ if (title === "") throw new Error("edit: --title must not be empty");
208
+ if (title !== task.title) { patch.title = title; fields.push("title"); }
209
+ }
210
+ if (options.role !== null) {
211
+ const role = String(options.role).trim();
212
+ if (role === "") throw new Error("edit: --role must not be empty");
213
+ if (role !== task.role) { patch.role = role; fields.push("role"); }
214
+ }
215
+ if (options.priority !== null) {
216
+ if (!Number.isInteger(options.priority)) throw new Error("edit: --priority must be an integer");
217
+ if (options.priority !== task.priority) { patch.priority = options.priority; fields.push("priority"); }
218
+ }
219
+ if (options.acceptance !== null) {
220
+ const text = String(options.acceptance).trim();
221
+ if (text === "") throw new Error("edit: --acceptance must not be empty (use --acceptance - to clear it)");
222
+ if (text === "-") {
223
+ if (!isDraft(task)) throw new Error("edit: only a draft card can clear its acceptance (--acceptance -)");
224
+ if (task.acceptance !== "") { patch.acceptance = ""; fields.push("acceptance"); }
225
+ } else if (text !== task.acceptance) {
226
+ patch.acceptance = text;
227
+ fields.push("acceptance");
228
+ }
229
+ }
230
+ if (options.scopeAdd.length > 0 || options.scopeRemove.length > 0) {
231
+ const add = [];
232
+ for (const raw of options.scopeAdd) {
233
+ const path = String(raw).trim();
234
+ if (path === "") throw new Error("edit: --scope-add needs a non-empty path");
235
+ if (!add.includes(path)) add.push(path);
236
+ }
237
+ const remove = [];
238
+ for (const raw of options.scopeRemove) {
239
+ const path = String(raw).trim();
240
+ if (path === "") throw new Error("edit: --scope-remove needs a non-empty path");
241
+ if (!remove.includes(path)) remove.push(path);
242
+ }
243
+ for (const path of add) {
244
+ if (remove.includes(path)) throw new Error("edit: scope path " + path + " is both added and removed");
245
+ }
246
+ const missing = remove.filter((path) => !task.scope.includes(path));
247
+ if (missing.length > 0) throw new Error("edit: --scope-remove: not in scope: " + missing.join(", "));
248
+ const scope = task.scope.filter((path) => !remove.includes(path));
249
+ for (const path of add) if (!scope.includes(path)) scope.push(path);
250
+ const same = scope.length === task.scope.length && scope.every((path, index) => path === task.scope[index]);
251
+ if (!same) { patch.scope = scope; fields.push("scope"); }
252
+ }
253
+ if (options.afterSet !== null) {
254
+ const ids = parseAfterSet(options.afterSet);
255
+ for (const dep of ids) {
256
+ if (dep === task.id) throw new Error("edit: a card cannot depend on itself");
257
+ if (!map.has(dep)) throw new Error("edit: --after-set: no such task: " + dep);
258
+ }
259
+ if (task.reviewOf && !ids.includes(task.reviewOf)) {
260
+ throw new Error("edit: --after-set must keep the review-of card " + task.reviewOf);
261
+ }
262
+ const same = ids.length === task.after.length
263
+ && [...ids].sort().join("\u0000") === [...task.after].sort().join("\u0000");
264
+ if (!same) {
265
+ if (dependencyCycle(map, task.id, ids)) {
266
+ throw new Error("edit: --after-set would create a dependency cycle through " + task.id);
267
+ }
268
+ patch.after = ids;
269
+ fields.push("after");
270
+ }
271
+ }
272
+ if (options.tags.length > 0) {
273
+ const add = [];
274
+ const remove = [];
275
+ for (const raw of options.tags) {
276
+ const text = String(raw).trim();
277
+ if (text.length < 2 || (text[0] !== "+" && text[0] !== "-")) {
278
+ throw new Error("edit: --tag must look like +name or -name");
279
+ }
280
+ const name = text.slice(1).trim();
281
+ if (name === "") throw new Error("edit: --tag must look like +name or -name");
282
+ if (text[0] === "+") { if (!add.includes(name)) add.push(name); }
283
+ else if (!remove.includes(name)) remove.push(name);
284
+ }
285
+ for (const name of add) {
286
+ if (remove.includes(name)) throw new Error("edit: tag " + name + " is both added and removed");
287
+ }
288
+ const tags = task.tags.filter((tag) => !remove.includes(tag));
289
+ for (const name of add) if (!tags.includes(name)) tags.push(name);
290
+ const same = tags.length === task.tags.length
291
+ && [...tags].sort().join("\u0000") === [...task.tags].sort().join("\u0000");
292
+ if (!same) { patch.tags = tags; fields.push("tags"); }
293
+ }
294
+ const clear = [];
295
+ if (options.supersedeFlag !== null) {
296
+ if (options.supersedeFlag === true) {
297
+ if (task.superseded !== true) {
298
+ patch.superseded = true;
299
+ patch.supersededReason = options.reason !== null ? String(options.reason).trim() : "superseded by edit";
300
+ fields.push("superseded");
301
+ }
302
+ } else if (task.superseded === true) {
303
+ clear.push("superseded", "supersededReason", "replacedBy");
304
+ fields.push("superseded");
305
+ }
306
+ }
307
+ return { patch, fields, clear };
308
+ }
309
+
310
+ /** A JSON array of strings, per split entry field. */
311
+ function splitStringList(value, where) {
312
+ if (!Array.isArray(value)) throw new Error(where + " must be a JSON array of strings");
313
+ const list = [];
314
+ for (const entry of value) {
315
+ if (typeof entry !== "string" || entry.trim() === "") throw new Error(where + " must contain non-empty strings");
316
+ if (!list.includes(entry.trim())) list.push(entry.trim());
317
+ }
318
+ return list;
319
+ }
320
+
321
+ /** One --into entry: { title, role?, scope?, acceptance?, after? }. */
322
+ function splitItem(entry, index) {
323
+ const where = "split: --into[" + index + "]";
324
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) throw new Error(where + " must be an object");
325
+ const title = typeof entry.title === "string" ? entry.title.trim() : "";
326
+ if (title === "") throw new Error(where + " needs a non-empty title");
327
+ const item = { title };
328
+ if (entry.role !== undefined) {
329
+ if (typeof entry.role !== "string" || entry.role.trim() === "") throw new Error(where + ".role must be a non-empty string");
330
+ item.role = entry.role.trim();
331
+ }
332
+ if (entry.scope !== undefined) item.scope = splitStringList(entry.scope, where + ".scope");
333
+ if (entry.acceptance !== undefined) {
334
+ if (typeof entry.acceptance !== "string" || entry.acceptance.trim() === "") throw new Error(where + ".acceptance must be a non-empty string");
335
+ item.acceptance = entry.acceptance.trim();
336
+ }
337
+ if (entry.after !== undefined) item.after = splitStringList(entry.after, where + ".after");
338
+ return item;
339
+ }
340
+
341
+ /** --into takes one JSON array with at least two entries. */
342
+ function splitItems(values) {
343
+ const raw = values.map((value) => String(value).trim()).filter((value) => value !== "");
344
+ const text = raw.length === 1 ? raw[0] : raw.join(" ");
345
+ if (text === "") throw new Error("split needs --into '<json array>'");
346
+ if (!text.startsWith("[")) throw new Error("split: --into must be a JSON array");
347
+ let parsed;
348
+ try {
349
+ parsed = JSON.parse(text);
350
+ } catch {
351
+ throw new Error("split: --into is not valid JSON");
352
+ }
353
+ if (!Array.isArray(parsed) || parsed.length < 2) throw new Error("split: --into JSON array needs at least two entries");
354
+ return parsed.map((entry, index) => splitItem(entry, index));
355
+ }
356
+
137
357
  /** The target key of a retry/reopen --stage flag (the last one wins). */
138
358
  function stageTarget(options) {
139
359
  return options.stageArgs.length ? options.stageArgs[options.stageArgs.length - 1] : null;
@@ -174,6 +394,12 @@ function printTask(task, json, extra = {}, extraLines = []) {
174
394
  }
175
395
  }
176
396
  if (task.draft) process.stdout.write(indent + "draft: true (never ready, not claimable)\n");
397
+ if (task.superseded) {
398
+ const parts = ["superseded: true"];
399
+ if (task.supersededReason) parts.push("reason: " + task.supersededReason);
400
+ if (task.replacedBy) parts.push("replaced by: " + task.replacedBy);
401
+ process.stdout.write(indent + parts.join(" ") + "\n");
402
+ }
177
403
  if (task.scope.length) process.stdout.write(indent + "scope: " + task.scope.join(", ") + "\n");
178
404
  if (task.after.length) process.stdout.write(indent + "after: " + task.after.join(", ") + "\n");
179
405
  if (task.reviewOf) process.stdout.write(indent + "review-of: " + task.reviewOf + "\n");
@@ -273,7 +499,7 @@ function run(argv) {
273
499
  return [...tasks, ...drafts.map((draft) => draft.task)];
274
500
  });
275
501
  if (!result.ok) fail("could not write the task board");
276
- append(repo, { actor: "planner", kind: "task_plan", count: drafts.length });
502
+ append(repo, { actor: eventActor("planner"), kind: "task_plan", count: drafts.length });
277
503
  for (const draft of drafts) process.stdout.write(draft.task.id + " " + draft.task.title + "\n");
278
504
  return;
279
505
  }
@@ -288,7 +514,7 @@ function run(argv) {
288
514
  if (current.state !== "claimed" || current.owner !== agent) fail("task " + id + " is not claimed by " + agent, 2);
289
515
  const result = mutate(repo, (tasks) => tasks.map((entry) => (entry.id === id ? { ...entry, claimedUntil: new Date(Date.now() + ttlMs).toISOString(), updatedAt: new Date().toISOString() } : entry)));
290
516
  if (!result.ok) fail("could not renew " + id);
291
- append(repo, { actor: agent, kind: "task_renew", task: id });
517
+ append(repo, { actor: eventActor(agent), kind: "task_renew", task: id });
292
518
  process.stdout.write(id + " renewed for " + Math.round(ttlMs / 1000) + "s\n");
293
519
  return;
294
520
  }
@@ -307,7 +533,7 @@ function run(argv) {
307
533
  // Legacy cards keep the idempotent no-op. A staged card always resets to
308
534
  // the requested stage (default the first), so a chain can be re-run.
309
535
  if (!isStaged(current) && current.state === "pending") {
310
- append(repo, { actor: agent, kind: "reopen", task: id, reason, noop: true });
536
+ append(repo, { actor: eventActor(agent), kind: "reopen", task: id, reason, noop: true });
311
537
  return printTask(current, options.json);
312
538
  }
313
539
 
@@ -331,13 +557,13 @@ function run(argv) {
331
557
  if (!result.ok) fail("could not reopen " + id);
332
558
 
333
559
  if (!reopened) {
334
- append(repo, { actor: agent, kind: "reopen", task: id, reason, noop: true });
560
+ append(repo, { actor: eventActor(agent), kind: "reopen", task: id, reason, noop: true });
335
561
  return printTask(readTask(repo, id), options.json);
336
562
  }
337
563
 
338
564
  // A claimed card may still hold announcements; release exactly the claim we reset.
339
565
  if (previous.state === "claimed") releaseLeases(repo, { paths: previous.scope, agent: previous.owner || agent });
340
- append(repo, { actor: agent, kind: "reopen", task: id, from: previous.state, reason, attempt: reopened.attempt, stage: isStaged(reopened) ? reopened.stage : undefined });
566
+ append(repo, { actor: eventActor(agent), kind: "reopen", task: id, from: previous.state, reason, attempt: reopened.attempt, stage: isStaged(reopened) ? reopened.stage : undefined });
341
567
  return printTask(reopened, options.json);
342
568
  }
343
569
 
@@ -373,11 +599,183 @@ function run(argv) {
373
599
  // --force deletes a claimed card only after releasing exactly the announcements
374
600
  // that claim holds, so a forced delete cannot strand them.
375
601
  if (deleted.state === "claimed") releaseLeases(repo, { paths: deleted.scope, agent: deleted.owner || agent });
376
- append(repo, { actor: agent, kind: "task_delete", task: id, id, state: deleted.state });
602
+ append(repo, { actor: eventActor(agent), kind: "task_delete", task: id, id, state: deleted.state });
377
603
  if (options.json) return process.stdout.write(JSON.stringify({ ...viewTask(deleted), deleted: true }, null, 2) + "\n");
378
604
  return process.stdout.write(id + " deleted [" + deleted.state + "] " + deleted.title + "\n");
379
605
  }
380
606
 
607
+ if (command === "edit") {
608
+ const id = options.args[0];
609
+ if (!id) fail("edit needs a task id", 2);
610
+ const actor = options.agent || process.env.HIVE_AGENT || "unknown";
611
+ if (!readTask(repo, id)) fail("no such task: " + id, 2);
612
+ const hasEdit = options.title !== null
613
+ || options.role !== null
614
+ || options.priority !== null
615
+ || options.acceptance !== null
616
+ || options.scopeAdd.length > 0
617
+ || options.scopeRemove.length > 0
618
+ || options.afterSet !== null
619
+ || options.tags.length > 0
620
+ || options.supersedeFlag !== null;
621
+ if (!hasEdit) {
622
+ fail("edit needs at least one field: --title, --scope-add, --scope-remove, --acceptance, --priority, --after-set, --tag, --role, --superseded", 2);
623
+ }
624
+
625
+ // Metadata only: the lane (state/stage/stageState) never changes here, so
626
+ // stateChangedAt is left alone and only updatedAt moves.
627
+ let previous = null;
628
+ let updated = null;
629
+ let fields = [];
630
+ try {
631
+ const result = mutate(repo, (tasks) => {
632
+ const map = byId(tasks);
633
+ const task = map.get(id);
634
+ if (!task) throw new Error("no such task: " + id);
635
+ if (task.state !== "pending" && task.state !== "failed") {
636
+ const hint = task.state === "claimed" ? "; done or fail it first" : task.state === "done" ? "; reopen it first" : "";
637
+ throw new Error("edit: task " + id + " is " + task.state + hint + " (edit only works on pending or failed tasks)");
638
+ }
639
+ const plan = planEdit(task, options, map);
640
+ if (plan.fields.length === 0) { updated = task; fields = []; return null; }
641
+ previous = task;
642
+ fields = plan.fields;
643
+ updated = { ...task, ...plan.patch, updatedAt: now() };
644
+ for (const key of plan.clear) delete updated[key];
645
+ return tasks.map((entry) => (entry.id === id ? updated : entry));
646
+ });
647
+ if (!result.ok) fail("could not edit " + id + " (too much contention)");
648
+ } catch (error) {
649
+ fail(error.message, 2);
650
+ }
651
+
652
+ // Keep the announcement board in sync with the task scope: added paths are
653
+ // announced under the task announcer (or the editor) and removed paths a
654
+ // claim of this task wrote are released.
655
+ if (fields.includes("scope")) {
656
+ const added = updated.scope.filter((path) => !previous.scope.includes(path));
657
+ const removed = previous.scope.filter((path) => !updated.scope.includes(path));
658
+ const announced = listLeases(repo).filter((entry) => (entry.value.task || "") === id);
659
+ const ttlMs = parseTtl(options.ttl);
660
+ const announcer = announced.length > 0 ? announced[0].value.agent : actor;
661
+ if (added.length > 0) claimLeases(repo, { paths: added, agent: announcer, ttlMs, taskId: id });
662
+ if (removed.length > 0) {
663
+ for (const agent of new Set(announced.map((entry) => entry.value.agent))) {
664
+ releaseLeases(repo, { paths: removed, agent });
665
+ }
666
+ }
667
+ }
668
+ if (fields.length > 0) {
669
+ const changed = {};
670
+ for (const name of fields) changed[name] = true;
671
+ append(repo, { actor: eventActor(actor), kind: "task_edit", task: id, fields: changed });
672
+ }
673
+ return printTask(updated, options.json);
674
+ }
675
+
676
+ if (command === "split") {
677
+ const id = options.args[0];
678
+ if (!id) fail("split needs a task id", 2);
679
+ const actor = options.agent || process.env.HIVE_AGENT || "unknown";
680
+ if (!readTask(repo, id)) fail("no such task: " + id, 2);
681
+ if (options.into.length === 0) fail("split needs --into '<json array>'", 2);
682
+
683
+ let parent = null;
684
+ let cards = [];
685
+ try {
686
+ const result = mutate(repo, (tasks) => {
687
+ const map = byId(tasks);
688
+ const task = map.get(id);
689
+ if (!task) throw new Error("no such task: " + id);
690
+ if (task.state !== "pending" && task.state !== "failed") {
691
+ const hint = task.state === "claimed" ? "; done or fail it first" : task.state === "done" ? "; reopen it first" : "";
692
+ throw new Error("split: task " + id + " is " + task.state + hint + " (split only works on pending or failed tasks)");
693
+ }
694
+ if (isSuperseded(task)) throw new Error("split: task " + id + " is already superseded");
695
+ const items = splitItems(options.into);
696
+ const parentDeps = Array.isArray(task.after) ? task.after.filter((dep) => dep !== id) : [];
697
+ cards = items.map((item, index) => {
698
+ const acceptance = item.acceptance !== undefined ? item.acceptance : task.acceptance;
699
+ if (!String(acceptance || "").trim()) {
700
+ throw new Error("split: --into[" + index + "] needs an acceptance command (the parent has none to inherit)");
701
+ }
702
+ const after = item.after !== undefined ? [...item.after] : [...parentDeps];
703
+ for (const dep of after) {
704
+ if (dep === id) throw new Error("split: --into[" + index + "].after cannot depend on the task being split");
705
+ if (!map.has(dep)) throw new Error("split: --into[" + index + "].after: no such task: " + dep);
706
+ }
707
+ const childAfter = options.keep && !after.includes(id) ? [...after, id] : after;
708
+ return create({
709
+ title: item.title,
710
+ role: item.role !== undefined ? item.role : task.role,
711
+ scope: item.scope !== undefined ? [...item.scope] : [...(task.scope || [])],
712
+ after: childAfter,
713
+ priority: task.priority,
714
+ tags: [...(task.tags || [])],
715
+ acceptance,
716
+ createdBy: actor,
717
+ });
718
+ });
719
+ if (options.keep) {
720
+ parent = task;
721
+ return [...tasks, ...cards];
722
+ }
723
+ const reason = options.reason !== null ? String(options.reason).trim() : "split into " + cards.length;
724
+ parent = { ...task, superseded: true, supersededReason: reason, replacedBy: cards[0].id, updatedAt: now() };
725
+ return [...tasks.map((entry) => (entry.id === id ? parent : entry)), ...cards];
726
+ });
727
+ if (!result.ok) fail("could not split " + id + " (too much contention)");
728
+ } catch (error) {
729
+ fail(error.message, 2);
730
+ }
731
+
732
+ const event = { actor: eventActor(actor), kind: "task_split", task: id, cards: cards.map((card) => card.id), kept: Boolean(options.keep) };
733
+ if (!options.keep) event.replacedBy = cards[0].id;
734
+ append(repo, event);
735
+ if (options.json) {
736
+ const payload = { task: viewTask(parent), cards: cards.map((card) => viewTask(card)) };
737
+ return process.stdout.write(JSON.stringify(payload, null, 2) + "\n");
738
+ }
739
+ printTask(parent, false);
740
+ for (const card of cards) process.stdout.write(" " + card.id + " " + card.title + "\n");
741
+ return;
742
+ }
743
+
744
+ if (command === "supersede") {
745
+ const id = options.args[0];
746
+ if (!id) fail("supersede needs a task id", 2);
747
+ const reason = options.reason === null ? "" : String(options.reason).trim();
748
+ if (reason === "") fail("supersede needs --reason R", 2);
749
+ const actor = options.agent || process.env.HIVE_AGENT || "unknown";
750
+ if (!readTask(repo, id)) fail("no such task: " + id, 2);
751
+ let updated = null;
752
+ try {
753
+ const result = mutate(repo, (tasks) => {
754
+ const map = byId(tasks);
755
+ const task = map.get(id);
756
+ if (!task) throw new Error("no such task: " + id);
757
+ if (isSuperseded(task)) throw new Error("task " + id + " is already superseded");
758
+ const patch = { superseded: true, supersededReason: reason, updatedAt: now() };
759
+ if (options.replacedBy !== null) {
760
+ const replacement = String(options.replacedBy).trim();
761
+ if (replacement === "") throw new Error("supersede: --replaced-by must not be empty");
762
+ if (replacement === id) throw new Error("supersede: a task cannot replace itself");
763
+ if (!map.has(replacement)) throw new Error("supersede: --replaced-by: no such task: " + replacement);
764
+ patch.replacedBy = replacement;
765
+ }
766
+ updated = { ...task, ...patch };
767
+ return tasks.map((entry) => (entry.id === id ? updated : entry));
768
+ });
769
+ if (!result.ok) fail("could not supersede " + id + " (too much contention)");
770
+ } catch (error) {
771
+ fail(error.message, 2);
772
+ }
773
+ const event = { actor: eventActor(actor), kind: "task_supersede", task: id, reason };
774
+ if (updated.replacedBy) event.replacedBy = updated.replacedBy;
775
+ append(repo, event);
776
+ return printTask(updated, options.json);
777
+ }
778
+
381
779
  if (command === "add") {
382
780
  if (!options.title) fail("--title is required", 2);
383
781
  // Mechanical enforcement of the acceptance rule: a card that can be dispatched
@@ -416,11 +814,37 @@ function run(argv) {
416
814
  return [...tasks, task];
417
815
  });
418
816
  if (!result.ok) fail("could not write the task board (too much contention)");
419
- append(repo, { actor: task.createdBy, kind: "task_add", task: task.id, stages: isStaged(task) ? task.stages.length : undefined });
817
+ append(repo, { actor: eventActor(task.createdBy), kind: "task_add", task: task.id, stages: isStaged(task) ? task.stages.length : undefined });
420
818
  return printTask(task, options.json);
421
819
  }
422
820
 
423
821
  if (command === "list" || command === "ready") {
822
+ // Paginated list: the index filters/orders/counts, and only the page's
823
+ // cards are parsed, so a page costs the same on a 10-task board and a
824
+ // 100k-task board.
825
+ if (command === "list" && (options.limit !== null || options.cursor !== null)) {
826
+ const limit = options.limit === null ? DEFAULT_PAGE_LIMIT : options.limit;
827
+ if (!Number.isInteger(limit) || limit <= 0) fail("list: --limit must be a positive integer", 2);
828
+ const cursor = options.cursor === null ? 0 : options.cursor;
829
+ if (!Number.isInteger(cursor) || cursor < 0) fail("list: --cursor must be a non-negative integer", 2);
830
+ const page = readTaskPage(repo, { state: options.state, role: options.role, limit, cursor });
831
+ if (options.json) {
832
+ const payload = {
833
+ items: page.items.map((task) => viewTask(task)),
834
+ total: page.total,
835
+ cursor: page.cursor,
836
+ hasMore: page.hasMore,
837
+ };
838
+ return process.stdout.write(JSON.stringify(payload, null, 2) + "\n");
839
+ }
840
+ if (page.items.length === 0) return process.stdout.write("No tasks.\n");
841
+ for (const task of page.items) {
842
+ const tags = (task.draft ? " [draft]" : "") + (task.superseded ? " [superseded]" : "");
843
+ process.stdout.write(task.id.padEnd(34) + task.state.padEnd(9) + stageRole(task).padEnd(11) + task.title + tags + "\n");
844
+ }
845
+ process.stdout.write("\n" + page.items.length + " of " + page.total + " tasks" + (page.hasMore ? "; next cursor: " + page.cursor : "") + "\n");
846
+ return;
847
+ }
424
848
  const tasks = board(repo);
425
849
  const selected = command === "ready"
426
850
  ? readyList(repo, tasks, { role: options.role })
@@ -436,7 +860,21 @@ function run(argv) {
436
860
  return process.stdout.write(JSON.stringify(rows, null, 2) + "\n");
437
861
  }
438
862
  if (limited.length === 0) return process.stdout.write(command === "ready" ? "Nothing ready.\n" : "No tasks.\n");
439
- for (const task of limited) process.stdout.write(task.id.padEnd(34) + task.state.padEnd(9) + stageRole(task).padEnd(11) + task.title + (task.draft ? " [draft]" : "") + "\n");
863
+ for (const task of limited) {
864
+ const tags = (task.draft ? " [draft]" : "") + (task.superseded ? " [superseded]" : "");
865
+ process.stdout.write(task.id.padEnd(34) + task.state.padEnd(9) + stageRole(task).padEnd(11) + task.title + tags + "\n");
866
+ }
867
+ return;
868
+ }
869
+
870
+ if (command === "counts") {
871
+ const summary = summarizeIndex(repo);
872
+ const payload = { total: summary.total, byState: summary.byState, superseded: summary.superseded, oldestPending: summary.oldestPending };
873
+ if (options.json) return process.stdout.write(JSON.stringify(payload, null, 2) + "\n");
874
+ process.stdout.write("cards: " + summary.total + "\n");
875
+ for (const [state, count] of Object.entries(summary.byState)) process.stdout.write(" " + state.padEnd(8) + count + "\n");
876
+ if (summary.superseded > 0) process.stdout.write(" " + "superseded".padEnd(8) + summary.superseded + "\n");
877
+ if (summary.oldestPending) process.stdout.write("oldest pending: " + summary.oldestPending.id + " (" + summary.oldestPending.createdAt + ")\n");
440
878
  return;
441
879
  }
442
880
 
@@ -471,6 +909,7 @@ function run(argv) {
471
909
  const preview = readTask(repo, id);
472
910
  if (!preview) fail("no such task: " + id, 2);
473
911
  if (isDraft(preview)) fail(draftClaimMessage(id), 2);
912
+ if (isSuperseded(preview)) fail(supersededClaimMessage(preview), 2);
474
913
  if (readMode(repo) === "freeze" && !options.force && !(preview.tags || []).includes("fix")) {
475
914
  fail("mode is freeze: only fix-tagged cards may be claimed (use --force to override)", 2);
476
915
  }
@@ -488,6 +927,7 @@ function run(argv) {
488
927
  const task = map.get(id);
489
928
  if (!task) throw new Error("no such task: " + id);
490
929
  if (isDraft(task)) throw new Error(draftClaimMessage(id));
930
+ if (isSuperseded(task)) throw new Error(supersededClaimMessage(task));
491
931
  const canReclaim = isReclaimable(task);
492
932
  if (task.state !== "pending" && !canReclaim) throw new Error("task " + id + " is " + task.state + stageOf(task));
493
933
  if (isStaged(task) && task.stageState !== "pending" && !(task.stageState === "claimed" && canReclaim)) {
@@ -516,7 +956,7 @@ function run(argv) {
516
956
  const announcements = claimLeases(repo, { paths: claimed.scope, agent, ttlMs, taskId: claimed.id });
517
957
  publishPresence(repo, { agent, task: claimed, state: "working", files: claimed.scope });
518
958
  append(repo, {
519
- actor: agent,
959
+ actor: eventActor(agent),
520
960
  kind: "task_claim",
521
961
  task: claimed.id,
522
962
  attempt: claimed.attempt,
@@ -637,13 +1077,13 @@ function run(argv) {
637
1077
  addVerdict(repo, { sha: options.sha, result: options.verdict });
638
1078
  }
639
1079
  publishPresence(repo, { agent, task: current, state: outcome.targetState === "done" ? "idle" : "working", files: [] });
640
- append(repo, { actor: agent, kind: "task_" + command, task: id, reason: options.reason || undefined, stage: isStaged(current) ? current.stage : undefined });
641
- for (const event of outcome.events) append(repo, { actor: agent, task: id, ...event });
1080
+ append(repo, { actor: eventActor(agent), kind: "task_" + command, task: id, reason: options.reason || undefined, stage: isStaged(current) ? current.stage : undefined });
1081
+ for (const event of outcome.events) append(repo, { actor: eventActor(agent), task: id, ...event });
642
1082
  if (command === "fail" && current.reviewOf && outcome.targetState === "failed") {
643
1083
  if (upstreamReopened) {
644
- append(repo, { actor: agent, kind: "reopen", task: upstreamReopened.id, from: "done", reason: upstreamReason, attempt: upstreamReopened.attempt, via: "review_failed" });
1084
+ append(repo, { actor: eventActor(agent), kind: "reopen", task: upstreamReopened.id, from: "done", reason: upstreamReason, attempt: upstreamReopened.attempt, via: "review_failed" });
645
1085
  }
646
- append(repo, { actor: agent, kind: "review_failed", task: id, reviewOf: current.reviewOf, reopened: Boolean(upstreamReopened), reason: options.reason || undefined });
1086
+ append(repo, { actor: eventActor(agent), kind: "review_failed", task: id, reviewOf: current.reviewOf, reopened: Boolean(upstreamReopened), reason: options.reason || undefined });
647
1087
  }
648
1088
 
649
1089
  const finalCard = readTask(repo, id);
@@ -656,20 +1096,14 @@ function run(argv) {
656
1096
  }
657
1097
 
658
1098
  if (command === "stats") {
659
- const items = board(repo);
660
- const byState = {};
661
- const byRole = {};
662
- let oldest = null;
663
- for (const task of items) {
664
- byState[task.state] = (byState[task.state] || 0) + 1;
665
- byRole[task.role] = (byRole[task.role] || 0) + 1;
666
- if (task.state === "pending" && (!oldest || task.createdAt < oldest.createdAt)) oldest = task;
667
- }
668
- const summary = { total: items.length, byState, byRole, oldestPending: oldest ? { id: oldest.id, createdAt: oldest.createdAt } : null };
1099
+ // Same shape as before, but from the lightweight index: no card blobs are
1100
+ // parsed for a board-wide summary.
1101
+ const summary = summarizeIndex(repo);
669
1102
  if (options.json) return process.stdout.write(JSON.stringify(summary, null, 2) + "\n");
670
1103
  process.stdout.write("cards: " + summary.total + "\n");
671
- for (const [state, count] of Object.entries(byState)) process.stdout.write(" " + state.padEnd(8) + count + "\n");
672
- if (oldest) process.stdout.write("oldest pending: " + oldest.id + " (" + oldest.createdAt + ")\n");
1104
+ for (const [state, count] of Object.entries(summary.byState)) process.stdout.write(" " + state.padEnd(8) + count + "\n");
1105
+ if (summary.superseded > 0) process.stdout.write(" " + "superseded".padEnd(8) + summary.superseded + "\n");
1106
+ if (summary.oldestPending) process.stdout.write("oldest pending: " + summary.oldestPending.id + " (" + summary.oldestPending.createdAt + ")\n");
673
1107
  return;
674
1108
  }
675
1109