hive-tasks 1.9.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 +72 -2
- package/README.md +48 -3
- package/README.zh-CN.md +42 -3
- package/SPEC.md +58 -4
- package/package.json +1 -1
- package/src/cli.js +185 -65
- package/src/git.js +19 -0
- package/src/store.js +377 -19
package/CHANGELOG.md
CHANGED
|
@@ -4,7 +4,69 @@ 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
|
-
##
|
|
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.
|
|
47
|
+
## [1.10.0] - 2026-12-06
|
|
48
|
+
|
|
49
|
+
### Added
|
|
50
|
+
|
|
51
|
+
- `HIVE_EVENT_ACTOR` decouples event `actor` from the task owner/claim identity; the
|
|
52
|
+
runner sets it to `worker:<role>` for worker CLI calls while the claim owner stays
|
|
53
|
+
the runner identity.
|
|
54
|
+
- `list --json --state S --role R --limit N --cursor C` returns one server-side page,
|
|
55
|
+
`{ items, total, cursor, hasMore }`, ordered by stateChangedAt descending (ties by
|
|
56
|
+
id); only the page's card blobs are read and cursor is the numeric offset returned
|
|
57
|
+
by the previous page.
|
|
58
|
+
- `counts --json` returns `{ total, byState, superseded, oldestPending }` from a
|
|
59
|
+
lightweight index; `stats` is index-backed too and keeps its shape.
|
|
60
|
+
- `show <id> --json` reads exactly one card blob.
|
|
61
|
+
- Derived `refs/hive/v1/tasks-index` cache, refreshed after every board write and
|
|
62
|
+
rebuilt once when missing or stale.
|
|
63
|
+
|
|
64
|
+
### Tests
|
|
65
|
+
|
|
66
|
+
- 68 node:test scenarios: the 62 from 1.9.0 unchanged, plus six in
|
|
67
|
+
test/pagination.test.mjs covering page walking against the filtered full list,
|
|
68
|
+
boundaries, counts versus stats, index rebuild after a missing/stale index, pages and
|
|
69
|
+
counts being index-only while show reads one blob, and a 100k-entry mock index.
|
|
8
70
|
|
|
9
71
|
### Changed
|
|
10
72
|
|
|
@@ -16,6 +78,10 @@ All notable changes to this project are documented here. The format follows
|
|
|
16
78
|
"never starts a process" claim and the generated id length). No behaviour or protocol
|
|
17
79
|
change.
|
|
18
80
|
|
|
81
|
+
### Published
|
|
82
|
+
|
|
83
|
+
- npm: `hive-tasks@1.10.0` on 2026-12-06.
|
|
84
|
+
|
|
19
85
|
## [1.9.0] - 2026-12-04
|
|
20
86
|
|
|
21
87
|
### Added
|
|
@@ -55,6 +121,10 @@ All notable changes to this project are documented here. The format follows
|
|
|
55
121
|
|
|
56
122
|
- Not published to npm in this change.
|
|
57
123
|
|
|
124
|
+
### Published
|
|
125
|
+
|
|
126
|
+
- npm: `hive-tasks@1.9.0` on 2026-12-04.
|
|
127
|
+
|
|
58
128
|
## [1.8.1] - 2026-12-04
|
|
59
129
|
|
|
60
130
|
### Added
|
|
@@ -316,4 +386,4 @@ All notable changes to this project are documented here. The format follows
|
|
|
316
386
|
[1.4.0]: https://github.com/d86e/hive-tasks/releases/tag/v1.4.0
|
|
317
387
|
[1.3.0]: https://github.com/d86e/hive-tasks/releases/tag/v1.3.0
|
|
318
388
|
[1.1.0]: https://github.com/d86e/hive-tasks/releases/tag/v1.1.0
|
|
319
|
-
[1.0.0]: https://github.com/d86e/hive-tasks/releases/tag/v1.0.0
|
|
389
|
+
[1.0.0]: https://github.com/d86e/hive-tasks/releases/tag/v1.0.0
|
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] | every task,
|
|
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,9 @@ 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
|
-
|
|
|
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 |
|
|
95
|
+
| stats [--json] | counts by state and role, plus the oldest pending task (index-backed) |
|
|
94
96
|
|
|
95
97
|
Exit codes: 0 success, 1 internal error, 2 refused (already claimed, wrong state, unknown
|
|
96
98
|
task, dependency missing, mode freeze, invalid stage chain, missing --acceptance, draft
|
|
@@ -131,9 +133,52 @@ Counts by state and role, plus the oldest pending task. Superseded tasks keep th
|
|
|
131
133
|
lane but are counted separately: `superseded` in the JSON and its own line in the text
|
|
132
134
|
output; they are not part of byState/byRole or the oldest pending task.
|
|
133
135
|
|
|
136
|
+
## Pagination and counts
|
|
137
|
+
|
|
138
|
+
Large boards are served a page at a time. `--limit` and/or `--cursor` switch
|
|
139
|
+
`list` into server-side pagination:
|
|
140
|
+
|
|
141
|
+
~~~bash
|
|
142
|
+
$ hive-tasks list --json --state pending --limit 50 --cursor 0
|
|
143
|
+
{ "items": [ ... ], "total": 1234, "cursor": 50, "hasMore": true, "skipped": 0 }
|
|
144
|
+
$ hive-tasks list --json --state pending --limit 50 --cursor 50 # next page
|
|
145
|
+
~~~
|
|
146
|
+
|
|
147
|
+
- rows are ordered by `stateChangedAt` descending, ties broken by id so a walk is
|
|
148
|
+
deterministic;
|
|
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;
|
|
155
|
+
- only the page's cards are read from git; filtering, ordering and the total come from
|
|
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
|
+
A `list` without `--limit`/`--cursor` keeps returning the full array. `counts --json`
|
|
163
|
+
returns the per-state numbers from that index without parsing any card:
|
|
164
|
+
|
|
165
|
+
~~~bash
|
|
166
|
+
$ hive-tasks counts --json
|
|
167
|
+
{ "total": 1234, "live": 1232, "byState": { "pending": 1200, "claimed": 3, "done": 30, "failed": 1 },
|
|
168
|
+
"superseded": 2, "oldestPending": { "id": "auth-token-a1b2", "createdAt": "..." } }
|
|
169
|
+
~~~
|
|
170
|
+
|
|
171
|
+
`show <id> --json` reads exactly that one card blob. `stats` keeps its older shape
|
|
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.
|
|
176
|
+
|
|
134
177
|
## How a claim works
|
|
135
178
|
|
|
136
|
-
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;
|
|
137
182
|
2. every scope path is announced on the hive-consensus announcement board; the latest
|
|
138
183
|
announcement wins and a live announcement by another agent is reported as an
|
|
139
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] |
|
|
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,9 @@ 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
|
-
|
|
|
92
|
+
| counts [--json] | 各状态存活计数、`live`、superseded 计数和最老 pending 任务,来自轻量索引 |
|
|
93
|
+
| reindex [--json] | 重建并持久化派生任务索引;只读命令永远不写它 |
|
|
94
|
+
| stats [--json] | 按状态和角色计数,外加最老的 pending 任务;superseded 单独计数(同样走索引) |
|
|
93
95
|
|
|
94
96
|
退出码:0 成功,1 内部错误,2 被拒(已被认领、状态不对、任务不存在、依赖缺失、
|
|
95
97
|
模式 freeze、阶段链非法、缺 --acceptance、认领草稿任务)。
|
|
@@ -125,9 +127,46 @@ hive-tasks stats --json
|
|
|
125
127
|
按状态和角色计数,外加最老的 pending 任务。superseded 任务保留原 lane,但单独计数:
|
|
126
128
|
JSON 里是 `superseded`,文本输出单独一行;它们不计入 byState/byRole,也不参与最老 pending。
|
|
127
129
|
|
|
130
|
+
## 分页与计数
|
|
131
|
+
|
|
132
|
+
大看板按页读取。`--limit` 和/或 `--cursor` 会把 `list` 切成服务端分页:
|
|
133
|
+
|
|
134
|
+
~~~bash
|
|
135
|
+
$ hive-tasks list --json --state pending --limit 50 --cursor 0
|
|
136
|
+
{ "items": [ ... ], "total": 1234, "cursor": 50, "hasMore": true, "skipped": 0 }
|
|
137
|
+
$ hive-tasks list --json --state pending --limit 50 --cursor 50 # 下一页
|
|
138
|
+
~~~
|
|
139
|
+
|
|
140
|
+
- 行按 `stateChangedAt` 倒序,时间相同按 id 升序,保证翻页顺序稳定;
|
|
141
|
+
- `cursor` 是上一页返回的数字偏移;`--limit`/`--cursor` 只接受文档范围内的十进制
|
|
142
|
+
整数(`0x10`、`1e1`、`+3`、`2.0`、带空格的 `" 5 "`、`-0` 都会被拒);
|
|
143
|
+
- `total` 是过滤后的存活总数,调用方能算出还剩几页;
|
|
144
|
+
- 默认隐藏 superseded 卡,因此分页 total 与 `counts` 对得上;
|
|
145
|
+
`--include-superseded` 返回包含它们的全量视图;
|
|
146
|
+
- 只读取当前页的卡片 blob;过滤、排序和总数来自轻量索引
|
|
147
|
+
(`refs/hive/v1/tasks-index`)。只读命令永不写该索引:缺失/过期/损坏时只为本次
|
|
148
|
+
命令在内存中重建,`reindex` 才持久化;只读仓库没有可用索引时明确报错,不会全树
|
|
149
|
+
扫描或崩溃。索引行 id 与卡片 id 不一致时计入 `skipped`(`show` 会拒绝),不再
|
|
150
|
+
静默丢卡。
|
|
151
|
+
|
|
152
|
+
不带 `--limit`/`--cursor` 的 `list` 仍返回完整数组。`counts --json` 直接从索引返回
|
|
153
|
+
各状态计数,不解析任何卡片:
|
|
154
|
+
|
|
155
|
+
~~~bash
|
|
156
|
+
$ hive-tasks counts --json
|
|
157
|
+
{ "total": 1234, "live": 1232, "byState": { "pending": 1200, "claimed": 3, "done": 30, "failed": 1 },
|
|
158
|
+
"superseded": 2, "oldestPending": { "id": "auth-token-a1b2", "createdAt": "..." } }
|
|
159
|
+
~~~
|
|
160
|
+
|
|
161
|
+
`show <id> --json` 只读取那一张卡的 blob。`stats` 保持原有输出形状
|
|
162
|
+
(byState、byRole、superseded、oldestPending),同样由索引支撑。`ready` 和 `next` 也走
|
|
163
|
+
索引:依赖状态、draft/superseded/fix 标记、阶段就绪、认领过期和排队顺序都从索引行
|
|
164
|
+
计算,只解析返回给调用方的卡片,因此 10 万卡仓库上的调度器不再全树扫描。
|
|
165
|
+
|
|
128
166
|
## claim 怎么走
|
|
129
167
|
|
|
130
|
-
1. 任务 CAS 把 pending 推到 claimed
|
|
168
|
+
1. 任务 CAS 把 pending 推到 claimed(一个任务唯一赢家)。若每次 CAS 重试都被别的写者抢先,
|
|
169
|
+
claim 会以退出码 1 报 contention 并且不写任何公告;事件和 presence ref 只在卡片落库后写;
|
|
131
170
|
2. scope 里每个路径都公告到 hive-consensus 的公告看板:后来者覆盖公告,别人的存活公告
|
|
132
171
|
作为 overlap 返回;
|
|
133
172
|
3. done、fail、reopen 和 rm --force 释放这次认领自己写的公告(retry 只接受 failed 任务,
|
package/SPEC.md
CHANGED
|
@@ -47,6 +47,25 @@ 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
|
+
A derived index lives next to the tree and is never the source of truth:
|
|
51
|
+
|
|
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.
|
|
68
|
+
|
|
50
69
|
## 3. Task blob
|
|
51
70
|
|
|
52
71
|
```json
|
|
@@ -343,7 +362,10 @@ see the same order; the claim CAS still gives exactly one winner per task.
|
|
|
343
362
|
[--after ID]... [--goal G] [--review-of ID] [--tag T]...
|
|
344
363
|
[--priority N] [--stage ROLE[:ACCEPTANCE]]... [--stages FILE]
|
|
345
364
|
hive-tasks plan [--file plan.json] # no --file reads the plan from stdin
|
|
346
|
-
hive-tasks list [--json] [--state S] [--role R]
|
|
365
|
+
hive-tasks list [--json] [--state S] [--role R] [--limit N] [--cursor C]
|
|
366
|
+
[--include-superseded]
|
|
367
|
+
hive-tasks counts [--json]
|
|
368
|
+
hive-tasks reindex [--json]
|
|
347
369
|
hive-tasks ready [--json] [--limit N] [--role R]
|
|
348
370
|
hive-tasks next [--role R] [--json] # the single best candidate, or null
|
|
349
371
|
hive-tasks show <id> [--json] # task plus resolved role source
|
|
@@ -378,12 +400,44 @@ stage key is derived from the role (a repeated role becomes coder-2, coder-3...)
|
|
|
378
400
|
FILE` takes a JSON array of stage objects and is the way to set explicit keys, onFail and
|
|
379
401
|
per-stage acceptance in one shot. The two flags are mutually exclusive.
|
|
380
402
|
|
|
381
|
-
Exit codes: 0 success; 1 internal error
|
|
382
|
-
|
|
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).
|
|
407
|
+
|
|
408
|
+
`list --json --state S --role R --limit N --cursor C` returns one server-side page:
|
|
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
|
|
424
|
+
lightweight index without parsing card blobs; superseded tasks are counted separately and
|
|
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.
|
|
383
434
|
|
|
384
435
|
claim couples the task with the hive-consensus announcement board, task first:
|
|
385
436
|
|
|
386
|
-
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;
|
|
387
441
|
2. announce every scope path (refs/hive/v1/lease/<key>/__key__). The announcement phase
|
|
388
442
|
never fails the claim: the latest announcement wins, and a live announcement by
|
|
389
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.
|
|
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 { listRaw, mutate, readTask } 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,
|
|
@@ -41,7 +41,14 @@ const USAGE = [
|
|
|
41
41
|
" task is superseded and points at the first subtask",
|
|
42
42
|
" hive-tasks supersede <id> --reason R [--replaced-by ID]",
|
|
43
43
|
" retire a task without done/failed; never dispatched",
|
|
44
|
-
" hive-tasks list [--json] [--state S] [--role R]",
|
|
44
|
+
" hive-tasks list [--json] [--state S] [--role R] [--limit N] [--cursor C]",
|
|
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)",
|
|
45
52
|
" hive-tasks show <id> [--json] card plus the resolved role source",
|
|
46
53
|
" hive-tasks ready [--json] [--limit N] [--role R]",
|
|
47
54
|
" hive-tasks next [--role R] [--json] the single best candidate",
|
|
@@ -81,7 +88,7 @@ function value(argv, index, flag) {
|
|
|
81
88
|
}
|
|
82
89
|
|
|
83
90
|
function parse(argv) {
|
|
84
|
-
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, 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 };
|
|
85
92
|
for (let i = 0; i < argv.length; i++) {
|
|
86
93
|
const arg = argv[i];
|
|
87
94
|
if (arg === "--json") out.json = true;
|
|
@@ -111,7 +118,15 @@ function parse(argv) {
|
|
|
111
118
|
else if (arg === "--sha") out.sha = value(argv, i++, arg);
|
|
112
119
|
else if (arg === "--state") out.state = value(argv, i++, arg);
|
|
113
120
|
else if (arg === "--role") out.role = value(argv, i++, arg);
|
|
114
|
-
else if (arg === "--limit")
|
|
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;
|
|
115
130
|
else if (arg === "--title") out.title = value(argv, i++, arg);
|
|
116
131
|
else if (arg === "--goal") out.goal = value(argv, i++, arg);
|
|
117
132
|
else if (arg === "--priority") out.priority = Number(value(argv, i++, arg));
|
|
@@ -121,6 +136,11 @@ function parse(argv) {
|
|
|
121
136
|
return out;
|
|
122
137
|
}
|
|
123
138
|
|
|
139
|
+
function eventActor(fallback) {
|
|
140
|
+
const value = (process.env.HIVE_EVENT_ACTOR || '').trim();
|
|
141
|
+
return value !== '' ? value : (fallback || 'unknown');
|
|
142
|
+
}
|
|
143
|
+
|
|
124
144
|
function identity(repo, explicit) {
|
|
125
145
|
const name = explicit || process.env.HIVE_AGENT || git(["config", "--get", "hive.agent"], { cwd: repo.top, allowFail: true }).stdout.trim();
|
|
126
146
|
if (!name) fail("an identity is required (--agent, HIVE_AGENT, or git config hive.agent)", 2);
|
|
@@ -351,12 +371,41 @@ function stageTarget(options) {
|
|
|
351
371
|
return options.stageArgs.length ? options.stageArgs[options.stageArgs.length - 1] : null;
|
|
352
372
|
}
|
|
353
373
|
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
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 };
|
|
360
409
|
}
|
|
361
410
|
|
|
362
411
|
/**
|
|
@@ -444,6 +493,16 @@ function run(argv) {
|
|
|
444
493
|
return;
|
|
445
494
|
}
|
|
446
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
|
+
|
|
447
506
|
if (command === "plan") {
|
|
448
507
|
const raw = options.file ? fs.readFileSync(options.file, "utf8") : fs.readFileSync(0, "utf8");
|
|
449
508
|
let plan;
|
|
@@ -491,7 +550,7 @@ function run(argv) {
|
|
|
491
550
|
return [...tasks, ...drafts.map((draft) => draft.task)];
|
|
492
551
|
});
|
|
493
552
|
if (!result.ok) fail("could not write the task board");
|
|
494
|
-
append(repo, { actor: "planner", kind: "task_plan", count: drafts.length });
|
|
553
|
+
append(repo, { actor: eventActor("planner"), kind: "task_plan", count: drafts.length });
|
|
495
554
|
for (const draft of drafts) process.stdout.write(draft.task.id + " " + draft.task.title + "\n");
|
|
496
555
|
return;
|
|
497
556
|
}
|
|
@@ -506,7 +565,7 @@ function run(argv) {
|
|
|
506
565
|
if (current.state !== "claimed" || current.owner !== agent) fail("task " + id + " is not claimed by " + agent, 2);
|
|
507
566
|
const result = mutate(repo, (tasks) => tasks.map((entry) => (entry.id === id ? { ...entry, claimedUntil: new Date(Date.now() + ttlMs).toISOString(), updatedAt: new Date().toISOString() } : entry)));
|
|
508
567
|
if (!result.ok) fail("could not renew " + id);
|
|
509
|
-
append(repo, { actor: agent, kind: "task_renew", task: id });
|
|
568
|
+
append(repo, { actor: eventActor(agent), kind: "task_renew", task: id });
|
|
510
569
|
process.stdout.write(id + " renewed for " + Math.round(ttlMs / 1000) + "s\n");
|
|
511
570
|
return;
|
|
512
571
|
}
|
|
@@ -525,7 +584,7 @@ function run(argv) {
|
|
|
525
584
|
// Legacy cards keep the idempotent no-op. A staged card always resets to
|
|
526
585
|
// the requested stage (default the first), so a chain can be re-run.
|
|
527
586
|
if (!isStaged(current) && current.state === "pending") {
|
|
528
|
-
append(repo, { actor: agent, kind: "reopen", task: id, reason, noop: true });
|
|
587
|
+
append(repo, { actor: eventActor(agent), kind: "reopen", task: id, reason, noop: true });
|
|
529
588
|
return printTask(current, options.json);
|
|
530
589
|
}
|
|
531
590
|
|
|
@@ -549,13 +608,13 @@ function run(argv) {
|
|
|
549
608
|
if (!result.ok) fail("could not reopen " + id);
|
|
550
609
|
|
|
551
610
|
if (!reopened) {
|
|
552
|
-
append(repo, { actor: agent, kind: "reopen", task: id, reason, noop: true });
|
|
611
|
+
append(repo, { actor: eventActor(agent), kind: "reopen", task: id, reason, noop: true });
|
|
553
612
|
return printTask(readTask(repo, id), options.json);
|
|
554
613
|
}
|
|
555
614
|
|
|
556
615
|
// A claimed card may still hold announcements; release exactly the claim we reset.
|
|
557
616
|
if (previous.state === "claimed") releaseLeases(repo, { paths: previous.scope, agent: previous.owner || agent });
|
|
558
|
-
append(repo, { actor: agent, kind: "reopen", task: id, from: previous.state, reason, attempt: reopened.attempt, stage: isStaged(reopened) ? reopened.stage : undefined });
|
|
617
|
+
append(repo, { actor: eventActor(agent), kind: "reopen", task: id, from: previous.state, reason, attempt: reopened.attempt, stage: isStaged(reopened) ? reopened.stage : undefined });
|
|
559
618
|
return printTask(reopened, options.json);
|
|
560
619
|
}
|
|
561
620
|
|
|
@@ -591,7 +650,7 @@ function run(argv) {
|
|
|
591
650
|
// --force deletes a claimed card only after releasing exactly the announcements
|
|
592
651
|
// that claim holds, so a forced delete cannot strand them.
|
|
593
652
|
if (deleted.state === "claimed") releaseLeases(repo, { paths: deleted.scope, agent: deleted.owner || agent });
|
|
594
|
-
append(repo, { actor: agent, kind: "task_delete", task: id, id, state: deleted.state });
|
|
653
|
+
append(repo, { actor: eventActor(agent), kind: "task_delete", task: id, id, state: deleted.state });
|
|
595
654
|
if (options.json) return process.stdout.write(JSON.stringify({ ...viewTask(deleted), deleted: true }, null, 2) + "\n");
|
|
596
655
|
return process.stdout.write(id + " deleted [" + deleted.state + "] " + deleted.title + "\n");
|
|
597
656
|
}
|
|
@@ -660,7 +719,7 @@ function run(argv) {
|
|
|
660
719
|
if (fields.length > 0) {
|
|
661
720
|
const changed = {};
|
|
662
721
|
for (const name of fields) changed[name] = true;
|
|
663
|
-
append(repo, { actor, kind: "task_edit", task: id, fields: changed });
|
|
722
|
+
append(repo, { actor: eventActor(actor), kind: "task_edit", task: id, fields: changed });
|
|
664
723
|
}
|
|
665
724
|
return printTask(updated, options.json);
|
|
666
725
|
}
|
|
@@ -721,7 +780,7 @@ function run(argv) {
|
|
|
721
780
|
fail(error.message, 2);
|
|
722
781
|
}
|
|
723
782
|
|
|
724
|
-
const event = { actor, kind: "task_split", task: id, cards: cards.map((card) => card.id), kept: Boolean(options.keep) };
|
|
783
|
+
const event = { actor: eventActor(actor), kind: "task_split", task: id, cards: cards.map((card) => card.id), kept: Boolean(options.keep) };
|
|
725
784
|
if (!options.keep) event.replacedBy = cards[0].id;
|
|
726
785
|
append(repo, event);
|
|
727
786
|
if (options.json) {
|
|
@@ -762,7 +821,7 @@ function run(argv) {
|
|
|
762
821
|
} catch (error) {
|
|
763
822
|
fail(error.message, 2);
|
|
764
823
|
}
|
|
765
|
-
const event = { actor, kind: "task_supersede", task: id, reason };
|
|
824
|
+
const event = { actor: eventActor(actor), kind: "task_supersede", task: id, reason };
|
|
766
825
|
if (updated.replacedBy) event.replacedBy = updated.replacedBy;
|
|
767
826
|
append(repo, event);
|
|
768
827
|
return printTask(updated, options.json);
|
|
@@ -806,40 +865,102 @@ function run(argv) {
|
|
|
806
865
|
return [...tasks, task];
|
|
807
866
|
});
|
|
808
867
|
if (!result.ok) fail("could not write the task board (too much contention)");
|
|
809
|
-
append(repo, { actor: task.createdBy, kind: "task_add", task: task.id, stages: isStaged(task) ? task.stages.length : undefined });
|
|
868
|
+
append(repo, { actor: eventActor(task.createdBy), kind: "task_add", task: task.id, stages: isStaged(task) ? task.stages.length : undefined });
|
|
810
869
|
return printTask(task, options.json);
|
|
811
870
|
}
|
|
812
871
|
|
|
813
|
-
if (command === "list"
|
|
872
|
+
if (command === "list") {
|
|
873
|
+
// Paginated list: the index filters/orders/counts, and only the page's
|
|
874
|
+
// cards are parsed, so a page costs the same on a 10-task board and a
|
|
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);
|
|
898
|
+
if (options.json) {
|
|
899
|
+
const payload = {
|
|
900
|
+
items: page.items.map((task) => viewTask(task)),
|
|
901
|
+
total: page.total,
|
|
902
|
+
cursor: page.cursor,
|
|
903
|
+
hasMore: page.hasMore,
|
|
904
|
+
skipped: page.skipped,
|
|
905
|
+
};
|
|
906
|
+
return process.stdout.write(JSON.stringify(payload, null, 2) + "\n");
|
|
907
|
+
}
|
|
908
|
+
if (page.items.length === 0) return process.stdout.write("No tasks.\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");
|
|
911
|
+
return;
|
|
912
|
+
}
|
|
814
913
|
const tasks = board(repo);
|
|
815
|
-
const selected =
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
.filter((task) => (!options.state || task.state === options.state) && matchesRole(task, options.role))
|
|
819
|
-
.sort(order);
|
|
914
|
+
const selected = tasks
|
|
915
|
+
.filter((task) => (!options.state || task.state === options.state) && matchesRole(task, options.role))
|
|
916
|
+
.sort(order);
|
|
820
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);
|
|
821
932
|
if (options.json) {
|
|
822
|
-
|
|
823
|
-
const view = viewTask(task);
|
|
824
|
-
return command === "ready" ? { ...view, readyRole: stageRole(task) } : view;
|
|
825
|
-
});
|
|
826
|
-
return process.stdout.write(JSON.stringify(rows, null, 2) + "\n");
|
|
827
|
-
}
|
|
828
|
-
if (limited.length === 0) return process.stdout.write(command === "ready" ? "Nothing ready.\n" : "No tasks.\n");
|
|
829
|
-
for (const task of limited) {
|
|
830
|
-
const tags = (task.draft ? " [draft]" : "") + (task.superseded ? " [superseded]" : "");
|
|
831
|
-
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");
|
|
832
934
|
}
|
|
935
|
+
if (cards.length === 0) return process.stdout.write("Nothing ready.\n");
|
|
936
|
+
for (const task of cards) printListLine(task);
|
|
937
|
+
return;
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
if (command === "counts") {
|
|
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 };
|
|
945
|
+
if (options.json) return process.stdout.write(JSON.stringify(payload, null, 2) + "\n");
|
|
946
|
+
process.stdout.write("cards: " + summary.total + "\n");
|
|
947
|
+
for (const [state, count] of Object.entries(summary.byState)) process.stdout.write(" " + state.padEnd(8) + count + "\n");
|
|
948
|
+
if (summary.superseded > 0) process.stdout.write(" " + "superseded".padEnd(8) + summary.superseded + "\n");
|
|
949
|
+
if (summary.oldestPending) process.stdout.write("oldest pending: " + summary.oldestPending.id + " (" + summary.oldestPending.createdAt + ")\n");
|
|
833
950
|
return;
|
|
834
951
|
}
|
|
835
952
|
|
|
836
953
|
if (command === "next") {
|
|
837
|
-
const
|
|
838
|
-
|
|
954
|
+
const rows = readyEntries(readableIndex(repo), { modeFree: readMode(repo) === "free" })
|
|
955
|
+
.filter((row) => !options.role || row.role === options.role);
|
|
956
|
+
if (rows.length === 0) {
|
|
839
957
|
if (options.json) process.stdout.write("null\n");
|
|
840
958
|
else process.stdout.write("Nothing ready.\n");
|
|
841
959
|
return;
|
|
842
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);
|
|
843
964
|
return printTask(first, options.json, { readyRole: stageRole(first) });
|
|
844
965
|
}
|
|
845
966
|
|
|
@@ -848,6 +969,7 @@ function run(argv) {
|
|
|
848
969
|
if (!id) fail("show needs a task id", 2);
|
|
849
970
|
const task = readTask(repo, id);
|
|
850
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);
|
|
851
973
|
const active = stageRole(task);
|
|
852
974
|
const resolved = resolveRole(repo, active, isStaged(task) ? task.stage : {});
|
|
853
975
|
const lines = ["role-source: " + resolved.source + " (adapter " + resolved.adapter + ", model " + (resolved.model || "-") + ")"];
|
|
@@ -873,11 +995,13 @@ function run(argv) {
|
|
|
873
995
|
if (isStaged(preview) && preview.stageState !== "pending" && !(preview.stageState === "claimed" && reclaim)) {
|
|
874
996
|
fail("task " + id + " stage " + preview.stage + " is " + preview.stageState, 2);
|
|
875
997
|
}
|
|
876
|
-
|
|
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);
|
|
877
1001
|
|
|
878
1002
|
let claimed = null;
|
|
879
1003
|
try {
|
|
880
|
-
mutate(repo, (tasks) => {
|
|
1004
|
+
const result = mutate(repo, (tasks) => {
|
|
881
1005
|
const map = byId(tasks);
|
|
882
1006
|
const task = map.get(id);
|
|
883
1007
|
if (!task) throw new Error("no such task: " + id);
|
|
@@ -896,14 +1020,18 @@ function run(argv) {
|
|
|
896
1020
|
claimedUntil: new Date(Date.now() + ttlMs).toISOString(),
|
|
897
1021
|
...stageStatePatch(task, "claimed"),
|
|
898
1022
|
};
|
|
899
|
-
|
|
900
|
-
return tasks.map((entry) => (entry.id === id ?
|
|
1023
|
+
const next = transition(task, "claimed", patch);
|
|
1024
|
+
return tasks.map((entry) => (entry.id === id ? next : entry));
|
|
901
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;
|
|
902
1030
|
} catch (error) {
|
|
903
1031
|
fail(error.message, 2);
|
|
904
1032
|
}
|
|
905
1033
|
|
|
906
|
-
if (!claimed) fail("could not claim " + id,
|
|
1034
|
+
if (!claimed) fail("could not claim " + id + " (the board was written but the card is missing)", 1);
|
|
907
1035
|
|
|
908
1036
|
// Announcements are information, never a gate: the card claim already
|
|
909
1037
|
// succeeded, and a live announcement by someone else is reported as an
|
|
@@ -911,7 +1039,7 @@ function run(argv) {
|
|
|
911
1039
|
const announcements = claimLeases(repo, { paths: claimed.scope, agent, ttlMs, taskId: claimed.id });
|
|
912
1040
|
publishPresence(repo, { agent, task: claimed, state: "working", files: claimed.scope });
|
|
913
1041
|
append(repo, {
|
|
914
|
-
actor: agent,
|
|
1042
|
+
actor: eventActor(agent),
|
|
915
1043
|
kind: "task_claim",
|
|
916
1044
|
task: claimed.id,
|
|
917
1045
|
attempt: claimed.attempt,
|
|
@@ -1032,13 +1160,13 @@ function run(argv) {
|
|
|
1032
1160
|
addVerdict(repo, { sha: options.sha, result: options.verdict });
|
|
1033
1161
|
}
|
|
1034
1162
|
publishPresence(repo, { agent, task: current, state: outcome.targetState === "done" ? "idle" : "working", files: [] });
|
|
1035
|
-
append(repo, { actor: agent, kind: "task_" + command, task: id, reason: options.reason || undefined, stage: isStaged(current) ? current.stage : undefined });
|
|
1036
|
-
for (const event of outcome.events) append(repo, { actor: agent, task: id, ...event });
|
|
1163
|
+
append(repo, { actor: eventActor(agent), kind: "task_" + command, task: id, reason: options.reason || undefined, stage: isStaged(current) ? current.stage : undefined });
|
|
1164
|
+
for (const event of outcome.events) append(repo, { actor: eventActor(agent), task: id, ...event });
|
|
1037
1165
|
if (command === "fail" && current.reviewOf && outcome.targetState === "failed") {
|
|
1038
1166
|
if (upstreamReopened) {
|
|
1039
|
-
append(repo, { actor: agent, kind: "reopen", task: upstreamReopened.id, from: "done", reason: upstreamReason, attempt: upstreamReopened.attempt, via: "review_failed" });
|
|
1167
|
+
append(repo, { actor: eventActor(agent), kind: "reopen", task: upstreamReopened.id, from: "done", reason: upstreamReason, attempt: upstreamReopened.attempt, via: "review_failed" });
|
|
1040
1168
|
}
|
|
1041
|
-
append(repo, { actor: agent, kind: "review_failed", task: id, reviewOf: current.reviewOf, reopened: Boolean(upstreamReopened), reason: options.reason || undefined });
|
|
1169
|
+
append(repo, { actor: eventActor(agent), kind: "review_failed", task: id, reviewOf: current.reviewOf, reopened: Boolean(upstreamReopened), reason: options.reason || undefined });
|
|
1042
1170
|
}
|
|
1043
1171
|
|
|
1044
1172
|
const finalCard = readTask(repo, id);
|
|
@@ -1051,25 +1179,17 @@ function run(argv) {
|
|
|
1051
1179
|
}
|
|
1052
1180
|
|
|
1053
1181
|
if (command === "stats") {
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
const
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
// Superseded tasks keep their lane but are counted separately, never as a
|
|
1061
|
-
// state or role of the live board.
|
|
1062
|
-
if (isSuperseded(task)) { superseded += 1; continue; }
|
|
1063
|
-
byState[task.state] = (byState[task.state] || 0) + 1;
|
|
1064
|
-
byRole[task.role] = (byRole[task.role] || 0) + 1;
|
|
1065
|
-
if (task.state === "pending" && (!oldest || task.createdAt < oldest.createdAt)) oldest = task;
|
|
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");
|
|
1066
1188
|
}
|
|
1067
|
-
const summary = { total: items.length, byState, byRole, superseded, oldestPending: oldest ? { id: oldest.id, createdAt: oldest.createdAt } : null };
|
|
1068
|
-
if (options.json) return process.stdout.write(JSON.stringify(summary, null, 2) + "\n");
|
|
1069
1189
|
process.stdout.write("cards: " + summary.total + "\n");
|
|
1070
|
-
for (const [state, count] of Object.entries(byState)) process.stdout.write(" " + state.padEnd(8) + count + "\n");
|
|
1071
|
-
if (superseded > 0) process.stdout.write(" " + "superseded".padEnd(8) + superseded + "\n");
|
|
1072
|
-
if (
|
|
1190
|
+
for (const [state, count] of Object.entries(summary.byState)) process.stdout.write(" " + state.padEnd(8) + count + "\n");
|
|
1191
|
+
if (summary.superseded > 0) process.stdout.write(" " + "superseded".padEnd(8) + summary.superseded + "\n");
|
|
1192
|
+
if (summary.oldestPending) process.stdout.write("oldest pending: " + summary.oldestPending.id + " (" + summary.oldestPending.createdAt + ")\n");
|
|
1073
1193
|
return;
|
|
1074
1194
|
}
|
|
1075
1195
|
|
package/src/git.js
CHANGED
|
@@ -21,6 +21,25 @@ export function out(args, opts) {
|
|
|
21
21
|
return git(args, opts).stdout.trim();
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
+
/**
|
|
25
|
+
* Run git and return stdout as a Buffer, for binary-framed output such as
|
|
26
|
+
* `cat-file --batch`. Input may be a string or Buffer.
|
|
27
|
+
*/
|
|
28
|
+
export function gitBuffer(args, { cwd, env, input, allowFail = false } = {}) {
|
|
29
|
+
const result = spawnSync("git", args, {
|
|
30
|
+
cwd,
|
|
31
|
+
env: env ? { ...process.env, ...env } : process.env,
|
|
32
|
+
input,
|
|
33
|
+
maxBuffer: 512 * 1024 * 1024,
|
|
34
|
+
});
|
|
35
|
+
if (result.error) throw result.error;
|
|
36
|
+
if (!allowFail && result.status !== 0) {
|
|
37
|
+
const detail = String(result.stderr || "").trim();
|
|
38
|
+
throw new Error("git " + args.join(" ") + " failed (exit " + result.status + ")" + (detail ? ": " + detail : ""));
|
|
39
|
+
}
|
|
40
|
+
return result;
|
|
41
|
+
}
|
|
42
|
+
|
|
24
43
|
export function ok(args, opts) {
|
|
25
44
|
return git(args, { ...opts, allowFail: true }).status === 0;
|
|
26
45
|
}
|
package/src/store.js
CHANGED
|
@@ -1,30 +1,382 @@
|
|
|
1
1
|
import crypto from "node:crypto";
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
|
-
import { git, out } from "./git.js";
|
|
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";
|
|
9
|
+
/**
|
|
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.
|
|
19
|
+
*/
|
|
20
|
+
export const TASKS_INDEX_REF = "refs/hive/v1/tasks-index";
|
|
21
|
+
export const INDEX_VERSION = 2;
|
|
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 });
|
|
7
29
|
|
|
8
|
-
|
|
9
|
-
|
|
30
|
+
const STATES = new Set(["pending", "claimed", "done", "failed"]);
|
|
31
|
+
|
|
32
|
+
function readRefSha(repo, ref) {
|
|
33
|
+
const result = git(["rev-parse", "--verify", "--quiet", ref], { cwd: repo.top, allowFail: true });
|
|
10
34
|
return result.status === 0 ? result.stdout.trim() : null;
|
|
11
35
|
}
|
|
12
36
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
37
|
+
export function refSha(repo) {
|
|
38
|
+
return readRefSha(repo, TASKS_REF);
|
|
39
|
+
}
|
|
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
|
+
|
|
52
|
+
/** [{ id, blobSha }] for one tree, or [] when the tree is missing. */
|
|
53
|
+
function readTree(repo, sha) {
|
|
16
54
|
if (!sha) return [];
|
|
17
|
-
const
|
|
55
|
+
const result = git(["ls-tree", "-z", sha], { cwd: repo.top, allowFail: true });
|
|
56
|
+
if (result.status !== 0) return [];
|
|
57
|
+
const raw = result.stdout;
|
|
18
58
|
if (!raw) return [];
|
|
19
|
-
|
|
59
|
+
const entries = [];
|
|
60
|
+
for (const line of raw.split("\u0000")) {
|
|
61
|
+
if (line === "") continue;
|
|
20
62
|
const tab = line.indexOf("\t");
|
|
63
|
+
if (tab < 0) continue;
|
|
21
64
|
const meta = line.slice(0, tab).split(/\s+/);
|
|
22
|
-
|
|
23
|
-
|
|
65
|
+
entries.push({ id: line.slice(tab + 1), blobSha: meta[2] });
|
|
66
|
+
}
|
|
67
|
+
return entries;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Read blobs by object name in one process: specs -> string[] (null per missing). */
|
|
71
|
+
function readBlobs(repo, specs) {
|
|
72
|
+
if (specs.length === 0) return [];
|
|
73
|
+
const result = gitBuffer(["cat-file", "--batch"], { cwd: repo.top, input: specs.join("\n") + "\n", allowFail: true });
|
|
74
|
+
if (result.status !== 0) {
|
|
75
|
+
const detail = String(result.stderr || "").trim();
|
|
76
|
+
throw new Error("git cat-file --batch failed" + (detail ? ": " + detail : ""));
|
|
77
|
+
}
|
|
78
|
+
const buffer = result.stdout;
|
|
79
|
+
const values = [];
|
|
80
|
+
let offset = 0;
|
|
81
|
+
for (let index = 0; index < specs.length; index += 1) {
|
|
82
|
+
const headerEnd = buffer.indexOf(0x0a, offset);
|
|
83
|
+
if (headerEnd < 0) { values.push(null); continue; }
|
|
84
|
+
const header = buffer.toString("utf8", offset, headerEnd);
|
|
85
|
+
offset = headerEnd + 1;
|
|
86
|
+
const parts = header.split(" ");
|
|
87
|
+
if (parts.length < 3) { values.push(null); continue; }
|
|
88
|
+
const size = Number(parts[2]);
|
|
89
|
+
if (!Number.isInteger(size) || size < 0) { values.push(null); continue; }
|
|
90
|
+
values.push(buffer.subarray(offset, offset + size).toString("utf8"));
|
|
91
|
+
offset += size + 1;
|
|
92
|
+
}
|
|
93
|
+
return values;
|
|
94
|
+
}
|
|
95
|
+
|
|
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));
|
|
100
|
+
const rows = [];
|
|
101
|
+
for (let index = 0; index < tree.length; index += 1) {
|
|
102
|
+
const text = blobs[index];
|
|
103
|
+
if (text === null) continue;
|
|
24
104
|
let value = null;
|
|
25
|
-
try { value = JSON.parse(
|
|
26
|
-
|
|
27
|
-
}
|
|
105
|
+
try { value = JSON.parse(text); } catch { value = null; }
|
|
106
|
+
if (value) rows.push({ id: tree[index].id, value });
|
|
107
|
+
}
|
|
108
|
+
return rows;
|
|
109
|
+
}
|
|
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
|
+
|
|
118
|
+
/** One card by id: a single blob read, never the whole tree. */
|
|
119
|
+
export function readTask(repo, id) {
|
|
120
|
+
const sha = refSha(repo);
|
|
121
|
+
if (!sha) return null;
|
|
122
|
+
const result = git(["cat-file", "blob", sha + ":" + id], { cwd: repo.top, allowFail: true });
|
|
123
|
+
if (result.status !== 0) return null;
|
|
124
|
+
try { return JSON.parse(result.stdout); } catch { return null; }
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Full cards for a known list of ids, aligned with the input (null per miss). */
|
|
128
|
+
export function readTasksByIdsAligned(repo, ids) {
|
|
129
|
+
if (!Array.isArray(ids) || ids.length === 0) return [];
|
|
130
|
+
const sha = refSha(repo);
|
|
131
|
+
if (!sha) return ids.map(() => null);
|
|
132
|
+
const blobs = readBlobs(repo, ids.map((id) => sha + ":" + id));
|
|
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);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Sort key shared by the index writer and readers: newest lane change first. */
|
|
145
|
+
export function taskSortTime(task) {
|
|
146
|
+
const value = task && (task.stateChangedAt || task.updatedAt || task.createdAt);
|
|
147
|
+
const time = Date.parse(value || "");
|
|
148
|
+
return Number.isFinite(time) ? time : 0;
|
|
149
|
+
}
|
|
150
|
+
|
|
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,
|
|
178
|
+
task.state,
|
|
179
|
+
typeof task.role === "string" ? task.role : "",
|
|
180
|
+
taskSortTime(task),
|
|
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));
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function readIndexBlob(repo) {
|
|
202
|
+
const sha = readRefSha(repo, TASKS_INDEX_REF);
|
|
203
|
+
if (!sha) return null;
|
|
204
|
+
const result = git(["cat-file", "blob", sha], { cwd: repo.top, allowFail: true });
|
|
205
|
+
if (result.status !== 0) return null;
|
|
206
|
+
try { return JSON.parse(result.stdout); } catch { return null; }
|
|
207
|
+
}
|
|
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. */
|
|
215
|
+
function writeIndex(repo, tasksSha, entries) {
|
|
216
|
+
const blob = out(["hash-object", "-w", "--stdin"], {
|
|
217
|
+
cwd: repo.top,
|
|
218
|
+
input: JSON.stringify({ v: INDEX_VERSION, tasks: tasksSha, entries }),
|
|
219
|
+
});
|
|
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;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
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`).
|
|
254
|
+
*/
|
|
255
|
+
export function readIndexForRead(repo) {
|
|
256
|
+
const tasksSha = refSha(repo);
|
|
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));
|
|
260
|
+
const cached = readIndexBlob(repo);
|
|
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 };
|
|
264
|
+
}
|
|
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 };
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** Newest stateChangedAt first; ids break ties so paging is deterministic. */
|
|
289
|
+
export function compareIndexRows(left, right) {
|
|
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]));
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Pure page computation over index rows: filter, sort newest-first, cut one
|
|
296
|
+
* page. Superseded rows are hidden by default so page totals match counts.
|
|
297
|
+
*/
|
|
298
|
+
export function paginateIndexEntries(entries, { state = null, role = null, limit = DEFAULT_PAGE_LIMIT, cursor = 0, includeSuperseded = false } = {}) {
|
|
299
|
+
let rows = entries;
|
|
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);
|
|
303
|
+
rows = rows.slice().sort(compareIndexRows);
|
|
304
|
+
const total = rows.length;
|
|
305
|
+
const start = Math.min(Math.max(0, cursor), total);
|
|
306
|
+
const page = rows.slice(start, start + limit);
|
|
307
|
+
const next = start + page.length;
|
|
308
|
+
return { page, total, cursor: next, hasMore: next < total };
|
|
309
|
+
}
|
|
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
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Ready rows computed from the index only: dependencies, draft/superseded/fix
|
|
328
|
+
* flags, stage readiness and the reclaim rule, then the queue order.
|
|
329
|
+
*/
|
|
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;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
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.
|
|
360
|
+
*/
|
|
361
|
+
export function summarizeEntries(entries) {
|
|
362
|
+
const byState = {};
|
|
363
|
+
const byRole = {};
|
|
364
|
+
let superseded = 0;
|
|
365
|
+
let oldest = null;
|
|
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]) };
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
return { total: entries.length, live: entries.length - superseded, byState, byRole, superseded, oldestPending: oldest };
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** Whole-board summary (index-backed, read-only). */
|
|
378
|
+
export function summarizeIndex(repo) {
|
|
379
|
+
return summarizeEntries(readIndexForRead(repo).entries);
|
|
28
380
|
}
|
|
29
381
|
|
|
30
382
|
function hashBlob(repo, value) {
|
|
@@ -33,7 +385,9 @@ function hashBlob(repo, value) {
|
|
|
33
385
|
|
|
34
386
|
/**
|
|
35
387
|
* Replace the whole board with the given tasks, compare-and-swap on the ref.
|
|
36
|
-
*
|
|
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).
|
|
37
391
|
*/
|
|
38
392
|
function write(repo, tasks, expectedSha) {
|
|
39
393
|
const indexFile = path.join(repo.stateDir, "index-tasks-" + process.pid + "-" + crypto.randomBytes(4).toString("hex"));
|
|
@@ -44,7 +398,7 @@ function write(repo, tasks, expectedSha) {
|
|
|
44
398
|
else git(["read-tree", "--empty"], { cwd: repo.top, env });
|
|
45
399
|
|
|
46
400
|
const keep = new Set(tasks.map((task) => task.id));
|
|
47
|
-
for (const entry of
|
|
401
|
+
for (const entry of readTree(repo, expectedSha)) {
|
|
48
402
|
if (!keep.has(entry.id)) git(["update-index", "--force-remove", entry.id], { cwd: repo.top, env });
|
|
49
403
|
}
|
|
50
404
|
for (const task of tasks) {
|
|
@@ -56,7 +410,9 @@ function write(repo, tasks, expectedSha) {
|
|
|
56
410
|
cwd: repo.top,
|
|
57
411
|
allowFail: true,
|
|
58
412
|
});
|
|
59
|
-
|
|
413
|
+
if (update.status !== 0) return false;
|
|
414
|
+
writeIndex(repo, tree, buildIndexEntries(tasks));
|
|
415
|
+
return true;
|
|
60
416
|
} finally {
|
|
61
417
|
fs.rmSync(indexFile, { force: true });
|
|
62
418
|
}
|
|
@@ -74,7 +430,9 @@ export function mutate(repo, fn) {
|
|
|
74
430
|
return { ok: false, tasks: [] };
|
|
75
431
|
}
|
|
76
432
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
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);
|
|
80
438
|
}
|