hive-tasks 1.10.0 → 1.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,70 @@ All notable changes to this project are documented here. The format follows
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
5
5
  [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [1.11.1] - 2026-12-06
8
+
9
+ ### Fixed
10
+
11
+ - A board write no longer leaves its temporary Git index in `.hive/`: the
12
+ `GIT_INDEX_FILE` lives under `os.tmpdir()` with a unique pid+random name, is
13
+ registered for exit cleanup and is always removed by `finally` on success and on
14
+ thrown errors. Killed writers previously leaked binary `index-tasks-*` files into
15
+ the repository (82 were found in a real checkout).
16
+ - Command startup sweeps stale temp index files: legacy `index-tasks-*` in the state
17
+ dir and current `hive-tasks-index-*` in `os.tmpdir()` are removed when older than
18
+ ten minutes and their embedded pid is no longer alive; fresh files and files owned
19
+ by a live process are kept.
20
+
21
+ ### Tests
22
+
23
+ - `test/temp-index.test.mjs`: a successful write leaves no files in `.hive/` or the
24
+ temp dir, a throwing write still cleans up (and the board stays readable), and the
25
+ startup sweep removes stale dead-pid files while keeping live/fresh ones.
26
+
27
+ ## [1.11.0] - 2026-12-06
28
+
29
+ ### Fixed
30
+
31
+ - `claim` no longer reports success when the task-board CAS exhausts its retries: a
32
+ contended claim exits non-zero with a contention message and writes no `task_claim`
33
+ event, announcement or presence ref. Previously the card stayed pending while the
34
+ command exited 0 and advertised a claim that was never persisted.
35
+ - Read-only commands (`list` pagination, `counts`, `stats`, `ready`, `next`) never write
36
+ `refs/hive/v1/tasks-index`: a missing/stale/corrupt index is rebuilt in memory for that
37
+ command. A read-only checkout with no usable index now fails with a clear error instead
38
+ of scanning the whole board or crashing on a failed `hash-object`.
39
+ - The index is validated before use (row shape and types, duplicate ids, ids present in
40
+ the pinned tree); corrupt rows are rebuilt once in memory rather than trusted, and
41
+ `reindex` persists a clean cache.
42
+ - A page whose index row id differs from the card blob id is no longer silently dropped:
43
+ the page reports `skipped`, prints a warning, and `show` refuses the inconsistent card.
44
+ - `counts` and the paginated `list` share the superseded rule: the page hides superseded
45
+ cards by default (`--include-superseded` returns the inventory view) and `counts` adds
46
+ `live`, so `list` totals match `counts` without a second scan.
47
+
48
+ ### Added
49
+
50
+ - `hive-tasks reindex [--json]`: explicit rebuild/persist of the derived task index.
51
+ - `ready` and `next` are index-backed: dependency states, draft/superseded/fix flags,
52
+ stage readiness, reclaim expiry and queue order are computed from the compact rows;
53
+ only the returned cards are parsed, so a dispatcher on a 100k-task board no longer
54
+ scans the whole tree (measured `ready --limit 5` well under the old 12s full scan).
55
+ - Strict pagination flags: `--limit` and `--cursor` only accept non-negative decimal
56
+ integers (`0x10`, `1e1`, `+3`, `2.0`, `" 5 "`, `-0` are refused with exit 2).
57
+ - Index format v2 with priority, flags, after ids, stage state/role and claim expiry;
58
+ an old v1 index rebuilds automatically in memory.
59
+
60
+ ### Tests
61
+
62
+ - Added `test/concurrency.test.mjs` (12 concurrent claims on 20 cards, 30 on 60 cards):
63
+ every exit-0 claim must be persisted, failures must be explicit, and a failed claim
64
+ must write no event or presence ref.
65
+ - `test/pagination.test.mjs` was rewritten for the read-only index, validation, skipped
66
+ rows, `reindex`, strict flags and the 100k `ready --limit`/page/counts budget.
67
+ ### Published
68
+
69
+ - npm: `hive-tasks@1.11.0` on 2026-12-06.
70
+
7
71
  ## [1.10.0] - 2026-12-06
8
72
 
9
73
  ### Added
@@ -38,6 +102,10 @@ All notable changes to this project are documented here. The format follows
38
102
  "never starts a process" claim and the generated id length). No behaviour or protocol
39
103
  change.
40
104
 
105
+ ### Published
106
+
107
+ - npm: `hive-tasks@1.10.0` on 2026-12-06.
108
+
41
109
  ## [1.9.0] - 2026-12-04
42
110
 
43
111
  ### Added
package/README.md CHANGED
@@ -78,7 +78,7 @@ token-tests-ba66 pending tester token tests
78
78
  | edit <id> [--title T] [--scope-add P] [--scope-remove P] [--acceptance CMD] [--priority N] [--after-set ID,ID] [--tag +T/-T] [--role R] [--superseded\|--no-superseded] | change only the fields you pass, on a pending or failed task; an empty --acceptance is refused and --acceptance - clears it on a draft; a scope edit syncs the task's announcements |
79
79
  | split <id> --into '<json array>' [--keep] [--reason R] [--json] | replace a task with finer cards; the parent is marked superseded unless --keep keeps it and gates the cards on it |
80
80
  | supersede <id> --reason R [--replaced-by ID] | retire a task without done/failed; it leaves ready, next and claim |
81
- | list [--state S] [--role R] [--json] [--limit N] [--cursor C] | every task, or one server-side page (`{ items, total, cursor, hasMore }`) newest stateChangedAt first |
81
+ | list [--state S] [--role R] [--json] [--limit N] [--cursor C] [--include-superseded] | every task, or one server-side live page (`{ items, total, cursor, hasMore, skipped }`) newest stateChangedAt first; superseded cards are hidden unless --include-superseded |
82
82
  | show <id> [--json] | one task, its stage chain, the draft and superseded flags, and the resolved role source |
83
83
  | ready [--limit N] [--role R] [--json] | pending, non-draft, non-superseded tasks whose dependencies are done, ordered by priority then age |
84
84
  | next [--role R] [--json] | the single best candidate |
@@ -90,7 +90,8 @@ token-tests-ba66 pending tester token tests
90
90
  | retry <id> [--stage KEY] | failed back to pending (or reset a chain to KEY) |
91
91
  | reopen <id> [--reason R] [--agent A] [--stage KEY] | every state back to pending; clears owner, claim, result and verdict, attempt + 1; releases the claim's announcements; a staged task resets to KEY (default the first stage) |
92
92
  | rm <id> [--force] [--json] | delete a pending/failed/done task; a claimed task is refused (exit 2) unless --force, which releases its announcements first |
93
- | counts [--json] | per-state counts, the superseded count and the oldest pending task, from the lightweight index |
93
+ | counts [--json] | live per-state counts, `live`, the superseded count and the oldest pending task, from the lightweight index |
94
+ | reindex [--json] | rebuild and persist the derived task index; read commands never write it |
94
95
  | stats [--json] | counts by state and role, plus the oldest pending task (index-backed) |
95
96
 
