hive-tasks 1.10.0 → 1.11.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/CHANGELOG.md CHANGED
@@ -4,6 +4,46 @@ 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.0] - 2026-12-06
8
+
9
+ ### Fixed
10
+
11
+ - `claim` no longer reports success when the task-board CAS exhausts its retries: a
12
+ contended claim exits non-zero with a contention message and writes no `task_claim`
13
+ event, announcement or presence ref. Previously the card stayed pending while the
14
+ command exited 0 and advertised a claim that was never persisted.
15
+ - Read-only commands (`list` pagination, `counts`, `stats`, `ready`, `next`) never write
16
+ `refs/hive/v1/tasks-index`: a missing/stale/corrupt index is rebuilt in memory for that
17
+ command. A read-only checkout with no usable index now fails with a clear error instead
18
+ of scanning the whole board or crashing on a failed `hash-object`.
19
+ - The index is validated before use (row shape and types, duplicate ids, ids present in
20
+ the pinned tree); corrupt rows are rebuilt once in memory rather than trusted, and
21
+ `reindex` persists a clean cache.
22
+ - A page whose index row id differs from the card blob id is no longer silently dropped:
23
+ the page reports `skipped`, prints a warning, and `show` refuses the inconsistent card.
24
+ - `counts` and the paginated `list` share the superseded rule: the page hides superseded
25
+ cards by default (`--include-superseded` returns the inventory view) and `counts` adds
26
+ `live`, so `list` totals match `counts` without a second scan.
27
+
28
+ ### Added
29
+
30
+ - `hive-tasks reindex [--json]`: explicit rebuild/persist of the derived task index.
31
+ - `ready` and `next` are index-backed: dependency states, draft/superseded/fix flags,
32
+ stage readiness, reclaim expiry and queue order are computed from the compact rows;
33
+ only the returned cards are parsed, so a dispatcher on a 100k-task board no longer
34
+ scans the whole tree (measured `ready --limit 5` well under the old 12s full scan).
35
+ - Strict pagination flags: `--limit` and `--cursor` only accept non-negative decimal
36
+ integers (`0x10`, `1e1`, `+3`, `2.0`, `" 5 "`, `-0` are refused with exit 2).
37
+ - Index format v2 with priority, flags, after ids, stage state/role and claim expiry;
38
+ an old v1 index rebuilds automatically in memory.
39
+
40
+ ### Tests
41
+
42
+ - Added `test/concurrency.test.mjs` (12 concurrent claims on 20 cards, 30 on 60 cards):
43
+ every exit-0 claim must be persisted, failures must be explicit, and a failed claim
44
+ must write no event or presence ref.
45
+ - `test/pagination.test.mjs` was rewritten for the read-only index, validation, skipped
46
+ rows, `reindex`, strict flags and the 100k `ready --limit`/page/counts budget.
7
47
  ## [1.10.0] - 2026-12-06
8
48
 
9
49
  ### Added
@@ -38,6 +78,10 @@ All notable changes to this project are documented here. The format follows
38
78
  "never starts a process" claim and the generated id length). No behaviour or protocol
39
79
  change.
40
80
 
81
+ ### Published
82
+
83
+ - npm: `hive-tasks@1.10.0` on 2026-12-06.
84
+
41
85
  ## [1.9.0] - 2026-12-04
42
86
 
43
87
  ### 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,45 @@ 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.
155
161
 
156
162
  A `list` without `--limit`/`--cursor` keeps returning the full array. `counts --json`
157
163
  returns the per-state numbers from that index without parsing any card:
158
164
 
159
165
  ~~~bash
160
166
  $ hive-tasks counts --json
161
- { "total": 1234, "byState": { "pending": 1200, "claimed": 3, "done": 30, "failed": 1 },
167
+ { "total": 1234, "live": 1232, "byState": { "pending": 1200, "claimed": 3, "done": 30, "failed": 1 },
162
168
  "superseded": 2, "oldestPending": { "id": "auth-token-a1b2", "createdAt": "..." } }
163
169
  ~~~
164
170
 
165
171
  `show <id> --json` reads exactly that one card blob. `stats` keeps its older shape
166
- (byState, byRole, superseded, oldestPending) and is index-backed too.
172
+ (byState, byRole, superseded, oldestPending) and is index-backed too. `ready` and `next`
173
+ are index-backed as well: dependencies, draft/superseded/fix flags, stage readiness,
174
+ reclaim expiry and queue order come from the index, so a dispatcher on a 100k-task board
175
+ no longer scans every card.
167
176
 
168
177
  ## How a claim works
169
178
 
170
- 1. the task CAS moves pending -> claimed in the task tree (one winner per task);
179
+ 1. the task CAS moves pending -> claimed in the task tree (one winner per task). If every
180
+ CAS retry loses to another writer the claim exits 1 with a contention message and
181
+ announces nothing; events and presence refs are written only after the card persists;
171
182
  2. every scope path is announced on the hive-consensus announcement board; the latest
172
183
  announcement wins and a live announcement by another agent is reported as an
173
184
  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,40 @@ 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
+ 静默丢卡。
145
151
 
146
152
  不带 `--limit`/`--cursor` 的 `list` 仍返回完整数组。`counts --json` 直接从索引返回
147
153
  各状态计数,不解析任何卡片:
148
154
 
149
155
  ~~~bash
150
156
  $ hive-tasks counts --json
151
- { "total": 1234, "byState": { "pending": 1200, "claimed": 3, "done": 30, "failed": 1 },
157
+ { "total": 1234, "live": 1232, "byState": { "pending": 1200, "claimed": 3, "done": 30, "failed": 1 },
152
158
  "superseded": 2, "oldestPending": { "id": "auth-token-a1b2", "createdAt": "..." } }
153
159
  ~~~
154
160
 
155
161
  `show <id> --json` 只读取那一张卡的 blob。`stats` 保持原有输出形状
156
- (byState、byRole、superseded、oldestPending),同样由索引支撑。
162
+ (byState、byRole、superseded、oldestPending),同样由索引支撑。`ready` 和 `next` 也走
163
+ 索引:依赖状态、draft/superseded/fix 标记、阶段就绪、认领过期和排队顺序都从索引行
164
+ 计算,只解析返回给调用方的卡片,因此 10 万卡仓库上的调度器不再全树扫描。
157
165
 
158
166
  ## claim 怎么走
159
167
 
160
- 1. 任务 CAS 把 pending 推到 claimed(一个任务唯一赢家);
168
+ 1. 任务 CAS 把 pending 推到 claimed(一个任务唯一赢家)。若每次 CAS 重试都被别的写者抢先,
169
+ claim 会以退出码 1 报 contention 并且不写任何公告;事件和 presence ref 只在卡片落库后写;
161
170
  2. scope 里每个路径都公告到 hive-consensus 的公告看板:后来者覆盖公告,别人的存活公告
162
171
  作为 overlap 返回;
163
172
  3. done、fail、reopen 和 rm --force 释放这次认领自己写的公告(retry 只接受 failed 任务,
package/SPEC.md CHANGED
@@ -49,13 +49,22 @@ Implementation sketch (plumbing, no working tree involved):
49
49
 
50
50
  A derived index lives next to the tree and is never the source of truth:
51
51
 
52
- refs/hive/v1/tasks-index -> blob { v: 1, tasks: <tasks tree sha>, entries: [...] }
53
-
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.
52
+ refs/hive/v1/tasks-index -> blob { v: 2, tasks: <tasks tree sha>, entries: [...] }
53
+
54
+ Each entry is a fixed-length array
55
+ [id, state, role, sortTime(ms), createdAt, flags, priority, after|null,
56
+ stageState|null, claimedUntil(ms)|null, stageRole|null]. flags packs the superseded (1),
57
+ draft (2) and fix-tag (4) bits; after/stage fields make readiness computable from the
58
+ index alone. The blob pins the task tree sha it describes. A board write refreshes it
59
+ after the task ref moves, so a crash between the two updates only costs one rebuild.
60
+
61
+ Read commands (`list` pagination, `counts`, `stats`, `ready`, `next`) never write the
62
+ index: a missing, stale or corrupt one is rebuilt in memory for that command, and a
63
+ read-only checkout with no usable index fails with a clear error instead of scanning
64
+ the board or crashing. `hive-tasks reindex` (and every board write) persists a clean
65
+ cache explicitly. Before using a cached index the reader validates the row shape, ids
66
+ unique and present in the pinned tree, and the state/role types; invalid rows are
67
+ discarded and rebuilt rather than trusted.
59
68
 
60
69
  ## 3. Task blob
61
70
 
@@ -354,7 +363,9 @@ see the same order; the claim CAS still gives exactly one winner per task.
354
363
  [--priority N] [--stage ROLE[:ACCEPTANCE]]... [--stages FILE]
355
364
  hive-tasks plan [--file plan.json] # no --file reads the plan from stdin
356
365
  hive-tasks list [--json] [--state S] [--role R] [--limit N] [--cursor C]
366
+ [--include-superseded]
357
367
  hive-tasks counts [--json]
368
+ hive-tasks reindex [--json]
358
369
  hive-tasks ready [--json] [--limit N] [--role R]
359
370
  hive-tasks next [--role R] [--json] # the single best candidate, or null
360
371
  hive-tasks show <id> [--json] # task plus resolved role source
@@ -389,25 +400,44 @@ stage key is derived from the role (a repeated role becomes coder-2, coder-3...)
389
400
  FILE` takes a JSON array of stage objects and is the way to set explicit keys, onFail and
390
401
  per-stage acceptance in one shot. The two flags are mutually exclusive.
391
402
 
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).
403
+ Exit codes: 0 success; 1 internal error (including a contended claim whose CAS retries
404
+ were exhausted, and a read-only checkout with no usable task index); 2 refused (already
405
+ claimed, wrong state, dependency missing, mode freeze, invalid stage chain, missing
406
+ --acceptance, draft claim, non-decimal pagination flags).
394
407
 
395
408
  `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
409
+ `{ items, total, cursor, hasMore, skipped }`. Rows are ordered by stateChangedAt
410
+ descending (ties by id ascending); `cursor` is the numeric offset printed by the previous
411
+ page (a cursor at or past the total yields an empty page); --limit and --cursor only
412
+ accept decimal integers in their documented ranges (`0x10`, `1e1`, `+3`, `2.0`, a padded
413
+ `" 5 "` and `-0` are refused with exit 2). `total` is the filtered live count, and only
414
+ the page's card blobs are read. A list without --limit/--cursor keeps returning the
415
+ array of all matching tasks (superseded included).
416
+
417
+ Paginated list hides superseded tasks by default so its `total` equals the corresponding
418
+ `counts.byState` number; `--include-superseded` brings them back (inventory view). If an
419
+ index row id and the card blob id disagree, that row is not silently dropped: the page
420
+ counts it in `skipped`, prints a warning, and `show <id>` refuses the inconsistent card
421
+ with exit 1 and a `reindex` hint.
422
+
423
+ `counts --json` returns `{ total, live, byState, superseded, oldestPending }` from the
404
424
  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.
425
+ do not appear inside byState or oldestPending. `live` is the non-superseded total, so it
426
+ matches a paginated list total with no state filter. `stats` keeps its shape (byState,
427
+ byRole, superseded, oldestPending) and is index-backed too. `show <id> --json` reads
428
+ exactly one card blob.
429
+
430
+ `ready` and `next` are index-backed as well: dependency states, draft/superseded/fix
431
+ flags, stage readiness, reclaim expiry and the queue order come from the index rows, and
432
+ only the cards returned to the caller are parsed. `reindex [--json]` rebuilds and persists
433
+ the derived cache explicitly.
407
434
 
408
435
  claim couples the task with the hive-consensus announcement board, task first:
409
436
 
410
- 1. CAS the task from pending to claimed (this is what picks the single winner);
437
+ 1. CAS the task from pending to claimed (this is what picks the single winner). The CAS
438
+ retries a bounded number of times when another writer wins; if every retry loses, the
439
+ claim exits 1 with a contention message and writes no event, announcement or presence
440
+ ref — a claim is only announced after the card write is persisted;
411
441
  2. announce every scope path (refs/hive/v1/lease/<key>/__key__). The announcement phase
412
442
  never fails the claim: the latest announcement wins, and a live announcement by
413
443
  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.0",
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, 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
  /**
@@ -452,6 +493,16 @@ function run(argv) {
452
493
  return;
453
494
  }
454
495
 
496
+ if (command === "reindex") {
497
+ // The index is a cache: every write refreshes it, and this command heals a
498
+ // missing/stale/corrupt one explicitly. Read commands never write it.
499
+ const result = reindex(repo);
500
+ if (!result.ok) fail("could not rebuild the task index (read-only refs/objects or too much contention); reindex needs a writable checkout", 1);
501
+ if (options.json) return process.stdout.write(JSON.stringify({ tasks: result.tasks, entries: result.entries }, null, 2) + "\n");
502
+ if (result.tasks === null) return process.stdout.write("reindexed: empty board, index removed\n");
503
+ return process.stdout.write("reindexed " + result.entries + " task(s) into refs/hive/v1/tasks-index\n");
504
+ }
505
+
455
506
  if (command === "plan") {
456
507
  const raw = options.file ? fs.readFileSync(options.file, "utf8") : fs.readFileSync(0, "utf8");
457
508
  let plan;
@@ -818,58 +869,79 @@ function run(argv) {
818
869
  return printTask(task, options.json);
819
870
  }
820
871
 
821
- if (command === "list" || command === "ready") {
872
+ if (command === "list") {
822
873
  // Paginated list: the index filters/orders/counts, and only the page's
823
874
  // 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 });
875
+ // 100k-task board. Read-only: a missing/stale index is rebuilt in memory
876
+ // for this command, never persisted.
877
+ if (options.limitToken !== null || options.cursorToken !== null) {
878
+ let limit = DEFAULT_PAGE_LIMIT;
879
+ if (options.limitToken !== null) {
880
+ if (!/^\d+$/.test(options.limitToken)) fail("list: --limit must be a positive integer", 2);
881
+ limit = Number(options.limitToken);
882
+ if (!Number.isSafeInteger(limit) || limit <= 0) fail("list: --limit must be a positive integer", 2);
883
+ }
884
+ let cursor = 0;
885
+ if (options.cursorToken !== null) {
886
+ if (!/^\d+$/.test(options.cursorToken)) fail("list: --cursor must be a non-negative integer", 2);
887
+ cursor = Number(options.cursorToken);
888
+ if (!Number.isSafeInteger(cursor)) fail("list: --cursor must be a non-negative integer", 2);
889
+ }
890
+ const page = pageFromEntries(repo, readableIndex(repo), {
891
+ state: options.state,
892
+ role: options.role,
893
+ limit,
894
+ cursor,
895
+ includeSuperseded: options.includeSuperseded,
896
+ });
897
+ if (page.skipped > 0) warnSkipped(page.skipped);
831
898
  if (options.json) {
832
899
  const payload = {
833
900
  items: page.items.map((task) => viewTask(task)),
834
901
  total: page.total,
835
902
  cursor: page.cursor,
836
903
  hasMore: page.hasMore,
904
+ skipped: page.skipped,
837
905
  };
838
906
  return process.stdout.write(JSON.stringify(payload, null, 2) + "\n");
839
907
  }
840
908
  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");
909
+ for (const task of page.items) printListLine(task);
910
+ 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
911
  return;
847
912
  }
848
913
  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);
914
+ const selected = tasks
915
+ .filter((task) => (!options.state || task.state === options.state) && matchesRole(task, options.role))
916
+ .sort(order);
854
917
  const limited = options.limit ? selected.slice(0, options.limit) : selected;
918
+ if (options.json) return process.stdout.write(JSON.stringify(limited.map((task) => viewTask(task)), null, 2) + "\n");
919
+ if (limited.length === 0) return process.stdout.write("No tasks.\n");
920
+ for (const task of limited) printListLine(task);
921
+ return;
922
+ }
923
+
924
+ if (command === "ready") {
925
+ // Ready is index-backed: dependencies, flags, stage readiness and the queue
926
+ // order come from the compact rows; only the returned cards are parsed.
927
+ let rows = readyEntries(readableIndex(repo), { modeFree: readMode(repo) === "free" });
928
+ if (options.role) rows = rows.filter((row) => row.role === options.role);
929
+ const limited = options.limit ? rows.slice(0, options.limit) : rows;
930
+ const { cards, skipped } = alignedCards(repo, limited);
931
+ if (skipped > 0) warnSkipped(skipped);
855
932
  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");
933
+ return process.stdout.write(JSON.stringify(cards.map((task) => ({ ...viewTask(task), readyRole: stageRole(task) })), null, 2) + "\n");
866
934
  }
935
+ if (cards.length === 0) return process.stdout.write("Nothing ready.\n");
936
+ for (const task of cards) printListLine(task);
867
937
  return;
868
938
  }
869
939
 
870
940
  if (command === "counts") {
871
- const summary = summarizeIndex(repo);
872
- const payload = { total: summary.total, byState: summary.byState, superseded: summary.superseded, oldestPending: summary.oldestPending };
941
+ // Same cache as the paginated list: byState hides superseded cards and
942
+ // counts.live matches the paginated list total (which hides them too).
943
+ const summary = summarizeEntries(readableIndex(repo));
944
+ const payload = { total: summary.total, live: summary.live, byState: summary.byState, superseded: summary.superseded, oldestPending: summary.oldestPending };
873
945
  if (options.json) return process.stdout.write(JSON.stringify(payload, null, 2) + "\n");
874
946
  process.stdout.write("cards: " + summary.total + "\n");
875
947
  for (const [state, count] of Object.entries(summary.byState)) process.stdout.write(" " + state.padEnd(8) + count + "\n");
@@ -879,12 +951,16 @@ function run(argv) {
879
951
  }
880
952
 
881
953
  if (command === "next") {
882
- const [first] = readyList(repo, board(repo), { role: options.role });
883
- if (!first) {
954
+ const rows = readyEntries(readableIndex(repo), { modeFree: readMode(repo) === "free" })
955
+ .filter((row) => !options.role || row.role === options.role);
956
+ if (rows.length === 0) {
884
957
  if (options.json) process.stdout.write("null\n");
885
958
  else process.stdout.write("Nothing ready.\n");
886
959
  return;
887
960
  }
961
+ const { cards } = alignedCards(repo, rows.slice(0, 1));
962
+ const [first] = cards;
963
+ if (!first) fail("task index and task tree disagree for the next ready card; run hive-tasks reindex", 1);
888
964
  return printTask(first, options.json, { readyRole: stageRole(first) });
889
965
  }
890
966
 
@@ -893,6 +969,7 @@ function run(argv) {
893
969
  if (!id) fail("show needs a task id", 2);
894
970
  const task = readTask(repo, id);
895
971
  if (!task) fail("no such task: " + id, 2);
972
+ 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
973
  const active = stageRole(task);
897
974
  const resolved = resolveRole(repo, active, isStaged(task) ? task.stage : {});
898
975
  const lines = ["role-source: " + resolved.source + " (adapter " + resolved.adapter + ", model " + (resolved.model || "-") + ")"];
@@ -918,11 +995,13 @@ function run(argv) {
918
995
  if (isStaged(preview) && preview.stageState !== "pending" && !(preview.stageState === "claimed" && reclaim)) {
919
996
  fail("task " + id + " stage " + preview.stage + " is " + preview.stageState, 2);
920
997
  }
921
- if (!isReady(preview, byId(board(repo)), { modeFree: true })) fail("task " + id + " is not ready (dependencies or mode)", 2);
998
+ // Readiness comes from the index rows, not from parsing every card blob.
999
+ const readyIds = new Set(readyEntries(readableIndex(repo), { modeFree: true }).map((row) => row.id));
1000
+ if (!readyIds.has(id)) fail("task " + id + " is not ready (dependencies or mode)", 2);
922
1001
 
923
1002
  let claimed = null;
924
1003
  try {
925
- mutate(repo, (tasks) => {
1004
+ const result = mutate(repo, (tasks) => {
926
1005
  const map = byId(tasks);
927
1006
  const task = map.get(id);
928
1007
  if (!task) throw new Error("no such task: " + id);
@@ -941,14 +1020,18 @@ function run(argv) {
941
1020
  claimedUntil: new Date(Date.now() + ttlMs).toISOString(),
942
1021
  ...stageStatePatch(task, "claimed"),
943
1022
  };
944
- claimed = transition(task, "claimed", patch);
945
- return tasks.map((entry) => (entry.id === id ? claimed : entry));
1023
+ const next = transition(task, "claimed", patch);
1024
+ return tasks.map((entry) => (entry.id === id ? next : entry));
946
1025
  });
1026
+ // A failed CAS (8 retries exhausted) must fail loudly: an event, an
1027
+ // announcement or a presence ref for an unpersisted claim is a ghost.
1028
+ if (!result.ok) fail("could not claim " + id + " (task board write contention; retry)", 1);
1029
+ claimed = result.tasks.find((task) => task.id === id) || null;
947
1030
  } catch (error) {
948
1031
  fail(error.message, 2);
949
1032
  }
950
1033
 
951
- if (!claimed) fail("could not claim " + id, 2);
1034
+ if (!claimed) fail("could not claim " + id + " (the board was written but the card is missing)", 1);
952
1035
 
953
1036
  // Announcements are information, never a gate: the card claim already
954
1037
  // succeeded, and a live announcement by someone else is reported as an
@@ -1096,10 +1179,13 @@ function run(argv) {
1096
1179
  }
1097
1180
 
1098
1181
  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");
1182
+ // Same output shape as before, but from the lightweight index: no card
1183
+ // blobs are parsed for a board-wide summary.
1184
+ const summary = summarizeEntries(readableIndex(repo));
1185
+ if (options.json) {
1186
+ const payload = { total: summary.total, byState: summary.byState, byRole: summary.byRole, superseded: summary.superseded, oldestPending: summary.oldestPending };
1187
+ return process.stdout.write(JSON.stringify(payload, null, 2) + "\n");
1188
+ }
1103
1189
  process.stdout.write("cards: " + summary.total + "\n");
1104
1190
  for (const [state, count] of Object.entries(summary.byState)) process.stdout.write(" " + state.padEnd(8) + count + "\n");
1105
1191
  if (summary.superseded > 0) process.stdout.write(" " + "superseded".padEnd(8) + summary.superseded + "\n");
package/src/store.js CHANGED
@@ -2,18 +2,32 @@ import crypto from "node:crypto";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { git, gitBuffer, out } from "./git.js";
5
+ import { currentStage, isStaged } from "./stage.js";
6
+ import { order } from "./task.js";
5
7
 
6
8
  export const TASKS_REF = "refs/hive/v1/tasks";
7
9
  /**
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`).
10
+ * A lightweight board index next to the task tree: one blob holding a compact
11
+ * row per task. It is a pure cache: writes refresh it after the task ref moves,
12
+ * and read commands never write it (a missing/stale index is rebuilt in memory
13
+ * for that command; `hive-tasks reindex` or the next write persists it).
14
+ *
15
+ * Row layout (array, fixed length 11):
16
+ * [id, state, role, sortTime(ms), createdAt, flags, priority,
17
+ * after|null, stageState|null, claimedUntil(ms)|null, stageRole|null]
18
+ * flags: 1 = superseded, 2 = draft, 4 = has the "fix" tag.
13
19
  */
14
20
  export const TASKS_INDEX_REF = "refs/hive/v1/tasks-index";
15
- export const INDEX_VERSION = 1;
21
+ export const INDEX_VERSION = 2;
16
22
  export const DEFAULT_PAGE_LIMIT = 50;
23
+ export const ENTRY_LENGTH = 11;
24
+ export const ROW = Object.freeze({
25
+ id: 0, state: 1, role: 2, time: 3, createdAt: 4, flags: 5,
26
+ priority: 6, after: 7, stageState: 8, claimedUntil: 9, stageRole: 10,
27
+ });
28
+ export const FLAG = Object.freeze({ superseded: 1, draft: 2, fix: 4 });
29
+
30
+ const STATES = new Set(["pending", "claimed", "done", "failed"]);
17
31
 
18
32
  function readRefSha(repo, ref) {
19
33
  const result = git(["rev-parse", "--verify", "--quiet", ref], { cwd: repo.top, allowFail: true });
@@ -24,6 +38,17 @@ export function refSha(repo) {
24
38
  return readRefSha(repo, TASKS_REF);
25
39
  }
26
40
 
41
+ /** True when this checkout can persist refs/objects (used to decide read-only errors). */
42
+ export function repositoryWritable(repo) {
43
+ try {
44
+ fs.accessSync(path.join(repo.gitDir, "objects"), fs.constants.W_OK);
45
+ fs.accessSync(path.join(repo.gitDir, "refs"), fs.constants.W_OK);
46
+ return true;
47
+ } catch {
48
+ return false;
49
+ }
50
+ }
51
+
27
52
  /** [{ id, blobSha }] for one tree, or [] when the tree is missing. */
28
53
  function readTree(repo, sha) {
29
54
  if (!sha) return [];
@@ -42,11 +67,7 @@ function readTree(repo, sha) {
42
67
  return entries;
43
68
  }
44
69
 
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
- */
70
+ /** Read blobs by object name in one process: specs -> string[] (null per missing). */
50
71
  function readBlobs(repo, specs) {
51
72
  if (specs.length === 0) return [];
52
73
  const result = gitBuffer(["cat-file", "--batch"], { cwd: repo.top, input: specs.join("\n") + "\n", allowFail: true });
@@ -72,24 +93,28 @@ function readBlobs(repo, specs) {
72
93
  return values;
73
94
  }
74
95
 
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));
96
+ /** Full cards for the entries of one tree (used by rebuilds and listRaw). */
97
+ function readTreeTasks(repo, tree) {
98
+ if (tree.length === 0) return [];
99
+ const blobs = readBlobs(repo, tree.map((entry) => entry.blobSha));
82
100
  const rows = [];
83
- for (let index = 0; index < entries.length; index += 1) {
101
+ for (let index = 0; index < tree.length; index += 1) {
84
102
  const text = blobs[index];
85
103
  if (text === null) continue;
86
104
  let value = null;
87
105
  try { value = JSON.parse(text); } catch { value = null; }
88
- if (value) rows.push({ id: entries[index].id, value });
106
+ if (value) rows.push({ id: tree[index].id, value });
89
107
  }
90
108
  return rows;
91
109
  }
92
110
 
111
+ /** [{ id, value }] from the task tree. An absent ref is an empty board. */
112
+ export function listRaw(repo) {
113
+ const sha = refSha(repo);
114
+ if (!sha) return [];
115
+ return readTreeTasks(repo, readTree(repo, sha));
116
+ }
117
+
93
118
  /** One card by id: a single blob read, never the whole tree. */
94
119
  export function readTask(repo, id) {
95
120
  const sha = refSha(repo);
@@ -99,23 +124,21 @@ export function readTask(repo, id) {
99
124
  try { return JSON.parse(result.stdout); } catch { return null; }
100
125
  }
101
126
 
102
- /** Full cards for a known page of ids, in one batch call. */
103
- export function readTasksByIds(repo, ids) {
127
+ /** Full cards for a known list of ids, aligned with the input (null per miss). */
128
+ export function readTasksByIdsAligned(repo, ids) {
104
129
  if (!Array.isArray(ids) || ids.length === 0) return [];
105
130
  const sha = refSha(repo);
106
- if (!sha) return [];
131
+ if (!sha) return ids.map(() => null);
107
132
  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;
133
+ return blobs.map((text) => {
134
+ if (text === null) return null;
135
+ try { return JSON.parse(text); } catch { return null; }
136
+ });
137
+ }
138
+
139
+ /** Full cards for a known list of ids, skipping misses. */
140
+ export function readTasksByIds(repo, ids) {
141
+ return readTasksByIdsAligned(repo, ids).filter(Boolean);
119
142
  }
120
143
 
121
144
  /** Sort key shared by the index writer and readers: newest lane change first. */
@@ -125,15 +148,54 @@ export function taskSortTime(task) {
125
148
  return Number.isFinite(time) ? time : 0;
126
149
  }
127
150
 
128
- export function buildIndexEntries(tasks) {
129
- return tasks.map((task) => [
130
- task.id,
151
+ function flagsOf(task) {
152
+ let flags = 0;
153
+ if (task.superseded === true) flags |= FLAG.superseded;
154
+ if (task.draft === true) flags |= FLAG.draft;
155
+ if (Array.isArray(task.tags) && task.tags.includes("fix")) flags |= FLAG.fix;
156
+ return flags;
157
+ }
158
+
159
+ function stageStateOf(task) {
160
+ return isStaged(task) && typeof task.stageState === "string" ? task.stageState : null;
161
+ }
162
+
163
+ function stageRoleOf(task) {
164
+ if (!isStaged(task)) return null;
165
+ const stage = currentStage(task);
166
+ return stage && typeof stage.role === "string" ? stage.role : null;
167
+ }
168
+
169
+ function claimedUntilOf(task) {
170
+ if (!task.claimedUntil) return null;
171
+ const time = Date.parse(task.claimedUntil);
172
+ return Number.isFinite(time) ? time : null;
173
+ }
174
+
175
+ function buildEntry(id, task) {
176
+ return [
177
+ id,
131
178
  task.state,
132
- task.role || "",
179
+ typeof task.role === "string" ? task.role : "",
133
180
  taskSortTime(task),
134
- task.createdAt || "",
135
- task.superseded === true ? 1 : 0,
136
- ]);
181
+ typeof task.createdAt === "string" ? task.createdAt : "",
182
+ flagsOf(task),
183
+ Number.isFinite(task.priority) ? task.priority : 0,
184
+ Array.isArray(task.after) && task.after.length > 0 ? [...task.after] : null,
185
+ stageStateOf(task),
186
+ claimedUntilOf(task),
187
+ stageRoleOf(task),
188
+ ];
189
+ }
190
+
191
+ /** Rows for the write path: every task already carries its immutable tree id. */
192
+ export function buildIndexEntries(tasks) {
193
+ return tasks.map((task) => buildEntry(task.id, task));
194
+ }
195
+
196
+ /** Rows for a rebuild: the tree entry name wins over the blob's id field. */
197
+ function buildEntriesFromRows(rows) {
198
+ return rows.map((row) => buildEntry(row.id, row.value));
137
199
  }
138
200
 
139
201
  function readIndexBlob(repo) {
@@ -144,46 +206,100 @@ function readIndexBlob(repo) {
144
206
  try { return JSON.parse(result.stdout); } catch { return null; }
145
207
  }
146
208
 
209
+ /** Delete the derived index (empty board / no tasks ref). */
210
+ function clearIndex(repo) {
211
+ git(["update-ref", "-d", TASKS_INDEX_REF], { cwd: repo.top, allowFail: true });
212
+ }
213
+
214
+ /** Write the index blob; returns false when the ref cannot be updated. */
147
215
  function writeIndex(repo, tasksSha, entries) {
148
216
  const blob = out(["hash-object", "-w", "--stdin"], {
149
217
  cwd: repo.top,
150
218
  input: JSON.stringify({ v: INDEX_VERSION, tasks: tasksSha, entries }),
151
219
  });
152
- git(["update-ref", TASKS_INDEX_REF, blob], { cwd: repo.top, allowFail: true });
220
+ return git(["update-ref", TASKS_INDEX_REF, blob], { cwd: repo.top, allowFail: true }).status === 0;
221
+ }
222
+
223
+ function validEntry(entry, treeNames) {
224
+ if (!Array.isArray(entry) || entry.length !== ENTRY_LENGTH) return false;
225
+ const [id, state, role, time, createdAt, flags, priority, after, stageState, claimedUntil, stageRole] = entry;
226
+ if (typeof id !== "string" || id === "" || !treeNames.has(id)) return false;
227
+ if (!STATES.has(state)) return false;
228
+ if (typeof role !== "string") return false;
229
+ if (!Number.isFinite(time) || typeof createdAt !== "string") return false;
230
+ if (!Number.isInteger(flags) || flags < 0 || flags > 7) return false;
231
+ if (!Number.isFinite(priority)) return false;
232
+ if (after !== null && (!Array.isArray(after) || after.some((dep) => typeof dep !== "string"))) return false;
233
+ if (stageState !== null && !STATES.has(stageState)) return false;
234
+ if (claimedUntil !== null && !Number.isFinite(claimedUntil)) return false;
235
+ if (stageRole !== null && typeof stageRole !== "string") return false;
236
+ return true;
237
+ }
238
+
239
+ /** Validated entries, or null when the cache is corrupt/stale/duplicated. */
240
+ function validateEntries(entries, treeNames) {
241
+ if (!Array.isArray(entries)) return null;
242
+ const seen = new Set();
243
+ for (const entry of entries) {
244
+ if (!validEntry(entry, treeNames)) return null;
245
+ if (seen.has(entry[ROW.id])) return null;
246
+ seen.add(entry[ROW.id]);
247
+ }
248
+ return entries;
153
249
  }
154
250
 
155
251
  /**
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.
252
+ * Index rows for a read-only consumer. Never writes: a missing, stale or corrupt
253
+ * index is rebuilt in memory for this call (the caller can surface `rebuilt`).
159
254
  */
160
- export function readIndex(repo) {
255
+ export function readIndexForRead(repo) {
161
256
  const tasksSha = refSha(repo);
162
- if (!tasksSha) return { tasksSha: null, entries: [] };
257
+ if (!tasksSha) return { tasksSha: null, entries: [], rebuilt: false };
258
+ const tree = readTree(repo, tasksSha);
259
+ const treeNames = new Set(tree.map((entry) => entry.id));
163
260
  const cached = readIndexBlob(repo);
164
- if (cached && cached.v === INDEX_VERSION && cached.tasks === tasksSha && Array.isArray(cached.entries)) {
165
- return { tasksSha, entries: cached.entries };
261
+ if (cached && cached.v === INDEX_VERSION && cached.tasks === tasksSha) {
262
+ const entries = validateEntries(cached.entries, treeNames);
263
+ if (entries) return { tasksSha, entries, rebuilt: false };
166
264
  }
167
- const tasks = listRaw(repo).map((entry) => entry.value);
168
- const entries = buildIndexEntries(tasks);
169
- writeIndex(repo, tasksSha, entries);
170
- return { tasksSha, entries };
265
+ const rows = readTreeTasks(repo, tree);
266
+ return { tasksSha, entries: buildEntriesFromRows(rows), rebuilt: true };
267
+ }
268
+
269
+ /**
270
+ * Explicit rebuild of the derived index (the `reindex` command). Writes the
271
+ * index ref only; the task tree and the working tree are untouched.
272
+ */
273
+ export function reindex(repo) {
274
+ for (let attempt = 0; attempt < 8; attempt += 1) {
275
+ const tasksSha = refSha(repo);
276
+ if (!tasksSha) {
277
+ clearIndex(repo);
278
+ return { ok: true, tasks: null, entries: 0 };
279
+ }
280
+ const tree = readTree(repo, tasksSha);
281
+ const entries = buildEntriesFromRows(readTreeTasks(repo, tree));
282
+ if (!writeIndex(repo, tasksSha, entries)) continue;
283
+ if (refSha(repo) === tasksSha) return { ok: true, tasks: tasksSha, entries: entries.length };
284
+ }
285
+ return { ok: false, tasks: null, entries: 0 };
171
286
  }
172
287
 
173
288
  /** Newest stateChangedAt first; ids break ties so paging is deterministic. */
174
289
  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]));
290
+ if (left[ROW.time] !== right[ROW.time]) return right[ROW.time] - left[ROW.time];
291
+ return String(left[ROW.id]).localeCompare(String(right[ROW.id]));
177
292
  }
178
293
 
179
294
  /**
180
295
  * 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.
296
+ * page. Superseded rows are hidden by default so page totals match counts.
182
297
  */
183
- export function paginateIndexEntries(entries, { state = null, role = null, limit = DEFAULT_PAGE_LIMIT, cursor = 0 } = {}) {
298
+ export function paginateIndexEntries(entries, { state = null, role = null, limit = DEFAULT_PAGE_LIMIT, cursor = 0, includeSuperseded = false } = {}) {
184
299
  let rows = entries;
185
- if (state) rows = rows.filter((entry) => entry[1] === state);
186
- if (role) rows = rows.filter((entry) => entry[2] === role);
300
+ if (!includeSuperseded) rows = rows.filter((entry) => (entry[ROW.flags] & FLAG.superseded) === 0);
301
+ if (state) rows = rows.filter((entry) => entry[ROW.state] === state);
302
+ if (role) rows = rows.filter((entry) => entry[ROW.role] === role);
187
303
  rows = rows.slice().sort(compareIndexRows);
188
304
  const total = rows.length;
189
305
  const start = Math.min(Math.max(0, cursor), total);
@@ -192,45 +308,75 @@ export function paginateIndexEntries(entries, { state = null, role = null, limit
192
308
  return { page, total, cursor: next, hasMore: next < total };
193
309
  }
194
310
 
311
+ /** Page payload with cards; index/card id mismatches are counted as skipped. */
312
+ export function pageFromEntries(repo, entries, options) {
313
+ const page = paginateIndexEntries(entries, options);
314
+ const ids = page.page.map((entry) => entry[ROW.id]);
315
+ const cards = readTasksByIdsAligned(repo, ids);
316
+ const items = [];
317
+ let skipped = 0;
318
+ for (let index = 0; index < ids.length; index += 1) {
319
+ const card = cards[index];
320
+ if (!card || card.id !== ids[index]) { skipped += 1; continue; }
321
+ items.push(card);
322
+ }
323
+ return { items, total: page.total, cursor: page.cursor, hasMore: page.hasMore, skipped };
324
+ }
325
+
195
326
  /**
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.
327
+ * Ready rows computed from the index only: dependencies, draft/superseded/fix
328
+ * flags, stage readiness and the reclaim rule, then the queue order.
199
329
  */
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 };
330
+ export function readyEntries(entries, { modeFree = true, now = Date.now() } = {}) {
331
+ const stateById = new Map(entries.map((entry) => [entry[ROW.id], entry[ROW.state]]));
332
+ const rows = [];
333
+ for (const entry of entries) {
334
+ const flags = entry[ROW.flags];
335
+ if ((flags & (FLAG.superseded | FLAG.draft)) !== 0) continue;
336
+ const state = entry[ROW.state];
337
+ const claimedUntil = entry[ROW.claimedUntil];
338
+ const reclaimable = state === "claimed" && claimedUntil !== null && claimedUntil <= now;
339
+ if (state !== "pending" && !reclaimable) continue;
340
+ const after = entry[ROW.after];
341
+ if (after && after.some((dep) => stateById.get(dep) !== "done")) continue;
342
+ const stageState = entry[ROW.stageState];
343
+ if (stageState !== null && !(stageState === "pending" || (stageState === "claimed" && reclaimable))) continue;
344
+ if (!modeFree && (flags & FLAG.fix) === 0) continue;
345
+ rows.push({
346
+ id: entry[ROW.id],
347
+ role: entry[ROW.stageRole] ?? entry[ROW.role],
348
+ priority: entry[ROW.priority],
349
+ createdAt: entry[ROW.createdAt],
350
+ });
351
+ }
352
+ rows.sort((left, right) => order({ priority: left.priority, createdAt: left.createdAt }, { priority: right.priority, createdAt: right.createdAt }));
353
+ return rows;
207
354
  }
208
355
 
209
356
  /**
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.
357
+ * Counts over index rows. Superseded tasks are counted separately and never
358
+ * inside byState/byRole; `live` is the non-superseded total so a paginated
359
+ * list (which hides superseded rows too) has a matching total.
213
360
  */
214
361
  export function summarizeEntries(entries) {
215
362
  const byState = {};
216
363
  const byRole = {};
217
364
  let superseded = 0;
218
365
  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) };
366
+ for (const entry of entries) {
367
+ if ((entry[ROW.flags] & FLAG.superseded) !== 0) { superseded += 1; continue; }
368
+ byState[entry[ROW.state]] = (byState[entry[ROW.state]] || 0) + 1;
369
+ byRole[entry[ROW.role]] = (byRole[entry[ROW.role]] || 0) + 1;
370
+ if (entry[ROW.state] === "pending" && (oldest === null || String(entry[ROW.createdAt]) < String(oldest.createdAt))) {
371
+ oldest = { id: entry[ROW.id], createdAt: String(entry[ROW.createdAt]) };
225
372
  }
226
373
  }
227
- return { total: entries.length, byState, byRole, superseded, oldestPending: oldest };
374
+ return { total: entries.length, live: entries.length - superseded, byState, byRole, superseded, oldestPending: oldest };
228
375
  }
229
376
 
230
- /** Counts for the whole board from the lightweight index. */
377
+ /** Whole-board summary (index-backed, read-only). */
231
378
  export function summarizeIndex(repo) {
232
- const { entries } = readIndex(repo);
233
- return summarizeEntries(entries);
379
+ return summarizeEntries(readIndexForRead(repo).entries);
234
380
  }
235
381
 
236
382
  function hashBlob(repo, value) {
@@ -239,8 +385,9 @@ function hashBlob(repo, value) {
239
385
 
240
386
  /**
241
387
  * 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).
388
+ * The lightweight index is refreshed after the task ref moves (cache only; a
389
+ * failure to write it never fails the task write). Returns false when the ref
390
+ * moved underneath us (caller retries).
244
391
  */
245
392
  function write(repo, tasks, expectedSha) {
246
393
  const indexFile = path.join(repo.stateDir, "index-tasks-" + process.pid + "-" + crypto.randomBytes(4).toString("hex"));
@@ -282,3 +429,10 @@ export function mutate(repo, fn) {
282
429
  }
283
430
  return { ok: false, tasks: [] };
284
431
  }
432
+
433
+ /**
434
+ * Backwards-compatible page reader (read-only; rebuilds in memory when needed).
435
+ */
436
+ export function readTaskPage(repo, options = {}) {
437
+ return pageFromEntries(repo, readIndexForRead(repo).entries, options);
438
+ }