96
97
  Exit codes: 0 success, 1 internal error, 2 refused (already claimed, wrong state, unknown
@@ -139,35 +140,50 @@ Large boards are served a page at a time. `--limit` and/or `--cursor` switch
139
140
 
140
141
  ~~~bash
141
142
  $ hive-tasks list --json --state pending --limit 50 --cursor 0
142
- { "items": [ ... ], "total": 1234, "cursor": 50, "hasMore": true }
143
+ { "items": [ ... ], "total": 1234, "cursor": 50, "hasMore": true, "skipped": 0 }
143
144
  $ hive-tasks list --json --state pending --limit 50 --cursor 50 # next page
144
145
  ~~~
145
146
 
146
147
  - rows are ordered by `stateChangedAt` descending, ties broken by id so a walk is
147
148
  deterministic;
148
- - `cursor` is the numeric offset printed by the previous page; `--limit` must be a
149
- positive integer (default 50 when only `--cursor` is given), `--cursor` a
150
- non-negative integer;
151
- - `total` is the filtered count, so the caller knows how many pages remain;
149
+ - `cursor` is the numeric offset printed by the previous page; `--limit` and
150
+ `--cursor` only accept decimal integers in their documented ranges (`0x10`, `1e1`,
151
+ `+3`, `2.0`, a padded `" 5 "` and `-0` are refused);
152
+ - `total` is the filtered live count, so the caller knows how many pages remain;
153
+ - superseded cards are hidden by default, so the page total matches `counts`;
154
+ `--include-superseded` returns the inventory view instead;
152
155
  - only the page's cards are read from git; filtering, ordering and the total come from
153
- a lightweight index (`refs/hive/v1/tasks-index`), which is written with every board
154
- write and rebuilt once when missing or stale.
156
+ a lightweight index (`refs/hive/v1/tasks-index`). Read commands never write that
157
+ index — a missing/stale/corrupt one is rebuilt in memory for that command and
158
+ `reindex` persists it; a read-only checkout with no usable index fails with a clear
159
+ error. A row whose card id disagrees with the tree entry is counted in `skipped`
160
+ (and `show` refuses it) instead of disappearing silently.
161
+
162
+ The temporary `GIT_INDEX_FILE` used by a board write lives under the system temp
163
+ directory, not `.hive/`, and is removed on success and on failures. A command start
164
+ also sweeps stale temp index files older than ten minutes whose pid is dead, so a
165
+ killed writer cannot grow a pile of binary index files in the repository.
155
166
 
156
167
  A `list` without `--limit`/`--cursor` keeps returning the full array. `counts --json`
157
168
  returns the per-state numbers from that index without parsing any card:
158
169
 
159
170
  ~~~bash
160
171
  $ hive-tasks counts --json
161
- { "total": 1234, "byState": { "pending": 1200, "claimed": 3, "done": 30, "failed": 1 },
172
+ { "total": 1234, "live": 1232, "byState": { "pending": 1200, "claimed": 3, "done": 30, "failed": 1 },
162
173
  "superseded": 2, "oldestPending": { "id": "auth-token-a1b2", "createdAt": "..." } }
163
174
  ~~~
164
175
 
165
176
  `show <id> --json` reads exactly that one card blob. `stats` keeps its older shape
166
- (byState, byRole, superseded, oldestPending) and is index-backed too.
177
+ (byState, byRole, superseded, oldestPending) and is index-backed too. `ready` and `next`
178
+ are index-backed as well: dependencies, draft/superseded/fix flags, stage readiness,
179
+ reclaim expiry and queue order come from the index, so a dispatcher on a 100k-task board
180
+ no longer scans every card.
167
181
 
168
182
  ## How a claim works
169
183
 
170
- 1. the task CAS moves pending -> claimed in the task tree (one winner per task);
184
+ 1. the task CAS moves pending -> claimed in the task tree (one winner per task). If every
185
+ CAS retry loses to another writer the claim exits 1 with a contention message and
186
+ announces nothing; events and presence refs are written only after the card persists;
171
187
  2. every scope path is announced on the hive-consensus announcement board; the latest
172
188
  announcement wins and a live announcement by another agent is reported as an
173
189
  overlap;
package/README.zh-CN.md CHANGED
@@ -77,7 +77,7 @@ token-tests-ba66 pending tester token tests
77
77
  | edit <id> [--title T] [--scope-add P] [--scope-remove P] [--acceptance CMD] [--priority N] [--after-set ID,ID] [--tag +T/-T] [--role R] [--superseded\|--no-superseded] | 只改传入的字段,且只对 pending/failed 任务生效;空 --acceptance 被拒,草稿可用 --acceptance - 清空;scope 改动会同步任务自己的公告 |
78
78
  | split <id> --into '<json array>' [--keep] [--reason R] [--json] | 用更细的卡替换一张任务;父任务默认标 superseded 并指向第一张新卡,--keep 保留父任务并让新卡以它为前置 |
79
79
  | supersede <id> --reason R [--replaced-by ID] | 退休一张任务(不是 done/failed),不再进入 ready、next 和 claim |
80
- | list [--state S] [--role R] [--json] [--limit N] [--cursor C] | 所有任务,或一页服务端分页结果(`{ items, total, cursor, hasMore }`),stateChangedAt 倒序 |
80
+ | list [--state S] [--role R] [--json] [--limit N] [--cursor C] [--include-superseded] | 所有任务,或一页服务端分页结果(`{ items, total, cursor, hasMore, skipped }`),stateChangedAt 倒序;默认隐藏 superseded 卡,--include-superseded 返回全量 |
81
81
  | show <id> [--json] | 单个任务、它的阶段链、draft/superseded 标记,以及解析到的角色来源 |
82
82
  | ready [--limit N] [--role R] [--json] | 依赖已完成的 pending 非草稿、非 superseded 任务,按优先级、再按时间排序 |
83
83
  | next [--role R] [--json] | 只给最优的那一个 |
@@ -89,7 +89,8 @@ token-tests-ba66 pending tester token tests
89
89
  | retry <id> [--stage KEY] | failed 回到 pending(或把链复位到 KEY) |
90
90
  | reopen <id> [--reason R] [--agent A] [--stage KEY] | 任何状态回到 pending;清 owner、认领、结果与判定,attempt + 1;释放认领时的公告;带阶段的任务复位到 KEY(默认第一阶段) |
91
91
  | rm <id> [--force] [--json] | 删除 pending/failed/done 的任务;claimed 的任务默认拒绝(退出码 2),加 --force 会先释放公告再删 |
92
- | counts [--json] | 各状态计数、superseded 计数和最老 pending 任务,来自轻量索引 |
92
+ | counts [--json] | 各状态存活计数、`live`、superseded 计数和最老 pending 任务,来自轻量索引 |
93
+ | reindex [--json] | 重建并持久化派生任务索引;只读命令永远不写它 |
93
94
  | stats [--json] | 按状态和角色计数,外加最老的 pending 任务;superseded 单独计数(同样走索引) |
94
95
 
95
96
  退出码:0 成功,1 内部错误,2 被拒(已被认领、状态不对、任务不存在、依赖缺失、
@@ -132,32 +133,44 @@ JSON 里是 `superseded`,文本输出单独一行;它们不计入 byState/by
132
133
 
133
134
  ~~~bash
134
135
  $ hive-tasks list --json --state pending --limit 50 --cursor 0
135
- { "items": [ ... ], "total": 1234, "cursor": 50, "hasMore": true }
136
+ { "items": [ ... ], "total": 1234, "cursor": 50, "hasMore": true, "skipped": 0 }
136
137
  $ hive-tasks list --json --state pending --limit 50 --cursor 50 # 下一页
137
138
  ~~~
138
139
 
139
140
  - 行按 `stateChangedAt` 倒序,时间相同按 id 升序,保证翻页顺序稳定;
140
- - `cursor` 是上一页返回的数字偏移;`--limit` 必须是正整数(只给 `--cursor` 时默认
141
- 50),`--cursor` 必须是非负整数;
142
- - `total` 是过滤后的总数,调用方能算出还剩几页;
141
+ - `cursor` 是上一页返回的数字偏移;`--limit`/`--cursor` 只接受文档范围内的十进制
142
+ 整数(`0x10`、`1e1`、`+3`、`2.0`、带空格的 `" 5 "`、`-0` 都会被拒);
143
+ - `total` 是过滤后的存活总数,调用方能算出还剩几页;
144
+ - 默认隐藏 superseded 卡,因此分页 total 与 `counts` 对得上;
145
+ `--include-superseded` 返回包含它们的全量视图;
143
146
  - 只读取当前页的卡片 blob;过滤、排序和总数来自轻量索引
144
- (`refs/hive/v1/tasks-index`),它随每次写板更新,缺失或过期时自动重建一次。
147
+ (`refs/hive/v1/tasks-index`)。只读命令永不写该索引:缺失/过期/损坏时只为本次
148
+ 命令在内存中重建,`reindex` 才持久化;只读仓库没有可用索引时明确报错,不会全树
149
+ 扫描或崩溃。索引行 id 与卡片 id 不一致时计入 `skipped`(`show` 会拒绝),不再
150
+ 静默丢卡。
151
+
152
+ 写板用的临时 `GIT_INDEX_FILE` 放在系统临时目录,不落在 `.hive/`;成功和失败路径都会
153
+ 删除。命令启动时还会清理超过 10 分钟且 pid 已死的陈旧临时索引文件,进程被杀也不会在
154
+ 仓库里堆积二进制索引文件。
145
155
 
146
156
  不带 `--limit`/`--cursor` 的 `list` 仍返回完整数组。`counts --json` 直接从索引返回
147
157
  各状态计数,不解析任何卡片:
148
158
 
149
159
  ~~~bash
150
160
  $ hive-tasks counts --json
151
- { "total": 1234, "byState": { "pending": 1200, "claimed": 3, "done": 30, "failed": 1 },
161
+ { "total": 1234, "live": 1232, "byState": { "pending": 1200, "claimed": 3, "done": 30, "failed": 1 },
152
162
  "superseded": 2, "oldestPending": { "id": "auth-token-a1b2", "createdAt": "..." } }
153
163
  ~~~
154
164
 
155
165
  `show <id> --json` 只读取那一张卡的 blob。`stats` 保持原有输出形状
156
- (byState、byRole、superseded、oldestPending),同样由索引支撑。
166
+ (byState、byRole、superseded、oldestPending),同样由索引支撑。`ready` 和 `next` 也走
167
+ 索引:依赖状态、draft/superseded/fix 标记、阶段就绪、认领过期和排队顺序都从索引行
168
+ 计算,只解析返回给调用方的卡片,因此 10 万卡仓库上的调度器不再全树扫描。
157
169
 
158
170
  ## claim 怎么走
159
171
 
160
- 1. 任务 CAS 把 pending 推到 claimed(一个任务唯一赢家);
172
+ 1. 任务 CAS 把 pending 推到 claimed(一个任务唯一赢家)。若每次 CAS 重试都被别的写者抢先,
173
+ claim 会以退出码 1 报 contention 并且不写任何公告;事件和 presence ref 只在卡片落库后写;
161
174
  2. scope 里每个路径都公告到 hive-consensus 的公告看板:后来者覆盖公告,别人的存活公告
162
175
  作为 overlap 返回;
163
176
  3. done、fail、reopen 和 rm --force 释放这次认领自己写的公告(retry 只接受 failed 任务,
package/SPEC.md CHANGED
@@ -47,15 +47,33 @@ Implementation sketch (plumbing, no working tree involved):
47
47
  GIT_INDEX_FILE=tmp git write-tree # new tree
48
48
  git update-ref refs/hive/v1/tasks <new-tree> <old-tree>
49
49
 
50
+ `tmp` is a unique file under `os.tmpdir()` (`hive-tasks-index-<pid>-<random>`), never a
51
+ path inside the repository: binary Git index files must not leak into `.hive/` when a
52
+ writer is killed. The file is removed in a `finally` block on success and on every
53
+ thrown error, and a normal exit also sweeps it. At command startup the CLI removes stale
54
+ temp index files — older than ten minutes and whose embedded pid is no longer alive —
55
+ scanning both the repository state dir (legacy `index-tasks-*` names from 1.11.0 and
56
+ earlier) and `os.tmpdir()` (current names). Fresh files and files owned by a live pid
57
+ are kept.
58
+
50
59
  A derived index lives next to the tree and is never the source of truth:
51
60
 
52
- refs/hive/v1/tasks-index -> blob { v: 1, tasks: <tasks tree sha>, entries: [...] }
61
+ refs/hive/v1/tasks-index -> blob { v: 2, tasks: <tasks tree sha>, entries: [...] }
62
+
63
+ Each entry is a fixed-length array
64
+ [id, state, role, sortTime(ms), createdAt, flags, priority, after|null,
65
+ stageState|null, claimedUntil(ms)|null, stageRole|null]. flags packs the superseded (1),
66
+ draft (2) and fix-tag (4) bits; after/stage fields make readiness computable from the
67
+ index alone. The blob pins the task tree sha it describes. A board write refreshes it
68
+ after the task ref moves, so a crash between the two updates only costs one rebuild.
53
69
 
54
- Each entry is [id, state, role, sortTime(ms), createdAt, superseded]. The blob pins the
55
- task tree sha it describes: a reader that finds it missing or pinned to another tree
56
- rebuilds it once from the task tree. A board write refreshes it after the task ref moves,
57
- so a crash between the two updates only costs one rebuild. `list` pagination, `counts`
58
- and `stats` read this index instead of parsing every card blob.
70
+ Read commands (`list` pagination, `counts`, `stats`, `ready`, `next`) never write the
71
+ index: a missing, stale or corrupt one is rebuilt in memory for that command, and a
72
+ read-only checkout with no usable index fails with a clear error instead of scanning
73
+ the board or crashing. `hive-tasks reindex` (and every board write) persists a clean
74
+ cache explicitly. Before using a cached index the reader validates the row shape, ids
75
+ unique and present in the pinned tree, and the state/role types; invalid rows are
76
+ discarded and rebuilt rather than trusted.
59
77
 
60
78
  ## 3. Task blob
61
79
 
@@ -354,7 +372,9 @@ see the same order; the claim CAS still gives exactly one winner per task.
354
372
  [--priority N] [--stage ROLE[:ACCEPTANCE]]... [--stages FILE]
355
373
  hive-tasks plan [--file plan.json] # no --file reads the plan from stdin
356
374
  hive-tasks list [--json] [--state S] [--role R] [--limit N] [--cursor C]
375
+ [--include-superseded]
357
376
  hive-tasks counts [--json]
377
+ hive-tasks reindex [--json]
358
378
  hive-tasks ready [--json] [--limit N] [--role R]
359
379
  hive-tasks next [--role R] [--json] # the single best candidate, or null
360
380
  hive-tasks show <id> [--json] # task plus resolved role source
@@ -389,25 +409,44 @@ stage key is derived from the role (a repeated role becomes coder-2, coder-3...)
389
409
  FILE` takes a JSON array of stage objects and is the way to set explicit keys, onFail and
390
410
  per-stage acceptance in one shot. The two flags are mutually exclusive.
391
411
 
392
- Exit codes: 0 success; 1 internal error; 2 refused (already claimed, wrong state,
393
- dependency missing, mode freeze, invalid stage chain, missing --acceptance, draft claim).
412
+ Exit codes: 0 success; 1 internal error (including a contended claim whose CAS retries
413
+ were exhausted, and a read-only checkout with no usable task index); 2 refused (already
414
+ claimed, wrong state, dependency missing, mode freeze, invalid stage chain, missing
415
+ --acceptance, draft claim, non-decimal pagination flags).
394
416
 
395
417
  `list --json --state S --role R --limit N --cursor C` returns one server-side page:
396
- `{ items, total, cursor, hasMore }`. Rows are ordered by stateChangedAt descending
397
- (ties by id ascending); `cursor` is the numeric offset printed by the previous page (a
398
- cursor at or past the total yields an empty page); --limit must be a positive integer
399
- (default 50 when only --cursor is passed) and --cursor a non-negative integer. `total`
400
- is the filtered count, and only the page's card blobs are read. A list without
401
- --limit/--cursor keeps returning the array of all matching tasks.
402
-
403
- `counts --json` returns `{ total, byState, superseded, oldestPending }` from the
418
+ `{ items, total, cursor, hasMore, skipped }`. Rows are ordered by stateChangedAt
419
+ descending (ties by id ascending); `cursor` is the numeric offset printed by the previous
420
+ page (a cursor at or past the total yields an empty page); --limit and --cursor only
421
+ accept decimal integers in their documented ranges (`0x10`, `1e1`, `+3`, `2.0`, a padded
422
+ `" 5 "` and `-0` are refused with exit 2). `total` is the filtered live count, and only
423
+ the page's card blobs are read. A list without --limit/--cursor keeps returning the
424
+ array of all matching tasks (superseded included).
425
+
426
+ Paginated list hides superseded tasks by default so its `total` equals the corresponding
427
+ `counts.byState` number; `--include-superseded` brings them back (inventory view). If an
428
+ index row id and the card blob id disagree, that row is not silently dropped: the page
429
+ counts it in `skipped`, prints a warning, and `show <id>` refuses the inconsistent card
430
+ with exit 1 and a `reindex` hint.
431
+
432
+ `counts --json` returns `{ total, live, byState, superseded, oldestPending }` from the
404
433
  lightweight index without parsing card blobs; superseded tasks are counted separately and
405
- do not appear inside byState. `stats` keeps its shape (byState, byRole, superseded,
406
- oldestPending) and is index-backed too. `show <id> --json` reads exactly one card blob.
434
+ do not appear inside byState or oldestPending. `live` is the non-superseded total, so it
435
+ matches a paginated list total with no state filter. `stats` keeps its shape (byState,
436
+ byRole, superseded, oldestPending) and is index-backed too. `show <id> --json` reads
437
+ exactly one card blob.
438
+
439
+ `ready` and `next` are index-backed as well: dependency states, draft/superseded/fix
440
+ flags, stage readiness, reclaim expiry and the queue order come from the index rows, and
441
+ only the cards returned to the caller are parsed. `reindex [--json]` rebuilds and persists
442
+ the derived cache explicitly.
407
443
 
408
444
  claim couples the task with the hive-consensus announcement board, task first:
409
445
 
410
- 1. CAS the task from pending to claimed (this is what picks the single winner);
446
+ 1. CAS the task from pending to claimed (this is what picks the single winner). The CAS
447
+ retries a bounded number of times when another writer wins; if every retry loses, the
448
+ claim exits 1 with a contention message and writes no event, announcement or presence
449
+ ref — a claim is only announced after the card write is persisted;
411
450
  2. announce every scope path (refs/hive/v1/lease/<key>/__key__). The announcement phase
412
451
  never fails the claim: the latest announcement wins, and a live announcement by
413
452
  another agent is returned as an overlap (in the claim event and in --json) and is
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hive-tasks",
3
- "version": "1.10.0",
3
+ "version": "1.11.1",
4
4
  "description": "Task cards for agent teams: one git tree behind one ref, with a state machine, optional stage chains, role resolution, dependencies and hive leases.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli.js CHANGED
@@ -3,7 +3,7 @@ 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 { DEFAULT_PAGE_LIMIT, listRaw, mutate, readTask, readTaskPage, summarizeIndex } from "./store.js";
6
+ import { DEFAULT_PAGE_LIMIT, cleanupStaleTempIndexes, listRaw, mutate, pageFromEntries, readIndexForRead, readTask, readTasksByIdsAligned, readyEntries, reindex, repositoryWritable, summarizeEntries } from "./store.js";
7
7
  import { create, isDraft, isReady, isReclaimable, isSuperseded, now, order, reopenPatch, transition } from "./task.js";
8
8
  import {
9
9
  advanceStage,
@@ -42,8 +42,13 @@ const USAGE = [
42
42
  " hive-tasks supersede <id> --reason R [--replaced-by ID]",
43
43
  " retire a task without done/failed; never dispatched",
44
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",
45
+ " [--include-superseded] a page of live tasks newest stateChangedAt",
46
+ " first (superseded cards are hidden): the",
47
+ " page total matches counts byState",
48
+ " hive-tasks counts [--json] live per-state counts + the oldest pending task",
49
+ " hive-tasks reindex [--json] rebuild the derived task index; read commands",
50
+ " never write it (a missing/stale index is",
51
+ " served from the task tree for that command)",
47
52
  " hive-tasks show <id> [--json] card plus the resolved role source",
48
53
  " hive-tasks ready [--json] [--limit N] [--role R]",
49
54
  " hive-tasks next [--role R] [--json] the single best candidate",
@@ -83,7 +88,7 @@ function value(argv, index, flag) {
83
88
  }
84
89
 
85
90
  function parse(argv) {
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 };
91
+ 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, limitToken: null, cursor: null, cursorToken: null, includeSuperseded: false, title: null, goal: null, priority: null, force: false, acceptance: null, verify: false, file: null, stagesFile: null, reviewOf: null, replacedBy: null, supersedeFlag: null, draft: false };
87
92
  for (let i = 0; i < argv.length; i++) {
88
93
  const arg = argv[i];
89
94
  if (arg === "--json") out.json = true;
@@ -113,8 +118,15 @@ function parse(argv) {
113
118
  else if (arg === "--sha") out.sha = value(argv, i++, arg);
114
119
  else if (arg === "--state") out.state = value(argv, i++, arg);
115
120
  else if (arg === "--role") out.role = value(argv, i++, arg);
116
- else if (arg === "--limit") out.limit = Number(value(argv, i++, arg));
117
- else if (arg === "--cursor") out.cursor = Number(value(argv, i++, arg));
121
+ else if (arg === "--limit") {
122
+ const raw = value(argv, i++, arg);
123
+ out.limitToken = raw;
124
+ out.limit = Number(raw);
125
+ } else if (arg === "--cursor") {
126
+ const raw = value(argv, i++, arg);
127
+ out.cursorToken = raw;
128
+ out.cursor = Number(raw);
129
+ } else if (arg === "--include-superseded") out.includeSuperseded = true;
118
130
  else if (arg === "--title") out.title = value(argv, i++, arg);
119
131
  else if (arg === "--goal") out.goal = value(argv, i++, arg);
120
132
  else if (arg === "--priority") out.priority = Number(value(argv, i++, arg));
@@ -359,12 +371,41 @@ function stageTarget(options) {
359
371
  return options.stageArgs.length ? options.stageArgs[options.stageArgs.length - 1] : null;
360
372
  }
361
373
 
362
- function readyList(repo, tasks, { role } = {}) {
363
- const free = readMode(repo) === "free";
364
- const map = byId(tasks);
365
- return tasks
366
- .filter((task) => matchesRole(task, role) && isReady(task, map, { modeFree: free }))
367
- .sort(order);
374
+ /**
375
+ * Index rows for a read-only command. Never writes: a missing, stale or corrupt
376
+ * index is rebuilt in memory for this call. A read-only checkout gets a clear
377
+ * error instead of a silent failure or a crash.
378
+ */
379
+ function readableIndex(repo) {
380
+ const index = readIndexForRead(repo);
381
+ if (!index.rebuilt) return index.entries;
382
+ if (!repositoryWritable(repo)) {
383
+ fail("task index is missing or stale and this repository is read-only; run hive-tasks reindex from a writable checkout");
384
+ }
385
+ process.stderr.write("hive-tasks: task index missing or stale; served from the task tree for this command (run hive-tasks reindex to persist it)\n");
386
+ return index.entries;
387
+ }
388
+
389
+ function printListLine(task) {
390
+ const tags = (task.draft ? " [draft]" : "") + (task.superseded ? " [superseded]" : "");
391
+ process.stdout.write(task.id.padEnd(34) + task.state.padEnd(9) + stageRole(task).padEnd(11) + task.title + tags + "\n");
392
+ }
393
+
394
+ function warnSkipped(skipped) {
395
+ process.stderr.write("hive-tasks: " + skipped + " card(s) were skipped: the index row id and the card id differ (run hive-tasks reindex after repairing the card)\n");
396
+ }
397
+
398
+ /** Fetch the cards for index rows, aligned; row/card id mismatches are counted. */
399
+ function alignedCards(repo, rows) {
400
+ const cards = readTasksByIdsAligned(repo, rows.map((row) => row.id));
401
+ const good = [];
402
+ let skipped = 0;
403
+ for (let index = 0; index < rows.length; index += 1) {
404
+ const card = cards[index];
405
+ if (!card || card.id !== rows[index].id) { skipped += 1; continue; }
406
+ good.push(card);
407
+ }
408
+ return { cards: good, skipped };
368
409
  }
369
410
 
370
411
  /**
@@ -440,6 +481,8 @@ function run(argv) {
440
481
  if (command === "-V" || command === "--version" || command === "version") return process.stdout.write(VERSION + "\n");
441
482
 
442
483
  const repo = repoInfo(process.cwd());
484
+ // Remove temp Git index files left by killed writers before doing any work.
485
+ cleanupStaleTempIndexes(repo);
443
486
 
444
487
  if (command === "init") {
445
488
  ensureState(repo);
@@ -452,6 +495,16 @@ function run(argv) {
452
495
  return;
453
496
  }
454
497
 
498
+ if (command === "reindex") {
499
+ // The index is a cache: every write refreshes it, and this command heals a
500
+ // missing/stale/corrupt one explicitly. Read commands never write it.
501
+ const result = reindex(repo);
502
+ if (!result.ok) fail("could not rebuild the task index (read-only refs/objects or too much contention); reindex needs a writable checkout", 1);
503
+ if (options.json) return process.stdout.write(JSON.stringify({ tasks: result.tasks, entries: result.entries }, null, 2) + "\n");
504
+ if (result.tasks === null) return process.stdout.write("reindexed: empty board, index removed\n");
505
+ return process.stdout.write("reindexed " + result.entries + " task(s) into refs/hive/v1/tasks-index\n");
506
+ }
507
+
455
508
  if (command === "plan") {
456
509
  const raw = options.file ? fs.readFileSync(options.file, "utf8") : fs.readFileSync(0, "utf8");
457
510
  let plan;
@@ -818,58 +871,79 @@ function run(argv) {
818
871
  return printTask(task, options.json);
819
872
  }
820
873
 
821
- if (command === "list" || command === "ready") {
874
+ if (command === "list") {
822
875
  // Paginated list: the index filters/orders/counts, and only the page's
823
876
  // 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 });
877
+ // 100k-task board. Read-only: a missing/stale index is rebuilt in memory
878
+ // for this command, never persisted.
879
+ if (options.limitToken !== null || options.cursorToken !== null) {
880
+ let limit = DEFAULT_PAGE_LIMIT;
881
+ if (options.limitToken !== null) {
882
+ if (!/^\d+$/.test(options.limitToken)) fail("list: --limit must be a positive integer", 2);
883
+ limit = Number(options.limitToken);
884
+ if (!Number.isSafeInteger(limit) || limit <= 0) fail("list: --limit must be a positive integer", 2);
885
+ }
886
+ let cursor = 0;
887
+ if (options.cursorToken !== null) {
888
+ if (!/^\d+$/.test(options.cursorToken)) fail("list: --cursor must be a non-negative integer", 2);
889
+ cursor = Number(options.cursorToken);
890
+ if (!Number.isSafeInteger(cursor)) fail("list: --cursor must be a non-negative integer", 2);
891
+ }
892
+ const page = pageFromEntries(repo, readableIndex(repo), {
893
+ state: options.state,
894
+ role: options.role,
895
+ limit,
896
+ cursor,
897
+ includeSuperseded: options.includeSuperseded,
898
+ });
899
+ if (page.skipped > 0) warnSkipped(page.skipped);
831
900
  if (options.json) {
832
901
  const payload = {
833
902
  items: page.items.map((task) => viewTask(task)),
834
903
  total: page.total,
835
904
  cursor: page.cursor,
836
905
  hasMore: page.hasMore,
906
+ skipped: page.skipped,
837
907
  };
838
908
  return process.stdout.write(JSON.stringify(payload, null, 2) + "\n");
839
909
  }
840
910
  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");
911
+ for (const task of page.items) printListLine(task);
912
+ process.stdout.write("\n" + page.items.length + " of " + page.total + " tasks" + (page.hasMore ? "; next cursor: " + page.cursor : "") + (page.skipped > 0 ? "; skipped " + page.skipped : "") + "\n");
846
913
  return;
847
914
  }
848
915
  const tasks = board(repo);
849
- const selected = command === "ready"
850
- ? readyList(repo, tasks, { role: options.role })
851
- : tasks
852
- .filter((task) => (!options.state || task.state === options.state) && matchesRole(task, options.role))
853
- .sort(order);
916
+ const selected = tasks
917
+ .filter((task) => (!options.state || task.state === options.state) && matchesRole(task, options.role))
918
+ .sort(order);
854
919
  const limited = options.limit ? selected.slice(0, options.limit) : selected;
920
+ if (options.json) return process.stdout.write(JSON.stringify(limited.map((task) => viewTask(task)), null, 2) + "\n");
921
+ if (limited.length === 0) return process.stdout.write("No tasks.\n");
922
+ for (const task of limited) printListLine(task);
923
+ return;
924
+ }
925
+
926
+ if (command === "ready") {
927
+ // Ready is index-backed: dependencies, flags, stage readiness and the queue
928
+ // order come from the compact rows; only the returned cards are parsed.
929
+ let rows = readyEntries(readableIndex(repo), { modeFree: readMode(repo) === "free" });
930
+ if (options.role) rows = rows.filter((row) => row.role === options.role);
931
+ const limited = options.limit ? rows.slice(0, options.limit) : rows;
932
+ const { cards, skipped } = alignedCards(repo, limited);
933
+ if (skipped > 0) warnSkipped(skipped);
855
934
  if (options.json) {
856
- const rows = limited.map((task) => {
857
- const view = viewTask(task);
858
- return command === "ready" ? { ...view, readyRole: stageRole(task) } : view;
859
- });
860
- return process.stdout.write(JSON.stringify(rows, null, 2) + "\n");
861
- }
862
- if (limited.length === 0) return process.stdout.write(command === "ready" ? "Nothing ready.\n" : "No tasks.\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");
935
+ return process.stdout.write(JSON.stringify(cards.map((task) => ({ ...viewTask(task), readyRole: stageRole(task) })), null, 2) + "\n");
866
936
  }
937
+ if (cards.length === 0) return process.stdout.write("Nothing ready.\n");
938
+ for (const task of cards) printListLine(task);
867
939
  return;
868
940
  }
869
941
 
870
942
  if (command === "counts") {
871
- const summary = summarizeIndex(repo);
872
- const payload = { total: summary.total, byState: summary.byState, superseded: summary.superseded, oldestPending: summary.oldestPending };
943
+ // Same cache as the paginated list: byState hides superseded cards and
944
+ // counts.live matches the paginated list total (which hides them too).
945
+ const summary = summarizeEntries(readableIndex(repo));
946
+ const payload = { total: summary.total, live: summary.live, byState: summary.byState, superseded: summary.superseded, oldestPending: summary.oldestPending };
873
947
  if (options.json) return process.stdout.write(JSON.stringify(payload, null, 2) + "\n");
874
948
  process.stdout.write("cards: " + summary.total + "\n");
875
949
  for (const [state, count] of Object.entries(summary.byState)) process.stdout.write(" " + state.padEnd(8) + count + "\n");
@@ -879,12 +953,16 @@ function run(argv) {
879
953
  }
880
954
 
881
955
  if (command === "next") {
882
- const [first] = readyList(repo, board(repo), { role: options.role });
883
- if (!first) {
956
+ const rows = readyEntries(readableIndex(repo), { modeFree: readMode(repo) === "free" })
957
+ .filter((row) => !options.role || row.role === options.role);
958
+ if (rows.length === 0) {
884
959
  if (options.json) process.stdout.write("null\n");
885
960
  else process.stdout.write("Nothing ready.\n");
886
961
  return;
887
962
  }
963
+ const { cards } = alignedCards(repo, rows.slice(0, 1));
964
+ const [first] = cards;
965
+ if (!first) fail("task index and task tree disagree for the next ready card; run hive-tasks reindex", 1);
888
966
  return printTask(first, options.json, { readyRole: stageRole(first) });
889
967
  }
890
968
 
@@ -893,6 +971,7 @@ function run(argv) {
893
971
  if (!id) fail("show needs a task id", 2);
894
972
  const task = readTask(repo, id);
895
973
  if (!task) fail("no such task: " + id, 2);
974
+ if (task.id !== id) fail("task " + id + " is inconsistent: tree entry " + id + " holds a card with id " + task.id + "; run hive-tasks reindex after repairing the card", 1);
896
975
  const active = stageRole(task);
897
976
  const resolved = resolveRole(repo, active, isStaged(task) ? task.stage : {});
898
977
  const lines = ["role-source: " + resolved.source + " (adapter " + resolved.adapter + ", model " + (resolved.model || "-") + ")"];
@@ -918,11 +997,13 @@ function run(argv) {
918
997
  if (isStaged(preview) && preview.stageState !== "pending" && !(preview.stageState === "claimed" && reclaim)) {
919
998
  fail("task " + id + " stage " + preview.stage + " is " + preview.stageState, 2);
920
999
  }
921
- if (!isReady(preview, byId(board(repo)), { modeFree: true })) fail("task " + id + " is not ready (dependencies or mode)", 2);
1000
+ // Readiness comes from the index rows, not from parsing every card blob.
1001
+ const readyIds = new Set(readyEntries(readableIndex(repo), { modeFree: true }).map((row) => row.id));
1002
+ if (!readyIds.has(id)) fail("task " + id + " is not ready (dependencies or mode)", 2);
922
1003
 
923
1004
  let claimed = null;
924
1005
  try {
925
- mutate(repo, (tasks) => {
1006
+ const result = mutate(repo, (tasks) => {
926
1007
  const map = byId(tasks);
927
1008
  const task = map.get(id);
928
1009
  if (!task) throw new Error("no such task: " + id);
@@ -941,14 +1022,18 @@ function run(argv) {
941
1022
  claimedUntil: new Date(Date.now() + ttlMs).toISOString(),
942
1023
  ...stageStatePatch(task, "claimed"),
943
1024
  };
944
- claimed = transition(task, "claimed", patch);
945
- return tasks.map((entry) => (entry.id === id ? claimed : entry));
1025
+ const next = transition(task, "claimed", patch);
1026
+ return tasks.map((entry) => (entry.id === id ? next : entry));
946
1027
  });
1028
+ // A failed CAS (8 retries exhausted) must fail loudly: an event, an
1029
+ // announcement or a presence ref for an unpersisted claim is a ghost.
1030
+ if (!result.ok) fail("could not claim " + id + " (task board write contention; retry)", 1);
1031
+ claimed = result.tasks.find((task) => task.id === id) || null;
947
1032
  } catch (error) {
948
1033
  fail(error.message, 2);
949
1034
  }
950
1035
 
951
- if (!claimed) fail("could not claim " + id, 2);
1036
+ if (!claimed) fail("could not claim " + id + " (the board was written but the card is missing)", 1);
952
1037
 
953
1038
  // Announcements are information, never a gate: the card claim already
954
1039
  // succeeded, and a live announcement by someone else is reported as an
@@ -1096,10 +1181,13 @@ function run(argv) {
1096
1181
  }
1097
1182
 
1098
1183
  if (command === "stats") {
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);
1102
- if (options.json) return process.stdout.write(JSON.stringify(summary, null, 2) + "\n");
1184
+ // Same output shape as before, but from the lightweight index: no card
1185
+ // blobs are parsed for a board-wide summary.
1186
+ const summary = summarizeEntries(readableIndex(repo));
1187
+ if (options.json) {
1188
+ const payload = { total: summary.total, byState: summary.byState, byRole: summary.byRole, superseded: summary.superseded, oldestPending: summary.oldestPending };
1189
+ return process.stdout.write(JSON.stringify(payload, null, 2) + "\n");
1190
+ }
1103
1191
  process.stdout.write("cards: " + summary.total + "\n");
1104
1192
  for (const [state, count] of Object.entries(summary.byState)) process.stdout.write(" " + state.padEnd(8) + count + "\n");
1105
1193
  if (summary.superseded > 0) process.stdout.write(" " + "superseded".padEnd(8) + summary.superseded + "\n");
package/src/store.js CHANGED
@@ -1,19 +1,34 @@
1
1
  import crypto from "node:crypto";
2
2
  import fs from "node:fs";
3
+ import os from "node:os";
3
4
  import path from "node:path";
4
5
  import { git, gitBuffer, out } from "./git.js";
6
+ import { currentStage, isStaged } from "./stage.js";
7
+ import { order } from "./task.js";
5
8
 
6
9
  export const TASKS_REF = "refs/hive/v1/tasks";
7
10
  /**
8
- * A lightweight board index next to the task tree: one blob holding
9
- * [id, state, role, sortTime(ms), createdAt, superseded] per task. It is
10
- * written with every board write, so list/counts/stats never have to parse
11
- * every card blob; a reader that finds the index missing or pinned to an older
12
- * tree rebuilds it once from the task tree (a single `cat-file --batch`).
11
+ * A lightweight board index next to the task tree: one blob holding a compact
12
+ * row per task. It is a pure cache: writes refresh it after the task ref moves,
13
+ * and read commands never write it (a missing/stale index is rebuilt in memory
14
+ * for that command; `hive-tasks reindex` or the next write persists it).
15
+ *
16
+ * Row layout (array, fixed length 11):
17
+ * [id, state, role, sortTime(ms), createdAt, flags, priority,
18
+ * after|null, stageState|null, claimedUntil(ms)|null, stageRole|null]
19
+ * flags: 1 = superseded, 2 = draft, 4 = has the "fix" tag.
13
20
  */
14
21
  export const TASKS_INDEX_REF = "refs/hive/v1/tasks-index";
15
- export const INDEX_VERSION = 1;
22
+ export const INDEX_VERSION = 2;
16
23
  export const DEFAULT_PAGE_LIMIT = 50;
24
+ export const ENTRY_LENGTH = 11;
25
+ export const ROW = Object.freeze({
26
+ id: 0, state: 1, role: 2, time: 3, createdAt: 4, flags: 5,
27
+ priority: 6, after: 7, stageState: 8, claimedUntil: 9, stageRole: 10,
28
+ });
29
+ export const FLAG = Object.freeze({ superseded: 1, draft: 2, fix: 4 });
30
+
31
+ const STATES = new Set(["pending", "claimed", "done", "failed"]);
17
32
 
18
33
  function readRefSha(repo, ref) {
19
34
  const result = git(["rev-parse", "--verify", "--quiet", ref], { cwd: repo.top, allowFail: true });
@@ -24,6 +39,17 @@ export function refSha(repo) {
24
39
  return readRefSha(repo, TASKS_REF);
25
40
  }
26
41
 
42
+ /** True when this checkout can persist refs/objects (used to decide read-only errors). */
43
+ export function repositoryWritable(repo) {
44
+ try {
45
+ fs.accessSync(path.join(repo.gitDir, "objects"), fs.constants.W_OK);
46
+ fs.accessSync(path.join(repo.gitDir, "refs"), fs.constants.W_OK);
47
+ return true;
48
+ } catch {
49
+ return false;
50
+ }
51
+ }
52
+
27
53
  /** [{ id, blobSha }] for one tree, or [] when the tree is missing. */
28
54
  function readTree(repo, sha) {
29
55
  if (!sha) return [];
@@ -42,11 +68,7 @@ function readTree(repo, sha) {
42
68
  return entries;
43
69
  }
44
70
 
45
- /**
46
- * Read blobs by object name in one process: [{ spec }] -> string[].
47
- * A missing object yields null in its slot. Framing follows git's
48
- * `<oid> <type> <size>\n<payload>\n` (or `<spec> missing\n`).
49
- */
71
+ /** Read blobs by object name in one process: specs -> string[] (null per missing). */
50
72
  function readBlobs(repo, specs) {
51
73
  if (specs.length === 0) return [];
52
74
  const result = gitBuffer(["cat-file", "--batch"], { cwd: repo.top, input: specs.join("\n") + "\n", allowFail: true });
@@ -72,24 +94,28 @@ function readBlobs(repo, specs) {
72
94
  return values;
73
95
  }
74
96
 
75
- /** [{ id, value }] from the task tree. An absent ref is an empty board. */
76
- export function listRaw(repo) {
77
- const sha = refSha(repo);
78
- if (!sha) return [];
79
- const entries = readTree(repo, sha);
80
- if (entries.length === 0) return [];
81
- const blobs = readBlobs(repo, entries.map((entry) => entry.blobSha));
97
+ /** Full cards for the entries of one tree (used by rebuilds and listRaw). */
98
+ function readTreeTasks(repo, tree) {
99
+ if (tree.length === 0) return [];
100
+ const blobs = readBlobs(repo, tree.map((entry) => entry.blobSha));
82
101
  const rows = [];
83
- for (let index = 0; index < entries.length; index += 1) {
102
+ for (let index = 0; index < tree.length; index += 1) {
84
103
  const text = blobs[index];
85
104
  if (text === null) continue;
86
105
  let value = null;
87
106
  try { value = JSON.parse(text); } catch { value = null; }
88
- if (value) rows.push({ id: entries[index].id, value });
107
+ if (value) rows.push({ id: tree[index].id, value });
89
108
  }
90
109
  return rows;
91
110
  }
92
111
 
112
+ /** [{ id, value }] from the task tree. An absent ref is an empty board. */
113
+ export function listRaw(repo) {
114
+ const sha = refSha(repo);
115
+ if (!sha) return [];
116
+ return readTreeTasks(repo, readTree(repo, sha));
117
+ }
118
+
93
119
  /** One card by id: a single blob read, never the whole tree. */
94
120
  export function readTask(repo, id) {
95
121
  const sha = refSha(repo);
@@ -99,23 +125,21 @@ export function readTask(repo, id) {
99
125
  try { return JSON.parse(result.stdout); } catch { return null; }
100
126
  }
101
127
 
102
- /** Full cards for a known page of ids, in one batch call. */
103
- export function readTasksByIds(repo, ids) {
128
+ /** Full cards for a known list of ids, aligned with the input (null per miss). */
129
+ export function readTasksByIdsAligned(repo, ids) {
104
130
  if (!Array.isArray(ids) || ids.length === 0) return [];
105
131
  const sha = refSha(repo);
106
- if (!sha) return [];
132
+ if (!sha) return ids.map(() => null);
107
133
  const blobs = readBlobs(repo, ids.map((id) => sha + ":" + id));
108
- const tasks = [];
109
- for (const text of blobs) {
110
- if (text === null) continue;
111
- try {
112
- const value = JSON.parse(text);
113
- if (value) tasks.push(value);
114
- } catch {
115
- // A malformed card is skipped, like listRaw does.
116
- }
117
- }
118
- return tasks;
134
+ return blobs.map((text) => {
135
+ if (text === null) return null;
136
+ try { return JSON.parse(text); } catch { return null; }
137
+ });
138
+ }
139
+
140
+ /** Full cards for a known list of ids, skipping misses. */
141
+ export function readTasksByIds(repo, ids) {
142
+ return readTasksByIdsAligned(repo, ids).filter(Boolean);
119
143
  }
120
144
 
121
145
  /** Sort key shared by the index writer and readers: newest lane change first. */
@@ -125,15 +149,54 @@ export function taskSortTime(task) {
125
149
  return Number.isFinite(time) ? time : 0;
126
150
  }
127
151
 
128
- export function buildIndexEntries(tasks) {
129
- return tasks.map((task) => [
130
- task.id,
152
+ function flagsOf(task) {
153
+ let flags = 0;
154
+ if (task.superseded === true) flags |= FLAG.superseded;
155
+ if (task.draft === true) flags |= FLAG.draft;
156
+ if (Array.isArray(task.tags) && task.tags.includes("fix")) flags |= FLAG.fix;
157
+ return flags;
158
+ }
159
+
160
+ function stageStateOf(task) {
161
+ return isStaged(task) && typeof task.stageState === "string" ? task.stageState : null;
162
+ }
163
+
164
+ function stageRoleOf(task) {
165
+ if (!isStaged(task)) return null;
166
+ const stage = currentStage(task);
167
+ return stage && typeof stage.role === "string" ? stage.role : null;
168
+ }
169
+
170
+ function claimedUntilOf(task) {
171
+ if (!task.claimedUntil) return null;
172
+ const time = Date.parse(task.claimedUntil);
173
+ return Number.isFinite(time) ? time : null;
174
+ }
175
+
176
+ function buildEntry(id, task) {
177
+ return [
178
+ id,
131
179
  task.state,
132
- task.role || "",
180
+ typeof task.role === "string" ? task.role : "",
133
181
  taskSortTime(task),
134
- task.createdAt || "",
135
- task.superseded === true ? 1 : 0,
136
- ]);
182
+ typeof task.createdAt === "string" ? task.createdAt : "",
183
+ flagsOf(task),
184
+ Number.isFinite(task.priority) ? task.priority : 0,
185
+ Array.isArray(task.after) && task.after.length > 0 ? [...task.after] : null,
186
+ stageStateOf(task),
187
+ claimedUntilOf(task),
188
+ stageRoleOf(task),
189
+ ];
190
+ }
191
+
192
+ /** Rows for the write path: every task already carries its immutable tree id. */
193
+ export function buildIndexEntries(tasks) {
194
+ return tasks.map((task) => buildEntry(task.id, task));
195
+ }
196
+
197
+ /** Rows for a rebuild: the tree entry name wins over the blob's id field. */
198
+ function buildEntriesFromRows(rows) {
199
+ return rows.map((row) => buildEntry(row.id, row.value));
137
200
  }
138
201
 
139
202
  function readIndexBlob(repo) {
@@ -144,46 +207,100 @@ function readIndexBlob(repo) {
144
207
  try { return JSON.parse(result.stdout); } catch { return null; }
145
208
  }
146
209
 
210
+ /** Delete the derived index (empty board / no tasks ref). */
211
+ function clearIndex(repo) {
212
+ git(["update-ref", "-d", TASKS_INDEX_REF], { cwd: repo.top, allowFail: true });
213
+ }
214
+
215
+ /** Write the index blob; returns false when the ref cannot be updated. */
147
216
  function writeIndex(repo, tasksSha, entries) {
148
217
  const blob = out(["hash-object", "-w", "--stdin"], {
149
218
  cwd: repo.top,
150
219
  input: JSON.stringify({ v: INDEX_VERSION, tasks: tasksSha, entries }),
151
220
  });
152
- git(["update-ref", TASKS_INDEX_REF, blob], { cwd: repo.top, allowFail: true });
221
+ return git(["update-ref", TASKS_INDEX_REF, blob], { cwd: repo.top, allowFail: true }).status === 0;
222
+ }
223
+
224
+ function validEntry(entry, treeNames) {
225
+ if (!Array.isArray(entry) || entry.length !== ENTRY_LENGTH) return false;
226
+ const [id, state, role, time, createdAt, flags, priority, after, stageState, claimedUntil, stageRole] = entry;
227
+ if (typeof id !== "string" || id === "" || !treeNames.has(id)) return false;
228
+ if (!STATES.has(state)) return false;
229
+ if (typeof role !== "string") return false;
230
+ if (!Number.isFinite(time) || typeof createdAt !== "string") return false;
231
+ if (!Number.isInteger(flags) || flags < 0 || flags > 7) return false;
232
+ if (!Number.isFinite(priority)) return false;
233
+ if (after !== null && (!Array.isArray(after) || after.some((dep) => typeof dep !== "string"))) return false;
234
+ if (stageState !== null && !STATES.has(stageState)) return false;
235
+ if (claimedUntil !== null && !Number.isFinite(claimedUntil)) return false;
236
+ if (stageRole !== null && typeof stageRole !== "string") return false;
237
+ return true;
238
+ }
239
+
240
+ /** Validated entries, or null when the cache is corrupt/stale/duplicated. */
241
+ function validateEntries(entries, treeNames) {
242
+ if (!Array.isArray(entries)) return null;
243
+ const seen = new Set();
244
+ for (const entry of entries) {
245
+ if (!validEntry(entry, treeNames)) return null;
246
+ if (seen.has(entry[ROW.id])) return null;
247
+ seen.add(entry[ROW.id]);
248
+ }
249
+ return entries;
153
250
  }
154
251
 
155
252
  /**
156
- * Lightweight rows for the whole board: [{ id, state, role, time, createdAt,
157
- * superseded }]. Uses the index when it is pinned to the current task tree;
158
- * otherwise rebuilds and stores the index once.
253
+ * Index rows for a read-only consumer. Never writes: a missing, stale or corrupt
254
+ * index is rebuilt in memory for this call (the caller can surface `rebuilt`).
159
255
  */
160
- export function readIndex(repo) {
256
+ export function readIndexForRead(repo) {
161
257
  const tasksSha = refSha(repo);
162
- if (!tasksSha) return { tasksSha: null, entries: [] };
258
+ if (!tasksSha) return { tasksSha: null, entries: [], rebuilt: false };
259
+ const tree = readTree(repo, tasksSha);
260
+ const treeNames = new Set(tree.map((entry) => entry.id));
163
261
  const cached = readIndexBlob(repo);
164
- if (cached && cached.v === INDEX_VERSION && cached.tasks === tasksSha && Array.isArray(cached.entries)) {
165
- return { tasksSha, entries: cached.entries };
262
+ if (cached && cached.v === INDEX_VERSION && cached.tasks === tasksSha) {
263
+ const entries = validateEntries(cached.entries, treeNames);
264
+ if (entries) return { tasksSha, entries, rebuilt: false };
265
+ }
266
+ const rows = readTreeTasks(repo, tree);
267
+ return { tasksSha, entries: buildEntriesFromRows(rows), rebuilt: true };
268
+ }
269
+
270
+ /**
271
+ * Explicit rebuild of the derived index (the `reindex` command). Writes the
272
+ * index ref only; the task tree and the working tree are untouched.
273
+ */
274
+ export function reindex(repo) {
275
+ for (let attempt = 0; attempt < 8; attempt += 1) {
276
+ const tasksSha = refSha(repo);
277
+ if (!tasksSha) {
278
+ clearIndex(repo);
279
+ return { ok: true, tasks: null, entries: 0 };
280
+ }
281
+ const tree = readTree(repo, tasksSha);
282
+ const entries = buildEntriesFromRows(readTreeTasks(repo, tree));
283
+ if (!writeIndex(repo, tasksSha, entries)) continue;
284
+ if (refSha(repo) === tasksSha) return { ok: true, tasks: tasksSha, entries: entries.length };
166
285
  }
167
- const tasks = listRaw(repo).map((entry) => entry.value);
168
- const entries = buildIndexEntries(tasks);
169
- writeIndex(repo, tasksSha, entries);
170
- return { tasksSha, entries };
286
+ return { ok: false, tasks: null, entries: 0 };
171
287
  }
172
288
 
173
289
  /** Newest stateChangedAt first; ids break ties so paging is deterministic. */
174
290
  export function compareIndexRows(left, right) {
175
- if (left[3] !== right[3]) return right[3] - left[3];
176
- return String(left[0]).localeCompare(String(right[0]));
291
+ if (left[ROW.time] !== right[ROW.time]) return right[ROW.time] - left[ROW.time];
292
+ return String(left[ROW.id]).localeCompare(String(right[ROW.id]));
177
293
  }
178
294
 
179
295
  /**
180
296
  * Pure page computation over index rows: filter, sort newest-first, cut one
181
- * page. Exported so the 100k-scale behaviour can be tested without git.
297
+ * page. Superseded rows are hidden by default so page totals match counts.
182
298
  */
183
- export function paginateIndexEntries(entries, { state = null, role = null, limit = DEFAULT_PAGE_LIMIT, cursor = 0 } = {}) {
299
+ export function paginateIndexEntries(entries, { state = null, role = null, limit = DEFAULT_PAGE_LIMIT, cursor = 0, includeSuperseded = false } = {}) {
184
300
  let rows = entries;
185
- if (state) rows = rows.filter((entry) => entry[1] === state);
186
- if (role) rows = rows.filter((entry) => entry[2] === role);
301
+ if (!includeSuperseded) rows = rows.filter((entry) => (entry[ROW.flags] & FLAG.superseded) === 0);
302
+ if (state) rows = rows.filter((entry) => entry[ROW.state] === state);
303
+ if (role) rows = rows.filter((entry) => entry[ROW.role] === role);
187
304
  rows = rows.slice().sort(compareIndexRows);
188
305
  const total = rows.length;
189
306
  const start = Math.min(Math.max(0, cursor), total);
@@ -192,45 +309,159 @@ export function paginateIndexEntries(entries, { state = null, role = null, limit
192
309
  return { page, total, cursor: next, hasMore: next < total };
193
310
  }
194
311
 
312
+ /** Page payload with cards; index/card id mismatches are counted as skipped. */
313
+ export function pageFromEntries(repo, entries, options) {
314
+ const page = paginateIndexEntries(entries, options);
315
+ const ids = page.page.map((entry) => entry[ROW.id]);
316
+ const cards = readTasksByIdsAligned(repo, ids);
317
+ const items = [];
318
+ let skipped = 0;
319
+ for (let index = 0; index < ids.length; index += 1) {
320
+ const card = cards[index];
321
+ if (!card || card.id !== ids[index]) { skipped += 1; continue; }
322
+ items.push(card);
323
+ }
324
+ return { items, total: page.total, cursor: page.cursor, hasMore: page.hasMore, skipped };
325
+ }
326
+
195
327
  /**
196
- * One server-side page of tasks, newest stateChangedAt first. Only the page's
197
- * cards are read from git; filtering, ordering and the total come from the
198
- * lightweight index.
328
+ * Ready rows computed from the index only: dependencies, draft/superseded/fix
329
+ * flags, stage readiness and the reclaim rule, then the queue order.
199
330
  */
200
- export function readTaskPage(repo, options = {}) {
201
- const { entries } = readIndex(repo);
202
- const page = paginateIndexEntries(entries, options);
203
- const tasks = readTasksByIds(repo, page.page.map((entry) => entry[0]));
204
- const byId = new Map(tasks.map((task) => [task.id, task]));
205
- const items = page.page.map((entry) => byId.get(entry[0])).filter(Boolean);
206
- return { items, total: page.total, cursor: page.cursor, hasMore: page.hasMore };
331
+ export function readyEntries(entries, { modeFree = true, now = Date.now() } = {}) {
332
+ const stateById = new Map(entries.map((entry) => [entry[ROW.id], entry[ROW.state]]));
333
+ const rows = [];
334
+ for (const entry of entries) {
335
+ const flags = entry[ROW.flags];
336
+ if ((flags & (FLAG.superseded | FLAG.draft)) !== 0) continue;
337
+ const state = entry[ROW.state];
338
+ const claimedUntil = entry[ROW.claimedUntil];
339
+ const reclaimable = state === "claimed" && claimedUntil !== null && claimedUntil <= now;
340
+ if (state !== "pending" && !reclaimable) continue;
341
+ const after = entry[ROW.after];
342
+ if (after && after.some((dep) => stateById.get(dep) !== "done")) continue;
343
+ const stageState = entry[ROW.stageState];
344
+ if (stageState !== null && !(stageState === "pending" || (stageState === "claimed" && reclaimable))) continue;
345
+ if (!modeFree && (flags & FLAG.fix) === 0) continue;
346
+ rows.push({
347
+ id: entry[ROW.id],
348
+ role: entry[ROW.stageRole] ?? entry[ROW.role],
349
+ priority: entry[ROW.priority],
350
+ createdAt: entry[ROW.createdAt],
351
+ });
352
+ }
353
+ rows.sort((left, right) => order({ priority: left.priority, createdAt: left.createdAt }, { priority: right.priority, createdAt: right.createdAt }));
354
+ return rows;
207
355
  }
208
356
 
209
357
  /**
210
- * Pure counts over index rows: per-state and per-role counts, the superseded
211
- * count and the oldest pending task. Superseded tasks keep their lane but are
212
- * counted separately, never inside byState/byRole. Exported for the 100k mock.
358
+ * Counts over index rows. Superseded tasks are counted separately and never
359
+ * inside byState/byRole; `live` is the non-superseded total so a paginated
360
+ * list (which hides superseded rows too) has a matching total.
213
361
  */
214
362
  export function summarizeEntries(entries) {
215
363
  const byState = {};
216
364
  const byRole = {};
217
365
  let superseded = 0;
218
366
  let oldest = null;
219
- for (const [id, state, role, , createdAt, isSuperseded] of entries) {
220
- if (isSuperseded) { superseded += 1; continue; }
221
- byState[state] = (byState[state] || 0) + 1;
222
- byRole[role] = (byRole[role] || 0) + 1;
223
- if (state === "pending" && (oldest === null || String(createdAt) < String(oldest.createdAt))) {
224
- oldest = { id, createdAt: String(createdAt) };
367
+ for (const entry of entries) {
368
+ if ((entry[ROW.flags] & FLAG.superseded) !== 0) { superseded += 1; continue; }
369
+ byState[entry[ROW.state]] = (byState[entry[ROW.state]] || 0) + 1;
370
+ byRole[entry[ROW.role]] = (byRole[entry[ROW.role]] || 0) + 1;
371
+ if (entry[ROW.state] === "pending" && (oldest === null || String(entry[ROW.createdAt]) < String(oldest.createdAt))) {
372
+ oldest = { id: entry[ROW.id], createdAt: String(entry[ROW.createdAt]) };
225
373
  }
226
374
  }
227
- return { total: entries.length, byState, byRole, superseded, oldestPending: oldest };
375
+ return { total: entries.length, live: entries.length - superseded, byState, byRole, superseded, oldestPending: oldest };
228
376
  }
229
377
 
230
- /** Counts for the whole board from the lightweight index. */
378
+ /** Whole-board summary (index-backed, read-only). */
231
379
  export function summarizeIndex(repo) {
232
- const { entries } = readIndex(repo);
233
- return summarizeEntries(entries);
380
+ return summarizeEntries(readIndexForRead(repo).entries);
381
+ }
382
+
383
+ /** GIT_INDEX_FILE temp files never live in the repository. Old releases wrote
384
+ * `index-tasks-*` into .hive/, so a killed process leaked binary Git index files
385
+ * there; startup cleanup removes stale ones (older than 10 minutes and a dead pid).
386
+ */
387
+ export const TEMP_INDEX_PREFIX = "hive-tasks-index-";
388
+ const LEGACY_INDEX_PREFIX = "index-tasks-";
389
+ const STALE_TEMP_INDEX_MS = 10 * 60 * 1000;
390
+ const activeTempIndexes = new Set();
391
+ let exitCleanupInstalled = false;
392
+
393
+ function installExitCleanup() {
394
+ if (exitCleanupInstalled) return;
395
+ exitCleanupInstalled = true;
396
+ // Best effort for a normal exit path; killed processes are covered by the
397
+ // startup sweep. `finally` in write() handles every thrown error.
398
+ process.once("exit", () => {
399
+ for (const file of activeTempIndexes) {
400
+ try { fs.rmSync(file, { force: true }); } catch { /* best effort */ }
401
+ }
402
+ });
403
+ }
404
+
405
+ function tempIndexPath() {
406
+ installExitCleanup();
407
+ const file = path.join(os.tmpdir(), TEMP_INDEX_PREFIX + process.pid + "-" + crypto.randomBytes(6).toString("hex"));
408
+ activeTempIndexes.add(file);
409
+ return file;
410
+ }
411
+
412
+ function removeTempIndex(file) {
413
+ try { fs.rmSync(file, { force: true }); } catch { /* already gone */ }
414
+ activeTempIndexes.delete(file);
415
+ }
416
+
417
+ function indexFilePid(name) {
418
+ for (const prefix of [LEGACY_INDEX_PREFIX, TEMP_INDEX_PREFIX]) {
419
+ if (!name.startsWith(prefix)) continue;
420
+ const match = /^(\d+)(?:-|$)/.exec(name.slice(prefix.length));
421
+ return match ? Number(match[1]) : null;
422
+ }
423
+ return null;
424
+ }
425
+
426
+ function processAlive(pid) {
427
+ if (!Number.isInteger(pid) || pid <= 0) return false;
428
+ if (pid === process.pid) return true;
429
+ try {
430
+ process.kill(pid, 0);
431
+ return true;
432
+ } catch (error) {
433
+ return Boolean(error && error.code === "EPERM");
434
+ }
435
+ }
436
+
437
+ /**
438
+ * Remove temp Git index files left behind by killed processes. A file is stale
439
+ * only when it is older than ten minutes and its embedded pid is no longer alive;
440
+ * fresh files and live writers are kept. Scans the repository state dir (legacy
441
+ * `index-tasks-*` names) and os.tmpdir() (current `hive-tasks-index-*`).
442
+ */
443
+ export function cleanupStaleTempIndexes(repo, { now = Date.now(), isAlive = processAlive } = {}) {
444
+ const dirs = [];
445
+ if (repo && repo.stateDir) dirs.push(repo.stateDir);
446
+ dirs.push(os.tmpdir());
447
+ const seen = new Set();
448
+ for (const dir of dirs) {
449
+ if (!dir || seen.has(dir)) continue;
450
+ seen.add(dir);
451
+ let names;
452
+ try { names = fs.readdirSync(dir); } catch { continue; }
453
+ for (const name of names) {
454
+ if (!name.startsWith(LEGACY_INDEX_PREFIX) && !name.startsWith(TEMP_INDEX_PREFIX)) continue;
455
+ const file = path.join(dir, name);
456
+ let stat;
457
+ try { stat = fs.statSync(file); } catch { continue; }
458
+ if (!stat.isFile()) continue;
459
+ if (now - stat.mtimeMs <= STALE_TEMP_INDEX_MS) continue;
460
+ const pid = indexFilePid(name);
461
+ if (pid !== null && isAlive(pid)) continue;
462
+ try { fs.rmSync(file, { force: true }); } catch { /* best effort */ }
463
+ }
464
+ }
234
465
  }
235
466
 
236
467
  function hashBlob(repo, value) {
@@ -239,11 +470,14 @@ function hashBlob(repo, value) {
239
470
 
240
471
  /**
241
472
  * Replace the whole board with the given tasks, compare-and-swap on the ref.
242
- * The lightweight index is written after the task ref moves. Returns false when
243
- * the ref moved underneath us (caller retries).
473
+ * The lightweight index is refreshed after the task ref moves (cache only; a
474
+ * failure to write it never fails the task write). Returns false when the ref
475
+ * moved underneath us (caller retries).
244
476
  */
245
477
  function write(repo, tasks, expectedSha) {
246
- const indexFile = path.join(repo.stateDir, "index-tasks-" + process.pid + "-" + crypto.randomBytes(4).toString("hex"));
478
+ // The temp index goes to the system temp dir, not the repository: a killed
479
+ // process must never leave a binary Git index inside .hive/.
480
+ const indexFile = tempIndexPath();
247
481
  const env = { GIT_INDEX_FILE: indexFile };
248
482
  try {
249
483
  fs.mkdirSync(repo.stateDir, { recursive: true });
@@ -267,7 +501,7 @@ function write(repo, tasks, expectedSha) {
267
501
  writeIndex(repo, tree, buildIndexEntries(tasks));
268
502
  return true;
269
503
  } finally {
270
- fs.rmSync(indexFile, { force: true });
504
+ removeTempIndex(indexFile);
271
505
  }
272
506
  }
273
507
 
@@ -282,3 +516,10 @@ export function mutate(repo, fn) {
282
516
  }
283
517
  return { ok: false, tasks: [] };
284
518
  }
519
+
520
+ /**
521
+ * Backwards-compatible page reader (read-only; rebuilds in memory when needed).
522
+ */
523
+ export function readTaskPage(repo, options = {}) {
524
+ return pageFromEntries(repo, readIndexForRead(repo).entries, options);
525
+ }